@dhedge/trading-widget 6.1.1 → 6.2.0-canary.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.
- package/const.cjs +1 -1
- package/const.js +23 -24
- package/core-kit/const/error.d.ts +6 -1
- package/core-kit/utils/error-registry.d.ts +46 -0
- package/core-kit/utils/index.d.ts +1 -0
- package/dytm-D2sVE2th.cjs +1 -0
- package/dytm-DycL7_hQ.js +864 -0
- package/{gmx-c42QlKyJ.js → gmx-Cyz_GmV5.js} +332 -481
- package/gmx-DJ0gqvLq.cjs +1 -0
- package/index.cjs +1 -1
- package/index.js +1479 -1477
- package/package.json +1 -1
- package/utils.cjs +1 -1
- package/utils.js +69 -65
- package/dytm-CQG65-Rc.cjs +0 -1
- package/dytm-CWhBYz0P.js +0 -784
- package/gmx-U3Bnivj2.cjs +0 -1
package/const.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("./geoblocking-peuNwHMJ.cjs"),_=require("./gmx-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("./geoblocking-peuNwHMJ.cjs"),_=require("./gmx-DJ0gqvLq.cjs"),A=require("wagmi/chains");exports.BLOCKED_COUNTRY_CODES_MAP=E.BLOCKED_COUNTRY_CODES_MAP;exports.COVERED_CALL_VAULT_ADDRESSES=E.COVERED_CALL_VAULT_ADDRESSES;exports.LOCAL_STORAGE_KEYS=E.LOCAL_STORAGE_KEYS;exports.MIDAS_MAPOLLO_ADDRESS=E.MIDAS_MAPOLLO_ADDRESS;exports.MIDAS_MAPOLLO_LINK=E.MIDAS_MAPOLLO_LINK;exports.ONDO_ASSET_TYPE=E.ONDO_ASSET_TYPE;exports.ONDO_BLOCKED_COUNTRY_CODES_MAP=E.ONDO_BLOCKED_COUNTRY_CODES_MAP;exports.ALCHEMY_RPC_URL_MAP=_.ALCHEMY_RPC_URL_MAP;exports.AddressZero=_.AddressZero;exports.BRIDGED_TOKENS_SYMBOLS=_.BRIDGED_TOKENS_SYMBOLS;exports.CHAIN_MAP=_.CHAIN_MAP;exports.CHAIN_NATIVE_TOKENS=_.CHAIN_NATIVE_TOKENS;exports.COMPLETE_WITHDRAW_ACTIONS=_.COMPLETE_WITHDRAW_ACTIONS;exports.CURRENCY_DECIMALS_MAP=_.CURRENCY_DECIMALS_MAP;exports.CURRENCY_SYMBOL_MAP=_.CURRENCY_SYMBOL_MAP;exports.DEFAULT_DEBOUNCE_TIME=_.DEFAULT_DEBOUNCE_TIME;exports.DEFAULT_DEPOSIT_METHOD=_.DEFAULT_DEPOSIT_METHOD;exports.DEFAULT_DEPOSIT_SLIPPAGE=_.DEFAULT_DEPOSIT_SLIPPAGE;exports.DEFAULT_DEPOSIT_SLIPPAGE_SCALE=_.DEFAULT_DEPOSIT_SLIPPAGE_SCALE;exports.DEFAULT_ERROR_MESSAGE=_.DEFAULT_ERROR_MESSAGE;exports.DEFAULT_LOCK_TIME=_.DEFAULT_LOCK_TIME;exports.DEFAULT_MAX_GAS_LIMIT=_.DEFAULT_MAX_GAS_LIMIT;exports.DEFAULT_MULTI_ASSET_WITHDRAW_METHOD=_.DEFAULT_MULTI_ASSET_WITHDRAW_METHOD;exports.DEFAULT_NOTIFICATION_DURATION_MS=_.DEFAULT_NOTIFICATION_DURATION_MS;exports.DEFAULT_NO_SWAP_MIN_DEPOSIT_AMOUNT_GAP=_.DEFAULT_NO_SWAP_MIN_DEPOSIT_AMOUNT_GAP;exports.DEFAULT_ONDO_WITHDRAWAL_CONTRACT_SLIPPAGE=_.DEFAULT_ONDO_WITHDRAWAL_CONTRACT_SLIPPAGE;exports.DEFAULT_POLLING_INTERVAL=_.DEFAULT_POLLING_INTERVAL;exports.DEFAULT_PRECISION=_.DEFAULT_PRECISION;exports.DEFAULT_PROMISE_TIMEOUT_MS=_.DEFAULT_PROMISE_TIMEOUT_MS;exports.DEFAULT_RECEIVED_VALUE_GAP=_.DEFAULT_RECEIVED_VALUE_GAP;exports.DEFAULT_SIMULATION_ERROR=_.DEFAULT_SIMULATION_ERROR;exports.DEFAULT_SWAP_TRANSACTION_SLIPPAGE=_.DEFAULT_SWAP_TRANSACTION_SLIPPAGE;exports.DEFAULT_VAULT_TOKEN_PRICE=_.DEFAULT_VAULT_TOKEN_PRICE;exports.DEFAULT_VISIBLE_ASSETS_LIMIT=_.DEFAULT_VISIBLE_ASSETS_LIMIT;exports.DEFAULT_WITHDRAW_SLIPPAGE=_.DEFAULT_WITHDRAW_SLIPPAGE;exports.DEPOSIT_SWAP_DATA_ERROR=_.DEPOSIT_SWAP_DATA_ERROR;exports.EASY_SWAPPER_V2_COMPLETE_WITHDRAW_METHOD=_.EASY_SWAPPER_V2_COMPLETE_WITHDRAW_METHOD;exports.EASY_SWAPPER_V2_DEPOSIT_METHODS=_.EASY_SWAPPER_V2_DEPOSIT_METHODS;exports.EASY_SWAPPER_V2_INITIATE_WITHDRAW_METHOD=_.EASY_SWAPPER_V2_INITIATE_WITHDRAW_METHOD;exports.EASY_SWAPPER_V2_UNROLL_AND_CLAIM_METHOD=_.EASY_SWAPPER_V2_UNROLL_AND_CLAIM_METHOD;exports.EMPTY_POOL_CONFIG=_.EMPTY_POOL_CONFIG;exports.EXTENDED_DEBOUNCE_TIME=_.EXTENDED_DEBOUNCE_TIME;exports.EXTENDED_POLLING_INTERVAL=_.EXTENDED_POLLING_INTERVAL;exports.EXTREMELY_SHORT_POLLING_INTERVAL=_.EXTREMELY_SHORT_POLLING_INTERVAL;exports.FALLBACK_ASSETS_MAP=_.FALLBACK_ASSETS_MAP;exports.FLAT_MONEY_COLLATERAL_MAP=_.FLAT_MONEY_COLLATERAL_MAP;exports.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES=_.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES;exports.FLAT_MONEY_UNIT_ADDRESSES=_.FLAT_MONEY_UNIT_ADDRESSES;exports.FLAT_MONEY_UNIT_LINK=_.FLAT_MONEY_UNIT_LINK;exports.FLAT_MONEY_V1_UNIT_ADDRESS=_.FLAT_MONEY_V1_UNIT_ADDRESS;exports.FLAT_MONEY_V1_UNIT_LINK=_.FLAT_MONEY_V1_UNIT_LINK;exports.GAS_ESTIMATION_ERROR=_.GAS_ESTIMATION_ERROR;exports.GAS_LIMIT_BUFFER_COEFF=_.GAS_LIMIT_BUFFER_COEFF;exports.GMX_MARKET_ASSETS=_.GMX_MARKET_ASSETS;exports.GMX_MARKET_ASSETS_MAP=_.GMX_MARKET_ASSETS_MAP;exports.GMX_WITHDRAW_ASSET_MAP=_.GMX_WITHDRAW_ASSET_MAP;exports.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS=_.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS;exports.INVALID_PRICES_LIMIT_ORDER_TITLE=_.INVALID_PRICES_LIMIT_ORDER_TITLE;exports.LIMIT_ORDER_TRANSACTION_ERRORS=_.LIMIT_ORDER_TRANSACTION_ERRORS;exports.LOG_EVENT_BY_TRANSACTION_ACTION_MAP=_.LOG_EVENT_BY_TRANSACTION_ACTION_MAP;exports.MANAGER_FEE_DENOMINATOR=_.MANAGER_FEE_DENOMINATOR;exports.MAX_GAS_LIMIT_MAP=_.MAX_GAS_LIMIT_MAP;exports.MULTI_ASSET_TOKEN=_.MULTI_ASSET_TOKEN;exports.MaxUint256=_.MaxUint256;exports.NATIVE_TOKEN_GAS_RESERVE_UNITS=_.NATIVE_TOKEN_GAS_RESERVE_UNITS;exports.ONDO_PRICES_FETCH_TIMEOUT_MS=_.ONDO_PRICES_FETCH_TIMEOUT_MS;exports.ONDO_PRICES_RABBY_SETTLE_DELAY=_.ONDO_PRICES_RABBY_SETTLE_DELAY;exports.ONDO_PRICE_CHECK_TIMEOUT_MS=_.ONDO_PRICE_CHECK_TIMEOUT_MS;exports.ONDO_PRICE_FRESHNESS_WINDOW_MS=_.ONDO_PRICE_FRESHNESS_WINDOW_MS;exports.ONDO_PRICE_MAX_DEVIATION_PERCENT=_.ONDO_PRICE_MAX_DEVIATION_PERCENT;exports.ON_DEMAND_PRICING_ASSET_BY_CHAIN_MAP=_.ON_DEMAND_PRICING_ASSET_BY_CHAIN_MAP;exports.PYTH_API_LINK=_.PYTH_API_LINK;exports.SHORTEN_POLLING_INTERVAL=_.SHORTEN_POLLING_INTERVAL;exports.SIMULATION_TIMEOUT_ERROR=_.SIMULATION_TIMEOUT_ERROR;exports.SLIPPAGE_AUTO_SIMULATION_CANDIDATES=_.SLIPPAGE_AUTO_SIMULATION_CANDIDATES;exports.STABLE_TOKEN_SYMBOLS=_.STABLE_TOKEN_SYMBOLS;exports.SWAP_FAILED_ERROR=_.SWAP_FAILED_ERROR;exports.SWAP_QUOTE_REFRESH_INTERVAL_MS=_.SWAP_QUOTE_REFRESH_INTERVAL_MS;exports.TRADING_LOG_EVENT_PARAM=_.TRADING_LOG_EVENT_PARAM;exports.TRADING_PANEL_LOG_EVENT=_.TRADING_PANEL_LOG_EVENT;exports.TRANSACTION_ERRORS=_.TRANSACTION_ERRORS;exports.TRANSACTION_SETTLE_DELAY=_.TRANSACTION_SETTLE_DELAY;exports.WBTC_BY_CHAIN_ID=_.WBTC_BY_CHAIN_ID;exports.WETH_BY_CHAIN_ID=_.WETH_BY_CHAIN_ID;exports.WITHDRAW_SWAP_DATA_ERROR=_.WITHDRAW_SWAP_DATA_ERROR;exports.contractsAbisMap=_.contractsAbisMap;exports.contractsAddressesMap=_.contractsAddressesMap;Object.defineProperty(exports,"arbitrum",{enumerable:!0,get:()=>A.arbitrum});Object.defineProperty(exports,"base",{enumerable:!0,get:()=>A.base});Object.defineProperty(exports,"hyperEvm",{enumerable:!0,get:()=>A.hyperEvm});Object.defineProperty(exports,"mainnet",{enumerable:!0,get:()=>A.mainnet});Object.defineProperty(exports,"optimism",{enumerable:!0,get:()=>A.optimism});Object.defineProperty(exports,"polygon",{enumerable:!0,get:()=>A.polygon});
|
package/const.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { B as A, C as T, L as S, M as I, a, O, b as L } from "./geoblocking-DtB4yr5l.js";
|
|
2
|
-
import { A as
|
|
3
|
-
import { arbitrum as
|
|
2
|
+
import { A as D, a as N, B as s, C as M, b as P, c as C, d as U, e as F, D as G, f as W, g as Y, h as H, i as V, j as B, k as K, l as r, m as o, n as e, o as t, p as X, q as m, r as p, s as i, t as n, u as b, v as c, w as d, x as f, y as x, E as g, z as h, F as l, G as y, H as j, I as k, J as u, K as v, L as Q, M as Z, N as q, O as w, P as z, Q as J, R as $, S as __, T as E_, U as A_, V as T_, W as S_, X as I_, Y as a_, Z as O_, _ as L_, $ as R_, a0 as D_, a1 as N_, a2 as s_, a3 as M_, a4 as P_, a5 as C_, a6 as U_, a7 as F_, a8 as G_, a9 as W_, aa as Y_, ab as H_, ac as V_, ad as B_, ae as K_, af as r_, ag as o_, ah as e_, ai as t_, aj as X_, ak as m_, al as p_, am as i_, an as n_, ao as b_, ap as c_ } from "./gmx-Cyz_GmV5.js";
|
|
3
|
+
import { arbitrum as f_, base as x_, hyperEvm as g_, mainnet as h_, optimism as l_, polygon as y_ } from "wagmi/chains";
|
|
4
4
|
export {
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
D as ALCHEMY_RPC_URL_MAP,
|
|
6
|
+
N as AddressZero,
|
|
7
7
|
A as BLOCKED_COUNTRY_CODES_MAP,
|
|
8
8
|
s as BRIDGED_TOKENS_SYMBOLS,
|
|
9
9
|
M as CHAIN_MAP,
|
|
@@ -39,11 +39,11 @@ export {
|
|
|
39
39
|
y as EASY_SWAPPER_V2_UNROLL_AND_CLAIM_METHOD,
|
|
40
40
|
j as EMPTY_POOL_CONFIG,
|
|
41
41
|
k as EXTENDED_DEBOUNCE_TIME,
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
u as EXTENDED_POLLING_INTERVAL,
|
|
43
|
+
v as EXTREMELY_SHORT_POLLING_INTERVAL,
|
|
44
|
+
Q as FALLBACK_ASSETS_MAP,
|
|
45
|
+
Z as FLAT_MONEY_COLLATERAL_MAP,
|
|
46
|
+
q as FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES,
|
|
47
47
|
w as FLAT_MONEY_UNIT_ADDRESSES,
|
|
48
48
|
z as FLAT_MONEY_UNIT_LINK,
|
|
49
49
|
J as FLAT_MONEY_V1_UNIT_ADDRESS,
|
|
@@ -59,10 +59,10 @@ export {
|
|
|
59
59
|
S as LOCAL_STORAGE_KEYS,
|
|
60
60
|
L_ as LOG_EVENT_BY_TRANSACTION_ACTION_MAP,
|
|
61
61
|
R_ as MANAGER_FEE_DENOMINATOR,
|
|
62
|
-
|
|
62
|
+
D_ as MAX_GAS_LIMIT_MAP,
|
|
63
63
|
I as MIDAS_MAPOLLO_ADDRESS,
|
|
64
64
|
a as MIDAS_MAPOLLO_LINK,
|
|
65
|
-
|
|
65
|
+
N_ as MULTI_ASSET_TOKEN,
|
|
66
66
|
s_ as MaxUint256,
|
|
67
67
|
M_ as NATIVE_TOKEN_GAS_RESERVE_UNITS,
|
|
68
68
|
O as ONDO_ASSET_TYPE,
|
|
@@ -83,17 +83,16 @@ export {
|
|
|
83
83
|
e_ as TRADING_LOG_EVENT_PARAM,
|
|
84
84
|
t_ as TRADING_PANEL_LOG_EVENT,
|
|
85
85
|
X_ as TRANSACTION_ERRORS,
|
|
86
|
-
m_ as
|
|
87
|
-
p_ as
|
|
88
|
-
i_ as
|
|
89
|
-
n_ as
|
|
90
|
-
|
|
91
|
-
x_ as
|
|
92
|
-
|
|
93
|
-
c_ as
|
|
94
|
-
|
|
95
|
-
h_ as
|
|
96
|
-
l_ as
|
|
97
|
-
y_ as
|
|
98
|
-
j_ as polygon
|
|
86
|
+
m_ as TRANSACTION_SETTLE_DELAY,
|
|
87
|
+
p_ as WBTC_BY_CHAIN_ID,
|
|
88
|
+
i_ as WETH_BY_CHAIN_ID,
|
|
89
|
+
n_ as WITHDRAW_SWAP_DATA_ERROR,
|
|
90
|
+
f_ as arbitrum,
|
|
91
|
+
x_ as base,
|
|
92
|
+
b_ as contractsAbisMap,
|
|
93
|
+
c_ as contractsAddressesMap,
|
|
94
|
+
g_ as hyperEvm,
|
|
95
|
+
h_ as mainnet,
|
|
96
|
+
l_ as optimism,
|
|
97
|
+
y_ as polygon
|
|
99
98
|
};
|
|
@@ -9,8 +9,13 @@ type ErrorsMap = Record<string, {
|
|
|
9
9
|
title: string;
|
|
10
10
|
hint?: string;
|
|
11
11
|
}>;
|
|
12
|
+
/**
|
|
13
|
+
* Sentinel "error messages" the widget itself emits for its own flows — these
|
|
14
|
+
* are not contract errors, so they can never come from the error registry.
|
|
15
|
+
* All contract revert copy comes from the registry fetched at runtime
|
|
16
|
+
* (core-kit/utils/error-registry.ts); nothing is duplicated here.
|
|
17
|
+
*/
|
|
12
18
|
export declare const TRANSACTION_ERRORS: ErrorsMap;
|
|
13
19
|
export declare const INVALID_PRICES_LIMIT_ORDER_TITLE = "Invalid limit order prices";
|
|
14
20
|
export declare const LIMIT_ORDER_TRANSACTION_ERRORS: ErrorsMap;
|
|
15
|
-
export declare const TRANSACTION_ERROR_KEYS: string[];
|
|
16
21
|
export {};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory client for the dHEDGE contract error registry — the single source
|
|
3
|
+
* of truth for contract revert copy (readmes/errorCodes/registry.json in
|
|
4
|
+
* github.com/dhedge/V2-Public).
|
|
5
|
+
*
|
|
6
|
+
* The registry is fetched at runtime (kicked off by ConfigProvider on mount)
|
|
7
|
+
* and kept in module memory; nothing is vendored into the codebase. Entries
|
|
8
|
+
* with `curated: false` carry generic placeholder copy and are dropped. Until
|
|
9
|
+
* the fetch resolves (or if it fails), decoding degrades gracefully to the
|
|
10
|
+
* widget's own sentinel entries and the generic fallback copy.
|
|
11
|
+
*/
|
|
12
|
+
export type ContractErrorCopy = {
|
|
13
|
+
title: string;
|
|
14
|
+
hint: string;
|
|
15
|
+
};
|
|
16
|
+
export type ContractSelectorErrorCopy = {
|
|
17
|
+
signature: string;
|
|
18
|
+
title: string;
|
|
19
|
+
hint: string;
|
|
20
|
+
};
|
|
21
|
+
export interface ContractErrorRegistry {
|
|
22
|
+
/**
|
|
23
|
+
* Human-reviewed copy for string reverts, keyed by the exact literal reason
|
|
24
|
+
* emitted via require(cond, "...") / revert("...").
|
|
25
|
+
*/
|
|
26
|
+
stringErrors: Record<string, ContractErrorCopy>;
|
|
27
|
+
/**
|
|
28
|
+
* Human-reviewed copy for custom Solidity errors, keyed by the 4-byte error
|
|
29
|
+
* selector (0x-prefixed, lowercase hex — the first 4 bytes of revert data).
|
|
30
|
+
*/
|
|
31
|
+
selectorErrors: Record<string, ContractSelectorErrorCopy>;
|
|
32
|
+
}
|
|
33
|
+
export declare const getContractErrorRegistry: () => ContractErrorRegistry;
|
|
34
|
+
/**
|
|
35
|
+
* Replace the in-memory registry. Exposed so hosts can inject a registry they
|
|
36
|
+
* fetched themselves and so tests can run against a fixture.
|
|
37
|
+
*/
|
|
38
|
+
export declare const applyContractErrorRegistry: (next: ContractErrorRegistry) => void;
|
|
39
|
+
export declare const fetchContractErrorRegistry: ({ timeoutMs, }?: {
|
|
40
|
+
timeoutMs?: number | undefined;
|
|
41
|
+
}) => Promise<ContractErrorRegistry>;
|
|
42
|
+
/**
|
|
43
|
+
* Idempotently load the registry into memory. Safe to call from multiple
|
|
44
|
+
* mount points; a failed attempt clears the latch so a later call retries.
|
|
45
|
+
*/
|
|
46
|
+
export declare const ensureContractErrorRegistryLoaded: () => Promise<void>;
|
|
@@ -6,6 +6,7 @@ export * from '../utils/transaction';
|
|
|
6
6
|
export * from '../utils/trading-result';
|
|
7
7
|
export * from '../utils/token';
|
|
8
8
|
export * from '../utils/error';
|
|
9
|
+
export * from '../utils/error-registry';
|
|
9
10
|
export * from '../utils/formatter';
|
|
10
11
|
export * from '../utils/ua';
|
|
11
12
|
export * from '../utils/flat-money';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const A=require("wagmi/chains"),a=require("./gmx-DJ0gqvLq.cjs"),p=require("bignumber.js"),d=require("viem"),it=typeof window<"u",ct=[{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"}],ut=[{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"}]}],dt=[{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"}],pt=[{inputs:[{internalType:"address",name:"_pool",type:"address"},{internalType:"uint256",name:"_poolTokenAmount",type:"uint256"}],name:"previewWithdrawal",outputs:[{name:"assetData",type:"tuple[]",components:dt}],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"}],lt=[{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"}],mt=[{type:"tuple",components:[{name:"actions",type:"tuple[]",components:[{name:"to",type:"address"},{name:"data",type:"bytes"}]},{name:"outputAsset",type:"address"},{name:"minOutputAmount",type:"uint256"}]}],yt=["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"],At=1,gt=1e4,I=2e6,Et=2e3,Tt=500,St=120,ht=300,_t=4,ft=/^dh\d{1,3}$/i,x=/[\u0000-\u001f\u007f]/,Dt=/https?:\/\/|[<>`]/i,bt=t=>t.length<=St&&!x.test(t)&&(ft.test(t)||t.length>=_t),T=t=>typeof t=="string"&&t.length>0&&t.length<=ht&&!x.test(t)&&!Dt.test(t),wt={stringErrors:{},selectorErrors:{}};let U=wt,_=null;const w=()=>U,F=t=>{U=t},Rt=t=>{const e=t;if(e?.schemaVersion!==At)throw new Error(`Unsupported error registry schemaVersion: ${String(e?.schemaVersion)}`);const n={};for(const[o,r]of Object.entries(e.stringErrors??{}))r?.curated===!0&&bt(o)&&T(r.description)&&T(r.action)&&(n[o]={title:r.description,hint:r.action});const s={};for(const[o,r]of Object.entries(e.selectorErrors??{}))r?.curated===!0&&/^0x[0-9a-f]{8}$/.test(o)&&T(r.signature)&&T(r.description)&&T(r.action)&&(s[o]={signature:r.signature,title:r.description,hint:r.action});if(!Object.keys(n).length)throw new Error("Error registry contained no curated string errors");if(Object.keys(n).length>Et||Object.keys(s).length>Tt)throw new Error("Error registry exceeded expected entry counts");return{stringErrors:n,selectorErrors:s}},v=async({timeoutMs:t=gt}={})=>{const e=[];for(const n of yt){const s=new AbortController,o=setTimeout(()=>s.abort(),t);try{const r=await fetch(n,{headers:{accept:"application/json"},signal:s.signal});if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=Number(r.headers.get("content-length"));if(i>I)throw new Error(`Response too large: ${i} bytes`);const c=await r.text();if(c.length>I)throw new Error(`Response too large: ${c.length} chars`);return Rt(JSON.parse(c))}catch(r){e.push(`${n}: ${r instanceof Error?r.message:String(r)}`)}finally{clearTimeout(o)}}throw new Error(`All error registry sources failed: ${e.join("; ")}`)},It=()=>(_??(_=v().then(F).catch(()=>{_=null})),_),Nt=()=>typeof window<"u";function Ct(){return Nt()&&typeof window.ethereum<"u"}async function Ot(t){try{if(Ct())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),S=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`)}},f=t=>t?d.pad(S(t),{size:32}):d.zeroHash,G=t=>{if(!t)throw new Error("Cannot decode an empty base64 string");return d.bytesToHex(Uint8Array.from(atob(t),e=>e.charCodeAt(0)))},W=(t,e)=>a.contractsAddressesMap[e]?.[t]??a.AddressZero,Pt=t=>a.contractsAbisMap[t],Lt=t=>t&&`${t.substring(0,6)}...${t.substring(t.length-4,t.length)}`,Bt=({address:t,chainId:e})=>{const n=W("aaveLendingPoolV3",e);return y(t,n)},$=({sourceAddress:t,amount:e})=>`${t}_${e}`,xt=(t,e)=>{const n=t.slice(0,e),s=t.slice(e);return{firstPart:n,secondPart:s}},H=(t,e)=>t/e*100,Ut=t=>t<1?4:t<10?3:2,Ft=(t,e=a.DEFAULT_PRECISION)=>new p(t.toString()).shiftedBy(e).toFixed(0),vt=(t,e,n,s)=>new p(e).dividedBy(n).multipliedBy(t).shiftedBy(-(s||a.DEFAULT_PRECISION)).toNumber(),Gt=t=>BigInt(new p(t||"0").shiftedBy(a.DEFAULT_PRECISION).toFixed(0,p.ROUND_DOWN)),Y=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))},Wt=({vaultAddress:t,swapData:e,sendTokenAddress:n,sendTokenAmount:s,vaultDepositTokenAddress:o,minVaultTokensReceivedAmount:r,routerKey:i="ONE_INCH",swapDestinationAmount:c,swapSlippage:u})=>{const l=new p(c).multipliedBy(1-u/100).toFixed(0),g=[d.stringToHex(i,{size:32}),e];return[t,[[n,s,g],[o,l]],r]},$t=({receiveAssetAddress:t,assets:e,swapData:n,slippage:s})=>{const o={srcData:[],destAmount:new p("0")},{srcData:r,destAmount:i}=e?.reduce((c,u)=>{const l=n?.[u.address];if(!l)return c;const g=[d.stringToHex(l.routerKey,{size:32}),l.rawTransaction.data],E=[u.address,u.rawBalance,g];return{srcData:[...c.srcData,E],destAmount:c.destAmount.plus(l.destinationAmount)}},o)??o;return[r,[t,i.times(1-s/100).toFixed(0,p.ROUND_DOWN)]]},V=({assetAddress:t,swapQuotes:e,swapParams:n,slippageToleranceForContractTransaction:s,routerKey:o})=>{if(!n)return{supportedAsset:t,withdrawData:"",slippageTolerance:BigInt(0)};const{srcData:r,dstData:i}=n,c=r.map(({asset:g,amount:E})=>{const h=e?.[$({sourceAddress:g,amount:E.toString()})]?.find(at=>at.routerKey===o);return{asset:g,amount:E,swapData:{routerKey:d.stringToHex(h?.routerKey??"",{size:32}),txData:h?.rawTransaction.data??"0x"}}}),u=d.encodeAbiParameters(a.ComplexWithdrawalAssetSrcDataAbiItem,[c]),l=d.encodeAbiParameters(a.ComplexWithdrawalDataAbiItem,[{encodedSrcData:u,dstData:{dstAddress:i.asset,dstAmount:i.amount},slippage:s}]);return{supportedAsset:t,withdrawData:l,slippageTolerance:s}},Ht=({chainId:t,txHash:e,error:n})=>{if(t!==A.mainnet.id||!e||!n)return!1;const s=n instanceof Error?n.message:String(n);return/\bNo Result\b/i.test(s)},Yt=({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 s=new p(n).multipliedBy(a.NATIVE_TOKEN_GAS_RESERVE_UNITS).shiftedBy(-e),o=new p(t).minus(s);return o.gt("0")?o:new p("0")},Kt=t=>a.STABLE_TOKEN_SYMBOLS.includes(t),qt=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},jt=(t,e=150)=>t.length>e?t.substring(0,e):t,k=()=>({...w().stringErrors,...a.TRANSACTION_ERRORS}),Xt=()=>[...Object.keys(k()),...Object.keys(a.LIMIT_ORDER_TRANSACTION_ERRORS)],Zt=/^dh\d+$/i,Qt=(t,e)=>Zt.test(e)?new RegExp(`\\b${e}\\b`,"i").test(t):t.includes(e.toLowerCase()),D=(t,e)=>{const n=t.toLowerCase();return[...e??Xt()].sort((s,o)=>o.length-s.length).find(s=>Qt(n,s))},N=t=>k()[t]??a.LIMIT_ORDER_TRANSACTION_ERRORS[t],zt=/\b0x[0-9a-f]{8}\b/i,Jt=t=>{const e=t.match(zt)?.[0]?.toLowerCase(),n=e?w().selectorErrors[e]:void 0;return n?{title:n.title,hint:n.hint}:void 0},te=({errorMessage:t,abiErrors:e})=>{if(!t||t.includes("User rejected"))return null;const n=e.find(i=>t.includes(i));if(n){const i=D(n);if(i)return N(i)}const s=D(t);if(s)return N(s);const o=Jt(t);if(o)return o;const[r]=t.split(n?".":"Contract").map(i=>i.trim());return{title:"Transaction failed",hint:`${jt(r??"")} ${n?`: ${n}`:""}`}},ee=t=>typeof t=="number"&&Number.isFinite(t),ne=t=>typeof t=="bigint"&&t!==BigInt(0),K=(t,e=a.DEFAULT_PRECISION$1)=>new p(t).shiftedBy(-e).toNumber(),q=t=>!isNaN(parseFloat(t))&&!isNaN(t),j=({value:t,minimumFractionDigits:e=2,maximumFractionDigits:n=2,compact:s=!1,normalize:o=!1})=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:s?"compact":void 0,minimumFractionDigits:e,maximumFractionDigits:n}).format(o?K(t):Number(t)),b=t=>q(t)?new p(t).toFixed():"",C=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"],X=({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[,r,i]=o;if(r.length>=e&&r.length<C.length)return`0.0${C[r.length]}${i.slice(0,3)}`}return b(n.toFixed(e))},Z=(t,e=0)=>`${t.toLocaleString("en-US",{maximumFractionDigits:e})}%`,se=t=>t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),re=(t,e,n=0)=>{const s=H(+t,e);return Z(s,n)},oe=({currency:t,value:e})=>t==="USD"?j({value:e}):`${a.CURRENCY_SYMBOL_MAP[t]} ${X({value:e,decimals:a.CURRENCY_DECIMALS_MAP[t]})}`,Q=(t,e)=>new p(new p(t).toFixed(e,p.ROUND_DOWN)).toString(),z=(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)}`},ae=({balance:t,symbol:e,precision:n,truncateSymbol:s})=>`${Q(t,n)} ${s?z(e):e}`,ie=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)}`},ce=t=>y(a.FLATMONEY_EARLY_DEPOSITOR_VAULT_ADDRESS_BASE,t)||y(a.FLATMONEY_DHT_STAKING_VAULT_ADDRESS_BASE,t),ue=t=>a.FLAT_MONEY_LEVERAGED_ASSET_ADDRESSES.some(e=>y(e,t)),de=t=>a.FLAT_MONEY_COLLATERAL_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},pe=t=>y(t,a.FLAT_MONEY_V1_UNIT_ADDRESS)?a.FLAT_MONEY_V1_UNIT_LINK:a.FLAT_MONEY_UNIT_LINK,J=t=>`eth_${t}`,le=({action:t,log:e,symbol:n,vaultAddress:s,chainId:o})=>{const r={[a.TRADING_LOG_EVENT_PARAM.SYMBOL.NAME]:n,[a.TRADING_LOG_EVENT_PARAM.CHAIN_ID.NAME]:o,[a.TRADING_LOG_EVENT_PARAM.ADDRESS.NAME]:J(s)};a.LOG_EVENT_BY_TRANSACTION_ACTION_MAP[t].forEach(i=>{e?.(i,r)})},me=t=>a.GMX_MARKET_ASSETS.some(e=>y(e,t)),ye=t=>a.GMX_WITHDRAW_ASSET_MAP[t.toLowerCase()]??{symbol:"",decimals:18,address:a.AddressZero},Ae=t=>a.GMX_WITHDRAW_ASSET_MAP_BY_VAULT_ADDRESS[t.toLowerCase()],tt="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 ge=t=>y(t,tt),Ee=()=>a.USDC_HYPEREVM,Te=new Map,R=(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}),et=t=>{const e=t.find(({swapQuotes:n})=>n);return e?.swapQuotes?Object.values(e.swapQuotes)[0]?.map(({routerKey:n})=>n)??[]:[]},nt=(t,e,n)=>t.map(({asset:s,swapParams:o,swapQuotes:r})=>!o||!r?{supportedAsset:s,withdrawData:"",slippageTolerance:n}:V({assetAddress:s,swapQuotes:r,swapParams:o,slippageToleranceForContractTransaction:n,routerKey:e})),st=async(t,e,n,s,o,r)=>{for(const i of t){const c=R(nt(e,i,n),r),{error:u}=await s(...o,c);if(!u)return c}return null},Se=(t,e,n)=>{const s=(t??[]).map(o=>({supportedAsset:o,withdrawData:"",slippageTolerance:e}));return R(s,n)},he=async(t,e,n,s,o)=>{for(const r of t){const i=Y(r);try{const c=await e(r),u=et(c),l=await st(u,c,i,n,s,o);if(l)return console.debug(`[Init Withdraw] Auto slippage simulation succeeded: slippage=${r}%`),console.debug("[Init Withdraw] Complex asset data:",l),l}catch(c){console.error(`[Init Withdraw] Failed to fetch quotes for slippage=${r}%:`,c)}}return null},_e=async(t,e,{fetchAaveSwapParams:n,fetchAaveSwapQuotes:s,withdrawAmountD18:o,slippage:r})=>Promise.all((t??[]).map(async i=>{if(!y(i,e))return{asset:i};try{const u=await n({withdrawAmountD18:o,slippage:r});if(u?.srcData.length){const l=await s({swapParams:u,slippage:r});return{asset:i,swapParams:u,swapQuotes:l}}return{asset:i}}catch(u){return console.error(u),{asset:i}}})),O=t=>Math.round(t*100)/100,fe=({maxSlippage:t,candidates:e=a.SLIPPAGE_AUTO_SIMULATION_CANDIDATES})=>{if(!Number.isFinite(t)||t<=0)return[];const n=O(Math.min(t,100)),s=e.filter(r=>r>0&&r<=n).map(O),o=new Set(s);return o.add(n),o.add(t),Array.from(o).sort((r,i)=>r-i)},M=1000000000000000000n,De=1000000n,P=10000n,L=100n,be=t=>({quotes:t.quotes.map(e=>({chainId:m(e.chainId,"chainId"),attestationId:m(e.attestationId,"attestationId"),userId:S(e.userId),asset:e.asset,price:m(e.price,"price"),quantity:m(e.quantity,"quantity"),expiration:m(e.expiration,"expiration"),side:Number(e.side),additionalData:S(e.additionalData)})),signatures:t.signatures.map(S)}),rt=(t,e,n)=>{const s=BigInt(Math.max(0,Math.round(n*100))),o=s>L?L:s,r=P-o,c=t*e/M*r*De,u=P*M;return(c+u-1n)/u},ot=(t,e)=>({chainId:e,attestationId:m(t.attestationId,"attestationId"),userId:f(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:f(t.additionalData)}),we=({attestation:t,chainId:e,slippagePercent:n})=>{const s=ot(t,e);return d.encodeAbiParameters(ut,[{attestationSignature:G(t.signature),quote:s,amountOutMinimum:rt(s.quantity,s.price,n)}])},Re=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(o=>o.accountId===n&&!o.isDebt),debt:t.find(o=>o.accountId===n&&o.isDebt)})),Ie=({collateral:t,dytmOffice:e,processor:n,gmToken:s,ondoGMSwap:o,usdc:r,gmAmount:i,amountOutMinimum:c,signature:u,quote:l})=>[{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:s,data:d.encodeFunctionData({abi:d.erc20Abi,functionName:"approve",args:[o,i]})},{to:o,data:d.encodeFunctionData({abi:lt,functionName:"swapExactInWithAttestation",args:[s,i,r,c,u,l]})}],Ne=({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:B,functionName:"repay",args:[{account:t,key:e,withCollateralType:0,assets:d.maxUint256,shares:0n,extraData:"0x"}]})}],Ce=({actions:t,outputAsset:e,minOutputAmount:n})=>d.encodeAbiParameters(mt,[{actions:t,outputAsset:e,minOutputAmount:n}]);exports.DytmOfficeAssetGuardAbi=pt;exports.EMPTY_PER_ASSET_WITHDRAW_DATA=Te;exports.HYPERLIQUID_PERPS_ACCOUNT_ADDRESS=tt;exports.OndoGMTokenAssetGuardAbi=ct;exports.addTokenToWallet=Ot;exports.applyContractErrorRegistry=F;exports.base64ToHex=G;exports.buildAaveWithdrawAssetTransactionData=V;exports.buildComplexAssetDataForRouter=nt;exports.buildDytmActions=Ie;exports.buildDytmRepayActions=Ne;exports.buildSwapQuoteKeyForAave=$;exports.buildSwapWithdrawTransactionData=$t;exports.buildZapDepositTransactionArguments=Wt;exports.clientSide=it;exports.commify=se;exports.computeAmountOutMinimumUsdc=rt;exports.createDefaultComplexAssetData=Se;exports.encodeOndoWithdrawData=we;exports.encodeUnwindPlan=Ce;exports.enrichAssetsWithSwapQuotes=_e;exports.ensureContractErrorRegistryLoaded=It;exports.ensureHexPrefix=S;exports.extractAvailableRouterKeys=et;exports.fetchContractErrorRegistry=v;exports.formatBalance=Q;exports.formatByCurrency=oe;exports.formatNumberToLimitedDecimals=X;exports.formatNumeratorToPercentage=re;exports.formatPercentage=Z;exports.formatToUsd=j;exports.formatTokenBalance=ae;exports.getAutoSlippageSimulationCandidates=fe;exports.getContractAbiById=Pt;exports.getContractAddressById=W;exports.getContractErrorRegistry=w;exports.getConventionalTokenPriceDecimals=Ut;exports.getErrorKey=D;exports.getFlatMoneyCollateralByLeverageAddress=de;exports.getFlatMoneyLinkByUnitAddress=pe;exports.getGmxWithdrawAssetByLeverageAddress=ye;exports.getGmxWithdrawAssetByVaultAddress=Ae;exports.getHyperliquidWithdrawAsset=Ee;exports.getNativeTokenInvestableBalance=kt;exports.getPercent=H;exports.getPoolFraction=vt;exports.getSettleDelay=Yt;exports.getSlippageToleranceForContractTransaction=Y;exports.getTxHashShort=ie;exports.groupPreviewByAccount=Re;exports.isAaveLendAndBorrowAsset=Bt;exports.isEqualAddress=y;exports.isFlatMoneyLeveragedAsset=ue;exports.isFmpAirdropVaultAddress=ce;exports.isGmxLeveragedAsset=me;exports.isHyperliquidPerpsAsset=ge;exports.isNativeToken=Vt;exports.isNumberType=ee;exports.isNumeric=q;exports.isStableSymbol=Kt;exports.isZeroAddress=Mt;exports.logTransactionByActionType=le;exports.mapAttestationToOndoQuote=ot;exports.mapOndoApiResponseToUpdatePricesArgs=be;exports.nonZeroBigInt=ne;exports.normalizeNumber=K;exports.overlayWithdrawData=R;exports.parseAmountToD18=Gt;exports.parseContractErrorMessage=te;exports.removeInsignificantTrailingZeros=b;exports.shiftBy=Ft;exports.shortenAddress=Lt;exports.shouldSwallowMainnetPollError=Ht;exports.sliceByIndex=xt;exports.toBigInt=m;exports.toBytes32Hex=f;exports.transformAddressForAnalytics=J;exports.truncateString=z;exports.tryEstimateWithRouters=st;exports.tryEstimateWithSlippageValues=he;exports.validateLoggerEventParams=qt;
|