@dhedge/trading-widget 6.2.2 → 6.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1015 @@
1
+ import { hyperEvm as W, mainnet as I, polygon as st, optimism as at, base as rt, arbitrum as ot } from "wagmi/chains";
2
+ import { aq as it, ao as ct, ap as ut, a as R, q as N, ar as dt, as as pt, a5 as lt, ak as mt, a3 as yt, b as gt, ae as At, Z as k, aj as Et, at as q, e as ht, d as ft, M as St, R as Tt, P as wt, au as _t, av as bt, Q as Dt, N as It, ah as w, _ as Rt, W as Nt, X as Ot, U as Ct, aw as V, ax as xt, ay as Bt, az as Lt, aA as Mt, aB as Pt, ad as Ut } from "./gmx-Cyz_GmV5.js";
3
+ import d from "bignumber.js";
4
+ import { zeroHash as $t, bytesToHex as vt, pad as Ft, stringToHex as O, encodeAbiParameters as T, encodeFunctionData as A, erc20Abi as K, maxUint256 as b } from "viem";
5
+ const x = "application/json";
6
+ class j extends Error {
7
+ constructor(e, n, s) {
8
+ super(`HTTP ${e}${s ? `: ${s}` : ""}`), this.name = "FetchRequestError", this.status = e, this.statusText = n, this.body = s;
9
+ }
10
+ }
11
+ const Ke = (t) => {
12
+ if (!(t instanceof j) || !t.body)
13
+ return null;
14
+ try {
15
+ return JSON.parse(t.body);
16
+ } catch {
17
+ return null;
18
+ }
19
+ }, Yt = (t) => typeof t == "string" || t instanceof FormData || t instanceof URLSearchParams || t instanceof Blob || t instanceof ArrayBuffer || ArrayBuffer.isView(t), Gt = (t, e) => {
20
+ const n = String(t), s = e ? new URLSearchParams(e).toString() : "";
21
+ if (!s)
22
+ return n;
23
+ const a = n.indexOf("#"), r = a === -1 ? n : n.slice(0, a), o = a === -1 ? "" : n.slice(a);
24
+ return `${r}${r.includes("?") ? "&" : "?"}${s}${o}`;
25
+ }, Ht = (t, e) => {
26
+ const n = new AbortController(), s = () => n.abort();
27
+ e?.aborted && s();
28
+ const a = setTimeout(s, t);
29
+ return e?.addEventListener("abort", s), {
30
+ signal: n.signal,
31
+ cleanup: () => {
32
+ clearTimeout(a), e?.removeEventListener("abort", s);
33
+ }
34
+ };
35
+ }, Wt = async (t, e, n) => {
36
+ if (n === void 0)
37
+ return await t[e]();
38
+ const s = Number(t.headers.get("content-length"));
39
+ if (s > n)
40
+ throw new Error(`Response too large: ${s} bytes`);
41
+ if (e === "blob" || e === "arrayBuffer") {
42
+ const r = await t[e](), o = r instanceof Blob ? r.size : r.byteLength;
43
+ if (o > n)
44
+ throw new Error(`Response too large: ${o} bytes`);
45
+ return r;
46
+ }
47
+ const a = await t.text();
48
+ if (a.length > n)
49
+ throw new Error(`Response too large: ${a.length} chars`);
50
+ return e === "json" ? JSON.parse(a) : a;
51
+ }, kt = async ({
52
+ url: t,
53
+ headers: e,
54
+ method: n,
55
+ body: s,
56
+ params: a,
57
+ signal: r,
58
+ readMethod: o = "json",
59
+ cache: c,
60
+ timeoutMs: i,
61
+ maxResponseBytes: u
62
+ }) => {
63
+ const l = s !== void 0 && n !== "GET", g = l && !Yt(s), m = new Headers(e);
64
+ o === "json" && !m.has("Accept") && m.set("Accept", x), g && !m.has("Content-Type") && m.set("Content-Type", x);
65
+ const f = i ? Ht(i, r) : void 0, nt = {
66
+ method: n,
67
+ headers: m,
68
+ signal: f?.signal ?? r,
69
+ ...c && { cache: c },
70
+ ...l && { body: g ? JSON.stringify(s) : s }
71
+ };
72
+ try {
73
+ const E = await fetch(Gt(t, a), nt);
74
+ if (!E.ok)
75
+ throw new j(E.status, E.statusText, await E.text().catch(() => ""));
76
+ return await Wt(E, o, u);
77
+ } finally {
78
+ f?.cleanup();
79
+ }
80
+ }, je = typeof window < "u", Xe = [
81
+ {
82
+ inputs: [
83
+ { internalType: "address", name: "_pool", type: "address" },
84
+ { internalType: "address", name: "_asset", type: "address" },
85
+ { internalType: "uint256", name: "_poolTokenAmount", type: "uint256" }
86
+ ],
87
+ name: "previewGmTokenAmount",
88
+ outputs: [
89
+ { internalType: "uint256", name: "gmTokenAmount", type: "uint256" }
90
+ ],
91
+ stateMutability: "nonpayable",
92
+ type: "function"
93
+ },
94
+ {
95
+ inputs: [],
96
+ name: "ondoGMSwap",
97
+ outputs: [{ internalType: "address", name: "", type: "address" }],
98
+ stateMutability: "view",
99
+ type: "function"
100
+ },
101
+ {
102
+ inputs: [],
103
+ name: "usdc",
104
+ outputs: [{ internalType: "address", name: "", type: "address" }],
105
+ stateMutability: "view",
106
+ type: "function"
107
+ }
108
+ ], qt = [
109
+ {
110
+ type: "tuple",
111
+ components: [
112
+ { name: "attestationSignature", type: "bytes" },
113
+ {
114
+ name: "quote",
115
+ type: "tuple",
116
+ components: [
117
+ { name: "chainId", type: "uint256" },
118
+ { name: "attestationId", type: "uint256" },
119
+ { name: "userId", type: "bytes32" },
120
+ { name: "asset", type: "address" },
121
+ { name: "price", type: "uint256" },
122
+ { name: "quantity", type: "uint256" },
123
+ { name: "expiration", type: "uint256" },
124
+ { name: "side", type: "uint8" },
125
+ { name: "additionalData", type: "bytes32" }
126
+ ]
127
+ },
128
+ { name: "amountOutMinimum", type: "uint256" }
129
+ ]
130
+ }
131
+ ], Vt = [
132
+ { name: "asset", type: "address" },
133
+ { name: "amount", type: "uint256" },
134
+ { name: "assetType", type: "uint16" },
135
+ { name: "isPool", type: "bool" },
136
+ { name: "isDebt", type: "bool" },
137
+ { name: "marketId", type: "uint88" },
138
+ { name: "accountId", type: "uint256" },
139
+ { name: "tokenId", type: "uint256" },
140
+ { name: "debtKey", type: "uint248" },
141
+ { name: "shares", type: "uint256" }
142
+ ], ze = [
143
+ {
144
+ inputs: [
145
+ { internalType: "address", name: "_pool", type: "address" },
146
+ { internalType: "uint256", name: "_poolTokenAmount", type: "uint256" }
147
+ ],
148
+ name: "previewWithdrawal",
149
+ outputs: [
150
+ {
151
+ name: "assetData",
152
+ type: "tuple[]",
153
+ components: Vt
154
+ }
155
+ ],
156
+ stateMutability: "nonpayable",
157
+ type: "function"
158
+ },
159
+ {
160
+ inputs: [],
161
+ name: "dytmWithdrawProcessor",
162
+ outputs: [{ name: "", type: "address" }],
163
+ stateMutability: "view",
164
+ type: "function"
165
+ }
166
+ ], C = [
167
+ {
168
+ inputs: [
169
+ {
170
+ name: "params",
171
+ type: "tuple",
172
+ components: [
173
+ { name: "account", type: "uint256" },
174
+ { name: "tokenId", type: "uint256" },
175
+ { name: "receiver", type: "address" },
176
+ { name: "assets", type: "uint256" },
177
+ { name: "shares", type: "uint256" },
178
+ { name: "extraData", type: "bytes" }
179
+ ]
180
+ }
181
+ ],
182
+ name: "withdraw",
183
+ outputs: [{ name: "assets", type: "uint256" }],
184
+ stateMutability: "nonpayable",
185
+ type: "function"
186
+ },
187
+ {
188
+ inputs: [
189
+ {
190
+ name: "params",
191
+ type: "tuple",
192
+ components: [
193
+ { name: "account", type: "uint256" },
194
+ { name: "key", type: "uint248" },
195
+ // DytmParamStructs.TokenType enum — 0 = NONE.
196
+ { name: "withCollateralType", type: "uint8" },
197
+ { name: "assets", type: "uint256" },
198
+ { name: "shares", type: "uint256" },
199
+ { name: "extraData", type: "bytes" }
200
+ ]
201
+ }
202
+ ],
203
+ name: "repay",
204
+ outputs: [{ name: "assetsRepaid", type: "uint256" }],
205
+ stateMutability: "nonpayable",
206
+ type: "function"
207
+ }
208
+ ], Kt = [
209
+ {
210
+ inputs: [
211
+ { name: "tokenIn", type: "address" },
212
+ { name: "amountIn", type: "uint256" },
213
+ { name: "tokenOut", type: "address" },
214
+ { name: "amountOutMinimum", type: "uint256" },
215
+ { name: "attestationSignature", type: "bytes" },
216
+ {
217
+ name: "quote",
218
+ type: "tuple",
219
+ components: [
220
+ { name: "chainId", type: "uint256" },
221
+ { name: "attestationId", type: "uint256" },
222
+ { name: "userId", type: "bytes32" },
223
+ { name: "asset", type: "address" },
224
+ { name: "price", type: "uint256" },
225
+ { name: "quantity", type: "uint256" },
226
+ { name: "expiration", type: "uint256" },
227
+ { name: "side", type: "uint8" },
228
+ { name: "additionalData", type: "bytes32" }
229
+ ]
230
+ }
231
+ ],
232
+ name: "swapExactInWithAttestation",
233
+ outputs: [],
234
+ stateMutability: "nonpayable",
235
+ type: "function"
236
+ }
237
+ ], jt = [
238
+ {
239
+ type: "tuple",
240
+ components: [
241
+ {
242
+ name: "actions",
243
+ type: "tuple[]",
244
+ components: [
245
+ { name: "to", type: "address" },
246
+ { name: "data", type: "bytes" }
247
+ ]
248
+ },
249
+ { name: "outputAsset", type: "address" },
250
+ { name: "minOutputAmount", type: "uint256" }
251
+ ]
252
+ }
253
+ ], D = {
254
+ stringErrors: {
255
+ // Ondo tokenized assets trade only during market hours; the full message
256
+ // includes a dynamic reopen time (e.g. "QUBTon is currently closed for
257
+ // trading. It will be open in 29 minutes."), so there is no fixed literal
258
+ // the registry could key on.
259
+ "currently closed for trading": {
260
+ title: "The market for this tokenized asset is closed right now",
261
+ hint: "Wait until the market reopens (the error message says when) and simply retry."
262
+ },
263
+ // Synthetix revert hit when a vault still holds deprecated synths.
264
+ "Synth exchange suspended. Operation prohibited": {
265
+ title: "Vault includes deprecated synths in portfolio",
266
+ hint: "Redeem deprecated synth to be able to withdraw."
267
+ }
268
+ },
269
+ selectorErrors: {
270
+ // EasySwapperV2 swap periphery (see core-kit/abi/easy-swapper-v2.ts).
271
+ "0x54971d46": {
272
+ signature: "SwapFailed(address,(address,uint256,(bytes32,bytes)),bytes)",
273
+ title: "The token swap failed to execute",
274
+ hint: "Your assets are still in your wallet — try again, or retry with a higher slippage tolerance."
275
+ },
276
+ "0x81a815ef": {
277
+ signature: "InsufficientAmountReceived(address,uint256,uint256)",
278
+ title: "Swap output was below the minimum received amount",
279
+ hint: "Increase slippage tolerance and try again."
280
+ }
281
+ }
282
+ }, X = (t) => ({
283
+ stringErrors: {
284
+ ...t.stringErrors,
285
+ ...D.stringErrors
286
+ },
287
+ selectorErrors: {
288
+ ...t.selectorErrors,
289
+ ...D.selectorErrors
290
+ }
291
+ }), Xt = [
292
+ "https://cdn.jsdelivr.net/gh/dhedge/V2-Public@master/readmes/errorCodes/registry.json",
293
+ "https://raw.githubusercontent.com/dhedge/V2-Public/master/readmes/errorCodes/registry.json"
294
+ ], zt = 1, Qt = 1e4, Zt = 2e6, Jt = 2e3, te = 500, ee = 120, ne = 300, se = 4, ae = /^dh\d{1,3}$/i, z = /[\u0000-\u001f\u007f]/, re = /https?:\/\/|[<>`]/i, oe = (t) => t.length <= ee && !z.test(t) && (ae.test(t) || t.length >= se), h = (t) => typeof t == "string" && t.length > 0 && t.length <= ne && !z.test(t) && !re.test(t);
295
+ let Q = D, _ = null;
296
+ const Z = () => Q, ie = (t) => {
297
+ Q = X(t);
298
+ }, ce = (t) => {
299
+ const e = t;
300
+ if (e?.schemaVersion !== zt)
301
+ throw new Error(
302
+ `Unsupported error registry schemaVersion: ${String(e?.schemaVersion)}`
303
+ );
304
+ const n = {};
305
+ for (const [a, r] of Object.entries(e.stringErrors ?? {}))
306
+ r?.curated === !0 && oe(a) && h(r.description) && h(r.action) && (n[a] = { title: r.description, hint: r.action });
307
+ const s = {};
308
+ for (const [a, r] of Object.entries(e.selectorErrors ?? {}))
309
+ r?.curated === !0 && /^0x[0-9a-f]{8}$/.test(a) && h(r.signature) && h(r.description) && h(r.action) && (s[a] = {
310
+ signature: r.signature,
311
+ title: r.description,
312
+ hint: r.action
313
+ });
314
+ if (!Object.keys(n).length)
315
+ throw new Error("Error registry contained no curated string errors");
316
+ if (Object.keys(n).length > Jt || Object.keys(s).length > te)
317
+ throw new Error("Error registry exceeded expected entry counts");
318
+ return { stringErrors: n, selectorErrors: s };
319
+ }, ue = async ({
320
+ timeoutMs: t = Qt
321
+ } = {}) => {
322
+ const e = [];
323
+ for (const n of Xt)
324
+ try {
325
+ const s = await kt({
326
+ url: n,
327
+ method: "GET",
328
+ timeoutMs: t,
329
+ maxResponseBytes: Zt
330
+ });
331
+ return X(ce(s));
332
+ } catch (s) {
333
+ e.push(
334
+ `${n}: ${s instanceof Error ? s.message : String(s)}`
335
+ );
336
+ }
337
+ throw new Error(`All error registry sources failed: ${e.join("; ")}`);
338
+ }, Qe = () => (_ ?? (_ = ue().then(ie).catch(() => {
339
+ _ = null;
340
+ })), _), de = () => typeof window < "u";
341
+ function pe() {
342
+ return de() && typeof window.ethereum < "u";
343
+ }
344
+ async function Ze(t) {
345
+ try {
346
+ if (pe())
347
+ return window.ethereum.request({
348
+ method: "wallet_watchAsset",
349
+ params: {
350
+ type: "ERC20",
351
+ options: t
352
+ }
353
+ });
354
+ } catch {
355
+ return !1;
356
+ }
357
+ return !1;
358
+ }
359
+ const p = (t, e) => t?.toLowerCase() === e?.toLowerCase(), Je = (t) => p(t, it), S = (t) => {
360
+ if (!t) throw new Error("Cannot prefix an empty hex value");
361
+ return t.startsWith("0x") ? t : `0x${t}`;
362
+ }, y = (t, e) => {
363
+ try {
364
+ return BigInt(t);
365
+ } catch {
366
+ throw new Error(`Cannot convert "${e}" value "${t}" to bigint`);
367
+ }
368
+ }, B = (t) => t ? Ft(S(t), { size: 32 }) : $t, le = (t) => {
369
+ if (!t) throw new Error("Cannot decode an empty base64 string");
370
+ return vt(Uint8Array.from(atob(t), (e) => e.charCodeAt(0)));
371
+ }, me = (t, e) => ut[e]?.[t] ?? R, tn = (t) => ct[t], en = (t) => t && `${t.substring(0, 6)}...${t.substring(
372
+ t.length - 4,
373
+ t.length
374
+ )}`, nn = ({
375
+ address: t,
376
+ chainId: e
377
+ }) => {
378
+ const n = me(
379
+ "aaveLendingPoolV3",
380
+ e
381
+ );
382
+ return p(t, n);
383
+ }, ye = ({
384
+ sourceAddress: t,
385
+ amount: e
386
+ }) => `${t}_${e}`, sn = (t, e) => {
387
+ const n = t.slice(0, e), s = t.slice(e);
388
+ return { firstPart: n, secondPart: s };
389
+ }, ge = (t, e) => t / e * 100, an = (t) => t < 1 ? 4 : t < 10 ? 3 : 2, rn = (t, e = N) => new d(t.toString()).shiftedBy(e).toFixed(0), on = (t, e, n, s) => new d(e).dividedBy(n).multipliedBy(t).shiftedBy(-(s || N)).toNumber(), cn = (t) => BigInt(
390
+ new d(t || "0").shiftedBy(N).toFixed(0, d.ROUND_DOWN)
391
+ ), J = (t) => {
392
+ const e = new d(0.01), n = new d(t), s = !n.isZero() && n.lt(e) ? e : n;
393
+ return BigInt(s.multipliedBy(100).toFixed(0));
394
+ }, un = ({
395
+ chainId: t,
396
+ slippage: e
397
+ }) => t === W.id ? BigInt(0) : J(e), dn = ({
398
+ vaultAddress: t,
399
+ swapData: e,
400
+ sendTokenAddress: n,
401
+ sendTokenAmount: s,
402
+ vaultDepositTokenAddress: a,
403
+ minVaultTokensReceivedAmount: r,
404
+ routerKey: o = "ONE_INCH",
405
+ swapDestinationAmount: c,
406
+ swapSlippage: i
407
+ }) => {
408
+ const u = new d(c).multipliedBy(1 - i / 100).toFixed(0), l = [O(o, { size: 32 }), e];
409
+ return [t, [[n, s, l], [a, u]], r];
410
+ }, pn = ({
411
+ receiveAssetAddress: t,
412
+ assets: e,
413
+ swapData: n,
414
+ slippage: s
415
+ }) => {
416
+ const a = {
417
+ srcData: [],
418
+ destAmount: new d("0")
419
+ }, { srcData: r, destAmount: o } = e?.reduce((c, i) => {
420
+ const u = n?.[i.address];
421
+ if (!u)
422
+ return c;
423
+ const l = [
424
+ O(u.routerKey, { size: 32 }),
425
+ u.rawTransaction.data
426
+ ], g = [i.address, i.rawBalance, l];
427
+ return {
428
+ srcData: [...c.srcData, g],
429
+ destAmount: c.destAmount.plus(u.destinationAmount)
430
+ };
431
+ }, a) ?? a;
432
+ return [
433
+ r,
434
+ [
435
+ t,
436
+ o.times(1 - s / 100).toFixed(0, d.ROUND_DOWN)
437
+ ]
438
+ ];
439
+ }, Ae = ({
440
+ assetAddress: t,
441
+ swapQuotes: e,
442
+ swapParams: n,
443
+ slippageToleranceForContractTransaction: s,
444
+ routerKey: a
445
+ }) => {
446
+ if (!n)
447
+ return {
448
+ supportedAsset: t,
449
+ withdrawData: "",
450
+ slippageTolerance: BigInt(0)
451
+ };
452
+ const { srcData: r, dstData: o } = n, c = r.map(({ asset: l, amount: g }) => {
453
+ const m = e?.[ye({
454
+ sourceAddress: l,
455
+ amount: g.toString()
456
+ })]?.find((f) => f.routerKey === a);
457
+ return {
458
+ asset: l,
459
+ amount: g,
460
+ swapData: {
461
+ routerKey: O(m?.routerKey ?? "", { size: 32 }),
462
+ txData: m?.rawTransaction.data ?? "0x"
463
+ }
464
+ };
465
+ }), i = T(
466
+ dt,
467
+ [c]
468
+ ), u = T(pt, [
469
+ {
470
+ encodedSrcData: i,
471
+ dstData: {
472
+ dstAddress: o.asset,
473
+ dstAmount: o.amount
474
+ },
475
+ slippage: s
476
+ }
477
+ ]);
478
+ return {
479
+ supportedAsset: t,
480
+ withdrawData: u,
481
+ slippageTolerance: s
482
+ };
483
+ }, ln = ({
484
+ chainId: t,
485
+ txHash: e,
486
+ error: n
487
+ }) => {
488
+ if (t !== I.id || !e || !n)
489
+ return !1;
490
+ const s = n instanceof Error ? n.message : String(n);
491
+ return /\bNo Result\b/i.test(s);
492
+ }, mn = ({
493
+ chainId: t,
494
+ action: e,
495
+ isRabbyWallet: n
496
+ }) => e === "update_ondo_prices" && t === I.id && n ? lt : t ? mt[t] ?? 0 : 0, yn = (t, e) => gt[e]?.nativeTokenSymbol === t, gn = ({
497
+ nativeTokenBalance: t,
498
+ tokenDecimals: e,
499
+ gasPrice: n
500
+ }) => {
501
+ const s = new d(n).multipliedBy(yt).shiftedBy(-e), a = new d(t).minus(
502
+ s
503
+ );
504
+ return a.gt("0") ? a : new d("0");
505
+ }, An = (t) => At.includes(t), En = (t) => {
506
+ const e = Object.values(t).reduce(
507
+ (n, { type: s }) => (n[s] = n[s] + 1, n),
508
+ { string: 0, number: 0 }
509
+ );
510
+ if (e.string > 10)
511
+ throw new Error("logger params must contain up to 10 string values");
512
+ if (e.number > 40)
513
+ throw new Error("logger params must contain up to 40 numeric values");
514
+ return !0;
515
+ }, Ee = (t, e = 150) => t.length > e ? t.substring(0, e) : t, tt = () => ({
516
+ ...Z().stringErrors,
517
+ ...Et
518
+ }), he = () => [
519
+ ...Object.keys(tt()),
520
+ ...Object.keys(k)
521
+ ], fe = /^dh\d+$/i, Se = (t, e) => fe.test(e) ? new RegExp(`\\b${e}\\b`, "i").test(t) : t.includes(e.toLowerCase()), L = (t, e) => {
522
+ const n = t.toLowerCase();
523
+ return [...e ?? he()].sort((s, a) => a.length - s.length).find((s) => Se(n, s));
524
+ }, M = (t) => tt()[t] ?? k[t], Te = /\b0x[0-9a-f]{8}\b/i, we = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), _e = (t) => {
525
+ const { selectorErrors: e } = Z(), n = t.match(Te)?.[0]?.toLowerCase(), s = n ? e[n] : void 0;
526
+ if (s)
527
+ return { title: s.title, hint: s.hint };
528
+ const a = Object.values(e).find(
529
+ (r) => new RegExp(
530
+ `\\b${we(r.signature.split("(")[0] ?? "")}\\b`
531
+ ).test(t)
532
+ );
533
+ return a ? { title: a.title, hint: a.hint } : void 0;
534
+ }, hn = ({
535
+ errorMessage: t,
536
+ abiErrors: e
537
+ }) => {
538
+ if (!t || t.includes("User rejected"))
539
+ return null;
540
+ const n = e.find((o) => t.includes(o));
541
+ if (n) {
542
+ const o = L(n);
543
+ if (o)
544
+ return M(o);
545
+ }
546
+ const s = L(t);
547
+ if (s)
548
+ return M(s);
549
+ const a = _e(t);
550
+ if (a)
551
+ return a;
552
+ const [r] = t.split(n ? "." : "Contract").map((o) => o.trim());
553
+ return {
554
+ title: "Transaction failed",
555
+ hint: `${Ee(r ?? "")} ${n ? `: ${n}` : ""}`
556
+ };
557
+ }, fn = (t) => typeof t == "number" && Number.isFinite(t), Sn = (t) => typeof t == "bigint" && t !== BigInt(0), be = (t, e = q) => new d(t).shiftedBy(-e).toNumber(), De = (t) => !isNaN(parseFloat(t)) && !isNaN(t), Ie = ({
558
+ value: t,
559
+ minimumFractionDigits: e = 2,
560
+ maximumFractionDigits: n = 2,
561
+ compact: s = !1,
562
+ normalize: a = !1
563
+ }) => new Intl.NumberFormat("en-US", {
564
+ style: "currency",
565
+ currency: "USD",
566
+ notation: s ? "compact" : void 0,
567
+ minimumFractionDigits: e,
568
+ maximumFractionDigits: n
569
+ }).format(a ? be(t) : Number(t)), P = (t) => De(t) ? new d(t).toFixed() : "", U = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"], Re = ({
570
+ value: t,
571
+ decimals: e = 4
572
+ }) => {
573
+ const n = new d(t);
574
+ if (n.isGreaterThan(1) || n.isZero())
575
+ return P(n.toFixed(e));
576
+ const a = (/e/i.test(t.toString()) ? parseFloat(t.toString()).toFixed(q) : t.toString()).match(/^0\.(0+)(\d+)$/);
577
+ if (a) {
578
+ const [, r, o] = a;
579
+ if (r.length >= e && r.length < U.length)
580
+ return `0.0${U[r.length]}${o.slice(0, 3)}`;
581
+ }
582
+ return P(n.toFixed(e));
583
+ }, Ne = (t, e = 0) => `${t.toLocaleString("en-US", { maximumFractionDigits: e })}%`, Tn = (t) => t.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), wn = (t, e, n = 0) => {
584
+ const s = ge(+t, e);
585
+ return Ne(s, n);
586
+ }, _n = ({
587
+ currency: t,
588
+ value: e
589
+ }) => t === "USD" ? Ie({ value: e }) : `${ht[t]} ${Re({
590
+ value: e,
591
+ decimals: ft[t]
592
+ })}`, Oe = (t, e) => new d(
593
+ new d(t).toFixed(e, d.ROUND_DOWN)
594
+ ).toString(), Ce = (t, e = 3, n = 2) => {
595
+ if (t.length <= 5)
596
+ return t;
597
+ const s = "...";
598
+ return t.length <= e + n + s.length ? t : `${t.slice(0, e)}${s}${t.slice(-n)}`;
599
+ }, bn = ({
600
+ balance: t,
601
+ symbol: e,
602
+ precision: n,
603
+ truncateSymbol: s
604
+ }) => `${Oe(t, n)} ${s ? Ce(e) : e}`, Dn = (t) => {
605
+ if (!t)
606
+ return;
607
+ const e = t.match(/0x[a-fA-F0-9]{64}/);
608
+ if (!e)
609
+ return;
610
+ const n = e[0];
611
+ return `${n.slice(0, 4)}...${n.slice(-3)}`;
612
+ }, In = (t) => p(_t, t) || p(bt, t), Rn = (t) => It.some(
613
+ (e) => p(e, t)
614
+ ), Nn = (t) => St[t.toLowerCase()] ?? {
615
+ symbol: "",
616
+ decimals: 18,
617
+ address: R
618
+ }, On = (t) => p(t, Dt) ? Tt : wt, xe = (t) => `eth_${t}`, Cn = ({
619
+ action: t,
620
+ log: e,
621
+ symbol: n,
622
+ vaultAddress: s,
623
+ chainId: a
624
+ }) => {
625
+ const r = {
626
+ [w.SYMBOL.NAME]: n,
627
+ [w.CHAIN_ID.NAME]: a,
628
+ [w.ADDRESS.NAME]: xe(s)
629
+ };
630
+ Rt[t].forEach((o) => {
631
+ e?.(o, r);
632
+ });
633
+ }, xn = (t) => Ct.some((e) => p(e, t)), Bn = (t) => Nt[t.toLowerCase()] ?? {
634
+ symbol: "",
635
+ decimals: 18,
636
+ address: R
637
+ }, Ln = (t) => Ot[t.toLowerCase()], Be = "0x3333333333333333333333333333333333333333";
638
+ ot.id + "", Pt.address, rt.id + "", Mt.address, at.id + "", Lt.address, st.id + "", Bt.address, I.id + "", xt.address, W.id + "", V.address;
639
+ const Le = "0x2222222222222222222222222222222222222222", $ = BigInt("0x2000000000000000000000000000000000000000"), Me = 10000n, Pe = (t) => p(t, Be), Ue = (t) => {
640
+ if (p(t, Le))
641
+ return !0;
642
+ try {
643
+ const e = BigInt(t);
644
+ return e >= $ && e < $ + Me;
645
+ } catch {
646
+ return !1;
647
+ }
648
+ }, Mn = (t) => Pe(t) || Ue(t), Pn = () => V, Un = /* @__PURE__ */ new Map(), et = (t, e) => !e || e.size === 0 ? t : t.map((n) => {
649
+ const s = e.get(
650
+ n.supportedAsset.toLowerCase()
651
+ );
652
+ return s ? {
653
+ ...n,
654
+ withdrawData: s.withdrawData,
655
+ slippageTolerance: s.slippageTolerance
656
+ } : n;
657
+ }), $e = (t) => {
658
+ const e = t.find(
659
+ ({ swapQuotes: n }) => n
660
+ );
661
+ return e?.swapQuotes ? Object.values(e.swapQuotes)[0]?.map(
662
+ ({ routerKey: n }) => n
663
+ ) ?? [] : [];
664
+ }, ve = (t, e, n) => t.map(({ asset: s, swapParams: a, swapQuotes: r }) => !a || !r ? {
665
+ supportedAsset: s,
666
+ withdrawData: "",
667
+ slippageTolerance: n
668
+ } : Ae({
669
+ assetAddress: s,
670
+ swapQuotes: r,
671
+ swapParams: a,
672
+ slippageToleranceForContractTransaction: n,
673
+ routerKey: e
674
+ })), Fe = async (t, e, n, s, a, r) => {
675
+ for (const o of t) {
676
+ const c = et(
677
+ ve(
678
+ e,
679
+ o,
680
+ n
681
+ ),
682
+ r
683
+ ), { error: i } = await s(...a, c);
684
+ if (!i)
685
+ return c;
686
+ }
687
+ return null;
688
+ }, $n = (t, e, n) => {
689
+ const s = (t ?? []).map((a) => ({
690
+ supportedAsset: a,
691
+ withdrawData: "",
692
+ slippageTolerance: e
693
+ }));
694
+ return et(s, n);
695
+ }, vn = async (t, e, n, s, a) => {
696
+ for (const r of t) {
697
+ const o = J(r);
698
+ try {
699
+ const c = await e(r), i = $e(
700
+ c
701
+ ), u = await Fe(
702
+ i,
703
+ c,
704
+ o,
705
+ n,
706
+ s,
707
+ a
708
+ );
709
+ if (u)
710
+ return console.debug(
711
+ `[Init Withdraw] Auto slippage simulation succeeded: slippage=${r}%`
712
+ ), console.debug("[Init Withdraw] Complex asset data:", u), u;
713
+ } catch (c) {
714
+ console.error(
715
+ `[Init Withdraw] Failed to fetch quotes for slippage=${r}%:`,
716
+ c
717
+ );
718
+ }
719
+ }
720
+ return null;
721
+ }, Fn = async (t, e, {
722
+ fetchAaveSwapParams: n,
723
+ fetchAaveSwapQuotes: s,
724
+ withdrawAmountD18: a,
725
+ slippage: r
726
+ }) => Promise.all(
727
+ (t ?? []).map(async (o) => {
728
+ if (!p(o, e))
729
+ return { asset: o };
730
+ try {
731
+ const i = await n({
732
+ withdrawAmountD18: a,
733
+ slippage: r
734
+ });
735
+ if (i?.srcData.length) {
736
+ const u = await s({
737
+ swapParams: i,
738
+ slippage: r
739
+ });
740
+ return { asset: o, swapParams: i, swapQuotes: u };
741
+ }
742
+ return { asset: o };
743
+ } catch (i) {
744
+ return console.error(i), { asset: o };
745
+ }
746
+ })
747
+ ), v = (t) => Math.round(t * 100) / 100, Yn = ({
748
+ maxSlippage: t,
749
+ candidates: e = Ut
750
+ }) => {
751
+ if (!Number.isFinite(t) || t <= 0)
752
+ return [];
753
+ const n = v(Math.min(t, 100)), s = e.filter((r) => r > 0 && r <= n).map(v), a = new Set(s);
754
+ return a.add(n), a.add(t), Array.from(a).sort((r, o) => r - o);
755
+ }, F = 1000000000000000000n, Ye = 1000000n, Y = 10000n, G = 100n, Gn = (t) => ({
756
+ quotes: t.quotes.map(
757
+ (e) => ({
758
+ chainId: y(e.chainId, "chainId"),
759
+ attestationId: y(e.attestationId, "attestationId"),
760
+ userId: S(e.userId),
761
+ asset: e.asset,
762
+ price: y(e.price, "price"),
763
+ quantity: y(e.quantity, "quantity"),
764
+ expiration: y(e.expiration, "expiration"),
765
+ side: Number(e.side),
766
+ additionalData: S(e.additionalData)
767
+ })
768
+ ),
769
+ signatures: t.signatures.map(S)
770
+ }), Ge = (t, e, n) => {
771
+ const s = BigInt(Math.max(0, Math.round(n * 100))), a = s > G ? G : s, r = Y - a, c = t * e / F * r * Ye, i = Y * F;
772
+ return (c + i - 1n) / i;
773
+ }, He = (t, e) => ({
774
+ chainId: e,
775
+ attestationId: y(t.attestationId, "attestationId"),
776
+ userId: B(t.userId),
777
+ asset: t.assetAddress,
778
+ price: y(t.price, "price"),
779
+ quantity: y(t.tokenAmount, "tokenAmount"),
780
+ expiration: y(t.expiration, "expiration"),
781
+ side: Number(t.side),
782
+ additionalData: B(t.additionalData)
783
+ }), Hn = ({
784
+ attestation: t,
785
+ chainId: e,
786
+ slippagePercent: n
787
+ }) => {
788
+ const s = He(t, e);
789
+ return T(qt, [
790
+ {
791
+ attestationSignature: le(t.signature),
792
+ quote: s,
793
+ amountOutMinimum: Ge(
794
+ s.quantity,
795
+ s.price,
796
+ n
797
+ )
798
+ }
799
+ ]);
800
+ }, Wn = (t) => [...t.reduce(
801
+ (n, s) => n.has(s.accountId) ? n : n.set(s.accountId, s),
802
+ /* @__PURE__ */ new Map()
803
+ ).values()].map(({ accountId: n, marketId: s }) => ({
804
+ accountId: n,
805
+ marketId: s,
806
+ collaterals: t.filter(
807
+ (a) => a.accountId === n && !a.isDebt
808
+ ),
809
+ debt: t.find(
810
+ (a) => a.accountId === n && a.isDebt
811
+ )
812
+ })), kn = ({
813
+ collateral: t,
814
+ dytmOffice: e,
815
+ processor: n,
816
+ gmToken: s,
817
+ ondoGMSwap: a,
818
+ usdc: r,
819
+ gmAmount: o,
820
+ amountOutMinimum: c,
821
+ signature: i,
822
+ quote: u
823
+ }) => [
824
+ {
825
+ // 1 · pull GM collateral out of the split account -> processor
826
+ to: e,
827
+ data: A({
828
+ abi: C,
829
+ functionName: "withdraw",
830
+ args: [
831
+ {
832
+ account: t.accountId,
833
+ tokenId: t.tokenId,
834
+ receiver: n,
835
+ assets: o,
836
+ shares: 0n,
837
+ extraData: "0x"
838
+ }
839
+ ]
840
+ })
841
+ },
842
+ {
843
+ // 2 · approve the GM token to Ondo's swap contract
844
+ to: s,
845
+ data: A({
846
+ abi: K,
847
+ functionName: "approve",
848
+ args: [a, o]
849
+ })
850
+ },
851
+ {
852
+ // 3 · redeem GM -> USDC with the signed attestation
853
+ to: a,
854
+ data: A({
855
+ abi: Kt,
856
+ functionName: "swapExactInWithAttestation",
857
+ args: [s, o, r, c, i, u]
858
+ })
859
+ }
860
+ ], qn = ({
861
+ collateral: t,
862
+ dytmOffice: e,
863
+ processor: n
864
+ }) => ({
865
+ to: e,
866
+ data: A({
867
+ abi: C,
868
+ functionName: "withdraw",
869
+ args: [
870
+ {
871
+ account: t.accountId,
872
+ tokenId: t.tokenId,
873
+ receiver: n,
874
+ assets: 0n,
875
+ shares: b,
876
+ extraData: "0x"
877
+ }
878
+ ]
879
+ })
880
+ }), Vn = ({
881
+ accountId: t,
882
+ debtKey: e,
883
+ dytmOffice: n,
884
+ usdc: s
885
+ }) => [
886
+ {
887
+ // approve USDC to the DYTM Office for the repay
888
+ to: s,
889
+ data: A({
890
+ abi: K,
891
+ functionName: "approve",
892
+ args: [n, b]
893
+ })
894
+ },
895
+ {
896
+ // repay the slice's whole USDC debt
897
+ to: n,
898
+ data: A({
899
+ abi: C,
900
+ functionName: "repay",
901
+ args: [
902
+ {
903
+ account: t,
904
+ key: e,
905
+ withCollateralType: 0,
906
+ // DytmParamStructs.TokenType.NONE
907
+ assets: b,
908
+ // repay all
909
+ shares: 0n,
910
+ extraData: "0x"
911
+ }
912
+ ]
913
+ })
914
+ }
915
+ ], Kn = ({
916
+ actions: t,
917
+ outputAsset: e,
918
+ minOutputAmount: n
919
+ }) => T(jt, [
920
+ { actions: t, outputAsset: e, minOutputAmount: n }
921
+ ]), H = /* @__PURE__ */ new Set(), jn = (t) => {
922
+ const e = t?.message;
923
+ !e || H.has(e) || (H.add(e), console.warn(e));
924
+ };
925
+ export {
926
+ An as $,
927
+ tn as A,
928
+ me as B,
929
+ Z as C,
930
+ an as D,
931
+ Un as E,
932
+ L as F,
933
+ Nn as G,
934
+ On as H,
935
+ Bn as I,
936
+ Ln as J,
937
+ Pn as K,
938
+ gn as L,
939
+ ge as M,
940
+ on as N,
941
+ mn as O,
942
+ J as P,
943
+ Dn as Q,
944
+ Wn as R,
945
+ nn as S,
946
+ D as T,
947
+ Rn as U,
948
+ In as V,
949
+ xn as W,
950
+ Mn as X,
951
+ Pe as Y,
952
+ Ue as Z,
953
+ yn as _,
954
+ ie as a,
955
+ jn as a0,
956
+ Cn as a1,
957
+ He as a2,
958
+ Gn as a3,
959
+ et as a4,
960
+ cn as a5,
961
+ hn as a6,
962
+ rn as a7,
963
+ en as a8,
964
+ ln as a9,
965
+ sn as aa,
966
+ y as ab,
967
+ B as ac,
968
+ xe as ad,
969
+ Ce as ae,
970
+ Fe as af,
971
+ vn as ag,
972
+ En as ah,
973
+ kt as ai,
974
+ Ke as aj,
975
+ Je as ak,
976
+ fn as al,
977
+ p as am,
978
+ Ie as an,
979
+ Sn as ao,
980
+ be as ap,
981
+ ze as aq,
982
+ Xe as ar,
983
+ Be as as,
984
+ Re as at,
985
+ Ze as au,
986
+ Ne as av,
987
+ De as aw,
988
+ Tn as ax,
989
+ P as ay,
990
+ le as b,
991
+ Ae as c,
992
+ ve as d,
993
+ kn as e,
994
+ qn as f,
995
+ Vn as g,
996
+ ye as h,
997
+ pn as i,
998
+ dn as j,
999
+ je as k,
1000
+ Ge as l,
1001
+ $n as m,
1002
+ Hn as n,
1003
+ Kn as o,
1004
+ Fn as p,
1005
+ Qe as q,
1006
+ S as r,
1007
+ $e as s,
1008
+ ue as t,
1009
+ Oe as u,
1010
+ _n as v,
1011
+ wn as w,
1012
+ bn as x,
1013
+ Yn as y,
1014
+ un as z
1015
+ };