@dhedge/trading-widget 6.0.6 → 6.1.1

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.
Files changed (51) hide show
  1. package/const.cjs +1 -1
  2. package/const.js +94 -89
  3. package/core-kit/abi/dytm-office-asset-guard.d.ts +194 -0
  4. package/core-kit/abi/index.d.ts +1 -0
  5. package/core-kit/abi/ondo-gm-token-asset-guard.d.ts +20 -0
  6. package/core-kit/abi/ondo-price-oracle.d.ts +18 -0
  7. package/core-kit/const/index.d.ts +1 -0
  8. package/core-kit/const/midas.d.ts +2 -0
  9. package/core-kit/const/trading.d.ts +3 -0
  10. package/core-kit/hooks/pool/index.d.ts +4 -0
  11. package/core-kit/hooks/pool/use-asset-guard-address.d.ts +8 -0
  12. package/core-kit/hooks/pool/use-dytm-vault-data.d.ts +8 -0
  13. package/core-kit/hooks/pool/use-ondo-price-deviation.d.ts +10 -0
  14. package/core-kit/hooks/pool/use-ondo-vault-data.d.ts +1 -0
  15. package/core-kit/hooks/pool/use-pool-assets-with-type.d.ts +14 -0
  16. package/core-kit/hooks/trading/deposit-v2/deposit-transaction/use-ondo-price-freshness.d.ts +4 -4
  17. package/core-kit/hooks/trading/withdraw-v2/init-step/use-fetch-dytm-withdraw-asset-data.d.ts +3 -0
  18. package/core-kit/hooks/trading/withdraw-v2/init-step/use-fetch-ondo-withdraw-asset-data.d.ts +3 -2
  19. package/core-kit/hooks/trading/withdraw-v2/init-step/use-init-withdraw-simulation-withdraw-data.d.ts +7 -0
  20. package/core-kit/services/ondo/api.d.ts +5 -1
  21. package/core-kit/services/ondo/index.d.ts +2 -2
  22. package/core-kit/services/ondo/types.d.ts +9 -0
  23. package/core-kit/utils/complex-withdraw-asset-data.d.ts +9 -5
  24. package/core-kit/utils/dytm.d.ts +51 -0
  25. package/core-kit/utils/index.d.ts +1 -0
  26. package/core-kit/utils/ondo.d.ts +2 -1
  27. package/core-kit/utils/web3.d.ts +5 -1
  28. package/dytm-CQG65-Rc.cjs +1 -0
  29. package/dytm-CWhBYz0P.js +784 -0
  30. package/{geoblocking-NkujbQRm.js → geoblocking-DtB4yr5l.js} +10 -8
  31. package/geoblocking-peuNwHMJ.cjs +1 -0
  32. package/gmx-U3Bnivj2.cjs +1 -0
  33. package/{gmx-DQ-wSifY.js → gmx-c42QlKyJ.js} +389 -369
  34. package/index.cjs +1 -1
  35. package/index.d.ts +1 -1
  36. package/index.js +4276 -3682
  37. package/package.json +1 -1
  38. package/trading-widget/components/widget/widget-input/all-assets-composition-table/all-assets-composition-table.hooks.d.ts +2 -0
  39. package/trading-widget/components/widget/widget-overlay/withdraw-stepper-overlay/steps/init-withdraw-step.hooks.d.ts +1 -1
  40. package/trading-widget/components/widget/widget-overlay/withdraw-stepper-overlay/steps/oracle-update-step.d.ts +3 -0
  41. package/trading-widget/components/widget/widget-overlay/withdraw-stepper-overlay/steps/oracle-update-step.hooks.d.ts +11 -0
  42. package/trading-widget/components/widget/widget-overlay/withdraw-stepper-overlay/withdraw-stepper-overlay.hooks.d.ts +10 -2
  43. package/trading-widget/components/widget/widget-overlay/withdraw-stepper-overlay/withdraw-steps.d.ts +2 -9
  44. package/trading-widget/components/widget/widget-overlay/withdraw-stepper-overlay/withdraw-steps.hooks.d.ts +26 -0
  45. package/utils.cjs +1 -1
  46. package/utils.js +67 -58
  47. package/core-kit/hooks/trading/withdraw-v2/init-step/use-init-withdraw-estimated-receive-assets.d.ts +0 -235
  48. package/geoblocking-9FD_O0-h.cjs +0 -1
  49. package/gmx-Dejxb5_t.cjs +0 -1
  50. package/ondo-GwhTVXds.js +0 -540
  51. package/ondo-rQybmFLf.cjs +0 -1
