@dhedge/trading-widget 6.3.2 → 6.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/{contract-error-log-D3UONUXl.cjs → contract-error-log-CNIRNvc6.cjs} +1 -1
- package/{contract-error-log-Ci0TIrO5.js → contract-error-log-CbE2J5kb.js} +16 -15
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/package.json +1 -1
- package/utils.cjs +1 -1
- package/utils.js +1 -1
package/LICENSE
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const E=require("wagmi/chains"),a=require("./gmx-DJ0gqvLq.cjs"),p=require("bignumber.js"),d=require("viem"),x="application/json";class W extends Error{constructor(e,n,s){super(`HTTP ${e}${s?`: ${s}`:""}`),this.name="FetchRequestError",this.status=e,this.statusText=n,this.body=s}}const Et=t=>{if(!(t instanceof W)||!t.body)return null;try{return JSON.parse(t.body)}catch{return null}},ht=t=>typeof t=="string"||t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob||t instanceof ArrayBuffer||ArrayBuffer.isView(t),Tt=(t,e)=>{const n=String(t),s=e?new URLSearchParams(e).toString():"";if(!s)return n;const r=n.indexOf("#"),o=r===-1?n:n.slice(0,r),i=r===-1?"":n.slice(r);return`${o}${o.includes("?")?"&":"?"}${s}${i}`},St=(t,e)=>{const n=new AbortController,s=()=>n.abort();e?.aborted&&s();const r=setTimeout(s,t);return e?.addEventListener("abort",s),{signal:n.signal,cleanup:()=>{clearTimeout(r),e?.removeEventListener("abort",s)}}},ft=async(t,e,n)=>{if(n===void 0)return await t[e]();const s=Number(t.headers.get("content-length"));if(s>n)throw new Error(`Response too large: ${s} bytes`);if(e==="blob"||e==="arrayBuffer"){const o=await t[e](),i=o instanceof Blob?o.size:o.byteLength;if(i>n)throw new Error(`Response too large: ${i} bytes`);return o}const r=await t.text();if(r.length>n)throw new Error(`Response too large: ${r.length} chars`);return e==="json"?JSON.parse(r):r},G=async({url:t,headers:e,method:n,body:s,params:r,signal:o,readMethod:i="json",cache:u,timeoutMs:c,maxResponseBytes:l})=>{const A=s!==void 0&&n!=="GET",h=A&&!ht(s),g=new Headers(e);i==="json"&&!g.has("Accept")&&g.set("Accept",x),h&&!g.has("Content-Type")&&g.set("Content-Type",x);const _=c?St(c,o):void 0,gt={method:n,headers:g,signal:_?.signal??o,...u&&{cache:u},...A&&{body:h?JSON.stringify(s):s}};try{const T=await fetch(Tt(t,r),gt);if(!T.ok)throw new W(T.status,T.statusText,await T.text().catch(()=>""));return await ft(T,i,l)}finally{_?.cleanup()}},_t=typeof window<"u",wt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"address",name:"_asset",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewGmTokenAmount",outputs:[{internalType:"uint256",name:"gmTokenAmount",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"ondoGMSwap",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usdc",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],Dt=[{type:"tuple",components:[{name:"attestationSignature",type:"bytes"},{name:"quote",type:"tuple",components:[{name:"chainId",type:"uint256"},{name:"attestationId",type:"uint256"},{name:"userId",type:"bytes32"},{name:"asset",type:"address"},{name:"price",type:"uint256"},{name:"quantity",type:"uint256"},{name:"expiration",type:"uint256"},{name:"side",type:"uint8"},{name:"additionalData",type:"bytes32"}]},{name:"amountOutMinimum",type:"uint256"}]}],bt=[{name:"asset",type:"address"},{name:"amount",type:"uint256"},{name:"assetType",type:"uint16"},{name:"isPool",type:"bool"},{name:"isDebt",type:"bool"},{name:"marketId",type:"uint88"},{name:"accountId",type:"uint256"},{name:"tokenId",type:"uint256"},{name:"debtKey",type:"uint248"},{name:"shares",type:"uint256"}],Rt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewWithdrawal",outputs:[{name:"assetData",type:"tuple[]",components:bt}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"dytmWithdrawProcessor",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],N=[{inputs:[{name:"params",type:"tuple",components:[{name:"account",type:"uint256"},{name:"tokenId",type:"uint256"},{name:"receiver",type:"address"},{name:"assets",type:"uint256"},{name:"shares",type:"uint256"},{name:"extraData",type:"bytes"}]}],name:"withdraw",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"params",type:"tuple",components:[{name:"account",type:"uint256"},{name:"key",type:"uint248"},{name:"withCollateralType",type:"uint8"},{name:"assets",type:"uint256"},{name:"shares",type:"uint256"},{name:"extraData",type:"bytes"}]}],name:"repay",outputs:[{name:"assetsRepaid",type:"uint256"}],stateMutability:"nonpayable",type:"function"}],It=[{inputs:[{name:"tokenIn",type:"address"},{name:"amountIn",type:"uint256"},{name:"tokenOut",type:"address"},{name:"amountOutMinimum",type:"uint256"},{name:"attestationSignature",type:"bytes"},{name:"quote",type:"tuple",components:[{name:"chainId",type:"uint256"},{name:"attestationId",type:"uint256"},{name:"userId",type:"bytes32"},{name:"asset",type:"address"},{name:"price",type:"uint256"},{name:"quantity",type:"uint256"},{name:"expiration",type:"uint256"},{name:"side",type:"uint8"},{name:"additionalData",type:"bytes32"}]}],name:"swapExactInWithAttestation",outputs:[],stateMutability:"nonpayable",type:"function"}],Nt=[{type:"tuple",components:[{name:"actions",type:"tuple[]",components:[{name:"to",type:"address"},{name:"data",type:"bytes"}]},{name:"outputAsset",type:"address"},{name:"minOutputAmount",type:"uint256"}]}],w={stringErrors:{"currently closed for trading":{title:"The market for this tokenized asset is closed right now",hint:"Wait until the market reopens (the error message says when) and simply retry."},"Synth exchange suspended. Operation prohibited":{title:"Vault includes deprecated synths in portfolio",hint:"Redeem deprecated synth to be able to withdraw."}},selectorErrors:{"0x54971d46":{signature:"SwapFailed(address,(address,uint256,(bytes32,bytes)),bytes)",title:"The token swap failed to execute",hint:"Your assets are still in your wallet — try again, or retry with a higher slippage tolerance."},"0x81a815ef":{signature:"InsufficientAmountReceived(address,uint256,uint256)",title:"Swap output was below the minimum received amount",hint:"Increase slippage tolerance and try again."}}},Y=t=>({stringErrors:{...t.stringErrors,...w.stringErrors},selectorErrors:{...t.selectorErrors,...w.selectorErrors}}),Ot=["https://cdn.jsdelivr.net/gh/dhedge/V2-Public@master/readmes/errorCodes/registry.json","https://raw.githubusercontent.com/dhedge/V2-Public/master/readmes/errorCodes/registry.json"],Ct=1,Pt=1e4,xt=2e6,Bt=2e3,Lt=500,Mt=120,vt=300,Ft=4,Ut=/^dh\d{1,3}$/i,q=/[\u0000-\u001f\u007f]/,$t=/https?:\/\/|[<>`]/i,Ht=t=>t.length<=Mt&&!q.test(t)&&(Ut.test(t)||t.length>=Ft),S=t=>typeof t=="string"&&t.length>0&&t.length<=vt&&!q.test(t)&&!$t.test(t);let k=w,D=null;const O=()=>k,V=t=>{k=Y(t)},Wt=t=>{const e=t;if(e?.schemaVersion!==Ct)throw new Error(`Unsupported error registry schemaVersion: ${String(e?.schemaVersion)}`);const n={};for(const[r,o]of Object.entries(e.stringErrors??{}))o?.curated===!0&&Ht(r)&&S(o.description)&&S(o.action)&&(n[r]={title:o.description,hint:o.action});const s={};for(const[r,o]of Object.entries(e.selectorErrors??{}))o?.curated===!0&&/^0x[0-9a-f]{8}$/.test(r)&&S(o.signature)&&S(o.description)&&S(o.action)&&(s[r]={signature:o.signature,title:o.description,hint:o.action});if(!Object.keys(n).length)throw new Error("Error registry contained no curated string errors");if(Object.keys(n).length>Bt||Object.keys(s).length>Lt)throw new Error("Error registry exceeded expected entry counts");return{stringErrors:n,selectorErrors:s}},K=async({timeoutMs:t=Pt}={})=>{const e=[];for(const n of Ot)try{const s=await G({url:n,method:"GET",timeoutMs:t,maxResponseBytes:xt});return Y(Wt(s))}catch(s){e.push(`${n}: ${s instanceof Error?s.message:String(s)}`)}throw new Error(`All error registry sources failed: ${e.join("; ")}`)},Gt=()=>(D??(D=K().then(V).catch(()=>{D=null})),D),Yt=()=>typeof window<"u";function qt(){return Yt()&&typeof window.ethereum<"u"}async function kt(t){try{if(qt())return window.ethereum.request({method:"wallet_watchAsset",params:{type:"ERC20",options:t}})}catch{return!1}return!1}const m=(t,e)=>t?.toLowerCase()===e?.toLowerCase(),Vt=t=>m(t,a.AddressZero$1),f=t=>{if(!t)throw new Error("Cannot prefix an empty hex value");return t.startsWith("0x")?t:`0x${t}`},y=(t,e)=>{try{return BigInt(t)}catch{throw new Error(`Cannot convert "${e}" value "${t}" to bigint`)}},b=t=>t?d.pad(f(t),{size:32}):d.zeroHash,j=t=>{if(!t)throw new Error("Cannot decode an empty base64 string");return d.bytesToHex(Uint8Array.from(atob(t),e=>e.charCodeAt(0)))},X=(t,e)=>a.contractsAddressesMap[e]?.[t]??a.AddressZero,Kt=t=>a.contractsAbisMap[t],jt=t=>t&&`${t.substring(0,6)}...${t.substring(t.length-4,t.length)}`,Xt=({address:t,chainId:e})=>{const n=X("aaveLendingPoolV3",e);return m(t,n)},Z=({sourceAddress:t,amount:e})=>`${t}_${e}`,Zt=(t,e)=>{const n=t.slice(0,e),s=t.slice(e);return{firstPart:n,secondPart:s}},z=(t,e)=>t/e*100,zt=t=>t<1?4:t<10?3:2,Qt=(t,e=a.DEFAULT_PRECISION)=>new p(t.toString()).shiftedBy(e).toFixed(0),Jt=(t,e,n,s)=>new p(e).dividedBy(n).multipliedBy(t).shiftedBy(-(s||a.DEFAULT_PRECISION)).toNumber(),te=t=>BigInt(new p(t||"0").shiftedBy(a.DEFAULT_PRECISION).toFixed(0,p.ROUND_DOWN)),C=t=>{const e=new p(.01),n=new p(t),s=!n.isZero()&&n.lt(e)?e:n;return BigInt(s.multipliedBy(100).toFixed(0))},ee=({chainId:t,slippage:e})=>t===E.hyperEvm.id?BigInt(0):C(e),ne=({vaultAddress:t,swapData:e,sendTokenAddress:n,sendTokenAmount:s,vaultDepositTokenAddress:r,minVaultTokensReceivedAmount:o,routerKey:i="ONE_INCH",swapDestinationAmount:u,swapSlippage:c})=>{const l=new p(u).multipliedBy(1-c/100).toFixed(0),A=[d.stringToHex(i,{size:32}),e];return[t,[[n,s,A],[r,l]],o]},se=({receiveAssetAddress:t,assets:e,swapData:n,slippage:s})=>{const r={srcData:[],destAmount:new p("0")},{srcData:o,destAmount:i}=e?.reduce((u,c)=>{const l=n?.[c.address];if(!l)return u;const A=[d.stringToHex(l.routerKey,{size:32}),l.rawTransaction.data],h=[c.address,c.rawBalance,A];return{srcData:[...u.srcData,h],destAmount:u.destAmount.plus(l.destinationAmount)}},r)??r;return[o,[t,i.times(1-s/100).toFixed(0,p.ROUND_DOWN)]]},Q=({assetAddress:t,swapQuotes:e,swapParams:n,slippageToleranceForContractTransaction:s,routerKey:r})=>{if(!n)return{supportedAsset:t,withdrawData:"",slippageTolerance:BigInt(0)};const{srcData:o,dstData:i}=n,u=o.map(({asset:A,amount:h})=>{const g=e?.[Z({sourceAddress:A,amount:h.toString()})]?.find(_=>_.routerKey===r);return{asset:A,amount:h,swapData:{routerKey:d.stringToHex(g?.routerKey??"",{size:32}),txData:g?.rawTransaction.data??"0x"}}}),c=d.encodeAbiParameters(a.ComplexWithdrawalAssetSrcDataAbiItem,[u]),l=d.encodeAbiParameters(a.ComplexWithdrawalDataAbiItem,[{encodedSrcData:c,dstData:{dstAddress:i.asset,dstAmount:i.amount},slippage:s}]);return{supportedAsset:t,withdrawData:l,slippageTolerance:s}},re=({chainId:t,txHash:e,error:n})=>{if(t!==E.mainnet.id||!e||!n)return!1;const s=n instanceof Error?n.message:String(n);return/\bNo Result\b/i.test(s)},oe=({chainId:t,action:e,isRabbyWallet:n})=>e==="update_ondo_prices"&&t===E.mainnet.id&&n?a.ONDO_PRICES_RABBY_SETTLE_DELAY:t?a.TRANSACTION_SETTLE_DELAY[t]??0:0,ae=(t,e)=>a.CHAIN_NATIVE_TOKENS[e]?.nativeTokenSymbol===t,ie=({nativeTokenBalance:t,tokenDecimals:e,gasPrice:n})=>{const s=new p(n).multipliedBy(a.NATIVE_TOKEN_GAS_RESERVE_UNITS).shiftedBy(-e),r=new p(t).minus(s);return r.gt("0")?r:new p("0")},ce=t=>a.STABLE_TOKEN_SYMBOLS.includes(t),ue=t=>{const e=Object.values(t).reduce((n,{type:s})=>(n[s]=n[s]+1,n),{string:0,number:0});if(e.string>10)throw new Error("logger params must contain up to 10 string values");if(e.number>40)throw new Error("logger params must contain up to 40 numeric values");return!0},de=(t,e=150)=>t.length>e?t.substring(0,e):t,J=()=>({...O().stringErrors,...a.TRANSACTION_ERRORS}),le=()=>[...Object.keys(J()),...Object.keys(a.LIMIT_ORDER_TRANSACTION_ERRORS)],pe=/^dh\d+$/i,me=(t,e)=>pe.test(e)?new RegExp(`\\b${e}\\b`,"i").test(t):t.includes(e.toLowerCase()),R=(t,e)=>{const n=t.toLowerCase();return[...e??le()].sort((s,r)=>r.length-s.length).find(s=>me(n,s))},B=t=>J()[t]??a.LIMIT_ORDER_TRANSACTION_ERRORS[t],ye=/\b0x[0-9a-f]{8}\b/i,Ae=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ge=t=>{const{selectorErrors:e}=O(),n=t.match(ye)?.[0]?.toLowerCase(),s=n?e[n]:void 0;if(s)return{title:s.title,hint:s.hint};const r=Object.values(e).find(o=>new RegExp(`\\b${Ae(o.signature.split("(")[0]??"")}\\b`).test(t));return r?{title:r.title,hint:r.hint}:void 0},Ee=({errorMessage:t,abiErrors:e})=>{if(!t||t.includes("User rejected"))return null;const n=e.find(i=>t.includes(i));if(n){const i=R(n);if(i)return B(i)}const s=R(t);if(s)return B(s);const r=ge(t);if(r)return r;const[o]=t.split(n?".":"Contract").map(i=>i.trim());return{title:"Transaction failed",hint:`${de(o??"")} ${n?`: ${n}`:""}`}},he=t=>typeof t=="number"&&Number.isFinite(t),Te=t=>typeof t=="bigint"&&t!==BigInt(0),tt=(t,e=a.DEFAULT_PRECISION$1)=>new p(t).shiftedBy(-e).toNumber(),et=t=>!isNaN(parseFloat(t))&&!isNaN(t),nt=({value:t,minimumFractionDigits:e=2,maximumFractionDigits:n=2,compact:s=!1,normalize:r=!1})=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:s?"compact":void 0,minimumFractionDigits:e,maximumFractionDigits:n}).format(r?tt(t):Number(t)),I=t=>et(t)?new p(t).toFixed():"",L=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"],st=({value:t,decimals:e=4})=>{const n=new p(t);if(n.isGreaterThan(1)||n.isZero())return I(n.toFixed(e));const r=(/e/i.test(t.toString())?parseFloat(t.toString()).toFixed(a.DEFAULT_PRECISION$1):t.toString()).match(/^0\.(0+)(\d+)$/);if(r){const[,o,i]=r;if(o.length>=e&&o.length<L.length)return`0.0${L[o.length]}${i.slice(0,3)}`}return I(n.toFixed(e))},rt=(t,e=0)=>`${t.toLocaleString("en-US",{maximumFractionDigits:e})}%`,Se=t=>t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),fe=(t,e,n=0)=>{const s=z(+t,e);return rt(s,n)},_e=({currency:t,value:e})=>t==="USD"?nt({value:e}):`${a.CURRENCY_SYMBOL_MAP[t]} ${st({value:e,decimals:a.CURRENCY_DECIMALS_MAP[t]})}`,ot=(t,e)=>new p(new p(t).toFixed(e,p.ROUND_DOWN)).toString(),at=(t,e=3,n=2)=>{if(t.length<=5)return t;const s="...";return t.length<=e+n+s.length?t:`${t.slice(0,e)}${s}${t.slice(-n)}`},we=({balance:t,symbol:e,precision:n,truncateSymbol:s})=>`${ot(t,n)} ${s?at(e):e}`,De=t=>{if(!t)return;const e=t.match(/0x[a-fA-F0-9]{64}/);if(!e)return;const n=e[0];return`${n.slice(0,4)}...${n.slice(-3)}`},be=t=>m(a.FLATMONEY_EARLY_DEPOSITOR_VAULT_ADDRESS_BASE,t)||m(a.FLATMONEY_DHT_STAKING_VAULT_ADDRESS_BASE,t),Re=t=>a.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES.some(e=>m(e,t)),Ie=t=>a.FLAT_MONEY_COLLATERAL_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},Ne=t=>m(t,a.FLAT_MONEY_V1_UNIT_ADDRESS)?a.FLAT_MONEY_V1_UNIT_LINK:a.FLAT_MONEY_UNIT_LINK,it=t=>`eth_${t}`,Oe=({action:t,log:e,symbol:n,vaultAddress:s,chainId:r})=>{const o={[a.TRADING_LOG_EVENT_PARAM.SYMBOL.NAME]:n,[a.TRADING_LOG_EVENT_PARAM.CHAIN_ID.NAME]:r,[a.TRADING_LOG_EVENT_PARAM.ADDRESS.NAME]:it(s)};a.LOG_EVENT_BY_TRANSACTION_ACTION_MAP[t].forEach(i=>{e?.(i,o)})},Ce=t=>a.GMX_MARKET_ASSETS.some(e=>m(e,t)),Pe=t=>a.GMX_WITHDRAW_ASSET_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},xe=t=>a.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS[t.toLowerCase()],ct="0x3333333333333333333333333333333333333333";E.arbitrum.id+"",a.USDC_ARBITRUM.address,E.base.id+"",a.USDC_BASE.address,E.optimism.id+"",a.USDC_OPTIMISM.address,E.polygon.id+"",a.USDC_POLYGON.address,E.mainnet.id+"",a.USDC_MAINNET.address,E.hyperEvm.id+"",a.USDC_HYPEREVM.address;const Be="0x2222222222222222222222222222222222222222",M=BigInt("0x2000000000000000000000000000000000000000"),Le=10000n,ut=t=>m(t,ct),dt=t=>{if(m(t,Be))return!0;try{const e=BigInt(t);return e>=M&&e<M+Le}catch{return!1}},Me=t=>ut(t)||dt(t),ve=()=>a.USDC_HYPEREVM,Fe=new Map,P=(t,e)=>!e||e.size===0?t:t.map(n=>{const s=e.get(n.supportedAsset.toLowerCase());return s?{...n,withdrawData:s.withdrawData,slippageTolerance:s.slippageTolerance}:n}),lt=t=>{const e=t.find(({swapQuotes:n})=>n);return e?.swapQuotes?Object.values(e.swapQuotes)[0]?.map(({routerKey:n})=>n)??[]:[]},pt=(t,e,n)=>t.map(({asset:s,swapParams:r,swapQuotes:o})=>!r||!o?{supportedAsset:s,withdrawData:"",slippageTolerance:n}:Q({assetAddress:s,swapQuotes:o,swapParams:r,slippageToleranceForContractTransaction:n,routerKey:e})),mt=async(t,e,n,s,r,o)=>{for(const i of t){const u=P(pt(e,i,n),o),{error:c}=await s(...r,u);if(!c)return u}return null},Ue=(t,e,n)=>{const s=(t??[]).map(r=>({supportedAsset:r,withdrawData:"",slippageTolerance:e}));return P(s,n)},$e=async(t,e,n,s,r)=>{for(const o of t){const i=C(o);try{const u=await e(o),c=lt(u),l=await mt(c,u,i,n,s,r);if(l)return console.debug(`[Init Withdraw] Auto slippage simulation succeeded: slippage=${o}%`),console.debug("[Init Withdraw] Complex asset data:",l),l}catch(u){console.error(`[Init Withdraw] Failed to fetch quotes for slippage=${o}%:`,u)}}return null},He=async(t,e,{fetchAaveSwapParams:n,fetchAaveSwapQuotes:s,withdrawAmountD18:r,slippage:o})=>Promise.all((t??[]).map(async i=>{if(!m(i,e))return{asset:i};try{const c=await n({withdrawAmountD18:r,slippage:o});if(c?.srcData.length){const l=await s({swapParams:c,slippage:o});return{asset:i,swapParams:c,swapQuotes:l}}return{asset:i}}catch(c){return console.error(c),{asset:i}}})),v=t=>Math.round(t*100)/100,We=({maxSlippage:t,candidates:e=a.SLIPPAGE_AUTO_SIMULATION_CANDIDATES})=>{if(!Number.isFinite(t)||t<=0)return[];const n=v(Math.min(t,100)),s=e.filter(o=>o>0&&o<=n).map(v),r=new Set(s);return r.add(n),r.add(t),Array.from(r).sort((o,i)=>o-i)},F=1000000000000000000n,Ge=1000000n,U=10000n,$=100n,Ye=t=>({quotes:t.quotes.map(e=>({chainId:y(e.chainId,"chainId"),attestationId:y(e.attestationId,"attestationId"),userId:f(e.userId),asset:e.asset,price:y(e.price,"price"),quantity:y(e.quantity,"quantity"),expiration:y(e.expiration,"expiration"),side:Number(e.side),additionalData:f(e.additionalData)})),signatures:t.signatures.map(f)}),yt=(t,e,n)=>{const s=BigInt(Math.max(0,Math.round(n*100))),r=s>$?$:s,o=U-r,u=t*e/F*o*Ge,c=U*F;return(u+c-1n)/c},At=(t,e)=>({chainId:e,attestationId:y(t.attestationId,"attestationId"),userId:b(t.userId),asset:t.assetAddress,price:y(t.price,"price"),quantity:y(t.tokenAmount,"tokenAmount"),expiration:y(t.expiration,"expiration"),side:Number(t.side),additionalData:b(t.additionalData)}),qe=({attestation:t,chainId:e,slippagePercent:n})=>{const s=At(t,e);return d.encodeAbiParameters(Dt,[{attestationSignature:j(t.signature),quote:s,amountOutMinimum:yt(s.quantity,s.price,n)}])},ke=t=>[...t.reduce((n,s)=>n.has(s.accountId)?n:n.set(s.accountId,s),new Map).values()].map(({accountId:n,marketId:s})=>({accountId:n,marketId:s,collaterals:t.filter(r=>r.accountId===n&&!r.isDebt),debt:t.find(r=>r.accountId===n&&r.isDebt)})),Ve=({collateral:t,dytmOffice:e,processor:n,gmToken:s,ondoGMSwap:r,usdc:o,gmAmount:i,amountOutMinimum:u,signature:c,quote:l})=>[{to:e,data:d.encodeFunctionData({abi:N,functionName:"withdraw",args:[{account:t.accountId,tokenId:t.tokenId,receiver:n,assets:i,shares:0n,extraData:"0x"}]})},{to:s,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[r,i]})},{to:r,data:d.encodeFunctionData({abi:It,functionName:"swapExactInWithAttestation",args:[s,i,o,u,c,l]})}],Ke=({collateral:t,dytmOffice:e,processor:n})=>({to:e,data:d.encodeFunctionData({abi:N,functionName:"withdraw",args:[{account:t.accountId,tokenId:t.tokenId,receiver:n,assets:0n,shares:d.maxUint256,extraData:"0x"}]})}),je=({accountId:t,debtKey:e,dytmOffice:n,usdc:s})=>[{to:s,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[n,d.maxUint256]})},{to:n,data:d.encodeFunctionData({abi:N,functionName:"repay",args:[{account:t,key:e,withCollateralType:0,assets:d.maxUint256,shares:0n,extraData:"0x"}]})}],Xe=({actions:t,outputAsset:e,minOutputAmount:n})=>d.encodeAbiParameters(Nt,[{actions:t,outputAsset:e,minOutputAmount:n}]),H=new Set,Ze=t=>{const e=t?.message;!e||H.has(e)||(H.add(e),console.warn(e))};exports.DytmOfficeAssetGuardAbi=Rt;exports.EMPTY_PER_ASSET_WITHDRAW_DATA=Fe;exports.HYPERLIQUID_PERPS_ACCOUNT_ADDRESS=ct;exports.OndoGMTokenAssetGuardAbi=wt;exports.THIRD_PARTY_CONTRACT_ERRORS=w;exports.addTokenToWallet=kt;exports.applyContractErrorRegistry=V;exports.base64ToHex=j;exports.buildAaveWithdrawAssetTransactionData=Q;exports.buildComplexAssetDataForRouter=pt;exports.buildDytmActions=Ve;exports.buildDytmOutputAssetWithdrawAction=Ke;exports.buildDytmRepayActions=je;exports.buildSwapQuoteKeyForAave=Z;exports.buildSwapWithdrawTransactionData=se;exports.buildZapDepositTransactionArguments=ne;exports.clientSide=_t;exports.commify=Se;exports.computeAmountOutMinimumUsdc=yt;exports.createDefaultComplexAssetData=Ue;exports.encodeOndoWithdrawData=qe;exports.encodeUnwindPlan=Xe;exports.enrichAssetsWithSwapQuotes=He;exports.ensureContractErrorRegistryLoaded=Gt;exports.ensureHexPrefix=f;exports.extractAvailableRouterKeys=lt;exports.fetchContractErrorRegistry=K;exports.fetchRequest=G;exports.formatBalance=ot;exports.formatByCurrency=_e;exports.formatNumberToLimitedDecimals=st;exports.formatNumeratorToPercentage=fe;exports.formatPercentage=rt;exports.formatToUsd=nt;exports.formatTokenBalance=we;exports.getAutoSlippageSimulationCandidates=We;exports.getComplexAssetDataSlippageTolerance=ee;exports.getContractAbiById=Kt;exports.getContractAddressById=X;exports.getContractErrorRegistry=O;exports.getConventionalTokenPriceDecimals=zt;exports.getErrorKey=R;exports.getFlatMoneyCollateralByLeverageAddress=Ie;exports.getFlatMoneyLinkByUnitAddress=Ne;exports.getGmxWithdrawAssetByLeverageAddress=Pe;exports.getGmxWithdrawAssetByVaultAddress=xe;exports.getHyperliquidWithdrawAsset=ve;exports.getNativeTokenInvestableBalance=ie;exports.getPercent=z;exports.getPoolFraction=Jt;exports.getSettleDelay=oe;exports.getSlippageToleranceForContractTransaction=C;exports.getTxHashShort=De;exports.groupPreviewByAccount=ke;exports.isAaveLendAndBorrowAsset=Xt;exports.isEqualAddress=m;exports.isFlatMoneyLeveragedAsset=Re;exports.isFmpAirdropVaultAddress=be;exports.isGmxLeveragedAsset=Ce;exports.isHyperliquidCorePositionAsset=Me;exports.isHyperliquidPerpsAsset=ut;exports.isHyperliquidSpotSystemAsset=dt;exports.isNativeToken=ae;exports.isNumberType=he;exports.isNumeric=et;exports.isStableSymbol=ce;exports.isZeroAddress=Vt;exports.logContractErrorOnce=Ze;exports.logTransactionByActionType=Oe;exports.mapAttestationToOndoQuote=At;exports.mapOndoApiResponseToUpdatePricesArgs=Ye;exports.nonZeroBigInt=Te;exports.normalizeNumber=tt;exports.overlayWithdrawData=P;exports.parseAmountToD18=te;exports.parseContractErrorMessage=Ee;exports.parseFetchErrorBody=Et;exports.removeInsignificantTrailingZeros=I;exports.shiftBy=Qt;exports.shortenAddress=jt;exports.shouldSwallowMainnetPollError=re;exports.sliceByIndex=Zt;exports.toBigInt=y;exports.toBytes32Hex=b;exports.transformAddressForAnalytics=it;exports.truncateString=at;exports.tryEstimateWithRouters=mt;exports.tryEstimateWithSlippageValues=$e;exports.validateLoggerEventParams=ue;
|
|
1
|
+
"use strict";const E=require("wagmi/chains"),a=require("./gmx-DJ0gqvLq.cjs"),p=require("bignumber.js"),d=require("viem"),P="application/json";class W extends Error{constructor(e,n,s){super(`HTTP ${e}${s?`: ${s}`:""}`),this.name="FetchRequestError",this.status=e,this.statusText=n,this.body=s}}const Et=t=>{if(!(t instanceof W)||!t.body)return null;try{return JSON.parse(t.body)}catch{return null}},ht=t=>typeof t=="string"||t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob||t instanceof ArrayBuffer||ArrayBuffer.isView(t),Tt=(t,e)=>{const n=String(t),s=e?new URLSearchParams(e).toString():"";if(!s)return n;const r=n.indexOf("#"),o=r===-1?n:n.slice(0,r),i=r===-1?"":n.slice(r);return`${o}${o.includes("?")?"&":"?"}${s}${i}`},St=(t,e)=>{const n=new AbortController,s=()=>n.abort();e?.aborted&&s();const r=setTimeout(s,t);return e?.addEventListener("abort",s),{signal:n.signal,cleanup:()=>{clearTimeout(r),e?.removeEventListener("abort",s)}}},ft=async(t,e,n)=>{if(n===void 0)return await t[e]();const s=Number(t.headers.get("content-length"));if(s>n)throw new Error(`Response too large: ${s} bytes`);if(e==="blob"||e==="arrayBuffer"){const o=await t[e](),i=o instanceof Blob?o.size:o.byteLength;if(i>n)throw new Error(`Response too large: ${i} bytes`);return o}const r=await t.text();if(r.length>n)throw new Error(`Response too large: ${r.length} chars`);return e==="json"?JSON.parse(r):r},G=async({url:t,headers:e,method:n,body:s,params:r,signal:o,readMethod:i="json",cache:u,timeoutMs:c,maxResponseBytes:l})=>{const A=s!==void 0&&n!=="GET",h=A&&!ht(s),g=new Headers(e);i==="json"&&!g.has("Accept")&&g.set("Accept",P),h&&!g.has("Content-Type")&&g.set("Content-Type",P);const _=c?St(c,o):void 0,gt={method:n,headers:g,signal:_?.signal??o,...u&&{cache:u},...A&&{body:h?JSON.stringify(s):s}};try{const T=await fetch(Tt(t,r),gt);if(!T.ok)throw new W(T.status,T.statusText,await T.text().catch(()=>""));return await ft(T,i,l)}finally{_?.cleanup()}},_t=typeof window<"u",wt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"address",name:"_asset",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewGmTokenAmount",outputs:[{internalType:"uint256",name:"gmTokenAmount",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"ondoGMSwap",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usdc",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],Dt=[{type:"tuple",components:[{name:"attestationSignature",type:"bytes"},{name:"quote",type:"tuple",components:[{name:"chainId",type:"uint256"},{name:"attestationId",type:"uint256"},{name:"userId",type:"bytes32"},{name:"asset",type:"address"},{name:"price",type:"uint256"},{name:"quantity",type:"uint256"},{name:"expiration",type:"uint256"},{name:"side",type:"uint8"},{name:"additionalData",type:"bytes32"}]},{name:"amountOutMinimum",type:"uint256"}]}],bt=[{name:"asset",type:"address"},{name:"amount",type:"uint256"},{name:"assetType",type:"uint16"},{name:"isPool",type:"bool"},{name:"isDebt",type:"bool"},{name:"marketId",type:"uint88"},{name:"accountId",type:"uint256"},{name:"tokenId",type:"uint256"},{name:"debtKey",type:"uint248"},{name:"shares",type:"uint256"}],Rt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewWithdrawal",outputs:[{name:"assetData",type:"tuple[]",components:bt}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"dytmWithdrawProcessor",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],N=[{inputs:[{name:"params",type:"tuple",components:[{name:"account",type:"uint256"},{name:"tokenId",type:"uint256"},{name:"receiver",type:"address"},{name:"assets",type:"uint256"},{name:"shares",type:"uint256"},{name:"extraData",type:"bytes"}]}],name:"withdraw",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"params",type:"tuple",components:[{name:"account",type:"uint256"},{name:"key",type:"uint248"},{name:"withCollateralType",type:"uint8"},{name:"assets",type:"uint256"},{name:"shares",type:"uint256"},{name:"extraData",type:"bytes"}]}],name:"repay",outputs:[{name:"assetsRepaid",type:"uint256"}],stateMutability:"nonpayable",type:"function"}],It=[{inputs:[{name:"tokenIn",type:"address"},{name:"amountIn",type:"uint256"},{name:"tokenOut",type:"address"},{name:"amountOutMinimum",type:"uint256"},{name:"attestationSignature",type:"bytes"},{name:"quote",type:"tuple",components:[{name:"chainId",type:"uint256"},{name:"attestationId",type:"uint256"},{name:"userId",type:"bytes32"},{name:"asset",type:"address"},{name:"price",type:"uint256"},{name:"quantity",type:"uint256"},{name:"expiration",type:"uint256"},{name:"side",type:"uint8"},{name:"additionalData",type:"bytes32"}]}],name:"swapExactInWithAttestation",outputs:[],stateMutability:"nonpayable",type:"function"}],Nt=[{type:"tuple",components:[{name:"actions",type:"tuple[]",components:[{name:"to",type:"address"},{name:"data",type:"bytes"}]},{name:"outputAsset",type:"address"},{name:"minOutputAmount",type:"uint256"}]}],w={stringErrors:{"currently closed for trading":{title:"The market for this tokenized asset is closed right now",hint:"Wait until the market reopens (the error message says when) and simply retry."},"Synth exchange suspended. Operation prohibited":{title:"Vault includes deprecated synths in portfolio",hint:"Redeem deprecated synth to be able to withdraw."}},selectorErrors:{"0x54971d46":{signature:"SwapFailed(address,(address,uint256,(bytes32,bytes)),bytes)",title:"The token swap failed to execute",hint:"Your assets are still in your wallet — try again, or retry with a higher slippage tolerance."},"0x81a815ef":{signature:"InsufficientAmountReceived(address,uint256,uint256)",title:"Swap output was below the minimum received amount",hint:"Increase slippage tolerance and try again."}}},Y=t=>({stringErrors:{...t.stringErrors,...w.stringErrors},selectorErrors:{...t.selectorErrors,...w.selectorErrors}}),Ot=["https://cdn.jsdelivr.net/gh/dhedge/V2-Public@master/readmes/errorCodes/registry.json","https://raw.githubusercontent.com/dhedge/V2-Public/master/readmes/errorCodes/registry.json"],Ct=1,xt=1e4,Pt=2e6,Bt=2e3,Lt=500,Mt=120,vt=300,Ut=4,Ft=/^dh\d{1,3}$/i,q=/[\u0000-\u001f\u007f]/,$t=/https?:\/\/|[<>`]/i,Ht=t=>t.length<=Mt&&!q.test(t)&&(Ft.test(t)||t.length>=Ut),S=t=>typeof t=="string"&&t.length>0&&t.length<=vt&&!q.test(t)&&!$t.test(t);let k=w,D=null;const O=()=>k,V=t=>{k=Y(t)},Wt=t=>{const e=t;if(e?.schemaVersion!==Ct)throw new Error(`Unsupported error registry schemaVersion: ${String(e?.schemaVersion)}`);const n={};for(const[r,o]of Object.entries(e.stringErrors??{}))o?.curated===!0&&Ht(r)&&S(o.description)&&S(o.action)&&(n[r]={title:o.description,hint:o.action});const s={};for(const[r,o]of Object.entries(e.selectorErrors??{}))o?.curated===!0&&/^0x[0-9a-f]{8}$/.test(r)&&S(o.signature)&&S(o.description)&&S(o.action)&&(s[r]={signature:o.signature,title:o.description,hint:o.action});if(!Object.keys(n).length)throw new Error("Error registry contained no curated string errors");if(Object.keys(n).length>Bt||Object.keys(s).length>Lt)throw new Error("Error registry exceeded expected entry counts");return{stringErrors:n,selectorErrors:s}},K=async({timeoutMs:t=xt}={})=>{const e=[];for(const n of Ot)try{const s=await G({url:n,method:"GET",timeoutMs:t,maxResponseBytes:Pt});return Y(Wt(s))}catch(s){e.push(`${n}: ${s instanceof Error?s.message:String(s)}`)}throw new Error(`All error registry sources failed: ${e.join("; ")}`)},Gt=()=>(D??(D=K().then(V).catch(()=>{D=null})),D),Yt=()=>typeof window<"u";function qt(){return Yt()&&typeof window.ethereum<"u"}async function kt(t){try{if(qt())return window.ethereum.request({method:"wallet_watchAsset",params:{type:"ERC20",options:t}})}catch{return!1}return!1}const m=(t,e)=>t?.toLowerCase()===e?.toLowerCase(),Vt=t=>m(t,a.AddressZero$1),f=t=>{if(!t)throw new Error("Cannot prefix an empty hex value");return t.startsWith("0x")?t:`0x${t}`},y=(t,e)=>{try{return BigInt(t)}catch{throw new Error(`Cannot convert "${e}" value "${t}" to bigint`)}},b=t=>t?d.pad(f(t),{size:32}):d.zeroHash,j=t=>{if(!t)throw new Error("Cannot decode an empty base64 string");return d.bytesToHex(Uint8Array.from(atob(t),e=>e.charCodeAt(0)))},X=(t,e)=>a.contractsAddressesMap[e]?.[t]??a.AddressZero,Kt=t=>a.contractsAbisMap[t],jt=t=>t&&`${t.substring(0,6)}...${t.substring(t.length-4,t.length)}`,Xt=({address:t,chainId:e})=>{const n=X("aaveLendingPoolV3",e);return m(t,n)},Z=({sourceAddress:t,amount:e})=>`${t}_${e}`,Zt=(t,e)=>{const n=t.slice(0,e),s=t.slice(e);return{firstPart:n,secondPart:s}},z=(t,e)=>t/e*100,zt=t=>t<1?4:t<10?3:2,Qt=(t,e=a.DEFAULT_PRECISION)=>new p(t.toString()).shiftedBy(e).toFixed(0),Jt=(t,e,n,s)=>new p(e).dividedBy(n).multipliedBy(t).shiftedBy(-(s||a.DEFAULT_PRECISION)).toNumber(),te=t=>BigInt(new p(t||"0").shiftedBy(a.DEFAULT_PRECISION).toFixed(0,p.ROUND_DOWN)),C=t=>{const e=new p(.01),n=new p(t),s=!n.isZero()&&n.lt(e)?e:n;return BigInt(s.multipliedBy(100).toFixed(0))},ee=({chainId:t,slippage:e})=>t===E.hyperEvm.id?BigInt(0):C(e),ne=({vaultAddress:t,swapData:e,sendTokenAddress:n,sendTokenAmount:s,vaultDepositTokenAddress:r,minVaultTokensReceivedAmount:o,routerKey:i="ONE_INCH",swapDestinationAmount:u,swapSlippage:c})=>{const l=new p(u).multipliedBy(1-c/100).toFixed(0),A=[d.stringToHex(i,{size:32}),e];return[t,[[n,s,A],[r,l]],o]},se=({receiveAssetAddress:t,assets:e,swapData:n,slippage:s})=>{const r={srcData:[],destAmount:new p("0")},{srcData:o,destAmount:i}=e?.reduce((u,c)=>{const l=n?.[c.address];if(!l)return u;const A=[d.stringToHex(l.routerKey,{size:32}),l.rawTransaction.data],h=[c.address,c.rawBalance,A];return{srcData:[...u.srcData,h],destAmount:u.destAmount.plus(l.destinationAmount)}},r)??r;return[o,[t,i.times(1-s/100).toFixed(0,p.ROUND_DOWN)]]},Q=({assetAddress:t,swapQuotes:e,swapParams:n,slippageToleranceForContractTransaction:s,routerKey:r})=>{if(!n)return{supportedAsset:t,withdrawData:"",slippageTolerance:BigInt(0)};const{srcData:o,dstData:i}=n,u=o.map(({asset:A,amount:h})=>{const g=e?.[Z({sourceAddress:A,amount:h.toString()})]?.find(_=>_.routerKey===r);return{asset:A,amount:h,swapData:{routerKey:d.stringToHex(g?.routerKey??"",{size:32}),txData:g?.rawTransaction.data??"0x"}}}),c=d.encodeAbiParameters(a.ComplexWithdrawalAssetSrcDataAbiItem,[u]),l=d.encodeAbiParameters(a.ComplexWithdrawalDataAbiItem,[{encodedSrcData:c,dstData:{dstAddress:i.asset,dstAmount:i.amount},slippage:s}]);return{supportedAsset:t,withdrawData:l,slippageTolerance:s}},re=({chainId:t,txHash:e,error:n})=>{if(t!==E.mainnet.id||!e||!n)return!1;const s=n instanceof Error?n.message:String(n);return/\bNo Result\b/i.test(s)},oe=({chainId:t,action:e,isRabbyWallet:n})=>e==="update_ondo_prices"&&t===E.mainnet.id&&n?a.ONDO_PRICES_RABBY_SETTLE_DELAY:t?a.TRANSACTION_SETTLE_DELAY[t]??0:0,ae=(t,e)=>a.CHAIN_NATIVE_TOKENS[e]?.nativeTokenSymbol===t,ie=({nativeTokenBalance:t,tokenDecimals:e,gasPrice:n})=>{const s=new p(n).multipliedBy(a.NATIVE_TOKEN_GAS_RESERVE_UNITS).shiftedBy(-e),r=new p(t).minus(s);return r.gt("0")?r:new p("0")},ce=t=>a.STABLE_TOKEN_SYMBOLS.includes(t),ue=t=>{const e=Object.values(t).reduce((n,{type:s})=>(n[s]=n[s]+1,n),{string:0,number:0});if(e.string>10)throw new Error("logger params must contain up to 10 string values");if(e.number>40)throw new Error("logger params must contain up to 40 numeric values");return!0},de=(t,e=150)=>t.length>e?t.substring(0,e):t,J=()=>({...O().stringErrors,...a.TRANSACTION_ERRORS}),le=()=>[...Object.keys(J()),...Object.keys(a.LIMIT_ORDER_TRANSACTION_ERRORS)],pe=/^dh\d+$/i,me=(t,e)=>pe.test(e)?new RegExp(`\\b${e}\\b`,"i").test(t):t.includes(e.toLowerCase()),R=(t,e)=>{const n=t.toLowerCase();return[...e??le()].sort((s,r)=>r.length-s.length).find(s=>me(n,s))},B=t=>J()[t]??a.LIMIT_ORDER_TRANSACTION_ERRORS[t],ye=/\b0x[0-9a-f]{8}\b/i,Ae=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ge=t=>{const{selectorErrors:e}=O(),n=t.match(ye)?.[0]?.toLowerCase(),s=n?e[n]:void 0;if(s)return{title:s.title,hint:s.hint};const r=Object.values(e).find(o=>new RegExp(`\\b${Ae(o.signature.split("(")[0]??"")}\\b`).test(t));return r?{title:r.title,hint:r.hint}:void 0},Ee=({errorMessage:t,abiErrors:e})=>{if(!t||t.includes("User rejected"))return null;const n=e.find(i=>t.includes(i));if(n){const i=R(n);if(i)return B(i)}const s=R(t);if(s)return B(s);const r=ge(t);if(r)return r;const[o]=t.split(n?".":"Contract").map(i=>i.trim());return{title:"Transaction failed",hint:`${de(o??"")} ${n?`: ${n}`:""}`}},he=t=>typeof t=="number"&&Number.isFinite(t),Te=t=>typeof t=="bigint"&&t!==BigInt(0),tt=(t,e=a.DEFAULT_PRECISION$1)=>new p(t).shiftedBy(-e).toNumber(),et=t=>!isNaN(parseFloat(t))&&!isNaN(t),nt=({value:t,minimumFractionDigits:e=2,maximumFractionDigits:n=2,compact:s=!1,normalize:r=!1})=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:s?"compact":void 0,minimumFractionDigits:e,maximumFractionDigits:n}).format(r?tt(t):Number(t)),I=t=>et(t)?new p(t).toFixed():"",L=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"],st=({value:t,decimals:e=4})=>{const n=new p(t);if(n.isGreaterThan(1)||n.isZero())return I(n.toFixed(e));const r=(/e/i.test(t.toString())?parseFloat(t.toString()).toFixed(a.DEFAULT_PRECISION$1):t.toString()).match(/^0\.(0+)(\d+)$/);if(r){const[,o,i]=r;if(o.length>=e&&o.length<L.length)return`0.0${L[o.length]}${i.slice(0,3)}`}return I(n.toFixed(e))},rt=(t,e=0)=>`${t.toLocaleString("en-US",{maximumFractionDigits:e})}%`,Se=t=>t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),fe=(t,e,n=0)=>{const s=z(+t,e);return rt(s,n)},_e=({currency:t,value:e})=>t==="USD"?nt({value:e}):`${a.CURRENCY_SYMBOL_MAP[t]} ${st({value:e,decimals:a.CURRENCY_DECIMALS_MAP[t]})}`,ot=(t,e)=>new p(new p(t).toFixed(e,p.ROUND_DOWN)).toString(),at=(t,e=3,n=2)=>{if(t.length<=5)return t;const s="...";return t.length<=e+n+s.length?t:`${t.slice(0,e)}${s}${t.slice(-n)}`},we=({balance:t,symbol:e,precision:n,truncateSymbol:s})=>`${ot(t,n)} ${s?at(e):e}`,De=t=>{if(!t)return;const e=t.match(/0x[a-fA-F0-9]{64}/);if(!e)return;const n=e[0];return`${n.slice(0,4)}...${n.slice(-3)}`},be=t=>m(a.FLATMONEY_EARLY_DEPOSITOR_VAULT_ADDRESS_BASE,t)||m(a.FLATMONEY_DHT_STAKING_VAULT_ADDRESS_BASE,t),Re=t=>a.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES.some(e=>m(e,t)),Ie=t=>a.FLAT_MONEY_COLLATERAL_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},Ne=t=>m(t,a.FLAT_MONEY_V1_UNIT_ADDRESS)?a.FLAT_MONEY_V1_UNIT_LINK:a.FLAT_MONEY_UNIT_LINK,it=t=>`eth_${t}`,Oe=({action:t,log:e,symbol:n,vaultAddress:s,chainId:r})=>{const o={[a.TRADING_LOG_EVENT_PARAM.SYMBOL.NAME]:n,[a.TRADING_LOG_EVENT_PARAM.CHAIN_ID.NAME]:r,[a.TRADING_LOG_EVENT_PARAM.ADDRESS.NAME]:it(s)};a.LOG_EVENT_BY_TRANSACTION_ACTION_MAP[t].forEach(i=>{e?.(i,o)})},Ce=t=>a.GMX_MARKET_ASSETS.some(e=>m(e,t)),xe=t=>a.GMX_WITHDRAW_ASSET_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},Pe=t=>a.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS[t.toLowerCase()],ct="0x3333333333333333333333333333333333333333";E.arbitrum.id+"",a.USDC_ARBITRUM.address,E.base.id+"",a.USDC_BASE.address,E.optimism.id+"",a.USDC_OPTIMISM.address,E.polygon.id+"",a.USDC_POLYGON.address,E.mainnet.id+"",a.USDC_MAINNET.address,E.hyperEvm.id+"",a.USDC_HYPEREVM.address;const Be="0x2222222222222222222222222222222222222222",M=BigInt("0x2000000000000000000000000000000000000000"),Le=10000n,ut=t=>m(t,ct),dt=t=>{if(m(t,Be))return!0;try{const e=BigInt(t);return e>=M&&e<M+Le}catch{return!1}},Me=t=>ut(t)||dt(t),ve=()=>a.USDC_HYPEREVM,Ue=new Map,x=(t,e)=>!e||e.size===0?t:t.map(n=>{const s=e.get(n.supportedAsset.toLowerCase());return s?{...n,withdrawData:s.withdrawData,slippageTolerance:s.slippageTolerance}:n}),lt=t=>{const e=t.find(({swapQuotes:n})=>n);return e?.swapQuotes?Object.values(e.swapQuotes)[0]?.map(({routerKey:n})=>n)??[]:[]},pt=(t,e,n)=>t.map(({asset:s,swapParams:r,swapQuotes:o})=>!r||!o?{supportedAsset:s,withdrawData:"",slippageTolerance:n}:Q({assetAddress:s,swapQuotes:o,swapParams:r,slippageToleranceForContractTransaction:n,routerKey:e})),mt=async(t,e,n,s,r,o)=>{for(const i of t){const u=x(pt(e,i,n),o),{error:c}=await s(...r,u);if(!c)return u}return null},Fe=(t,e,n)=>{const s=(t??[]).map(r=>({supportedAsset:r,withdrawData:"",slippageTolerance:e}));return x(s,n)},$e=async(t,e,n,s,r)=>{for(const o of t){const i=C(o);try{const u=await e(o),c=lt(u),l=await mt(c,u,i,n,s,r);if(l)return console.debug(`[Init Withdraw] Auto slippage simulation succeeded: slippage=${o}%`),console.debug("[Init Withdraw] Complex asset data:",l),l}catch(u){console.error(`[Init Withdraw] Failed to fetch quotes for slippage=${o}%:`,u)}}return null},He=async(t,e,{fetchAaveSwapParams:n,fetchAaveSwapQuotes:s,withdrawAmountD18:r,slippage:o})=>Promise.all((t??[]).map(async i=>{if(!m(i,e))return{asset:i};try{const c=await n({withdrawAmountD18:r,slippage:o});if(c?.srcData.length){const l=await s({swapParams:c,slippage:o});return{asset:i,swapParams:c,swapQuotes:l}}return{asset:i}}catch(c){return console.error(c),{asset:i}}})),v=t=>Math.round(t*100)/100,We=({maxSlippage:t,candidates:e=a.SLIPPAGE_AUTO_SIMULATION_CANDIDATES})=>{if(!Number.isFinite(t)||t<=0)return[];const n=v(Math.min(t,100)),s=e.filter(o=>o>0&&o<=n).map(v),r=new Set(s);return r.add(n),r.add(t),Array.from(r).sort((o,i)=>o-i)},U=1000000000000000000n,Ge=1000000n,F=10000n,$=100n,Ye=t=>({quotes:t.quotes.map(e=>({chainId:y(e.chainId,"chainId"),attestationId:y(e.attestationId,"attestationId"),userId:f(e.userId),asset:e.asset,price:y(e.price,"price"),quantity:y(e.quantity,"quantity"),expiration:y(e.expiration,"expiration"),side:Number(e.side),additionalData:f(e.additionalData)})),signatures:t.signatures.map(f)}),yt=(t,e,n)=>{const s=BigInt(Math.max(0,Math.round(n*100))),r=s>$?$:s,o=F-r,u=t*e/U*o*Ge,c=F*U;return(u+c-1n)/c},At=(t,e)=>({chainId:e,attestationId:y(t.attestationId,"attestationId"),userId:b(t.userId),asset:t.assetAddress,price:y(t.price,"price"),quantity:y(t.tokenAmount,"tokenAmount"),expiration:y(t.expiration,"expiration"),side:Number(t.side),additionalData:b(t.additionalData)}),qe=({attestation:t,chainId:e,slippagePercent:n})=>{const s=At(t,e);return d.encodeAbiParameters(Dt,[{attestationSignature:j(t.signature),quote:s,amountOutMinimum:yt(s.quantity,s.price,n)}])},ke=t=>[...t.reduce((n,s)=>n.has(s.accountId)?n:n.set(s.accountId,s),new Map).values()].map(({accountId:n,marketId:s})=>({accountId:n,marketId:s,collaterals:t.filter(r=>r.accountId===n&&!r.isDebt),debt:t.find(r=>r.accountId===n&&r.isDebt)})),Ve=({collateral:t,dytmOffice:e,processor:n,gmToken:s,ondoGMSwap:r,usdc:o,gmAmount:i,amountOutMinimum:u,signature:c,quote:l})=>[{to:e,data:d.encodeFunctionData({abi:N,functionName:"withdraw",args:[{account:t.accountId,tokenId:t.tokenId,receiver:n,assets:0n,shares:d.maxUint256,extraData:"0x"}]})},{to:s,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[r,i]})},{to:r,data:d.encodeFunctionData({abi:It,functionName:"swapExactInWithAttestation",args:[s,i,o,u,c,l]})}],Ke=({collateral:t,dytmOffice:e,processor:n})=>({to:e,data:d.encodeFunctionData({abi:N,functionName:"withdraw",args:[{account:t.accountId,tokenId:t.tokenId,receiver:n,assets:0n,shares:d.maxUint256,extraData:"0x"}]})}),je=({accountId:t,debtKey:e,dytmOffice:n,usdc:s})=>[{to:s,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[n,d.maxUint256]})},{to:n,data:d.encodeFunctionData({abi:N,functionName:"repay",args:[{account:t,key:e,withCollateralType:0,assets:d.maxUint256,shares:0n,extraData:"0x"}]})}],Xe=({actions:t,outputAsset:e,minOutputAmount:n})=>d.encodeAbiParameters(Nt,[{actions:t,outputAsset:e,minOutputAmount:n}]),H=new Set,Ze=t=>{const e=t?.message;!e||H.has(e)||(H.add(e),console.warn(e))};exports.DytmOfficeAssetGuardAbi=Rt;exports.EMPTY_PER_ASSET_WITHDRAW_DATA=Ue;exports.HYPERLIQUID_PERPS_ACCOUNT_ADDRESS=ct;exports.OndoGMTokenAssetGuardAbi=wt;exports.THIRD_PARTY_CONTRACT_ERRORS=w;exports.addTokenToWallet=kt;exports.applyContractErrorRegistry=V;exports.base64ToHex=j;exports.buildAaveWithdrawAssetTransactionData=Q;exports.buildComplexAssetDataForRouter=pt;exports.buildDytmActions=Ve;exports.buildDytmOutputAssetWithdrawAction=Ke;exports.buildDytmRepayActions=je;exports.buildSwapQuoteKeyForAave=Z;exports.buildSwapWithdrawTransactionData=se;exports.buildZapDepositTransactionArguments=ne;exports.clientSide=_t;exports.commify=Se;exports.computeAmountOutMinimumUsdc=yt;exports.createDefaultComplexAssetData=Fe;exports.encodeOndoWithdrawData=qe;exports.encodeUnwindPlan=Xe;exports.enrichAssetsWithSwapQuotes=He;exports.ensureContractErrorRegistryLoaded=Gt;exports.ensureHexPrefix=f;exports.extractAvailableRouterKeys=lt;exports.fetchContractErrorRegistry=K;exports.fetchRequest=G;exports.formatBalance=ot;exports.formatByCurrency=_e;exports.formatNumberToLimitedDecimals=st;exports.formatNumeratorToPercentage=fe;exports.formatPercentage=rt;exports.formatToUsd=nt;exports.formatTokenBalance=we;exports.getAutoSlippageSimulationCandidates=We;exports.getComplexAssetDataSlippageTolerance=ee;exports.getContractAbiById=Kt;exports.getContractAddressById=X;exports.getContractErrorRegistry=O;exports.getConventionalTokenPriceDecimals=zt;exports.getErrorKey=R;exports.getFlatMoneyCollateralByLeverageAddress=Ie;exports.getFlatMoneyLinkByUnitAddress=Ne;exports.getGmxWithdrawAssetByLeverageAddress=xe;exports.getGmxWithdrawAssetByVaultAddress=Pe;exports.getHyperliquidWithdrawAsset=ve;exports.getNativeTokenInvestableBalance=ie;exports.getPercent=z;exports.getPoolFraction=Jt;exports.getSettleDelay=oe;exports.getSlippageToleranceForContractTransaction=C;exports.getTxHashShort=De;exports.groupPreviewByAccount=ke;exports.isAaveLendAndBorrowAsset=Xt;exports.isEqualAddress=m;exports.isFlatMoneyLeveragedAsset=Re;exports.isFmpAirdropVaultAddress=be;exports.isGmxLeveragedAsset=Ce;exports.isHyperliquidCorePositionAsset=Me;exports.isHyperliquidPerpsAsset=ut;exports.isHyperliquidSpotSystemAsset=dt;exports.isNativeToken=ae;exports.isNumberType=he;exports.isNumeric=et;exports.isStableSymbol=ce;exports.isZeroAddress=Vt;exports.logContractErrorOnce=Ze;exports.logTransactionByActionType=Oe;exports.mapAttestationToOndoQuote=At;exports.mapOndoApiResponseToUpdatePricesArgs=Ye;exports.nonZeroBigInt=Te;exports.normalizeNumber=tt;exports.overlayWithdrawData=x;exports.parseAmountToD18=te;exports.parseContractErrorMessage=Ee;exports.parseFetchErrorBody=Et;exports.removeInsignificantTrailingZeros=I;exports.shiftBy=Qt;exports.shortenAddress=jt;exports.shouldSwallowMainnetPollError=re;exports.sliceByIndex=Zt;exports.toBigInt=y;exports.toBytes32Hex=b;exports.transformAddressForAnalytics=it;exports.truncateString=at;exports.tryEstimateWithRouters=mt;exports.tryEstimateWithSlippageValues=$e;exports.validateLoggerEventParams=ue;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { hyperEvm as W, mainnet as I, polygon as st, optimism as at, base as rt, arbitrum as ot } from "wagmi/chains";
|
|
2
|
-
import { aq as it, ao as ct, ap as ut, a as R, q as N, ar as dt, as as pt, a5 as lt, ak as mt, a3 as yt, b as gt, ae as At, Z as k, aj as Et, at as q, e as ht, d as ft, M as St, R as Tt, P as wt, au as _t, av as bt, Q as Dt, N as It, ah as
|
|
2
|
+
import { aq as it, ao as ct, ap as ut, a as R, q as N, ar as dt, as as pt, a5 as lt, ak as mt, a3 as yt, b as gt, ae as At, Z as k, aj as Et, at as q, e as ht, d as ft, M as St, R as Tt, P as wt, au as _t, av as bt, Q as Dt, N as It, ah as _, _ as Rt, W as Nt, X as Ot, U as Ct, aw as V, ax as xt, ay as Bt, az as Lt, aA as Mt, aB as Pt, ad as Ut } from "./gmx-Cyz_GmV5.js";
|
|
3
3
|
import d from "bignumber.js";
|
|
4
|
-
import { zeroHash as $t, bytesToHex as vt, pad as Ft, stringToHex as O, encodeAbiParameters as T, encodeFunctionData as A,
|
|
4
|
+
import { zeroHash as $t, bytesToHex as vt, pad as Ft, stringToHex as O, encodeAbiParameters as T, encodeFunctionData as A, maxUint256 as w, erc20Abi as K } from "viem";
|
|
5
5
|
const x = "application/json";
|
|
6
6
|
class j extends Error {
|
|
7
7
|
constructor(e, n, s) {
|
|
@@ -292,7 +292,7 @@ const Ke = (t) => {
|
|
|
292
292
|
"https://cdn.jsdelivr.net/gh/dhedge/V2-Public@master/readmes/errorCodes/registry.json",
|
|
293
293
|
"https://raw.githubusercontent.com/dhedge/V2-Public/master/readmes/errorCodes/registry.json"
|
|
294
294
|
], zt = 1, Qt = 1e4, Zt = 2e6, Jt = 2e3, te = 500, ee = 120, ne = 300, se = 4, ae = /^dh\d{1,3}$/i, z = /[\u0000-\u001f\u007f]/, re = /https?:\/\/|[<>`]/i, oe = (t) => t.length <= ee && !z.test(t) && (ae.test(t) || t.length >= se), h = (t) => typeof t == "string" && t.length > 0 && t.length <= ne && !z.test(t) && !re.test(t);
|
|
295
|
-
let Q = D,
|
|
295
|
+
let Q = D, b = null;
|
|
296
296
|
const Z = () => Q, ie = (t) => {
|
|
297
297
|
Q = X(t);
|
|
298
298
|
}, ce = (t) => {
|
|
@@ -335,9 +335,9 @@ const Z = () => Q, ie = (t) => {
|
|
|
335
335
|
);
|
|
336
336
|
}
|
|
337
337
|
throw new Error(`All error registry sources failed: ${e.join("; ")}`);
|
|
338
|
-
}, Qe = () => (
|
|
339
|
-
|
|
340
|
-
})),
|
|
338
|
+
}, Qe = () => (b ?? (b = ue().then(ie).catch(() => {
|
|
339
|
+
b = null;
|
|
340
|
+
})), b), de = () => typeof window < "u";
|
|
341
341
|
function pe() {
|
|
342
342
|
return de() && typeof window.ethereum < "u";
|
|
343
343
|
}
|
|
@@ -623,9 +623,9 @@ const p = (t, e) => t?.toLowerCase() === e?.toLowerCase(), Je = (t) => p(t, it),
|
|
|
623
623
|
chainId: a
|
|
624
624
|
}) => {
|
|
625
625
|
const r = {
|
|
626
|
-
[
|
|
627
|
-
[
|
|
628
|
-
[
|
|
626
|
+
[_.SYMBOL.NAME]: n,
|
|
627
|
+
[_.CHAIN_ID.NAME]: a,
|
|
628
|
+
[_.ADDRESS.NAME]: xe(s)
|
|
629
629
|
};
|
|
630
630
|
Rt[t].forEach((o) => {
|
|
631
631
|
e?.(o, r);
|
|
@@ -822,7 +822,8 @@ const Le = "0x2222222222222222222222222222222222222222", $ = BigInt("0x200000000
|
|
|
822
822
|
quote: u
|
|
823
823
|
}) => [
|
|
824
824
|
{
|
|
825
|
-
// 1 ·
|
|
825
|
+
// 1 · drain GM collateral out of the split account -> processor with the
|
|
826
|
+
// max-shares sentinel.
|
|
826
827
|
to: e,
|
|
827
828
|
data: A({
|
|
828
829
|
abi: C,
|
|
@@ -832,8 +833,8 @@ const Le = "0x2222222222222222222222222222222222222222", $ = BigInt("0x200000000
|
|
|
832
833
|
account: t.accountId,
|
|
833
834
|
tokenId: t.tokenId,
|
|
834
835
|
receiver: n,
|
|
835
|
-
assets:
|
|
836
|
-
shares:
|
|
836
|
+
assets: 0n,
|
|
837
|
+
shares: w,
|
|
837
838
|
extraData: "0x"
|
|
838
839
|
}
|
|
839
840
|
]
|
|
@@ -872,7 +873,7 @@ const Le = "0x2222222222222222222222222222222222222222", $ = BigInt("0x200000000
|
|
|
872
873
|
tokenId: t.tokenId,
|
|
873
874
|
receiver: n,
|
|
874
875
|
assets: 0n,
|
|
875
|
-
shares:
|
|
876
|
+
shares: w,
|
|
876
877
|
extraData: "0x"
|
|
877
878
|
}
|
|
878
879
|
]
|
|
@@ -889,7 +890,7 @@ const Le = "0x2222222222222222222222222222222222222222", $ = BigInt("0x200000000
|
|
|
889
890
|
data: A({
|
|
890
891
|
abi: K,
|
|
891
892
|
functionName: "approve",
|
|
892
|
-
args: [n,
|
|
893
|
+
args: [n, w]
|
|
893
894
|
})
|
|
894
895
|
},
|
|
895
896
|
{
|
|
@@ -904,7 +905,7 @@ const Le = "0x2222222222222222222222222222222222222222", $ = BigInt("0x200000000
|
|
|
904
905
|
key: e,
|
|
905
906
|
withCollateralType: 0,
|
|
906
907
|
// DytmParamStructs.TokenType.NONE
|
|
907
|
-
assets:
|
|
908
|
+
assets: w,
|
|
908
909
|
// repay all
|
|
909
910
|
shares: 0n,
|
|
910
911
|
extraData: "0x"
|