@rhinestone/deposit-modal 0.14.1 → 0.16.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.
Files changed (70) hide show
  1. package/README.md +26 -24
  2. package/bridge-transcript.json +14 -0
  3. package/dist/{DepositModalReown-GAD45GIC.cjs → DepositModalReown-IFN6YLZJ.cjs} +20 -22
  4. package/dist/{DepositModalReown-2EVV64OA.mjs → DepositModalReown-R7UROJPJ.mjs} +5 -7
  5. package/dist/WithdrawModal-SZEAI473.cjs +11 -0
  6. package/dist/WithdrawModal-XKSSHVEJ.mjs +11 -0
  7. package/dist/{caip-D8aRWdEY.d.cts → caip-BMi-9t09.d.cts} +27 -3
  8. package/dist/{caip-D8aRWdEY.d.ts → caip-BMi-9t09.d.ts} +27 -3
  9. package/dist/{chunk-A6JPBMYY.cjs → chunk-24N4KMJX.cjs} +234 -115
  10. package/dist/{chunk-LMG46EP2.mjs → chunk-3HCCR54R.mjs} +1 -1
  11. package/dist/{chunk-AQVJUXSG.cjs → chunk-5CM3ZQ5U.cjs} +1 -1
  12. package/dist/chunk-EA5CE2UZ.mjs +7599 -0
  13. package/dist/{chunk-VUATPOWJ.mjs → chunk-EAGMY3QE.mjs} +74 -17
  14. package/dist/{chunk-5Q5CSVKF.mjs → chunk-F6ROQ6RJ.mjs} +215 -517
  15. package/dist/{chunk-RN5VKWI6.mjs → chunk-FTWKAJGN.mjs} +1 -1
  16. package/dist/chunk-H4O22O7Y.cjs +7599 -0
  17. package/dist/{chunk-GZ4GQ5MC.mjs → chunk-HMB2XQGD.mjs} +172 -53
  18. package/dist/{chunk-DW2EQA2U.cjs → chunk-LVCD6RHF.cjs} +2 -2
  19. package/dist/{chunk-4KCSH4T3.cjs → chunk-OY5N3E6L.cjs} +86 -29
  20. package/dist/{chunk-NQMC5VKQ.cjs → chunk-V466XQSG.cjs} +551 -853
  21. package/dist/{constants-DBrWhJWE.d.cts → constants-BT4ctuHo.d.cts} +7 -6
  22. package/dist/{constants-DBrWhJWE.d.ts → constants-D21ZdNOP.d.ts} +7 -6
  23. package/dist/constants.cjs +3 -3
  24. package/dist/constants.d.cts +3 -3
  25. package/dist/constants.d.ts +3 -3
  26. package/dist/constants.mjs +2 -2
  27. package/dist/deposit.cjs +6 -8
  28. package/dist/deposit.d.cts +3 -3
  29. package/dist/deposit.d.ts +3 -3
  30. package/dist/deposit.mjs +5 -7
  31. package/dist/embed.cjs +130 -80
  32. package/dist/embed.d.cts +3 -9
  33. package/dist/embed.d.ts +3 -9
  34. package/dist/embed.mjs +112 -62
  35. package/dist/index.cjs +8 -11
  36. package/dist/index.d.cts +3 -5
  37. package/dist/index.d.ts +3 -5
  38. package/dist/index.mjs +10 -13
  39. package/dist/polymarket.cjs +6 -6
  40. package/dist/polymarket.mjs +2 -2
  41. package/dist/server.d.cts +2 -2
  42. package/dist/server.d.ts +2 -2
  43. package/dist/styles.css +147 -100
  44. package/dist/{types-DP_3KwlD.d.cts → types-B9SbZQIG.d.ts} +145 -108
  45. package/dist/{types-Bho4OA03.d.ts → types-SwGGf0eH.d.cts} +145 -108
  46. package/dist/withdraw.cjs +5 -6
  47. package/dist/withdraw.d.cts +33 -5
  48. package/dist/withdraw.d.ts +33 -5
  49. package/dist/withdraw.mjs +4 -5
  50. package/package.json +6 -37
  51. package/dist/ClaimModal-GDFENSLV.mjs +0 -13
  52. package/dist/ClaimModal-L3FUBI5U.cjs +0 -13
  53. package/dist/WithdrawModal-FAQH35NG.cjs +0 -12
  54. package/dist/WithdrawModal-IKUHF5CF.mjs +0 -12
  55. package/dist/chunk-4J5ADVIN.cjs +0 -1848
  56. package/dist/chunk-62UCV2LG.cjs +0 -81
  57. package/dist/chunk-7AZFT2MV.cjs +0 -163
  58. package/dist/chunk-HAQOFI3D.cjs +0 -3699
  59. package/dist/chunk-QACOOLOE.mjs +0 -1062
  60. package/dist/chunk-R5UQ3TN4.mjs +0 -81
  61. package/dist/chunk-UX35GYLM.mjs +0 -3699
  62. package/dist/chunk-VALXN5IO.mjs +0 -163
  63. package/dist/chunk-XCTRKCNM.mjs +0 -1848
  64. package/dist/chunk-YP7QVKQ6.cjs +0 -1062
  65. package/dist/claim.cjs +0 -11
  66. package/dist/claim.d.cts +0 -17
  67. package/dist/claim.d.ts +0 -17
  68. package/dist/claim.mjs +0 -11
  69. package/dist/modal-ui-state-OD1RmKkK.d.cts +0 -30
  70. package/dist/modal-ui-state-OD1RmKkK.d.ts +0 -30