@@ -3,8 +3,12 @@ import type { useFetchAaveSwapParams } from '../hooks/trading/withdraw-v2/init-s
3
3
  import type { useFetchInitWithdrawAaveSwapQuotes } from '../hooks/trading/withdraw-v2/init-step/use-fetch-init-withdraw-aave-swap-quotes';
4
4
  import type { CalculateSwapDataParamsResponse, ComplexWithdrawAssetData, EstimateCall, Hex } from '../types';
5
5
  import type { SwapsQuotesMap } from '../utils/swap-data';
6
- export declare const EMPTY_PER_ASSET_WITHDRAW_DATA: Map<string, Hex>;
7
- export declare const overlayWithdrawData: (complexAssetData: ComplexWithdrawAssetData[], perAssetWithdrawData: Map<string, Hex> | undefined) => ComplexWithdrawAssetData[];
6
+ export interface WithdrawDataOverride {
7
+ withdrawData: Hex;
8
+ slippageTolerance: bigint;
9
+ }
10
+ export declare const EMPTY_PER_ASSET_WITHDRAW_DATA: Map<string, WithdrawDataOverride>;
11
+ export declare const overlayWithdrawData: (complexAssetData: ComplexWithdrawAssetData[], perAssetWithdrawData: Map<string, WithdrawDataOverride> | undefined) => ComplexWithdrawAssetData[];
8
12
  type VaultAssetWithSwapQuotes = {
9
13
  asset: Address;
10
14
  swapParams?: CalculateSwapDataParamsResponse;
@@ -18,13 +22,13 @@ interface EnrichAssetParams {
18
22
  }
19
23
  export declare const extractAvailableRouterKeys: (vaultAssetsWithSwapQuotes: VaultAssetWithSwapQuotes[]) => Array<SwapDataResponse['routerKey']>;
20
24
  export declare const buildComplexAssetDataForRouter: (vaultAssetsWithSwapQuotes: VaultAssetWithSwapQuotes[], routerKey: SwapDataResponse['routerKey'], slippageTolerance: bigint) => ComplexWithdrawAssetData[];
21
- export declare const tryEstimateWithRouters: (availableRouterKeys: Array<SwapDataResponse['routerKey']>, vaultAssetsWithSwapQuotes: VaultAssetWithSwapQuotes[], slippageTolerance: bigint, estimate: EstimateCall, transactionArgs: unknown[], perAssetWithdrawData?: Map<string, Hex>) => Promise<ComplexWithdrawAssetData[] | null>;
22
- export declare const createDefaultComplexAssetData: (supportedVaultAssets: Address[] | undefined, slippageTolerance: bigint, perAssetWithdrawData: Map<string, Hex>) => ComplexWithdrawAssetData[];
25
+ export declare const tryEstimateWithRouters: (availableRouterKeys: Array<SwapDataResponse['routerKey']>, vaultAssetsWithSwapQuotes: VaultAssetWithSwapQuotes[], slippageTolerance: bigint, estimate: EstimateCall, transactionArgs: unknown[], perAssetWithdrawData?: Map<string, WithdrawDataOverride>) => Promise<ComplexWithdrawAssetData[] | null>;
26
+ export declare const createDefaultComplexAssetData: (supportedVaultAssets: Address[] | undefined, slippageTolerance: bigint, perAssetWithdrawData: Map<string, WithdrawDataOverride>) => ComplexWithdrawAssetData[];
23
27
  /**
24
28
  * Tries slippage candidates from lowest to highest.
25
29
  * For each candidate, re-fetches swap quotes at that slippage, then tries all routers.
26
30
  * Returns the first complexAssetData that passes estimation, or null if all candidates fail.
27
31
  */
28
- export declare const tryEstimateWithSlippageValues: (slippageCandidates: number[], fetchQuotesForSlippage: (candidateSlippage: number) => Promise<VaultAssetWithSwapQuotes[]>, estimate: EstimateCall, transactionArgs: unknown[], perAssetWithdrawData?: Map<string, Hex>) => Promise<ComplexWithdrawAssetData[] | null>;
32
+ export declare const tryEstimateWithSlippageValues: (slippageCandidates: number[], fetchQuotesForSlippage: (candidateSlippage: number) => Promise<VaultAssetWithSwapQuotes[]>, estimate: EstimateCall, transactionArgs: unknown[], perAssetWithdrawData?: Map<string, WithdrawDataOverride>) => Promise<ComplexWithdrawAssetData[] | null>;
29
33
  export declare const enrichAssetsWithSwapQuotes: (supportedVaultAssets: Address[] | undefined, aaveLendingPoolV3Address: Address, { fetchAaveSwapParams, fetchAaveSwapQuotes, withdrawAmountD18, slippage, }: EnrichAssetParams) => Promise<VaultAssetWithSwapQuotes[]>;
30
34
  export {};
@@ -0,0 +1,51 @@
1
+ import type { Address, Hex } from '../types/web3.types';
2
+ import type { OndoPriceOracleQuote } from '../utils/ondo';
3
+ export interface DytmAssetData {
4
+ asset: Address;
5
+ amount: bigint;
6
+ assetType: number;
7
+ isPool: boolean;
8
+ isDebt: boolean;
9
+ marketId: bigint;
10
+ accountId: bigint;
11
+ tokenId: bigint;
12
+ debtKey: bigint;
13
+ shares: bigint;
14
+ }
15
+ export interface DytmAccountGroup {
16
+ accountId: bigint;
17
+ marketId: bigint;
18
+ collaterals: DytmAssetData[];
19
+ debt?: DytmAssetData;
20
+ }
21
+ export interface DytmAction {
22
+ to: Address;
23
+ data: Hex;
24
+ }
25
+ export declare const groupPreviewByAccount: (assetData: readonly DytmAssetData[]) => DytmAccountGroup[];
26
+ export interface BuildDytmActionsParams {
27
+ collateral: DytmAssetData;
28
+ dytmOffice: Address;
29
+ processor: Address;
30
+ gmToken: Address;
31
+ ondoGMSwap: Address;
32
+ usdc: Address;
33
+ gmAmount: bigint;
34
+ amountOutMinimum: bigint;
35
+ signature: Hex;
36
+ quote: OndoPriceOracleQuote;
37
+ }
38
+ export declare const buildDytmActions: ({ collateral, dytmOffice, processor, gmToken, ondoGMSwap, usdc, gmAmount, amountOutMinimum, signature, quote, }: BuildDytmActionsParams) => DytmAction[];
39
+ export interface BuildDytmRepayActionsParams {
40
+ accountId: bigint;
41
+ debtKey: bigint;
42
+ dytmOffice: Address;
43
+ usdc: Address;
44
+ }
45
+ export declare const buildDytmRepayActions: ({ accountId, debtKey, dytmOffice, usdc, }: BuildDytmRepayActionsParams) => DytmAction[];
46
+ export interface EncodeUnwindPlanParams {
47
+ actions: DytmAction[];
48
+ outputAsset: Address;
49
+ minOutputAmount: bigint;
50
+ }
51
+ export declare const encodeUnwindPlan: ({ actions, outputAsset, minOutputAmount, }: EncodeUnwindPlanParams) => Hex;
@@ -15,3 +15,4 @@ export * from '../utils/hyperliquid';
15
15
  export * from '../utils/complex-withdraw-asset-data';
16
16
  export * from '../utils/slippage-auto-simulation';
17
17
  export * from '../utils/ondo';
18
+ export * from '../utils/dytm';
@@ -1,6 +1,5 @@
1
1
  import type { OndoAttestationApiResponse, OndoPriceUpdateApiResponse } from '../services/ondo/types';
2
2
  import type { Address, Hex } from '../types/web3.types';
3
- export declare const base64SignatureToHex: (b64: string) => Hex;
4
3
  export interface OndoPriceOracleQuote {
5
4
  chainId: bigint;
6
5
  attestationId: bigint;
@@ -22,4 +21,6 @@ export interface EncodeOndoWithdrawDataParams {
22
21
  chainId: bigint;
23
22
  slippagePercent: number;
24
23
  }
24
+ export declare const computeAmountOutMinimumUsdc: (quantity: bigint, price: bigint, slippagePercent: number) => bigint;
25
+ export declare const mapAttestationToOndoQuote: (attestation: OndoAttestationApiResponse, chainId: bigint) => OndoPriceOracleQuote;
25
26
  export declare const encodeOndoWithdrawData: ({ attestation, chainId, slippagePercent, }: EncodeOndoWithdrawDataParams) => Hex;
@@ -1,6 +1,10 @@
1
1
  import type { ContractId } from '../const';
2
- import type { Address, ChainId } from '../types/web3.types';
2
+ import type { Address, ChainId, Hex } from '../types/web3.types';
3
3
  export { formatUnits, formatEther, encodeFunctionData, decodeErrorResult, hexToString, trim, } from 'viem';
4
+ export declare const ensureHexPrefix: (value: string) => Hex;
5
+ export declare const toBigInt: (value: string | number, field: string) => bigint;
6
+ export declare const toBytes32Hex: (value: string) => Hex;
7
+ export declare const base64ToHex: (value: string) => Hex;
4
8
  export declare const getContractAddressById: (contractId: ContractId, chainId: ChainId) => Address;
5
9
  export declare const getContractAbiById: (contractId: ContractId) => any;
6
10
  export declare const shortenAddress: (address: string) => string;
@@ -0,0 +1 @@
1
+ "use strict";const y=require("wagmi/chains"),o=require("./gmx-U3Bnivj2.cjs"),p=require("bignumber.js"),d=require("viem"),X=typeof window<"u",J=[{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"}],tt=[{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"}]}],et=[{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"}],nt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewWithdrawal",outputs:[{name:"assetData",type:"tuple[]",components:et}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"dytmWithdrawProcessor",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],B=[{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"}],at=[{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"}],st=[{type:"tuple",components:[{name:"actions",type:"tuple[]",components:[{name:"to",type:"address"},{name:"data",type:"bytes"}]},{name:"outputAsset",type:"address"},{name:"minOutputAmount",type:"uint256"}]}],ot=()=>typeof window<"u";function rt(){return ot()&&typeof window.ethereum<"u"}async function it(t){try{if(rt())return window.ethereum.request({method:"wallet_watchAsset",params:{type:"ERC20",options:t}})}catch{return!1}return!1}const A=(t,e)=>t?.toLowerCase()===e?.toLowerCase(),ut=t=>A(t,o.AddressZero$1),D=t=>{if(!t)throw new Error("Cannot prefix an empty hex value");return t.startsWith("0x")?t:`0x${t}`},l=(t,e)=>{try{return BigInt(t)}catch{throw new Error(`Cannot convert "${e}" value "${t}" to bigint`)}},E=t=>t?d.pad(D(t),{size:32}):d.zeroHash,O=t=>{if(!t)throw new Error("Cannot decode an empty base64 string");return d.bytesToHex(Uint8Array.from(atob(t),e=>e.charCodeAt(0)))},M=(t,e)=>o.contractsAddressesMap[e]?.[t]??o.AddressZero,ct=t=>o.contractsAbisMap[t],dt=t=>t&&`${t.substring(0,6)}...${t.substring(t.length-4,t.length)}`,pt=({address:t,chainId:e})=>{const n=M("aaveLendingPoolV3",e);return A(t,n)},P=({sourceAddress:t,amount:e})=>`${t}_${e}`,mt=(t,e)=>{const n=t.slice(0,e),a=t.slice(e);return{firstPart:n,secondPart:a}},L=(t,e)=>t/e*100,lt=t=>t<1?4:t<10?3:2,At=(t,e=o.DEFAULT_PRECISION)=>new p(t.toString()).shiftedBy(e).toFixed(0),yt=(t,e,n,a)=>new p(e).dividedBy(n).multipliedBy(t).shiftedBy(-(a||o.DEFAULT_PRECISION)).toNumber(),Tt=t=>BigInt(new p(t||"0").shiftedBy(o.DEFAULT_PRECISION).toFixed(0,p.ROUND_DOWN)),x=t=>{const e=new p(.01),n=new p(t),a=!n.isZero()&&n.lt(e)?e:n;return BigInt(a.multipliedBy(100).toFixed(0))},gt=({vaultAddress:t,swapData:e,sendTokenAddress:n,sendTokenAmount:a,vaultDepositTokenAddress:s,minVaultTokensReceivedAmount:r,routerKey:i="ONE_INCH",swapDestinationAmount:c,swapSlippage:u})=>{const m=new p(c).multipliedBy(1-u/100).toFixed(0),T=[d.stringToHex(i,{size:32}),e];return[t,[[n,a,T],[s,m]],r]},Dt=({receiveAssetAddress:t,assets:e,swapData:n,slippage:a})=>{const s={srcData:[],destAmount:new p("0")},{srcData:r,destAmount:i}=e?.reduce((c,u)=>{const m=n?.[u.address];if(!m)return c;const T=[d.stringToHex(m.routerKey,{size:32}),m.rawTransaction.data],g=[u.address,u.rawBalance,T];return{srcData:[...c.srcData,g],destAmount:c.destAmount.plus(m.destinationAmount)}},s)??s;return[r,[t,i.times(1-a/100).toFixed(0,p.ROUND_DOWN)]]},v=({assetAddress:t,swapQuotes:e,swapParams:n,slippageToleranceForContractTransaction:a,routerKey:s})=>{if(!n)return{supportedAsset:t,withdrawData:"",slippageTolerance:BigInt(0)};const{srcData:r,dstData:i}=n,c=r.map(({asset:T,amount:g})=>{const S=e?.[P({sourceAddress:T,amount:g.toString()})]?.find(j=>j.routerKey===s);return{asset:T,amount:g,swapData:{routerKey:d.stringToHex(S?.routerKey??"",{size:32}),txData:S?.rawTransaction.data??"0x"}}}),u=d.encodeAbiParameters(o.ComplexWithdrawalAssetSrcDataAbiItem,[c]),m=d.encodeAbiParameters(o.ComplexWithdrawalDataAbiItem,[{encodedSrcData:u,dstData:{dstAddress:i.asset,dstAmount:i.amount},slippage:a}]);return{supportedAsset:t,withdrawData:m,slippageTolerance:a}},St=({chainId:t,txHash:e,error:n})=>{if(t!==y.mainnet.id||!e||!n)return!1;const a=n instanceof Error?n.message:String(n);return/\bNo Result\b/i.test(a)},Et=({chainId:t,action:e,isRabbyWallet:n})=>e==="update_ondo_prices"&&t===y.mainnet.id&&n?o.ONDO_PRICES_RABBY_SETTLE_DELAY:t?o.TRANSACTION_SETTLE_DELAY[t]??0:0,_t=(t,e)=>o.CHAIN_NATIVE_TOKENS[e]?.nativeTokenSymbol===t,ft=({nativeTokenBalance:t,tokenDecimals:e,gasPrice:n})=>{const a=new p(n).multipliedBy(o.NATIVE_TOKEN_GAS_RESERVE_UNITS).shiftedBy(-e),s=new p(t).minus(a);return s.gt("0")?s:new p("0")},bt=t=>o.STABLE_TOKEN_SYMBOLS.includes(t),wt=t=>{const e=Object.values(t).reduce((n,{type:a})=>(n[a]=n[a]+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},ht=(t,e=150)=>t.length>e?t.substring(0,e):t,_=(t,e=o.TRANSACTION_ERROR_KEYS)=>{const n=t.toLowerCase();return e.sort((a,s)=>s.length-a.length).find(a=>n.includes(a.toLowerCase()))},w=t=>o.TRANSACTION_ERRORS[t]??o.LIMIT_ORDER_TRANSACTION_ERRORS[t],It=({errorMessage:t,abiErrors:e})=>{if(!t||t.includes("User rejected"))return null;const n=e.find(r=>t.includes(r));if(n&&_(n))return w(n);const a=_(t);if(a)return w(a);const[s]=t.split(n?".":"Contract").map(r=>r.trim());return{title:"Transaction failed",hint:`${ht(s??"")} ${n?`: ${n}`:""}`}},Nt=t=>typeof t=="number"&&Number.isFinite(t),Rt=t=>typeof t=="bigint"&&t!==BigInt(0),F=(t,e=o.DEFAULT_PRECISION$1)=>new p(t).shiftedBy(-e).toNumber(),U=t=>!isNaN(parseFloat(t))&&!isNaN(t),W=({value:t,minimumFractionDigits:e=2,maximumFractionDigits:n=2,compact:a=!1,normalize:s=!1})=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:a?"compact":void 0,minimumFractionDigits:e,maximumFractionDigits:n}).format(s?F(t):Number(t)),f=t=>U(t)?new p(t).toFixed():"",h=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"],G=({value:t,decimals:e=4})=>{const n=new p(t);if(n.isGreaterThan(1)||n.isZero())return f(n.toFixed(e));const s=(/e/i.test(t.toString())?parseFloat(t.toString()).toFixed(o.DEFAULT_PRECISION$1):t.toString()).match(/^0\.(0+)(\d+)$/);if(s){const[,r,i]=s;if(r.length>=e&&r.length<h.length)return`0.0${h[r.length]}${i.slice(0,3)}`}return f(n.toFixed(e))},H=(t,e=0)=>`${t.toLocaleString("en-US",{maximumFractionDigits:e})}%`,Ct=t=>t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),Bt=(t,e,n=0)=>{const a=L(+t,e);return H(a,n)},Ot=({currency:t,value:e})=>t==="USD"?W({value:e}):`${o.CURRENCY_SYMBOL_MAP[t]} ${G({value:e,decimals:o.CURRENCY_DECIMALS_MAP[t]})}`,$=(t,e)=>new p(new p(t).toFixed(e,p.ROUND_DOWN)).toString(),k=(t,e=3,n=2)=>{if(t.length<=5)return t;const a="...";return t.length<=e+n+a.length?t:`${t.slice(0,e)}${a}${t.slice(-n)}`},Mt=({balance:t,symbol:e,precision:n,truncateSymbol:a})=>`${$(t,n)} ${a?k(e):e}`,Pt=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)}`},Lt=t=>A(o.FLATMONEY_EARLY_DEPOSITOR_VAULT_ADDRESS_BASE,t)||A(o.FLATMONEY_DHT_STAKING_VAULT_ADDRESS_BASE,t),xt=t=>o.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES.some(e=>A(e,t)),vt=t=>o.FLAT_MONEY_COLLATERAL_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:o.AddressZero},Ft=t=>A(t,o.FLAT_MONEY_V1_UNIT_ADDRESS)?o.FLAT_MONEY_V1_UNIT_LINK:o.FLAT_MONEY_UNIT_LINK,V=t=>`eth_${t}`,Ut=({action:t,log:e,symbol:n,vaultAddress:a,chainId:s})=>{const r={[o.TRADING_LOG_EVENT_PARAM.SYMBOL.NAME]:n,[o.TRADING_LOG_EVENT_PARAM.CHAIN_ID.NAME]:s,[o.TRADING_LOG_EVENT_PARAM.ADDRESS.NAME]:V(a)};o.LOG_EVENT_BY_TRANSACTION_ACTION_MAP[t].forEach(i=>{e?.(i,r)})},Wt=t=>o.GMX_MARKET_ASSETS.some(e=>A(e,t)),Gt=t=>o.GMX_WITHDRAW_ASSET_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:o.AddressZero},Ht=t=>o.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS[t.toLowerCase()],q="0x3333333333333333333333333333333333333333";y.arbitrum.id+"",o.USDC_ARBITRUM.address,y.base.id+"",o.USDC_BASE.address,y.optimism.id+"",o.USDC_OPTIMISM.address,y.polygon.id+"",o.USDC_POLYGON.address,y.mainnet.id+"",o.USDC_MAINNET.address,y.hyperEvm.id+"",o.USDC_HYPEREVM.address;const $t=t=>A(t,q),kt=()=>o.USDC_HYPEREVM,Vt=new Map,b=(t,e)=>!e||e.size===0?t:t.map(n=>{const a=e.get(n.supportedAsset.toLowerCase());return a?{...n,withdrawData:a.withdrawData,slippageTolerance:a.slippageTolerance}:n}),Y=t=>{const e=t.find(({swapQuotes:n})=>n);return e?.swapQuotes?Object.values(e.swapQuotes)[0]?.map(({routerKey:n})=>n)??[]:[]},K=(t,e,n)=>t.map(({asset:a,swapParams:s,swapQuotes:r})=>!s||!r?{supportedAsset:a,withdrawData:"",slippageTolerance:n}:v({assetAddress:a,swapQuotes:r,swapParams:s,slippageToleranceForContractTransaction:n,routerKey:e})),Z=async(t,e,n,a,s,r)=>{for(const i of t){const c=b(K(e,i,n),r),{error:u}=await a(...s,c);if(!u)return c}return null},qt=(t,e,n)=>{const a=(t??[]).map(s=>({supportedAsset:s,withdrawData:"",slippageTolerance:e}));return b(a,n)},Yt=async(t,e,n,a,s)=>{for(const r of t){const i=x(r);try{const c=await e(r),u=Y(c),m=await Z(u,c,i,n,a,s);if(m)return console.debug(`[Init Withdraw] Auto slippage simulation succeeded: slippage=${r}%`),console.debug("[Init Withdraw] Complex asset data:",m),m}catch(c){console.error(`[Init Withdraw] Failed to fetch quotes for slippage=${r}%:`,c)}}return null},Kt=async(t,e,{fetchAaveSwapParams:n,fetchAaveSwapQuotes:a,withdrawAmountD18:s,slippage:r})=>Promise.all((t??[]).map(async i=>{if(!A(i,e))return{asset:i};try{const u=await n({withdrawAmountD18:s,slippage:r});if(u?.srcData.length){const m=await a({swapParams:u,slippage:r});return{asset:i,swapParams:u,swapQuotes:m}}return{asset:i}}catch(u){return console.error(u),{asset:i}}})),I=t=>Math.round(t*100)/100,Zt=({maxSlippage:t,candidates:e=o.SLIPPAGE_AUTO_SIMULATION_CANDIDATES})=>{if(!Number.isFinite(t)||t<=0)return[];const n=I(Math.min(t,100)),a=e.filter(r=>r>0&&r<=n).map(I),s=new Set(a);return s.add(n),s.add(t),Array.from(s).sort((r,i)=>r-i)},N=1000000000000000000n,Qt=1000000n,R=10000n,C=100n,zt=t=>({quotes:t.quotes.map(e=>({chainId:l(e.chainId,"chainId"),attestationId:l(e.attestationId,"attestationId"),userId:D(e.userId),asset:e.asset,price:l(e.price,"price"),quantity:l(e.quantity,"quantity"),expiration:l(e.expiration,"expiration"),side:Number(e.side),additionalData:D(e.additionalData)})),signatures:t.signatures.map(D)}),Q=(t,e,n)=>{const a=BigInt(Math.max(0,Math.round(n*100))),s=a>C?C:a,r=R-s,c=t*e/N*r*Qt,u=R*N;return(c+u-1n)/u},z=(t,e)=>({chainId:e,attestationId:l(t.attestationId,"attestationId"),userId:E(t.userId),asset:t.assetAddress,price:l(t.price,"price"),quantity:l(t.tokenAmount,"tokenAmount"),expiration:l(t.expiration,"expiration"),side:Number(t.side),additionalData:E(t.additionalData)}),jt=({attestation:t,chainId:e,slippagePercent:n})=>{const a=z(t,e);return d.encodeAbiParameters(tt,[{attestationSignature:O(t.signature),quote:a,amountOutMinimum:Q(a.quantity,a.price,n)}])},Xt=t=>[...t.reduce((n,a)=>n.has(a.accountId)?n:n.set(a.accountId,a),new Map).values()].map(({accountId:n,marketId:a})=>({accountId:n,marketId:a,collaterals:t.filter(s=>s.accountId===n&&!s.isDebt),debt:t.find(s=>s.accountId===n&&s.isDebt)})),Jt=({collateral:t,dytmOffice:e,processor:n,gmToken:a,ondoGMSwap:s,usdc:r,gmAmount:i,amountOutMinimum:c,signature:u,quote:m})=>[{to:e,data:d.encodeFunctionData({abi:B,functionName:"withdraw",args:[{account:t.accountId,tokenId:t.tokenId,receiver:n,assets:i,shares:0n,extraData:"0x"}]})},{to:a,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[s,i]})},{to:s,data:d.encodeFunctionData({abi:at,functionName:"swapExactInWithAttestation",args:[a,i,r,c,u,m]})}],te=({accountId:t,debtKey:e,dytmOffice:n,usdc:a})=>[{to:a,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[n,d.maxUint256]})},{to:n,data:d.encodeFunctionData({abi:B,functionName:"repay",args:[{account:t,key:e,withCollateralType:0,assets:d.maxUint256,shares:0n,extraData:"0x"}]})}],ee=({actions:t,outputAsset:e,minOutputAmount:n})=>d.encodeAbiParameters(st,[{actions:t,outputAsset:e,minOutputAmount:n}]);exports.DytmOfficeAssetGuardAbi=nt;exports.EMPTY_PER_ASSET_WITHDRAW_DATA=Vt;exports.HYPERLIQUID_PERPS_ACCOUNT_ADDRESS=q;exports.OndoGMTokenAssetGuardAbi=J;exports.addTokenToWallet=it;exports.base64ToHex=O;exports.buildAaveWithdrawAssetTransactionData=v;exports.buildComplexAssetDataForRouter=K;exports.buildDytmActions=Jt;exports.buildDytmRepayActions=te;exports.buildSwapQuoteKeyForAave=P;exports.buildSwapWithdrawTransactionData=Dt;exports.buildZapDepositTransactionArguments=gt;exports.clientSide=X;exports.commify=Ct;exports.computeAmountOutMinimumUsdc=Q;exports.createDefaultComplexAssetData=qt;exports.encodeOndoWithdrawData=jt;exports.encodeUnwindPlan=ee;exports.enrichAssetsWithSwapQuotes=Kt;exports.ensureHexPrefix=D;exports.extractAvailableRouterKeys=Y;exports.formatBalance=$;exports.formatByCurrency=Ot;exports.formatNumberToLimitedDecimals=G;exports.formatNumeratorToPercentage=Bt;exports.formatPercentage=H;exports.formatToUsd=W;exports.formatTokenBalance=Mt;exports.getAutoSlippageSimulationCandidates=Zt;exports.getContractAbiById=ct;exports.getContractAddressById=M;exports.getConventionalTokenPriceDecimals=lt;exports.getErrorKey=_;exports.getFlatMoneyCollateralByLeverageAddress=vt;exports.getFlatMoneyLinkByUnitAddress=Ft;exports.getGmxWithdrawAssetByLeverageAddress=Gt;exports.getGmxWithdrawAssetByVaultAddress=Ht;exports.getHyperliquidWithdrawAsset=kt;exports.getNativeTokenInvestableBalance=ft;exports.getPercent=L;exports.getPoolFraction=yt;exports.getSettleDelay=Et;exports.getSlippageToleranceForContractTransaction=x;exports.getTxHashShort=Pt;exports.groupPreviewByAccount=Xt;exports.isAaveLendAndBorrowAsset=pt;exports.isEqualAddress=A;exports.isFlatMoneyLeveragedAsset=xt;exports.isFmpAirdropVaultAddress=Lt;exports.isGmxLeveragedAsset=Wt;exports.isHyperliquidPerpsAsset=$t;exports.isNativeToken=_t;exports.isNumberType=Nt;exports.isNumeric=U;exports.isStableSymbol=bt;exports.isZeroAddress=ut;exports.logTransactionByActionType=Ut;exports.mapAttestationToOndoQuote=z;exports.mapOndoApiResponseToUpdatePricesArgs=zt;exports.nonZeroBigInt=Rt;exports.normalizeNumber=F;exports.overlayWithdrawData=b;exports.parseAmountToD18=Tt;exports.parseContractErrorMessage=It;exports.removeInsignificantTrailingZeros=f;exports.shiftBy=At;exports.shortenAddress=dt;exports.shouldSwallowMainnetPollError=St;exports.sliceByIndex=mt;exports.toBigInt=l;exports.toBytes32Hex=E;exports.transformAddressForAnalytics=V;exports.truncateString=k;exports.tryEstimateWithRouters=Z;exports.tryEstimateWithSlippageValues=Yt;exports.validateLoggerEventParams=wt;