@dhedge/trading-widget 6.2.1 → 6.3.0
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/README.md +1 -0
- package/core-kit/utils/dytm.d.ts +6 -0
- package/core-kit/utils/hyperliquid.d.ts +2 -0
- package/core-kit/utils/transaction.d.ts +14 -1
- package/{dytm-DdzHS3o4.js → dytm-D5O16WMt.js} +387 -351
- package/dytm-wondvAJ2.cjs +1 -0
- package/index.cjs +1 -1
- package/index.js +2745 -2684
- package/package.json +1 -1
- package/utils.cjs +1 -1
- package/utils.js +67 -63
- package/dytm-CliLZLfa.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("./dytm-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./dytm-wondvAJ2.cjs"),t=require("viem");exports.EMPTY_PER_ASSET_WITHDRAW_DATA=e.EMPTY_PER_ASSET_WITHDRAW_DATA;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.isStableSymbol=e.isStableSymbol;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,5 +1,5 @@
|
|
|
1
|
-
import { E as s, T as t, a as r, b as o, c as i, d as n, e as d, f as l, g as
|
|
2
|
-
import { decodeErrorResult as
|
|
1
|
+
import { E as s, T as t, a as r, b as o, c as i, d as n, e as d, f as l, g as A, h as c, i as g, j as u, k as p, l as y, m, n as T, o as S, p as h, q as D, r as C, s as R, t as B, u as v, v as w, w as x, x as E, y as b, z as P, A as f, B as W, C as F, D as H, F as L, G as I, H as M, I as O, J as _, K as k, L as U, M as q, N, O as G, P as K, Q, R as V, S as Y, U as Z, V as j, W as z, X as J, Y as X, Z as $, _ as aa, $ as ea, a0 as sa, 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 ga, ab as ua, ac as pa, ad as ya, ae as ma, af as Ta, ag as Sa } from "./dytm-D5O16WMt.js";
|
|
2
|
+
import { decodeErrorResult as Da, encodeFunctionData as Ca, formatEther as Ra, formatUnits as Ba, hexToString as va, trim as wa } from "viem";
|
|
3
3
|
export {
|
|
4
4
|
s as EMPTY_PER_ASSET_WITHDRAW_DATA,
|
|
5
5
|
t as THIRD_PARTY_CONTRACT_ERRORS,
|
|
@@ -8,70 +8,74 @@ export {
|
|
|
8
8
|
i as buildAaveWithdrawAssetTransactionData,
|
|
9
9
|
n as buildComplexAssetDataForRouter,
|
|
10
10
|
d as buildDytmActions,
|
|
11
|
-
l as
|
|
11
|
+
l as buildDytmOutputAssetWithdrawAction,
|
|
12
|
+
A as buildDytmRepayActions,
|
|
12
13
|
c as buildSwapQuoteKeyForAave,
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
g as buildSwapWithdrawTransactionData,
|
|
15
|
+
u as buildZapDepositTransactionArguments,
|
|
16
|
+
p as clientSide,
|
|
16
17
|
y as computeAmountOutMinimumUsdc,
|
|
17
18
|
m as createDefaultComplexAssetData,
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
Da as decodeErrorResult,
|
|
20
|
+
Ca as encodeFunctionData,
|
|
21
|
+
T as encodeOndoWithdrawData,
|
|
22
|
+
S as encodeUnwindPlan,
|
|
22
23
|
h as enrichAssetsWithSwapQuotes,
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
D as ensureContractErrorRegistryLoaded,
|
|
25
|
+
C as ensureHexPrefix,
|
|
26
|
+
R as extractAvailableRouterKeys,
|
|
27
|
+
B as fetchContractErrorRegistry,
|
|
27
28
|
v as formatBalance,
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
_ as
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
N as
|
|
48
|
-
G as
|
|
49
|
-
K as
|
|
50
|
-
Q as
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
ca as
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
ya as
|
|
29
|
+
w as formatByCurrency,
|
|
30
|
+
Ra as formatEther,
|
|
31
|
+
x as formatNumeratorToPercentage,
|
|
32
|
+
E as formatTokenBalance,
|
|
33
|
+
Ba as formatUnits,
|
|
34
|
+
b as getAutoSlippageSimulationCandidates,
|
|
35
|
+
P as getComplexAssetDataSlippageTolerance,
|
|
36
|
+
f as getContractAbiById,
|
|
37
|
+
W as getContractAddressById,
|
|
38
|
+
F as getContractErrorRegistry,
|
|
39
|
+
H as getConventionalTokenPriceDecimals,
|
|
40
|
+
L as getErrorKey,
|
|
41
|
+
I as getFlatMoneyCollateralByLeverageAddress,
|
|
42
|
+
M as getFlatMoneyLinkByUnitAddress,
|
|
43
|
+
O as getGmxWithdrawAssetByLeverageAddress,
|
|
44
|
+
_ as getGmxWithdrawAssetByVaultAddress,
|
|
45
|
+
k as getHyperliquidWithdrawAsset,
|
|
46
|
+
U as getNativeTokenInvestableBalance,
|
|
47
|
+
q as getPercent,
|
|
48
|
+
N as getPoolFraction,
|
|
49
|
+
G as getSettleDelay,
|
|
50
|
+
K as getSlippageToleranceForContractTransaction,
|
|
51
|
+
Q as getTxHashShort,
|
|
52
|
+
V as groupPreviewByAccount,
|
|
53
|
+
va as hexToString,
|
|
54
|
+
Y as isAaveLendAndBorrowAsset,
|
|
55
|
+
Z as isFlatMoneyLeveragedAsset,
|
|
56
|
+
j as isFmpAirdropVaultAddress,
|
|
57
|
+
z as isGmxLeveragedAsset,
|
|
58
|
+
J as isHyperliquidCorePositionAsset,
|
|
59
|
+
X as isHyperliquidPerpsAsset,
|
|
60
|
+
$ as isHyperliquidSpotSystemAsset,
|
|
61
|
+
aa as isNativeToken,
|
|
62
|
+
ea as isStableSymbol,
|
|
63
|
+
sa as logTransactionByActionType,
|
|
64
|
+
ta as mapAttestationToOndoQuote,
|
|
65
|
+
ra as mapOndoApiResponseToUpdatePricesArgs,
|
|
66
|
+
oa as overlayWithdrawData,
|
|
67
|
+
ia as parseAmountToD18,
|
|
68
|
+
na as parseContractErrorMessage,
|
|
69
|
+
da as shiftBy,
|
|
70
|
+
la as shortenAddress,
|
|
71
|
+
Aa as shouldSwallowMainnetPollError,
|
|
72
|
+
ca as sliceByIndex,
|
|
73
|
+
ga as toBigInt,
|
|
74
|
+
ua as toBytes32Hex,
|
|
75
|
+
pa as transformAddressForAnalytics,
|
|
76
|
+
wa as trim,
|
|
77
|
+
ya as truncateString,
|
|
78
|
+
ma as tryEstimateWithRouters,
|
|
79
|
+
Ta as tryEstimateWithSlippageValues,
|
|
80
|
+
Sa as validateLoggerEventParams
|
|
77
81
|
};
|
package/dytm-CliLZLfa.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const A=require("wagmi/chains"),a=require("./gmx-DJ0gqvLq.cjs"),p=require("bignumber.js"),u=require("viem"),dt=typeof window<"u",ut=[{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"}],pt=[{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"}]}],lt=[{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"}],mt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewWithdrawal",outputs:[{name:"assetData",type:"tuple[]",components:lt}],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"}],yt=[{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"}],At=[{type:"tuple",components:[{name:"actions",type:"tuple[]",components:[{name:"to",type:"address"},{name:"data",type:"bytes"}]},{name:"outputAsset",type:"address"},{name:"minOutputAmount",type:"uint256"}]}],S={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."}}},U=t=>({stringErrors:{...t.stringErrors,...S.stringErrors},selectorErrors:{...t.selectorErrors,...S.selectorErrors}}),gt=["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"],Et=1,Tt=1e4,N=2e6,ht=2e3,St=500,_t=120,ft=300,Dt=4,wt=/^dh\d{1,3}$/i,F=/[\u0000-\u001f\u007f]/,bt=/https?:\/\/|[<>`]/i,Rt=t=>t.length<=_t&&!F.test(t)&&(wt.test(t)||t.length>=Dt),T=t=>typeof t=="string"&&t.length>0&&t.length<=ft&&!F.test(t)&&!bt.test(t);let v=S,f=null;const R=()=>v,W=t=>{v=U(t)},It=t=>{const e=t;if(e?.schemaVersion!==Et)throw new Error(`Unsupported error registry schemaVersion: ${String(e?.schemaVersion)}`);const n={};for(const[o,s]of Object.entries(e.stringErrors??{}))s?.curated===!0&&Rt(o)&&T(s.description)&&T(s.action)&&(n[o]={title:s.description,hint:s.action});const r={};for(const[o,s]of Object.entries(e.selectorErrors??{}))s?.curated===!0&&/^0x[0-9a-f]{8}$/.test(o)&&T(s.signature)&&T(s.description)&&T(s.action)&&(r[o]={signature:s.signature,title:s.description,hint:s.action});if(!Object.keys(n).length)throw new Error("Error registry contained no curated string errors");if(Object.keys(n).length>ht||Object.keys(r).length>St)throw new Error("Error registry exceeded expected entry counts");return{stringErrors:n,selectorErrors:r}},G=async({timeoutMs:t=Tt}={})=>{const e=[];for(const n of gt){const r=new AbortController,o=setTimeout(()=>r.abort(),t);try{const s=await fetch(n,{headers:{accept:"application/json"},signal:r.signal});if(!s.ok)throw new Error(`HTTP ${s.status}`);const i=Number(s.headers.get("content-length"));if(i>N)throw new Error(`Response too large: ${i} bytes`);const c=await s.text();if(c.length>N)throw new Error(`Response too large: ${c.length} chars`);return U(It(JSON.parse(c)))}catch(s){e.push(`${n}: ${s instanceof Error?s.message:String(s)}`)}finally{clearTimeout(o)}}throw new Error(`All error registry sources failed: ${e.join("; ")}`)},Nt=()=>(f??(f=G().then(W).catch(()=>{f=null})),f),Ct=()=>typeof window<"u";function Ot(){return Ct()&&typeof window.ethereum<"u"}async function Pt(t){try{if(Ot())return window.ethereum.request({method:"wallet_watchAsset",params:{type:"ERC20",options:t}})}catch{return!1}return!1}const y=(t,e)=>t?.toLowerCase()===e?.toLowerCase(),Mt=t=>y(t,a.AddressZero$1),h=t=>{if(!t)throw new Error("Cannot prefix an empty hex value");return t.startsWith("0x")?t:`0x${t}`},m=(t,e)=>{try{return BigInt(t)}catch{throw new Error(`Cannot convert "${e}" value "${t}" to bigint`)}},D=t=>t?u.pad(h(t),{size:32}):u.zeroHash,$=t=>{if(!t)throw new Error("Cannot decode an empty base64 string");return u.bytesToHex(Uint8Array.from(atob(t),e=>e.charCodeAt(0)))},H=(t,e)=>a.contractsAddressesMap[e]?.[t]??a.AddressZero,Lt=t=>a.contractsAbisMap[t],xt=t=>t&&`${t.substring(0,6)}...${t.substring(t.length-4,t.length)}`,Bt=({address:t,chainId:e})=>{const n=H("aaveLendingPoolV3",e);return y(t,n)},Y=({sourceAddress:t,amount:e})=>`${t}_${e}`,Ut=(t,e)=>{const n=t.slice(0,e),r=t.slice(e);return{firstPart:n,secondPart:r}},k=(t,e)=>t/e*100,Ft=t=>t<1?4:t<10?3:2,vt=(t,e=a.DEFAULT_PRECISION)=>new p(t.toString()).shiftedBy(e).toFixed(0),Wt=(t,e,n,r)=>new p(e).dividedBy(n).multipliedBy(t).shiftedBy(-(r||a.DEFAULT_PRECISION)).toNumber(),Gt=t=>BigInt(new p(t||"0").shiftedBy(a.DEFAULT_PRECISION).toFixed(0,p.ROUND_DOWN)),V=t=>{const e=new p(.01),n=new p(t),r=!n.isZero()&&n.lt(e)?e:n;return BigInt(r.multipliedBy(100).toFixed(0))},$t=({vaultAddress:t,swapData:e,sendTokenAddress:n,sendTokenAmount:r,vaultDepositTokenAddress:o,minVaultTokensReceivedAmount:s,routerKey:i="ONE_INCH",swapDestinationAmount:c,swapSlippage:d})=>{const l=new p(c).multipliedBy(1-d/100).toFixed(0),g=[u.stringToHex(i,{size:32}),e];return[t,[[n,r,g],[o,l]],s]},Ht=({receiveAssetAddress:t,assets:e,swapData:n,slippage:r})=>{const o={srcData:[],destAmount:new p("0")},{srcData:s,destAmount:i}=e?.reduce((c,d)=>{const l=n?.[d.address];if(!l)return c;const g=[u.stringToHex(l.routerKey,{size:32}),l.rawTransaction.data],E=[d.address,d.rawBalance,g];return{srcData:[...c.srcData,E],destAmount:c.destAmount.plus(l.destinationAmount)}},o)??o;return[s,[t,i.times(1-r/100).toFixed(0,p.ROUND_DOWN)]]},K=({assetAddress:t,swapQuotes:e,swapParams:n,slippageToleranceForContractTransaction:r,routerKey:o})=>{if(!n)return{supportedAsset:t,withdrawData:"",slippageTolerance:BigInt(0)};const{srcData:s,dstData:i}=n,c=s.map(({asset:g,amount:E})=>{const _=e?.[Y({sourceAddress:g,amount:E.toString()})]?.find(ct=>ct.routerKey===o);return{asset:g,amount:E,swapData:{routerKey:u.stringToHex(_?.routerKey??"",{size:32}),txData:_?.rawTransaction.data??"0x"}}}),d=u.encodeAbiParameters(a.ComplexWithdrawalAssetSrcDataAbiItem,[c]),l=u.encodeAbiParameters(a.ComplexWithdrawalDataAbiItem,[{encodedSrcData:d,dstData:{dstAddress:i.asset,dstAmount:i.amount},slippage:r}]);return{supportedAsset:t,withdrawData:l,slippageTolerance:r}},Yt=({chainId:t,txHash:e,error:n})=>{if(t!==A.mainnet.id||!e||!n)return!1;const r=n instanceof Error?n.message:String(n);return/\bNo Result\b/i.test(r)},kt=({chainId:t,action:e,isRabbyWallet:n})=>e==="update_ondo_prices"&&t===A.mainnet.id&&n?a.ONDO_PRICES_RABBY_SETTLE_DELAY:t?a.TRANSACTION_SETTLE_DELAY[t]??0:0,Vt=(t,e)=>a.CHAIN_NATIVE_TOKENS[e]?.nativeTokenSymbol===t,Kt=({nativeTokenBalance:t,tokenDecimals:e,gasPrice:n})=>{const r=new p(n).multipliedBy(a.NATIVE_TOKEN_GAS_RESERVE_UNITS).shiftedBy(-e),o=new p(t).minus(r);return o.gt("0")?o:new p("0")},qt=t=>a.STABLE_TOKEN_SYMBOLS.includes(t),jt=t=>{const e=Object.values(t).reduce((n,{type:r})=>(n[r]=n[r]+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},Xt=(t,e=150)=>t.length>e?t.substring(0,e):t,q=()=>({...R().stringErrors,...a.TRANSACTION_ERRORS}),Zt=()=>[...Object.keys(q()),...Object.keys(a.LIMIT_ORDER_TRANSACTION_ERRORS)],Qt=/^dh\d+$/i,zt=(t,e)=>Qt.test(e)?new RegExp(`\\b${e}\\b`,"i").test(t):t.includes(e.toLowerCase()),w=(t,e)=>{const n=t.toLowerCase();return[...e??Zt()].sort((r,o)=>o.length-r.length).find(r=>zt(n,r))},C=t=>q()[t]??a.LIMIT_ORDER_TRANSACTION_ERRORS[t],Jt=/\b0x[0-9a-f]{8}\b/i,te=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ee=t=>{const{selectorErrors:e}=R(),n=t.match(Jt)?.[0]?.toLowerCase(),r=n?e[n]:void 0;if(r)return{title:r.title,hint:r.hint};const o=Object.values(e).find(s=>new RegExp(`\\b${te(s.signature.split("(")[0]??"")}\\b`).test(t));return o?{title:o.title,hint:o.hint}:void 0},ne=({errorMessage:t,abiErrors:e})=>{if(!t||t.includes("User rejected"))return null;const n=e.find(i=>t.includes(i));if(n){const i=w(n);if(i)return C(i)}const r=w(t);if(r)return C(r);const o=ee(t);if(o)return o;const[s]=t.split(n?".":"Contract").map(i=>i.trim());return{title:"Transaction failed",hint:`${Xt(s??"")} ${n?`: ${n}`:""}`}},re=t=>typeof t=="number"&&Number.isFinite(t),se=t=>typeof t=="bigint"&&t!==BigInt(0),j=(t,e=a.DEFAULT_PRECISION$1)=>new p(t).shiftedBy(-e).toNumber(),X=t=>!isNaN(parseFloat(t))&&!isNaN(t),Z=({value:t,minimumFractionDigits:e=2,maximumFractionDigits:n=2,compact:r=!1,normalize:o=!1})=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:r?"compact":void 0,minimumFractionDigits:e,maximumFractionDigits:n}).format(o?j(t):Number(t)),b=t=>X(t)?new p(t).toFixed():"",O=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"],Q=({value:t,decimals:e=4})=>{const n=new p(t);if(n.isGreaterThan(1)||n.isZero())return b(n.toFixed(e));const o=(/e/i.test(t.toString())?parseFloat(t.toString()).toFixed(a.DEFAULT_PRECISION$1):t.toString()).match(/^0\.(0+)(\d+)$/);if(o){const[,s,i]=o;if(s.length>=e&&s.length<O.length)return`0.0${O[s.length]}${i.slice(0,3)}`}return b(n.toFixed(e))},z=(t,e=0)=>`${t.toLocaleString("en-US",{maximumFractionDigits:e})}%`,oe=t=>t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),ae=(t,e,n=0)=>{const r=k(+t,e);return z(r,n)},ie=({currency:t,value:e})=>t==="USD"?Z({value:e}):`${a.CURRENCY_SYMBOL_MAP[t]} ${Q({value:e,decimals:a.CURRENCY_DECIMALS_MAP[t]})}`,J=(t,e)=>new p(new p(t).toFixed(e,p.ROUND_DOWN)).toString(),tt=(t,e=3,n=2)=>{if(t.length<=5)return t;const r="...";return t.length<=e+n+r.length?t:`${t.slice(0,e)}${r}${t.slice(-n)}`},ce=({balance:t,symbol:e,precision:n,truncateSymbol:r})=>`${J(t,n)} ${r?tt(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)}`},ue=t=>y(a.FLATMONEY_EARLY_DEPOSITOR_VAULT_ADDRESS_BASE,t)||y(a.FLATMONEY_DHT_STAKING_VAULT_ADDRESS_BASE,t),pe=t=>a.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES.some(e=>y(e,t)),le=t=>a.FLAT_MONEY_COLLATERAL_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},me=t=>y(t,a.FLAT_MONEY_V1_UNIT_ADDRESS)?a.FLAT_MONEY_V1_UNIT_LINK:a.FLAT_MONEY_UNIT_LINK,et=t=>`eth_${t}`,ye=({action:t,log:e,symbol:n,vaultAddress:r,chainId:o})=>{const s={[a.TRADING_LOG_EVENT_PARAM.SYMBOL.NAME]:n,[a.TRADING_LOG_EVENT_PARAM.CHAIN_ID.NAME]:o,[a.TRADING_LOG_EVENT_PARAM.ADDRESS.NAME]:et(r)};a.LOG_EVENT_BY_TRANSACTION_ACTION_MAP[t].forEach(i=>{e?.(i,s)})},Ae=t=>a.GMX_MARKET_ASSETS.some(e=>y(e,t)),ge=t=>a.GMX_WITHDRAW_ASSET_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},Ee=t=>a.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS[t.toLowerCase()],nt="0x3333333333333333333333333333333333333333";A.arbitrum.id+"",a.USDC_ARBITRUM.address,A.base.id+"",a.USDC_BASE.address,A.optimism.id+"",a.USDC_OPTIMISM.address,A.polygon.id+"",a.USDC_POLYGON.address,A.mainnet.id+"",a.USDC_MAINNET.address,A.hyperEvm.id+"",a.USDC_HYPEREVM.address;const Te=t=>y(t,nt),he=()=>a.USDC_HYPEREVM,Se=new Map,I=(t,e)=>!e||e.size===0?t:t.map(n=>{const r=e.get(n.supportedAsset.toLowerCase());return r?{...n,withdrawData:r.withdrawData,slippageTolerance:r.slippageTolerance}:n}),rt=t=>{const e=t.find(({swapQuotes:n})=>n);return e?.swapQuotes?Object.values(e.swapQuotes)[0]?.map(({routerKey:n})=>n)??[]:[]},st=(t,e,n)=>t.map(({asset:r,swapParams:o,swapQuotes:s})=>!o||!s?{supportedAsset:r,withdrawData:"",slippageTolerance:n}:K({assetAddress:r,swapQuotes:s,swapParams:o,slippageToleranceForContractTransaction:n,routerKey:e})),ot=async(t,e,n,r,o,s)=>{for(const i of t){const c=I(st(e,i,n),s),{error:d}=await r(...o,c);if(!d)return c}return null},_e=(t,e,n)=>{const r=(t??[]).map(o=>({supportedAsset:o,withdrawData:"",slippageTolerance:e}));return I(r,n)},fe=async(t,e,n,r,o)=>{for(const s of t){const i=V(s);try{const c=await e(s),d=rt(c),l=await ot(d,c,i,n,r,o);if(l)return console.debug(`[Init Withdraw] Auto slippage simulation succeeded: slippage=${s}%`),console.debug("[Init Withdraw] Complex asset data:",l),l}catch(c){console.error(`[Init Withdraw] Failed to fetch quotes for slippage=${s}%:`,c)}}return null},De=async(t,e,{fetchAaveSwapParams:n,fetchAaveSwapQuotes:r,withdrawAmountD18:o,slippage:s})=>Promise.all((t??[]).map(async i=>{if(!y(i,e))return{asset:i};try{const d=await n({withdrawAmountD18:o,slippage:s});if(d?.srcData.length){const l=await r({swapParams:d,slippage:s});return{asset:i,swapParams:d,swapQuotes:l}}return{asset:i}}catch(d){return console.error(d),{asset:i}}})),P=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=P(Math.min(t,100)),r=e.filter(s=>s>0&&s<=n).map(P),o=new Set(r);return o.add(n),o.add(t),Array.from(o).sort((s,i)=>s-i)},M=1000000000000000000n,be=1000000n,L=10000n,x=100n,Re=t=>({quotes:t.quotes.map(e=>({chainId:m(e.chainId,"chainId"),attestationId:m(e.attestationId,"attestationId"),userId:h(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:h(e.additionalData)})),signatures:t.signatures.map(h)}),at=(t,e,n)=>{const r=BigInt(Math.max(0,Math.round(n*100))),o=r>x?x:r,s=L-o,c=t*e/M*s*be,d=L*M;return(c+d-1n)/d},it=(t,e)=>({chainId:e,attestationId:m(t.attestationId,"attestationId"),userId:D(t.userId),asset:t.assetAddress,price:m(t.price,"price"),quantity:m(t.tokenAmount,"tokenAmount"),expiration:m(t.expiration,"expiration"),side:Number(t.side),additionalData:D(t.additionalData)}),Ie=({attestation:t,chainId:e,slippagePercent:n})=>{const r=it(t,e);return u.encodeAbiParameters(pt,[{attestationSignature:$(t.signature),quote:r,amountOutMinimum:at(r.quantity,r.price,n)}])},Ne=t=>[...t.reduce((n,r)=>n.has(r.accountId)?n:n.set(r.accountId,r),new Map).values()].map(({accountId:n,marketId:r})=>({accountId:n,marketId:r,collaterals:t.filter(o=>o.accountId===n&&!o.isDebt),debt:t.find(o=>o.accountId===n&&o.isDebt)})),Ce=({collateral:t,dytmOffice:e,processor:n,gmToken:r,ondoGMSwap:o,usdc:s,gmAmount:i,amountOutMinimum:c,signature:d,quote:l})=>[{to:e,data:u.encodeFunctionData({abi:B,functionName:"withdraw",args:[{account:t.accountId,tokenId:t.tokenId,receiver:n,assets:i,shares:0n,extraData:"0x"}]})},{to:r,data:u.encodeFunctionData({abi:u.erc20Abi,functionName:"approve",args:[o,i]})},{to:o,data:u.encodeFunctionData({abi:yt,functionName:"swapExactInWithAttestation",args:[r,i,s,c,d,l]})}],Oe=({accountId:t,debtKey:e,dytmOffice:n,usdc:r})=>[{to:r,data:u.encodeFunctionData({abi:u.erc20Abi,functionName:"approve",args:[n,u.maxUint256]})},{to:n,data:u.encodeFunctionData({abi:B,functionName:"repay",args:[{account:t,key:e,withCollateralType:0,assets:u.maxUint256,shares:0n,extraData:"0x"}]})}],Pe=({actions:t,outputAsset:e,minOutputAmount:n})=>u.encodeAbiParameters(At,[{actions:t,outputAsset:e,minOutputAmount:n}]);exports.DytmOfficeAssetGuardAbi=mt;exports.EMPTY_PER_ASSET_WITHDRAW_DATA=Se;exports.HYPERLIQUID_PERPS_ACCOUNT_ADDRESS=nt;exports.OndoGMTokenAssetGuardAbi=ut;exports.THIRD_PARTY_CONTRACT_ERRORS=S;exports.addTokenToWallet=Pt;exports.applyContractErrorRegistry=W;exports.base64ToHex=$;exports.buildAaveWithdrawAssetTransactionData=K;exports.buildComplexAssetDataForRouter=st;exports.buildDytmActions=Ce;exports.buildDytmRepayActions=Oe;exports.buildSwapQuoteKeyForAave=Y;exports.buildSwapWithdrawTransactionData=Ht;exports.buildZapDepositTransactionArguments=$t;exports.clientSide=dt;exports.commify=oe;exports.computeAmountOutMinimumUsdc=at;exports.createDefaultComplexAssetData=_e;exports.encodeOndoWithdrawData=Ie;exports.encodeUnwindPlan=Pe;exports.enrichAssetsWithSwapQuotes=De;exports.ensureContractErrorRegistryLoaded=Nt;exports.ensureHexPrefix=h;exports.extractAvailableRouterKeys=rt;exports.fetchContractErrorRegistry=G;exports.formatBalance=J;exports.formatByCurrency=ie;exports.formatNumberToLimitedDecimals=Q;exports.formatNumeratorToPercentage=ae;exports.formatPercentage=z;exports.formatToUsd=Z;exports.formatTokenBalance=ce;exports.getAutoSlippageSimulationCandidates=we;exports.getContractAbiById=Lt;exports.getContractAddressById=H;exports.getContractErrorRegistry=R;exports.getConventionalTokenPriceDecimals=Ft;exports.getErrorKey=w;exports.getFlatMoneyCollateralByLeverageAddress=le;exports.getFlatMoneyLinkByUnitAddress=me;exports.getGmxWithdrawAssetByLeverageAddress=ge;exports.getGmxWithdrawAssetByVaultAddress=Ee;exports.getHyperliquidWithdrawAsset=he;exports.getNativeTokenInvestableBalance=Kt;exports.getPercent=k;exports.getPoolFraction=Wt;exports.getSettleDelay=kt;exports.getSlippageToleranceForContractTransaction=V;exports.getTxHashShort=de;exports.groupPreviewByAccount=Ne;exports.isAaveLendAndBorrowAsset=Bt;exports.isEqualAddress=y;exports.isFlatMoneyLeveragedAsset=pe;exports.isFmpAirdropVaultAddress=ue;exports.isGmxLeveragedAsset=Ae;exports.isHyperliquidPerpsAsset=Te;exports.isNativeToken=Vt;exports.isNumberType=re;exports.isNumeric=X;exports.isStableSymbol=qt;exports.isZeroAddress=Mt;exports.logTransactionByActionType=ye;exports.mapAttestationToOndoQuote=it;exports.mapOndoApiResponseToUpdatePricesArgs=Re;exports.nonZeroBigInt=se;exports.normalizeNumber=j;exports.overlayWithdrawData=I;exports.parseAmountToD18=Gt;exports.parseContractErrorMessage=ne;exports.removeInsignificantTrailingZeros=b;exports.shiftBy=vt;exports.shortenAddress=xt;exports.shouldSwallowMainnetPollError=Yt;exports.sliceByIndex=Ut;exports.toBigInt=m;exports.toBytes32Hex=D;exports.transformAddressForAnalytics=et;exports.truncateString=tt;exports.tryEstimateWithRouters=ot;exports.tryEstimateWithSlippageValues=fe;exports.validateLoggerEventParams=jt;
|