@@ -1,3699 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
- var _chunkAQVJUXSGcjs = require('./chunk-AQVJUXSG.cjs');
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
- var _chunk4KCSH4T3cjs = require('./chunk-4KCSH4T3.cjs');
30
-
31
- // src/components/ui/Modal.tsx
32
-
33
-
34
-
35
-
36
- var _react = require('react');
37
- var _reactdom = require('react-dom');
38
- var _jsxruntime = require('react/jsx-runtime');
39
- function getFocusableElements(container) {
40
- const elements = container.querySelectorAll(
41
- 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
42
- );
43
- return Array.from(elements).filter(
44
- (el) => !el.hasAttribute("disabled") && el.offsetParent !== null
45
- );
46
- }
47
- function Modal({
48
- isOpen,
49
- onClose,
50
- children,
51
- className = "",
52
- inline = false,
53
- closeOnOverlayClick = false
54
- }) {
55
- const overlayRef = _react.useRef.call(void 0, null);
56
- const contentRef = _react.useRef.call(void 0, null);
57
- const previousActiveElement = _react.useRef.call(void 0, null);
58
- _react.useEffect.call(void 0, () => {
59
- if (isOpen) {
60
- previousActiveElement.current = document.activeElement;
61
- }
62
- }, [isOpen]);
63
- _react.useEffect.call(void 0, () => {
64
- if (!isOpen && previousActiveElement.current) {
65
- previousActiveElement.current.focus();
66
- previousActiveElement.current = null;
67
- }
68
- }, [isOpen]);
69
- _react.useEffect.call(void 0, () => {
70
- if (isOpen && contentRef.current) {
71
- contentRef.current.focus();
72
- }
73
- }, [isOpen]);
74
- _react.useEffect.call(void 0, () => {
75
- if (isOpen && !inline) {
76
- const originalOverflow = document.body.style.overflow;
77
- document.body.style.overflow = "hidden";
78
- return () => {
79
- document.body.style.overflow = originalOverflow;
80
- };
81
- }
82
- }, [isOpen, inline]);
83
- const handleKeyDown = _react.useCallback.call(void 0,
84
- (event) => {
85
- if (event.key === "Escape") {
86
- event.preventDefault();
87
- onClose("escape");
88
- return;
89
- }
90
- if (event.key === "Tab" && contentRef.current) {
91
- const focusable = getFocusableElements(contentRef.current);
92
- if (focusable.length === 0) return;
93
- const firstElement = focusable[0];
94
- const lastElement = focusable[focusable.length - 1];
95
- if (event.shiftKey) {
96
- if (document.activeElement === firstElement || document.activeElement === contentRef.current) {
97
- event.preventDefault();
98
- lastElement.focus();
99
- }
100
- } else {
101
- if (document.activeElement === lastElement) {
102
- event.preventDefault();
103
- firstElement.focus();
104
- }
105
- }
106
- }
107
- },
108
- [onClose]
109
- );
110
- const handleOverlayClick = _react.useCallback.call(void 0,
111
- (event) => {
112
- if (closeOnOverlayClick && event.target === overlayRef.current) {
113
- onClose("overlay");
114
- }
115
- },
116
- [closeOnOverlayClick, onClose]
117
- );
118
- if (!isOpen) return null;
119
- if (inline) {
120
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
121
- "div",
122
- {
123
- ref: contentRef,
124
- className: `rs-modal-content rs-modal-content--inline ${className}`,
125
- tabIndex: -1,
126
- children
127
- }
128
- );
129
- }
130
- return _reactdom.createPortal.call(void 0,
131
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
132
- "div",
133
- {
134
- ref: overlayRef,
135
- className: `rs-modal-overlay ${isOpen ? "rs-modal-overlay--open" : ""}`,
136
- onClick: handleOverlayClick,
137
- onKeyDown: handleKeyDown,
138
- role: "dialog",
139
- "aria-modal": "true",
140
- "aria-labelledby": "rs-modal-title",
141
- children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
142
- "div",
143
- {
144
- ref: contentRef,
145
- className: `rs-modal-content ${className}`,
146
- tabIndex: -1,
147
- children
148
- }
149
- )
150
- }
151
- ),
152
- document.body
153
- );
154
- }
155
- Modal.displayName = "Modal";
156
-
157
- // src/components/ui/Icons.tsx
158
-
159
-
160
-
161
-
162
-
163
-
164
-
165
-
166
-
167
-
168
-
169
-
170
-
171
-
172
-
173
-
174
-
175
-
176
-
177
-
178
- var _lucidereact = require('lucide-react');
179
-
180
- var WalletIcon = _lucidereact.Wallet;
181
- var ExternalLinkIcon = _lucidereact.ExternalLink;
182
- var CheckIcon = _lucidereact.Check;
183
- function TransferCryptoIcon() {
184
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
185
- "svg",
186
- {
187
- width: "24",
188
- height: "24",
189
- viewBox: "8 8 24 24",
190
- fill: "none",
191
- xmlns: "http://www.w3.org/2000/svg",
192
- "aria-hidden": "true",
193
- children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
194
- "path",
195
- {
196
- d: "M26.08 18.37C27.03 18.72 27.87 19.30 28.53 20.07C29.19 20.83 29.65 21.75 29.86 22.73C30.07 23.72 30.03 24.74 29.74 25.71C29.45 26.68 28.92 27.55 28.20 28.26C27.48 28.97 26.59 29.49 25.62 29.76C24.65 30.04 23.63 30.06 22.64 29.83C21.66 29.61 20.75 29.14 20.00 28.47C19.24 27.80 18.67 26.95 18.33 26.00M15 14H16V18M24.70 21.87L25.40 22.58L22.58 25.40M22 16C22 19.31 19.31 22 16 22C12.68 22 10 19.31 10 16C10 12.68 12.68 10 16 10C19.31 10 22 12.68 22 16Z",
197
- stroke: "currentColor",
198
- strokeWidth: "2",
199
- strokeLinecap: "round",
200
- strokeLinejoin: "round"
201
- }
202
- )
203
- }
204
- );
205
- }
206
- var ChevronRightIcon = _lucidereact.ChevronRight;
207
- var ChevronLeftIcon = _lucidereact.ChevronLeft;
208
- var ChevronDownIcon = _lucidereact.ChevronDown;
209
- var CloseIcon = _lucidereact.X;
210
- var HandCoinsIcon = _lucidereact.HandCoins;
211
- var CoinsIcon = _lucidereact.Coins;
212
- var HistoryIcon = _lucidereact.History;
213
- var InfoIcon = _lucidereact.Info;
214
- var CopyIcon = _lucidereact.Copy;
215
- var ArrowUpRightIcon = _lucidereact.ArrowUpRight;
216
- var AlertTriangleIcon = _lucidereact.AlertTriangle;
217
- var CircleArrowOutUpLeftIcon = _lucidereact.CircleArrowOutUpLeft;
218
- var CardIcon = _lucidereact.CreditCard;
219
- var BankIcon = _lucidereact.Landmark;
220
- var UnplugIcon = _lucidereact.Unplug;
221
- function MigrateAssetsIcon() {
222
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
223
- "svg",
224
- {
225
- width: "24",
226
- height: "24",
227
- viewBox: "0 0 24 24",
228
- fill: "none",
229
- xmlns: "http://www.w3.org/2000/svg",
230
- "aria-hidden": "true",
231
- children: /* @__PURE__ */ _jsxruntime.jsxs.call(void 0,
232
- "g",
233
- {
234
- stroke: "currentColor",
235
- strokeWidth: "2",
236
- strokeLinecap: "round",
237
- strokeLinejoin: "round",
238
- children: [
239
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
240
- "path",
241
- {
242
- d: "M19 4.344V3C19 2.46957 18.7893 1.96086 18.4142 1.58579C18.0391 1.21071 17.5304 1 17 1H3C2.46957 1 1.96086 1.21071 1.58579 1.58579C1.21071 1.96086 1 2.46957 1 3V17C1 17.5304 1.21071 18.0391 1.58579 18.4142C1.96086 18.7893 2.46957 19 3 19H17C17.5304 19 18.0391 18.7893 18.4142 18.4142C18.7893 18.0391 19 17.5304 19 17V15.656",
243
- transform: "translate(2 2)"
244
- }
245
- ),
246
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { d: "M1 1H12", transform: "translate(9 11)" }),
247
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { d: "M1 9L5 5L1 1", transform: "translate(16 7)" })
248
- ]
249
- }
250
- )
251
- }
252
- );
253
- }
254
- function AppleIcon() {
255
- return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0,
256
- "svg",
257
- {
258
- width: "24",
259
- height: "24",
260
- viewBox: "0 0 24 24",
261
- fill: "none",
262
- xmlns: "http://www.w3.org/2000/svg",
263
- "aria-hidden": "true",
264
- children: [
265
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
266
- "path",
267
- {
268
- d: "M16.36 1.43c0 1.14-.49 2.27-1.18 3.08-.74.9-1.99 1.57-2.98 1.57-.12 0-.23-.02-.3-.03-.01-.06-.04-.22-.04-.39 0-1.15.57-2.27 1.2-2.98.8-.94 2.15-1.64 3.25-1.68.03.13.05.28.05.43z",
269
- stroke: "currentColor",
270
- strokeWidth: "1.6",
271
- strokeLinejoin: "round"
272
- }
273
- ),
274
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
275
- "path",
276
- {
277
- d: "M20.93 17.14c-.03.07-.46 1.58-1.52 3.12-.94 1.34-1.94 2.71-3.43 2.71-1.51 0-1.9-.88-3.63-.88-1.7 0-2.3.91-3.67.91-1.38 0-2.33-1.26-3.43-2.8-1.29-1.82-2.32-4.63-2.32-7.28 0-4.28 2.8-6.55 5.55-6.55 1.45 0 2.68.95 3.6.95.86 0 2.22-1.01 3.9-1.01.61 0 2.89.06 4.37 2.19-.13.09-2.38 1.37-2.38 4.19 0 3.26 2.85 4.42 2.96 4.45z",
278
- stroke: "currentColor",
279
- strokeWidth: "1.6",
280
- strokeLinejoin: "round"
281
- }
282
- )
283
- ]
284
- }
285
- );
286
- }
287
-
288
- // src/components/ui/BodyHeader.tsx
289
-
290
- function BodyHeader({
291
- icon,
292
- title,
293
- subtitle,
294
- variant = "default",
295
- aside
296
- }) {
297
- const iconClasses = [
298
- "rs-body-header-icon",
299
- variant === "success" ? "rs-body-header-icon--success" : "",
300
- variant === "error" ? "rs-body-header-icon--error" : ""
301
- ].filter(Boolean).join(" ");
302
- return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "rs-body-header", children: [
303
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: iconClasses, children: icon }),
304
- /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "rs-body-header-main", children: [
305
- /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "rs-body-header-text", children: [
306
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "h2", { className: "rs-body-header-title", children: title }),
307
- subtitle && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "p", { className: "rs-body-header-subtitle", children: subtitle })
308
- ] }),
309
- aside && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "rs-body-header-aside", children: aside })
310
- ] })
311
- ] });
312
- }
313
- BodyHeader.displayName = "BodyHeader";
314
-
315
- // src/components/ui/CdnIcon.tsx
316
-
317
-
318
- function preconnectIconCdn() {
319
- if (typeof document === "undefined") return;
320
- if (document.getElementById("rs-icon-cdn-preconnect")) return;
321
- const link = document.createElement("link");
322
- link.id = "rs-icon-cdn-preconnect";
323
- link.rel = "preconnect";
324
- link.href = _chunk4KCSH4T3cjs.ICON_CDN;
325
- link.crossOrigin = "anonymous";
326
- document.head.appendChild(link);
327
- }
328
- preconnectIconCdn();
329
- function CdnIcon({
330
- src,
331
- alt = "",
332
- className,
333
- fallback,
334
- loading = "eager"
335
- }) {
336
- const [loadedSrc, setLoadedSrc] = _react.useState.call(void 0, null);
337
- const [erroredSrc, setErroredSrc] = _react.useState.call(void 0, null);
338
- if (!src || erroredSrc === src) {
339
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children: fallback });
340
- }
341
- const isLoading = loadedSrc !== src;
342
- const settleIfAlreadyComplete = (el) => {
343
- if (_optionalChain([el, 'optionalAccess', _ => _.complete])) setLoadedSrc(src);
344
- };
345
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
346
- "img",
347
- {
348
- ref: settleIfAlreadyComplete,
349
- src,
350
- alt,
351
- className: `rs-cdn-icon ${_nullishCoalesce(className, () => ( ""))}`.trimEnd(),
352
- loading,
353
- decoding: "async",
354
- "data-loading": isLoading ? "" : void 0,
355
- onLoad: () => setLoadedSrc(src),
356
- onError: () => setErroredSrc(src)
357
- },
358
- src
359
- );
360
- }
361
- CdnIcon.displayName = "CdnIcon";
362
-
363
- // src/components/ui/PoweredBy.tsx
364
-
365
- var rhinestoneLogo = /* @__PURE__ */ _jsxruntime.jsxs.call(void 0,
366
- "svg",
367
- {
368
- className: "rs-powered-by-logo",
369
- viewBox: "0 0 72 16",
370
- fill: "none",
371
- xmlns: "http://www.w3.org/2000/svg",
372
- "aria-hidden": "true",
373
- children: [
374
- /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "g", { fill: "currentColor", clipPath: "url(#rs-pb-clip)", children: [
375
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
376
- "path",
377
- {
378
- opacity: "0.5",
379
- fillRule: "evenodd",
380
- clipRule: "evenodd",
381
- d: "M10.48 14.82a4.3 4.3 0 0 1-2.9 1 4.3 4.3 0 0 1-2.4-1 25 25 0 0 1-2.08-1.95l-.13-.13c-.78-.78-1.46-1.46-1.94-2.08a4.3 4.3 0 0 1-1-2.9c.05-.96.48-1.72 1-2.4a25 25 0 0 1 1.94-2.08l.07-.06.06-.07a25 25 0 0 1 2.08-1.94 4.3 4.3 0 0 1 2.9-1c.96.05 1.73.48 2.4 1 .62.49 1.3 1.17 2.08 1.94l.13.13c.77.78 1.46 1.46 1.94 2.09a4.3 4.3 0 0 1 1 2.9 4.3 4.3 0 0 1-1 2.39c-.48.62-1.17 1.3-1.94 2.08l-.07.07-.06.06c-.78.78-1.46 1.46-2.08 1.94m-8.9-6.63c.07 1.02.9 1.86 2.56 3.52s2.5 2.5 3.53 2.56h.32c1.03-.06 1.86-.9 3.53-2.56s2.5-2.5 2.56-3.52v-.33c-.07-1.03-.9-1.86-2.56-3.52-1.67-1.67-2.5-2.5-3.53-2.56h-.32c-1.03.06-1.86.89-3.53 2.56-1.66 1.66-2.5 2.5-2.56 3.52z"
382
- }
383
- ),
384
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { d: "M3.66 8.01q.02-.27.28-.35a4.6 4.6 0 0 0 2.53-1.48q.72-.8 1-2.05a.4.4 0 0 1 .36-.29c.17 0 .32.12.36.29a4.6 4.6 0 0 0 1.47 2.52c.55.49 1.21.8 2.06 1a.4.4 0 0 1 .28.36.4.4 0 0 1-.28.36 4.6 4.6 0 0 0-2.53 1.47 4.6 4.6 0 0 0-1 2.06.4.4 0 0 1-.36.28.4.4 0 0 1-.36-.28A4.6 4.6 0 0 0 6 9.38a4.6 4.6 0 0 0-2.06-1.01.4.4 0 0 1-.28-.36m26.46-3.44c0 .51.38.87.96.87s.95-.36.95-.87c0-.52-.37-.86-.95-.86s-.96.34-.96.86m.2 1.44v5.33h1.53V6.01zm-4.4 5.33h-1.55V3.88h1.54v2.98c.25-.5.8-1.01 1.6-1.01 1.29 0 1.87.83 1.87 2.28v3.21h-1.54V8.3c0-.77-.34-1.16-.92-1.16-.67 0-1 .53-1 1.3zm-4.45 0h-1.54V6.01h1.54l-.27 1.22a.1.1 0 0 0 .02.1.1.1 0 0 0 .1.04q.09 0 .1-.09c.24-.84.93-1.36 1.64-1.36q.4.01.57.05v1.42l-.67-.04c-.67 0-1.5.31-1.5 2zm13 0h-1.55V6.01h1.54l-.02.9a1.8 1.8 0 0 1 1.61-1.06c1.3 0 1.88.83 1.88 2.28v3.21H36.4V8.3c0-.77-.35-1.16-.93-1.16-.67 0-1 .53-1 1.3z" }),
385
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
386
- "path",
387
- {
388
- fillRule: "evenodd",
389
- clipRule: "evenodd",
390
- d: "M38.74 8.69c0 1.63 1.01 2.82 2.7 2.82 1.51 0 2.32-.82 2.55-1.73l-1.43-.26c-.1.37-.47.82-1.12.82-.67 0-1.23-.6-1.24-1.31H44q.05-.19.06-.56a2.55 2.55 0 0 0-2.6-2.63c-1.5 0-2.72 1.2-2.72 2.85m3.82-.58h-2.3a1.2 1.2 0 0 1 1.18-1.13c.6 0 1.14.45 1.12 1.13"
391
- }
392
- ),
393
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { d: "M47.1 11.51c-1.2 0-2.33-.41-2.55-1.65l1.43-.21q.27.8 1.1.79c.5 0 .77-.24.77-.55 0-.27-.2-.45-.75-.55l-.5-.1c-1.1-.24-1.77-.74-1.77-1.63 0-1.06.91-1.78 2.25-1.78 1.26 0 2.2.59 2.32 1.68l-1.41.22c-.07-.52-.43-.82-.91-.82-.5 0-.75.26-.75.57 0 .25.17.42.63.51l.5.1c1.28.26 1.94.77 1.94 1.75 0 1.01-1.03 1.66-2.3 1.66" }),
394
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
395
- "path",
396
- {
397
- fillRule: "evenodd",
398
- clipRule: "evenodd",
399
- d: "M54.44 8.68c0 1.53 1.08 2.83 2.78 2.83s2.79-1.3 2.79-2.83c0-1.55-1.1-2.84-2.79-2.84-1.7 0-2.78 1.29-2.78 2.84m4.02 0c0 .98-.59 1.45-1.24 1.45-.64 0-1.23-.47-1.23-1.45 0-.97.59-1.47 1.23-1.47.65 0 1.24.48 1.24 1.47"
400
- }
401
- ),
402
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { d: "M62.4 11.34h-1.53V6.01h1.54l-.02.9a1.8 1.8 0 0 1 1.6-1.06c1.3 0 1.89.83 1.89 2.28v3.21h-1.54V8.3c0-.77-.34-1.16-.93-1.16-.66 0-1 .53-1 1.3z" }),
403
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
404
- "path",
405
- {
406
- fillRule: "evenodd",
407
- clipRule: "evenodd",
408
- d: "M66.68 8.69c0 1.63 1.02 2.82 2.71 2.82 1.51 0 2.31-.82 2.55-1.73l-1.44-.26c-.1.37-.47.82-1.12.82-.67 0-1.23-.6-1.24-1.31h3.8q.06-.19.06-.56a2.55 2.55 0 0 0-2.6-2.63c-1.5 0-2.72 1.2-2.72 2.85m3.82-.58h-2.3a1.2 1.2 0 0 1 1.18-1.13c.6 0 1.15.45 1.12 1.13"
409
- }
410
- ),
411
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { d: "M52.44 9.05V7.26h1.53V6h-1.53V4.42h-1.53V6h-1.1v1.26h1.1v1.85l.02.49a1.9 1.9 0 0 0 1.67 1.67c.22.03.47.03.62.03h.65V9.87h-.61c-.4 0-.59 0-.7-.12-.12-.11-.12-.3-.12-.64z" })
412
- ] }),
413
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "defs", { children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "clipPath", { id: "rs-pb-clip", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "path", { fill: "#fff", d: "M0 0h72v16H0z" }) }) })
414
- ]
415
- }
416
- );
417
- function PoweredBy() {
418
- return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "rs-powered-by", "aria-label": "Powered by Rhinestone", children: [
419
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "span", { children: "Powered by" }),
420
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
421
- "a",
422
- {
423
- className: "rs-powered-by-link",
424
- href: "https://www.rhinestone.dev",
425
- target: "_blank",
426
- rel: "noopener noreferrer",
427
- children: rhinestoneLogo
428
- }
429
- )
430
- ] });
431
- }
432
- PoweredBy.displayName = "PoweredBy";
433
-
434
- // src/core/deposit-service.ts
435
- var _viem = require('viem');
436
-
437
- // src/core/debug.ts
438
- function truncateString(value, max = 240) {
439
- if (value.length <= max) return value;
440
- return `${value.slice(0, max)}...`;
441
- }
442
- function normalizeForLog(value, depth = 0) {
443
- if (depth > 3) return "[MaxDepth]";
444
- if (value === null || value === void 0) return value;
445
- if (typeof value === "bigint") return value.toString();
446
- if (typeof value === "string") return truncateString(value);
447
- if (typeof value === "number" || typeof value === "boolean") return value;
448
- if (value instanceof Error) {
449
- return {
450
- name: value.name,
451
- message: value.message,
452
- stack: value.stack ? truncateString(value.stack, 600) : void 0
453
- };
454
- }
455
- if (Array.isArray(value)) {
456
- return value.slice(0, 12).map((entry) => normalizeForLog(entry, depth + 1));
457
- }
458
- if (typeof value === "object") {
459
- const input = value;
460
- const output = {};
461
- for (const [key, raw] of Object.entries(input)) {
462
- const keyLower = key.toLowerCase();
463
- if (keyLower.includes("signature") || keyLower.includes("privatekey") || keyLower.includes("sessiondetails") || keyLower.includes("rpcurl") || keyLower.includes("apikey") || keyLower.includes("authorization")) {
464
- output[key] = "[Redacted]";
465
- continue;
466
- }
467
- output[key] = normalizeForLog(raw, depth + 1);
468
- }
469
- return output;
470
- }
471
- return String(value);
472
- }
473
- function debugLog(enabled, scope, message, data) {
474
- if (!enabled) return;
475
- if (data === void 0) {
476
- console.log(`[deposit-modal:${scope}] ${message}`);
477
- return;
478
- }
479
- console.log(
480
- `[deposit-modal:${scope}] ${message}`,
481
- normalizeForLog(data)
482
- );
483
- }
484
- function debugError(enabled, scope, message, error, data) {
485
- if (!enabled) return;
486
- const payload = data === void 0 ? { error: normalizeForLog(error) } : { error: normalizeForLog(error), meta: normalizeForLog(data) };
487
- console.error(`[deposit-modal:${scope}] ${message}`, payload);
488
- }
489
-
490
- // src/core/chain-catalog.ts
491
- function parseToken(value) {
492
- if (typeof value !== "object" || value === null) return null;
493
- const { symbol, address, decimals } = value;
494
- if (typeof symbol !== "string" || typeof address !== "string" || typeof decimals !== "number") {
495
- return null;
496
- }
497
- return { symbol, address, decimals };
498
- }
499
- function parseExplorer(value) {
500
- if (typeof value !== "object" || value === null) return null;
501
- const { url, addressPath, txPath } = value;
502
- if (typeof url !== "string" || typeof addressPath !== "string" || typeof txPath !== "string") {
503
- return null;
504
- }
505
- return { url, addressPath, txPath };
506
- }
507
- function parseVmType(value) {
508
- return value === "evm" || value === "svm" || value === "tvm" ? value : null;
509
- }
510
- function parseOptionalString(value) {
511
- return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
512
- }
513
- function parseChain(caip2, value) {
514
- if (typeof value !== "object" || value === null) return null;
515
- const raw = value;
516
- const { name, testnet, deposit, destination, refund } = raw;
517
- if (typeof name !== "string" || typeof testnet !== "boolean" || typeof deposit !== "boolean" || typeof destination !== "boolean" || typeof refund !== "boolean") {
518
- return null;
519
- }
520
- const vmType = parseVmType(raw.vmType);
521
- const nativeToken = parseToken(raw.nativeToken);
522
- if (!vmType || !nativeToken) return null;
523
- let supportedTokens;
524
- if (raw.supportedTokens === "all") {
525
- supportedTokens = "all";
526
- } else if (Array.isArray(raw.supportedTokens)) {
527
- const tokens = [];
528
- for (const entry of raw.supportedTokens) {
529
- const token = parseToken(entry);
530
- if (!token) return null;
531
- tokens.push(token);
532
- }
533
- supportedTokens = tokens;
534
- } else {
535
- return null;
536
- }
537
- return {
538
- caip2,
539
- // `parseEvmChainId` returns null for `solana:`/`tron:`/`hypercore:` keys,
540
- // which is the intended answer — those chains have no numeric id, and the
541
- // modal addresses them by their CAIP-2 string or a sentinel.
542
- chainId: _chunk4KCSH4T3cjs.parseEvmChainId.call(void 0, caip2),
543
- name,
544
- testnet,
545
- deposit,
546
- destination,
547
- refund,
548
- vmType,
549
- nativeToken,
550
- explorer: parseExplorer(raw.explorer),
551
- supportedTokens,
552
- publicRpcUrl: parseOptionalString(raw.publicRpcUrl),
553
- iconUrl: parseOptionalString(raw.iconUrl)
554
- };
555
- }
556
- function parseChainCatalog(body) {
557
- if (typeof body !== "object" || body === null || Array.isArray(body)) {
558
- return null;
559
- }
560
- const all = [];
561
- const byCaip2 = /* @__PURE__ */ new Map();
562
- const byChainId = /* @__PURE__ */ new Map();
563
- for (const [caip2, value] of Object.entries(body)) {
564
- const chain = parseChain(caip2, value);
565
- if (!chain) continue;
566
- all.push(chain);
567
- byCaip2.set(chain.caip2, chain);
568
- if (chain.chainId !== null) byChainId.set(chain.chainId, chain);
569
- }
570
- if (all.length === 0) return null;
571
- aliasHyperCoreOrigin(byCaip2, all);
572
- return { all, byCaip2, byChainId };
573
- }
574
- function aliasHyperCoreOrigin(byCaip2, all) {
575
- if (byCaip2.has(_chunk4KCSH4T3cjs.HYPERCORE_SPOT_CAIP2)) return;
576
- const origin = _nullishCoalesce(all.find((c) => _chunk4KCSH4T3cjs.isHyperCoreCaip2.call(void 0, c.caip2) && c.deposit), () => ( all.find((c) => _chunk4KCSH4T3cjs.isHyperCoreCaip2.call(void 0, c.caip2))));
577
- if (origin) byCaip2.set(_chunk4KCSH4T3cjs.HYPERCORE_SPOT_CAIP2, origin);
578
- }
579
- function catalogKeyForChain(chainId) {
580
- if (chainId === "solana") return _chunk4KCSH4T3cjs.SOLANA_MAINNET_CAIP2;
581
- if (chainId === "hypercore" || chainId === _chunk4KCSH4T3cjs.HYPERCORE_CHAIN_ID) {
582
- return _chunk4KCSH4T3cjs.HYPERCORE_SPOT_CAIP2;
583
- }
584
- return chainId;
585
- }
586
- function catalogExplorerTxUrl(chain, txHash) {
587
- if (!_optionalChain([chain, 'optionalAccess', _2 => _2.explorer])) return void 0;
588
- return `${chain.explorer.url}${chain.explorer.txPath}${txHash}`;
589
- }
590
-
591
- // src/core/deposit-asset-helpers.ts
592
- function getAssetId(asset) {
593
- return `${asset.chainId}:${asset.token.toLowerCase()}`;
594
- }
595
- function chainIdsByValue(tokens) {
596
- const usdByChain = /* @__PURE__ */ new Map();
597
- for (const token of tokens) {
598
- if (typeof token.chainId !== "number") continue;
599
- const usd = Number.isFinite(token.balanceUsd) ? token.balanceUsd : 0;
600
- if (usd <= 0) continue;
601
- usdByChain.set(token.chainId, (_nullishCoalesce(usdByChain.get(token.chainId), () => ( 0))) + usd);
602
- }
603
- return [...usdByChain.entries()].sort((a, b) => b[1] - a[1]).map(([chainId]) => chainId);
604
- }
605
- function isEvmAddress(value) {
606
- return /^0x[a-fA-F0-9]{40}$/.test(value);
607
- }
608
- function portfolioTokenToAsset(token) {
609
- if (typeof token.chainId !== "number") return null;
610
- if (!isEvmAddress(token.address)) return null;
611
- return {
612
- id: getAssetId({ chainId: token.chainId, token: token.address }),
613
- chainId: token.chainId,
614
- token: token.address,
615
- symbol: token.symbol,
616
- name: token.name,
617
- decimals: token.decimals,
618
- balance: token.balance,
619
- balanceUsd: token.balanceUsd
620
- };
621
- }
622
- function safeBigInt(value) {
623
- if (!value) return BigInt(0);
624
- try {
625
- return BigInt(value);
626
- } catch (e) {
627
- return BigInt(0);
628
- }
629
- }
630
- function portfolioToAssets(tokens) {
631
- return tokens.map(portfolioTokenToAsset).filter((token) => token !== null).sort((a, b) => {
632
- const balanceA = safeBigInt(a.balance);
633
- const balanceB = safeBigInt(b.balance);
634
- if (balanceB > balanceA) return 1;
635
- if (balanceB < balanceA) return -1;
636
- return 0;
637
- });
638
- }
639
- function isNativeAsset(asset) {
640
- return asset.token.toLowerCase() === "0x0000000000000000000000000000000000000000";
641
- }
642
-
643
- // src/core/deposit-service.ts
644
- function depositRowToEvent(row) {
645
- const status = row.status;
646
- if (!status) return void 0;
647
- const deposit = {
648
- transactionHash: row.txHash,
649
- chain: row.chain,
650
- amount: _nullishCoalesce(row.sourceAmount, () => ( row.amount)),
651
- asset: row.token,
652
- token: row.token
653
- };
654
- const source = row.sourceTxHash ? { transactionHash: row.sourceTxHash, chain: row.chain } : { transactionHash: row.txHash, chain: row.chain };
655
- const destination = row.destinationTxHash ? {
656
- transactionHash: row.destinationTxHash,
657
- chain: row.targetChain,
658
- amount: _nullishCoalesce(row.destinationAmount, () => ( void 0))
659
- } : void 0;
660
- const time = _nullishCoalesce(_nullishCoalesce(row.completedAt, () => ( row.createdAt)), () => ( void 0));
661
- if (status === "completed") {
662
- return {
663
- type: "bridge-complete",
664
- time: _nullishCoalesce(time, () => ( void 0)),
665
- data: {
666
- deposit,
667
- source,
668
- ...destination && { destination }
669
- }
670
- };
671
- }
672
- if (status === "failed" || status === "refunded") {
673
- return {
674
- type: "bridge-failed",
675
- time: _nullishCoalesce(time, () => ( void 0)),
676
- data: {
677
- deposit,
678
- source,
679
- ...row.errorCode && { error: { code: row.errorCode } }
680
- }
681
- };
682
- }
683
- if (status === "processing") {
684
- return {
685
- type: "bridge-started",
686
- time: _nullishCoalesce(time, () => ( void 0)),
687
- data: {
688
- deposit,
689
- source
690
- }
691
- };
692
- }
693
- return {
694
- type: "deposit-received",
695
- time: _nullishCoalesce(time, () => ( void 0)),
696
- data: {
697
- transactionHash: row.txHash,
698
- chain: row.chain,
699
- amount: row.amount,
700
- token: row.token
701
- }
702
- };
703
- }
704
- function normalizeEvmAddress(value) {
705
- try {
706
- return _viem.getAddress.call(void 0, value);
707
- } catch (e2) {
708
- return value;
709
- }
710
- }
711
- function userPaidUsd(fees) {
712
- let sum = 0;
713
- for (const line of Object.values(fees.breakdown)) {
714
- if (line.sponsored || line.internal) continue;
715
- if (Number.isFinite(line.usd) && line.usd > 0) sum += line.usd;
716
- }
717
- return sum;
718
- }
719
- function formatFeeUsd(usd) {
720
- const value = Number.isFinite(usd) && usd > 0 ? usd : 0;
721
- if (value > 0 && value < 0.01) return "<$0.01";
722
- return `$${value.toFixed(2)}`;
723
- }
724
- function quoteFeeRow(fees) {
725
- if (!fees) return { display: null, struck: false };
726
- const userUsd = userPaidUsd(fees);
727
- const totalUsd = Number.isFinite(fees.total.usd) ? fees.total.usd : 0;
728
- const struck = userUsd === 0 && totalUsd > 0;
729
- return { display: formatFeeUsd(struck ? totalUsd : userUsd), struck };
730
- }
731
- function quoteFeeGroups(breakdown) {
732
- const groups = /* @__PURE__ */ new Map();
733
- for (const [category, line] of Object.entries(breakdown)) {
734
- if (line.internal || !Number.isFinite(line.usd) || line.usd < 0) continue;
735
- const label = _optionalChain([line, 'access', _3 => _3.label, 'optionalAccess', _4 => _4.trim, 'call', _5 => _5()]) || titleCaseFeeCategory(category);
736
- const group = _nullishCoalesce(groups.get(label), () => ( {
737
- label,
738
- chargedUsd: 0,
739
- sponsoredUsd: 0
740
- }));
741
- if (line.sponsored) group.sponsoredUsd += line.usd;
742
- else group.chargedUsd += line.usd;
743
- groups.set(label, group);
744
- }
745
- return [...groups.values()];
746
- }
747
- function titleCaseFeeCategory(category) {
748
- return category.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[-_]+/g, " ").split(" ").filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
749
- }
750
- function parseQuotePreview(raw) {
751
- if (typeof raw !== "object" || raw === null) return null;
752
- const obj = raw;
753
- if (typeof obj.settlementLayer !== "string") return null;
754
- if (typeof obj.expiresAt !== "number" || !Number.isFinite(obj.expiresAt)) {
755
- return null;
756
- }
757
- if (typeof obj.estimatedFillTimeSeconds !== "number" || !Number.isFinite(obj.estimatedFillTimeSeconds)) {
758
- return null;
759
- }
760
- const output = parseQuoteOutput(obj.output);
761
- if (!output) return null;
762
- const fees = obj.fees;
763
- if (typeof fees !== "object" || fees === null) return null;
764
- const total = fees.total;
765
- if (typeof total !== "object" || total === null) return null;
766
- const totalUsd = total.usd;
767
- if (typeof totalUsd !== "number" || !Number.isFinite(totalUsd) || totalUsd < 0) {
768
- return null;
769
- }
770
- const rawBreakdown = fees.breakdown;
771
- if (typeof rawBreakdown !== "object" || rawBreakdown === null || Array.isArray(rawBreakdown)) {
772
- return null;
773
- }
774
- const entries = Object.entries(rawBreakdown);
775
- const parsedEntries = [];
776
- for (const [key, value] of entries) {
777
- const line = parseFeeLine(value);
778
- if (!line) return null;
779
- parsedEntries.push([key, line]);
780
- }
781
- const breakdownTotalUsd = parsedEntries.reduce(
782
- (sum, [, line]) => sum + line.usd,
783
- 0
784
- );
785
- if (Math.abs(totalUsd - breakdownTotalUsd) > 1e-6) return null;
786
- const breakdown = Object.fromEntries(parsedEntries);
787
- return {
788
- settlementLayer: obj.settlementLayer,
789
- expiresAt: obj.expiresAt,
790
- estimatedFillTimeSeconds: obj.estimatedFillTimeSeconds,
791
- fees: { total: { usd: totalUsd }, breakdown },
792
- output
793
- };
794
- }
795
- function parseQuoteOutput(raw) {
796
- if (typeof raw !== "object" || raw === null) return null;
797
- const o = raw;
798
- if (typeof o.token !== "string") return null;
799
- if (typeof o.amount !== "string") return null;
800
- if (o.symbol !== null && typeof o.symbol !== "string") return null;
801
- if (o.decimals !== null && typeof o.decimals !== "number") return null;
802
- return {
803
- token: o.token,
804
- amount: o.amount,
805
- symbol: o.symbol,
806
- decimals: o.decimals
807
- };
808
- }
809
- function parseFeeLine(raw) {
810
- if (typeof raw !== "object" || raw === null || Array.isArray(raw))
811
- return null;
812
- const line = raw;
813
- const usd = line.usd;
814
- if (typeof usd !== "number" || !Number.isFinite(usd) || usd < 0) return null;
815
- const sponsored = line.sponsored;
816
- if (typeof sponsored !== "boolean") return null;
817
- if (line.label !== void 0 && typeof line.label !== "string") return null;
818
- if (line.internal !== void 0 && typeof line.internal !== "boolean") {
819
- return null;
820
- }
821
- return {
822
- usd,
823
- sponsored,
824
- ...line.label !== void 0 && { label: line.label },
825
- ...line.internal !== void 0 && { internal: line.internal }
826
- };
827
- }
828
- var SwappedConnectFeeChangedError = class extends Error {
829
- constructor(exchangeFeeBps, message = "The Exchange Fee changed") {
830
- super(message);
831
- this.exchangeFeeBps = exchangeFeeBps;
832
- this.name = "SwappedConnectFeeChangedError";
833
- }
834
- };
835
- function parseExchangeFeeBps(value) {
836
- return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1e4 ? value : void 0;
837
- }
838
- var UNSUPPORTED_CONNECT_EXCHANGES = /* @__PURE__ */ new Set(["kraken", "htx"]);
839
- var SUPPORTED_CONNECT_EXCHANGE_COUNT = 7;
840
- function isSupportedConnectExchange(exchange) {
841
- return !UNSUPPORTED_CONNECT_EXCHANGES.has(exchange.connection.toLowerCase());
842
- }
843
- function resolveAppFeeBps(appFees, sourceChainCaip2, sourceToken) {
844
- const override = _optionalChain([appFees, 'optionalAccess', _6 => _6.tokens, 'optionalAccess', _7 => _7[sourceChainCaip2], 'optionalAccess', _8 => _8[sourceToken.toLowerCase()]]);
845
- const bps = _nullishCoalesce(_nullishCoalesce(override, () => ( _optionalChain([appFees, 'optionalAccess', _9 => _9.feeBps]))), () => ( 0));
846
- return bps > 0 ? bps : 0;
847
- }
848
- var PermitDepositSubmitError = class extends Error {
849
- constructor(message, safeToTransfer) {
850
- super(message);
851
- this.safeToTransfer = safeToTransfer;
852
- this.name = "PermitDepositSubmitError";
853
- }
854
- };
855
- function createDepositService(baseUrl, options) {
856
- const normalizedBaseUrl = baseUrl.replace(/\/$/, "");
857
- const debug = _optionalChain([options, 'optionalAccess', _10 => _10.debug]) === true;
858
- const scope = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _11 => _11.debugScope]), () => ( "service"));
859
- function apiUrl(path) {
860
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
861
- return `${normalizedBaseUrl}${normalizedPath}`;
862
- }
863
- function shortRef(value) {
864
- if (value.length <= 20) return value;
865
- return `${value.slice(0, 10)}...${value.slice(-8)}`;
866
- }
867
- const PORTFOLIO_CACHE_TTL_MS = 3e4;
868
- const portfolioCache = /* @__PURE__ */ new Map();
869
- let topTokensPromise = null;
870
- let chainsPromise = null;
871
- function parseTopTokens(value) {
872
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
873
- return null;
874
- }
875
- const parsed = {};
876
- for (const [chainKey, list] of Object.entries(value)) {
877
- if (!Array.isArray(list)) return null;
878
- const tokens = [];
879
- for (const entry of list) {
880
- if (typeof entry !== "object" || entry === null) return null;
881
- const { symbol, address, decimals } = entry;
882
- if (typeof symbol !== "string" || typeof address !== "string" || typeof decimals !== "number") {
883
- return null;
884
- }
885
- tokens.push({ symbol, address, decimals });
886
- }
887
- parsed[chainKey] = tokens;
888
- }
889
- return parsed;
890
- }
891
- async function requestTopTokens() {
892
- try {
893
- const response = await fetch(apiUrl("/qr/tokens"), {
894
- method: "GET",
895
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, )
896
- });
897
- if (!response.ok) {
898
- debugLog(debug, scope, "getTopTokens:unavailable", {
899
- status: response.status
900
- });
901
- return null;
902
- }
903
- const data = await response.json();
904
- const tokens = parseTopTokens(data.tokens);
905
- if (!tokens) {
906
- debugLog(debug, scope, "getTopTokens:malformed");
907
- return null;
908
- }
909
- debugLog(debug, scope, "getTopTokens:success", {
910
- chains: Object.keys(tokens).length
911
- });
912
- return tokens;
913
- } catch (error) {
914
- debugError(debug, scope, "getTopTokens:error", error);
915
- return null;
916
- }
917
- }
918
- async function requestChains() {
919
- try {
920
- const response = await fetch(apiUrl("/chains"), {
921
- method: "GET",
922
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, )
923
- });
924
- if (!response.ok) {
925
- debugLog(debug, scope, "getChains:unavailable", {
926
- status: response.status
927
- });
928
- return null;
929
- }
930
- const catalog = parseChainCatalog(await response.json());
931
- if (!catalog) {
932
- debugLog(debug, scope, "getChains:malformed");
933
- return null;
934
- }
935
- debugLog(debug, scope, "getChains:success", {
936
- chains: catalog.all.length
937
- });
938
- return catalog;
939
- } catch (error) {
940
- debugError(debug, scope, "getChains:error", error);
941
- return null;
942
- }
943
- }
944
- function cachedPortfolio(key, fetcher, forceRefresh = false) {
945
- const now = Date.now();
946
- const entry = portfolioCache.get(key);
947
- if (!forceRefresh && entry && entry.expiresAt > now) {
948
- debugLog(debug, scope, "portfolio:cache-hit", { key });
949
- return entry.promise;
950
- }
951
- let promise;
952
- promise = fetcher().catch((err) => {
953
- if (_optionalChain([portfolioCache, 'access', _12 => _12.get, 'call', _13 => _13(key), 'optionalAccess', _14 => _14.promise]) === promise) {
954
- portfolioCache.delete(key);
955
- }
956
- throw err;
957
- });
958
- portfolioCache.set(key, {
959
- promise,
960
- expiresAt: now + PORTFOLIO_CACHE_TTL_MS
961
- });
962
- return promise;
963
- }
964
- return {
965
- async registerManagedAccount(params) {
966
- const url = apiUrl("/register-managed");
967
- debugLog(debug, scope, "registerManagedAccount:request", {
968
- url,
969
- salt: params.salt,
970
- targetChain: params.target.chain,
971
- targetToken: params.target.token,
972
- recipient: shortRef(params.target.recipient)
973
- });
974
- const response = await fetch(url, {
975
- method: "POST",
976
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
977
- body: JSON.stringify({ account: params })
978
- });
979
- if (!response.ok) {
980
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
981
- debugError(debug, scope, "registerManagedAccount:failed", error, {
982
- status: response.status,
983
- salt: params.salt
984
- });
985
- const detail = Array.isArray(error.details) ? error.details.map((d) => _optionalChain([d, 'optionalAccess', _15 => _15.message])).filter(Boolean).join("; ") : void 0;
986
- const base = error.error || `Account registration failed: ${response.status}`;
987
- throw new Error(detail ? `${base}: ${detail}` : base);
988
- }
989
- const result = await response.json();
990
- debugLog(debug, scope, "registerManagedAccount:success", {
991
- evmDepositAddress: _optionalChain([result, 'optionalAccess', _16 => _16.evmDepositAddress]),
992
- hasSolanaDepositAddress: Boolean(_optionalChain([result, 'optionalAccess', _17 => _17.solanaDepositAddress])),
993
- hasTronDepositAddress: Boolean(_optionalChain([result, 'optionalAccess', _18 => _18.tronDepositAddress]))
994
- });
995
- return {
996
- ...result,
997
- evmDepositAddress: normalizeEvmAddress(_optionalChain([result, 'optionalAccess', _19 => _19.evmDepositAddress]))
998
- };
999
- },
1000
- async fetchPortfolio(address, options2) {
1001
- return cachedPortfolio(
1002
- `evm:${address.toLowerCase()}`,
1003
- async () => {
1004
- const url = apiUrl(`/portfolio/${address}?includeUnsupported=true`);
1005
- debugLog(debug, scope, "fetchPortfolio:request", { url, address });
1006
- const response = await fetch(url, {
1007
- method: "GET",
1008
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, )
1009
- });
1010
- if (!response.ok) {
1011
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1012
- debugError(debug, scope, "fetchPortfolio:failed", error, {
1013
- status: response.status,
1014
- address
1015
- });
1016
- throw new Error(
1017
- error.error || `Portfolio fetch failed: ${response.status}`
1018
- );
1019
- }
1020
- const data = await response.json();
1021
- const direct = normalizeDirectPortfolio(data);
1022
- if (direct.tokens.length > 0) {
1023
- debugLog(debug, scope, "fetchPortfolio:success", {
1024
- address,
1025
- source: "direct",
1026
- tokenCount: direct.tokens.length,
1027
- totalUsd: direct.totalUsd
1028
- });
1029
- return direct;
1030
- }
1031
- const portfolioData = extractOrchestratorPortfolio(data);
1032
- if (portfolioData) {
1033
- const normalized = normalizeOrchestratorPortfolio(portfolioData);
1034
- debugLog(debug, scope, "fetchPortfolio:success", {
1035
- address,
1036
- source: "orchestrator",
1037
- tokenCount: normalized.tokens.length,
1038
- totalUsd: normalized.totalUsd
1039
- });
1040
- return normalized;
1041
- }
1042
- debugLog(debug, scope, "fetchPortfolio:empty", { address });
1043
- return { tokens: [], totalUsd: 0 };
1044
- },
1045
- _optionalChain([options2, 'optionalAccess', _20 => _20.forceRefresh])
1046
- );
1047
- },
1048
- async fetchSolanaPortfolio(address, options2) {
1049
- return cachedPortfolio(
1050
- `sol:${address}`,
1051
- async () => {
1052
- const url = apiUrl(`/portfolio/solana/${address}`);
1053
- debugLog(debug, scope, "fetchSolanaPortfolio:request", {
1054
- url,
1055
- address
1056
- });
1057
- const response = await fetch(url, {
1058
- method: "GET",
1059
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, )
1060
- });
1061
- if (!response.ok) {
1062
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1063
- debugError(debug, scope, "fetchSolanaPortfolio:failed", error, {
1064
- status: response.status,
1065
- address
1066
- });
1067
- throw new Error(
1068
- error.error || `Solana portfolio fetch failed: ${response.status}`
1069
- );
1070
- }
1071
- const data = await response.json();
1072
- const normalized = normalizeDirectPortfolio(data);
1073
- debugLog(debug, scope, "fetchSolanaPortfolio:success", {
1074
- address,
1075
- tokenCount: normalized.tokens.length,
1076
- totalUsd: normalized.totalUsd
1077
- });
1078
- return normalized;
1079
- },
1080
- _optionalChain([options2, 'optionalAccess', _21 => _21.forceRefresh])
1081
- );
1082
- },
1083
- async checkAccount(address) {
1084
- const url = apiUrl(`/check/${address}`);
1085
- debugLog(debug, scope, "checkAccount:request", { url, address });
1086
- const response = await fetch(url, {
1087
- method: "GET",
1088
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, )
1089
- });
1090
- if (!response.ok) {
1091
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1092
- debugError(debug, scope, "checkAccount:failed", error, {
1093
- status: response.status,
1094
- address
1095
- });
1096
- throw new Error(
1097
- error.error || `Account check failed: ${response.status}`
1098
- );
1099
- }
1100
- const data = await response.json();
1101
- const result = {
1102
- isRegistered: _optionalChain([data, 'optionalAccess', _22 => _22.isRegistered]) === true,
1103
- targetChain: _optionalChain([data, 'optionalAccess', _23 => _23.targetChain]),
1104
- targetToken: _optionalChain([data, 'optionalAccess', _24 => _24.targetToken])
1105
- };
1106
- debugLog(debug, scope, "checkAccount:success", {
1107
- address,
1108
- isRegistered: result.isRegistered,
1109
- targetChain: result.targetChain,
1110
- targetToken: result.targetToken
1111
- });
1112
- return result;
1113
- },
1114
- async fetchStatus(address, txHash) {
1115
- const normalized = txHash.startsWith("0x") || txHash.startsWith("0X") ? txHash.toLowerCase() : txHash;
1116
- const txHashParam = encodeURIComponent(normalized);
1117
- const url = apiUrl(
1118
- `/deposits?account=${encodeURIComponent(
1119
- address
1120
- )}&txHash=${txHashParam}&limit=1`
1121
- );
1122
- const response = await fetch(url, {
1123
- method: "GET",
1124
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1125
- cache: "no-store"
1126
- });
1127
- if (!response.ok) {
1128
- debugLog(debug, scope, "fetchStatus:miss", {
1129
- address,
1130
- txHash: shortRef(normalized),
1131
- status: response.status
1132
- });
1133
- return { lastEvent: void 0 };
1134
- }
1135
- const body = await response.json();
1136
- const row = _optionalChain([body, 'access', _25 => _25.deposits, 'optionalAccess', _26 => _26[0]]);
1137
- const lastEvent = row ? depositRowToEvent(row) : void 0;
1138
- debugLog(debug, scope, "fetchStatus:success", {
1139
- address,
1140
- txHash: shortRef(normalized),
1141
- eventType: _optionalChain([lastEvent, 'optionalAccess', _27 => _27.type])
1142
- });
1143
- return { lastEvent };
1144
- },
1145
- async lookupRecoverableDeposits(params) {
1146
- const txHashParam = params.txHash.startsWith("0x") ? params.txHash.toLowerCase() : params.txHash;
1147
- const url = apiUrl(
1148
- `/deposits?txHash=${encodeURIComponent(txHashParam)}&includeSpam=true`
1149
- );
1150
- const response = await fetch(url, {
1151
- method: "GET",
1152
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1153
- cache: "no-store"
1154
- });
1155
- if (!response.ok) {
1156
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1157
- debugError(debug, scope, "lookupRecoverableDeposits:failed", error, {
1158
- status: response.status
1159
- });
1160
- throw new Error(error.error || `Lookup failed: ${response.status}`);
1161
- }
1162
- const body = await response.json();
1163
- const deposits = _nullishCoalesce(body.deposits, () => ( []));
1164
- debugLog(debug, scope, "lookupRecoverableDeposits:success", {
1165
- txHash: shortRef(txHashParam),
1166
- count: deposits.length
1167
- });
1168
- return deposits;
1169
- },
1170
- async fetchLatestStatus(address) {
1171
- const url = apiUrl(
1172
- `/deposits?account=${encodeURIComponent(address)}&limit=1`
1173
- );
1174
- const response = await fetch(url, {
1175
- method: "GET",
1176
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1177
- cache: "no-store"
1178
- });
1179
- if (!response.ok) {
1180
- debugLog(debug, scope, "fetchLatestStatus:miss", {
1181
- address,
1182
- status: response.status
1183
- });
1184
- return { lastEvent: void 0 };
1185
- }
1186
- const body = await response.json();
1187
- const row = _optionalChain([body, 'access', _28 => _28.deposits, 'optionalAccess', _29 => _29[0]]);
1188
- const lastEvent = row ? depositRowToEvent(row) : void 0;
1189
- debugLog(debug, scope, "fetchLatestStatus:success", {
1190
- address,
1191
- eventType: _optionalChain([lastEvent, 'optionalAccess', _30 => _30.type])
1192
- });
1193
- return { lastEvent };
1194
- },
1195
- async getPositions(address) {
1196
- const url = apiUrl(`/positions/${address}`);
1197
- debugLog(debug, scope, "getPositions:request", { url, address });
1198
- const response = await fetch(url, { headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ) });
1199
- if (!response.ok) {
1200
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1201
- debugError(debug, scope, "getPositions:failed", error, {
1202
- status: response.status,
1203
- address
1204
- });
1205
- throw new Error(
1206
- error.error || `Position lookup failed: ${response.status}`
1207
- );
1208
- }
1209
- const result = await response.json();
1210
- debugLog(debug, scope, "getPositions:success", {
1211
- address,
1212
- count: _nullishCoalesce(_optionalChain([result, 'access', _31 => _31.positions, 'optionalAccess', _32 => _32.length]), () => ( 0)),
1213
- totalUsd: result.totalUsd,
1214
- failures: _optionalChain([result, 'access', _33 => _33.failures, 'optionalAccess', _34 => _34.map, 'call', _35 => _35((f) => f.venue)])
1215
- });
1216
- return result;
1217
- },
1218
- async prepareUnwind(params) {
1219
- const { address, account, market, chainId, asset, amount } = params;
1220
- const url = apiUrl(`/positions/${address}/unwind`);
1221
- debugLog(debug, scope, "prepareUnwind:request", {
1222
- url,
1223
- address,
1224
- account,
1225
- market,
1226
- chainId,
1227
- asset,
1228
- amount
1229
- });
1230
- const response = await fetch(url, {
1231
- method: "POST",
1232
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1233
- body: JSON.stringify({ account, market, chainId, asset, amount })
1234
- });
1235
- if (!response.ok) {
1236
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1237
- debugError(debug, scope, "prepareUnwind:failed", error, {
1238
- status: response.status,
1239
- address,
1240
- market,
1241
- asset
1242
- });
1243
- throw new Error(
1244
- error.error || `Unwind preparation failed: ${response.status}`
1245
- );
1246
- }
1247
- const result = await response.json();
1248
- debugLog(debug, scope, "prepareUnwind:success", {
1249
- address,
1250
- amount: result.amount,
1251
- isFullExit: result.isFullExit,
1252
- recipient: result.recipient
1253
- });
1254
- return result;
1255
- },
1256
- async submitPolymarketWithdraw(params) {
1257
- const { depositWallet, owner, nonce, deadline, calls, signature } = params;
1258
- const url = apiUrl(`/polymarket/withdraw`);
1259
- debugLog(debug, scope, "submitPolymarketWithdraw:request", {
1260
- url,
1261
- depositWallet,
1262
- owner,
1263
- nonce,
1264
- callCount: calls.length
1265
- });
1266
- const response = await fetch(url, {
1267
- method: "POST",
1268
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1269
- body: JSON.stringify({
1270
- depositWallet,
1271
- owner,
1272
- nonce,
1273
- deadline,
1274
- calls,
1275
- signature
1276
- })
1277
- });
1278
- if (!response.ok) {
1279
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1280
- debugError(debug, scope, "submitPolymarketWithdraw:failed", error, {
1281
- status: response.status,
1282
- depositWallet,
1283
- owner
1284
- });
1285
- throw new Error(
1286
- error.error || `Polymarket withdraw failed: ${response.status}`
1287
- );
1288
- }
1289
- const result = await response.json();
1290
- debugLog(debug, scope, "submitPolymarketWithdraw:success", {
1291
- depositWallet,
1292
- txHash: _optionalChain([result, 'optionalAccess', _36 => _36.txHash]) ? shortRef(result.txHash) : void 0
1293
- });
1294
- return result;
1295
- },
1296
- async fetchDepositHistory(params) {
1297
- const searchParams = new URLSearchParams({ recipient: params.recipient });
1298
- searchParams.set("limit", String(_nullishCoalesce(params.limit, () => ( 20))));
1299
- if (params.cursor) {
1300
- searchParams.set("cursor", params.cursor);
1301
- }
1302
- const url = apiUrl(`/deposits?${searchParams.toString()}`);
1303
- debugLog(debug, scope, "fetchDepositHistory:request", {
1304
- url,
1305
- recipient: shortRef(params.recipient),
1306
- cursor: params.cursor
1307
- });
1308
- const response = await fetch(url, {
1309
- method: "GET",
1310
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1311
- cache: "no-store"
1312
- });
1313
- if (!response.ok) {
1314
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1315
- debugError(debug, scope, "fetchDepositHistory:failed", error, {
1316
- status: response.status,
1317
- recipient: shortRef(params.recipient)
1318
- });
1319
- throw new Error(
1320
- error.error || `Deposit history fetch failed: ${response.status}`
1321
- );
1322
- }
1323
- const data = await response.json();
1324
- const deposits = Array.isArray(_optionalChain([data, 'optionalAccess', _37 => _37.deposits])) ? data.deposits : [];
1325
- const nextCursor = _nullishCoalesce(_nullishCoalesce(_optionalChain([data, 'optionalAccess', _38 => _38.nextCursor]), () => ( _optionalChain([data, 'optionalAccess', _39 => _39.next_cursor]))), () => ( null));
1326
- debugLog(debug, scope, "fetchDepositHistory:success", {
1327
- recipient: shortRef(params.recipient),
1328
- count: deposits.length,
1329
- hasMore: Boolean(nextCursor)
1330
- });
1331
- return { deposits, nextCursor };
1332
- },
1333
- async checkLiquidity(params) {
1334
- if (_chunk4KCSH4T3cjs.isSolanaCaip2.call(void 0, params.destinationChainId) || params.destinationChainId === "solana") {
1335
- const token = _chunk4KCSH4T3cjs.getSolanaTokenByMint.call(void 0, params.destinationToken);
1336
- return {
1337
- hasLiquidity: true,
1338
- symbol: _nullishCoalesce(_optionalChain([token, 'optionalAccess', _40 => _40.symbol]), () => ( "Token")),
1339
- decimals: _nullishCoalesce(_optionalChain([token, 'optionalAccess', _41 => _41.decimals]), () => ( 9)),
1340
- unlimited: true,
1341
- maxAmount: null
1342
- };
1343
- }
1344
- const searchParams = new URLSearchParams({
1345
- sourceChainId: _chunk4KCSH4T3cjs.toEvmCaip2.call(void 0, params.sourceChainId),
1346
- sourceToken: params.sourceToken,
1347
- destinationChainId: params.destinationChainId,
1348
- destinationToken: params.destinationToken,
1349
- amount: params.amount
1350
- });
1351
- const url = apiUrl(`/liquidity?${searchParams.toString()}`);
1352
- debugLog(debug, scope, "checkLiquidity:request", {
1353
- url,
1354
- sourceChainId: params.sourceChainId,
1355
- destinationChainId: params.destinationChainId,
1356
- amount: params.amount
1357
- });
1358
- const response = await fetch(url, {
1359
- method: "GET",
1360
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1361
- cache: "no-store"
1362
- });
1363
- if (!response.ok) {
1364
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1365
- debugError(debug, scope, "checkLiquidity:failed", error, {
1366
- status: response.status
1367
- });
1368
- throw new Error(
1369
- error.error || `Liquidity check failed: ${response.status}`
1370
- );
1371
- }
1372
- const data = await response.json();
1373
- const result = {
1374
- hasLiquidity: data.hasLiquidity === true,
1375
- symbol: typeof data.symbol === "string" ? data.symbol : "",
1376
- decimals: typeof data.decimals === "number" ? data.decimals : 0,
1377
- unlimited: data.unlimited === true,
1378
- maxAmount: typeof data.maxAmount === "string" ? data.maxAmount : null
1379
- };
1380
- debugLog(debug, scope, "checkLiquidity:success", {
1381
- hasLiquidity: result.hasLiquidity,
1382
- unlimited: result.unlimited,
1383
- maxAmount: result.maxAmount
1384
- });
1385
- return result;
1386
- },
1387
- async getQuotePreview(params) {
1388
- const url = apiUrl("/quotes/preview");
1389
- const body = {
1390
- account: params.account,
1391
- // HyperCore has its own CAIP-2 namespace — never the eip155 placeholder.
1392
- // The branch is unreachable against today's processor whatever venue it
1393
- // names: `sourceToken` is validated as a 20-byte 0x address on every
1394
- // chain, and a HyperCore source token is a 16-byte Core spot tokenId.
1395
- sourceChainId: params.sourceChainId === "hypercore" ? _chunk4KCSH4T3cjs.HYPERCORE_SPOT_CAIP2 : `eip155:${params.sourceChainId}`,
1396
- sourceToken: params.sourceToken,
1397
- amount: params.amount
1398
- };
1399
- debugLog(debug, scope, "getQuotePreview:request", {
1400
- url,
1401
- sourceChainId: body.sourceChainId,
1402
- sourceToken: params.sourceToken,
1403
- amount: params.amount
1404
- });
1405
- try {
1406
- const response = await fetch(url, {
1407
- method: "POST",
1408
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1409
- body: JSON.stringify(body),
1410
- cache: "no-store"
1411
- });
1412
- if (!response.ok) {
1413
- debugLog(debug, scope, "getQuotePreview:unavailable", {
1414
- status: response.status
1415
- });
1416
- return null;
1417
- }
1418
- const quote = parseQuotePreview(await response.json());
1419
- if (!quote) {
1420
- debugLog(debug, scope, "getQuotePreview:unavailable", {
1421
- status: response.status,
1422
- reason: "malformed"
1423
- });
1424
- return null;
1425
- }
1426
- debugLog(debug, scope, "getQuotePreview:success", {
1427
- settlementLayer: quote.settlementLayer,
1428
- totalUsd: quote.fees.total.usd
1429
- });
1430
- return quote;
1431
- } catch (error) {
1432
- debugError(debug, scope, "getQuotePreview:error", error);
1433
- return null;
1434
- }
1435
- },
1436
- async preparePermitDeposit(params) {
1437
- const url = apiUrl("/deposits/permit/prepare");
1438
- debugLog(debug, scope, "preparePermitDeposit:request", {
1439
- url,
1440
- account: shortRef(params.account),
1441
- sourceChain: params.sourceChain,
1442
- token: params.token,
1443
- amount: params.amount
1444
- });
1445
- try {
1446
- const response = await fetch(url, {
1447
- method: "POST",
1448
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1449
- body: JSON.stringify({ ...params, kind: "auto" }),
1450
- cache: "no-store"
1451
- });
1452
- if (!response.ok) {
1453
- debugLog(debug, scope, "preparePermitDeposit:unavailable", {
1454
- status: response.status
1455
- });
1456
- return null;
1457
- }
1458
- const data = await response.json();
1459
- if (!data || typeof data.available !== "boolean") {
1460
- debugLog(debug, scope, "preparePermitDeposit:unavailable", {
1461
- status: response.status,
1462
- reason: "malformed"
1463
- });
1464
- return null;
1465
- }
1466
- if (data.available === false) {
1467
- const reason = data.reason;
1468
- if (reason !== "permit2-approval-required" && reason !== "unsupported-token" && reason !== "unsupported-owner") {
1469
- return null;
1470
- }
1471
- debugLog(debug, scope, "preparePermitDeposit:unavailable", {
1472
- status: response.status,
1473
- reason
1474
- });
1475
- const approval = data.approval;
1476
- const parsedApproval = approval && typeof approval.token === "string" && typeof approval.spender === "string" && typeof approval.minimumAmount === "string" ? {
1477
- token: approval.token,
1478
- spender: approval.spender,
1479
- minimumAmount: approval.minimumAmount
1480
- } : void 0;
1481
- return {
1482
- available: false,
1483
- reason,
1484
- ...parsedApproval && { approval: parsedApproval }
1485
- };
1486
- }
1487
- const authorization = data.authorization;
1488
- if (!authorization || typeof authorization.typedData !== "object" || authorization.typedData === null || typeof authorization.nonce !== "string") {
1489
- return null;
1490
- }
1491
- if (authorization.kind === "erc3009" && typeof authorization.validAfter === "string" && typeof authorization.validBefore === "string") {
1492
- debugLog(debug, scope, "preparePermitDeposit:success", {
1493
- kind: authorization.kind,
1494
- nonce: authorization.nonce
1495
- });
1496
- return {
1497
- available: true,
1498
- authorization: {
1499
- kind: "erc3009",
1500
- typedData: authorization.typedData,
1501
- nonce: authorization.nonce,
1502
- validAfter: authorization.validAfter,
1503
- validBefore: authorization.validBefore
1504
- }
1505
- };
1506
- }
1507
- if ((authorization.kind === "erc2612" || authorization.kind === "permit2") && typeof authorization.deadline === "string") {
1508
- debugLog(debug, scope, "preparePermitDeposit:success", {
1509
- kind: authorization.kind,
1510
- nonce: authorization.nonce
1511
- });
1512
- return {
1513
- available: true,
1514
- authorization: {
1515
- kind: authorization.kind,
1516
- typedData: authorization.typedData,
1517
- nonce: authorization.nonce,
1518
- deadline: authorization.deadline
1519
- }
1520
- };
1521
- }
1522
- return null;
1523
- } catch (error) {
1524
- debugError(debug, scope, "preparePermitDeposit:error", error);
1525
- return null;
1526
- }
1527
- },
1528
- async submitPermitDeposit(params) {
1529
- const url = apiUrl("/deposits/permit");
1530
- debugLog(debug, scope, "submitPermitDeposit:request", {
1531
- url,
1532
- account: shortRef(params.account),
1533
- sourceChain: params.sourceChain,
1534
- token: params.token,
1535
- amount: params.amount,
1536
- nonce: params.nonce
1537
- });
1538
- let response;
1539
- try {
1540
- response = await fetch(url, {
1541
- method: "POST",
1542
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1543
- body: JSON.stringify(params)
1544
- });
1545
- } catch (error) {
1546
- const message = error instanceof Error ? error.message : "Network error";
1547
- throw new PermitDepositSubmitError(message, false);
1548
- }
1549
- if (!response.ok) {
1550
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1551
- debugError(debug, scope, "submitPermitDeposit:failed", error, {
1552
- status: response.status,
1553
- account: shortRef(params.account)
1554
- });
1555
- const safeToTransfer = [400, 401, 403, 404, 422].includes(
1556
- response.status
1557
- );
1558
- throw new PermitDepositSubmitError(
1559
- error.error || `Permit deposit failed: ${response.status}`,
1560
- safeToTransfer
1561
- );
1562
- }
1563
- const result = await response.json();
1564
- if (typeof _optionalChain([result, 'optionalAccess', _42 => _42.txHash]) !== "string" || result.txHash.length === 0) {
1565
- debugError(debug, scope, "submitPermitDeposit:failed", result, {
1566
- reason: "missing txHash"
1567
- });
1568
- throw new PermitDepositSubmitError(
1569
- "Permit deposit response missing txHash",
1570
- false
1571
- );
1572
- }
1573
- debugLog(debug, scope, "submitPermitDeposit:success", {
1574
- depositId: result.depositId,
1575
- txHash: shortRef(result.txHash),
1576
- status: result.status
1577
- });
1578
- return {
1579
- depositId: _nullishCoalesce(result.depositId, () => ( "")),
1580
- txHash: result.txHash,
1581
- status: _nullishCoalesce(result.status, () => ( "processing"))
1582
- };
1583
- },
1584
- async fetchPrices(symbols) {
1585
- const list = symbols.filter((s) => s.length > 0);
1586
- if (list.length === 0) return {};
1587
- const url = apiUrl(
1588
- `/prices?${new URLSearchParams({ symbols: list.join(",") }).toString()}`
1589
- );
1590
- try {
1591
- const response = await fetch(url, {
1592
- method: "GET",
1593
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1594
- cache: "no-store"
1595
- });
1596
- if (!response.ok) {
1597
- debugError(debug, scope, "fetchPrices:failed", {
1598
- status: response.status
1599
- });
1600
- return {};
1601
- }
1602
- const data = await response.json();
1603
- return Object.fromEntries(
1604
- Object.entries(_nullishCoalesce(data.prices, () => ( {}))).map(([symbol, price]) => [
1605
- symbol.toUpperCase(),
1606
- price
1607
- ])
1608
- );
1609
- } catch (err) {
1610
- debugError(debug, scope, "fetchPrices:error", err);
1611
- return {};
1612
- }
1613
- },
1614
- async fetchPricesByAddress(caip2Ids) {
1615
- const list = caip2Ids.filter((id) => id.length > 0);
1616
- if (list.length === 0) return {};
1617
- const url = apiUrl(
1618
- `/prices?${new URLSearchParams({
1619
- addresses: list.join(",")
1620
- }).toString()}`
1621
- );
1622
- try {
1623
- const response = await fetch(url, {
1624
- method: "GET",
1625
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1626
- cache: "no-store"
1627
- });
1628
- if (!response.ok) {
1629
- debugError(debug, scope, "fetchPricesByAddress:failed", {
1630
- status: response.status
1631
- });
1632
- return {};
1633
- }
1634
- const data = await response.json();
1635
- return _nullishCoalesce(data.prices, () => ( {}));
1636
- } catch (err) {
1637
- debugError(debug, scope, "fetchPricesByAddress:error", err);
1638
- return {};
1639
- }
1640
- },
1641
- async getSwappedWidgetUrl(params) {
1642
- const url = apiUrl("/onramp/swapped/widget-url");
1643
- debugLog(debug, scope, "getSwappedWidgetUrl:request", {
1644
- smartAccount: shortRef(params.smartAccount),
1645
- method: params.method,
1646
- methodSelectionSource: params.methodSelectionSource
1647
- });
1648
- const response = await fetch(url, {
1649
- method: "POST",
1650
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1651
- body: JSON.stringify(params)
1652
- });
1653
- if (!response.ok) {
1654
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1655
- debugError(debug, scope, "getSwappedWidgetUrl:failed", error, {
1656
- status: response.status
1657
- });
1658
- throw new Error(
1659
- error.error || `Swapped widget URL failed: ${response.status}`
1660
- );
1661
- }
1662
- const body = await response.json();
1663
- if (typeof body.url !== "string" || typeof body.currencyCode !== "string" || typeof body.externalCustomerId !== "string") {
1664
- throw new Error("Swapped widget URL: malformed response");
1665
- }
1666
- return {
1667
- url: body.url,
1668
- currencyCode: body.currencyCode,
1669
- sandbox: body.sandbox === true,
1670
- externalCustomerId: body.externalCustomerId,
1671
- expiresAt: body.expiresAt
1672
- };
1673
- },
1674
- async getSwappedConnectUrl(params) {
1675
- const url = apiUrl("/onramp/swapped/connect-url");
1676
- debugLog(debug, scope, "getSwappedConnectUrl:request", {
1677
- smartAccount: shortRef(params.smartAccount),
1678
- connection: params.connection
1679
- });
1680
- const response = await fetch(url, {
1681
- method: "POST",
1682
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1683
- body: JSON.stringify(params)
1684
- });
1685
- if (!response.ok) {
1686
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1687
- debugError(debug, scope, "getSwappedConnectUrl:failed", error, {
1688
- status: response.status
1689
- });
1690
- const currentFeeBps = parseExchangeFeeBps(error.exchangeFeeBps);
1691
- if (response.status === 409 && currentFeeBps !== void 0) {
1692
- throw new SwappedConnectFeeChangedError(
1693
- currentFeeBps,
1694
- typeof error.error === "string" ? error.error : void 0
1695
- );
1696
- }
1697
- throw new Error(
1698
- typeof error.error === "string" && error.error || `Swapped Connect URL failed: ${response.status}`
1699
- );
1700
- }
1701
- const body = await response.json();
1702
- if (typeof body.url !== "string" || typeof body.currencyCode !== "string" || typeof body.externalCustomerId !== "string") {
1703
- throw new Error("Swapped Connect URL: malformed response");
1704
- }
1705
- return {
1706
- url: body.url,
1707
- currencyCode: body.currencyCode,
1708
- sandbox: body.sandbox === true,
1709
- externalCustomerId: body.externalCustomerId,
1710
- expiresAt: body.expiresAt,
1711
- exchangeFeeBps: parseExchangeFeeBps(body.exchangeFeeBps)
1712
- };
1713
- },
1714
- async getSwappedConnectExchanges() {
1715
- const url = apiUrl("/onramp/swapped/connect-exchanges");
1716
- debugLog(debug, scope, "getSwappedConnectExchanges:request");
1717
- const response = await fetch(url, {
1718
- method: "GET",
1719
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1720
- cache: "no-store"
1721
- });
1722
- if (!response.ok) {
1723
- const error = await response.json().catch(() => ({ error: "Unknown error" }));
1724
- debugError(debug, scope, "getSwappedConnectExchanges:failed", error, {
1725
- status: response.status
1726
- });
1727
- throw new Error(
1728
- error.error || `Swapped Connect exchanges failed: ${response.status}`
1729
- );
1730
- }
1731
- const body = await response.json();
1732
- const rawExchanges = Array.isArray(body.exchanges) ? body.exchanges : null;
1733
- const exchanges = [];
1734
- let hasMalformedExchange = rawExchanges === null;
1735
- for (const exchange of _nullishCoalesce(rawExchanges, () => ( []))) {
1736
- if (!exchange || typeof exchange !== "object") {
1737
- hasMalformedExchange = true;
1738
- continue;
1739
- }
1740
- const raw = exchange;
1741
- const connection = typeof raw.connection === "string" ? raw.connection : "";
1742
- const name = typeof raw.name === "string" ? raw.name : "";
1743
- const logoUrl = typeof raw.logoUrl === "string" || raw.logoUrl === null ? raw.logoUrl : null;
1744
- if (!connection || !name) {
1745
- hasMalformedExchange = true;
1746
- continue;
1747
- }
1748
- exchanges.push({ connection, name, logoUrl });
1749
- }
1750
- if (hasMalformedExchange || typeof body.fetchedAt !== "string" || typeof body.expiresAt !== "string") {
1751
- throw new Error("Swapped Connect exchanges: malformed response");
1752
- }
1753
- return {
1754
- exchanges: exchanges.filter(isSupportedConnectExchange),
1755
- fetchedAt: body.fetchedAt,
1756
- expiresAt: body.expiresAt,
1757
- stale: body.stale === true ? true : void 0,
1758
- exchangeFeeBps: parseExchangeFeeBps(body.exchangeFeeBps)
1759
- };
1760
- },
1761
- async getSwappedPaymentMethods() {
1762
- const empty = {
1763
- country: null,
1764
- methods: [],
1765
- recommendedMethod: null
1766
- };
1767
- const url = apiUrl("/onramp/swapped/payment-methods");
1768
- debugLog(debug, scope, "getSwappedPaymentMethods:request");
1769
- try {
1770
- const response = await fetch(url, {
1771
- method: "GET",
1772
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1773
- cache: "no-store"
1774
- });
1775
- if (!response.ok) {
1776
- debugLog(debug, scope, "getSwappedPaymentMethods:unavailable", {
1777
- status: response.status
1778
- });
1779
- return empty;
1780
- }
1781
- const body = await response.json();
1782
- if (!body || typeof body !== "object" || Array.isArray(body)) {
1783
- return empty;
1784
- }
1785
- const rawBody = body;
1786
- const rawCountry = rawBody.country;
1787
- const country = typeof rawCountry === "string" ? rawCountry.trim().toUpperCase() : rawCountry === null ? null : void 0;
1788
- if (country === void 0 || country !== null && !/^[A-Z]{2}$/.test(country)) {
1789
- return empty;
1790
- }
1791
- const rawRecommendedMethod = rawBody.recommendedMethod;
1792
- const recommendedMethod = typeof rawRecommendedMethod === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(rawRecommendedMethod) ? rawRecommendedMethod : rawRecommendedMethod === null ? null : void 0;
1793
- if (recommendedMethod === void 0 || !Array.isArray(rawBody.methods)) {
1794
- return empty;
1795
- }
1796
- const methods = [];
1797
- const seen = /* @__PURE__ */ new Set();
1798
- for (const raw of rawBody.methods) {
1799
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1800
- return empty;
1801
- }
1802
- const m = raw;
1803
- const method = typeof m.method === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(m.method) ? m.method : null;
1804
- const label = typeof m.label === "string" && m.label.trim().length > 0 ? m.label.trim() : null;
1805
- const iconUrl = typeof m.iconUrl === "string" ? m.iconUrl : m.iconUrl === null ? null : void 0;
1806
- const iconUrlLight = typeof m.iconUrlLight === "string" ? m.iconUrlLight : m.iconUrlLight === null ? null : void 0;
1807
- const minAmount = typeof m.minAmount === "number" && Number.isFinite(m.minAmount) && m.minAmount >= 0 ? m.minAmount : m.minAmount === null ? null : void 0;
1808
- const maxAmount = typeof m.maxAmount === "number" && Number.isFinite(m.maxAmount) && m.maxAmount >= 0 ? m.maxAmount : m.maxAmount === null ? null : void 0;
1809
- const badge = m.badge === "Popular" ? "Popular" : m.badge === null ? null : void 0;
1810
- if (!method || !label || iconUrl === void 0 || iconUrlLight === void 0 || minAmount === void 0 || maxAmount === void 0 || badge === void 0 || seen.has(method)) {
1811
- return empty;
1812
- }
1813
- seen.add(method);
1814
- methods.push({
1815
- method,
1816
- label,
1817
- iconUrl,
1818
- iconUrlLight,
1819
- minAmount,
1820
- maxAmount,
1821
- badge
1822
- });
1823
- }
1824
- if (country === null && (methods.length > 0 || recommendedMethod !== null) || recommendedMethod !== null && !seen.has(recommendedMethod)) {
1825
- return empty;
1826
- }
1827
- return { country, methods, recommendedMethod };
1828
- } catch (error) {
1829
- debugError(debug, scope, "getSwappedPaymentMethods:error", error);
1830
- return empty;
1831
- }
1832
- },
1833
- getTopTokens() {
1834
- if (!topTokensPromise) {
1835
- const attempt = requestTopTokens().then((tokens) => {
1836
- if (!tokens && topTokensPromise === attempt) topTokensPromise = null;
1837
- return tokens;
1838
- });
1839
- topTokensPromise = attempt;
1840
- }
1841
- return topTokensPromise;
1842
- },
1843
- getChains() {
1844
- if (!chainsPromise) {
1845
- const attempt = requestChains().then((catalog) => {
1846
- if (!catalog && chainsPromise === attempt) chainsPromise = null;
1847
- return catalog;
1848
- });
1849
- chainsPromise = attempt;
1850
- }
1851
- return chainsPromise;
1852
- },
1853
- async getSetup() {
1854
- const url = apiUrl("/setup");
1855
- try {
1856
- const response = await fetch(url, {
1857
- method: "GET",
1858
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1859
- cache: "no-store"
1860
- });
1861
- if (!response.ok) {
1862
- debugLog(debug, scope, "getSetup:unavailable", {
1863
- status: response.status
1864
- });
1865
- return null;
1866
- }
1867
- const data = await response.json();
1868
- debugLog(debug, scope, "getSetup:success", {
1869
- hasWhitelist: Boolean(data.depositWhitelist),
1870
- whitelistChains: data.depositWhitelist ? Object.keys(data.depositWhitelist).length : 0,
1871
- minDepositUsd: data.minDepositUsd
1872
- });
1873
- return data;
1874
- } catch (error) {
1875
- debugError(debug, scope, "getSetup:error", error);
1876
- return null;
1877
- }
1878
- },
1879
- async fetchSwappedOrderStatus(smartAccount) {
1880
- const url = apiUrl(
1881
- `/onramp/swapped/status/${encodeURIComponent(smartAccount)}`
1882
- );
1883
- const response = await fetch(url, {
1884
- method: "GET",
1885
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
1886
- cache: "no-store"
1887
- });
1888
- if (!response.ok) return null;
1889
- let body = null;
1890
- try {
1891
- body = await response.json();
1892
- } catch (e3) {
1893
- return null;
1894
- }
1895
- if (!body || body.ok !== true) return null;
1896
- const status = typeof body.status === "string" ? body.status : null;
1897
- const orderId = typeof body.orderId === "string" ? body.orderId : null;
1898
- if (!status || !orderId) return null;
1899
- const numericOrNull = (v) => {
1900
- if (typeof v === "number") {
1901
- return Number.isFinite(v) ? v : null;
1902
- }
1903
- if (typeof v === "string" && v.trim().length > 0) {
1904
- const parsed = Number(v);
1905
- return Number.isFinite(parsed) ? parsed : null;
1906
- }
1907
- return null;
1908
- };
1909
- return {
1910
- orderId,
1911
- status,
1912
- orderCrypto: typeof body.orderCrypto === "string" ? body.orderCrypto : null,
1913
- orderCryptoAmount: typeof body.orderCryptoAmount === "string" ? body.orderCryptoAmount : null,
1914
- transactionId: typeof body.transactionId === "string" ? body.transactionId : null,
1915
- receivedAt: typeof body.receivedAt === "string" ? body.receivedAt : null,
1916
- paidAmountUsd: numericOrNull(body.paidAmountUsd),
1917
- paidAmountEur: numericOrNull(body.paidAmountEur),
1918
- onrampFeeUsd: numericOrNull(body.onrampFeeUsd),
1919
- paymentMethod: typeof body.paymentMethod === "string" ? body.paymentMethod : null
1920
- };
1921
- }
1922
- };
1923
- }
1924
- function normalizeDirectPortfolio(data) {
1925
- const rawTokens = _nullishCoalesce(_nullishCoalesce(extractArray(data, "tokens"), () => ( extractArray(
1926
- _optionalChain([data, 'optionalAccess', _43 => _43.data]),
1927
- "tokens"
1928
- ))), () => ( []));
1929
- const totalUsd = _nullishCoalesce(_nullishCoalesce(extractNumber(data, "totalUsd"), () => ( extractNumber(_optionalChain([data, 'optionalAccess', _44 => _44.data]), "totalUsd"))), () => ( 0));
1930
- const tokens = rawTokens.map((token) => normalizeDirectToken(token)).filter((token) => Boolean(token));
1931
- return { tokens, totalUsd };
1932
- }
1933
- function extractOrchestratorPortfolio(data) {
1934
- const portfolio = _nullishCoalesce(extractArray(data, "portfolio"), () => ( extractArray(
1935
- _optionalChain([data, 'optionalAccess', _45 => _45.data]),
1936
- "portfolio"
1937
- )));
1938
- if (!portfolio || !Array.isArray(portfolio)) return null;
1939
- return { portfolio };
1940
- }
1941
- function normalizeOrchestratorPortfolio(data) {
1942
- const tokens = [];
1943
- for (const tokenData of data.portfolio || []) {
1944
- const chainBalances = _nullishCoalesce(_nullishCoalesce(tokenData.tokenChainBalance, () => ( tokenData.chainBalances)), () => ( []));
1945
- for (const chainBalance of chainBalances) {
1946
- const unlocked = _nullishCoalesce(_optionalChain([chainBalance, 'access', _46 => _46.balance, 'optionalAccess', _47 => _47.unlocked]), () => ( "0"));
1947
- const normalizedName = tokenData.tokenName.trim();
1948
- const isNativeSymbol = normalizedName.toUpperCase() === "ETH" || normalizedName.toUpperCase() === "ETHER";
1949
- const tokenAddress = _nullishCoalesce(_nullishCoalesce(chainBalance.tokenAddress, () => ( extractTokenAddress(tokenData, chainBalance.chainId))), () => ( _chunk4KCSH4T3cjs.getTokenAddress.call(void 0, tokenData.tokenName, chainBalance.chainId)));
1950
- const resolvedTokenAddress = isNativeSymbol ? _chunk4KCSH4T3cjs.NATIVE_TOKEN_ADDRESS : tokenAddress;
1951
- if (!resolvedTokenAddress) {
1952
- continue;
1953
- }
1954
- const registrySymbol = _chunk4KCSH4T3cjs.getTokenSymbol.call(void 0,
1955
- resolvedTokenAddress,
1956
- chainBalance.chainId
1957
- );
1958
- const symbol = registrySymbol !== "Token" ? registrySymbol : normalizedName || "Token";
1959
- const decimals = registrySymbol !== "Token" ? _chunk4KCSH4T3cjs.getTokenDecimalsByAddress.call(void 0,
1960
- resolvedTokenAddress,
1961
- chainBalance.chainId
1962
- ) : _nullishCoalesce(tokenData.tokenDecimals, () => ( 18));
1963
- tokens.push({
1964
- chainId: chainBalance.chainId,
1965
- address: resolvedTokenAddress,
1966
- symbol,
1967
- name: symbol,
1968
- decimals,
1969
- balance: unlocked,
1970
- balanceUsd: 0
1971
- });
1972
- }
1973
- }
1974
- return {
1975
- tokens,
1976
- totalUsd: 0
1977
- };
1978
- }
1979
- function normalizeDirectToken(token) {
1980
- const rawChainId = _nullishCoalesce(extractNumber(token, "chainId"), () => ( extractNumber(token.chain, "id")));
1981
- const rawChainString = _nullishCoalesce(extractString(token, "chainId"), () => ( extractString(token.chain, "id")));
1982
- const chainId = _nullishCoalesce(rawChainId, () => ( (rawChainString ? _chunk4KCSH4T3cjs.isSolanaCaip2.call(void 0, rawChainString) || rawChainString.toLowerCase() === "solana" ? "solana" : (
1983
- // HyperCore is a non-EVM source under its own namespace; keep its
1984
- // USDC instead of dropping it as an unparseable chain string.
1985
- _chunk4KCSH4T3cjs.isHyperCoreCaip2.call(void 0, rawChainString) || rawChainString.toLowerCase() === "hypercore" ? "hypercore" : _chunk4KCSH4T3cjs.parseEvmChainId.call(void 0, rawChainString)
1986
- ) : null)));
1987
- if (chainId === null) return null;
1988
- const registryChainId = typeof chainId === "number" ? chainId : chainId === "hypercore" ? _chunk4KCSH4T3cjs.HYPERCORE_CHAIN_ID : void 0;
1989
- const symbol = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(extractString(token, "symbol"), () => ( extractString(token, "tokenSymbol"))), () => ( extractString(token, "tokenName"))), () => ( extractString(token, "name")));
1990
- if (!symbol) return null;
1991
- const balanceValue = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(extractString(token, "balance"), () => ( extractString(token, "amount"))), () => ( extractString(token, "value"))), () => ( extractString(token, "rawBalance"))), () => ( _optionalChain([extractNumber, 'call', _48 => _48(token, "balance"), 'optionalAccess', _49 => _49.toString, 'call', _50 => _50()]))), () => ( _optionalChain([extractNumber, 'call', _51 => _51(token, "amount"), 'optionalAccess', _52 => _52.toString, 'call', _53 => _53()]))), () => ( _optionalChain([extractNumber, 'call', _54 => _54(token, "value"), 'optionalAccess', _55 => _55.toString, 'call', _56 => _56()]))), () => ( _optionalChain([extractNumber, 'call', _57 => _57(token, "rawBalance"), 'optionalAccess', _58 => _58.toString, 'call', _59 => _59()])));
1992
- if (!balanceValue) return null;
1993
- const address = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(extractString(token, "address"), () => ( extractString(token, "tokenAddress"))), () => ( extractString(
1994
- token.token,
1995
- "address"
1996
- ))), () => ( (registryChainId !== void 0 ? _chunk4KCSH4T3cjs.getTokenAddress.call(void 0, symbol, registryChainId) : void 0)));
1997
- if (!address) return null;
1998
- const balanceUsd = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(extractNumber(token, "balanceUsd"), () => ( extractNumber(token, "usdValue"))), () => ( extractNumber(token, "valueUsd"))), () => ( extractNumericString(token, "balanceUsd"))), () => ( extractNumericString(token, "usdValue"))), () => ( extractNumericString(token, "valueUsd"))), () => ( 0));
1999
- const isSolanaToken = chainId === "solana";
2000
- const registrySymbol = isSolanaToken ? "Token" : _chunk4KCSH4T3cjs.getTokenSymbol.call(void 0, address, registryChainId);
2001
- const resolvedSymbol = isSolanaToken ? symbol : registrySymbol !== "Token" ? registrySymbol : symbol;
2002
- const backendDecimals = _nullishCoalesce(extractNumber(token, "decimals"), () => ( extractNumber(token, "tokenDecimals")));
2003
- const resolvedDecimals = !isSolanaToken && registrySymbol !== "Token" ? _chunk4KCSH4T3cjs.getTokenDecimalsByAddress.call(void 0, address, registryChainId) : _nullishCoalesce(backendDecimals, () => ( 18));
2004
- return {
2005
- chainId,
2006
- address,
2007
- symbol: resolvedSymbol,
2008
- name: resolvedSymbol,
2009
- decimals: resolvedDecimals,
2010
- balance: balanceValue,
2011
- balanceUsd
2012
- };
2013
- }
2014
- function extractTokenAddress(tokenData, chainId) {
2015
- const token = tokenData;
2016
- return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(token.tokenAddress, () => ( token.address)), () => ( _optionalChain([token, 'access', _60 => _60.addresses, 'optionalAccess', _61 => _61[chainId]]))), () => ( _optionalChain([token, 'access', _62 => _62.token, 'optionalAccess', _63 => _63.address]))), () => ( _optionalChain([token, 'access', _64 => _64.token, 'optionalAccess', _65 => _65.addresses, 'optionalAccess', _66 => _66[chainId]])));
2017
- }
2018
- function extractArray(data, key) {
2019
- if (!data || typeof data !== "object") return null;
2020
- const record = data;
2021
- const value = record[key];
2022
- return Array.isArray(value) ? value : null;
2023
- }
2024
- function extractNumber(data, key) {
2025
- if (!data || typeof data !== "object") return null;
2026
- const record = data;
2027
- const value = record[key];
2028
- return typeof value === "number" ? value : null;
2029
- }
2030
- function extractString(data, key) {
2031
- if (!data || typeof data !== "object") return null;
2032
- const record = data;
2033
- const value = record[key];
2034
- return typeof value === "string" ? value : null;
2035
- }
2036
- function extractNumericString(data, key) {
2037
- const value = extractString(data, key);
2038
- if (!value) return null;
2039
- const parsed = Number(value);
2040
- return Number.isFinite(parsed) ? parsed : null;
2041
- }
2042
-
2043
- // src/core/rpc.ts
2044
-
2045
- function rpcUrlFor(rpcUrls, chain) {
2046
- const url = _optionalChain([rpcUrls, 'optionalAccess', _67 => _67[chain], 'optionalAccess', _68 => _68.trim, 'call', _69 => _69()]);
2047
- return url ? url : void 0;
2048
- }
2049
- var RpcUrlsContext = _react.createContext.call(void 0, void 0);
2050
- var RpcUrlsProvider = RpcUrlsContext.Provider;
2051
- function useRpcUrls() {
2052
- return _react.useContext.call(void 0, RpcUrlsContext);
2053
- }
2054
- function rpcUrlsKey(rpcUrls) {
2055
- if (!rpcUrls) return "";
2056
- return Object.entries(rpcUrls).map(([chain, url]) => [chain, _nullishCoalesce(_optionalChain([url, 'optionalAccess', _70 => _70.trim, 'call', _71 => _71()]), () => ( ""))]).filter(([, url]) => url !== "").map(([chain, url]) => `${chain}=${url}`).sort().join("|");
2057
- }
2058
- function useStableRpcUrls(rpcUrls) {
2059
- const key = rpcUrlsKey(rpcUrls);
2060
- return _react.useMemo.call(void 0, () => rpcUrls, [key]);
2061
- }
2062
-
2063
- // src/core/chain-catalog-context.tsx
2064
-
2065
-
2066
-
2067
-
2068
-
2069
-
2070
-
2071
-
2072
-
2073
- // src/core/public-client.ts
2074
-
2075
- var clientCache = /* @__PURE__ */ new Map();
2076
- var runtimeChainById = /* @__PURE__ */ new Map();
2077
- var BOOTSTRAP_RPC_URL = {
2078
- 1: "https://eth.merkle.io",
2079
- 10: "https://mainnet.optimism.io",
2080
- 56: "https://56.rpc.thirdweb.com",
2081
- 100: "https://rpc.gnosischain.com",
2082
- 130: "https://mainnet.unichain.org",
2083
- 137: "https://polygon.drpc.org",
2084
- 143: "https://rpc.monad.xyz",
2085
- 146: "https://rpc.soniclabs.com",
2086
- 999: "https://rpc.hyperliquid.xyz/evm",
2087
- 1868: "https://rpc.soneium.org",
2088
- 8453: "https://mainnet.base.org",
2089
- 9745: "https://rpc.plasma.to",
2090
- 42161: "https://arb1.arbitrum.io/rpc",
2091
- 747474: "https://rpc.katana.network"
2092
- };
2093
- var runtimeChainsVersion = 0;
2094
- var runtimeChainListeners = /* @__PURE__ */ new Set();
2095
- function subscribeToRuntimeChains(listener) {
2096
- runtimeChainListeners.add(listener);
2097
- return () => {
2098
- runtimeChainListeners.delete(listener);
2099
- };
2100
- }
2101
- function getRuntimeChainsVersion() {
2102
- return runtimeChainsVersion;
2103
- }
2104
- function setRuntimeChains(chains) {
2105
- let changed = false;
2106
- for (const chain of chains) {
2107
- const known = runtimeChainById.get(chain.id);
2108
- if (known === chain) continue;
2109
- runtimeChainById.set(chain.id, chain);
2110
- changed = true;
2111
- for (const key of clientCache.keys()) {
2112
- if (key.startsWith(`${chain.id}|`)) clientCache.delete(key);
2113
- }
2114
- }
2115
- if (!changed) return;
2116
- runtimeChainsVersion += 1;
2117
- for (const listener of runtimeChainListeners) listener();
2118
- }
2119
- function getPublicClient(chainId, rpcUrls) {
2120
- const url = rpcUrlFor(rpcUrls, chainId);
2121
- const cacheKey = `${chainId}|${_nullishCoalesce(url, () => ( ""))}`;
2122
- let client = clientCache.get(cacheKey);
2123
- if (!client) {
2124
- const chain = runtimeChainById.get(chainId);
2125
- client = _viem.createPublicClient.call(void 0, {
2126
- chain,
2127
- transport: _viem.http.call(void 0, _nullishCoalesce(url, () => ( (chain ? void 0 : BOOTSTRAP_RPC_URL[chainId]))))
2128
- });
2129
- clientCache.set(cacheKey, client);
2130
- }
2131
- return client;
2132
- }
2133
-
2134
- // src/core/chain-objects.ts
2135
-
2136
- var viemChainsById = null;
2137
- var viemChainsPromise = null;
2138
- async function loadViemChains() {
2139
- if (viemChainsById) return viemChainsById;
2140
- if (!viemChainsPromise) {
2141
- viemChainsPromise = Promise.resolve().then(() => _interopRequireWildcard(require("viem/chains"))).then((module) => {
2142
- const map = /* @__PURE__ */ new Map();
2143
- for (const value of Object.values(module)) {
2144
- if (value && typeof value === "object" && typeof value.id === "number" && _optionalChain([value, 'access', _72 => _72.rpcUrls, 'optionalAccess', _73 => _73.default, 'optionalAccess', _74 => _74.http, 'optionalAccess', _75 => _75.length])) {
2145
- const chain = value;
2146
- const existing = map.get(chain.id);
2147
- if (existing) existing.push(chain);
2148
- else map.set(chain.id, [chain]);
2149
- }
2150
- }
2151
- viemChainsById = map;
2152
- return map;
2153
- });
2154
- }
2155
- return viemChainsPromise;
2156
- }
2157
- function pickViemChain(candidates, chain) {
2158
- if (!_optionalChain([candidates, 'optionalAccess', _76 => _76.length])) return void 0;
2159
- if (candidates.length === 1) return candidates[0];
2160
- const sameNetworkClass = candidates.filter(
2161
- (candidate) => Boolean(candidate.testnet) === chain.testnet
2162
- );
2163
- if (sameNetworkClass.length === 1) return sameNetworkClass[0];
2164
- const pool = sameNetworkClass.length > 0 ? sameNetworkClass : candidates;
2165
- const normalized = chain.name.toLowerCase().replace(/\s+/g, "");
2166
- const byName = pool.find(
2167
- (candidate) => candidate.name.toLowerCase().replace(/\s+/g, "") === normalized
2168
- );
2169
- if (byName) return byName;
2170
- return void 0;
2171
- }
2172
- function resolveRpcUrls(chain, override, viemChains) {
2173
- const urls = [];
2174
- if (_optionalChain([override, 'optionalAccess', _77 => _77.trim, 'call', _78 => _78()])) urls.push(override.trim());
2175
- if (chain.publicRpcUrl) urls.push(chain.publicRpcUrl);
2176
- if (chain.chainId !== null && chain.vmType === "evm") {
2177
- const http2 = _optionalChain([pickViemChain, 'call', _79 => _79(_optionalChain([viemChains, 'optionalAccess', _80 => _80.get, 'call', _81 => _81(chain.chainId)]), chain), 'optionalAccess', _82 => _82.rpcUrls, 'optionalAccess', _83 => _83.default, 'optionalAccess', _84 => _84.http]);
2178
- if (http2) urls.push(...http2);
2179
- }
2180
- return [...new Set(urls)];
2181
- }
2182
- function toViemChain(chain, override, viemChains) {
2183
- if (chain.vmType !== "evm" || chain.chainId === null) return null;
2184
- const rpcUrls = resolveRpcUrls(chain, override, viemChains);
2185
- if (rpcUrls.length === 0) return null;
2186
- const bundled = pickViemChain(_optionalChain([viemChains, 'optionalAccess', _85 => _85.get, 'call', _86 => _86(chain.chainId)]), chain);
2187
- if (bundled) {
2188
- if (rpcUrls[0] === bundled.rpcUrls.default.http[0]) return bundled;
2189
- return _viem.defineChain.call(void 0, {
2190
- ...bundled,
2191
- rpcUrls: { ...bundled.rpcUrls, default: { http: rpcUrls } }
2192
- });
2193
- }
2194
- return _viem.defineChain.call(void 0, {
2195
- id: chain.chainId,
2196
- name: chain.name,
2197
- nativeCurrency: {
2198
- name: chain.nativeToken.symbol,
2199
- symbol: chain.nativeToken.symbol,
2200
- decimals: chain.nativeToken.decimals
2201
- },
2202
- rpcUrls: { default: { http: rpcUrls } },
2203
- blockExplorers: chain.explorer ? {
2204
- default: {
2205
- name: "Explorer",
2206
- url: chain.explorer.url
2207
- }
2208
- } : void 0,
2209
- testnet: chain.testnet
2210
- });
2211
- }
2212
- function toViemChains(catalog, overrides, viemChains) {
2213
- const chains = [];
2214
- for (const entry of catalog.all) {
2215
- const chain = toViemChain(
2216
- entry,
2217
- entry.chainId === null ? void 0 : _optionalChain([overrides, 'optionalAccess', _87 => _87[entry.chainId]]),
2218
- viemChains
2219
- );
2220
- if (chain) chains.push(chain);
2221
- }
2222
- return chains;
2223
- }
2224
- function needsViemChains(catalog, overrides) {
2225
- return catalog.all.some(
2226
- (chain) => chain.vmType === "evm" && chain.chainId !== null && !chain.publicRpcUrl && !_optionalChain([overrides, 'optionalAccess', _88 => _88[chain.chainId], 'optionalAccess', _89 => _89.trim, 'call', _90 => _90()])
2227
- );
2228
- }
2229
-
2230
- // src/core/chain-catalog-context.tsx
2231
-
2232
- var EMPTY = {
2233
- catalog: null,
2234
- viemChains: null,
2235
- isLoading: true,
2236
- shortlist: null,
2237
- clientCapableChainIds: null
2238
- };
2239
- var ChainCatalogContext = _react.createContext.call(void 0, EMPTY);
2240
- var resolvedChainsByKey = /* @__PURE__ */ new Map();
2241
- function overridesKey(overrides) {
2242
- return Object.entries(_nullishCoalesce(overrides, () => ( {}))).map(([id, override]) => `${id}=${_nullishCoalesce(override, () => ( ""))}`).sort().join("|");
2243
- }
2244
- function runtimeChainsKey(backendUrl, overrides) {
2245
- return [backendUrl.replace(/\/$/, ""), overridesKey(overrides)].join("#");
2246
- }
2247
- var catalogByBackend = /* @__PURE__ */ new Map();
2248
- function primeChainCatalog(backendUrl, debug = false) {
2249
- const key = backendUrl.replace(/\/$/, "");
2250
- let promise = catalogByBackend.get(key);
2251
- if (!promise) {
2252
- promise = createDepositService(key, {
2253
- debug,
2254
- debugScope: "service:chains"
2255
- }).getChains();
2256
- catalogByBackend.set(key, promise);
2257
- promise.then((catalog) => {
2258
- if (!catalog) catalogByBackend.delete(key);
2259
- });
2260
- }
2261
- return promise;
2262
- }
2263
- function peekRuntimeChains(backendUrl, overrides) {
2264
- return _nullishCoalesce(resolvedChainsByKey.get(runtimeChainsKey(backendUrl, overrides)), () => ( null));
2265
- }
2266
- function publishCatalogTokens(catalog) {
2267
- _chunk4KCSH4T3cjs.setRuntimeTokens.call(void 0,
2268
- catalog.all.flatMap(
2269
- (chain) => chain.chainId === null || !Array.isArray(chain.supportedTokens) ? [] : chain.supportedTokens.map((token) => ({
2270
- chainId: chain.chainId,
2271
- symbol: token.symbol,
2272
- address: token.address,
2273
- decimals: token.decimals
2274
- }))
2275
- )
2276
- );
2277
- }
2278
- function publishRuntimeChainMeta(catalog) {
2279
- _chunk4KCSH4T3cjs.setRuntimeChainMeta.call(void 0,
2280
- catalog.all.flatMap((chain) => {
2281
- const ids = [];
2282
- if (chain.chainId !== null) ids.push(chain.chainId);
2283
- if (_chunk4KCSH4T3cjs.isHyperCoreCaip2.call(void 0, chain.caip2)) ids.push(_chunk4KCSH4T3cjs.HYPERCORE_CHAIN_ID);
2284
- return ids.map((chainId) => ({
2285
- chainId,
2286
- name: chain.name,
2287
- iconUrl: _nullishCoalesce(chain.iconUrl, () => ( void 0)),
2288
- nativeSymbol: chain.nativeToken.symbol,
2289
- explorerUrl: _optionalChain([chain, 'access', _91 => _91.explorer, 'optionalAccess', _92 => _92.url])
2290
- }));
2291
- })
2292
- );
2293
- }
2294
- var runtimeChainsByBackend = /* @__PURE__ */ new Map();
2295
- function primeRuntimeChains(backendUrl, overrides, debug = false) {
2296
- const url = backendUrl.replace(/\/$/, "");
2297
- const key = runtimeChainsKey(url, overrides);
2298
- let promise = runtimeChainsByBackend.get(key);
2299
- if (!promise) {
2300
- promise = primeChainCatalog(url, debug).then(async (catalog) => {
2301
- if (!catalog) return [];
2302
- publishRuntimeChainMeta(catalog);
2303
- publishCatalogTokens(catalog);
2304
- const viemChains = needsViemChains(catalog, overrides) ? await loadViemChains() : null;
2305
- const chains = toViemChains(catalog, overrides, viemChains);
2306
- if (chains.length > 0) {
2307
- setRuntimeChains(chains);
2308
- resolvedChainsByKey.set(key, chains);
2309
- }
2310
- return chains;
2311
- }).catch(() => []);
2312
- runtimeChainsByBackend.set(key, promise);
2313
- promise.then((chains) => {
2314
- if (chains.length === 0) runtimeChainsByBackend.delete(key);
2315
- });
2316
- }
2317
- return promise;
2318
- }
2319
- function useChainCatalog() {
2320
- return _react.useContext.call(void 0, ChainCatalogContext);
2321
- }
2322
- function useCatalogChain(chainId) {
2323
- const { catalog } = useChainCatalog();
2324
- if (!catalog || chainId == null) return void 0;
2325
- return typeof chainId === "number" ? catalog.byChainId.get(chainId) : catalog.byCaip2.get(chainId);
2326
- }
2327
- function useDepositChainIds() {
2328
- const { catalog } = useChainCatalog();
2329
- return _react.useMemo.call(void 0, () => {
2330
- if (!catalog) return [];
2331
- const ids = catalog.all.filter(
2332
- (c) => c.deposit && c.vmType === "evm" && c.chainId !== null && // `/chains` enumerates testnets; the bundled list never did, and a
2333
- // production picker offering Sepolia next to Ethereum is a way to
2334
- // lose funds. Reading the set at runtime must not quietly widen it
2335
- // to a different KIND of chain.
2336
- !c.testnet
2337
- ).map((c) => c.chainId);
2338
- const rank = (id) => {
2339
- const i = _chunk4KCSH4T3cjs.CHAIN_DISPLAY_ORDER.indexOf(id);
2340
- return i === -1 ? _chunk4KCSH4T3cjs.CHAIN_DISPLAY_ORDER.length : i;
2341
- };
2342
- return ids.map((id, i) => ({ id, i })).sort((a, b) => rank(a.id) - rank(b.id) || a.i - b.i).map(({ id }) => id);
2343
- }, [catalog]);
2344
- }
2345
- function useDestinationChains() {
2346
- const { catalog } = useChainCatalog();
2347
- return _react.useMemo.call(void 0, () => {
2348
- if (!catalog) return [];
2349
- const rank = (id) => {
2350
- const i = _chunk4KCSH4T3cjs.CHAIN_DISPLAY_ORDER.indexOf(id);
2351
- return i === -1 ? _chunk4KCSH4T3cjs.CHAIN_DISPLAY_ORDER.length : i;
2352
- };
2353
- return catalog.all.filter(
2354
- (c) => c.destination && c.vmType === "evm" && c.chainId !== null && !c.testnet
2355
- ).map((c, i) => ({ id: c.chainId, name: c.name, i })).sort((a, b) => rank(a.id) - rank(b.id) || a.i - b.i).map(({ id, name }) => ({ id, name }));
2356
- }, [catalog]);
2357
- }
2358
- function useTargetTokens() {
2359
- const { catalog, shortlist } = useChainCatalog();
2360
- return _react.useMemo.call(void 0, () => {
2361
- return (chainId) => {
2362
- const fromShortlist = _optionalChain([shortlist, 'optionalAccess', _93 => _93[String(chainId)]]);
2363
- if (fromShortlist) {
2364
- return fromShortlist.map((token) => ({
2365
- symbol: token.symbol,
2366
- address: token.address,
2367
- decimals: token.decimals
2368
- }));
2369
- }
2370
- const entry = _optionalChain([catalog, 'optionalAccess', _94 => _94.byChainId, 'access', _95 => _95.get, 'call', _96 => _96(chainId)]);
2371
- return Array.isArray(_optionalChain([entry, 'optionalAccess', _97 => _97.supportedTokens])) ? entry.supportedTokens.map((token) => ({
2372
- symbol: token.symbol,
2373
- address: token.address,
2374
- decimals: token.decimals
2375
- })) : [];
2376
- };
2377
- }, [catalog, shortlist]);
2378
- }
2379
- function useIsDepositChain() {
2380
- const ids = useDepositChainIds();
2381
- const { clientCapableChainIds } = useChainCatalog();
2382
- return _react.useMemo.call(void 0, () => {
2383
- const set = new Set(ids);
2384
- return (chainId) => set.has(chainId) && (clientCapableChainIds === null || clientCapableChainIds.has(chainId));
2385
- }, [ids, clientCapableChainIds]);
2386
- }
2387
- function useChainName() {
2388
- const { catalog } = useChainCatalog();
2389
- return _react.useMemo.call(void 0, () => {
2390
- return (chainId) => {
2391
- if (!catalog) return _chunk4KCSH4T3cjs.getChainName.call(void 0, chainId);
2392
- const key = catalogKeyForChain(chainId);
2393
- const entry = typeof key === "number" ? catalog.byChainId.get(key) : catalog.byCaip2.get(key);
2394
- return _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _98 => _98.name]), () => ( _chunk4KCSH4T3cjs.getChainName.call(void 0, chainId)));
2395
- };
2396
- }, [catalog]);
2397
- }
2398
- function useRuntimeChainsVersion() {
2399
- return _react.useSyncExternalStore.call(void 0,
2400
- subscribeToRuntimeChains,
2401
- getRuntimeChainsVersion,
2402
- getRuntimeChainsVersion
2403
- );
2404
- }
2405
- function useReadClient(chainId, rpcUrls) {
2406
- const version = useRuntimeChainsVersion();
2407
- return _react.useMemo.call(void 0,
2408
- () => getPublicClient(chainId, rpcUrls),
2409
- [chainId, rpcUrls, version]
2410
- );
2411
- }
2412
- function useExplorerTxUrl() {
2413
- const { catalog } = useChainCatalog();
2414
- return _react.useMemo.call(void 0, () => {
2415
- return (chainId, txHash) => {
2416
- if (chainId === "hypercore") return _chunk4KCSH4T3cjs.getExplorerTxUrl.call(void 0, chainId, txHash);
2417
- const key = catalog ? catalogKeyForChain(chainId) : void 0;
2418
- const entry = key === void 0 ? void 0 : typeof key === "number" ? _optionalChain([catalog, 'optionalAccess', _99 => _99.byChainId, 'access', _100 => _100.get, 'call', _101 => _101(key)]) : _optionalChain([catalog, 'optionalAccess', _102 => _102.byCaip2, 'access', _103 => _103.get, 'call', _104 => _104(key)]);
2419
- return _nullishCoalesce(catalogExplorerTxUrl(entry, txHash), () => ( _chunk4KCSH4T3cjs.getExplorerTxUrl.call(void 0, chainId, txHash)));
2420
- };
2421
- }, [catalog]);
2422
- }
2423
- function ChainCatalogProvider({
2424
- service,
2425
- rpcUrls,
2426
- children
2427
- }) {
2428
- const [catalog, setCatalog] = _react.useState.call(void 0, null);
2429
- const [viemChains, setViemChains] = _react.useState.call(void 0, null);
2430
- const [isLoading, setIsLoading] = _react.useState.call(void 0, true);
2431
- _react.useEffect.call(void 0, () => {
2432
- let active = true;
2433
- setIsLoading(true);
2434
- service.getChains().then((next) => {
2435
- if (!active) return;
2436
- setCatalog(next);
2437
- setIsLoading(false);
2438
- });
2439
- return () => {
2440
- active = false;
2441
- };
2442
- }, [service]);
2443
- const overrides = _react.useMemo.call(void 0, () => {
2444
- if (!rpcUrls) return void 0;
2445
- const out = {};
2446
- for (const [key, url] of Object.entries(rpcUrls)) {
2447
- const id = Number(key);
2448
- if (Number.isFinite(id) && typeof url === "string") out[id] = url;
2449
- }
2450
- return out;
2451
- }, [rpcUrls]);
2452
- const overrideKey = overridesKey(overrides);
2453
- _react.useEffect.call(void 0, () => {
2454
- if (!catalog || viemChains) return;
2455
- if (!needsViemChains(catalog, overrides)) return;
2456
- let active = true;
2457
- loadViemChains().then((chains) => {
2458
- if (active) setViemChains(chains);
2459
- });
2460
- return () => {
2461
- active = false;
2462
- };
2463
- }, [catalog, viemChains, overrideKey]);
2464
- _react.useEffect.call(void 0, () => {
2465
- if (!catalog) return;
2466
- publishRuntimeChainMeta(catalog);
2467
- publishCatalogTokens(catalog);
2468
- const chains = toViemChains(catalog, overrides, viemChains);
2469
- if (chains.length > 0) setRuntimeChains(chains);
2470
- }, [catalog, viemChains, overrides]);
2471
- const [shortlist, setShortlist] = _react.useState.call(void 0, null);
2472
- _react.useEffect.call(void 0, () => {
2473
- let active = true;
2474
- setShortlist(null);
2475
- service.getTopTokens().then((tokens) => {
2476
- if (!active || !tokens) return;
2477
- _chunk4KCSH4T3cjs.publishShortlistTokens.call(void 0, tokens);
2478
- setShortlist(tokens);
2479
- });
2480
- return () => {
2481
- active = false;
2482
- };
2483
- }, [service]);
2484
- const clientCapableChainIds = _react.useMemo.call(void 0, () => {
2485
- if (!catalog) return null;
2486
- return new Set(
2487
- toViemChains(catalog, overrides, viemChains).map((c) => c.id)
2488
- );
2489
- }, [catalog, viemChains, overrideKey]);
2490
- const value = _react.useMemo.call(void 0,
2491
- () => ({
2492
- catalog,
2493
- viemChains,
2494
- isLoading,
2495
- shortlist,
2496
- clientCapableChainIds
2497
- }),
2498
- [catalog, viemChains, isLoading, shortlist, clientCapableChainIds]
2499
- );
2500
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, ChainCatalogContext.Provider, { value, children });
2501
- }
2502
-
2503
- // src/core/useLatestRef.ts
2504
-
2505
- function useLatestRef(value) {
2506
- const ref = _react.useRef.call(void 0, value);
2507
- _react.useEffect.call(void 0, () => {
2508
- ref.current = value;
2509
- }, [value]);
2510
- return ref;
2511
- }
2512
-
2513
- // src/components/ui/Spinner.tsx
2514
-
2515
- function Spinner({ className }) {
2516
- return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0,
2517
- "svg",
2518
- {
2519
- className: `rs-spinner ${className || ""}`,
2520
- fill: "none",
2521
- viewBox: "0 0 20 21",
2522
- children: [
2523
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2524
- "path",
2525
- {
2526
- d: "M10 0.5C8.02 0.5 6.08 1.08 4.44 2.18C2.79 3.28 1.51 4.84 0.76 6.67C0.00 8.50 -0.19 10.51 0.19 12.45C0.57 14.39 1.53 16.17 2.92 17.57C4.32 18.96 6.10 19.92 8.04 20.30C9.98 20.69 11.99 20.49 13.82 19.73C15.65 18.98 17.21 17.70 18.31 16.05C19.41 14.41 20 12.47 20 10.5C20 7.84 18.94 5.30 17.07 3.42C15.19 1.55 12.65 0.5 10 0.5ZM10 17.77C8.56 17.77 7.15 17.34 5.95 16.54C4.76 15.74 3.83 14.61 3.28 13.28C2.73 11.95 2.58 10.49 2.86 9.08C3.14 7.67 3.84 6.37 4.85 5.35C5.87 4.34 7.17 3.64 8.58 3.36C9.99 3.08 11.45 3.23 12.78 3.78C14.11 4.33 15.24 5.26 16.04 6.45C16.84 7.65 17.27 9.06 17.27 10.5C17.27 12.42 16.50 14.27 15.14 15.64C13.77 17.00 11.92 17.77 10 17.77Z",
2527
- fill: "currentColor",
2528
- opacity: 0.3
2529
- }
2530
- ),
2531
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2532
- "path",
2533
- {
2534
- d: "M10 3.22C11.74 3.22 13.42 3.84 14.75 4.95C16.08 6.07 16.96 7.61 17.25 9.31C17.30 9.64 17.46 9.94 17.71 10.15C17.96 10.37 18.28 10.49 18.62 10.5C18.82 10.50 19.01 10.45 19.20 10.37C19.38 10.29 19.54 10.16 19.67 10.01C19.80 9.86 19.89 9.68 19.95 9.49C20.00 9.30 20.01 9.10 19.98 8.90C19.59 6.56 18.38 4.42 16.55 2.88C14.72 1.34 12.40 0.5 10 0.5C7.59 0.5 5.27 1.34 3.44 2.88C1.61 4.42 0.40 6.56 0.01 8.90C-0.01 9.10 -0.00 9.30 0.04 9.49C0.10 9.68 0.19 9.86 0.32 10.01C0.45 10.16 0.61 10.29 0.79 10.37C0.98 10.45 1.17 10.50 1.37 10.5C1.71 10.49 2.03 10.37 2.28 10.15C2.53 9.94 2.69 9.64 2.74 9.31C3.03 7.61 3.91 6.07 5.24 4.95C6.57 3.84 8.25 3.22 10 3.22Z",
2535
- fill: "currentColor"
2536
- }
2537
- )
2538
- ]
2539
- }
2540
- );
2541
- }
2542
-
2543
- // src/components/ui/Button.tsx
2544
-
2545
- function Button({
2546
- children,
2547
- variant = "accent",
2548
- size = "default",
2549
- loading = false,
2550
- loadingText,
2551
- fullWidth = false,
2552
- disabled,
2553
- className = "",
2554
- ...props
2555
- }) {
2556
- const classes = [
2557
- "rs-button",
2558
- `rs-button--${variant}`,
2559
- `rs-button--size-${size}`,
2560
- fullWidth ? "rs-button--full-width" : "",
2561
- className
2562
- ].filter(Boolean).join(" ");
2563
- const showInlineLoadingText = loading && loadingText !== void 0;
2564
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2565
- "button",
2566
- {
2567
- className: classes,
2568
- disabled: disabled || loading,
2569
- "aria-busy": loading || void 0,
2570
- ...props,
2571
- children: showInlineLoadingText ? /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "span", { className: "rs-button__loading-row", children: [
2572
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Spinner, { className: "rs-spinner--sm" }),
2573
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "span", { children: loadingText })
2574
- ] }) : /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment, { children: [
2575
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "span", { className: loading ? "rs-button__content--hidden" : "", children }),
2576
- loading && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "span", { className: "rs-button__spinner", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Spinner, { className: "rs-spinner--sm" }) })
2577
- ] })
2578
- }
2579
- );
2580
- }
2581
- Button.displayName = "Button";
2582
-
2583
- // src/components/ui/Callout.tsx
2584
-
2585
- function CircleAlertIcon() {
2586
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2587
- "svg",
2588
- {
2589
- width: "16",
2590
- height: "16",
2591
- viewBox: "0 0 16 16",
2592
- fill: "none",
2593
- xmlns: "http://www.w3.org/2000/svg",
2594
- "aria-hidden": "true",
2595
- children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2596
- "path",
2597
- {
2598
- d: "M10 5.99L6 9.99M6 5.99L10 9.99M14.66 7.99C14.66 11.68 11.68 14.66 8 14.66C4.31 14.66 1.33 11.68 1.33 7.99C1.33 4.31 4.31 1.33 8 1.33C11.68 1.33 14.66 4.31 14.66 7.99Z",
2599
- stroke: "currentColor",
2600
- strokeWidth: "1.33",
2601
- strokeLinecap: "round",
2602
- strokeLinejoin: "round"
2603
- }
2604
- )
2605
- }
2606
- );
2607
- }
2608
- function Callout({ variant = "error", children, role }) {
2609
- return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0,
2610
- "div",
2611
- {
2612
- className: `rs-callout rs-callout--${variant}`,
2613
- role: _nullishCoalesce(role, () => ( (variant === "error" ? "alert" : "status"))),
2614
- children: [
2615
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "span", { className: "rs-callout-icon", children: variant === "error" ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, CircleAlertIcon, {}) : /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AlertTriangleIcon, {}) }),
2616
- /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "span", { className: "rs-callout-text", children })
2617
- ]
2618
- }
2619
- );
2620
- }
2621
- Callout.displayName = "Callout";
2622
-
2623
- // src/components/ui/TokenIcon.tsx
2624
-
2625
- function TokenIcon({ symbol, className, fallback }) {
2626
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2627
- CdnIcon,
2628
- {
2629
- src: _chunk4KCSH4T3cjs.tokenIconUrl.call(void 0, symbol),
2630
- className: `rs-token-icon ${_nullishCoalesce(className, () => ( ""))}`.trimEnd(),
2631
- fallback
2632
- }
2633
- );
2634
- }
2635
- TokenIcon.displayName = "TokenIcon";
2636
-
2637
- // src/core/formatters.ts
2638
- var currencyFormatter = new Intl.NumberFormat("en-US", {
2639
- style: "currency",
2640
- currency: "USD",
2641
- maximumFractionDigits: 2
2642
- });
2643
- var tokenFormatter = new Intl.NumberFormat("en-US", {
2644
- minimumFractionDigits: 2,
2645
- maximumFractionDigits: 5
2646
- });
2647
- function isUnsupportedChainSwitchError(error) {
2648
- if (!error) return false;
2649
- const name = error instanceof Error ? error.name : "";
2650
- const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
2651
- return name === "SwitchChainNotSupportedError" || message.includes("does not support programmatic chain switching") || message.includes("switch chain not supported") || message.includes("method not found") || message.includes("does not exist") || message.includes("is not available");
2652
- }
2653
- var OPAQUE_REVERT_REASONS = [
2654
- "unexpected error",
2655
- "internal error",
2656
- "unknown error",
2657
- "internal json-rpc error"
2658
- ];
2659
- var DETAIL_SECTION_HEADINGS = [
2660
- "Request Arguments:",
2661
- "Raw Call Arguments:",
2662
- "Request body:",
2663
- "Contract Call:",
2664
- "Docs:",
2665
- "Details:",
2666
- "Version:",
2667
- "URL:"
2668
- ];
2669
- function formatUserError(raw) {
2670
- const lower = raw.toLowerCase();
2671
- if (lower.includes("user rejected") || lower.includes("user denied")) {
2672
- return "Transaction cancelled";
2673
- }
2674
- if (lower.includes("insufficient funds")) {
2675
- return "Insufficient funds for this transaction";
2676
- }
2677
- if (lower.includes("nonce too low") || lower.includes("nonce too high")) {
2678
- return "Transaction conflict \u2014 please try again";
2679
- }
2680
- const revertMarker = "reverted with the following reason:";
2681
- const revertIdx = lower.indexOf(revertMarker);
2682
- const revertReason = revertIdx === -1 ? null : _nullishCoalesce(raw.slice(revertIdx + revertMarker.length).split(/\n[^\S\n]*\n/)[0].split("\n").map((line) => line.trim()).find(
2683
- (line) => line.length > 0 && !DETAIL_SECTION_HEADINGS.some(
2684
- (heading) => line.startsWith(heading)
2685
- )
2686
- ), () => ( ""));
2687
- if (revertReason !== null) {
2688
- const reasonLower = revertReason.toLowerCase();
2689
- if (reasonLower.includes("execution reverted")) {
2690
- return "Transaction would fail on-chain";
2691
- }
2692
- if (revertReason === "" || revertReason === "0x" || OPAQUE_REVERT_REASONS.some((opaque) => reasonLower.includes(opaque))) {
2693
- return "Your wallet couldn't send the transaction \u2014 please try again";
2694
- }
2695
- }
2696
- if (lower.includes("execution reverted")) {
2697
- return "Transaction would fail on-chain";
2698
- }
2699
- if (lower.includes("timed out") || lower.includes("took too long")) {
2700
- return "Request timed out \u2014 please try again";
2701
- }
2702
- if (lower.includes("econnrefused") || lower.includes("econnreset") || lower.includes("enotfound") || lower.includes("fetch failed")) {
2703
- return "Service unavailable \u2014 please try again";
2704
- }
2705
- if (lower.includes("recent blockhash") || lower.includes("latest blockhash")) {
2706
- return "Solana RPC unavailable \u2014 please retry";
2707
- }
2708
- if (lower.includes("network") || lower.includes("disconnected")) {
2709
- return "Network error \u2014 check your connection";
2710
- }
2711
- if (lower.includes("rate limit") || lower.includes("429")) {
2712
- return "Rate limited \u2014 please try again shortly";
2713
- }
2714
- let cleaned = revertReason || raw;
2715
- const stripMarkers = [
2716
- "\n\nRequest Arguments:",
2717
- "\nRaw Call Arguments:",
2718
- "\nRequest body:",
2719
- "\nContract Call:",
2720
- "\nDocs:",
2721
- "\nDetails:",
2722
- "\nVersion:",
2723
- "\nURL:"
2724
- ];
2725
- for (const marker of stripMarkers) {
2726
- const idx = cleaned.indexOf(marker);
2727
- if (idx !== -1) {
2728
- cleaned = cleaned.slice(0, idx).trim();
2729
- }
2730
- }
2731
- cleaned = cleaned.replace(/https?:\/\/\S+/g, "").trim();
2732
- if (cleaned.length === 0) {
2733
- return "An unexpected error occurred";
2734
- }
2735
- if (cleaned.length > 120) {
2736
- return cleaned.slice(0, 120) + "...";
2737
- }
2738
- return cleaned;
2739
- }
2740
-
2741
- // src/core/token-amount.ts
2742
-
2743
- var STABLECOIN_SYMBOLS = /* @__PURE__ */ new Set([
2744
- "USDC",
2745
- "USDT",
2746
- "USDT0",
2747
- "DAI",
2748
- "FRAX",
2749
- "PYUSD",
2750
- "USDP",
2751
- "TUSD",
2752
- "GUSD",
2753
- "USDS",
2754
- "LUSD",
2755
- "BUSD",
2756
- "USDE"
2757
- ]);
2758
- var EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
2759
- function resolveTokenDisplay(token, chain, fallback) {
2760
- if (token !== void 0) {
2761
- if (chain === "solana") {
2762
- const solanaToken = _chunk4KCSH4T3cjs.getSolanaTokenByMint.call(void 0, token);
2763
- if (solanaToken) {
2764
- return { symbol: solanaToken.symbol, decimals: solanaToken.decimals };
2765
- }
2766
- } else if (chain === "hypercore") {
2767
- const t = _chunk4KCSH4T3cjs.HYPERCORE_SOURCE_TOKENS.find(
2768
- (x) => x.address.toLowerCase() === token.toLowerCase()
2769
- );
2770
- if (t) return { symbol: t.symbol, decimals: t.decimals };
2771
- } else if (EVM_ADDRESS_RE.test(token)) {
2772
- const symbol = _chunk4KCSH4T3cjs.getTokenSymbol.call(void 0, token, chain);
2773
- const decimals = _chunk4KCSH4T3cjs.findTokenDecimals.call(void 0, token, chain);
2774
- if (symbol !== "Token" || decimals !== void 0) {
2775
- return {
2776
- symbol: symbol !== "Token" ? symbol : _nullishCoalesce(_optionalChain([fallback, 'optionalAccess', _105 => _105.symbol]), () => ( symbol)),
2777
- decimals: _nullishCoalesce(decimals, () => ( _optionalChain([fallback, 'optionalAccess', _106 => _106.decimals])))
2778
- };
2779
- }
2780
- }
2781
- }
2782
- return {
2783
- symbol: _nullishCoalesce(_optionalChain([fallback, 'optionalAccess', _107 => _107.symbol]), () => ( "Token")),
2784
- decimals: _optionalChain([fallback, 'optionalAccess', _108 => _108.decimals])
2785
- };
2786
- }
2787
- function maxFractionDigitsFor(symbol) {
2788
- if (!symbol) return 6;
2789
- return STABLECOIN_SYMBOLS.has(symbol.toUpperCase()) ? 3 : 6;
2790
- }
2791
- function formatTokenAmount(amount, symbol) {
2792
- if (!Number.isFinite(amount)) return void 0;
2793
- return amount.toLocaleString("en-US", {
2794
- minimumFractionDigits: 2,
2795
- maximumFractionDigits: maxFractionDigitsFor(symbol)
2796
- });
2797
- }
2798
- function tokenAmountToNumber(rawAmount, decimals) {
2799
- if (decimals === void 0) return void 0;
2800
- try {
2801
- const value = Number(_viem.formatUnits.call(void 0, BigInt(rawAmount), decimals));
2802
- return Number.isFinite(value) ? value : void 0;
2803
- } catch (e4) {
2804
- return void 0;
2805
- }
2806
- }
2807
- function formatRawTokenAmount(rawAmount, token) {
2808
- const value = tokenAmountToNumber(rawAmount, token.decimals);
2809
- if (value === void 0) return void 0;
2810
- return formatTokenAmount(value, token.symbol);
2811
- }
2812
- function isDisplayStablecoinSymbol(symbol) {
2813
- return symbol !== void 0 && STABLECOIN_SYMBOLS.has(symbol.toUpperCase());
2814
- }
2815
- function priceUsdFor(symbol, prices) {
2816
- if (!symbol) return void 0;
2817
- const quoted = prices[symbol.toUpperCase()];
2818
- return typeof quoted === "number" && quoted > 0 ? quoted : void 0;
2819
- }
2820
- function isRecognizedToken(address, chain) {
2821
- if (address === void 0 || chain === void 0) return false;
2822
- if (chain === "solana") return _chunk4KCSH4T3cjs.getSolanaTokenByMint.call(void 0, address) !== void 0;
2823
- if (chain === "hypercore") {
2824
- return _chunk4KCSH4T3cjs.HYPERCORE_SOURCE_TOKENS.some(
2825
- (t) => t.address.toLowerCase() === address.toLowerCase()
2826
- );
2827
- }
2828
- return EVM_ADDRESS_RE.test(address) && _chunk4KCSH4T3cjs.isRegistryTokenOnChain.call(void 0, address, chain);
2829
- }
2830
- function estimateReceiveAmount(params) {
2831
- const {
2832
- sourceAmount,
2833
- sourceSymbol,
2834
- targetSymbol,
2835
- sourceAmountUsd,
2836
- prices,
2837
- sourceTrusted
2838
- } = params;
2839
- const trusted = sourceTrusted !== false;
2840
- if (trusted && sourceSymbol !== void 0 && sourceSymbol.toUpperCase() === targetSymbol.toUpperCase()) {
2841
- return sourceAmount;
2842
- }
2843
- if (!trusted) return void 0;
2844
- const usdValue = sourceAmountUsd !== void 0 && Number.isFinite(sourceAmountUsd) ? sourceAmountUsd : sourceAmount !== void 0 ? (() => {
2845
- const sourcePrice = priceUsdFor(sourceSymbol, prices);
2846
- return sourcePrice !== void 0 ? sourceAmount * sourcePrice : void 0;
2847
- })() : void 0;
2848
- if (usdValue === void 0) return void 0;
2849
- const targetPrice = priceUsdFor(targetSymbol, prices);
2850
- if (targetPrice === void 0) return void 0;
2851
- return usdValue / targetPrice;
2852
- }
2853
- function formatQuotedReceive(output, fallbackSymbol) {
2854
- if (output.decimals === null) return void 0;
2855
- let raw;
2856
- try {
2857
- raw = BigInt(output.amount);
2858
- } catch (e5) {
2859
- return void 0;
2860
- }
2861
- if (raw <= 0n) return void 0;
2862
- const symbol = _nullishCoalesce(output.symbol, () => ( fallbackSymbol));
2863
- const formatted = formatRawTokenAmount(raw, {
2864
- symbol,
2865
- decimals: output.decimals
2866
- });
2867
- if (formatted === void 0) return void 0;
2868
- return `~${formatted} ${symbol}`;
2869
- }
2870
- function formatReceiveEstimate(params) {
2871
- const estimate = estimateReceiveAmount(params);
2872
- if (estimate === void 0) return void 0;
2873
- const formatted = formatTokenAmount(estimate, params.targetSymbol);
2874
- if (formatted === void 0) return void 0;
2875
- const sameSymbol = params.sourceSymbol.toUpperCase() === params.targetSymbol.toUpperCase();
2876
- return sameSymbol ? `${formatted} ${params.targetSymbol}` : `~${formatted} ${params.targetSymbol}`;
2877
- }
2878
-
2879
- // src/core/analytics.tsx
2880
-
2881
-
2882
-
2883
-
2884
-
2885
-
2886
-
2887
-
2888
-
2889
- // src/core/analytics-ingest.ts
2890
- var DEFAULT_ANALYTICS_INGEST_URL = "https://v1.orchestrator.rhinestone.dev/deposit-processor/analytics/events";
2891
- var MAX_BATCH = 20;
2892
- var MAX_QUEUE = 200;
2893
- var FLUSH_DELAY_MS = 5e3;
2894
- var MAX_BODY_BYTES = 48 * 1024;
2895
- var TOKEN_REFRESH_MARGIN_MS = 6e4;
2896
- var TOKEN_TIMEOUT_MS = 3e3;
2897
- var CLOSE_MINT_WAIT_MS = 1500;
2898
- var MAX_ATTEMPTS = 3;
2899
- var MAX_BACKOFF_MS = 3e4;
2900
- var IDLE = 0;
2901
- var CLOSING = 1;
2902
- var DISMISSAL = 2;
2903
- var ENVELOPE_FIELDS = /* @__PURE__ */ new Set([
2904
- "type",
2905
- "timestamp",
2906
- "session_id",
2907
- "modal",
2908
- "widget_version",
2909
- "session_properties",
2910
- "funding_method"
2911
- ]);
2912
- function createIngestTransport(options) {
2913
- const {
2914
- ingestUrl,
2915
- backendUrl,
2916
- proxyOrigin,
2917
- sessionId,
2918
- modal,
2919
- widgetVersion,
2920
- sessionProperties,
2921
- onFailure
2922
- } = options;
2923
- const fetchImpl = _nullishCoalesce(options.fetchImpl, () => ( (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : void 0)));
2924
- const now = _nullishCoalesce(options.now, () => ( (() => Date.now())));
2925
- const createEventId = _nullishCoalesce(options.createEventId, () => ( randomUuid));
2926
- const mintUrl = `${backendUrl.replace(/\/$/, "")}/analytics/ingest-token`;
2927
- const queue = [];
2928
- let sequence = 0;
2929
- let dropped = 0;
2930
- let token = null;
2931
- let mintUnavailable = false;
2932
- let mintFailures = 0;
2933
- let mintBackoffUntil = 0;
2934
- let timer = null;
2935
- let sending = false;
2936
- let disposed = false;
2937
- let pendingRun = false;
2938
- let urgency = IDLE;
2939
- let minting = null;
2940
- let mintAbort = null;
2941
- const sleepers = /* @__PURE__ */ new Set();
2942
- function report(reason, status) {
2943
- try {
2944
- onFailure({ reason, status, droppedEvents: dropped });
2945
- } catch (e6) {
2946
- }
2947
- }
2948
- function drop(batch, reason, status) {
2949
- dropped += batch.length;
2950
- report(reason, status);
2951
- }
2952
- function toWireEvent(event) {
2953
- const payload = {};
2954
- for (const [key, value] of Object.entries(event)) {
2955
- if (!ENVELOPE_FIELDS.has(key)) payload[key] = value;
2956
- }
2957
- const wire = {
2958
- event_id: createEventId(),
2959
- session_id: sessionId,
2960
- sequence: sequence++,
2961
- type: String(event.type),
2962
- timestamp: String(event.timestamp),
2963
- widget_version: widgetVersion,
2964
- proxy_origin: proxyOrigin,
2965
- modal,
2966
- session_properties: sessionProperties,
2967
- payload
2968
- };
2969
- if (modal === "deposit") wire.funding_method = _nullishCoalesce(event.funding_method, () => ( null));
2970
- return wire;
2971
- }
2972
- function takeBatch() {
2973
- const batch = queue.slice(0, MAX_BATCH);
2974
- while (batch.length > 1 && bodyOf(batch).length > MAX_BODY_BYTES) {
2975
- batch.pop();
2976
- }
2977
- queue.splice(0, batch.length);
2978
- return batch;
2979
- }
2980
- function bodyOf(batch) {
2981
- return JSON.stringify({ events: batch });
2982
- }
2983
- function backoff(attempt) {
2984
- return Math.min(1e3 * 2 ** (attempt - 1), MAX_BACKOFF_MS);
2985
- }
2986
- function sleep(ms) {
2987
- return new Promise((resolve) => {
2988
- const timeout = setTimeout(finish, ms);
2989
- function finish() {
2990
- clearTimeout(timeout);
2991
- sleepers.delete(finish);
2992
- resolve();
2993
- }
2994
- sleepers.add(finish);
2995
- });
2996
- }
2997
- function interruptForUnload() {
2998
- for (const wake of [...sleepers]) wake();
2999
- _optionalChain([mintAbort, 'optionalAccess', _109 => _109.abort, 'call', _110 => _110()]);
3000
- }
3001
- function retryDelay(response, attempt) {
3002
- const seconds = Number(_optionalChain([response, 'access', _111 => _111.headers, 'optionalAccess', _112 => _112.get, 'optionalCall', _113 => _113("Retry-After")]));
3003
- if (Number.isFinite(seconds) && seconds > 0) {
3004
- return Math.min(seconds * 1e3, MAX_BACKOFF_MS);
3005
- }
3006
- return backoff(attempt);
3007
- }
3008
- async function mintToken() {
3009
- if (mintUnavailable || !fetchImpl) return;
3010
- const controller = typeof AbortController === "function" ? new AbortController() : null;
3011
- mintAbort = controller;
3012
- const timeout = controller ? setTimeout(() => controller.abort(), TOKEN_TIMEOUT_MS) : null;
3013
- let response;
3014
- try {
3015
- response = await fetchImpl(mintUrl, {
3016
- method: "POST",
3017
- headers: _chunkAQVJUXSGcjs.serviceHeaders.call(void 0, ),
3018
- signal: _optionalChain([controller, 'optionalAccess', _114 => _114.signal])
3019
- });
3020
- } catch (e7) {
3021
- if (urgency !== DISMISSAL) {
3022
- mintFailures += 1;
3023
- mintBackoffUntil = now() + backoff(mintFailures);
3024
- }
3025
- return;
3026
- } finally {
3027
- if (timeout !== null) clearTimeout(timeout);
3028
- mintAbort = null;
3029
- }
3030
- if (response.status === 404 || response.status === 401 || response.status === 403) {
3031
- mintUnavailable = true;
3032
- report("token_unavailable", response.status);
3033
- return;
3034
- }
3035
- if (!response.ok) {
3036
- mintFailures += 1;
3037
- mintBackoffUntil = now() + backoff(mintFailures);
3038
- return;
3039
- }
3040
- try {
3041
- const data = await response.json();
3042
- const value = typeof data.token === "string" ? data.token : "";
3043
- const expiresAt = Date.parse(String(data.expiresAt));
3044
- if (!value || Number.isNaN(expiresAt)) throw new Error("malformed");
3045
- token = { value, expiresAt };
3046
- mintFailures = 0;
3047
- mintBackoffUntil = 0;
3048
- } catch (e8) {
3049
- mintUnavailable = true;
3050
- report("token_unavailable", response.status);
3051
- }
3052
- }
3053
- function startMint() {
3054
- if (!minting) {
3055
- minting = mintToken().finally(() => {
3056
- minting = null;
3057
- });
3058
- }
3059
- return minting;
3060
- }
3061
- async function ensureToken(maxWaitMs) {
3062
- if (mintUnavailable) return;
3063
- if (token && token.expiresAt - now() > TOKEN_REFRESH_MARGIN_MS) return;
3064
- if (now() < mintBackoffUntil) return;
3065
- const pending = startMint();
3066
- await (maxWaitMs === void 0 ? pending : Promise.race([pending, sleep(maxWaitMs)]));
3067
- }
3068
- async function deliver(batch) {
3069
- if (!fetchImpl) return drop(batch, "unsupported");
3070
- let attempt = 0;
3071
- let refreshed = false;
3072
- let unattributed = false;
3073
- for (; ; ) {
3074
- const terminal = urgency === DISMISSAL;
3075
- attempt += 1;
3076
- const headers = {
3077
- "Content-Type": "application/json"
3078
- };
3079
- if (token && !unattributed) headers.Authorization = `Bearer ${token.value}`;
3080
- let response;
3081
- try {
3082
- response = await fetchImpl(ingestUrl, {
3083
- method: "POST",
3084
- headers,
3085
- body: bodyOf(batch),
3086
- keepalive: true
3087
- });
3088
- } catch (e9) {
3089
- if (terminal || attempt >= MAX_ATTEMPTS) {
3090
- return drop(batch, "network");
3091
- }
3092
- await sleep(backoff(attempt));
3093
- continue;
3094
- }
3095
- if (response.ok) return;
3096
- const status = response.status;
3097
- if (status === 401) {
3098
- token = null;
3099
- if (!refreshed && !terminal) {
3100
- refreshed = true;
3101
- await startMint();
3102
- if (token) continue;
3103
- }
3104
- if (!unattributed) {
3105
- unattributed = true;
3106
- continue;
3107
- }
3108
- return drop(batch, "unauthorized", status);
3109
- }
3110
- if (status === 409) return drop(batch, "conflict", status);
3111
- if (status === 429 || status >= 500) {
3112
- if (terminal || attempt >= MAX_ATTEMPTS) {
3113
- return drop(batch, status === 429 ? "throttled" : "unavailable", status);
3114
- }
3115
- await sleep(retryDelay(response, attempt));
3116
- continue;
3117
- }
3118
- return drop(batch, "rejected", status);
3119
- }
3120
- }
3121
- function escalate(level) {
3122
- if (level <= urgency) return;
3123
- urgency = level;
3124
- if (level === DISMISSAL) interruptForUnload();
3125
- }
3126
- function onDismissal(event) {
3127
- if (event.type === "pagehide" || document.visibilityState === "hidden") {
3128
- escalate(DISMISSAL);
3129
- }
3130
- }
3131
- function dismissalGuard(attach) {
3132
- if (typeof window === "undefined" || typeof document === "undefined") return;
3133
- const bind = attach ? "addEventListener" : "removeEventListener";
3134
- window[bind]("pagehide", onDismissal);
3135
- document[bind]("visibilitychange", onDismissal);
3136
- }
3137
- async function run(level) {
3138
- escalate(level);
3139
- if (sending) {
3140
- pendingRun = true;
3141
- return;
3142
- }
3143
- sending = true;
3144
- try {
3145
- while (queue.length > 0) {
3146
- const batch = takeBatch();
3147
- if (urgency !== DISMISSAL) {
3148
- await ensureToken(urgency === CLOSING ? CLOSE_MINT_WAIT_MS : void 0);
3149
- }
3150
- await deliver(batch);
3151
- }
3152
- } finally {
3153
- sending = false;
3154
- }
3155
- if (pendingRun) {
3156
- pendingRun = false;
3157
- await run(urgency);
3158
- return;
3159
- }
3160
- if (!disposed) urgency = IDLE;
3161
- else dismissalGuard(false);
3162
- }
3163
- function clearFlushTimer() {
3164
- if (timer !== null) {
3165
- clearTimeout(timer);
3166
- timer = null;
3167
- }
3168
- }
3169
- function scheduleFlush() {
3170
- if (timer !== null || disposed) return;
3171
- timer = setTimeout(() => {
3172
- timer = null;
3173
- void run(IDLE);
3174
- }, FLUSH_DELAY_MS);
3175
- }
3176
- return {
3177
- enqueue(event) {
3178
- if (disposed) return;
3179
- queue.push(toWireEvent(event));
3180
- if (sequence === 1) void ensureToken();
3181
- if (queue.length > MAX_QUEUE) {
3182
- dropped += queue.length - MAX_QUEUE;
3183
- queue.splice(0, queue.length - MAX_QUEUE);
3184
- }
3185
- if (queue.length >= MAX_BATCH) {
3186
- clearFlushTimer();
3187
- void run(IDLE);
3188
- } else {
3189
- scheduleFlush();
3190
- }
3191
- },
3192
- flush(flushOptions) {
3193
- const dismissal = _nullishCoalesce(_optionalChain([flushOptions, 'optionalAccess', _115 => _115.terminal]), () => ( false));
3194
- if (disposed && !dismissal) return;
3195
- clearFlushTimer();
3196
- void run(dismissal ? DISMISSAL : IDLE);
3197
- },
3198
- dispose() {
3199
- if (disposed) return;
3200
- disposed = true;
3201
- clearFlushTimer();
3202
- dismissalGuard(true);
3203
- void run(CLOSING);
3204
- }
3205
- };
3206
- }
3207
- function randomUuid() {
3208
- if (typeof _optionalChain([globalThis, 'access', _116 => _116.crypto, 'optionalAccess', _117 => _117.randomUUID]) === "function") {
3209
- return globalThis.crypto.randomUUID();
3210
- }
3211
- const bytes = new Uint8Array(16);
3212
- _optionalChain([globalThis, 'access', _118 => _118.crypto, 'optionalAccess', _119 => _119.getRandomValues, 'optionalCall', _120 => _120(bytes)]);
3213
- if (!bytes.some(Boolean)) {
3214
- for (let index = 0; index < bytes.length; index += 1) {
3215
- bytes[index] = Math.floor(Math.random() * 256);
3216
- }
3217
- }
3218
- bytes[6] = bytes[6] & 15 | 64;
3219
- bytes[8] = bytes[8] & 63 | 128;
3220
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
3221
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
3222
- }
3223
- function resolveProxyOrigin(backendUrl) {
3224
- if (!backendUrl.trim()) return null;
3225
- try {
3226
- const { origin } = new URL(backendUrl, _optionalChain([globalThis, 'access', _121 => _121.location, 'optionalAccess', _122 => _122.href]));
3227
- return origin.startsWith("http") ? origin : null;
3228
- } catch (e10) {
3229
- return null;
3230
- }
3231
- }
3232
-
3233
- // src/core/analytics.tsx
3234
-
3235
- var AnalyticsContext = _react.createContext.call(void 0, null);
3236
- var noopDepositEmitter = () => {
3237
- };
3238
- var noopWithdrawEmitter = () => {
3239
- };
3240
- var noopClaimEmitter = () => {
3241
- };
3242
- function cloneAndFreeze(value) {
3243
- if (Array.isArray(value)) {
3244
- return Object.freeze(value.map(cloneAndFreeze));
3245
- }
3246
- if (value && typeof value === "object") {
3247
- const clone = Object.fromEntries(
3248
- Object.entries(value).map(([key, child]) => [key, cloneAndFreeze(child)])
3249
- );
3250
- return Object.freeze(clone);
3251
- }
3252
- return value;
3253
- }
3254
- function AnalyticsSession(props) {
3255
- const sessionIdRef = _react.useRef.call(void 0, void 0);
3256
- if (sessionIdRef.current === void 0) {
3257
- sessionIdRef.current = (_nullishCoalesce(props.createSessionId, () => ( randomUuid)))();
3258
- }
3259
- const sessionPropertiesRef = _react.useRef.call(void 0, void 0);
3260
- if (sessionPropertiesRef.current === void 0) {
3261
- sessionPropertiesRef.current = cloneAndFreeze(props.sessionProperties);
3262
- }
3263
- const onEventRef = _react.useRef.call(void 0, props.onEvent);
3264
- onEventRef.current = props.onEvent;
3265
- const nowRef = _react.useRef.call(void 0, _nullishCoalesce(props.now, () => ( (() => /* @__PURE__ */ new Date()))));
3266
- nowRef.current = _nullishCoalesce(props.now, () => ( (() => /* @__PURE__ */ new Date())));
3267
- const modal = props.modal;
3268
- const reportedFailuresRef = _react.useRef.call(void 0, /* @__PURE__ */ new Set());
3269
- const emitFailure = _react.useCallback.call(void 0,
3270
- ({ reason, status, droppedEvents }) => {
3271
- if (reportedFailuresRef.current.has(reason)) return;
3272
- reportedFailuresRef.current.add(reason);
3273
- const event = {
3274
- type: "analytics_ingest_failure",
3275
- session_id: sessionIdRef.current,
3276
- modal,
3277
- widget_version: _chunkAQVJUXSGcjs.MODAL_VERSION,
3278
- timestamp: nowRef.current().toISOString(),
3279
- reason,
3280
- ...status === void 0 ? {} : { status },
3281
- dropped_events: droppedEvents
3282
- };
3283
- _optionalChain([onEventRef, 'access', _123 => _123.current, 'optionalCall', _124 => _124(event)]);
3284
- },
3285
- [modal]
3286
- );
3287
- function createIngest() {
3288
- if (props.enableIngest === false) {
3289
- return { transport: null, initialFailure: null };
3290
- }
3291
- const proxyOrigin = resolveProxyOrigin(_nullishCoalesce(props.backendUrl, () => ( "")));
3292
- if (!proxyOrigin || typeof globalThis.fetch !== "function") {
3293
- return {
3294
- transport: null,
3295
- initialFailure: { reason: "unsupported", droppedEvents: 0 }
3296
- };
3297
- }
3298
- return {
3299
- transport: createIngestTransport({
3300
- ingestUrl: _nullishCoalesce(props.ingestUrl, () => ( DEFAULT_ANALYTICS_INGEST_URL)),
3301
- backendUrl: props.backendUrl,
3302
- proxyOrigin,
3303
- sessionId: sessionIdRef.current,
3304
- modal,
3305
- widgetVersion: _chunkAQVJUXSGcjs.MODAL_VERSION,
3306
- sessionProperties: sessionPropertiesRef.current,
3307
- onFailure: (failure) => emitFailure(failure),
3308
- fetchImpl: props.fetchImpl,
3309
- createEventId: props.createEventId
3310
- }),
3311
- initialFailure: null
3312
- };
3313
- }
3314
- const ingestRef = _react.useRef.call(void 0, void 0);
3315
- if (ingestRef.current === void 0) {
3316
- ingestRef.current = createIngest();
3317
- }
3318
- const pendingDisposalRef = _react.useRef.call(void 0, null);
3319
- const enqueue = _react.useCallback.call(void 0,
3320
- (event) => {
3321
- try {
3322
- _optionalChain([ingestRef, 'access', _125 => _125.current, 'optionalAccess', _126 => _126.transport, 'optionalAccess', _127 => _127.enqueue, 'call', _128 => _128(
3323
- event
3324
- )]);
3325
- } catch (e11) {
3326
- }
3327
- },
3328
- []
3329
- );
3330
- _react.useEffect.call(void 0, () => {
3331
- if (pendingDisposalRef.current !== null) {
3332
- clearTimeout(pendingDisposalRef.current);
3333
- pendingDisposalRef.current = null;
3334
- }
3335
- const setup = ingestRef.current;
3336
- if (setup.initialFailure) emitFailure(setup.initialFailure);
3337
- const transport = setup.transport;
3338
- if (!transport) return;
3339
- const flush = () => transport.flush({ terminal: true });
3340
- const onVisibilityChange = () => {
3341
- if (document.visibilityState === "hidden") flush();
3342
- };
3343
- window.addEventListener("pagehide", flush);
3344
- document.addEventListener("visibilitychange", onVisibilityChange);
3345
- return () => {
3346
- window.removeEventListener("pagehide", flush);
3347
- document.removeEventListener("visibilitychange", onVisibilityChange);
3348
- pendingDisposalRef.current = setTimeout(() => {
3349
- pendingDisposalRef.current = null;
3350
- transport.dispose();
3351
- }, 0);
3352
- };
3353
- }, [emitFailure]);
3354
- const emitDeposit = _react.useCallback.call(void 0,
3355
- (...[payload, fundingMethod]) => {
3356
- if (modal !== "deposit") return;
3357
- const event = {
3358
- ...payload,
3359
- session_id: sessionIdRef.current,
3360
- modal,
3361
- widget_version: _chunkAQVJUXSGcjs.MODAL_VERSION,
3362
- timestamp: nowRef.current().toISOString(),
3363
- session_properties: sessionPropertiesRef.current,
3364
- funding_method: fundingMethod
3365
- };
3366
- _optionalChain([onEventRef, 'access', _129 => _129.current, 'optionalCall', _130 => _130(
3367
- event
3368
- )]);
3369
- enqueue(event);
3370
- },
3371
- [enqueue, modal, nowRef, onEventRef]
3372
- );
3373
- const emitWithdraw = _react.useCallback.call(void 0,
3374
- (payload) => {
3375
- if (modal !== "withdraw") return;
3376
- const event = {
3377
- ...payload,
3378
- session_id: sessionIdRef.current,
3379
- modal,
3380
- widget_version: _chunkAQVJUXSGcjs.MODAL_VERSION,
3381
- timestamp: nowRef.current().toISOString(),
3382
- session_properties: sessionPropertiesRef.current
3383
- };
3384
- _optionalChain([onEventRef, 'access', _131 => _131.current, 'optionalCall', _132 => _132(event)]);
3385
- enqueue(event);
3386
- },
3387
- [enqueue, modal, nowRef, onEventRef]
3388
- );
3389
- const emitClaim = _react.useCallback.call(void 0,
3390
- (payload) => {
3391
- if (modal !== "claim") return;
3392
- const event = {
3393
- ...payload,
3394
- session_id: sessionIdRef.current,
3395
- modal,
3396
- widget_version: _chunkAQVJUXSGcjs.MODAL_VERSION,
3397
- timestamp: nowRef.current().toISOString(),
3398
- session_properties: sessionPropertiesRef.current
3399
- };
3400
- _optionalChain([onEventRef, 'access', _133 => _133.current, 'optionalCall', _134 => _134(event)]);
3401
- enqueue(event);
3402
- },
3403
- [enqueue, modal, nowRef, onEventRef]
3404
- );
3405
- const context = _react.useMemo.call(void 0,
3406
- () => modal === "deposit" ? { modal, emit: emitDeposit } : modal === "withdraw" ? { modal, emit: emitWithdraw } : { modal, emit: emitClaim },
3407
- [modal, emitDeposit, emitWithdraw, emitClaim]
3408
- );
3409
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AnalyticsContext.Provider, { value: context, children: props.children });
3410
- }
3411
- function useDepositAnalyticsEmitter() {
3412
- const context = _react.useContext.call(void 0, AnalyticsContext);
3413
- if (!context || context.modal !== "deposit") return noopDepositEmitter;
3414
- return context.emit;
3415
- }
3416
- function useWithdrawAnalyticsEmitter() {
3417
- const context = _react.useContext.call(void 0, AnalyticsContext);
3418
- if (!context || context.modal !== "withdraw") return noopWithdrawEmitter;
3419
- return context.emit;
3420
- }
3421
- function useClaimAnalyticsEmitter() {
3422
- const context = _react.useContext.call(void 0, AnalyticsContext);
3423
- if (!context || context.modal !== "claim") return noopClaimEmitter;
3424
- return context.emit;
3425
- }
3426
-
3427
- // src/core/theme.ts
3428
- var RADIUS_SCALE = {
3429
- none: { sm: "0", md: "0", lg: "0" },
3430
- sm: { sm: "4px", md: "6px", lg: "8px" },
3431
- md: { sm: "8px", md: "10px", lg: "14px" },
3432
- lg: { sm: "10px", md: "14px", lg: "18px" },
3433
- full: { sm: "9999px", md: "9999px", lg: "9999px" }
3434
- };
3435
- function setVar(targets, prop, value) {
3436
- for (const el of targets) {
3437
- el.style.setProperty(prop, value);
3438
- }
3439
- }
3440
- function clearVar(targets, prop) {
3441
- for (const el of targets) {
3442
- el.style.removeProperty(prop);
3443
- }
3444
- }
3445
- function normalizeHex(input) {
3446
- const v = input.trim().replace(/^#/, "");
3447
- if (/^[0-9a-fA-F]{3}$/.test(v)) {
3448
- return v.split("").map((c) => c + c).join("").toLowerCase();
3449
- }
3450
- if (/^[0-9a-fA-F]{6}$/.test(v)) return v.toLowerCase();
3451
- return null;
3452
- }
3453
- function hexToHsl(hex) {
3454
- const normalized = normalizeHex(hex);
3455
- if (!normalized) return null;
3456
- const r = parseInt(normalized.slice(0, 2), 16) / 255;
3457
- const g = parseInt(normalized.slice(2, 4), 16) / 255;
3458
- const b = parseInt(normalized.slice(4, 6), 16) / 255;
3459
- const max = Math.max(r, g, b);
3460
- const min = Math.min(r, g, b);
3461
- const l = (max + min) / 2;
3462
- let h = 0;
3463
- let s = 0;
3464
- if (max !== min) {
3465
- const d = max - min;
3466
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
3467
- switch (max) {
3468
- case r:
3469
- h = (g - b) / d + (g < b ? 6 : 0);
3470
- break;
3471
- case g:
3472
- h = (b - r) / d + 2;
3473
- break;
3474
- case b:
3475
- h = (r - g) / d + 4;
3476
- break;
3477
- }
3478
- h *= 60;
3479
- }
3480
- return { h, s: s * 100, l: l * 100 };
3481
- }
3482
- var clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
3483
- var hsl = ({ h, s, l }) => `hsl(${h.toFixed(1)} ${clamp(s, 0, 100).toFixed(1)}% ${clamp(l, 0, 100).toFixed(1)}%)`;
3484
- function deriveCustomPrimary(baseHex) {
3485
- const base = hexToHsl(baseHex);
3486
- if (!base) return null;
3487
- const { h, s, l } = base;
3488
- const direction = l < 25 ? 1 : -1;
3489
- const hoverL = clamp(l + 8 * direction, 4, 96);
3490
- const activeL = clamp(l + 14 * direction, 2, 98);
3491
- const disabledBg = {
3492
- h,
3493
- s: clamp(s * 0.25, 0, 20),
3494
- l: clamp(l > 75 ? l - 15 : 88, 12, 92)
3495
- };
3496
- const disabledFg = {
3497
- h,
3498
- s: clamp(s * 0.35, 0, 25),
3499
- l: clamp(l > 75 ? 35 : 45, 30, 60)
3500
- };
3501
- const norm = normalizeHex(baseHex);
3502
- const ch = (i) => {
3503
- const v = parseInt(norm.slice(i, i + 2), 16) / 255;
3504
- return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
3505
- };
3506
- const y = 0.2126 * ch(0) + 0.7152 * ch(2) + 0.0722 * ch(4);
3507
- const foreground = y > 0.45 ? "#18181b" : "#fafafa";
3508
- return {
3509
- base: hsl({ h, s, l }),
3510
- hover: hsl({ h, s, l: hoverL }),
3511
- active: hsl({ h, s, l: activeL }),
3512
- disabledBg: hsl(disabledBg),
3513
- disabledFg: hsl(disabledFg),
3514
- foreground
3515
- };
3516
- }
3517
- var CUSTOM_PRIMARY_VARS = [
3518
- "--rs-primary",
3519
- "--rs-primary-hover",
3520
- "--rs-primary-active",
3521
- "--rs-primary-disabled-bg",
3522
- "--rs-primary-disabled-fg",
3523
- "--rs-primary-foreground",
3524
- "--rs-border-accent"
3525
- ];
3526
- var DARK_SCHEME_QUERY = "(prefers-color-scheme: dark)";
3527
- var NOTHING_TO_STOP = () => {
3528
- };
3529
- function resolveThemeMode(mode) {
3530
- if (mode !== "system") return mode;
3531
- return _optionalChain([globalThis, 'access', _135 => _135.matchMedia, 'optionalCall', _136 => _136(DARK_SCHEME_QUERY), 'access', _137 => _137.matches]) ? "dark" : "light";
3532
- }
3533
- function followSystemAppearance(mode, onChange) {
3534
- if (mode !== "system") return NOTHING_TO_STOP;
3535
- const query = _optionalChain([globalThis, 'access', _138 => _138.matchMedia, 'optionalCall', _139 => _139(DARK_SCHEME_QUERY)]);
3536
- if (!query) return NOTHING_TO_STOP;
3537
- query.addEventListener("change", onChange);
3538
- return () => query.removeEventListener("change", onChange);
3539
- }
3540
- function applyTheme(element, theme) {
3541
- if (!element) return NOTHING_TO_STOP;
3542
- const parent = element.parentElement;
3543
- const targets = _optionalChain([parent, 'optionalAccess', _140 => _140.classList, 'access', _141 => _141.contains, 'call', _142 => _142("rs-modal-content")]) ? [element, parent] : [element];
3544
- const paintMode = () => {
3545
- const resolved = resolveThemeMode(_optionalChain([theme, 'optionalAccess', _143 => _143.mode]));
3546
- for (const t of targets) {
3547
- if (resolved) t.setAttribute("data-theme", resolved);
3548
- else t.removeAttribute("data-theme");
3549
- }
3550
- };
3551
- paintMode();
3552
- if (_optionalChain([theme, 'optionalAccess', _144 => _144.fontColor])) {
3553
- setVar(targets, "--rs-foreground", theme.fontColor);
3554
- }
3555
- if (_optionalChain([theme, 'optionalAccess', _145 => _145.iconColor])) {
3556
- setVar(targets, "--rs-icon", theme.iconColor);
3557
- }
3558
- if (_optionalChain([theme, 'optionalAccess', _146 => _146.ctaColor])) {
3559
- const derived = deriveCustomPrimary(theme.ctaColor);
3560
- if (derived) {
3561
- setVar(targets, "--rs-primary", derived.base);
3562
- setVar(
3563
- targets,
3564
- "--rs-primary-hover",
3565
- _nullishCoalesce(theme.ctaHoverColor, () => ( derived.hover))
3566
- );
3567
- setVar(targets, "--rs-primary-active", derived.active);
3568
- setVar(targets, "--rs-primary-disabled-bg", derived.disabledBg);
3569
- setVar(targets, "--rs-primary-disabled-fg", derived.disabledFg);
3570
- setVar(targets, "--rs-primary-foreground", derived.foreground);
3571
- setVar(targets, "--rs-border-accent", derived.base);
3572
- } else {
3573
- setVar(targets, "--rs-primary", theme.ctaColor);
3574
- setVar(targets, "--rs-border-accent", theme.ctaColor);
3575
- setVar(
3576
- targets,
3577
- "--rs-primary-hover",
3578
- _nullishCoalesce(theme.ctaHoverColor, () => ( theme.ctaColor))
3579
- );
3580
- }
3581
- } else {
3582
- for (const v of CUSTOM_PRIMARY_VARS) clearVar(targets, v);
3583
- if (_optionalChain([theme, 'optionalAccess', _147 => _147.ctaHoverColor])) {
3584
- setVar(targets, "--rs-primary-hover", theme.ctaHoverColor);
3585
- }
3586
- }
3587
- if (_optionalChain([theme, 'optionalAccess', _148 => _148.borderColor])) {
3588
- setVar(targets, "--rs-border", theme.borderColor);
3589
- setVar(targets, "--rs-border-surface", theme.borderColor);
3590
- }
3591
- if (_optionalChain([theme, 'optionalAccess', _149 => _149.backgroundColor])) {
3592
- setVar(targets, "--rs-background", theme.backgroundColor);
3593
- }
3594
- if (_optionalChain([theme, 'optionalAccess', _150 => _150.radius])) {
3595
- const scale = RADIUS_SCALE[theme.radius];
3596
- setVar(targets, "--rs-radius-sm", scale.sm);
3597
- setVar(targets, "--rs-radius-md", scale.md);
3598
- setVar(targets, "--rs-radius-lg", scale.lg);
3599
- setVar(targets, "--rs-radius", scale.md);
3600
- }
3601
- return followSystemAppearance(_optionalChain([theme, 'optionalAccess', _151 => _151.mode]), paintMode);
3602
- }
3603
-
3604
- // src/core/backend-url.ts
3605
- var warned = /* @__PURE__ */ new Set();
3606
- function checkBackendUrl(component, backendUrl) {
3607
- if (typeof backendUrl === "string" && backendUrl.trim() !== "") return;
3608
- if (warned.has(component)) return;
3609
- warned.add(component);
3610
- console.error(
3611
- `[rhinestone] <${component}> requires \`backendUrl\`. Point it at a proxy that holds your Rhinestone API key and forwards to the deposit processor \u2014 every request the modal makes goes there, so nothing will work without it.`
3612
- );
3613
- }
3614
-
3615
-
3616
-
3617
-
3618
-
3619
-
3620
-
3621
-
3622
-
3623
-
3624
-
3625
-
3626
-
3627
-
3628
-
3629
-
3630
-
3631
-
3632
-
3633
-
3634
-
3635
-
3636
-
3637
-
3638
-
3639
-
3640
-
3641
-
3642
-
3643
-
3644
-
3645
-
3646
-
3647
-
3648
-
3649
-
3650
-
3651
-
3652
-
3653
-
3654
-
3655
-
3656
-
3657
-
3658
-
3659
-
3660
-
3661
-
3662
-
3663
-
3664
-
3665
-
3666
-
3667
-
3668
-
3669
-
3670
-
3671
-
3672
-
3673
-
3674
-
3675
-
3676
-
3677
-
3678
-
3679
-
3680
-
3681
-
3682
-
3683
-
3684
-
3685
-
3686
-
3687
-
3688
-
3689
-
3690
-
3691
-
3692
-
3693
-
3694
-
3695
-
3696
-
3697
-
3698
-
3699
- exports.Modal = Modal; exports.WalletIcon = WalletIcon; exports.ExternalLinkIcon = ExternalLinkIcon; exports.CheckIcon = CheckIcon; exports.TransferCryptoIcon = TransferCryptoIcon; exports.ChevronRightIcon = ChevronRightIcon; exports.ChevronLeftIcon = ChevronLeftIcon; exports.ChevronDownIcon = ChevronDownIcon; exports.CloseIcon = CloseIcon; exports.HandCoinsIcon = HandCoinsIcon; exports.CoinsIcon = CoinsIcon; exports.HistoryIcon = HistoryIcon; exports.InfoIcon = InfoIcon; exports.CopyIcon = CopyIcon; exports.ArrowUpRightIcon = ArrowUpRightIcon; exports.AlertTriangleIcon = AlertTriangleIcon; exports.CircleArrowOutUpLeftIcon = CircleArrowOutUpLeftIcon; exports.CardIcon = CardIcon; exports.BankIcon = BankIcon; exports.UnplugIcon = UnplugIcon; exports.MigrateAssetsIcon = MigrateAssetsIcon; exports.AppleIcon = AppleIcon; exports.BodyHeader = BodyHeader; exports.CdnIcon = CdnIcon; exports.PoweredBy = PoweredBy; exports.Spinner = Spinner; exports.catalogKeyForChain = catalogKeyForChain; exports.debugLog = debugLog; exports.debugError = debugError; exports.getAssetId = getAssetId; exports.chainIdsByValue = chainIdsByValue; exports.portfolioToAssets = portfolioToAssets; exports.isNativeAsset = isNativeAsset; exports.formatFeeUsd = formatFeeUsd; exports.quoteFeeRow = quoteFeeRow; exports.quoteFeeGroups = quoteFeeGroups; exports.SwappedConnectFeeChangedError = SwappedConnectFeeChangedError; exports.SUPPORTED_CONNECT_EXCHANGE_COUNT = SUPPORTED_CONNECT_EXCHANGE_COUNT; exports.resolveAppFeeBps = resolveAppFeeBps; exports.PermitDepositSubmitError = PermitDepositSubmitError; exports.createDepositService = createDepositService; exports.rpcUrlFor = rpcUrlFor; exports.RpcUrlsProvider = RpcUrlsProvider; exports.useRpcUrls = useRpcUrls; exports.useStableRpcUrls = useStableRpcUrls; exports.getPublicClient = getPublicClient; exports.peekRuntimeChains = peekRuntimeChains; exports.primeRuntimeChains = primeRuntimeChains; exports.useChainCatalog = useChainCatalog; exports.useCatalogChain = useCatalogChain; exports.useDepositChainIds = useDepositChainIds; exports.useDestinationChains = useDestinationChains; exports.useTargetTokens = useTargetTokens; exports.useIsDepositChain = useIsDepositChain; exports.useChainName = useChainName; exports.useReadClient = useReadClient; exports.useExplorerTxUrl = useExplorerTxUrl; exports.ChainCatalogProvider = ChainCatalogProvider; exports.useLatestRef = useLatestRef; exports.Button = Button; exports.Callout = Callout; exports.TokenIcon = TokenIcon; exports.currencyFormatter = currencyFormatter; exports.tokenFormatter = tokenFormatter; exports.isUnsupportedChainSwitchError = isUnsupportedChainSwitchError; exports.formatUserError = formatUserError; exports.resolveTokenDisplay = resolveTokenDisplay; exports.formatTokenAmount = formatTokenAmount; exports.tokenAmountToNumber = tokenAmountToNumber; exports.formatRawTokenAmount = formatRawTokenAmount; exports.isDisplayStablecoinSymbol = isDisplayStablecoinSymbol; exports.isRecognizedToken = isRecognizedToken; exports.estimateReceiveAmount = estimateReceiveAmount; exports.formatQuotedReceive = formatQuotedReceive; exports.formatReceiveEstimate = formatReceiveEstimate; exports.AnalyticsSession = AnalyticsSession; exports.useDepositAnalyticsEmitter = useDepositAnalyticsEmitter; exports.useWithdrawAnalyticsEmitter = useWithdrawAnalyticsEmitter; exports.useClaimAnalyticsEmitter = useClaimAnalyticsEmitter; exports.resolveThemeMode = resolveThemeMode; exports.followSystemAppearance = followSystemAppearance; exports.applyTheme = applyTheme; exports.checkBackendUrl = checkBackendUrl;