@dhedge/trading-widget 6.3.3 → 6.3.6
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-CbE2J5kb.js → contract-error-log-C72hcInG.js} +356 -349
- package/contract-error-log-xoZ1OAil.cjs +1 -0
- package/core-kit/hooks/trading/withdraw-v2/init-step/use-init-withdraw-simulation-withdraw-data.d.ts +4 -1
- package/core-kit/utils/number.d.ts +1 -0
- package/core-kit/utils/ondo.d.ts +2 -0
- package/index.cjs +1 -1
- package/index.js +3791 -3755
- package/limit-orders/common/utils.d.ts +0 -1
- package/package.json +1 -1
- package/utils.cjs +1 -1
- package/utils.js +73 -70
- package/contract-error-log-CNIRNvc6.cjs +0 -1
package/package.json
CHANGED
package/utils.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./contract-error-log-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./contract-error-log-xoZ1OAil.cjs"),t=require("viem");exports.EMPTY_PER_ASSET_WITHDRAW_DATA=e.EMPTY_PER_ASSET_WITHDRAW_DATA;exports.MIN_GM_UNWIND_VALUE_USD=e.MIN_GM_UNWIND_VALUE_USD;exports.THIRD_PARTY_CONTRACT_ERRORS=e.THIRD_PARTY_CONTRACT_ERRORS;exports.applyContractErrorRegistry=e.applyContractErrorRegistry;exports.base64ToHex=e.base64ToHex;exports.buildAaveWithdrawAssetTransactionData=e.buildAaveWithdrawAssetTransactionData;exports.buildComplexAssetDataForRouter=e.buildComplexAssetDataForRouter;exports.buildDytmActions=e.buildDytmActions;exports.buildDytmOutputAssetWithdrawAction=e.buildDytmOutputAssetWithdrawAction;exports.buildDytmRepayActions=e.buildDytmRepayActions;exports.buildSwapQuoteKeyForAave=e.buildSwapQuoteKeyForAave;exports.buildSwapWithdrawTransactionData=e.buildSwapWithdrawTransactionData;exports.buildZapDepositTransactionArguments=e.buildZapDepositTransactionArguments;exports.clientSide=e.clientSide;exports.computeAmountOutMinimumUsdc=e.computeAmountOutMinimumUsdc;exports.createDefaultComplexAssetData=e.createDefaultComplexAssetData;exports.encodeOndoWithdrawData=e.encodeOndoWithdrawData;exports.encodeUnwindPlan=e.encodeUnwindPlan;exports.enrichAssetsWithSwapQuotes=e.enrichAssetsWithSwapQuotes;exports.ensureContractErrorRegistryLoaded=e.ensureContractErrorRegistryLoaded;exports.ensureHexPrefix=e.ensureHexPrefix;exports.extractAvailableRouterKeys=e.extractAvailableRouterKeys;exports.fetchContractErrorRegistry=e.fetchContractErrorRegistry;exports.formatBalance=e.formatBalance;exports.formatByCurrency=e.formatByCurrency;exports.formatNumeratorToPercentage=e.formatNumeratorToPercentage;exports.formatTokenBalance=e.formatTokenBalance;exports.getAutoSlippageSimulationCandidates=e.getAutoSlippageSimulationCandidates;exports.getComplexAssetDataSlippageTolerance=e.getComplexAssetDataSlippageTolerance;exports.getContractAbiById=e.getContractAbiById;exports.getContractAddressById=e.getContractAddressById;exports.getContractErrorRegistry=e.getContractErrorRegistry;exports.getConventionalTokenPriceDecimals=e.getConventionalTokenPriceDecimals;exports.getErrorKey=e.getErrorKey;exports.getFlatMoneyCollateralByLeverageAddress=e.getFlatMoneyCollateralByLeverageAddress;exports.getFlatMoneyLinkByUnitAddress=e.getFlatMoneyLinkByUnitAddress;exports.getGmxWithdrawAssetByLeverageAddress=e.getGmxWithdrawAssetByLeverageAddress;exports.getGmxWithdrawAssetByVaultAddress=e.getGmxWithdrawAssetByVaultAddress;exports.getHyperliquidWithdrawAsset=e.getHyperliquidWithdrawAsset;exports.getNativeTokenInvestableBalance=e.getNativeTokenInvestableBalance;exports.getPercent=e.getPercent;exports.getPoolFraction=e.getPoolFraction;exports.getSettleDelay=e.getSettleDelay;exports.getSlippageToleranceForContractTransaction=e.getSlippageToleranceForContractTransaction;exports.getTxHashShort=e.getTxHashShort;exports.groupPreviewByAccount=e.groupPreviewByAccount;exports.isAaveLendAndBorrowAsset=e.isAaveLendAndBorrowAsset;exports.isFlatMoneyLeveragedAsset=e.isFlatMoneyLeveragedAsset;exports.isFmpAirdropVaultAddress=e.isFmpAirdropVaultAddress;exports.isGmxLeveragedAsset=e.isGmxLeveragedAsset;exports.isHyperliquidCorePositionAsset=e.isHyperliquidCorePositionAsset;exports.isHyperliquidPerpsAsset=e.isHyperliquidPerpsAsset;exports.isHyperliquidSpotSystemAsset=e.isHyperliquidSpotSystemAsset;exports.isNativeToken=e.isNativeToken;exports.isPositiveNumber=e.isPositiveNumber;exports.isStableSymbol=e.isStableSymbol;exports.isUnswappableGmDust=e.isUnswappableGmDust;exports.logContractErrorOnce=e.logContractErrorOnce;exports.logTransactionByActionType=e.logTransactionByActionType;exports.mapAttestationToOndoQuote=e.mapAttestationToOndoQuote;exports.mapOndoApiResponseToUpdatePricesArgs=e.mapOndoApiResponseToUpdatePricesArgs;exports.overlayWithdrawData=e.overlayWithdrawData;exports.parseAmountToD18=e.parseAmountToD18;exports.parseContractErrorMessage=e.parseContractErrorMessage;exports.shiftBy=e.shiftBy;exports.shortenAddress=e.shortenAddress;exports.shouldSwallowMainnetPollError=e.shouldSwallowMainnetPollError;exports.sliceByIndex=e.sliceByIndex;exports.toBigInt=e.toBigInt;exports.toBytes32Hex=e.toBytes32Hex;exports.transformAddressForAnalytics=e.transformAddressForAnalytics;exports.truncateString=e.truncateString;exports.tryEstimateWithRouters=e.tryEstimateWithRouters;exports.tryEstimateWithSlippageValues=e.tryEstimateWithSlippageValues;exports.validateLoggerEventParams=e.validateLoggerEventParams;Object.defineProperty(exports,"decodeErrorResult",{enumerable:!0,get:()=>t.decodeErrorResult});Object.defineProperty(exports,"encodeFunctionData",{enumerable:!0,get:()=>t.encodeFunctionData});Object.defineProperty(exports,"formatEther",{enumerable:!0,get:()=>t.formatEther});Object.defineProperty(exports,"formatUnits",{enumerable:!0,get:()=>t.formatUnits});Object.defineProperty(exports,"hexToString",{enumerable:!0,get:()=>t.hexToString});Object.defineProperty(exports,"trim",{enumerable:!0,get:()=>t.trim});
|
package/utils.js
CHANGED
|
@@ -1,82 +1,85 @@
|
|
|
1
|
-
import { E as
|
|
2
|
-
import { decodeErrorResult as
|
|
1
|
+
import { E as e, M as t, T as r, a as o, b as i, c as n, d, e as l, f as A, g as c, h as u, i as g, j as p, k as y, l as m, m as T, n as D, o as S, p as h, q as C, r as E, s as R, t as b, u as v, v as w, w as B, x, y as P, z as f, A as W, B as _, C as F, D as H, F as I, G as L, H as M, I as U, J as N, K as O, L as k, N as G, O as q, P as V, Q as K, R as Q, S as Y, U as j, V as Z, W as z, X as J, Y as X, Z as $, _ as aa, $ as sa, a0 as ea, a1 as ta, a2 as ra, a3 as oa, a4 as ia, a5 as na, a6 as da, a7 as la, a8 as Aa, a9 as ca, aa as ua, ab as ga, ac as pa, ad as ya, ae as ma, af as Ta, ag as Da, ah as Sa, ai as ha, aj as Ca, ak as Ea } from "./contract-error-log-C72hcInG.js";
|
|
2
|
+
import { decodeErrorResult as ba, encodeFunctionData as va, formatEther as wa, formatUnits as Ba, hexToString as xa, trim as Pa } from "viem";
|
|
3
3
|
export {
|
|
4
|
-
|
|
5
|
-
t as
|
|
6
|
-
r as
|
|
7
|
-
o as
|
|
8
|
-
i as
|
|
9
|
-
n as
|
|
10
|
-
d as
|
|
11
|
-
l as
|
|
4
|
+
e as EMPTY_PER_ASSET_WITHDRAW_DATA,
|
|
5
|
+
t as MIN_GM_UNWIND_VALUE_USD,
|
|
6
|
+
r as THIRD_PARTY_CONTRACT_ERRORS,
|
|
7
|
+
o as applyContractErrorRegistry,
|
|
8
|
+
i as base64ToHex,
|
|
9
|
+
n as buildAaveWithdrawAssetTransactionData,
|
|
10
|
+
d as buildComplexAssetDataForRouter,
|
|
11
|
+
l as buildDytmActions,
|
|
12
|
+
A as buildDytmOutputAssetWithdrawAction,
|
|
12
13
|
c as buildDytmRepayActions,
|
|
13
|
-
|
|
14
|
+
u as buildSwapQuoteKeyForAave,
|
|
14
15
|
g as buildSwapWithdrawTransactionData,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
p as buildZapDepositTransactionArguments,
|
|
17
|
+
y as clientSide,
|
|
18
|
+
m as computeAmountOutMinimumUsdc,
|
|
19
|
+
T as createDefaultComplexAssetData,
|
|
20
|
+
ba as decodeErrorResult,
|
|
21
|
+
va as encodeFunctionData,
|
|
22
|
+
D as encodeOndoWithdrawData,
|
|
23
|
+
S as encodeUnwindPlan,
|
|
24
|
+
h as enrichAssetsWithSwapQuotes,
|
|
24
25
|
C as ensureContractErrorRegistryLoaded,
|
|
25
|
-
|
|
26
|
+
E as ensureHexPrefix,
|
|
26
27
|
R as extractAvailableRouterKeys,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
28
|
+
b as fetchContractErrorRegistry,
|
|
29
|
+
v as formatBalance,
|
|
30
|
+
w as formatByCurrency,
|
|
31
|
+
wa as formatEther,
|
|
32
|
+
B as formatNumeratorToPercentage,
|
|
32
33
|
x as formatTokenBalance,
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
Ba as formatUnits,
|
|
35
|
+
P as getAutoSlippageSimulationCandidates,
|
|
36
|
+
f as getComplexAssetDataSlippageTolerance,
|
|
37
|
+
W as getContractAbiById,
|
|
38
|
+
_ as getContractAddressById,
|
|
38
39
|
F as getContractErrorRegistry,
|
|
39
40
|
H as getConventionalTokenPriceDecimals,
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
41
|
+
I as getErrorKey,
|
|
42
|
+
L as getFlatMoneyCollateralByLeverageAddress,
|
|
43
|
+
M as getFlatMoneyLinkByUnitAddress,
|
|
44
|
+
U as getGmxWithdrawAssetByLeverageAddress,
|
|
45
|
+
N as getGmxWithdrawAssetByVaultAddress,
|
|
46
|
+
O as getHyperliquidWithdrawAsset,
|
|
47
|
+
k as getNativeTokenInvestableBalance,
|
|
48
|
+
G as getPercent,
|
|
49
|
+
q as getPoolFraction,
|
|
50
|
+
V as getSettleDelay,
|
|
50
51
|
K as getSlippageToleranceForContractTransaction,
|
|
51
52
|
Q as getTxHashShort,
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
Y as groupPreviewByAccount,
|
|
54
|
+
xa as hexToString,
|
|
55
|
+
j as isAaveLendAndBorrowAsset,
|
|
55
56
|
Z as isFlatMoneyLeveragedAsset,
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
ea as
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
ca as
|
|
72
|
-
|
|
73
|
-
ga as
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
57
|
+
z as isFmpAirdropVaultAddress,
|
|
58
|
+
J as isGmxLeveragedAsset,
|
|
59
|
+
X as isHyperliquidCorePositionAsset,
|
|
60
|
+
$ as isHyperliquidPerpsAsset,
|
|
61
|
+
aa as isHyperliquidSpotSystemAsset,
|
|
62
|
+
sa as isNativeToken,
|
|
63
|
+
ea as isPositiveNumber,
|
|
64
|
+
ta as isStableSymbol,
|
|
65
|
+
ra as isUnswappableGmDust,
|
|
66
|
+
oa as logContractErrorOnce,
|
|
67
|
+
ia as logTransactionByActionType,
|
|
68
|
+
na as mapAttestationToOndoQuote,
|
|
69
|
+
da as mapOndoApiResponseToUpdatePricesArgs,
|
|
70
|
+
la as overlayWithdrawData,
|
|
71
|
+
Aa as parseAmountToD18,
|
|
72
|
+
ca as parseContractErrorMessage,
|
|
73
|
+
ua as shiftBy,
|
|
74
|
+
ga as shortenAddress,
|
|
75
|
+
pa as shouldSwallowMainnetPollError,
|
|
76
|
+
ya as sliceByIndex,
|
|
77
|
+
ma as toBigInt,
|
|
78
|
+
Ta as toBytes32Hex,
|
|
79
|
+
Da as transformAddressForAnalytics,
|
|
80
|
+
Pa as trim,
|
|
81
|
+
Sa as truncateString,
|
|
82
|
+
ha as tryEstimateWithRouters,
|
|
83
|
+
Ca as tryEstimateWithSlippageValues,
|
|
84
|
+
Ea as validateLoggerEventParams
|
|
82
85
|
};
|
|
@@ -1 +0,0 @@
|
|
|
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;
|