@dhedge/trading-widget 6.0.1 → 6.0.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.
@@ -0,0 +1 @@
1
+ "use strict";const u=require("bignumber.js"),r=require("./gmx-DVJxXc_8.cjs"),p=require("viem"),T=require("wagmi/chains"),Q=typeof window<"u",z=[{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"}],j=[{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"}]}],X=()=>typeof window<"u";function J(){return X()&&typeof window.ethereum<"u"}async function tt(t){try{if(J())return window.ethereum.request({method:"wallet_watchAsset",params:{type:"ERC20",options:t}})}catch{return!1}return!1}const l=(t,e)=>t?.toLowerCase()===e?.toLowerCase(),et=t=>l(t,r.AddressZero$1),O=(t,e)=>r.contractsAddressesMap[e]?.[t]??r.AddressZero,nt=t=>r.contractsAbisMap[t],st=t=>t&&`${t.substring(0,6)}...${t.substring(t.length-4,t.length)}`,rt=({address:t,chainId:e})=>{const n=O("aaveLendingPoolV3",e);return l(t,n)},B=({sourceAddress:t,amount:e})=>`${t}_${e}`,ot=(t,e)=>{const n=t.slice(0,e),s=t.slice(e);return{firstPart:n,secondPart:s}},L=(t,e)=>t/e*100,at=t=>t<1?4:t<10?3:2,it=(t,e=r.DEFAULT_PRECISION)=>new u(t.toString()).shiftedBy(e).toFixed(0),ct=(t,e,n,s)=>new u(e).dividedBy(n).multipliedBy(t).shiftedBy(-(s||r.DEFAULT_PRECISION)).toNumber(),dt=t=>BigInt(new u(t||"0").shiftedBy(r.DEFAULT_PRECISION).toFixed(0,u.ROUND_DOWN)),P=t=>{const e=new u(.01),n=new u(t),s=!n.isZero()&&n.lt(e)?e:n;return BigInt(s.multipliedBy(100).toFixed(0))},ut=({vaultAddress:t,swapData:e,sendTokenAddress:n,sendTokenAmount:s,vaultDepositTokenAddress:o,minVaultTokensReceivedAmount:a,routerKey:i="ONE_INCH",swapDestinationAmount:d,swapSlippage:c})=>{const A=new u(d).multipliedBy(1-c/100).toFixed(0),g=[p.stringToHex(i,{size:32}),e];return[t,[[n,s,g],[o,A]],a]},At=({receiveAssetAddress:t,assets:e,swapData:n,slippage:s})=>{const o={srcData:[],destAmount:new u("0")},{srcData:a,destAmount:i}=e?.reduce((d,c)=>{const A=n?.[c.address];if(!A)return d;const g=[p.stringToHex(A.routerKey,{size:32}),A.rawTransaction.data],y=[c.address,c.rawBalance,g];return{srcData:[...d.srcData,y],destAmount:d.destAmount.plus(A.destinationAmount)}},o)??o;return[a,[t,i.times(1-s/100).toFixed(0,u.ROUND_DOWN)]]},M=({assetAddress:t,swapQuotes:e,swapParams:n,slippageToleranceForContractTransaction:s,routerKey:o})=>{if(!n)return{supportedAsset:t,withdrawData:"",slippageTolerance:BigInt(0)};const{srcData:a,dstData:i}=n,d=a.map(({asset:g,amount:y})=>{const D=e?.[B({sourceAddress:g,amount:y.toString()})]?.find(Z=>Z.routerKey===o);return{asset:g,amount:y,swapData:{routerKey:p.stringToHex(D?.routerKey??"",{size:32}),txData:D?.rawTransaction.data??"0x"}}}),c=p.encodeAbiParameters(r.ComplexWithdrawalAssetSrcDataAbiItem,[d]),A=p.encodeAbiParameters(r.ComplexWithdrawalDataAbiItem,[{encodedSrcData:c,dstData:{dstAddress:i.asset,dstAmount:i.amount},slippage:s}]);return{supportedAsset:t,withdrawData:A,slippageTolerance:s}},lt=(t,e)=>r.CHAIN_NATIVE_TOKENS[e]?.nativeTokenSymbol===t,mt=({nativeTokenBalance:t,tokenDecimals:e,gasPrice:n})=>{const s=new u(n).multipliedBy(r.NATIVE_TOKEN_DEPOSIT_GAS_LIMIT).shiftedBy(-e),o=new u(t).minus(s);return o.gt("0")?o:new u("0")},pt=t=>r.STABLE_TOKEN_SYMBOLS.includes(t),gt=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},Tt=(t,e=150)=>t.length>e?t.substring(0,e):t,_=(t,e=r.TRANSACTION_ERROR_KEYS)=>{const n=t.toLowerCase();return e.sort((s,o)=>o.length-s.length).find(s=>n.includes(s.toLowerCase()))},h=t=>r.TRANSACTION_ERRORS[t]??r.LIMIT_ORDER_TRANSACTION_ERRORS[t],yt=({errorMessage:t,abiErrors:e})=>{if(!t||t.includes("User rejected"))return null;const n=e.find(a=>t.includes(a));if(n&&_(n))return h(n);const s=_(t);if(s)return h(s);const[o]=t.split(n?".":"Contract").map(a=>a.trim());return{title:"Transaction failed",hint:`${Tt(o??"")} ${n?`: ${n}`:""}`}},St=t=>typeof t=="number"&&Number.isFinite(t),Dt=t=>typeof t=="bigint"&&t!==BigInt(0),x=(t,e=r.DEFAULT_PRECISION$1)=>new u(t).shiftedBy(-e).toNumber(),F=t=>!isNaN(parseFloat(t))&&!isNaN(t),U=({value:t,minimumFractionDigits:e=2,maximumFractionDigits:n=2,compact:s=!1,normalize:o=!1})=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:s?"compact":void 0,minimumFractionDigits:e,maximumFractionDigits:n}).format(o?x(t):Number(t)),E=t=>F(t)?new u(t).toFixed():"",N=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"],v=({value:t,decimals:e=4})=>{const n=new u(t);if(n.isGreaterThan(1)||n.isZero())return E(n.toFixed(e));const o=(/e/i.test(t.toString())?parseFloat(t.toString()).toFixed(r.DEFAULT_PRECISION$1):t.toString()).match(/^0\.(0+)(\d+)$/);if(o){const[,a,i]=o;if(a.length>=e&&a.length<N.length)return`0.0${N[a.length]}${i.slice(0,3)}`}return E(n.toFixed(e))},W=(t,e=0)=>`${t.toLocaleString("en-US",{maximumFractionDigits:e})}%`,_t=t=>t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),Et=(t,e,n=0)=>{const s=L(+t,e);return W(s,n)},It=({currency:t,value:e})=>t==="USD"?U({value:e}):`${r.CURRENCY_SYMBOL_MAP[t]} ${v({value:e,decimals:r.CURRENCY_DECIMALS_MAP[t]})}`,G=(t,e)=>new u(new u(t).toFixed(e,u.ROUND_DOWN)).toString(),$=(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)}`},ht=({balance:t,symbol:e,precision:n,truncateSymbol:s})=>`${G(t,n)} ${s?$(e):e}`,Nt=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)}`},ft=t=>l(r.FLATMONEY_EARLY_DEPOSITOR_VAULT_ADDRESS_BASE,t)||l(r.FLATMONEY_DHT_STAKING_VAULT_ADDRESS_BASE,t),wt=t=>r.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES.some(e=>l(e,t)),bt=t=>r.FLAT_MONEY_COLLATERAL_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:r.AddressZero},Rt=t=>l(t,r.FLAT_MONEY_V1_UNIT_ADDRESS)?r.FLAT_MONEY_V1_UNIT_LINK:r.FLAT_MONEY_UNIT_LINK,H=t=>`eth_${t}`,Ct=({action:t,log:e,symbol:n,vaultAddress:s,chainId:o})=>{const a={[r.TRADING_LOG_EVENT_PARAM.SYMBOL.NAME]:n,[r.TRADING_LOG_EVENT_PARAM.CHAIN_ID.NAME]:o,[r.TRADING_LOG_EVENT_PARAM.ADDRESS.NAME]:H(s)};r.LOG_EVENT_BY_TRANSACTION_ACTION_MAP[t].forEach(i=>{e?.(i,a)})},Ot=t=>r.GMX_MARKET_ASSETS.some(e=>l(e,t)),Bt=t=>r.GMX_WITHDRAW_ASSET_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:r.AddressZero},Lt=t=>r.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS[t.toLowerCase()],V="0x3333333333333333333333333333333333333333";T.arbitrum.id+"",r.USDC_ARBITRUM.address,T.base.id+"",r.USDC_BASE.address,T.optimism.id+"",r.USDC_OPTIMISM.address,T.polygon.id+"",r.USDC_POLYGON.address,T.mainnet.id+"",r.USDC_MAINNET.address,T.hyperEvm.id+"",r.USDC_HYPEREVM.address;const Pt=t=>l(t,V),Mt=()=>r.USDC_HYPEREVM,xt=new Map,I=(t,e)=>!e||e.size===0?t:t.map(n=>{const s=e.get(n.supportedAsset.toLowerCase());return s?{...n,withdrawData:s,slippageTolerance:r.DEFAULT_ONDO_WITHDRAWAL_CONTRACT_SLIPPAGE}:n}),q=t=>{const e=t.find(({swapQuotes:n})=>n);return e?.swapQuotes?Object.values(e.swapQuotes)[0]?.map(({routerKey:n})=>n)??[]:[]},Y=(t,e,n)=>t.map(({asset:s,swapParams:o,swapQuotes:a})=>!o||!a?{supportedAsset:s,withdrawData:"",slippageTolerance:n}:M({assetAddress:s,swapQuotes:a,swapParams:o,slippageToleranceForContractTransaction:n,routerKey:e})),K=async(t,e,n,s,o,a)=>{for(const i of t){const d=I(Y(e,i,n),a),{error:c}=await s(...o,d);if(!c)return d}return null},Ft=(t,e,n)=>{const s=(t??[]).map(o=>({supportedAsset:o,withdrawData:"",slippageTolerance:e}));return I(s,n)},Ut=async(t,e,n,s,o)=>{for(const a of t){const i=P(a);try{const d=await e(a),c=q(d),A=await K(c,d,i,n,s,o);if(A)return console.debug(`[Init Withdraw] Auto slippage simulation succeeded: slippage=${a}%`),console.debug("[Init Withdraw] Complex asset data:",A),A}catch(d){console.error(`[Init Withdraw] Failed to fetch quotes for slippage=${a}%:`,d)}}return null},vt=async(t,e,{fetchAaveSwapParams:n,fetchAaveSwapQuotes:s,withdrawAmountD18:o,slippage:a})=>Promise.all((t??[]).map(async i=>{if(!l(i,e))return{asset:i};try{const c=await n({withdrawAmountD18:o,slippage:a});if(c?.srcData.length){const A=await s({swapParams:c,slippage:a});return{asset:i,swapParams:c,swapQuotes:A}}return{asset:i}}catch(c){return console.error(c),{asset:i}}})),f=t=>Math.round(t*100)/100,Wt=({maxSlippage:t,candidates:e=r.SLIPPAGE_AUTO_SIMULATION_CANDIDATES})=>{if(!Number.isFinite(t)||t<=0)return[];const n=f(Math.min(t,100)),s=e.filter(a=>a>0&&a<=n).map(f),o=new Set(s);return o.add(n),o.add(t),Array.from(o).sort((a,i)=>a-i)},w=1000000000000000000n,Gt=1000000n,b=10000n,R=100n,S=t=>{if(!t)throw new Error("Ondo: empty hex value");return t.startsWith("0x")?t:`0x${t}`},m=(t,e)=>{try{return BigInt(t)}catch{throw new Error(`Ondo: cannot convert "${e}" value "${t}" to bigint`)}},C=t=>t?p.pad(S(t),{size:32}):p.zeroHash,k=t=>{if(!t)throw new Error("Ondo: empty signature");return p.bytesToHex(Uint8Array.from(atob(t),e=>e.charCodeAt(0)))},$t=t=>({quotes:t.quotes.map(e=>({chainId:m(e.chainId,"chainId"),attestationId:m(e.attestationId,"attestationId"),userId:S(e.userId),asset:e.asset,price:m(e.price,"price"),quantity:m(e.quantity,"quantity"),expiration:m(e.expiration,"expiration"),side:Number(e.side),additionalData:S(e.additionalData)})),signatures:t.signatures.map(S)}),Ht=(t,e,n)=>{const s=BigInt(Math.max(0,Math.round(n*100))),o=s>R?R:s,a=b-o,d=t*e/w*a*Gt,c=b*w;return(d+c-1n)/c},Vt=({attestation:t,chainId:e,slippagePercent:n})=>{const s=m(t.tokenAmount,"tokenAmount"),o=m(t.price,"price");return p.encodeAbiParameters(j,[{attestationSignature:k(t.signature),quote:{chainId:e,attestationId:m(t.attestationId,"attestationId"),userId:C(t.userId),asset:t.assetAddress,price:o,quantity:s,expiration:m(t.expiration,"expiration"),side:Number(t.side),additionalData:C(t.additionalData)},amountOutMinimum:Ht(s,o,n)}])};exports.EMPTY_PER_ASSET_WITHDRAW_DATA=xt;exports.HYPERLIQUID_PERPS_ACCOUNT_ADDRESS=V;exports.OndoGMTokenAssetGuardAbi=z;exports.addTokenToWallet=tt;exports.base64SignatureToHex=k;exports.buildAaveWithdrawAssetTransactionData=M;exports.buildComplexAssetDataForRouter=Y;exports.buildSwapQuoteKeyForAave=B;exports.buildSwapWithdrawTransactionData=At;exports.buildZapDepositTransactionArguments=ut;exports.clientSide=Q;exports.commify=_t;exports.createDefaultComplexAssetData=Ft;exports.encodeOndoWithdrawData=Vt;exports.enrichAssetsWithSwapQuotes=vt;exports.extractAvailableRouterKeys=q;exports.formatBalance=G;exports.formatByCurrency=It;exports.formatNumberToLimitedDecimals=v;exports.formatNumeratorToPercentage=Et;exports.formatPercentage=W;exports.formatToUsd=U;exports.formatTokenBalance=ht;exports.getAutoSlippageSimulationCandidates=Wt;exports.getContractAbiById=nt;exports.getContractAddressById=O;exports.getConventionalTokenPriceDecimals=at;exports.getErrorKey=_;exports.getFlatMoneyCollateralByLeverageAddress=bt;exports.getFlatMoneyLinkByUnitAddress=Rt;exports.getGmxWithdrawAssetByLeverageAddress=Bt;exports.getGmxWithdrawAssetByVaultAddress=Lt;exports.getHyperliquidWithdrawAsset=Mt;exports.getNativeTokenInvestableBalance=mt;exports.getPercent=L;exports.getPoolFraction=ct;exports.getSlippageToleranceForContractTransaction=P;exports.getTxHashShort=Nt;exports.isAaveLendAndBorrowAsset=rt;exports.isEqualAddress=l;exports.isFlatMoneyLeveragedAsset=wt;exports.isFmpAirdropVaultAddress=ft;exports.isGmxLeveragedAsset=Ot;exports.isHyperliquidPerpsAsset=Pt;exports.isNativeToken=lt;exports.isNumberType=St;exports.isNumeric=F;exports.isStableSymbol=pt;exports.isZeroAddress=et;exports.logTransactionByActionType=Ct;exports.mapOndoApiResponseToUpdatePricesArgs=$t;exports.nonZeroBigInt=Dt;exports.normalizeNumber=x;exports.overlayWithdrawData=I;exports.parseAmountToD18=dt;exports.parseContractErrorMessage=yt;exports.removeInsignificantTrailingZeros=E;exports.shiftBy=it;exports.shortenAddress=st;exports.sliceByIndex=ot;exports.transformAddressForAnalytics=H;exports.truncateString=$;exports.tryEstimateWithRouters=K;exports.tryEstimateWithSlippageValues=Ut;exports.validateLoggerEventParams=gt;