@dhedge/trading-widget 6.3.0 → 6.3.2
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/contract-error-log-Ci0TIrO5.js +1015 -0
- package/contract-error-log-D3UONUXl.cjs +1 -0
- package/core-kit/models/ondo-api-error.d.ts +5 -1
- package/core-kit/utils/contract-error-log.d.ts +1 -0
- package/core-kit/utils/index.d.ts +1 -0
- package/index.cjs +1 -1
- package/index.js +2124 -2133
- package/package.json +1 -1
- package/utils.cjs +1 -1
- package/utils.js +34 -33
- package/dytm-D5O16WMt.js +0 -943
- package/dytm-wondvAJ2.cjs +0 -1
|
@@ -0,0 +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;
|
|
@@ -7,5 +7,9 @@ export declare class OndoApiError extends CustomError {
|
|
|
7
7
|
code?: string;
|
|
8
8
|
constructor({ message, code }: OndoApiErrorParams);
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Normalizes any Ondo request failure — HTTP error, network error or timeout —
|
|
12
|
+
* into an `OndoApiError`, preferring the API's own message over the fallback.
|
|
13
|
+
*/
|
|
14
|
+
export declare const throwOndoApiError: (cause: unknown, fallbackMessage: string) => Promise<never>;
|
|
11
15
|
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const logContractErrorOnce: (error?: Error | null) => void;
|