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