@glacislabs/stablegenie-zerodelta 4.12.0 → 4.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mount.cjs CHANGED
@@ -4,7 +4,575 @@ var react = require('react');
4
4
  var client = require('react-dom/client');
5
5
  var jsxRuntime = require('react/jsx-runtime');
6
6
 
7
- // src/mount.ts
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // node_modules/@noble/ed25519/index.js
18
+ var ed25519_exports = {};
19
+ __export(ed25519_exports, {
20
+ Point: () => Point,
21
+ etc: () => etc,
22
+ getPublicKey: () => getPublicKey,
23
+ getPublicKeyAsync: () => getPublicKeyAsync,
24
+ hash: () => hash,
25
+ hashes: () => hashes,
26
+ keygen: () => keygen,
27
+ keygenAsync: () => keygenAsync,
28
+ sign: () => sign,
29
+ signAsync: () => signAsync,
30
+ utils: () => utils,
31
+ verify: () => verify,
32
+ verifyAsync: () => verifyAsync
33
+ });
34
+ var ed25519_CURVE, P2, N, Gx, Gy, _a, _d, h, L, L2, captureTrace, err, isBig, isStr, isBytes, abytes, u8n, u8fr, padh, bytesToHex, C, _ch, hexToBytes, cr, subtle, concatBytes, randomBytes, big, assertRange, M, modN, invert, callHash, hash, apoint, B256, Point, G, I, numTo32bLE, bytesToNumLE, pow2, pow_2_252_3, RM1, uvRatio, modL_LE, sha512a, sha512s, hash2extK, getExtendedPublicKeyAsync, getExtendedPublicKey, getPublicKeyAsync, getPublicKey, hashFinishA, hashFinishS, _sign, signAsync, sign, defaultVerifyOpts, _verify, verifyAsync, verify, etc, hashes, randomSecretKey, keygen, keygenAsync, utils, W, scalarBits, pwindows, pwindowSize, precompute, Gpows, ctneg, wNAF;
35
+ var init_ed25519 = __esm({
36
+ "node_modules/@noble/ed25519/index.js"() {
37
+ ed25519_CURVE = {
38
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
39
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
40
+ h: 8n,
41
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
42
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
43
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
44
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
45
+ };
46
+ ({ p: P2, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE);
47
+ L = 32;
48
+ L2 = 64;
49
+ captureTrace = (...args) => {
50
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
51
+ Error.captureStackTrace(...args);
52
+ }
53
+ };
54
+ err = (message = "") => {
55
+ const e = new Error(message);
56
+ captureTrace(e, err);
57
+ throw e;
58
+ };
59
+ isBig = (n) => typeof n === "bigint";
60
+ isStr = (s) => typeof s === "string";
61
+ isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
62
+ abytes = (value, length, title = "") => {
63
+ const bytes = isBytes(value);
64
+ const len = value?.length;
65
+ const needsLen = length !== void 0;
66
+ if (!bytes || needsLen && len !== length) {
67
+ const prefix = title && `"${title}" `;
68
+ const ofLen = needsLen ? ` of length ${length}` : "";
69
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
70
+ err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
71
+ }
72
+ return value;
73
+ };
74
+ u8n = (len) => new Uint8Array(len);
75
+ u8fr = (buf) => Uint8Array.from(buf);
76
+ padh = (n, pad) => n.toString(16).padStart(pad, "0");
77
+ bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
78
+ C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
79
+ _ch = (ch) => {
80
+ if (ch >= C._0 && ch <= C._9)
81
+ return ch - C._0;
82
+ if (ch >= C.A && ch <= C.F)
83
+ return ch - (C.A - 10);
84
+ if (ch >= C.a && ch <= C.f)
85
+ return ch - (C.a - 10);
86
+ return;
87
+ };
88
+ hexToBytes = (hex) => {
89
+ const e = "hex invalid";
90
+ if (!isStr(hex))
91
+ return err(e);
92
+ const hl = hex.length;
93
+ const al = hl / 2;
94
+ if (hl % 2)
95
+ return err(e);
96
+ const array = u8n(al);
97
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
98
+ const n1 = _ch(hex.charCodeAt(hi));
99
+ const n2 = _ch(hex.charCodeAt(hi + 1));
100
+ if (n1 === void 0 || n2 === void 0)
101
+ return err(e);
102
+ array[ai] = n1 * 16 + n2;
103
+ }
104
+ return array;
105
+ };
106
+ cr = () => globalThis?.crypto;
107
+ subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
108
+ concatBytes = (...arrs) => {
109
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
110
+ let pad = 0;
111
+ arrs.forEach((a) => {
112
+ r.set(a, pad);
113
+ pad += a.length;
114
+ });
115
+ return r;
116
+ };
117
+ randomBytes = (len = L) => {
118
+ const c = cr();
119
+ return c.getRandomValues(u8n(len));
120
+ };
121
+ big = BigInt;
122
+ assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
123
+ M = (a, b = P2) => {
124
+ const r = a % b;
125
+ return r >= 0n ? r : b + r;
126
+ };
127
+ modN = (a) => M(a, N);
128
+ invert = (num, md) => {
129
+ if (num === 0n || md <= 0n)
130
+ err("no inverse n=" + num + " mod=" + md);
131
+ let a = M(num, md), b = md, x = 0n, u = 1n;
132
+ while (a !== 0n) {
133
+ const q = b / a, r = b % a;
134
+ const m = x - u * q;
135
+ b = a, a = r, x = u, u = m;
136
+ }
137
+ return b === 1n ? M(x, md) : err("no inverse");
138
+ };
139
+ callHash = (name) => {
140
+ const fn = hashes[name];
141
+ if (typeof fn !== "function")
142
+ err("hashes." + name + " not set");
143
+ return fn;
144
+ };
145
+ hash = (msg) => callHash("sha512")(msg);
146
+ apoint = (p) => p instanceof Point ? p : err("Point expected");
147
+ B256 = 2n ** 256n;
148
+ Point = class _Point {
149
+ static BASE;
150
+ static ZERO;
151
+ X;
152
+ Y;
153
+ Z;
154
+ T;
155
+ constructor(X, Y, Z, T) {
156
+ const max = B256;
157
+ this.X = assertRange(X, 0n, max);
158
+ this.Y = assertRange(Y, 0n, max);
159
+ this.Z = assertRange(Z, 1n, max);
160
+ this.T = assertRange(T, 0n, max);
161
+ Object.freeze(this);
162
+ }
163
+ static CURVE() {
164
+ return ed25519_CURVE;
165
+ }
166
+ static fromAffine(p) {
167
+ return new _Point(p.x, p.y, 1n, M(p.x * p.y));
168
+ }
169
+ /** RFC8032 5.1.3: Uint8Array to Point. */
170
+ static fromBytes(hex, zip215 = false) {
171
+ const d = _d;
172
+ const normed = u8fr(abytes(hex, L));
173
+ const lastByte = hex[31];
174
+ normed[31] = lastByte & -129;
175
+ const y = bytesToNumLE(normed);
176
+ const max = zip215 ? B256 : P2;
177
+ assertRange(y, 0n, max);
178
+ const y2 = M(y * y);
179
+ const u = M(y2 - 1n);
180
+ const v = M(d * y2 + 1n);
181
+ let { isValid, value: x } = uvRatio(u, v);
182
+ if (!isValid)
183
+ err("bad point: y not sqrt");
184
+ const isXOdd = (x & 1n) === 1n;
185
+ const isLastByteOdd = (lastByte & 128) !== 0;
186
+ if (!zip215 && x === 0n && isLastByteOdd)
187
+ err("bad point: x==0, isLastByteOdd");
188
+ if (isLastByteOdd !== isXOdd)
189
+ x = M(-x);
190
+ return new _Point(x, y, 1n, M(x * y));
191
+ }
192
+ static fromHex(hex, zip215) {
193
+ return _Point.fromBytes(hexToBytes(hex), zip215);
194
+ }
195
+ get x() {
196
+ return this.toAffine().x;
197
+ }
198
+ get y() {
199
+ return this.toAffine().y;
200
+ }
201
+ /** Checks if the point is valid and on-curve. */
202
+ assertValidity() {
203
+ const a = _a;
204
+ const d = _d;
205
+ const p = this;
206
+ if (p.is0())
207
+ return err("bad point: ZERO");
208
+ const { X, Y, Z, T } = p;
209
+ const X2 = M(X * X);
210
+ const Y2 = M(Y * Y);
211
+ const Z2 = M(Z * Z);
212
+ const Z4 = M(Z2 * Z2);
213
+ const aX2 = M(X2 * a);
214
+ const left = M(Z2 * M(aX2 + Y2));
215
+ const right = M(Z4 + M(d * M(X2 * Y2)));
216
+ if (left !== right)
217
+ return err("bad point: equation left != right (1)");
218
+ const XY = M(X * Y);
219
+ const ZT = M(Z * T);
220
+ if (XY !== ZT)
221
+ return err("bad point: equation left != right (2)");
222
+ return this;
223
+ }
224
+ /** Equality check: compare points P&Q. */
225
+ equals(other) {
226
+ const { X: X1, Y: Y1, Z: Z1 } = this;
227
+ const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
228
+ const X1Z2 = M(X1 * Z2);
229
+ const X2Z1 = M(X2 * Z1);
230
+ const Y1Z2 = M(Y1 * Z2);
231
+ const Y2Z1 = M(Y2 * Z1);
232
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
233
+ }
234
+ is0() {
235
+ return this.equals(I);
236
+ }
237
+ /** Flip point over y coordinate. */
238
+ negate() {
239
+ return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
240
+ }
241
+ /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
242
+ double() {
243
+ const { X: X1, Y: Y1, Z: Z1 } = this;
244
+ const a = _a;
245
+ const A = M(X1 * X1);
246
+ const B = M(Y1 * Y1);
247
+ const C2 = M(2n * M(Z1 * Z1));
248
+ const D2 = M(a * A);
249
+ const x1y1 = X1 + Y1;
250
+ const E = M(M(x1y1 * x1y1) - A - B);
251
+ const G2 = D2 + B;
252
+ const F = G2 - C2;
253
+ const H = D2 - B;
254
+ const X3 = M(E * F);
255
+ const Y3 = M(G2 * H);
256
+ const T3 = M(E * H);
257
+ const Z3 = M(F * G2);
258
+ return new _Point(X3, Y3, Z3, T3);
259
+ }
260
+ /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
261
+ add(other) {
262
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
263
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
264
+ const a = _a;
265
+ const d = _d;
266
+ const A = M(X1 * X2);
267
+ const B = M(Y1 * Y2);
268
+ const C2 = M(T1 * d * T2);
269
+ const D2 = M(Z1 * Z2);
270
+ const E = M((X1 + Y1) * (X2 + Y2) - A - B);
271
+ const F = M(D2 - C2);
272
+ const G2 = M(D2 + C2);
273
+ const H = M(B - a * A);
274
+ const X3 = M(E * F);
275
+ const Y3 = M(G2 * H);
276
+ const T3 = M(E * H);
277
+ const Z3 = M(F * G2);
278
+ return new _Point(X3, Y3, Z3, T3);
279
+ }
280
+ subtract(other) {
281
+ return this.add(apoint(other).negate());
282
+ }
283
+ /**
284
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
285
+ * Uses {@link wNAF} for base point.
286
+ * Uses fake point to mitigate side-channel leakage.
287
+ * @param n scalar by which point is multiplied
288
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
289
+ */
290
+ multiply(n, safe = true) {
291
+ if (!safe && (n === 0n || this.is0()))
292
+ return I;
293
+ assertRange(n, 1n, N);
294
+ if (n === 1n)
295
+ return this;
296
+ if (this.equals(G))
297
+ return wNAF(n).p;
298
+ let p = I;
299
+ let f = G;
300
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
301
+ if (n & 1n)
302
+ p = p.add(d);
303
+ else if (safe)
304
+ f = f.add(d);
305
+ }
306
+ return p;
307
+ }
308
+ multiplyUnsafe(scalar) {
309
+ return this.multiply(scalar, false);
310
+ }
311
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
312
+ toAffine() {
313
+ const { X, Y, Z } = this;
314
+ if (this.equals(I))
315
+ return { x: 0n, y: 1n };
316
+ const iz = invert(Z, P2);
317
+ if (M(Z * iz) !== 1n)
318
+ err("invalid inverse");
319
+ const x = M(X * iz);
320
+ const y = M(Y * iz);
321
+ return { x, y };
322
+ }
323
+ toBytes() {
324
+ const { x, y } = this.assertValidity().toAffine();
325
+ const b = numTo32bLE(y);
326
+ b[31] |= x & 1n ? 128 : 0;
327
+ return b;
328
+ }
329
+ toHex() {
330
+ return bytesToHex(this.toBytes());
331
+ }
332
+ clearCofactor() {
333
+ return this.multiply(big(h), false);
334
+ }
335
+ isSmallOrder() {
336
+ return this.clearCofactor().is0();
337
+ }
338
+ isTorsionFree() {
339
+ let p = this.multiply(N / 2n, false).double();
340
+ if (N % 2n)
341
+ p = p.add(this);
342
+ return p.is0();
343
+ }
344
+ };
345
+ G = new Point(Gx, Gy, 1n, M(Gx * Gy));
346
+ I = new Point(0n, 1n, 1n, 0n);
347
+ Point.BASE = G;
348
+ Point.ZERO = I;
349
+ numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
350
+ bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
351
+ pow2 = (x, power) => {
352
+ let r = x;
353
+ while (power-- > 0n) {
354
+ r *= r;
355
+ r %= P2;
356
+ }
357
+ return r;
358
+ };
359
+ pow_2_252_3 = (x) => {
360
+ const x2 = x * x % P2;
361
+ const b2 = x2 * x % P2;
362
+ const b4 = pow2(b2, 2n) * b2 % P2;
363
+ const b5 = pow2(b4, 1n) * x % P2;
364
+ const b10 = pow2(b5, 5n) * b5 % P2;
365
+ const b20 = pow2(b10, 10n) * b10 % P2;
366
+ const b40 = pow2(b20, 20n) * b20 % P2;
367
+ const b80 = pow2(b40, 40n) * b40 % P2;
368
+ const b160 = pow2(b80, 80n) * b80 % P2;
369
+ const b240 = pow2(b160, 80n) * b80 % P2;
370
+ const b250 = pow2(b240, 10n) * b10 % P2;
371
+ const pow_p_5_8 = pow2(b250, 2n) * x % P2;
372
+ return { pow_p_5_8, b2 };
373
+ };
374
+ RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
375
+ uvRatio = (u, v) => {
376
+ const v3 = M(v * v * v);
377
+ const v7 = M(v3 * v3 * v);
378
+ const pow3 = pow_2_252_3(u * v7).pow_p_5_8;
379
+ let x = M(u * v3 * pow3);
380
+ const vx2 = M(v * x * x);
381
+ const root1 = x;
382
+ const root2 = M(x * RM1);
383
+ const useRoot1 = vx2 === u;
384
+ const useRoot2 = vx2 === M(-u);
385
+ const noRoot = vx2 === M(-u * RM1);
386
+ if (useRoot1)
387
+ x = root1;
388
+ if (useRoot2 || noRoot)
389
+ x = root2;
390
+ if ((M(x) & 1n) === 1n)
391
+ x = M(-x);
392
+ return { isValid: useRoot1 || useRoot2, value: x };
393
+ };
394
+ modL_LE = (hash2) => modN(bytesToNumLE(hash2));
395
+ sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
396
+ sha512s = (...m) => callHash("sha512")(concatBytes(...m));
397
+ hash2extK = (hashed) => {
398
+ const head = hashed.slice(0, L);
399
+ head[0] &= 248;
400
+ head[31] &= 127;
401
+ head[31] |= 64;
402
+ const prefix = hashed.slice(L, L2);
403
+ const scalar = modL_LE(head);
404
+ const point = G.multiply(scalar);
405
+ const pointBytes = point.toBytes();
406
+ return { head, prefix, scalar, point, pointBytes };
407
+ };
408
+ getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
409
+ getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
410
+ getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
411
+ getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
412
+ hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
413
+ hashFinishS = (res) => res.finish(sha512s(res.hashable));
414
+ _sign = (e, rBytes, msg) => {
415
+ const { pointBytes: P3, scalar: s } = e;
416
+ const r = modL_LE(rBytes);
417
+ const R = G.multiply(r).toBytes();
418
+ const hashable = concatBytes(R, P3, msg);
419
+ const finish = (hashed) => {
420
+ const S = modN(r + modL_LE(hashed) * s);
421
+ return abytes(concatBytes(R, numTo32bLE(S)), L2);
422
+ };
423
+ return { hashable, finish };
424
+ };
425
+ signAsync = async (message, secretKey) => {
426
+ const m = abytes(message);
427
+ const e = await getExtendedPublicKeyAsync(secretKey);
428
+ const rBytes = await sha512a(e.prefix, m);
429
+ return hashFinishA(_sign(e, rBytes, m));
430
+ };
431
+ sign = (message, secretKey) => {
432
+ const m = abytes(message);
433
+ const e = getExtendedPublicKey(secretKey);
434
+ const rBytes = sha512s(e.prefix, m);
435
+ return hashFinishS(_sign(e, rBytes, m));
436
+ };
437
+ defaultVerifyOpts = { zip215: true };
438
+ _verify = (sig, msg, pub, opts = defaultVerifyOpts) => {
439
+ sig = abytes(sig, L2);
440
+ msg = abytes(msg);
441
+ pub = abytes(pub, L);
442
+ const { zip215 } = opts;
443
+ let A;
444
+ let R;
445
+ let s;
446
+ let SB;
447
+ let hashable = Uint8Array.of();
448
+ try {
449
+ A = Point.fromBytes(pub, zip215);
450
+ R = Point.fromBytes(sig.slice(0, L), zip215);
451
+ s = bytesToNumLE(sig.slice(L, L2));
452
+ SB = G.multiply(s, false);
453
+ hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
454
+ } catch (error) {
455
+ }
456
+ const finish = (hashed) => {
457
+ if (SB == null)
458
+ return false;
459
+ if (!zip215 && A.isSmallOrder())
460
+ return false;
461
+ const k = modL_LE(hashed);
462
+ const RkA = R.add(A.multiply(k, false));
463
+ return RkA.add(SB.negate()).clearCofactor().is0();
464
+ };
465
+ return { hashable, finish };
466
+ };
467
+ verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
468
+ verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));
469
+ etc = {
470
+ bytesToHex,
471
+ hexToBytes,
472
+ concatBytes,
473
+ mod: M,
474
+ invert,
475
+ randomBytes
476
+ };
477
+ hashes = {
478
+ sha512Async: async (message) => {
479
+ const s = subtle();
480
+ const m = concatBytes(message);
481
+ return u8n(await s.digest("SHA-512", m.buffer));
482
+ },
483
+ sha512: void 0
484
+ };
485
+ randomSecretKey = (seed = randomBytes(L)) => seed;
486
+ keygen = (seed) => {
487
+ const secretKey = randomSecretKey(seed);
488
+ const publicKey = getPublicKey(secretKey);
489
+ return { secretKey, publicKey };
490
+ };
491
+ keygenAsync = async (seed) => {
492
+ const secretKey = randomSecretKey(seed);
493
+ const publicKey = await getPublicKeyAsync(secretKey);
494
+ return { secretKey, publicKey };
495
+ };
496
+ utils = {
497
+ getExtendedPublicKeyAsync,
498
+ getExtendedPublicKey,
499
+ randomSecretKey
500
+ };
501
+ W = 8;
502
+ scalarBits = 256;
503
+ pwindows = Math.ceil(scalarBits / W) + 1;
504
+ pwindowSize = 2 ** (W - 1);
505
+ precompute = () => {
506
+ const points = [];
507
+ let p = G;
508
+ let b = p;
509
+ for (let w = 0; w < pwindows; w++) {
510
+ b = p;
511
+ points.push(b);
512
+ for (let i = 1; i < pwindowSize; i++) {
513
+ b = b.add(p);
514
+ points.push(b);
515
+ }
516
+ p = b.double();
517
+ }
518
+ return points;
519
+ };
520
+ Gpows = void 0;
521
+ ctneg = (cnd, p) => {
522
+ const n = p.negate();
523
+ return cnd ? n : p;
524
+ };
525
+ wNAF = (n) => {
526
+ const comp = Gpows || (Gpows = precompute());
527
+ let p = I;
528
+ let f = G;
529
+ const pow_2_w = 2 ** W;
530
+ const maxNum = pow_2_w;
531
+ const mask = big(pow_2_w - 1);
532
+ const shiftBy = big(W);
533
+ for (let w = 0; w < pwindows; w++) {
534
+ let wbits = Number(n & mask);
535
+ n >>= shiftBy;
536
+ if (wbits > pwindowSize) {
537
+ wbits -= maxNum;
538
+ n += 1n;
539
+ }
540
+ const off = w * pwindowSize;
541
+ const offF = off;
542
+ const offP = off + Math.abs(wbits) - 1;
543
+ const isEven = w % 2 !== 0;
544
+ const isNeg = wbits < 0;
545
+ if (wbits === 0) {
546
+ f = f.add(ctneg(isEven, comp[offF]));
547
+ } else {
548
+ p = p.add(ctneg(isNeg, comp[offP]));
549
+ }
550
+ }
551
+ if (n !== 0n)
552
+ err("invalid wnaf");
553
+ return { p, f };
554
+ };
555
+ }
556
+ });
557
+
558
+ // src/core/ed25519.ts
559
+ var ed25519_exports2 = {};
560
+ __export(ed25519_exports2, {
561
+ eventPublicKey: () => eventPublicKey,
562
+ eventSignature: () => eventSignature
563
+ });
564
+ async function eventPublicKey(seed) {
565
+ const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
566
+ return ed.getPublicKeyAsync(seed);
567
+ }
568
+ async function eventSignature(message, seed) {
569
+ const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
570
+ return ed.signAsync(message, seed);
571
+ }
572
+ var init_ed255192 = __esm({
573
+ "src/core/ed25519.ts"() {
574
+ }
575
+ });
8
576
  var ConfigContext = react.createContext({});
9
577
  function useMergedConfig(local) {
10
578
  const ctx = react.useContext(ConfigContext);
@@ -104,7 +672,10 @@ var CANONICAL_ESCROW = Object.freeze({
104
672
  // Plume
105
673
  });
106
674
  var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
107
- var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {};
675
+ var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
676
+ 9745: 2500n * 10n ** 18n,
677
+ 98866: 5000n * 10n ** 18n
678
+ };
108
679
  function maxNativeFeeWei(chainId) {
109
680
  return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
110
681
  }
@@ -222,6 +793,247 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
222
793
  1151111081099710: "Solana"
223
794
  });
224
795
 
796
+ // src/core/solana.ts
797
+ var SOLANA_CHAIN_ID = 1151111081099710;
798
+ function isSolanaChainId(value) {
799
+ return Number(value) === SOLANA_CHAIN_ID;
800
+ }
801
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
802
+ function base58Encode(bytes) {
803
+ let zeros = 0;
804
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
805
+ let value = 0n;
806
+ for (const byte of bytes) value = value << 8n | BigInt(byte);
807
+ let out = "";
808
+ while (value > 0n) {
809
+ out = BASE58_ALPHABET[Number(value % 58n)] + out;
810
+ value /= 58n;
811
+ }
812
+ return "1".repeat(zeros) + out;
813
+ }
814
+ function base58Decode(text) {
815
+ let value = 0n;
816
+ for (const char of text) {
817
+ const digit = BASE58_ALPHABET.indexOf(char);
818
+ if (digit < 0) return null;
819
+ value = value * 58n + BigInt(digit);
820
+ }
821
+ const body = [];
822
+ while (value > 0n) {
823
+ body.unshift(Number(value & 0xffn));
824
+ value >>= 8n;
825
+ }
826
+ let zeros = 0;
827
+ while (zeros < text.length && text[zeros] === "1") zeros += 1;
828
+ return new Uint8Array([...new Array(zeros).fill(0), ...body]);
829
+ }
830
+ function isSolanaAddress(value) {
831
+ const text = typeof value === "string" ? value.trim() : "";
832
+ return text.length >= 32 && text.length <= 44 && base58Decode(text)?.length === 32;
833
+ }
834
+ function solanaKeyHex(value) {
835
+ if (!isSolanaAddress(value)) return null;
836
+ return `0x${Array.from(base58Decode(value.trim()), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
837
+ }
838
+ function hexToSolanaKey(value) {
839
+ if (!/^0x[0-9a-fA-F]{64}$/.test(value)) return null;
840
+ return base58Encode(Uint8Array.from(value.slice(2).match(/../g), (byte) => Number.parseInt(byte, 16)));
841
+ }
842
+ var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
843
+ var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
844
+ var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
845
+ var pin = (symbol, decimals, bridge, tokenProgram) => Object.freeze({ symbol, decimals, bridge, tokenProgram });
846
+ var SOLANA_DESTINATION_ASSETS = Object.freeze({
847
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: pin("USDC", 6, "cctp", TOKEN_PROGRAM),
848
+ "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": pin("PYUSD", 6, "layerzero", TOKEN_2022_PROGRAM),
849
+ DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT: pin("USDE", 9, "layerzero", TOKEN_PROGRAM),
850
+ "2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": pin("USDG", 6, "layerzero", TOKEN_2022_PROGRAM),
851
+ AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
852
+ });
853
+ function solanaDestinationAsset(mint) {
854
+ const key = typeof mint === "string" ? mint.trim() : "";
855
+ return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
856
+ }
857
+ function solanaBridgeOf(token) {
858
+ const pinned = solanaDestinationAsset(token.address);
859
+ if (!pinned || pinned.symbol !== token.symbol.trim().toUpperCase()) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
860
+ return pinned.bridge;
861
+ }
862
+ var K = new Uint32Array([
863
+ 1116352408,
864
+ 1899447441,
865
+ 3049323471,
866
+ 3921009573,
867
+ 961987163,
868
+ 1508970993,
869
+ 2453635748,
870
+ 2870763221,
871
+ 3624381080,
872
+ 310598401,
873
+ 607225278,
874
+ 1426881987,
875
+ 1925078388,
876
+ 2162078206,
877
+ 2614888103,
878
+ 3248222580,
879
+ 3835390401,
880
+ 4022224774,
881
+ 264347078,
882
+ 604807628,
883
+ 770255983,
884
+ 1249150122,
885
+ 1555081692,
886
+ 1996064986,
887
+ 2554220882,
888
+ 2821834349,
889
+ 2952996808,
890
+ 3210313671,
891
+ 3336571891,
892
+ 3584528711,
893
+ 113926993,
894
+ 338241895,
895
+ 666307205,
896
+ 773529912,
897
+ 1294757372,
898
+ 1396182291,
899
+ 1695183700,
900
+ 1986661051,
901
+ 2177026350,
902
+ 2456956037,
903
+ 2730485921,
904
+ 2820302411,
905
+ 3259730800,
906
+ 3345764771,
907
+ 3516065817,
908
+ 3600352804,
909
+ 4094571909,
910
+ 275423344,
911
+ 430227734,
912
+ 506948616,
913
+ 659060556,
914
+ 883997877,
915
+ 958139571,
916
+ 1322822218,
917
+ 1537002063,
918
+ 1747873779,
919
+ 1955562222,
920
+ 2024104815,
921
+ 2227730452,
922
+ 2361852424,
923
+ 2428436474,
924
+ 2756734187,
925
+ 3204031479,
926
+ 3329325298
927
+ ]);
928
+ function sha256(data) {
929
+ const bitLen = data.length * 8;
930
+ const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
931
+ padded.set(data);
932
+ padded[data.length] = 128;
933
+ const view = new DataView(padded.buffer);
934
+ view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
935
+ view.setUint32(padded.length - 4, bitLen >>> 0);
936
+ const h2 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
937
+ const w = new Uint32Array(64);
938
+ const rotr = (x, n) => x >>> n | x << 32 - n;
939
+ for (let off = 0; off < padded.length; off += 64) {
940
+ for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
941
+ for (let i = 16; i < 64; i += 1) {
942
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
943
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
944
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
945
+ }
946
+ let [a, b, c, d, e, f, g, hh] = h2;
947
+ for (let i = 0; i < 64; i += 1) {
948
+ const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
949
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
950
+ hh = g;
951
+ g = f;
952
+ f = e;
953
+ e = d + t1 >>> 0;
954
+ d = c;
955
+ c = b;
956
+ b = a;
957
+ a = t1 + t2 >>> 0;
958
+ }
959
+ h2[0] = h2[0] + a >>> 0;
960
+ h2[1] = h2[1] + b >>> 0;
961
+ h2[2] = h2[2] + c >>> 0;
962
+ h2[3] = h2[3] + d >>> 0;
963
+ h2[4] = h2[4] + e >>> 0;
964
+ h2[5] = h2[5] + f >>> 0;
965
+ h2[6] = h2[6] + g >>> 0;
966
+ h2[7] = h2[7] + hh >>> 0;
967
+ }
968
+ const out = new Uint8Array(32);
969
+ const outView = new DataView(out.buffer);
970
+ for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h2[i]);
971
+ return out;
972
+ }
973
+ var P = 2n ** 255n - 19n;
974
+ var mod = (a) => (a % P + P) % P;
975
+ var pow = (base, exp) => {
976
+ let result = 1n;
977
+ let b = mod(base);
978
+ for (let e = exp; e > 0n; e >>= 1n) {
979
+ if (e & 1n) result = result * b % P;
980
+ b = b * b % P;
981
+ }
982
+ return result;
983
+ };
984
+ var D = mod(-121665n * pow(121666n, P - 2n));
985
+ function isOnEd25519Curve(bytes) {
986
+ let y = 0n;
987
+ for (let i = 31; i >= 0; i -= 1) y = y << 8n | BigInt(bytes[i]);
988
+ y = mod(y & (1n << 255n) - 1n);
989
+ const yy = y * y % P;
990
+ const u = mod(yy - 1n);
991
+ const v = mod(D * yy + 1n);
992
+ if (v === 0n) return u === 0n;
993
+ const x2 = u * pow(v, P - 2n) % P;
994
+ return x2 === 0n || pow(x2, (P - 1n) / 2n) === 1n;
995
+ }
996
+ function keyBytes(base58) {
997
+ const bytes = base58Decode(base58);
998
+ if (!bytes || bytes.length !== 32) throw new Error("Not a valid Solana address.");
999
+ return bytes;
1000
+ }
1001
+ function findProgramAddress(seeds, programId) {
1002
+ const program = keyBytes(programId);
1003
+ const marker = new TextEncoder().encode("ProgramDerivedAddress");
1004
+ for (let bump = 255; bump >= 1; bump -= 1) {
1005
+ const parts = [...seeds, Uint8Array.of(bump), program, marker];
1006
+ const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
1007
+ let at = 0;
1008
+ for (const part of parts) {
1009
+ buf.set(part, at);
1010
+ at += part.length;
1011
+ }
1012
+ const candidate = sha256(buf);
1013
+ if (!isOnEd25519Curve(candidate)) return candidate;
1014
+ }
1015
+ throw new Error("Could not derive a program address.");
1016
+ }
1017
+ function associatedTokenAddress(owner, mint, tokenProgram) {
1018
+ return base58Encode(findProgramAddress([keyBytes(owner), keyBytes(tokenProgram), keyBytes(mint)], ASSOCIATED_TOKEN_PROGRAM));
1019
+ }
1020
+ function expectedSolanaDelivery(recipient2, mint) {
1021
+ if (!isSolanaAddress(recipient2)) throw new Error("Not a valid Solana address.");
1022
+ const pinned = solanaDestinationAsset(mint);
1023
+ if (!pinned) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
1024
+ const target = pinned.bridge === "cctp" ? associatedTokenAddress(recipient2.trim(), mint.trim(), pinned.tokenProgram) : recipient2.trim();
1025
+ return solanaKeyHex(target);
1026
+ }
1027
+ function checkSolanaReceiver(request, intended, mint) {
1028
+ if (!isSolanaAddress(intended)) throw new Error("Not a valid Solana address.");
1029
+ if (request.destinationReceiverOwner !== intended.trim()) throw new Error("The quote was not made out to your Solana recipient; refusing to sign.");
1030
+ const receiver = request.destinationReceiver || "";
1031
+ const display = hexToSolanaKey(receiver);
1032
+ if (!display) throw new Error("The quote carries no Solana delivery account; refusing to sign.");
1033
+ if (request.destinationReceiverBase58 && request.destinationReceiverBase58 !== display) throw new Error("The quote names two different Solana delivery accounts; refusing to sign.");
1034
+ if (receiver.toLowerCase() !== expectedSolanaDelivery(intended, mint)) throw new Error("The quote would deliver to an account that is not your Solana recipient's; refusing to sign.");
1035
+ }
1036
+
225
1037
  // src/core/address.ts
226
1038
  function symbolKey(value) {
227
1039
  return String(value || "").trim().toUpperCase();
@@ -238,66 +1050,26 @@ function assertAddress(value, label) {
238
1050
  if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label} is not a valid EVM address.`);
239
1051
  return normalized;
240
1052
  }
241
- function resolveSwapReceiver(recipient, payer) {
1053
+ function resolveSwapReceiver(recipient2, payer, destinationChainId) {
242
1054
  const payerAddr = assertAddress(payer, "Swap wallet");
243
- if (recipient === void 0 || recipient === null || recipient === "") return payerAddr;
244
- const normalized = normalizeAddress(recipient);
1055
+ if (isSolanaChainId(destinationChainId)) return assertChainAddress(destinationChainId, recipient2, "Deposit recipient");
1056
+ if (recipient2 === void 0 || recipient2 === null || recipient2 === "") return payerAddr;
1057
+ const normalized = normalizeAddress(recipient2);
245
1058
  if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
246
1059
  return normalized;
247
1060
  }
248
-
249
- // src/core/units.ts
250
- function assetDecimals(token) {
251
- const sym = symbolKey(token?.symbol);
252
- const registry = Number(token?.decimals);
253
- const canonical = CANONICAL_DECIMALS[sym];
254
- if (canonical !== void 0) {
255
- if (!Number.isInteger(registry)) {
256
- throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
257
- }
258
- if (registry !== canonical) {
259
- throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
260
- }
261
- return canonical;
262
- }
263
- if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
264
- throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
265
- }
266
- return registry;
1061
+ function isChainAddress(chainId, value) {
1062
+ return isSolanaChainId(chainId) ? isSolanaAddress(value) : isAddress(value);
267
1063
  }
268
- function normalizeDecimalText(value) {
269
- const text = String(value || "").trim().replace(/\s+/g, "");
270
- if (!text) return "";
271
- if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
272
- if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
273
- if (text.includes(",")) return "";
274
- return text;
1064
+ function chainAddressKey(chainId, value) {
1065
+ const text = String(value || "");
1066
+ return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
275
1067
  }
276
- function parseUnitsDecimal(amount, decimals) {
277
- const text = normalizeDecimalText(amount);
278
- if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
279
- const [whole, frac = ""] = text.split(".");
280
- if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
281
- const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
282
- const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
283
- if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
284
- return value;
285
- }
286
- function scaleDecimals(amount, fromDecimals, toDecimals) {
287
- if (toDecimals === fromDecimals) return amount;
288
- if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
289
- return amount / 10n ** BigInt(fromDecimals - toDecimals);
290
- }
291
- function formatUnits(raw, decimals, maxDecimals = 6) {
292
- const value = BigInt(raw || "0");
293
- const base = 10n ** BigInt(decimals);
294
- const whole = value / base;
295
- const fracFull = (value % base).toString().padStart(decimals, "0");
296
- const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
297
- return frac ? `${whole}.${frac}` : whole.toString();
298
- }
299
- function finalOf(quote) {
300
- return BigInt(quote?.finalAmount || quote?.toAmount || "0");
1068
+ function assertChainAddress(chainId, value, label) {
1069
+ if (!isSolanaChainId(chainId)) return assertAddress(value, label);
1070
+ if (!String(value || "").trim()) throw new Error("Connect a Solana wallet or enter a Solana recipient address.");
1071
+ if (!isSolanaAddress(value)) throw new Error("Not a valid Solana address.");
1072
+ return String(value).trim();
301
1073
  }
302
1074
 
303
1075
  // src/core/abi.ts
@@ -376,8 +1148,6 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
376
1148
  }).join("");
377
1149
  return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
378
1150
  }
379
- var EVM_BYTES_PAYLOAD_BYTES = 64;
380
- var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
381
1151
  var MAX_DECODED_ORDERS = 16;
382
1152
  function decodeSubmitOrderCalldata(data) {
383
1153
  const hex = strip0x(String(data || "")).toLowerCase();
@@ -398,12 +1168,14 @@ function decodeSubmitOrderCalldata(data) {
398
1168
  const w = word(byteOffset);
399
1169
  return w === null || w > MAX_UINT64 ? null : w;
400
1170
  };
401
- const evmBytesAt = (byteOffset) => {
1171
+ const keyBytesAt = (byteOffset) => {
402
1172
  const len = word(byteOffset);
403
- if (len !== 20n) return null;
404
- const content = body.slice((byteOffset + 32) * 2, (byteOffset + 64) * 2);
405
- if (content.length !== 64 || !content.endsWith("0".repeat(24))) return null;
406
- return `0x${content.slice(0, 40)}`;
1173
+ if (len !== 20n && len !== 32n) return null;
1174
+ const length = Number(len);
1175
+ const padded = Math.ceil(length / 32) * 32;
1176
+ const content = body.slice((byteOffset + 32) * 2, (byteOffset + 32 + padded) * 2);
1177
+ if (content.length !== padded * 2 || content.slice(length * 2) !== "0".repeat((padded - length) * 2)) return null;
1178
+ return { value: `0x${content.slice(0, length * 2)}`, size: 32 + padded };
407
1179
  };
408
1180
  if (word(0) !== 64n) return null;
409
1181
  if (word(32) === null) return null;
@@ -412,12 +1184,12 @@ function decodeSubmitOrderCalldata(data) {
412
1184
  if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
413
1185
  const n = Number(count);
414
1186
  const arrayBase = 96;
415
- if (totalBytes !== arrayBase + 32 * n + EVM_ORDER_TUPLE_BYTES * n) return null;
1187
+ let next = arrayBase + 32 * n;
416
1188
  const orders = [];
417
1189
  for (let i = 0; i < n; i += 1) {
418
1190
  const rel = word(arrayBase + i * 32);
419
- if (rel === null || rel !== BigInt(32 * n + EVM_ORDER_TUPLE_BYTES * i)) return null;
420
- const base = arrayBase + Number(rel);
1191
+ if (rel === null || rel !== BigInt(next - arrayBase)) return null;
1192
+ const base = next;
421
1193
  const owner = addressAt(base);
422
1194
  const bidToken = addressAt(base + 32);
423
1195
  const bidTokenAmount = word(base + 64);
@@ -427,14 +1199,17 @@ function decodeSubmitOrderCalldata(data) {
427
1199
  const destinationChainId = uint64At(base + 192);
428
1200
  const executionChainId = uint64At(base + 224);
429
1201
  const deadline = uint64At(base + 256);
430
- if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES || receiverOffset !== ORDER_HEAD_BYTES + BigInt(EVM_BYTES_PAYLOAD_BYTES)) {
1202
+ if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES) {
431
1203
  return null;
432
1204
  }
433
- const askToken = evmBytesAt(base + Number(askOffset));
434
- const destinationReceiver = evmBytesAt(base + Number(receiverOffset));
1205
+ const askToken = keyBytesAt(base + Number(askOffset));
1206
+ if (!askToken || receiverOffset !== ORDER_HEAD_BYTES + BigInt(askToken.size)) return null;
1207
+ const destinationReceiver = keyBytesAt(base + Number(receiverOffset));
435
1208
  if (askToken === null || destinationReceiver === null) return null;
436
- orders.push({ owner, bidToken, bidTokenAmount, askToken, askTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline });
1209
+ next = base + Number(ORDER_HEAD_BYTES) + askToken.size + destinationReceiver.size;
1210
+ orders.push({ owner, bidToken, bidTokenAmount, askToken: askToken.value, askTokenAmount, destinationReceiver: destinationReceiver.value, destinationChainId, executionChainId, deadline });
437
1211
  }
1212
+ if (next !== totalBytes) return null;
438
1213
  return { partnerId, orders };
439
1214
  }
440
1215
  function toHexQuantity(value) {
@@ -442,47 +1217,343 @@ function toHexQuantity(value) {
442
1217
  return `0x${n.toString(16)}`;
443
1218
  }
444
1219
 
445
- // src/core/escrow.ts
446
- function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
447
- const fromQuote = normalizeAddress(quoteEscrow);
448
- const fromChains = normalizeAddress(chainsEscrow);
449
- if (!fromChains || fromChains === ZERO_ADDRESS) {
450
- throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
1220
+ // src/core/solana-tx.ts
1221
+ function bytesEqual(a, b) {
1222
+ return a.length === b.length && a.every((v, i) => v === b[i]);
1223
+ }
1224
+ function hexBytes(hex) {
1225
+ const h2 = strip0x(hex);
1226
+ if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
1227
+ return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
1228
+ }
1229
+ function solanaKeyBytes(key) {
1230
+ if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
1231
+ return base58Decode(key);
1232
+ }
1233
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1234
+ function base64Decode(text) {
1235
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) throw new Error("Invalid base64.");
1236
+ const out = [];
1237
+ let value = 0, bits = 0;
1238
+ for (const ch of text.replace(/=+$/, "")) {
1239
+ value = value << 6 | B64.indexOf(ch);
1240
+ bits += 6;
1241
+ if (bits >= 8) {
1242
+ bits -= 8;
1243
+ out.push(value >> bits & 255);
1244
+ }
451
1245
  }
452
- if (!fromQuote || fromQuote === ZERO_ADDRESS) {
453
- throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
1246
+ const bytes = Uint8Array.from(out);
1247
+ if (base64Encode(bytes) !== text) throw new Error("Noncanonical base64.");
1248
+ return bytes;
1249
+ }
1250
+ function base64Encode(bytes) {
1251
+ let out = "";
1252
+ for (let i = 0; i < bytes.length; i += 3) {
1253
+ const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
1254
+ out += B64[n >>> 18 & 63] + B64[n >>> 12 & 63] + (i + 1 < bytes.length ? B64[n >>> 6 & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
454
1255
  }
455
- if (fromQuote !== fromChains) {
456
- throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
1256
+ return out;
1257
+ }
1258
+ var Reader = class {
1259
+ constructor(bytes) {
1260
+ this.bytes = bytes;
1261
+ }
1262
+ bytes;
1263
+ at = 0;
1264
+ take(n) {
1265
+ if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error("Truncated Solana data.");
1266
+ const v = this.bytes.slice(this.at, this.at + n);
1267
+ this.at += n;
1268
+ return v;
1269
+ }
1270
+ byte() {
1271
+ return this.take(1)[0];
1272
+ }
1273
+ compact() {
1274
+ let n = 0;
1275
+ for (let i = 0; i < 3; i++) {
1276
+ const b = this.byte();
1277
+ if (i === 2 && b > 3) throw new Error("Invalid compact-u16.");
1278
+ n |= (b & 127) << 7 * i;
1279
+ if (!(b & 128)) {
1280
+ if (i && b === 0) throw new Error("Noncanonical compact-u16.");
1281
+ return n;
1282
+ }
1283
+ }
1284
+ throw new Error("Invalid compact-u16.");
457
1285
  }
458
- const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
459
- if (pinned && pinned !== fromChains) {
460
- throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
1286
+ u64() {
1287
+ const b = this.take(8);
1288
+ let n = 0n;
1289
+ for (let i = 7; i >= 0; i--) n = n << 8n | BigInt(b[i]);
1290
+ return n;
461
1291
  }
462
- return fromChains;
1292
+ vec() {
1293
+ const b = this.take(4);
1294
+ return this.take(new DataView(b.buffer).getUint32(0, true));
1295
+ }
1296
+ end() {
1297
+ if (this.at !== this.bytes.length) throw new Error("Trailing Solana data.");
1298
+ }
1299
+ };
1300
+ function parseSolanaTransaction(input) {
1301
+ const bytes = new Uint8Array(input), r = new Reader(bytes);
1302
+ const count = r.compact(), signatureOffset = r.at;
1303
+ if (count < 1 || count > 127) throw new Error("Invalid signature count.");
1304
+ r.take(count * 64);
1305
+ const messageOffset = r.at, first = r.byte();
1306
+ if (first & 128 && first !== 128) throw new Error("Unsupported Solana message version.");
1307
+ const version = first === 128 ? 0 : "legacy";
1308
+ const requiredSignatures = version === 0 ? r.byte() : first;
1309
+ const readonlySigned = r.byte(), readonlyUnsigned = r.byte();
1310
+ const keyCount = r.compact();
1311
+ if (requiredSignatures !== count || requiredSignatures > keyCount || readonlySigned >= count || readonlyUnsigned > keyCount - count || keyCount > 256) throw new Error("Invalid Solana message header.");
1312
+ const staticKeys = Array.from({ length: keyCount }, () => base58Encode(r.take(32)));
1313
+ const blockhashOffset = r.at;
1314
+ r.take(32);
1315
+ const instructions = Array.from({ length: r.compact() }, () => {
1316
+ const programIdIndex = r.byte();
1317
+ const accounts = Array.from(r.take(r.compact()));
1318
+ return { programIdIndex, accounts, data: r.take(r.compact()) };
1319
+ });
1320
+ const lookups = version === 0 ? Array.from({ length: r.compact() }, () => ({
1321
+ address: base58Encode(r.take(32)),
1322
+ writable: Array.from(r.take(r.compact())),
1323
+ readonly: Array.from(r.take(r.compact()))
1324
+ })) : [];
1325
+ r.end();
1326
+ const all = keyCount + lookups.reduce((n, l) => n + l.writable.length + l.readonly.length, 0);
1327
+ if (all > 256 || instructions.some((ix) => ix.programIdIndex >= keyCount || ix.accounts.some((i) => i >= all))) throw new Error("Invalid Solana account index.");
1328
+ return { bytes, messageOffset, blockhashOffset, version, requiredSignatures, signatureOffset, staticKeys, instructions, lookups };
1329
+ }
1330
+ function overwriteBlockhash(input, blockhash) {
1331
+ const tx = parseSolanaTransaction(input), out = new Uint8Array(input);
1332
+ out.set(solanaKeyBytes(blockhash), tx.blockhashOffset);
1333
+ return out;
463
1334
  }
464
- function isLayerZeroRoute(quote, option = {}) {
465
- const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
466
- return bridge.includes("layerzero") || bridge.includes("layer zero");
1335
+ function placeSignature(input, publicKey, signature) {
1336
+ const tx = parseSolanaTransaction(input), index = tx.staticKeys.slice(0, tx.requiredSignatures).indexOf(publicKey);
1337
+ if (index < 0 || signature.length !== 64) throw new Error("Missing Solana signer slot.");
1338
+ const out = new Uint8Array(input);
1339
+ out.set(signature, tx.signatureOffset + index * 64);
1340
+ return out;
467
1341
  }
468
- function sourceAssetKey(quote, option = {}) {
469
- return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
1342
+ function assertWalletMessage(original, signed) {
1343
+ const a = parseSolanaTransaction(original), b = parseSolanaTransaction(signed);
1344
+ if (!bytesEqual(a.bytes.subarray(a.messageOffset), b.bytes.subarray(b.messageOffset))) throw new Error("The wallet modified the transaction message; refusing to send.");
1345
+ for (let i = 1; i < a.requiredSignatures; i++) {
1346
+ const start2 = a.signatureOffset + 64 * i;
1347
+ if (!bytesEqual(a.bytes.subarray(start2, start2 + 64), b.bytes.subarray(b.signatureOffset + i * 64, b.signatureOffset + (i + 1) * 64))) throw new Error("The wallet removed a co-signature; refusing to send.");
1348
+ }
1349
+ if (!b.bytes.subarray(b.signatureOffset, b.signatureOffset + 64).some(Boolean)) throw new Error("The wallet returned no fee-payer signature.");
1350
+ }
1351
+ var SUBMIT_ORDER_DISCRIMINATOR = [230, 150, 200, 53, 92, 208, 109, 108];
1352
+ function isSubmitOrder(data) {
1353
+ return data.length >= 8 && SUBMIT_ORDER_DISCRIMINATOR.every((v, i) => data[i] === v);
1354
+ }
1355
+ function decodeSolanaSubmitOrder(data) {
1356
+ if (!isSubmitOrder(data)) throw new Error("Not a submit_order instruction.");
1357
+ const r = new Reader(data);
1358
+ r.take(8);
1359
+ const owner = r.take(20), askToken = r.vec();
1360
+ let askTokenAmount = 0n;
1361
+ for (const b of r.take(32)) askTokenAmount = askTokenAmount << 8n | BigInt(b);
1362
+ const bidTokenAmount = r.u64(), destinationReceiver = r.vec(), destinationChainId = r.u64(), executionChainId = r.u64(), deadline = r.u64();
1363
+ const tag = r.byte();
1364
+ if (tag !== 0 && tag !== 1) throw new Error("Invalid submit_order partner tag.");
1365
+ const partnerId = tag === 1 ? r.take(32) : null;
1366
+ r.end();
1367
+ return { owner, askToken, askTokenAmount, bidTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline, partnerId };
1368
+ }
1369
+ function verifySolanaSubmit(p, e) {
1370
+ const fail = (field) => {
1371
+ throw new Error(`Solana order mismatch (${field}); refusing to sign.`);
1372
+ };
1373
+ if (hexBytes(e.owner).length !== 20 || !bytesEqual(p.owner, hexBytes(e.owner))) fail("owner");
1374
+ if (!bytesEqual(p.askToken, hexBytes(e.askToken))) fail("ask token");
1375
+ if (p.askTokenAmount <= 0n) fail("non-positive output");
1376
+ if (p.askTokenAmount < BigInt(e.minAskTokenAmount)) fail("minimum received");
1377
+ if (p.askTokenAmount > BigInt(e.maxAskTokenAmount)) fail("maximum received");
1378
+ if (p.bidTokenAmount !== BigInt(e.bidTokenAmount)) fail("amount sent");
1379
+ if (!bytesEqual(p.destinationReceiver, hexBytes(e.destinationReceiver))) fail("receiver");
1380
+ if (p.destinationChainId !== BigInt(e.destinationChainId)) fail("destination chain");
1381
+ if (p.executionChainId !== BigInt(e.executionChainId)) fail("execution chain");
1382
+ if (p.deadline !== BigInt(e.deadline)) fail("deadline");
1383
+ if (p.partnerId !== null !== (e.partnerId !== null)) fail("subsidy marker");
1384
+ }
1385
+ var PREPARATION_INSTRUCTIONS = [
1386
+ { discriminator: [225, 205, 234, 143, 17, 186, 50, 220], signer: 2 },
1387
+ // create_profile
1388
+ { discriminator: [223, 99, 118, 101, 213, 29, 215, 137], signer: 3 },
1389
+ // initialize_buffer_data
1390
+ { discriminator: [105, 254, 33, 182, 188, 80, 204, 204], signer: 3 },
1391
+ // write_buffer_data
1392
+ { discriminator: [179, 249, 129, 154, 80, 167, 138, 18], signer: 3 },
1393
+ // finalize_buffer_data
1394
+ { discriminator: [23, 25, 65, 45, 74, 9, 223, 23], signer: 2 }
1395
+ // close_buffer_data
1396
+ ];
1397
+ var SUBMIT_SIGNER_ACCOUNT = 11;
1398
+ function preparationInstruction(data) {
1399
+ return data.length >= 8 ? PREPARATION_INSTRUCTIONS.find((p) => p.discriminator.every((byte, i) => data[i] === byte)) : void 0;
1400
+ }
1401
+ function verifySolanaTransaction(tx, expected, keys, mustSubmit) {
1402
+ if (tx.staticKeys[0] !== expected.signer) throw new Error("Wrong Solana fee payer; refusing to sign.");
1403
+ if (!mustSubmit && tx.requiredSignatures !== 1) throw new Error("Unexpected co-signer on a preparation step; refusing to sign.");
1404
+ let submits = 0, buffer = null;
1405
+ for (const ix of tx.instructions) {
1406
+ if (tx.staticKeys[ix.programIdIndex] !== expected.program) throw new Error("Foreign program instruction; refusing to sign.");
1407
+ const preparation = preparationInstruction(ix.data);
1408
+ if (!isSubmitOrder(ix.data) && !preparation) throw new Error("Unexpected ZeroDelta instruction; refusing to sign.");
1409
+ const signerSlot = preparation ? preparation.signer : SUBMIT_SIGNER_ACCOUNT;
1410
+ if (keys[ix.accounts[signerSlot]] !== expected.signer) throw new Error("ZeroDelta instruction names another signer; refusing to sign.");
1411
+ if (!isSubmitOrder(ix.data)) continue;
1412
+ submits++;
1413
+ verifySolanaSubmit(decodeSolanaSubmitOrder(ix.data), expected);
1414
+ if (keys[ix.accounts[1]] !== expected.mint) throw new Error("Wrong source mint; refusing to sign.");
1415
+ buffer = keys[ix.accounts[8]] ?? null;
1416
+ if (!buffer) throw new Error("Missing route buffer; refusing to sign.");
1417
+ }
1418
+ if (submits !== (mustSubmit ? 1 : 0)) throw new Error("Expected exactly one submit_order in submit and none in preparation; refusing to sign.");
1419
+ return buffer;
1420
+ }
1421
+ function parseAddressLookupTable(data) {
1422
+ if (data.length < 56 || (data.length - 56) % 32 || new DataView(data.buffer, data.byteOffset, 4).getUint32(0, true) !== 1) throw new Error("Invalid address lookup table.");
1423
+ return Array.from({ length: (data.length - 56) / 32 }, (_, i) => base58Encode(data.subarray(56 + 32 * i, 88 + 32 * i)));
1424
+ }
1425
+ async function resolveSolanaKeys(tx, rpc) {
1426
+ if (!tx.lookups.length) return [...tx.staticKeys];
1427
+ const result = await rpc("getMultipleAccounts", [tx.lookups.map((l) => l.address), { encoding: "base64", commitment: "confirmed" }]);
1428
+ if (!Array.isArray(result.value) || result.value.length !== tx.lookups.length) throw new Error("Missing lookup tables.");
1429
+ const writable = [], readonly = [];
1430
+ tx.lookups.forEach((lookup, i) => {
1431
+ const account = result.value[i];
1432
+ if (account?.owner !== "AddressLookupTab1e1111111111111111111111111" || account.data[1] !== "base64") throw new Error("Invalid lookup table account.");
1433
+ const table = parseAddressLookupTable(base64Decode(account.data[0]));
1434
+ for (const [indexes, into] of [[lookup.writable, writable], [lookup.readonly, readonly]]) for (const index of indexes) {
1435
+ if (!table[index]) throw new Error("Lookup table index out of range.");
1436
+ into.push(table[index]);
1437
+ }
1438
+ });
1439
+ return [...tx.staticKeys, ...writable, ...readonly];
1440
+ }
1441
+ function encodeNextSolanaOrders(legs) {
1442
+ return legs.length ? hexBytes(`0x${uintWord(32)}${encodeSubmitOrder(legs).slice(10 + 128)}`) : new Uint8Array();
1443
+ }
1444
+ function checkSolanaRouteBuffer(account, expected) {
1445
+ if (!account || account.owner !== expected.program || account.data[1] !== "base64") throw new Error("Route buffer is not a ZeroDelta account.");
1446
+ const d = base64Decode(account.data[0]);
1447
+ if (d.length < 53) throw new Error("Route buffer truncated.");
1448
+ if (base58Encode(d.subarray(9, 41)) !== expected.signer) throw new Error("Route buffer signer mismatch.");
1449
+ const len = new DataView(d.buffer, d.byteOffset + 49, 4).getUint32(0, true);
1450
+ if (d.length < 53 + len || !bytesEqual(d.subarray(53, 53 + len), encodeNextSolanaOrders(expected.nextOrders))) throw new Error("Route buffer legs mismatch.");
1451
+ }
1452
+ function checkSolanaProgram(gateway, pinned, registry2) {
1453
+ const program = gateway || registry2 || "";
1454
+ solanaKeyBytes(program);
1455
+ if (pinned ? program !== pinned : gateway && registry2 && gateway !== registry2) throw new Error("Solana program does not match pin or chains registry.");
1456
+ return program;
1457
+ }
1458
+ function checkSolanaPlan(txs) {
1459
+ if (!Array.isArray(txs) || !txs.length || txs.length > 64 || txs.some((tx) => !["setup", "buffer", "write", "submit"].includes(tx.actionType) || typeof tx.transaction !== "string") || txs.filter((tx) => tx.actionType === "submit").length !== 1 || txs[txs.length - 1].actionType !== "submit" || txs.some((tx) => tx.buildData && tx.actionType !== "submit")) throw new Error("Plan must end in exactly one submit; buildData is only allowed on it.");
1460
+ }
1461
+ async function deriveSolanaEvent(signer, salt) {
1462
+ const s = hexBytes(salt), material = new Uint8Array(32 + s.length);
1463
+ material.set(solanaKeyBytes(signer));
1464
+ material.set(s, 32);
1465
+ const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", material));
1466
+ const { eventPublicKey: eventPublicKey2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
1467
+ return { seed, publicKey: base58Encode(await eventPublicKey2(seed)) };
1468
+ }
1469
+ async function cosignSolanaEvent(bytes, signer, build) {
1470
+ const event = await deriveSolanaEvent(signer, build.salt);
1471
+ if (event.publicKey !== build.messageSentEventData) throw new Error("Event buildData key mismatch; refusing to sign.");
1472
+ const tx = parseSolanaTransaction(bytes);
1473
+ const { eventSignature: eventSignature2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
1474
+ return placeSignature(bytes, event.publicKey, await eventSignature2(tx.bytes.subarray(tx.messageOffset), event.seed));
1475
+ }
1476
+ async function pollSolanaConfirmation(rpc, signature) {
1477
+ const deadline = Date.now() + 9e4;
1478
+ while (Date.now() < deadline) {
1479
+ const { value } = await rpc("getSignatureStatuses", [[signature]]);
1480
+ const status = value?.[0];
1481
+ if (status?.err) throw new Error(`Transaction failed on chain: ${JSON.stringify(status.err)}`);
1482
+ if (["confirmed", "finalized"].includes(status?.confirmationStatus)) return;
1483
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
1484
+ }
1485
+ throw new Error("Transaction confirmation timed out; check the signature before retrying.");
470
1486
  }
471
- function requiresNativeBridgeFee(quote, option = {}) {
472
- const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
473
- const execChainId = Number(quote?.executionChainId);
474
- if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
475
- return false;
1487
+
1488
+ // src/core/units.ts
1489
+ function assetDecimals(token) {
1490
+ const sym = symbolKey(token?.symbol);
1491
+ const registry2 = Number(token?.decimals);
1492
+ const canonical = isSolanaChainId(token?.chainId) ? solanaDestinationAsset(token?.address)?.decimals : CANONICAL_DECIMALS[sym];
1493
+ if (canonical !== void 0) {
1494
+ if (!Number.isInteger(registry2)) {
1495
+ throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
1496
+ }
1497
+ if (registry2 !== canonical) {
1498
+ throw new Error(`ZeroDelta token registry reported ${registry2} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
1499
+ }
1500
+ return canonical;
476
1501
  }
477
- const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
478
- if (canonical) return canonical === "layerzero";
479
- return isLayerZeroRoute(quote, option);
1502
+ if (!Number.isInteger(registry2) || registry2 < 0 || registry2 > 36) {
1503
+ throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
1504
+ }
1505
+ return registry2;
480
1506
  }
481
- function applyLayerZeroBuffer(quote, option = {}) {
482
- const gas = BigInt(quote?.gasCostSource || "0");
483
- if (gas <= 0n) return 0n;
484
- if (!requiresNativeBridgeFee(quote, option)) return 0n;
485
- return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
1507
+ function normalizeDecimalText(value) {
1508
+ const text = String(value || "").trim().replace(/\s+/g, "");
1509
+ if (!text) return "";
1510
+ if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
1511
+ if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
1512
+ if (text.includes(",")) return "";
1513
+ return text;
1514
+ }
1515
+ function parseUnitsDecimal(amount, decimals) {
1516
+ const text = normalizeDecimalText(amount);
1517
+ if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
1518
+ const [whole, frac = ""] = text.split(".");
1519
+ if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
1520
+ const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
1521
+ const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
1522
+ if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
1523
+ return value;
1524
+ }
1525
+ function scaleDecimals(amount, fromDecimals, toDecimals) {
1526
+ if (toDecimals === fromDecimals) return amount;
1527
+ if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
1528
+ return amount / 10n ** BigInt(fromDecimals - toDecimals);
1529
+ }
1530
+ function formatUnits(raw2, decimals, maxDecimals = 6) {
1531
+ const value = BigInt(raw2 || "0");
1532
+ const base = 10n ** BigInt(decimals);
1533
+ const whole = value / base;
1534
+ const fracFull = (value % base).toString().padStart(decimals, "0");
1535
+ const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
1536
+ return frac ? `${whole}.${frac}` : whole.toString();
1537
+ }
1538
+ function finalOf(quote) {
1539
+ return BigInt(quote?.finalAmount || quote?.toAmount || "0");
1540
+ }
1541
+
1542
+ // src/core/ask-scale.ts
1543
+ function askTokenDecimals(quote, tokens, _from, to) {
1544
+ const requests = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
1545
+ const execution = Number(requests[requests.length - 1]?.executionChainId || quote.executionChainId);
1546
+ if (!Number.isSafeInteger(execution) || execution <= 0) throw new Error("Could not verify the quote amount precision.");
1547
+ if (execution === Number(to.chainId)) return assetDecimals(to);
1548
+ const row = tokens.find((token) => Number(token.chainId) === execution && symbolKey(token.symbol) === symbolKey(to.symbol));
1549
+ if (row) return assetDecimals(row);
1550
+ if (isSolanaChainId(to.chainId)) throw new Error("Could not verify the quote amount precision.");
1551
+ return assetDecimals(to);
1552
+ }
1553
+ function askCovers(ask, final, askDecimals, finalDecimals) {
1554
+ if (![askDecimals, finalDecimals].every((n) => Number.isInteger(n) && n >= 0 && n <= 36)) throw new Error("Could not verify the quote amount precision.");
1555
+ const shift = askDecimals - finalDecimals;
1556
+ return shift >= 0 ? ask >= final * 10n ** BigInt(shift) : ask * 10n ** BigInt(-shift) >= final;
486
1557
  }
487
1558
 
488
1559
  // src/core/ticker.ts
@@ -523,7 +1594,7 @@ function counterpartTokens(tokens, selected) {
523
1594
  return tokens.filter((token) => assetClassOf(token.symbol) === want);
524
1595
  }
525
1596
  function tokenKey(chainId, address) {
526
- return `${Number(chainId)}:${String(address || "").toLowerCase()}`;
1597
+ return `${Number(chainId)}:${chainAddressKey(chainId, address)}`;
527
1598
  }
528
1599
  function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
529
1600
  return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
@@ -559,35 +1630,35 @@ function isSourceToken(token, ctx) {
559
1630
  if (!ctx.sourceChains.has(chainId)) return false;
560
1631
  return ctx.execution.has(chainId) || !isKnownUnbridgeable(token.bridge) && ctx.source.has(tokenKey(chainId, token.address));
561
1632
  }
562
- function directLaneOK(token, source, lanes) {
563
- if (!source || !lanes) return true;
564
- if (symbolKey(source.symbol) !== symbolKey(token.symbol)) return true;
565
- if (Number(source.chainId) === Number(token.chainId)) return true;
566
- return lanes.has(laneKey(source.chainId, source.address, token.chainId, token.address));
1633
+ function directLaneOK(token, source2, lanes) {
1634
+ if (!source2 || !lanes) return true;
1635
+ if (symbolKey(source2.symbol) !== symbolKey(token.symbol)) return true;
1636
+ if (Number(source2.chainId) === Number(token.chainId)) return true;
1637
+ return lanes.has(laneKey(source2.chainId, source2.address, token.chainId, token.address));
567
1638
  }
568
- function brokenLaneFor(token, source, brokenLanes) {
569
- if (!source || !brokenLanes) return void 0;
570
- return brokenLanes.get(laneKey(source.chainId, source.address, token.chainId, token.address));
1639
+ function brokenLaneFor(token, source2, brokenLanes) {
1640
+ if (!source2 || !brokenLanes) return void 0;
1641
+ return brokenLanes.get(laneKey(source2.chainId, source2.address, token.chainId, token.address));
571
1642
  }
572
- function laneLimitFor(token, source, limitedLanes2) {
573
- if (!source || !limitedLanes2) return void 0;
574
- return limitedLanes2.get(laneKey(source.chainId, source.address, token.chainId, token.address));
1643
+ function laneLimitFor(token, source2, limitedLanes2) {
1644
+ if (!source2 || !limitedLanes2) return void 0;
1645
+ return limitedLanes2.get(laneKey(source2.chainId, source2.address, token.chainId, token.address));
575
1646
  }
576
- function destinationAvailability(token, ctx, source) {
577
- if (brokenLaneFor(token, source ?? void 0, ctx.brokenLanes)) return "unreachable";
578
- if (directLaneOK(token, source ?? void 0, ctx.lanes)) {
1647
+ function destinationAvailability(token, ctx, source2) {
1648
+ if (brokenLaneFor(token, source2 ?? void 0, ctx.brokenLanes)) return "unreachable";
1649
+ if (directLaneOK(token, source2 ?? void 0, ctx.lanes)) {
579
1650
  if (ctx.execution.has(Number(token.chainId))) return "available";
580
1651
  if (token.isChainedDestination === true) return "available";
581
1652
  if (!isKnownUnbridgeable(token.bridge) && ctx.destination.has(tokenKey(token.chainId, token.address))) return "available";
582
1653
  }
583
1654
  return ctx.hubSymbols.has(symbolKey(token.symbol)) ? "hub-only" : "unreachable";
584
1655
  }
585
- function hasReachableDestination(source, catalogue, ctx) {
1656
+ function hasReachableDestination(source2, catalogue, ctx) {
586
1657
  if (catalogue.length === 0) return true;
587
- const from = tokenKey(source.chainId, source.address);
1658
+ const from = tokenKey(source2.chainId, source2.address);
588
1659
  for (const candidate of catalogue) {
589
1660
  if (tokenKey(candidate.chainId, candidate.address) === from) continue;
590
- if (destinationAvailability(candidate, ctx, source) === "available") return true;
1661
+ if (destinationAvailability(candidate, ctx, source2) === "available") return true;
591
1662
  }
592
1663
  return false;
593
1664
  }
@@ -601,7 +1672,7 @@ function buildCatalogue(input) {
601
1672
  const sourceChains = new Set([...registryChainIds].filter((id) => supportedChainIds.has(id)));
602
1673
  const execution = executionChainIds(enabledChains);
603
1674
  const projected = product === "rwa" ? routes.filter((route) => route.isEnabled !== false) : executableRoutes(routes);
604
- const source = sourceKeys(projected);
1675
+ const source2 = sourceKeys(projected);
605
1676
  const destination = destinationKeys(projected);
606
1677
  const lanes = laneKeys(projected);
607
1678
  const chainIds = new Set(sourceChains);
@@ -609,19 +1680,19 @@ function buildCatalogue(input) {
609
1680
  const id = Number(route.toChainId);
610
1681
  if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
611
1682
  }
612
- const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
1683
+ const allowed = tokens.filter((token) => token.isEnabled !== false && isChainAddress(token.chainId, token.address) && allowedAssets.has(symbolKey(token.symbol)));
613
1684
  const projectedCatalogue = allowed.filter((token) => {
614
1685
  if (!chainIds.has(Number(token.chainId))) return false;
615
1686
  if (product === "rwa") return true;
616
1687
  if (!isExecutableBridge(token)) return false;
617
1688
  const key = tokenKey(token.chainId, token.address);
618
- return source.has(key) || destination.has(key) || execution.has(Number(token.chainId));
1689
+ return source2.has(key) || destination.has(key) || execution.has(Number(token.chainId));
619
1690
  });
620
1691
  const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
621
1692
  const catalogue = ready ? projectedCatalogue : allowed;
622
1693
  const hubSymbols = hubDeliverableSymbols(catalogue, execution);
623
- const ctx = { source, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
624
- const sources = ready ? catalogue.filter((token) => isSourceToken(token, ctx) && hasReachableDestination(token, catalogue, ctx)) : (
1694
+ const ctx = { source: source2, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
1695
+ const sources2 = ready ? catalogue.filter((token) => isSourceToken(token, ctx) && hasReachableDestination(token, catalogue, ctx)) : (
625
1696
  // Unprojected: the only rule we can still apply with confidence is the escrow-chain bound,
626
1697
  // which comes from this build's own pins rather than from the registry.
627
1698
  catalogue.filter((token) => sourceChains.has(Number(token.chainId)))
@@ -632,7 +1703,7 @@ function buildCatalogue(input) {
632
1703
  ...ctx,
633
1704
  product,
634
1705
  tokens: catalogue,
635
- sources,
1706
+ sources: sources2,
636
1707
  chainIds,
637
1708
  chains: [...byId.values()],
638
1709
  ready,
@@ -643,19 +1714,19 @@ function buildCatalogue(input) {
643
1714
 
644
1715
  // src/core/options.ts
645
1716
  function chainNameOf(chainId, chains) {
646
- const chain = chains.find((item) => Number(item.chainId) === Number(chainId));
647
- return chain?.displayName || chain?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
1717
+ const chain2 = chains.find((item) => Number(item.chainId) === Number(chainId));
1718
+ return chain2?.displayName || chain2?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
648
1719
  }
649
1720
  function chainById(chains, chainId) {
650
- return chains.find((chain) => Number(chain.chainId) === Number(chainId)) || null;
1721
+ return chains.find((chain2) => Number(chain2.chainId) === Number(chainId)) || null;
651
1722
  }
652
- function chainSelectable(chain, chainId) {
1723
+ function chainSelectable(chain2, chainId) {
653
1724
  if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
654
- if (!chain) return true;
655
- return chain.isEnabled !== false;
1725
+ if (!chain2) return true;
1726
+ return chain2.isEnabled !== false;
656
1727
  }
657
1728
  function tokenEnabled(token) {
658
- return token?.isEnabled !== false && isAddress(token?.address) && Number.isFinite(Number(token?.chainId));
1729
+ return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
659
1730
  }
660
1731
  function findToken(tokens, chainId, symbol) {
661
1732
  const key = symbolKey(symbol);
@@ -691,8 +1762,8 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
691
1762
  for (const token of universe) {
692
1763
  if (!tokenEnabled(token)) continue;
693
1764
  const chainId = Number(token.chainId);
694
- const chain = chainById(chains, chainId);
695
- if (!chainSelectable(chain, chainId)) continue;
1765
+ const chain2 = chainById(chains, chainId);
1766
+ if (!chainSelectable(chain2, chainId)) continue;
696
1767
  const key = tokenKey(chainId, token.address);
697
1768
  if (seen.has(key)) continue;
698
1769
  if (refusal(token)) continue;
@@ -714,38 +1785,503 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
714
1785
  direct
715
1786
  });
716
1787
  }
717
- options.sort((a, b) => {
718
- const walletChain = Number(walletChainId || 0);
719
- if (walletChain) {
720
- if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
721
- if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
722
- }
723
- if (a.direct !== b.direct) return a.direct ? -1 : 1;
724
- if (a.symbolKey !== b.symbolKey) {
725
- if (a.symbolKey === invoiceKey) return -1;
726
- if (b.symbolKey === invoiceKey) return 1;
727
- return a.symbolKey.localeCompare(b.symbolKey);
1788
+ options.sort((a, b) => {
1789
+ const walletChain = Number(walletChainId || 0);
1790
+ if (walletChain) {
1791
+ if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
1792
+ if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
1793
+ }
1794
+ if (a.direct !== b.direct) return a.direct ? -1 : 1;
1795
+ if (a.symbolKey !== b.symbolKey) {
1796
+ if (a.symbolKey === invoiceKey) return -1;
1797
+ if (b.symbolKey === invoiceKey) return 1;
1798
+ return a.symbolKey.localeCompare(b.symbolKey);
1799
+ }
1800
+ if (a.sameChain !== b.sameChain) return a.sameChain ? -1 : 1;
1801
+ return a.chainId - b.chainId;
1802
+ });
1803
+ return options;
1804
+ }
1805
+
1806
+ // src/core/solana-source.ts
1807
+ var CANONICAL_SOLANA_PROGRAM = "zd1E5feCJLNYaPPsBAYkCPMKGVnipYf8God9h917W33";
1808
+ var MAX_ASK_OVER_FINAL_BPS = 200n;
1809
+ var states = /* @__PURE__ */ new WeakMap();
1810
+ var quoteRequests = /* @__PURE__ */ new WeakMap();
1811
+ var inFlight = /* @__PURE__ */ new Map();
1812
+ var activeSigners = /* @__PURE__ */ new Set();
1813
+ var clone = (value) => JSON.parse(JSON.stringify(value));
1814
+ function freeze(value) {
1815
+ if (value && typeof value === "object") {
1816
+ for (const v of Object.values(value)) freeze(v);
1817
+ Object.freeze(value);
1818
+ }
1819
+ return value;
1820
+ }
1821
+ function raw(value, label, positive = false) {
1822
+ if (typeof value !== "string" || !/^\d+$/.test(value) || positive && BigInt(value) <= 0n || BigInt(value) >= 1n << 256n) throw new Error(`Invalid ${label}.`);
1823
+ return value;
1824
+ }
1825
+ function chain(value) {
1826
+ const text = String(value);
1827
+ if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) >= 1n << 64n) throw new Error("Invalid order chain.");
1828
+ return text;
1829
+ }
1830
+ function same(a, b) {
1831
+ return a.toLowerCase() === b.toLowerCase();
1832
+ }
1833
+ function recipient(input) {
1834
+ const to = input.recipient || (isSolanaChainId(input.toChainId) ? input.sender : input.owner);
1835
+ if (!isChainAddress(input.toChainId, to)) throw new Error("Invalid destination recipient.");
1836
+ return chainAddressKey(input.toChainId, to);
1837
+ }
1838
+ function validateInput(input) {
1839
+ if (input.fromChainId !== void 0 && input.fromChainId !== SOLANA_CHAIN_ID) throw new Error("Solana source chain required.");
1840
+ if (!Number.isSafeInteger(input.toChainId) || input.toChainId <= 0) throw new Error("Invalid destination chain.");
1841
+ if (!SUPPORTED_ASSETS.has(symbolKey(input.fromToken)) || !SUPPORTED_ASSETS.has(symbolKey(input.toToken))) throw new Error("Unsupported Solana source asset.");
1842
+ assertAddress(input.owner, "EVM order owner");
1843
+ solanaKeyBytes(input.sender);
1844
+ recipient(input);
1845
+ const span = input.deadlineSpanSeconds ?? 7200, slip = input.slippageBps ?? 0;
1846
+ if (!Number.isInteger(span) || span < 1 || span > 86400) throw new Error("Invalid Solana deadline span.");
1847
+ if (!Number.isInteger(slip) || slip < 0 || slip > 1e4) throw new Error("Invalid slippage tolerance.");
1848
+ }
1849
+ function selections(input, tokens) {
1850
+ validateInput(input);
1851
+ const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
1852
+ if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
1853
+ solanaKeyBytes(from.address);
1854
+ assertPinnedSolanaSource(from);
1855
+ if (!isChainAddress(input.toChainId, to.address)) throw new Error("Invalid destination token.");
1856
+ const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
1857
+ raw(amount, "input amount", true);
1858
+ if (BigInt(amount) >= 1n << 64n) throw new Error("Solana bid exceeds u64.");
1859
+ return { from, to, amount };
1860
+ }
1861
+ function assertPinnedSolanaSource(token) {
1862
+ const pinned = solanaDestinationAsset(token.address);
1863
+ if (!pinned || pinned.symbol !== symbolKey(token.symbol) || pinned.decimals !== Number(token.decimals)) {
1864
+ throw new Error("This Solana token is not supported for payment; refusing to sign.");
1865
+ }
1866
+ }
1867
+ function makeRequest(input, from, to, amount) {
1868
+ return {
1869
+ inputChain: SOLANA_CHAIN_ID,
1870
+ outputChain: input.toChainId,
1871
+ inputToken: from.symbol,
1872
+ outputToken: to.symbol,
1873
+ inputAmount: amount,
1874
+ owners: { evm: input.owner },
1875
+ destinationWallet: recipient(input),
1876
+ sender: input.sender,
1877
+ deadline: String(Math.floor(Date.now() / 1e3) + (input.deadlineSpanSeconds ?? 7200))
1878
+ };
1879
+ }
1880
+ function normalizePreview(request, quote, to, amount) {
1881
+ const option = quote?.options?.[0];
1882
+ if (!option) throw new Error("Native quote returned no options.");
1883
+ const receive = raw(option.finalAmount, "quoted output", true);
1884
+ return {
1885
+ receive: formatUnits(receive, assetDecimals(to)),
1886
+ receiveRaw: receive,
1887
+ fromAmount: amount,
1888
+ fromToken: request.inputToken,
1889
+ toToken: request.outputToken,
1890
+ bridge: option.bridge || "",
1891
+ feeBps: Number(option.feeBps || 0),
1892
+ estimatedDuration: Number(option.estimatedTimeSec || 0),
1893
+ via: null,
1894
+ nativeFeeRaw: String(option.gasCostSource || "0"),
1895
+ quote,
1896
+ option,
1897
+ txData: option.txData,
1898
+ request
1899
+ };
1900
+ }
1901
+ async function quoteSolanaSource(api, input) {
1902
+ const { from, to, amount } = selections(input, await api.fetchTokens());
1903
+ const request = makeRequest(input, from, to, amount);
1904
+ const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1905
+ const preview = normalizePreview(request, quote, to, input.amountIn);
1906
+ quoteRequests.set(preview, { api, request: clone(request) });
1907
+ return preview;
1908
+ }
1909
+ async function previewSolanaSource(api, input) {
1910
+ const tokens = await api.fetchTokens();
1911
+ const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
1912
+ if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
1913
+ assertPinnedSolanaSource(from);
1914
+ const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
1915
+ raw(amount, "input amount", true);
1916
+ const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
1917
+ const request = body;
1918
+ const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1919
+ const option = quote?.options?.[0];
1920
+ if (!option) throw new Error("Native quote returned no options.");
1921
+ const receive = raw(option.finalAmount, "quoted output", true);
1922
+ return {
1923
+ receive: formatUnits(receive, assetDecimals(to)),
1924
+ receiveRaw: receive,
1925
+ fromAmount: input.amountIn,
1926
+ fromToken: request.inputToken,
1927
+ toToken: request.outputToken,
1928
+ bridge: option.bridge || "",
1929
+ feeBps: Number(option.feeBps || 0),
1930
+ estimatedDuration: Number(option.estimatedTimeSec || 0),
1931
+ via: null,
1932
+ nativeFeeRaw: "0"
1933
+ };
1934
+ }
1935
+ function denied(value) {
1936
+ return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
1937
+ }
1938
+ async function checkActiveScreens(api, input) {
1939
+ const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
1940
+ const screens = await Promise.all(addresses.map(async (address) => {
1941
+ try {
1942
+ return await api.screenWallet(address);
1943
+ } catch {
1944
+ return void 0;
1945
+ }
1946
+ }));
1947
+ if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
1948
+ }
1949
+ function jsonGuards(input, preview, tokens, chains) {
1950
+ const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
1951
+ const wanted = makeRequest(input, from, to, amount);
1952
+ for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
1953
+ if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
1954
+ }
1955
+ if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
1956
+ const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
1957
+ if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
1958
+ if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
1959
+ if (denied(preview.quote.compliance) || denied(preview.quote.complianceDecision) || denied(preview.quote.complianceStatus) || denied(option.compliance) || denied(option.complianceDecision)) throw new Error("Compliance DENY; refusing to sign.");
1960
+ if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
1961
+ if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
1962
+ if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
1963
+ if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
1964
+ checkSolanaPlan(option.txData);
1965
+ const orders = option.orderRequests;
1966
+ if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
1967
+ const first = orders[0], last = orders[orders.length - 1];
1968
+ if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
1969
+ if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
1970
+ const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
1971
+ if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
1972
+ if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
1973
+ for (let i = 0; i < orders.length; i++) {
1974
+ const order = orders[i];
1975
+ if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
1976
+ raw(order.askTokenAmount, "ask amount", true);
1977
+ raw(order.bidTokenAmount, "bid amount", true);
1978
+ chain(order.destinationChainId);
1979
+ chain(order.executionChainId);
1980
+ if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
1981
+ if (isSolanaChainId(order.destinationChainId)) {
1982
+ if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
1983
+ solanaBridgeOf(to);
1984
+ checkSolanaReceiver(order, recipient(input), to.address);
1985
+ } else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
1986
+ if (i === 0 ? String(order.deadline) !== request.deadline : String(order.deadline) !== "0" && String(order.deadline) !== request.deadline) throw new Error("Order deadline differs from requested deadline.");
1987
+ if (i) {
1988
+ const previous = orders[i - 1];
1989
+ if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
1990
+ if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
1991
+ }
1992
+ }
1993
+ const quoteForScale = { ...option, orderRequests: orders };
1994
+ const execution = Number(last.executionChainId);
1995
+ if (execution !== Number(to.chainId) && !tokens.some((t) => Number(t.chainId) === execution && symbolKey(t.symbol) === symbolKey(to.symbol))) throw new Error("Cannot resolve ask amount precision.");
1996
+ const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
1997
+ const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
1998
+ const minFinal = final * (10000n - slip) / 10000n;
1999
+ if (!askCovers(BigInt(last.askTokenAmount), minFinal, askScale, finalScale) || !askCovers(BigInt(last.askTokenAmount), BigInt(raw(input.minReceiveRaw ?? minFinal.toString(), "minimum output")), askScale, finalScale)) throw new Error("Ask below receive floor.");
2000
+ if (!askCovers(BigInt(final) * (10000n + MAX_ASK_OVER_FINAL_BPS), BigInt(last.askTokenAmount) * 10000n, finalScale, askScale)) throw new Error("Ask far above the displayed receive amount; refusing to sign.");
2001
+ const registry2 = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
2002
+ const contracts = registry2?.contracts;
2003
+ const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry2?.escrowContract);
2004
+ const marker = option.partnerId ?? preview.quote.partnerId;
2005
+ if (marker !== void 0 && marker !== null && !/^0x[0-9a-fA-F]{64}$/.test(String(marker))) throw new Error("Invalid partner marker; re-quote with both wallets.");
2006
+ const ask = BigInt(first.askTokenAmount);
2007
+ return {
2008
+ program,
2009
+ signer: input.sender,
2010
+ mint: from.address,
2011
+ owner: input.owner,
2012
+ askToken: first.askToken,
2013
+ minAskTokenAmount: ask.toString(),
2014
+ maxAskTokenAmount: ask.toString(),
2015
+ bidTokenAmount: amount,
2016
+ destinationReceiver: first.destinationReceiver,
2017
+ destinationChainId: String(first.destinationChainId),
2018
+ executionChainId: String(first.executionChainId),
2019
+ deadline: request.deadline,
2020
+ partnerId: marker == null ? null : String(marker),
2021
+ nextOrders: orders.slice(1)
2022
+ };
2023
+ }
2024
+ async function buildSolanaSourcePlan(api, input, quoted) {
2025
+ const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
2026
+ const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
2027
+ if (!original || original.api !== api || JSON.stringify(original.request) !== JSON.stringify(served.request)) throw new Error("Quote request provenance changed; fetch a fresh native quote.");
2028
+ const preview = clone(served);
2029
+ const expected = jsonGuards(input, preview, tokens, chains);
2030
+ await checkActiveScreens(api, input);
2031
+ const plan = freeze({ preview, expected, txData: preview.option.txData });
2032
+ const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
2033
+ states.set(plan, {
2034
+ api,
2035
+ input: clone(input),
2036
+ plan,
2037
+ failed: false,
2038
+ busy: false,
2039
+ originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
2040
+ signatures: [],
2041
+ done: 0
2042
+ });
2043
+ return plan;
2044
+ }
2045
+ function createSolanaRpc(api) {
2046
+ return async (method, params) => {
2047
+ const body = await api.apiRequest("/solana-rpc", {
2048
+ method: "POST",
2049
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
2050
+ timeoutMs: 15e3
2051
+ });
2052
+ if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
2053
+ return body.result;
2054
+ };
2055
+ }
2056
+ var SolanaSendError = class extends Error {
2057
+ constructor(message, signature, sentAt) {
2058
+ super(message);
2059
+ this.signature = signature;
2060
+ this.sentAt = sentAt;
2061
+ this.name = "SolanaSendError";
2062
+ }
2063
+ signature;
2064
+ sentAt;
2065
+ };
2066
+ async function executeSolanaPlan(input) {
2067
+ const signature = await runSolanaPlan(input, false);
2068
+ if (!signature) throw new Error("Missing final Solana submit.");
2069
+ return signature;
2070
+ }
2071
+ async function executeSolanaPlanStaged(input) {
2072
+ const signature = await runSolanaPlan(input, true);
2073
+ return signature ? { status: "sent", signature } : { status: "prepared" };
2074
+ }
2075
+ function solanaPlanNeedsPreparation(plan) {
2076
+ const state = states.get(plan);
2077
+ const live = state?.plan ?? plan;
2078
+ return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
2079
+ }
2080
+ async function runSolanaPlan(input, stopBeforeSubmit) {
2081
+ const state = states.get(input.plan);
2082
+ if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
2083
+ if (state.sent) return state.sent;
2084
+ if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
2085
+ if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
2086
+ state.busy = true;
2087
+ activeSigners.add(input.signer.publicKey);
2088
+ let index = 0, completedBeforeRun = state.signatures.length;
2089
+ const progress = (stage) => {
2090
+ const pending = inFlight.get(input.signer.publicKey);
2091
+ try {
2092
+ input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
2093
+ } catch {
2094
+ }
2095
+ };
2096
+ try {
2097
+ progress("preparing");
2098
+ const pending = inFlight.get(input.signer.publicKey);
2099
+ if (pending) {
2100
+ const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
2101
+ const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
2102
+ if (status?.err) inFlight.delete(input.signer.publicKey);
2103
+ else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
2104
+ inFlight.delete(input.signer.publicKey);
2105
+ if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
2106
+ if (pending.final) {
2107
+ pending.state.sent = pending.signature;
2108
+ reportSolana(pending.state, pending.signature);
2109
+ if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
2110
+ progress("sent");
2111
+ return pending.signature;
2112
+ }
2113
+ } else {
2114
+ if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
2115
+ throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
2116
+ }
2117
+ inFlight.delete(input.signer.publicKey);
2118
+ }
2119
+ }
2120
+ if (state.failed) {
2121
+ const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
2122
+ if (!same(retried.expected.askToken, state.plan.expected.askToken) || retried.expected.executionChainId !== state.plan.expected.executionChainId || retried.expected.destinationChainId !== state.plan.expected.destinationChainId) throw new Error("Retry changed connector route; request a new order.");
2123
+ state.plan = retried;
2124
+ state.done = 0;
2125
+ state.failed = false;
2126
+ }
2127
+ const plan = state.plan;
2128
+ checkSolanaPlan(plan.txData);
2129
+ for (const tx of plan.txData) {
2130
+ const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
2131
+ verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
2132
+ }
2133
+ for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
2134
+ completedBeforeRun = state.signatures.length;
2135
+ const startAt = state.done;
2136
+ for (index = startAt; index < plan.txData.length; index++) {
2137
+ if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
2138
+ progress("ready");
2139
+ return null;
2140
+ }
2141
+ if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
2142
+ await checkActiveScreens(state.api, state.input);
2143
+ const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
2144
+ const keys = await resolveSolanaKeys(parsed, input.rpc);
2145
+ const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
2146
+ if (buffer) {
2147
+ const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
2148
+ checkSolanaRouteBuffer(account.value, plan.expected);
2149
+ }
2150
+ const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
2151
+ let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
2152
+ if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
2153
+ verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
2154
+ progress("signing");
2155
+ const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
2156
+ assertWalletMessage(bytes, signed);
2157
+ verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
2158
+ const signedTx = parseSolanaTransaction(signed);
2159
+ const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
2160
+ const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
2161
+ inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
2162
+ progress("sending");
2163
+ try {
2164
+ const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
2165
+ if (returned !== signature) throw new Error("RPC returned a different signature.");
2166
+ if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
2167
+ } catch (error) {
2168
+ throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
2169
+ }
2170
+ inFlight.delete(input.signer.publicKey);
2171
+ state.signatures.push(signature);
2172
+ state.done = index + 1;
2173
+ if (tx.actionType === "submit") {
2174
+ state.sent = signature;
2175
+ reportSolana(state, signature);
2176
+ progress("sent");
2177
+ return signature;
2178
+ }
2179
+ progress("ready");
2180
+ }
2181
+ throw new Error("Missing final Solana submit.");
2182
+ } catch (error) {
2183
+ state.failed = true;
2184
+ progress("failed");
2185
+ throw error;
2186
+ } finally {
2187
+ state.busy = false;
2188
+ activeSigners.delete(input.signer.publicKey);
2189
+ }
2190
+ }
2191
+ function reportSolana(state, signature) {
2192
+ try {
2193
+ void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
2194
+ });
2195
+ } catch {
2196
+ }
2197
+ }
2198
+ async function readSolanaBalance(rpc, owner, mint) {
2199
+ try {
2200
+ solanaKeyBytes(owner);
2201
+ solanaKeyBytes(mint);
2202
+ const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
2203
+ if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
2204
+ let total = 0n, decimals;
2205
+ for (const item of result.value) {
2206
+ const amount = item.account?.data?.parsed?.info?.tokenAmount;
2207
+ if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
2208
+ decimals = amount.decimals;
2209
+ total += BigInt(raw(amount.amount, "token balance"));
728
2210
  }
729
- if (a.sameChain !== b.sameChain) return a.sameChain ? -1 : 1;
730
- return a.chainId - b.chainId;
731
- });
732
- return options;
2211
+ return total;
2212
+ } catch {
2213
+ return void 0;
2214
+ }
2215
+ }
2216
+ async function simulateSolanaCost(rpc, plan) {
2217
+ checkSolanaPlan(plan.txData);
2218
+ const signer = plan.expected.signer;
2219
+ const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
2220
+ const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
2221
+ if (sim.value?.err) throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
2222
+ const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
2223
+ if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
2224
+ const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
2225
+ return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
2226
+ }
2227
+
2228
+ // src/core/escrow.ts
2229
+ function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
2230
+ const fromQuote = normalizeAddress(quoteEscrow);
2231
+ const fromChains = normalizeAddress(chainsEscrow);
2232
+ if (!fromChains || fromChains === ZERO_ADDRESS) {
2233
+ throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
2234
+ }
2235
+ if (!fromQuote || fromQuote === ZERO_ADDRESS) {
2236
+ throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
2237
+ }
2238
+ if (fromQuote !== fromChains) {
2239
+ throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
2240
+ }
2241
+ const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
2242
+ if (pinned && pinned !== fromChains) {
2243
+ throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
2244
+ }
2245
+ return fromChains;
2246
+ }
2247
+ function isLayerZeroRoute(quote, option = {}) {
2248
+ const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
2249
+ return bridge.includes("layerzero") || bridge.includes("layer zero");
2250
+ }
2251
+ function sourceAssetKey(quote, option = {}) {
2252
+ return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
2253
+ }
2254
+ function requiresNativeBridgeFee(quote, option = {}) {
2255
+ const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
2256
+ const execChainId = Number(quote?.executionChainId);
2257
+ if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
2258
+ return false;
2259
+ }
2260
+ const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
2261
+ if (canonical) return canonical === "layerzero";
2262
+ return isLayerZeroRoute(quote, option);
2263
+ }
2264
+ function applyLayerZeroBuffer(quote, option = {}) {
2265
+ const gas = BigInt(quote?.gasCostSource || "0");
2266
+ if (gas <= 0n) return 0n;
2267
+ if (!requiresNativeBridgeFee(quote, option)) return 0n;
2268
+ return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
733
2269
  }
734
2270
 
735
2271
  // src/core/native-fee.ts
736
2272
  function routeNativeValue(route) {
737
2273
  try {
738
- const raw = route?.quote?.msgValue;
739
- if (raw === void 0 || raw === null || raw === "") return 0n;
740
- const value = BigInt(raw);
2274
+ const raw2 = route?.quote?.msgValue;
2275
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
2276
+ const value = BigInt(raw2);
741
2277
  return value > 0n ? value : 0n;
742
2278
  } catch {
743
2279
  return 0n;
744
2280
  }
745
2281
  }
746
2282
  function nativeSymbol(chainId, chains = []) {
747
- const registry = chainById(chains, Number(chainId))?.nativeCurrency;
748
- const fromRegistry = typeof registry === "string" ? registry.trim() : "";
2283
+ const registry2 = chainById(chains, Number(chainId))?.nativeCurrency;
2284
+ const fromRegistry = typeof registry2 === "string" ? registry2.trim() : "";
749
2285
  return fromRegistry || BUNDLED_NATIVE_SYMBOL[Number(chainId)] || "ETH";
750
2286
  }
751
2287
  function formatNative(wei) {
@@ -772,6 +2308,11 @@ function nativeFeeShortMessage(check2, symbol, chainName3) {
772
2308
  }
773
2309
 
774
2310
  // src/core/route-health.ts
2311
+ function healthLaneKey(value) {
2312
+ if (typeof value !== "string") return "";
2313
+ const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
2314
+ return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
2315
+ }
775
2316
  var EMPTY = /* @__PURE__ */ new Map();
776
2317
  var NO_LIMITS = /* @__PURE__ */ new Map();
777
2318
  function laneAvailabilityState(lane) {
@@ -791,7 +2332,7 @@ function suppressedLanes(health) {
791
2332
  const out = /* @__PURE__ */ new Map();
792
2333
  for (const lane of health.lanes) {
793
2334
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
794
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
2335
+ const key = healthLaneKey(lane.laneKey);
795
2336
  if (!key) continue;
796
2337
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
797
2338
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
@@ -811,7 +2352,7 @@ function limitedLanes(health) {
811
2352
  const out = /* @__PURE__ */ new Map();
812
2353
  for (const lane of health.lanes) {
813
2354
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
814
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
2355
+ const key = healthLaneKey(lane.laneKey);
815
2356
  const limit = lane.availability?.limit;
816
2357
  if (!key || !limit || typeof limit !== "object") continue;
817
2358
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
@@ -834,14 +2375,14 @@ function limitedLanes(health) {
834
2375
  }
835
2376
  function exceedsLaneLimit(limit, amount, bidDecimals) {
836
2377
  if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
837
- let raw;
2378
+ let raw2;
838
2379
  try {
839
- raw = parseUnitsDecimal(amount, bidDecimals);
2380
+ raw2 = parseUnitsDecimal(amount, bidDecimals);
840
2381
  } catch {
841
2382
  return false;
842
2383
  }
843
2384
  const scale = Math.max(bidDecimals, limit.decimals);
844
- return scaleDecimals(raw, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
2385
+ return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
845
2386
  }
846
2387
  function laneLimitAmount(limit) {
847
2388
  return formatUnits(limit.maxAmount, limit.decimals);
@@ -1007,12 +2548,12 @@ function stripBundlePrefix(head) {
1007
2548
  if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
1008
2549
  return { head, source: null };
1009
2550
  }
1010
- function complianceReasonHead(raw) {
1011
- return stripBundlePrefix((raw.split(":")[0] ?? "").trim()).head;
2551
+ function complianceReasonHead(raw2) {
2552
+ return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
1012
2553
  }
1013
- function usd(raw) {
1014
- const n = Number(raw);
1015
- if (!Number.isFinite(n)) return `$${raw}`;
2554
+ function usd(raw2) {
2555
+ const n = Number(raw2);
2556
+ if (!Number.isFinite(n)) return `$${raw2}`;
1016
2557
  return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
1017
2558
  }
1018
2559
  function capFromDetail(detail) {
@@ -1023,11 +2564,11 @@ function categoryPhrase(detail) {
1023
2564
  const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
1024
2565
  return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
1025
2566
  }
1026
- function humanizeComplianceReason(raw) {
1027
- const [headRaw, ...restParts] = raw.split(":");
2567
+ function humanizeComplianceReason(raw2) {
2568
+ const [headRaw, ...restParts] = raw2.split(":");
1028
2569
  const detail = restParts.join(":").trim();
1029
- const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
1030
- const scope = source === "legislation" ? "applicable regulations" : "the applicable policy";
2570
+ const { head, source: source2 } = stripBundlePrefix((headRaw ?? "").trim());
2571
+ const scope = source2 === "legislation" ? "applicable regulations" : "the applicable policy";
1031
2572
  switch (head) {
1032
2573
  case "asset_pair_not_allowed": {
1033
2574
  const m = detail.match(/^(\S+)->(\S+)\s+in\s+(\S+)/);
@@ -1101,8 +2642,8 @@ var CHECK_HEADS = {
1101
2642
  function distinctScreenedWallets(compliance) {
1102
2643
  const seen = /* @__PURE__ */ new Set();
1103
2644
  const wallets = [];
1104
- for (const raw of compliance?.screenedWallets ?? []) {
1105
- const address = raw?.trim();
2645
+ for (const raw2 of compliance?.screenedWallets ?? []) {
2646
+ const address = raw2?.trim();
1106
2647
  if (!address) continue;
1107
2648
  const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
1108
2649
  if (seen.has(key)) continue;
@@ -1122,11 +2663,11 @@ function screeningLabel(wallets) {
1122
2663
  function complianceChecks(compliance, cv = complianceView(compliance)) {
1123
2664
  if (cv.tone === "neutral") return [];
1124
2665
  const byControl = /* @__PURE__ */ new Map();
1125
- for (const raw of compliance?.reasons ?? []) {
1126
- const head = complianceReasonHead(raw);
2666
+ for (const raw2 of compliance?.reasons ?? []) {
2667
+ const head = complianceReasonHead(raw2);
1127
2668
  const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
1128
2669
  if (!id) continue;
1129
- byControl.set(id, [...byControl.get(id) ?? [], raw]);
2670
+ byControl.set(id, [...byControl.get(id) ?? [], raw2]);
1130
2671
  }
1131
2672
  const screenedWallets = distinctScreenedWallets(compliance);
1132
2673
  const wallets = screenedWallets.length;
@@ -1175,8 +2716,8 @@ var BLOCK_CATEGORY_LABELS = {
1175
2716
  };
1176
2717
  var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
1177
2718
  function blockLabelFor(categories) {
1178
- for (const raw of categories) {
1179
- const label = BLOCK_CATEGORY_LABELS[String(raw || "").trim().toUpperCase()];
2719
+ for (const raw2 of categories) {
2720
+ const label = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
1180
2721
  if (label) return label;
1181
2722
  }
1182
2723
  return BLOCK_LABEL_DEFAULT;
@@ -1197,8 +2738,8 @@ var REASON_TAGS = {
1197
2738
  dest_chain_not_allowed: "Chain not allowed",
1198
2739
  jurisdiction_out_of_scope: "Out of scope"
1199
2740
  };
1200
- function complianceReasonTag(raw) {
1201
- const head = complianceReasonHead(raw);
2741
+ function complianceReasonTag(raw2) {
2742
+ const head = complianceReasonHead(raw2);
1202
2743
  return REASON_TAGS[head] ?? head.replace(/_/g, " ");
1203
2744
  }
1204
2745
  function complianceTagOf(compliance) {
@@ -1261,8 +2802,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1261
2802
  const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
1262
2803
  const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
1263
2804
  const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
1264
- const enforcePayCeiling = (raw) => {
1265
- if (maxPayRaw > 0n && BigInt(raw) > maxPayRaw) {
2805
+ const enforcePayCeiling = (raw2) => {
2806
+ if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
1266
2807
  throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
1267
2808
  }
1268
2809
  };
@@ -1286,7 +2827,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1286
2827
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
1287
2828
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1288
2829
  }
1289
- const guaranteed = BigInt(quote?.toAmount || "0");
2830
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1290
2831
  const final = finalOf(quote);
1291
2832
  if (final > bestFinal) {
1292
2833
  bestFinal = final;
@@ -1323,7 +2864,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1323
2864
  directTransfer: false,
1324
2865
  quote: best,
1325
2866
  youPayRaw: bestGuess.toString(),
1326
- recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
2867
+ recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
1327
2868
  targetRaw: targetRaw.toString(),
1328
2869
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
1329
2870
  meetsTarget: bestFinal >= targetRaw,
@@ -1345,7 +2886,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
1345
2886
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
1346
2887
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1347
2888
  }
1348
- const guaranteed = BigInt(quote?.toAmount || "0");
2889
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1349
2890
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
1350
2891
  return {
1351
2892
  directTransfer: false,
@@ -1376,13 +2917,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
1376
2917
  const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
1377
2918
  const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
1378
2919
  if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
2920
+ const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
2921
+ const keyBytes2 = (value, label) => {
2922
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label} is not a valid 32-byte Solana key.`);
2923
+ return String(value).toLowerCase();
2924
+ };
1379
2925
  return {
1380
2926
  owner: assertAddress(order.owner || payer, "Order owner"),
1381
2927
  bidToken: assertAddress(order.bidToken, "Bid token"),
1382
2928
  bidTokenAmount: String(order.bidTokenAmount || "0"),
1383
- askToken: assertAddress(order.askToken, "Ask token"),
2929
+ askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
1384
2930
  askTokenAmount: String(order.askTokenAmount || "0"),
1385
- destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
2931
+ destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
2932
+ ...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
1386
2933
  destinationChainId: String(order.destinationChainId || destination.chainId),
1387
2934
  executionChainId,
1388
2935
  deadline
@@ -1394,17 +2941,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
1394
2941
  (request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
1395
2942
  );
1396
2943
  }
1397
- function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
2944
+ function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
1398
2945
  const list = orders?.length ? orders : [order];
1399
2946
  const sourceOrder = list[0];
1400
2947
  const finalOrder = list[list.length - 1];
1401
2948
  const now = Math.floor(Date.now() / 1e3);
1402
2949
  const deadline = Number(sourceOrder.deadline || 0);
2950
+ const solana = isSolanaChainId(destination.chainId);
2951
+ if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
2952
+ throw new Error("This Solana token is not supported for delivery; refusing to sign.");
2953
+ }
1403
2954
  for (const current of list) {
1404
2955
  if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
1405
2956
  throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
1406
2957
  }
1407
- if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(destination.address)) {
2958
+ if (isSolanaChainId(current.destinationChainId)) {
2959
+ if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
2960
+ checkSolanaReceiver(current, destination.address, destinationToken.address);
2961
+ } else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
1408
2962
  throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
1409
2963
  }
1410
2964
  if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
@@ -1414,9 +2968,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1414
2968
  if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
1415
2969
  throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
1416
2970
  }
1417
- if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
2971
+ if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
1418
2972
  throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
1419
2973
  }
2974
+ if (solana && finalOrder.askTokenBase58 && finalOrder.askTokenBase58 !== destinationToken.address) throw new Error("ZeroDelta quote returned an ask token mint that does not match the destination asset.");
1420
2975
  if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
1421
2976
  throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
1422
2977
  }
@@ -1435,10 +2990,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1435
2990
  if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
1436
2991
  throw new Error("ZeroDelta quote returned a non-positive output amount.");
1437
2992
  }
1438
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
2993
+ const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
2994
+ const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
2995
+ if (!covers(result.targetRaw)) {
1439
2996
  throw new Error("ZeroDelta quote would not cover the requested destination amount.");
1440
2997
  }
1441
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
2998
+ if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
1442
2999
  throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
1443
3000
  }
1444
3001
  const maxDeadline = maxDeadlineSeconds(quote);
@@ -1470,8 +3027,8 @@ function routeDeltaLabel(result, quote) {
1470
3027
  return "~0";
1471
3028
  }
1472
3029
  function quotePartnerId(quote) {
1473
- const raw = quote.partnerId;
1474
- return typeof raw === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw) ? raw.toLowerCase() : NO_PARTNER_ID;
3030
+ const raw2 = quote.partnerId;
3031
+ return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
1475
3032
  }
1476
3033
  function optionTicker(option) {
1477
3034
  return option.ticker || option.symbol;
@@ -1482,14 +3039,15 @@ function routeLabelFor(option, destinationToken, result) {
1482
3039
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
1483
3040
  }
1484
3041
  function tokenAt(tokens, chainId, address) {
1485
- const wanted = normalizeAddress(address);
3042
+ const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
3043
+ const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
1486
3044
  if (!wanted || !tokens?.length) return void 0;
1487
- return tokens.find((t) => Number(t.chainId) === Number(chainId) && normalizeAddress(t.address) === wanted);
3045
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
1488
3046
  }
1489
- function legAmount(raw, decimals) {
3047
+ function legAmount(raw2, decimals) {
1490
3048
  if (decimals === void 0) return "";
1491
3049
  try {
1492
- return formatUnits(raw || "0", decimals);
3050
+ return formatUnits(raw2 || "0", decimals);
1493
3051
  } catch {
1494
3052
  return "";
1495
3053
  }
@@ -1520,7 +3078,7 @@ function buildLegs(orders, ctx) {
1520
3078
  toTicker,
1521
3079
  toChainId,
1522
3080
  toChainName: chainNameOf(toChainId, ctx.chains),
1523
- toAmount: legAmount(order.askTokenAmount, toDecimals),
3081
+ toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
1524
3082
  executionChainId,
1525
3083
  executionChainName: chainNameOf(executionChainId, ctx.chains)
1526
3084
  });
@@ -1624,8 +3182,12 @@ async function buildRoute({
1624
3182
  const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
1625
3183
  const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
1626
3184
  const order = orders[0];
1627
- assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
1628
- const needsNativeFee = requiresNativeBridgeFee(quote, option);
3185
+ assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
3186
+ const echoedExecution = Number(quote.executionChainId || 0);
3187
+ if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
3188
+ throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
3189
+ }
3190
+ const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
1629
3191
  if (needsNativeFee) {
1630
3192
  let rawFee;
1631
3193
  try {
@@ -1669,7 +3231,7 @@ async function buildRoute({
1669
3231
  },
1670
3232
  routeLabel: routeLabelFor(option, destinationToken, result),
1671
3233
  deltaLabel: routeDeltaLabel(result, quote),
1672
- legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
3234
+ legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
1673
3235
  transactions: [
1674
3236
  {
1675
3237
  id: "approve",
@@ -1702,6 +3264,7 @@ async function buildRoute({
1702
3264
  gasCostSource: quote.gasCostSource,
1703
3265
  msgValue: valueRaw.toString(),
1704
3266
  deadline: order.deadline,
3267
+ ...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
1705
3268
  partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
1706
3269
  iterations: result.iterations,
1707
3270
  // Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
@@ -1717,10 +3280,10 @@ var CHANNEL_HEADER = "x-zd-channel";
1717
3280
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
1718
3281
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
1719
3282
  var WIDGET_CHANNEL = "widget";
1720
- var WIDGET_VERSION = "4.12.0" ;
3283
+ var WIDGET_VERSION = "4.13.0" ;
1721
3284
  var MAX_CHANNEL_VERSION_LEN = 32;
1722
- function sanitizeVersion(raw) {
1723
- const v = String(raw).trim();
3285
+ function sanitizeVersion(raw2) {
3286
+ const v = String(raw2).trim();
1724
3287
  if (!v) return "";
1725
3288
  const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
1726
3289
  return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
@@ -1756,9 +3319,9 @@ function isReportableSubmission(report) {
1756
3319
 
1757
3320
  // src/core/api.ts
1758
3321
  function apiError(message, props = {}) {
1759
- const err = new Error(message);
1760
- Object.assign(err, props);
1761
- return err;
3322
+ const err2 = new Error(message);
3323
+ Object.assign(err2, props);
3324
+ return err2;
1762
3325
  }
1763
3326
  function toQuery(params) {
1764
3327
  const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== "" && v !== null);
@@ -1776,14 +3339,14 @@ function sanitizeMessage(value, fallback) {
1776
3339
  return text.length > MAX_MESSAGE_LEN ? `${text.slice(0, MAX_MESSAGE_LEN - 1)}\u2026` : text;
1777
3340
  }
1778
3341
  function apiMessage(json, fallback) {
1779
- const err = json?.error || json;
1780
- if (err?.fieldErrors?.[0]?.message) return sanitizeMessage(err.fieldErrors[0].message, fallback);
1781
- if (Array.isArray(err?.reasons) && err.reasons.length) {
1782
- const head = sanitizeMessage(err.message, fallback);
1783
- const detail = sanitizeMessage(err.reasons.filter((r) => typeof r === "string").join(", "), "");
3342
+ const err2 = json?.error || json;
3343
+ if (err2?.fieldErrors?.[0]?.message) return sanitizeMessage(err2.fieldErrors[0].message, fallback);
3344
+ if (Array.isArray(err2?.reasons) && err2.reasons.length) {
3345
+ const head = sanitizeMessage(err2.message, fallback);
3346
+ const detail = sanitizeMessage(err2.reasons.filter((r) => typeof r === "string").join(", "), "");
1784
3347
  return detail ? `${head}: ${detail}` : head;
1785
3348
  }
1786
- return sanitizeMessage(err?.message, fallback);
3349
+ return sanitizeMessage(err2?.message, fallback);
1787
3350
  }
1788
3351
  function isStructuredComplianceBlock(error) {
1789
3352
  const code = String(error?.code || "").toUpperCase();
@@ -1923,9 +3486,9 @@ function createApiClient(cfg) {
1923
3486
  if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
1924
3487
  return once("chains", async () => {
1925
3488
  const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
1926
- const normalized = (Array.isArray(chains) ? chains : []).map((chain) => ({ ...chain, chainId: Number(chain.chainId) })).map((chain) => {
1927
- const escrow = normalizeAddress(chain.escrowContract);
1928
- return escrow ? { ...chain, escrowContract: escrow } : { ...chain, escrowContract: void 0 };
3489
+ const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
3490
+ const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
3491
+ return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
1929
3492
  });
1930
3493
  cache.chains = { at: Date.now(), value: normalized };
1931
3494
  return normalized;
@@ -2028,14 +3591,16 @@ function createApiClient(cfg) {
2028
3591
  async function screenWallet(address, chainId) {
2029
3592
  const addr = String(address || "").trim();
2030
3593
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
2031
- const key = `${/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr}|${chainId ?? ""}`;
3594
+ const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3595
+ if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3596
+ const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
2032
3597
  const hit = screenCache.get(key);
2033
3598
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
2034
3599
  const inflight = screenInflight.get(key);
2035
3600
  if (inflight) return inflight;
2036
3601
  const request = apiRequest("/screen/wallet", {
2037
3602
  method: "POST",
2038
- body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
3603
+ body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
2039
3604
  timeoutMs: 12e3
2040
3605
  }).then((screen) => {
2041
3606
  if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
@@ -2075,7 +3640,7 @@ function createApiClient(cfg) {
2075
3640
 
2076
3641
  // src/core/plan.ts
2077
3642
  function optionBalanceKey(option) {
2078
- return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
3643
+ return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
2079
3644
  }
2080
3645
  function hasPositiveBalance(option, balances) {
2081
3646
  try {
@@ -2085,7 +3650,8 @@ function hasPositiveBalance(option, balances) {
2085
3650
  }
2086
3651
  }
2087
3652
  function validateDestination(destination) {
2088
- assertAddress(destination.address, "Destination address");
3653
+ const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
3654
+ if (isSolanaChainId(destination.chainId)) destination.address = address;
2089
3655
  const chainId = Number(destination.chainId);
2090
3656
  const asset = symbolKey(destination.asset);
2091
3657
  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
@@ -2143,8 +3709,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
2143
3709
  if (directOptions.length) {
2144
3710
  const parties = [];
2145
3711
  const seenParty = /* @__PURE__ */ new Set();
2146
- for (const raw of [payer, destination.address]) {
2147
- const addr = String(raw || "").trim();
3712
+ for (const raw2 of [payer, destination.address]) {
3713
+ const addr = String(raw2 || "").trim();
2148
3714
  if (!addr) continue;
2149
3715
  const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
2150
3716
  if (seenParty.has(key)) continue;
@@ -2252,7 +3818,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
2252
3818
  if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
2253
3819
  const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
2254
3820
  const option = buildPayOptions({ invoiceAsset: destination.asset, invoiceChainId: destination.chainId, tokens, routes, chains, walletChainId: wallet.chainId, catalogue }).find(
2255
- (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && o.address.toLowerCase() === String(picked.address).toLowerCase() && (!allowedFunding || allowedFunding.has(o.symbolKey))
3821
+ (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
2256
3822
  );
2257
3823
  if (!option) throw new Error("That funding option is not available for this payment right now.");
2258
3824
  return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
@@ -2275,8 +3841,10 @@ function viaOf(quote, tokens) {
2275
3841
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
2276
3842
  if (orders.length < 2) return null;
2277
3843
  const first = orders[0];
2278
- const wanted = normalizeAddress(first?.askToken);
2279
- const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && normalizeAddress(t.address) === wanted) : void 0;
3844
+ const chainId = Number(first?.destinationChainId);
3845
+ const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
3846
+ const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
3847
+ const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
2280
3848
  return token ? tokenTicker(token) : "";
2281
3849
  }
2282
3850
  async function quoteSwapPreview(api, swap, owner) {
@@ -2288,7 +3856,7 @@ async function quoteSwapPreview(api, swap, owner) {
2288
3856
  if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
2289
3857
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2290
3858
  const account = normalizeAddress(owner) || PREVIEW_OWNER;
2291
- const previewReceiver = normalizeAddress(swap.recipient) || account;
3859
+ const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
2292
3860
  const quote = await api.fetchQuote({
2293
3861
  fromChainId: v.fromChainId,
2294
3862
  toChainId: v.toChainId,
@@ -2296,7 +3864,7 @@ async function quoteSwapPreview(api, swap, owner) {
2296
3864
  toToken: destToken.symbol,
2297
3865
  fromAmount: amountInRaw.toString(),
2298
3866
  owner: account,
2299
- destinationReceiver: previewReceiver
3867
+ ...previewReceiver ? { destinationReceiver: previewReceiver } : {}
2300
3868
  });
2301
3869
  const final = finalOf(quote);
2302
3870
  return {
@@ -2321,7 +3889,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
2321
3889
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
2322
3890
  if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
2323
3891
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2324
- const receiver = resolveSwapReceiver(swap.recipient, account);
3892
+ const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
2325
3893
  const option = {
2326
3894
  symbol: sourceToken.symbol,
2327
3895
  symbolKey: symbolKey(sourceToken.symbol),
@@ -2391,9 +3959,9 @@ function rawEquals(value, expected) {
2391
3959
  }
2392
3960
  function planMsgValueHex(route) {
2393
3961
  try {
2394
- const raw = route?.quote?.msgValue;
2395
- if (raw === void 0 || raw === null || raw === "") return "0x0";
2396
- return "0x" + BigInt(raw).toString(16);
3962
+ const raw2 = route?.quote?.msgValue;
3963
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
3964
+ return "0x" + BigInt(raw2).toString(16);
2397
3965
  } catch {
2398
3966
  return null;
2399
3967
  }
@@ -2420,15 +3988,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
2420
3988
  if (!decoded) return false;
2421
3989
  const first = decoded.orders[0];
2422
3990
  const last = decoded.orders[decoded.orders.length - 1];
2423
- return decoded.partnerId === lower(route.quote?.partnerId || NO_PARTNER_ID) && lower(first.bidToken) === lower(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower(last.askToken) === lower(route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && lower(last.destinationReceiver) === lower(expectedRecipient);
3991
+ return decoded.partnerId === lower(route.quote?.partnerId || NO_PARTNER_ID) && lower(first.bidToken) === lower(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower(last.askToken) === lower(isSolanaChainId(route.receive.chainId) ? solanaKeyHex(route.receive.tokenAddress || "") : route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && (isSolanaChainId(route.receive.chainId) ? solanaDeliveryMatches(last.destinationReceiver, expectedRecipient, route.receive.tokenAddress) : lower(last.destinationReceiver) === lower(expectedRecipient));
2424
3992
  }
2425
3993
  return false;
2426
3994
  }
3995
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
3996
+ try {
3997
+ return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
3998
+ } catch {
3999
+ return false;
4000
+ }
4001
+ }
2427
4002
  async function allowanceCovers(tx, account, ethCall2) {
2428
4003
  if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
2429
4004
  try {
2430
- const raw = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
2431
- return BigInt(raw || "0x0") >= BigInt(tx.amountRaw || "0");
4005
+ const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
4006
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
2432
4007
  } catch {
2433
4008
  return false;
2434
4009
  }
@@ -2439,9 +4014,9 @@ var TX_VERIFY_ATTEMPTS = 5;
2439
4014
  var TX_VERIFY_INTERVAL_MS = 2500;
2440
4015
  var TX_VERIFY_FETCH_MS = 5e3;
2441
4016
  var TX_VERIFY_DEADLINE_MS = 18e3;
2442
- function registryRpc(chain) {
2443
- if (!chain) return "";
2444
- const candidates = [chain.rpcUrl, Array.isArray(chain.rpcUrls) ? chain.rpcUrls[0] : null, chain.publicRpcUrl, chain.rpc, chain.rpcEndpoint];
4017
+ function registryRpc(chain2) {
4018
+ if (!chain2) return "";
4019
+ const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
2445
4020
  const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
2446
4021
  return found || "";
2447
4022
  }
@@ -2522,8 +4097,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2522
4097
  }
2523
4098
  return null;
2524
4099
  }
2525
- async function verifySubmittedTx({ chainId, hash, from, to, data, value, minNonce }) {
2526
- if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash || ""))) return { status: "mismatch" };
4100
+ async function verifySubmittedTx({ chainId, hash: hash2, from, to, data, value, minNonce }) {
4101
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash2 || ""))) return { status: "mismatch" };
2527
4102
  if (!normalizeAddress(from) || typeof minNonce !== "number") return { status: "unconfirmed", reason: "no-binding" };
2528
4103
  const rpcUrl = await chainRpcUrl(chainId);
2529
4104
  if (!rpcUrl) return { status: "unconfirmed", reason: "no-rpc" };
@@ -2534,7 +4109,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2534
4109
  if (!matched) {
2535
4110
  let tx = null;
2536
4111
  try {
2537
- tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash]);
4112
+ tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash2]);
2538
4113
  } catch {
2539
4114
  tx = null;
2540
4115
  }
@@ -2546,7 +4121,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2546
4121
  if (matched) {
2547
4122
  let receipt = null;
2548
4123
  try {
2549
- receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash]);
4124
+ receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash2]);
2550
4125
  } catch {
2551
4126
  receipt = null;
2552
4127
  }
@@ -2588,9 +4163,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2588
4163
  }
2589
4164
  function record(target, hex) {
2590
4165
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
2591
- const raw = BigInt(hex || "0x0").toString();
4166
+ const raw2 = BigInt(hex || "0x0").toString();
2592
4167
  const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
2593
- out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
4168
+ out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
2594
4169
  return true;
2595
4170
  }
2596
4171
  async function readOne(rpcUrl, target) {
@@ -2656,9 +4231,9 @@ function isSameOriginPath(value) {
2656
4231
  return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
2657
4232
  }
2658
4233
  function resolveApiBase(value) {
2659
- const raw = value ?? DEFAULT_WIDGET_API_BASE;
2660
- if (isSameOriginPath(raw)) return raw.replace(/\/+$/, "") || "/";
2661
- return parseAllowedApiBase(raw) || DEFAULT_WIDGET_API_BASE;
4234
+ const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
4235
+ if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
4236
+ return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
2662
4237
  }
2663
4238
  function canAttachApiKey(apiBase, trustedOrigin) {
2664
4239
  if (isSameOriginPath(apiBase)) return true;
@@ -2697,31 +4272,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
2697
4272
  }
2698
4273
 
2699
4274
  // src/core/index.ts
4275
+ var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
2700
4276
  function sanitizeLegs(legs) {
2701
4277
  if (!Array.isArray(legs) || !legs.length) return void 0;
2702
4278
  const text = (v, max) => String(v ?? "").slice(0, max);
2703
- const chain = (v) => Number(v) || 0;
4279
+ const chain2 = (v) => Number(v) || 0;
2704
4280
  const ticker = (value, asset) => safeTicker(value, asset) || void 0;
2705
4281
  return legs.slice(0, 8).map((leg, i) => ({
2706
4282
  index: Number(leg?.index) || i + 1,
2707
4283
  fromAsset: text(leg?.fromAsset, 12),
2708
4284
  fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
2709
- fromChainId: chain(leg?.fromChainId),
4285
+ fromChainId: chain2(leg?.fromChainId),
2710
4286
  fromChainName: text(leg?.fromChainName, 40),
2711
4287
  fromAmount: text(leg?.fromAmount, 40),
2712
4288
  toAsset: text(leg?.toAsset, 12),
2713
4289
  toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
2714
- toChainId: chain(leg?.toChainId),
4290
+ toChainId: chain2(leg?.toChainId),
2715
4291
  toChainName: text(leg?.toChainName, 40),
2716
4292
  toAmount: text(leg?.toAmount, 40),
2717
- executionChainId: chain(leg?.executionChainId),
4293
+ executionChainId: chain2(leg?.executionChainId),
2718
4294
  executionChainName: text(leg?.executionChainName, 40)
2719
4295
  }));
2720
4296
  }
2721
4297
  function sanitizeTxEntry(entry) {
2722
4298
  return {
2723
4299
  kind: entry.kind === "swap" ? "swap" : "payment",
2724
- hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
4300
+ // A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
4301
+ hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) || isSolanaChainId(entry.chainId) && /^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
2725
4302
  txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
2726
4303
  chainId: Number(entry.chainId) || null,
2727
4304
  chainName: String(entry.chainName || "").slice(0, 40),
@@ -2732,7 +4309,7 @@ function sanitizeTxEntry(entry) {
2732
4309
  payAmount: String(entry.payAmount || "").slice(0, 40),
2733
4310
  receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
2734
4311
  account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
2735
- recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
4312
+ recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
2736
4313
  settlement: entry.settlement === "direct" ? "direct" : "escrow",
2737
4314
  status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
2738
4315
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2743,6 +4320,7 @@ function createEngine(config = {}) {
2743
4320
  const resolved = resolveConfig(config);
2744
4321
  const api = createApiClient(resolved);
2745
4322
  const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
4323
+ const solanaRpc = createSolanaRpc(api);
2746
4324
  return {
2747
4325
  api,
2748
4326
  verifier,
@@ -2753,7 +4331,7 @@ function createEngine(config = {}) {
2753
4331
  fetchRouteHealth: api.fetchRouteHealth,
2754
4332
  fetchQuote: api.fetchQuote,
2755
4333
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
2756
- fetchCatalogue: async (allowedAssets, product) => {
4334
+ fetchCatalogue: async (allowedAssets, product, options) => {
2757
4335
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
2758
4336
  api.fetchChains().catch(() => []),
2759
4337
  api.fetchTokens().catch(() => []),
@@ -2770,7 +4348,9 @@ function createEngine(config = {}) {
2770
4348
  routes,
2771
4349
  product,
2772
4350
  ...allowed ? { allowedAssets: allowed } : {},
2773
- supportedChainIds: SUPPORTED_CHAIN_IDS,
4351
+ // Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
4352
+ // Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
4353
+ supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
2774
4354
  brokenLanes: suppressedLanes(health),
2775
4355
  // Same read, same degraded mode: a null health response limits nothing.
2776
4356
  limitedLanes: limitedLanes(health),
@@ -2781,6 +4361,13 @@ function createEngine(config = {}) {
2781
4361
  quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
2782
4362
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
2783
4363
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
4364
+ quoteSolanaSource: (input) => quoteSolanaSource(api, input),
4365
+ buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
4366
+ executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
4367
+ executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
4368
+ previewSolanaSource: (input) => previewSolanaSource(api, input),
4369
+ readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
4370
+ simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
2784
4371
  payerNonceBaseline: verifier.payerNonceBaseline,
2785
4372
  verifySubmittedTx: verifier.verifySubmittedTx,
2786
4373
  readBalances: verifier.readBalances,
@@ -2879,8 +4466,8 @@ function addChainParams(chainId) {
2879
4466
  rpcUrls: [rpc]
2880
4467
  };
2881
4468
  }
2882
- function rpcErrorCode(err) {
2883
- let cur = err;
4469
+ function rpcErrorCode(err2) {
4470
+ let cur = err2;
2884
4471
  const seen = /* @__PURE__ */ new Set();
2885
4472
  while (cur && typeof cur === "object" && !seen.has(cur)) {
2886
4473
  seen.add(cur);
@@ -2894,50 +4481,50 @@ function rpcErrorCode(err) {
2894
4481
  async function switchChain(provider, chainId) {
2895
4482
  try {
2896
4483
  await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainHex(chainId) }] });
2897
- } catch (err) {
4484
+ } catch (err2) {
2898
4485
  const params = addChainParams(chainId);
2899
- if (rpcErrorCode(err) === 4902 && params) {
4486
+ if (rpcErrorCode(err2) === 4902 && params) {
2900
4487
  await provider.request({ method: "wallet_addEthereumChain", params: [params] });
2901
4488
  await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainHex(chainId) }] });
2902
4489
  return;
2903
4490
  }
2904
- throw err;
4491
+ throw err2;
2905
4492
  }
2906
4493
  }
2907
- function shortWalletMessage(err) {
2908
- if (err && typeof err === "object") {
2909
- const e = err;
4494
+ function shortWalletMessage(err2) {
4495
+ if (err2 && typeof err2 === "object") {
4496
+ const e = err2;
2910
4497
  if (typeof e.shortMessage === "string" && e.shortMessage) return e.shortMessage;
2911
4498
  if (typeof e.message === "string" && e.message) return e.message;
2912
4499
  }
2913
4500
  return void 0;
2914
4501
  }
2915
- function normalizeWalletError(err, fallback = "Transaction failed.") {
2916
- if (!err) return fallback;
2917
- const code = rpcErrorCode(err);
2918
- const name = err && typeof err === "object" && "name" in err ? err.name : void 0;
4502
+ function normalizeWalletError(err2, fallback = "Transaction failed.") {
4503
+ if (!err2) return fallback;
4504
+ const code = rpcErrorCode(err2);
4505
+ const name = err2 && typeof err2 === "object" && "name" in err2 ? err2.name : void 0;
2919
4506
  if (code === -32002) return "Open your wallet \u2014 a request is already pending.";
2920
4507
  if (code === 4001 || name === "UserRejectedRequestError") return "Request was rejected in your wallet.";
2921
4508
  if (code === 4902) return "This chain isn't set up in your wallet. Approve adding it and try again.";
2922
- if (code === -32603) return shortWalletMessage(err) || "Your wallet returned an internal error. Try again.";
2923
- return shortWalletMessage(err) || fallback;
4509
+ if (code === -32603) return shortWalletMessage(err2) || "Your wallet returned an internal error. Try again.";
4510
+ return shortWalletMessage(err2) || fallback;
2924
4511
  }
2925
4512
  async function sendTransaction(provider, tx) {
2926
- const hash = await provider.request({
4513
+ const hash2 = await provider.request({
2927
4514
  method: "eth_sendTransaction",
2928
4515
  params: [{ from: tx.from, to: tx.to, data: tx.data, value: tx.value || "0x0" }]
2929
4516
  });
2930
- return hash;
4517
+ return hash2;
2931
4518
  }
2932
4519
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2933
- async function waitForReceipt(provider, hash, opts = {}) {
4520
+ async function waitForReceipt(provider, hash2, opts = {}) {
2934
4521
  const timeoutMs = opts.timeoutMs ?? 9e4;
2935
4522
  const pollMs = opts.pollMs ?? 2500;
2936
4523
  const deadline = Date.now() + timeoutMs;
2937
4524
  for (; ; ) {
2938
4525
  let receipt = null;
2939
4526
  try {
2940
- receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash] });
4527
+ receipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash2] });
2941
4528
  } catch {
2942
4529
  }
2943
4530
  if (receipt && receipt.status != null) {
@@ -2958,9 +4545,9 @@ async function ethCall(provider, to, data) {
2958
4545
  }
2959
4546
  async function nativeBalance(provider, account) {
2960
4547
  try {
2961
- const raw = await provider.request({ method: "eth_getBalance", params: [account, "latest"] });
2962
- if (typeof raw !== "string" || !/^0x[0-9a-fA-F]*$/.test(raw)) return null;
2963
- return BigInt(raw || "0x0");
4548
+ const raw2 = await provider.request({ method: "eth_getBalance", params: [account, "latest"] });
4549
+ if (typeof raw2 !== "string" || !/^0x[0-9a-fA-F]*$/.test(raw2)) return null;
4550
+ return BigInt(raw2 || "0x0");
2964
4551
  } catch {
2965
4552
  return null;
2966
4553
  }
@@ -3046,9 +4633,9 @@ function isEntry(v) {
3046
4633
  function readTxHistory(account, storage2 = defaultStorage()) {
3047
4634
  if (!storage2 || !validAccount(account)) return [];
3048
4635
  try {
3049
- const raw = storage2.getItem(txHistoryKey(account));
3050
- if (!raw) return [];
3051
- const parsed = JSON.parse(raw);
4636
+ const raw2 = storage2.getItem(txHistoryKey(account));
4637
+ if (!raw2) return [];
4638
+ const parsed = JSON.parse(raw2);
3052
4639
  return Array.isArray(parsed) ? parsed.filter(isEntry) : [];
3053
4640
  } catch {
3054
4641
  return [];
@@ -3267,7 +4854,7 @@ function useFlow(args) {
3267
4854
  const account = wallet.account;
3268
4855
  if (!route || !provider || !account) return;
3269
4856
  busyRef.current = true;
3270
- const recipient = recipientFor(account);
4857
+ const recipient2 = recipientFor(account);
3271
4858
  const sourceChainId = route.source.chainId;
3272
4859
  const txSteps = route.transactions.map((tx) => ({ id: tx.id, label: tx.label, state: "pending" }));
3273
4860
  txSteps.push({ id: "verify", label: "Confirm on-chain", state: "pending" });
@@ -3275,7 +4862,7 @@ function useFlow(args) {
3275
4862
  setStatus("submitting");
3276
4863
  setError(null);
3277
4864
  setVerdict(null);
3278
- const patch = (id, s, hash) => setSteps((prev) => prev.map((st) => st.id === id ? { ...st, state: s, ...hash ? { hash } : {} } : st));
4865
+ const patch = (id, s, hash2) => setSteps((prev) => prev.map((st) => st.id === id ? { ...st, state: s, ...hash2 ? { hash: hash2 } : {} } : st));
3279
4866
  try {
3280
4867
  const current = await getChainId(provider);
3281
4868
  if (current !== Number(sourceChainId)) {
@@ -3305,17 +4892,17 @@ function useFlow(args) {
3305
4892
  patch(tx.id, "done");
3306
4893
  continue;
3307
4894
  }
3308
- if (!validatePlannedTransaction(tx, route, recipient)) {
4895
+ if (!validatePlannedTransaction(tx, route, recipient2)) {
3309
4896
  throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
3310
4897
  }
3311
4898
  patch(tx.id, "active");
3312
- const hash = await sendTransaction(provider, { from: account, to: tx.to, data: tx.data, value: tx.value });
4899
+ const hash2 = await sendTransaction(provider, { from: account, to: tx.to, data: tx.data, value: tx.value });
3313
4900
  if (!isFinal) {
3314
- await waitForReceipt(provider, hash);
4901
+ await waitForReceipt(provider, hash2);
3315
4902
  }
3316
- patch(tx.id, "done", hash);
4903
+ patch(tx.id, "done", hash2);
3317
4904
  if (tx.kind !== "approve") {
3318
- settleHash = hash;
4905
+ settleHash = hash2;
3319
4906
  settleTx = tx;
3320
4907
  }
3321
4908
  }
@@ -3343,7 +4930,7 @@ function useFlow(args) {
3343
4930
  payAmount: route.source.payAmount,
3344
4931
  receiveAmount: route.receive.amount,
3345
4932
  account,
3346
- recipient,
4933
+ recipient: recipient2,
3347
4934
  settlement: route.state === "DIRECT" ? "direct" : "escrow",
3348
4935
  status: v.status === "confirmed" ? "confirmed" : v.status === "mismatch" || v.status === "reverted" ? "error" : "unconfirmed",
3349
4936
  // One signature can be several orders. Record them, or the history of a chained RWA trade
@@ -3471,18 +5058,18 @@ function groupDecimal(value) {
3471
5058
  var SIGNIFICANT_DIGITS = 7;
3472
5059
  var MIN_FRACTION_DIGITS = 4;
3473
5060
  function formatCalculatedAmount(value, decimals) {
3474
- let raw = typeof value === "number" ? String(value) : value.trim();
5061
+ let raw2 = typeof value === "number" ? String(value) : value.trim();
3475
5062
  if (typeof value === "number") {
3476
- if (!Number.isFinite(value)) return raw;
3477
- if (/e/i.test(raw)) {
3478
- raw = value.toLocaleString("en-US", {
5063
+ if (!Number.isFinite(value)) return raw2;
5064
+ if (/e/i.test(raw2)) {
5065
+ raw2 = value.toLocaleString("en-US", {
3479
5066
  useGrouping: false,
3480
5067
  maximumFractionDigits: 20
3481
5068
  });
3482
5069
  }
3483
5070
  }
3484
- const match = raw.match(/^([+-]?)(\d*)(?:\.(\d*))?$/);
3485
- if (!match) return raw;
5071
+ const match = raw2.match(/^([+-]?)(\d*)(?:\.(\d*))?$/);
5072
+ if (!match) return raw2;
3486
5073
  const negative = match[1] === "-";
3487
5074
  const integer = (match[2] || "0").replace(/^0+(?=\d)/, "");
3488
5075
  const fraction = match[3] ?? "";
@@ -3507,15 +5094,15 @@ function formatCalculatedAmount(value, decimals) {
3507
5094
  const out = groupDecimal(trimFraction(fixed));
3508
5095
  return negative && out !== "0" ? `-${out}` : out;
3509
5096
  }
3510
- function exactAmountTitle(raw, shown) {
3511
- const full = typeof raw === "number" ? String(raw) : raw.trim();
5097
+ function exactAmountTitle(raw2, shown) {
5098
+ const full = typeof raw2 === "number" ? String(raw2) : raw2.trim();
3512
5099
  if (!full || /e/i.test(full)) return void 0;
3513
5100
  const normalized = full.includes(".") ? trimFraction(full) : full;
3514
5101
  const grouped = groupDecimal(normalized);
3515
5102
  return grouped === shown ? void 0 : grouped;
3516
5103
  }
3517
- function sanitizeAmount(raw) {
3518
- const cleaned = raw.replace(/[^0-9.]/g, "");
5104
+ function sanitizeAmount(raw2) {
5105
+ const cleaned = raw2.replace(/[^0-9.]/g, "");
3519
5106
  const first = cleaned.indexOf(".");
3520
5107
  if (first === -1) return cleaned;
3521
5108
  return cleaned.slice(0, first + 1) + cleaned.slice(first + 1).replace(/\./g, "");
@@ -4428,9 +6015,9 @@ function useGroupedAmountInput(amount, onAmount) {
4428
6015
  });
4429
6016
  const onChange = (e) => {
4430
6017
  const input = e.target;
4431
- const raw = input.value;
4432
- caret.current = { input, kept: sanitizeAmount(raw.slice(0, input.selectionEnd ?? raw.length)).length };
4433
- onAmount(sanitizeAmount(raw));
6018
+ const raw2 = input.value;
6019
+ caret.current = { input, kept: sanitizeAmount(raw2.slice(0, input.selectionEnd ?? raw2.length)).length };
6020
+ onAmount(sanitizeAmount(raw2));
4434
6021
  rerender();
4435
6022
  };
4436
6023
  const onKeyDown = (e) => {
@@ -4554,11 +6141,11 @@ var METHODS = [
4554
6141
  function isLiveMethod(m) {
4555
6142
  return m === "stablecoin";
4556
6143
  }
4557
- function balanceRank(raw, decimals) {
4558
- if (raw == null) return 0n;
6144
+ function balanceRank(raw2, decimals) {
6145
+ if (raw2 == null) return 0n;
4559
6146
  try {
4560
6147
  const d = Number.isFinite(Number(decimals)) ? Math.max(0, Math.trunc(Number(decimals))) : 18;
4561
- const v = BigInt(raw);
6148
+ const v = BigInt(raw2);
4562
6149
  return d <= 18 ? v * 10n ** BigInt(18 - d) : v / 10n ** BigInt(d - 18);
4563
6150
  } catch {
4564
6151
  return 0n;
@@ -4598,7 +6185,7 @@ function RouteList(props) {
4598
6185
  visible.map((r) => {
4599
6186
  const selected = props.selectedId === r.id;
4600
6187
  const bal = props.balances?.[routeBalanceKey(r)];
4601
- const short = props.shortIds?.has(r.id) ?? false;
6188
+ const short2 = props.shortIds?.has(r.id) ?? false;
4602
6189
  const held = props.heldIds?.has(r.id) ?? false;
4603
6190
  return (
4604
6191
  // a11y note: a native radio cannot contain the rich
@@ -4610,7 +6197,7 @@ function RouteList(props) {
4610
6197
  {
4611
6198
  className: "sg-route-item",
4612
6199
  "data-selected": selected,
4613
- "data-short": short || void 0,
6200
+ "data-short": short2 || void 0,
4614
6201
  "data-held": held || void 0,
4615
6202
  role: "radio",
4616
6203
  "aria-checked": selected,
@@ -4645,7 +6232,7 @@ function RouteList(props) {
4645
6232
  "bal ",
4646
6233
  bal.formatted
4647
6234
  ] }) : null,
4648
- short ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Short" }) : r.state === "DIRECT" ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Direct" }) : r.recommended ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "accent", children: "Best" }) : null,
6235
+ short2 ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Short" }) : r.state === "DIRECT" ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Direct" }) : r.recommended ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "accent", children: "Best" }) : null,
4649
6236
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-radio", "aria-hidden": "true" })
4650
6237
  ] })
4651
6238
  ]
@@ -4892,9 +6479,9 @@ function buildChainSearchTerms(chains) {
4892
6479
  const byId = /* @__PURE__ */ new Map();
4893
6480
  const ids = /* @__PURE__ */ new Set([...chains.map((c) => Number(c.chainId)), ...Object.keys(CHAIN_LABELS).map(Number)]);
4894
6481
  for (const id of ids) {
4895
- const chain = chains.find((c) => Number(c.chainId) === id);
6482
+ const chain2 = chains.find((c) => Number(c.chainId) === id);
4896
6483
  const terms = /* @__PURE__ */ new Set();
4897
- for (const label of [chain?.displayName, chain?.name, typeof chain?.slug === "string" ? chain.slug : void 0, CHAIN_LABELS[id]]) {
6484
+ for (const label of [chain2?.displayName, chain2?.name, typeof chain2?.slug === "string" ? chain2.slug : void 0, CHAIN_LABELS[id]]) {
4898
6485
  if (label) for (const form of labelForms(label)) terms.add(form);
4899
6486
  }
4900
6487
  for (const alias of CHAIN_ALIASES[id] ?? []) terms.add(alias);
@@ -5384,7 +6971,7 @@ function durationLabel(seconds) {
5384
6971
  }
5385
6972
  function TokenButton(props) {
5386
6973
  const shown = props.token ? tokenTicker(props.token) : props.symbol ?? "";
5387
- const chain = props.chainId ? CHAIN_LABELS[props.chainId] || `Chain ${props.chainId}` : "";
6974
+ const chain2 = props.chainId ? CHAIN_LABELS[props.chainId] || `Chain ${props.chainId}` : "";
5388
6975
  return /* @__PURE__ */ jsxRuntime.jsxs(
5389
6976
  "button",
5390
6977
  {
@@ -5393,13 +6980,13 @@ function TokenButton(props) {
5393
6980
  className: "sg-tokbtn",
5394
6981
  disabled: props.disabled,
5395
6982
  onClick: props.onClick,
5396
- "aria-label": `${props.label}: ${props.symbol ? `${shown} on ${chain}` : "select token"}`,
6983
+ "aria-label": `${props.label}: ${props.symbol ? `${shown} on ${chain2}` : "select token"}`,
5397
6984
  children: [
5398
6985
  props.symbol && props.chainId ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
5399
6986
  /* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: props.symbol, logoUrl: props.token?.logoUrl, chainId: props.chainId, size: "xs" }),
5400
6987
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-tokbtn-text", children: [
5401
6988
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-sym", children: shown }),
5402
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chain", children: chain })
6989
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chain", children: chain2 })
5403
6990
  ] })
5404
6991
  ] }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-text", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-sym", children: "Select" }) }),
5405
6992
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-tokbtn-chev", children: /* @__PURE__ */ jsxRuntime.jsx(ChevronRight, {}) })
@@ -6041,6 +7628,444 @@ function TxHistoryPanel(props) {
6041
7628
  selected ? /* @__PURE__ */ jsxRuntime.jsx(TxDetail, { entry: selected, tokens: props.tokens, vaultIcons: props.vaultIcons }) : /* @__PURE__ */ jsxRuntime.jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
6042
7629
  ] });
6043
7630
  }
7631
+
7632
+ // src/provider/solana-wallet.ts
7633
+ var sources = /* @__PURE__ */ new WeakMap();
7634
+ var infos = /* @__PURE__ */ new WeakMap();
7635
+ var connected = /* @__PURE__ */ new WeakMap();
7636
+ var registries = /* @__PURE__ */ new WeakMap();
7637
+ var EMPTY2 = Object.freeze([]);
7638
+ function normalizeSolanaWalletName(name) {
7639
+ return name.trim().toLowerCase().replace(/\s+(wallet|evm|solana)$/i, "");
7640
+ }
7641
+ function solanaWalletInfo(provider) {
7642
+ const standard = "features" in provider;
7643
+ if (standard ? !provider.chains?.some((chain2) => chain2.startsWith("solana:")) || typeof provider.features?.["standard:connect"]?.connect !== "function" : typeof provider.connect !== "function") return null;
7644
+ let info = infos.get(provider);
7645
+ if (!info) {
7646
+ const name = provider.name || (!standard && provider.isPhantom ? "Phantom" : !standard && provider.isSolflare ? "Solflare" : "Solana wallet");
7647
+ info = Object.freeze({ name, icon: standard ? provider.icon : void 0, kind: standard ? "standard" : "legacy" });
7648
+ infos.set(provider, info);
7649
+ sources.set(info, provider);
7650
+ }
7651
+ return info;
7652
+ }
7653
+ function targetWindow(win) {
7654
+ return win ?? (typeof window === "undefined" ? void 0 : window);
7655
+ }
7656
+ function registry(win) {
7657
+ const existing = registries.get(win);
7658
+ if (existing) return existing;
7659
+ const standard = /* @__PURE__ */ new Set();
7660
+ const listeners = /* @__PURE__ */ new Set();
7661
+ let snapshot = EMPTY2;
7662
+ const read = () => {
7663
+ const candidates = [...standard].map(solanaWalletInfo);
7664
+ for (const [provider, name] of [[win.phantom?.solana, "Phantom"], [win.solflare, "Solflare"], [win.solana, void 0]]) {
7665
+ if (!provider || typeof provider.connect !== "function") continue;
7666
+ let info = solanaWalletInfo(provider);
7667
+ if (info && name && info.name === "Solana wallet") {
7668
+ info = Object.freeze({ ...info, name });
7669
+ infos.set(provider, info);
7670
+ sources.set(info, provider);
7671
+ }
7672
+ candidates.push(info);
7673
+ }
7674
+ const names = /* @__PURE__ */ new Set();
7675
+ const providers = /* @__PURE__ */ new Set();
7676
+ const next = candidates.filter((info) => {
7677
+ if (!info) return false;
7678
+ const name = normalizeSolanaWalletName(info.name);
7679
+ const provider = sources.get(info);
7680
+ if (names.has(name) || providers.has(provider)) return false;
7681
+ names.add(name);
7682
+ providers.add(provider);
7683
+ return true;
7684
+ });
7685
+ if (next.length !== snapshot.length || next.some((info) => !snapshot.includes(info))) snapshot = Object.freeze(next);
7686
+ return snapshot;
7687
+ };
7688
+ const refresh = () => {
7689
+ const previous = snapshot;
7690
+ read();
7691
+ if (previous !== snapshot) for (const cb of listeners) cb();
7692
+ };
7693
+ const api = {
7694
+ register(...wallets) {
7695
+ const added = wallets.filter((wallet) => !standard.has(wallet));
7696
+ for (const wallet of added) standard.add(wallet);
7697
+ refresh();
7698
+ return () => {
7699
+ for (const wallet of added) standard.delete(wallet);
7700
+ refresh();
7701
+ };
7702
+ }
7703
+ };
7704
+ const result = { read, watch: (cb) => {
7705
+ listeners.add(cb);
7706
+ return () => {
7707
+ listeners.delete(cb);
7708
+ };
7709
+ } };
7710
+ registries.set(win, result);
7711
+ win.addEventListener("wallet-standard:register-wallet", (event) => {
7712
+ const callback = event.detail;
7713
+ if (typeof callback === "function") callback(api);
7714
+ });
7715
+ win.addEventListener("focus", refresh);
7716
+ const EventClass = win.CustomEvent;
7717
+ win.dispatchEvent(new EventClass("wallet-standard:app-ready", { detail: api }));
7718
+ read();
7719
+ return result;
7720
+ }
7721
+ function discoverSolanaWallets(win) {
7722
+ const target = targetWindow(win);
7723
+ return target ? registry(target).read() : EMPTY2;
7724
+ }
7725
+ function watchSolanaWallets(cb, win) {
7726
+ const target = targetWindow(win);
7727
+ if (!target) return () => {
7728
+ };
7729
+ const store = registry(target);
7730
+ const unsubscribe = store.watch(() => cb(store.read()));
7731
+ cb(store.read());
7732
+ return unsubscribe;
7733
+ }
7734
+ function source(info) {
7735
+ const provider = sources.get(info);
7736
+ if (!provider) throw new Error("Solana wallet is no longer available. Discover it before connecting.");
7737
+ return provider;
7738
+ }
7739
+ function validAddress(value) {
7740
+ const address = value?.toString().trim();
7741
+ return address && isSolanaAddress(address) ? address : null;
7742
+ }
7743
+ function accountAddress(accounts) {
7744
+ const account = accounts?.find((item) => !item.chains?.length || item.chains.some((chain2) => chain2.startsWith("solana:")));
7745
+ return validAddress(account?.address);
7746
+ }
7747
+ function connectedSolanaAddress(info) {
7748
+ const provider = source(info);
7749
+ return "features" in provider ? accountAddress(provider.accounts) : validAddress(provider.publicKey);
7750
+ }
7751
+ async function connectSolanaWallet(info, options = {}) {
7752
+ const provider = source(info);
7753
+ let address;
7754
+ if ("features" in provider) {
7755
+ const result = await provider.features["standard:connect"].connect(options.silent ? { silent: true } : void 0);
7756
+ const accounts = result?.accounts ?? provider.accounts;
7757
+ connected.set(provider, accounts ?? []);
7758
+ address = accountAddress(accounts);
7759
+ } else {
7760
+ const result = await provider.connect(options.silent ? { onlyIfTrusted: true } : void 0);
7761
+ address = validAddress(result?.publicKey ?? provider.publicKey);
7762
+ connected.set(provider, address ? [{ address }] : []);
7763
+ }
7764
+ if (!address) throw new Error("The wallet did not return a valid Solana address.");
7765
+ return address;
7766
+ }
7767
+ async function disconnectSolanaWallet(info) {
7768
+ const provider = source(info);
7769
+ if ("features" in provider) await provider.features["standard:disconnect"]?.disconnect();
7770
+ else await provider.disconnect?.();
7771
+ connected.delete(provider);
7772
+ }
7773
+ var CANNOT_PAY = "This wallet cannot pay from Solana here; use a Wallet Standard wallet (Phantom, Solflare, Backpack).";
7774
+ function solanaWalletSigner(info) {
7775
+ const provider = source(info);
7776
+ const accounts = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
7777
+ const address = accountAddress(accounts);
7778
+ if (!connected.has(provider) || !address) throw new Error("Connect a Solana wallet before paying.");
7779
+ if ("features" in provider ? typeof provider.features["solana:signTransaction"]?.signTransaction !== "function" : typeof provider.signTransactionBytes !== "function") throw new Error(CANNOT_PAY);
7780
+ return {
7781
+ publicKey: address,
7782
+ async signTransaction(bytes) {
7783
+ const current = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
7784
+ const account = current?.find((a) => a.address === address);
7785
+ if (!connected.has(provider) || !account || accountAddress(current) !== address) throw new Error("Solana wallet account changed; reconnect before paying.");
7786
+ let signed;
7787
+ if ("features" in provider) {
7788
+ if (!provider.chains.includes("solana:mainnet") || account.chains?.length && !account.chains.includes("solana:mainnet")) throw new Error("This wallet account cannot pay on Solana mainnet.");
7789
+ const result = await provider.features["solana:signTransaction"].signTransaction({ account, chain: "solana:mainnet", transaction: new Uint8Array(bytes) });
7790
+ if (result.length !== 1) throw new Error("Wallet returned an invalid Solana signing result.");
7791
+ signed = result[0]?.signedTransaction;
7792
+ } else signed = await provider.signTransactionBytes(new Uint8Array(bytes));
7793
+ if (!(signed instanceof Uint8Array)) throw new Error("Wallet did not return signed transaction bytes.");
7794
+ return new Uint8Array(signed);
7795
+ }
7796
+ };
7797
+ }
7798
+ function onSolanaAccountChange(info, cb) {
7799
+ const provider = source(info);
7800
+ if ("features" in provider) return provider.features["standard:events"]?.on("change", (change) => {
7801
+ if (change.accounts !== void 0) {
7802
+ connected.set(provider, change.accounts);
7803
+ cb(accountAddress(change.accounts));
7804
+ }
7805
+ }) ?? (() => {
7806
+ });
7807
+ const changed = (key) => {
7808
+ const address = validAddress(key);
7809
+ connected.set(provider, address ? [{ address }] : []);
7810
+ cb(address);
7811
+ };
7812
+ const disconnected = () => {
7813
+ connected.delete(provider);
7814
+ cb(null);
7815
+ };
7816
+ provider.on?.("accountChanged", changed);
7817
+ provider.on?.("connect", changed);
7818
+ provider.on?.("disconnect", disconnected);
7819
+ return () => {
7820
+ const off = provider.off ?? provider.removeListener;
7821
+ off?.call(provider, "accountChanged", changed);
7822
+ off?.call(provider, "connect", changed);
7823
+ off?.call(provider, "disconnect", disconnected);
7824
+ };
7825
+ }
7826
+
7827
+ // src/react/hooks/useSolanaWallet.ts
7828
+ var STORAGE_KEY = "sg-solana-wallet";
7829
+ function remember(name) {
7830
+ try {
7831
+ if (name) window.localStorage.setItem(STORAGE_KEY, name);
7832
+ else window.localStorage.removeItem(STORAGE_KEY);
7833
+ } catch {
7834
+ }
7835
+ }
7836
+ function remembered() {
7837
+ try {
7838
+ return window.localStorage.getItem(STORAGE_KEY);
7839
+ } catch {
7840
+ return null;
7841
+ }
7842
+ }
7843
+ var INITIAL = { address: null, walletName: null, status: "idle", error: null };
7844
+ function useSolanaWallet(provider) {
7845
+ const override = react.useMemo(() => null, [provider]);
7846
+ const [discovered, setDiscovered] = react.useState(discoverSolanaWallets);
7847
+ const wallets = react.useMemo(() => discovered, [provider, override, discovered]);
7848
+ const [state, setState] = react.useState(INITIAL);
7849
+ const active = react.useRef(null);
7850
+ const unsubscribe = react.useRef(() => {
7851
+ });
7852
+ const generation = react.useRef(0);
7853
+ const attempted = react.useRef(false);
7854
+ react.useEffect(() => {
7855
+ attempted.current = false;
7856
+ setState(INITIAL);
7857
+ return () => {
7858
+ generation.current += 1;
7859
+ unsubscribe.current();
7860
+ active.current = null;
7861
+ };
7862
+ }, [provider]);
7863
+ react.useEffect(() => watchSolanaWallets(setDiscovered), [provider]);
7864
+ const runConnect = react.useCallback(async (info, silent = false) => {
7865
+ const request = ++generation.current;
7866
+ unsubscribe.current();
7867
+ active.current = null;
7868
+ setState({ ...INITIAL, status: "connecting" });
7869
+ try {
7870
+ const address = await connectSolanaWallet(info, { silent });
7871
+ if (request !== generation.current) return;
7872
+ active.current = info;
7873
+ unsubscribe.current = onSolanaAccountChange(info, (next) => {
7874
+ if (request !== generation.current) return;
7875
+ setState({ address: next, walletName: next ? info.name : null, status: next ? "connected" : "idle", error: null });
7876
+ if (!next) {
7877
+ generation.current += 1;
7878
+ unsubscribe.current();
7879
+ active.current = null;
7880
+ remember(null);
7881
+ }
7882
+ });
7883
+ setState({ address, walletName: info.name, status: "connected", error: null });
7884
+ remember(info.name);
7885
+ return address;
7886
+ } catch (error) {
7887
+ if (request === generation.current) setState(silent ? INITIAL : {
7888
+ ...INITIAL,
7889
+ status: "error",
7890
+ error: error instanceof Error ? error.message : "Could not connect a Solana wallet."
7891
+ });
7892
+ }
7893
+ }, []);
7894
+ react.useEffect(() => {
7895
+ if (attempted.current || active.current) return;
7896
+ const name = remembered();
7897
+ const info = wallets.find((wallet) => connectedSolanaAddress(wallet)) ?? (name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : void 0);
7898
+ if (!info) return;
7899
+ attempted.current = true;
7900
+ void runConnect(info, true);
7901
+ }, [wallets, runConnect]);
7902
+ const connect = react.useCallback(async (name) => {
7903
+ if (!name && wallets.length > 1) return wallets;
7904
+ attempted.current = true;
7905
+ const info = name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : wallets[0];
7906
+ if (!info) {
7907
+ setState({ ...INITIAL, status: "error", error: name ? "Solana wallet is not available." : "No Solana wallet found." });
7908
+ return;
7909
+ }
7910
+ return runConnect(info);
7911
+ }, [wallets, runConnect]);
7912
+ const disconnect = react.useCallback(async () => {
7913
+ attempted.current = true;
7914
+ generation.current += 1;
7915
+ unsubscribe.current();
7916
+ const info = active.current;
7917
+ active.current = null;
7918
+ setState(INITIAL);
7919
+ remember(null);
7920
+ if (info) {
7921
+ try {
7922
+ await disconnectSolanaWallet(info);
7923
+ } catch {
7924
+ }
7925
+ }
7926
+ }, []);
7927
+ return { ...state, wallets, connect, disconnect };
7928
+ }
7929
+
7930
+ // src/react/hooks/useRecipient.ts
7931
+ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
7932
+ const recipientFamily = isSolanaChainId(destinationChainId) ? "solana" : "evm";
7933
+ const own = useSolanaWallet();
7934
+ const wallet = opts.solanaWallet ?? own;
7935
+ const [custom, setCustom] = react.useState({});
7936
+ const [open, setOpen] = react.useState(false);
7937
+ const triggerRef = react.useRef(null);
7938
+ const evmManaged = recipientFamily === "evm" && Boolean(opts.sourceIsSolana);
7939
+ const managed = hostRecipient === void 0 && (recipientFamily === "solana" || evmManaged);
7940
+ const error = hostRecipient === void 0 ? null : recipientFamily === "solana" && !isSolanaAddress(hostRecipient) ? "The configured recipient is not a Solana address." : evmManaged && !isAddress(hostRecipient) ? "The configured recipient is not an EVM address." : null;
7941
+ const recipient2 = hostRecipient !== void 0 ? hostRecipient : recipientFamily === "solana" ? custom.solana || wallet.address || void 0 : evmManaged ? custom.evm || opts.evm?.account || void 0 : void 0;
7942
+ const missing = managed && !recipient2;
7943
+ const familyWallet = recipientFamily === "solana" ? { address: wallet.address, wallets: wallet.wallets, connecting: wallet.status === "connecting", error: wallet.error } : { address: opts.evm?.account ?? null, wallets: [], connecting: Boolean(opts.evm?.connecting), error: null };
7944
+ const close = () => {
7945
+ setOpen(false);
7946
+ requestAnimationFrame(() => triggerRef.current?.focus());
7947
+ };
7948
+ const selectAddress = (address) => {
7949
+ setCustom((prev) => ({ ...prev, [recipientFamily]: address }));
7950
+ close();
7951
+ };
7952
+ const connect = async (name) => {
7953
+ if (recipientFamily === "evm") {
7954
+ if (opts.evm?.account) selectAddress("");
7955
+ else opts.evm?.connect();
7956
+ return;
7957
+ }
7958
+ if (wallet.address && !name) {
7959
+ selectAddress("");
7960
+ return;
7961
+ }
7962
+ if (!name && wallet.wallets.length !== 1) {
7963
+ setOpen(true);
7964
+ return;
7965
+ }
7966
+ const address = await wallet.connect(name);
7967
+ if (typeof address === "string") selectAddress("");
7968
+ else setOpen(true);
7969
+ };
7970
+ const recipientFor = (account) => recipientFamily === "solana" || evmManaged ? recipient2 || "" : hostRecipient || account;
7971
+ return { recipientFamily, recipient: recipient2, recipientFor, managed, missing, error, wallet, familyWallet, open: open && managed, show: () => setOpen(true), close, selectAddress, connect, triggerRef };
7972
+ }
7973
+ var short = (address) => `${address.slice(0, 4)}\u2026${address.slice(-4)}`;
7974
+ function RecipientNote({ state, disabled }) {
7975
+ if (state.error) return /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: state.error });
7976
+ if (!state.managed) return null;
7977
+ const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
7978
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", justifyContent: "center", gap: 6, marginTop: 10, fontSize: 13, color: "var(--sg-text-muted)", flexWrap: "wrap" }, children: [
7979
+ state.recipient ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
7980
+ "To ",
7981
+ /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", title: state.recipient, style: { color: "var(--sg-text)" }, children: short(state.recipient) }),
7982
+ " on ",
7983
+ family,
7984
+ " \xB7 "
7985
+ ] }) : null,
7986
+ /* @__PURE__ */ jsxRuntime.jsx("button", { ref: state.triggerRef, type: "button", className: "sg-cp-link", onClick: state.show, disabled, "aria-haspopup": "dialog", children: state.recipient ? "Change" : "Send to a different address" })
7987
+ ] });
7988
+ }
7989
+ function RecipientSheet({ state, symbol }) {
7990
+ const [draft, setDraft] = react.useState(state.recipient ?? "");
7991
+ const id = react.useId();
7992
+ const inputRef = react.useRef(null);
7993
+ const sheetRef = react.useRef(null);
7994
+ const closeRef = react.useRef(state.close);
7995
+ closeRef.current = state.close;
7996
+ const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
7997
+ const valid = state.recipientFamily === "solana" ? isSolanaAddress(draft) : /^0x[0-9a-fA-F]{40}$/.test(draft.trim());
7998
+ const invalid = Boolean(draft.trim()) && !valid;
7999
+ const noWallet = state.recipientFamily === "solana" && !state.familyWallet.address && !state.familyWallet.wallets.length;
8000
+ react.useEffect(() => {
8001
+ (noWallet ? inputRef : sheetRef).current?.focus();
8002
+ const onKey = (event) => {
8003
+ if (event.key === "Escape") {
8004
+ event.stopPropagation();
8005
+ closeRef.current();
8006
+ }
8007
+ };
8008
+ document.addEventListener("keydown", onKey, true);
8009
+ return () => document.removeEventListener("keydown", onKey, true);
8010
+ }, [noWallet]);
8011
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet", role: "dialog", "aria-modal": "true", "aria-label": `${family} recipient`, ref: sheetRef, tabIndex: -1, children: [
8012
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet-head", children: [
8013
+ /* @__PURE__ */ jsxRuntime.jsxs("h4", { className: "sg-cp-sheet-title", children: [
8014
+ family,
8015
+ " recipient"
8016
+ ] }),
8017
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cp-close", onClick: state.close, "aria-label": "Close recipient", children: /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m6 6 12 12M18 6 6 18", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }) }) })
8018
+ ] }),
8019
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-sheet-body", children: [
8020
+ /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cp-card", children: [
8021
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", style: { margin: "0 0 12px" }, children: [
8022
+ symbol,
8023
+ " is delivered to a ",
8024
+ family,
8025
+ " wallet. Your EVM wallet stays the owner of the order and can cancel it."
8026
+ ] }),
8027
+ /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: () => noWallet ? inputRef.current?.focus() : void state.connect(), busy: state.familyWallet.connecting, children: state.familyWallet.address ? `Use ${short(state.familyWallet.address)}` : `Connect ${family} wallet` }),
8028
+ !state.familyWallet.address && state.familyWallet.wallets.length > 1 ? state.familyWallet.wallets.map((wallet) => /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => void state.connect(wallet.name), disabled: state.familyWallet.connecting, children: wallet.name }, wallet.name)) : null,
8029
+ noWallet ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cp-summary-sub", children: [
8030
+ "No ",
8031
+ family,
8032
+ " wallet found. Enter a ",
8033
+ family,
8034
+ " address instead."
8035
+ ] }) : null,
8036
+ state.familyWallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: state.familyWallet.error }) : null
8037
+ ] }),
8038
+ /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cp-card", children: [
8039
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-field", style: { margin: 0 }, children: [
8040
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "sg-label", htmlFor: id, children: "Send to a different address" }),
8041
+ /* @__PURE__ */ jsxRuntime.jsx(
8042
+ "input",
8043
+ {
8044
+ ref: inputRef,
8045
+ id,
8046
+ className: "sg-input sg-mono",
8047
+ style: { fontSize: 14, padding: "12px 14px", border: "1px solid var(--sg-border)", borderRadius: "var(--sg-radius-control)", width: "100%", boxSizing: "border-box", background: "var(--sg-bg)" },
8048
+ placeholder: `${family} recipient address`,
8049
+ "aria-label": `${family} recipient address`,
8050
+ "aria-invalid": invalid || void 0,
8051
+ "aria-describedby": `${id}-help${invalid ? ` ${id}-error` : ""}`,
8052
+ value: draft,
8053
+ onChange: (event) => setDraft(event.target.value),
8054
+ spellCheck: false
8055
+ }
8056
+ )
8057
+ ] }),
8058
+ invalid ? /* @__PURE__ */ jsxRuntime.jsx("div", { id: `${id}-error`, children: /* @__PURE__ */ jsxRuntime.jsxs(StatusPanel, { tone: "error", children: [
8059
+ "Not a valid ",
8060
+ family,
8061
+ " address."
8062
+ ] }) }) : null,
8063
+ /* @__PURE__ */ jsxRuntime.jsx("p", { id: `${id}-help`, className: "sg-cp-summary-sub", style: { margin: "8px 0 12px" }, children: "Double-check it: a payment sent to a wrong address cannot be recovered." }),
8064
+ /* @__PURE__ */ jsxRuntime.jsx(Button, { disabled: !valid, onClick: () => state.selectAddress(draft.trim()), children: "Use this address" })
8065
+ ] })
8066
+ ] })
8067
+ ] });
8068
+ }
6044
8069
  var IDENTITY_KEY_PREFIX = "sg:link:v1:";
6045
8070
  var LEGACY_IDENTITY_KEY = "zd-link-identity";
6046
8071
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
@@ -6055,10 +8080,10 @@ function storage() {
6055
8080
  return null;
6056
8081
  }
6057
8082
  }
6058
- function parseIdentity(raw) {
6059
- if (!raw) return null;
8083
+ function parseIdentity(raw2) {
8084
+ if (!raw2) return null;
6060
8085
  try {
6061
- const p = JSON.parse(raw);
8086
+ const p = JSON.parse(raw2);
6062
8087
  if (!p || typeof p !== "object") return null;
6063
8088
  const walletAddress = typeof p.walletAddress === "string" ? p.walletAddress : "";
6064
8089
  if (!ADDRESS_RE.test(walletAddress)) return null;
@@ -6398,14 +8423,17 @@ function PaymentIsland(props) {
6398
8423
  const exQuotable = !rampMode && exAmountValid && !exOverLimit && Boolean(exFromChainId && exFromAsset && exToChainId && exToAsset);
6399
8424
  const payFundingAssets = props.fundingAssets?.length ? props.fundingAssets : ["USDC", "USDT", "USDE"];
6400
8425
  const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${payFundingAssets.join(",")}`;
6401
- const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${props.recipient ?? ""}`;
8426
+ const recipientState = useRecipient(isPay ? null : exToChainId ?? null, props.recipient);
8427
+ const recipient2 = recipientState.recipient;
8428
+ const needsRecipient = !isPay && (recipientState.missing || !!recipientState.error);
8429
+ const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${recipient2 ?? ""}`;
6402
8430
  const flow = useFlow({
6403
8431
  engine,
6404
8432
  wallet,
6405
8433
  kind: isPay ? "payment" : "swap",
6406
8434
  // Bank settlement parks the card, so gate the network work off too — otherwise the island would
6407
8435
  // quote (and fire onQuote) for a payment whose CTA it never shows.
6408
- enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable,
8436
+ enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable && !needsRecipient,
6409
8437
  paramsKey: isPay ? payParamsKey : exParamsKey,
6410
8438
  loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
6411
8439
  chainId,
@@ -6417,11 +8445,11 @@ function PaymentIsland(props) {
6417
8445
  fromToken: exFromAsset,
6418
8446
  toToken: exToAsset,
6419
8447
  amountIn: normEx,
6420
- recipient: props.recipient
8448
+ recipient: recipient2
6421
8449
  },
6422
8450
  payer
6423
8451
  ),
6424
- recipientFor: (account) => isPay ? props.recipient : props.recipient || account,
8452
+ recipientFor: (account) => isPay ? props.recipient : recipientState.recipientFor(account),
6425
8453
  onQuote: config.onQuote,
6426
8454
  onSuccess: config.onSuccess,
6427
8455
  onError: config.onError
@@ -6513,27 +8541,27 @@ function PaymentIsland(props) {
6513
8541
  }, [isPay, exProduct, catalogue, exSourceTokens, exchangeTokens, props.defaultFromAsset, props.defaultToAsset]);
6514
8542
  const exDestinationStates = react.useMemo(() => {
6515
8543
  if (!catalogue?.ready) return void 0;
6516
- const states = {};
8544
+ const states2 = {};
6517
8545
  for (const token of catalogue.tokens) {
6518
8546
  const key = balanceKey(Number(token.chainId), token.address);
6519
8547
  const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
6520
8548
  if (measured) {
6521
- states[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
8549
+ states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
6522
8550
  continue;
6523
8551
  }
6524
8552
  const verdict = destinationAvailability(token, catalogue, exFromToken);
6525
8553
  if (verdict === "available") {
6526
8554
  const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
6527
- if (limit) states[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
8555
+ if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
6528
8556
  continue;
6529
8557
  }
6530
- states[key] = {
8558
+ states2[key] = {
6531
8559
  disabled: true,
6532
8560
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
6533
8561
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
6534
8562
  };
6535
8563
  }
6536
- return states;
8564
+ return states2;
6537
8565
  }, [catalogue, exFromToken]);
6538
8566
  const exFromBal = exFrom && exFromToken ? exBalances[balanceKey(exFrom.chainId, exFromToken.address)] : void 0;
6539
8567
  const fundingTokens = react.useMemo(() => {
@@ -6739,12 +8767,12 @@ function PaymentIsland(props) {
6739
8767
  const activeStep = flow.steps.find((s) => s.state === "active");
6740
8768
  const liveMsg = flow.status === "loading" ? isPay ? "Finding the best way to pay." : "Finding the best route." : flow.status === "submitting" ? `${activeStep?.label ?? (isPay ? "Processing your payment" : `Processing your ${verb.present.toLowerCase()}`)} \u2014 in progress.` : flow.status === "success" || flow.status === "pending" ? flow.verdict?.status === "confirmed" ? isPay ? "Payment confirmed on-chain \u2014 the merchant has been settled." : `${verb.past} \u2014 confirmed on-chain.` : isPay ? "Payment sent \u2014 confirmation is still pending." : "Submitted \u2014 confirmation is still pending." : "";
6741
8769
  const loading = flow.status === "loading";
6742
- const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel);
8770
+ const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel) && !needsRecipient;
6743
8771
  const ctaLabel = submitting ? isPay ? "Paying\u2026" : kind === "swap" ? "Swapping\u2026" : "Exchanging\u2026" : flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall ? flow.nativeShortfall : loading ? "Getting a price\u2026" : isPay ? sel && selectedVisible ? `Pay ${sel.source.payAmount} ${sel.source.ticker || sel.source.asset}` : "Pay" : kind === "swap" ? "Swap" : "Exchange";
6744
8772
  const exPct = (p) => {
6745
8773
  if (!exFromBal || !exFromToken) return;
6746
- const raw = BigInt(exFromBal.raw);
6747
- setExAmount(formatUnits(p === 100 ? raw : raw * BigInt(p) / 100n, assetDecimals(exFromToken)));
8774
+ const raw2 = BigInt(exFromBal.raw);
8775
+ setExAmount(formatUnits(p === 100 ? raw2 : raw2 * BigInt(p) / 100n, assetDecimals(exFromToken)));
6748
8776
  };
6749
8777
  const exGatewayAmountError = !isPay && exQuotable && flow.status === "error" && flow.steps.length === 0 ? flow.fieldError : null;
6750
8778
  const exAmountError = exOverLimit && exLaneLimit ? laneLimitError(exLaneLimit, exLimitSymbol) : exGatewayAmountError;
@@ -6821,6 +8849,8 @@ function PaymentIsland(props) {
6821
8849
  }
6822
8850
  }
6823
8851
  );
8852
+ } else if (recipientState.open && !isPay) {
8853
+ body = /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: destTicker });
6824
8854
  } else if (rampMode) {
6825
8855
  body = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-soonpanel", children: [
6826
8856
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-soonpanel-title", children: mode === "onramp" ? "Buying with fiat is coming soon" : "Cashing out to fiat is coming soon" }),
@@ -6871,7 +8901,7 @@ function PaymentIsland(props) {
6871
8901
  ] }),
6872
8902
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
6873
8903
  confirmed ? "Confirmed on-chain" : "Confirmation pending",
6874
- isPay && props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
8904
+ (flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : ""
6875
8905
  ] })
6876
8906
  ] }),
6877
8907
  !identityMatchesWallet ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-remember", children: [
@@ -6987,16 +9017,23 @@ function PaymentIsland(props) {
6987
9017
  quoteError ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: flow.error || "Couldn't get a price right now." }) : null,
6988
9018
  walletError ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: flow.error || "The wallet could not complete this payment." }) : null,
6989
9019
  submitting || walletError ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { variant: "rich", steps: flow.steps, verdict: flow.verdict }) : null,
6990
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cta-wrap", children: quoteError ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.reload, children: "Try again" }) : walletError ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: payReady ? flow.submit : void 0, disabled: !payReady, children: "Try again" }) : /* @__PURE__ */ jsxRuntime.jsx(
6991
- Button,
6992
- {
6993
- onClick: payReady && !submitting && !flow.insufficient && !flow.nativeShortfall && !loading ? flow.submit : void 0,
6994
- busy: submitting || loading,
6995
- softDisabled: submitting,
6996
- disabled: !submitting && (!payReady || flow.insufficient || !!flow.nativeShortfall || loading),
6997
- children: ctaLabel
6998
- }
6999
- ) })
9020
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
9021
+ recipientState.missing && !isPay && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
9022
+ "Connect ",
9023
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
9024
+ " wallet"
9025
+ ] }) : quoteError ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.reload, children: "Try again" }) : walletError ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: payReady ? flow.submit : void 0, disabled: !payReady, children: "Try again" }) : /* @__PURE__ */ jsxRuntime.jsx(
9026
+ Button,
9027
+ {
9028
+ onClick: payReady && !submitting && !flow.insufficient && !flow.nativeShortfall && !loading ? flow.submit : void 0,
9029
+ busy: submitting || loading,
9030
+ softDisabled: submitting,
9031
+ disabled: !submitting && (!payReady || flow.insufficient || !!flow.nativeShortfall || loading),
9032
+ children: ctaLabel
9033
+ }
9034
+ ),
9035
+ !isPay ? /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null
9036
+ ] })
7000
9037
  ] })
7001
9038
  ] });
7002
9039
  }
@@ -7458,6 +9495,9 @@ function StableGenieSwap(props) {
7458
9495
  const [toChainId, setToChainId] = react.useState(props.defaultToChainId ?? 8453);
7459
9496
  const [toAsset, setToAsset] = react.useState(props.defaultToAsset ?? "USDC");
7460
9497
  const [amount, setAmount] = react.useState(props.defaultAmount ?? "");
9498
+ const recipientState = useRecipient(toChainId, props.recipient);
9499
+ const recipient2 = recipientState.recipient;
9500
+ const needsRecipient = recipientState.missing || !!recipientState.error;
7461
9501
  const [catalogue, setCatalogue] = react.useState(null);
7462
9502
  react.useEffect(() => {
7463
9503
  if (props.variant === "pill") return;
@@ -7487,15 +9527,15 @@ function StableGenieSwap(props) {
7487
9527
  }, [catalogue]);
7488
9528
  const amountValid = /^\d+(\.\d+)?$/.test(amount.replace(",", ".")) && Number(amount.replace(",", ".")) > 0;
7489
9529
  const enabled = amountValid && props.variant !== "pill";
7490
- const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${props.recipient ?? ""}`;
9530
+ const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${recipient2 ?? ""}`;
7491
9531
  const flow = useFlow({
7492
9532
  engine,
7493
9533
  wallet,
7494
9534
  kind: "swap",
7495
- enabled,
9535
+ enabled: enabled && !needsRecipient,
7496
9536
  paramsKey,
7497
- loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient: props.recipient }, payer),
7498
- recipientFor: (account) => props.recipient || account,
9537
+ loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient: recipient2 }, payer),
9538
+ recipientFor: recipientState.recipientFor,
7499
9539
  onQuote: config.onQuote,
7500
9540
  onSuccess: config.onSuccess,
7501
9541
  onError: config.onError
@@ -7538,6 +9578,7 @@ function StableGenieSwap(props) {
7538
9578
  if (hist && wallet.account) {
7539
9579
  return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) });
7540
9580
  }
9581
+ if (recipientState.open) return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: toAsset }) });
7541
9582
  if (flow.status === "success" || flow.status === "pending") {
7542
9583
  return /* @__PURE__ */ jsxRuntime.jsxs(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: [
7543
9584
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
@@ -7549,7 +9590,7 @@ function StableGenieSwap(props) {
7549
9590
  ] }),
7550
9591
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
7551
9592
  flow.verdict?.status === "confirmed" ? "Confirmed on-chain" : "Submitted \u2014 awaiting confirmation",
7552
- props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
9593
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
7553
9594
  ] })
7554
9595
  ] }),
7555
9596
  lastTxOwned ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cta-wrap", children: /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: flow.lastTxEntry }), children: "View transaction" }) }) : null
@@ -7578,11 +9619,169 @@ function StableGenieSwap(props) {
7578
9619
  flow.selected && flow.status !== "loading" ? /* @__PURE__ */ jsxRuntime.jsx(CompliancePanel, { compliance: flow.selected.quote.compliance, direct: flow.selected.state === "DIRECT" }) : null,
7579
9620
  submitting ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { steps: flow.steps }) : null,
7580
9621
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
7581
- !wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.submit, busy: submitting, disabled: !flow.selected || flow.insufficient || !!flow.nativeShortfall || !enabled || flow.status === "loading", children: swapLabel }),
9622
+ !wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : recipientState.missing && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
9623
+ "Connect ",
9624
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
9625
+ " wallet"
9626
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: flow.submit, busy: submitting, disabled: needsRecipient || !flow.selected || flow.insufficient || !!flow.nativeShortfall || !enabled || flow.status === "loading", children: swapLabel }),
9627
+ /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }),
7582
9628
  wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
7583
9629
  ] })
7584
9630
  ] });
7585
9631
  }
9632
+ function keyOf(a) {
9633
+ return `${a.fromSymbol}|${a.toChainId}|${a.toSymbol}|${a.amount}|${a.owner ?? ""}|${a.payer ?? ""}|${a.recipient ?? ""}`;
9634
+ }
9635
+ function useSolanaSourceFlow(args) {
9636
+ const { engine, enabled, fromSymbol, fromMint, toChainId, toSymbol, amount, owner, payer, recipient: recipient2 } = args;
9637
+ const [status, setStatus] = react.useState("idle");
9638
+ const [preview, setPreview] = react.useState(null);
9639
+ const [plan, setPlan] = react.useState(null);
9640
+ const [error, setError] = react.useState(null);
9641
+ const [balanceRaw, setBalanceRaw] = react.useState(void 0);
9642
+ const [cost, setCost] = react.useState(null);
9643
+ const [progress, setProgress] = react.useState(null);
9644
+ const [signature, setSignature] = react.useState(null);
9645
+ const [lastTxEntry, setLastTxEntry] = react.useState(null);
9646
+ const [sent, setSent] = react.useState(null);
9647
+ const [nonce, setNonce] = react.useState(0);
9648
+ const req = react.useRef(0);
9649
+ const busy = react.useRef(false);
9650
+ const latest = react.useRef(args);
9651
+ latest.current = args;
9652
+ const planKey = react.useRef(null);
9653
+ const planArgs = react.useRef(null);
9654
+ const changedWhileBusy = react.useRef(false);
9655
+ const addressed = Boolean(owner && payer && recipient2);
9656
+ const key = keyOf(args);
9657
+ react.useEffect(() => {
9658
+ const id = ++req.current;
9659
+ if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
9660
+ setStatus("idle");
9661
+ setPreview(null);
9662
+ setPlan(null);
9663
+ setError(null);
9664
+ setCost(null);
9665
+ return;
9666
+ }
9667
+ if (busy.current) {
9668
+ changedWhileBusy.current = true;
9669
+ return;
9670
+ }
9671
+ setStatus("quoting");
9672
+ planKey.current = null;
9673
+ planArgs.current = null;
9674
+ setError(null);
9675
+ setPlan(null);
9676
+ setCost(null);
9677
+ const timer2 = setTimeout(async () => {
9678
+ try {
9679
+ if (!addressed) {
9680
+ const next = await engine.previewSolanaSource({ toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount });
9681
+ if (id !== req.current) return;
9682
+ setPreview(next);
9683
+ setStatus("ready");
9684
+ return;
9685
+ }
9686
+ const input = { toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount, owner, sender: payer, recipient: recipient2 };
9687
+ const quoted = await engine.quoteSolanaSource(input);
9688
+ const built = await engine.buildSolanaSourcePlan(input, quoted);
9689
+ if (id !== req.current) return;
9690
+ planKey.current = key;
9691
+ planArgs.current = { ...latest.current };
9692
+ setPreview(quoted);
9693
+ setPlan(built);
9694
+ setStatus("ready");
9695
+ engine.simulateSolanaCost(built).then(
9696
+ (c) => id === req.current && setCost(c),
9697
+ () => id === req.current && setCost(null)
9698
+ );
9699
+ } catch (e) {
9700
+ if (id !== req.current) return;
9701
+ setStatus("error");
9702
+ setError(e instanceof Error ? e.message : String(e));
9703
+ }
9704
+ }, 350);
9705
+ return () => clearTimeout(timer2);
9706
+ }, [engine, enabled, key, addressed, nonce]);
9707
+ react.useEffect(() => {
9708
+ let alive = true;
9709
+ setBalanceRaw(void 0);
9710
+ if (!enabled || !payer || !fromMint) return;
9711
+ engine.readSolanaBalance(payer, fromMint).then((b) => {
9712
+ if (alive) setBalanceRaw(b);
9713
+ });
9714
+ return () => {
9715
+ alive = false;
9716
+ };
9717
+ }, [engine, enabled, payer, fromMint]);
9718
+ const needsPreparation = plan ? solanaPlanNeedsPreparation(plan) : false;
9719
+ const run = react.useCallback(async () => {
9720
+ const current = plan;
9721
+ if (!current || busy.current) return;
9722
+ if (planKey.current !== keyOf(latest.current)) {
9723
+ setError("The order changed; review the new quote before signing.");
9724
+ setNonce((n) => n + 1);
9725
+ return;
9726
+ }
9727
+ busy.current = true;
9728
+ let broadcast = false;
9729
+ setError(null);
9730
+ setStatus(needsPreparation ? "preparing" : "submitting");
9731
+ try {
9732
+ const result = await engine.executeSolanaPlanStaged({ plan: current, signer: latest.current.signer(), onProgress: setProgress });
9733
+ if (result.status === "prepared") {
9734
+ setStatus("prepared");
9735
+ return;
9736
+ }
9737
+ const a = planArgs.current ?? latest.current;
9738
+ broadcast = true;
9739
+ setSent({ receive: current.preview.receive, toTicker: a.toTicker, recipient: a.recipient ?? "" });
9740
+ setSignature(result.signature);
9741
+ setStatus("sent");
9742
+ const entry = engine.recordTransaction({
9743
+ kind: "swap",
9744
+ hash: result.signature,
9745
+ txKind: "submitOrder",
9746
+ chainId: SOLANA_CHAIN_ID,
9747
+ chainName: a.chainName,
9748
+ fromAsset: a.fromSymbol ?? "",
9749
+ toAsset: a.toSymbol ?? "",
9750
+ fromTicker: a.fromTicker,
9751
+ toTicker: a.toTicker,
9752
+ payAmount: a.amount,
9753
+ receiveAmount: current.preview.receive,
9754
+ account: a.owner ?? "",
9755
+ recipient: a.recipient ?? "",
9756
+ settlement: "escrow",
9757
+ status: "submitted"
9758
+ });
9759
+ setLastTxEntry(entry.hash ? entry : null);
9760
+ appendTxHistory(a.owner, entry);
9761
+ } catch (e) {
9762
+ const err2 = e instanceof Error ? e : new Error(String(e));
9763
+ setStatus("failed");
9764
+ setError(err2.message);
9765
+ latest.current.onError?.(err2);
9766
+ } finally {
9767
+ busy.current = false;
9768
+ if (changedWhileBusy.current) {
9769
+ changedWhileBusy.current = false;
9770
+ if (!broadcast && planKey.current !== keyOf(latest.current)) setNonce((n) => n + 1);
9771
+ }
9772
+ }
9773
+ }, [engine, plan, needsPreparation]);
9774
+ const insufficient = balanceRaw !== void 0 && plan ? balanceRaw < BigInt(plan.expected.bidTokenAmount) : false;
9775
+ const solShort = cost ? !cost.sufficient : false;
9776
+ const reset = react.useCallback(() => {
9777
+ setSignature(null);
9778
+ setLastTxEntry(null);
9779
+ setSent(null);
9780
+ setProgress(null);
9781
+ setNonce((n) => n + 1);
9782
+ }, []);
9783
+ return { status, preview, plan, error, balanceRaw, cost, progress, signature, lastTxEntry, sent, addressed, needsPreparation, insufficient, solShort, run, reset };
9784
+ }
7586
9785
  function QuoteSheet(props) {
7587
9786
  const sheetRef = react.useRef(null);
7588
9787
  const onCloseRef = react.useRef(props.onClose);
@@ -7691,7 +9890,7 @@ function ExchangeCard(props) {
7691
9890
  react.useEffect(() => {
7692
9891
  if (isPill) return;
7693
9892
  let alive = true;
7694
- engine.fetchCatalogue(allowed, product).then((next) => {
9893
+ engine.fetchCatalogue(allowed, product, { solanaSources: true }).then((next) => {
7695
9894
  if (alive) setCatalogue(next);
7696
9895
  });
7697
9896
  return () => {
@@ -7724,6 +9923,16 @@ function ExchangeCard(props) {
7724
9923
  () => props.defaultToChainId && props.defaultToAsset ? { chainId: props.defaultToChainId, symbol: symbolKey(props.defaultToAsset) } : null
7725
9924
  );
7726
9925
  const [amount, setAmount] = react.useState(props.defaultAmount ?? "");
9926
+ const solanaWallet = useSolanaWallet();
9927
+ const [payerChooser, setPayerChooser] = react.useState(false);
9928
+ const sourceIsSolana = isSolanaChainId(from?.chainId);
9929
+ const recipientState = useRecipient(to?.chainId ?? null, props.recipient, {
9930
+ solanaWallet,
9931
+ sourceIsSolana,
9932
+ evm: { account: wallet.account, connect: wallet.connect, connecting: wallet.connecting }
9933
+ });
9934
+ const recipient2 = recipientState.recipient;
9935
+ const needsRecipient = recipientState.missing || !!recipientState.error;
7727
9936
  const onInputChange = react.useRef(props.onInputChange);
7728
9937
  onInputChange.current = props.onInputChange;
7729
9938
  const fromChainId = from?.chainId ?? null;
@@ -7754,27 +9963,27 @@ function ExchangeCard(props) {
7754
9963
  }, [product, catalogue, sourceTokens, tokens, props.defaultFromAsset, props.defaultToAsset]);
7755
9964
  const destinationStates = react.useMemo(() => {
7756
9965
  if (!catalogue?.ready) return void 0;
7757
- const states = {};
9966
+ const states2 = {};
7758
9967
  for (const token of catalogue.tokens) {
7759
9968
  const key = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
7760
9969
  const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
7761
9970
  if (measured) {
7762
- states[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
9971
+ states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
7763
9972
  continue;
7764
9973
  }
7765
9974
  const verdict = destinationAvailability(token, catalogue, fromToken);
7766
9975
  if (verdict === "available") {
7767
9976
  const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
7768
- if (limit) states[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
9977
+ if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
7769
9978
  continue;
7770
9979
  }
7771
- states[key] = {
9980
+ states2[key] = {
7772
9981
  disabled: true,
7773
9982
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
7774
9983
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
7775
9984
  };
7776
9985
  }
7777
- return states;
9986
+ return states2;
7778
9987
  }, [catalogue, fromToken]);
7779
9988
  const toPickerVisible = react.useMemo(
7780
9989
  () => destinationStates ? toPickerTokens.filter((t) => !destinationStates[`${Number(t.chainId)}:${String(t.address || "").toLowerCase()}`]?.disabled) : toPickerTokens,
@@ -7819,7 +10028,7 @@ function ExchangeCard(props) {
7819
10028
  if (id === balReq.current) setBalances(res);
7820
10029
  });
7821
10030
  }, [engine, wallet.account, tokens]);
7822
- const fromBal = from && fromToken ? balances[balanceKey(from.chainId, fromToken.address)] : void 0;
10031
+ const evmFromBal = from && fromToken ? balances[balanceKey(from.chainId, fromToken.address)] : void 0;
7823
10032
  const [prices, setPrices] = react.useState({});
7824
10033
  react.useEffect(() => {
7825
10034
  if (isPill) return;
@@ -7833,24 +10042,47 @@ function ExchangeCard(props) {
7833
10042
  alive = false;
7834
10043
  };
7835
10044
  }, [engine, from?.symbol, to?.symbol, isPill]);
7836
- const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${props.recipient ?? ""}`;
10045
+ const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${recipient2 ?? ""}`;
7837
10046
  const flow = useFlow({
7838
10047
  engine,
7839
10048
  wallet,
7840
10049
  kind: "swap",
7841
- enabled: quotable && !isPill,
10050
+ enabled: quotable && !isPill && !needsRecipient && !sourceIsSolana,
7842
10051
  paramsKey,
7843
- loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: props.recipient }, payer),
7844
- recipientFor: (account) => props.recipient || account,
10052
+ loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: recipient2 }, payer),
10053
+ recipientFor: recipientState.recipientFor,
7845
10054
  onQuote: config.onQuote,
7846
10055
  onSuccess: config.onSuccess,
7847
10056
  onError: config.onError
7848
10057
  });
10058
+ const solActive = sourceIsSolana && !isPill && !rampMode;
10059
+ const solFlow = useSolanaSourceFlow({
10060
+ engine,
10061
+ enabled: solActive && quotable && !recipientState.error,
10062
+ fromSymbol: from?.symbol ?? null,
10063
+ fromMint: fromToken?.address ?? null,
10064
+ toChainId: to?.chainId ?? null,
10065
+ toSymbol: to ? toSymbol : null,
10066
+ amount: normalizedAmount,
10067
+ owner: wallet.account,
10068
+ payer: solanaWallet.address,
10069
+ recipient: recipient2,
10070
+ signer: () => {
10071
+ const info = solanaWallet.wallets.find((w) => normalizeSolanaWalletName(w.name) === normalizeSolanaWalletName(solanaWallet.walletName ?? ""));
10072
+ if (!info) throw new Error("Connect a Solana wallet to pay from Solana.");
10073
+ return solanaWalletSigner(info);
10074
+ },
10075
+ chainName: "Solana",
10076
+ fromTicker,
10077
+ toTicker,
10078
+ onError: config.onError
10079
+ });
10080
+ const fromBal = solActive ? solFlow.balanceRaw !== void 0 && fromToken ? { ...evmFromBal, raw: solFlow.balanceRaw.toString(), formatted: formatUnits(solFlow.balanceRaw, assetDecimals(fromToken)) } : void 0 : evmFromBal;
7849
10081
  const [preview, setPreview] = react.useState({ status: "idle" });
7850
10082
  const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
7851
10083
  const prevReq = react.useRef(0);
7852
10084
  react.useEffect(() => {
7853
- if (isPill || wallet.account || !quotable) {
10085
+ if (isPill || sourceIsSolana || wallet.account && !needsRecipient || !quotable) {
7854
10086
  prevReq.current += 1;
7855
10087
  setPreview({ status: "idle" });
7856
10088
  return;
@@ -7858,23 +10090,24 @@ function ExchangeCard(props) {
7858
10090
  const id = ++prevReq.current;
7859
10091
  setPreview({ status: "loading" });
7860
10092
  const timer2 = setTimeout(() => {
7861
- engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: props.recipient }).then((data) => {
10093
+ engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: recipient2 }, wallet.account ?? void 0).then((data) => {
7862
10094
  if (id === prevReq.current) setPreview({ status: "ready", data });
7863
10095
  }).catch((e) => {
7864
10096
  if (id === prevReq.current) setPreview({ status: "error", error: e instanceof Error ? e.message : String(e), fieldError: amountFieldError(e) });
7865
10097
  });
7866
10098
  }, 350);
7867
10099
  return () => clearTimeout(timer2);
7868
- }, [engine, wallet.account, quotable, paramsKey, returnedAt2]);
7869
- const connected = Boolean(wallet.account);
7870
- const submitting = flow.status === "submitting";
10100
+ }, [engine, wallet.account, quotable, paramsKey, returnedAt2, needsRecipient, sourceIsSolana]);
10101
+ const connected2 = Boolean(wallet.account);
10102
+ const addressed = connected2 && !needsRecipient;
10103
+ const submitting = solActive ? solFlow.status === "preparing" || solFlow.status === "submitting" : flow.status === "submitting";
7871
10104
  const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
7872
- const quoting = connected ? flow.status === "loading" : preview.status === "loading";
7873
- const quoteError = !quotable ? null : connected ? flow.status === "error" ? flow.error : null : preview.status === "error" ? preview.error ?? "No route." : null;
7874
- const gatewayAmountError = !quoteError ? null : connected ? flow.fieldError : preview.fieldError ?? null;
10105
+ const quoting = solActive ? solFlow.status === "quoting" : addressed ? flow.status === "loading" : preview.status === "loading";
10106
+ const quoteError = !quotable ? null : solActive ? solFlow.status === "error" || solFlow.status === "failed" ? solFlow.error : null : addressed ? flow.status === "error" ? flow.error : null : preview.status === "error" ? preview.error ?? "No route." : null;
10107
+ const gatewayAmountError = !quoteError || solActive ? null : addressed ? flow.fieldError : preview.fieldError ?? null;
7875
10108
  const amountError = overLimit && laneLimit ? laneLimitError(laneLimit, limitSymbol) : gatewayAmountError;
7876
10109
  const amountNote = mode === "exchange" ? amountError || (laneLimit ? laneLimitHint(laneLimit, limitSymbol) : null) : null;
7877
- const receive = connected ? flow.selected?.receive.amount : preview.data?.receive;
10110
+ const receive = solActive ? solFlow.preview?.receive : addressed ? flow.selected?.receive.amount : preview.data?.receive;
7878
10111
  const receiveOutRef = react.useRef(null);
7879
10112
  const receiveSideRef = react.useRef(null);
7880
10113
  const receiveShown = `${receive ?? ""}|${quoting}|${toTicker}`;
@@ -7887,17 +10120,17 @@ function ExchangeCard(props) {
7887
10120
  return void 0;
7888
10121
  }
7889
10122
  }, [toToken]);
7890
- const meta = connected ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
10123
+ const meta = solActive ? solFlow.preview ? { bridge: solFlow.preview.bridge || "ZeroDelta", feeBps: solFlow.preview.feeBps, duration: solFlow.preview.estimatedDuration } : null : addressed ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
7891
10124
  const pct = (p) => {
7892
10125
  if (!fromBal || !fromToken) return;
7893
- const raw = BigInt(fromBal.raw);
7894
- setAmount(formatUnits(p === 100 ? raw : raw * BigInt(p) / 100n, assetDecimals(fromToken)));
10126
+ const raw2 = BigInt(fromBal.raw);
10127
+ setAmount(formatUnits(p === 100 ? raw2 : raw2 * BigInt(p) / 100n, assetDecimals(fromToken)));
7895
10128
  };
7896
10129
  const title = config.title || (mode === "onramp" ? "Buy stablecoins" : mode === "offramp" ? "Cash out" : "Exchange");
7897
10130
  const soonLabel = mode === "onramp" ? "On-ramp coming soon" : "Off-ramp coming soon";
7898
- const quotePaused = connected ? flow.quotePaused : idle2 && preview.status === "ready";
7899
- const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
7900
- const selected = connected ? flow.selected : null;
10131
+ const quotePaused = solActive ? false : addressed ? flow.quotePaused : idle2 && preview.status === "ready";
10132
+ const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected2 && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
10133
+ const selected = addressed ? flow.selected : null;
7901
10134
  const hasQuote = Boolean(quotable && !quoting && !quoteError && receive);
7902
10135
  const nativeWei = (() => {
7903
10136
  try {
@@ -7907,7 +10140,7 @@ function ExchangeCard(props) {
7907
10140
  return 0n;
7908
10141
  }
7909
10142
  })();
7910
- const networkFee = nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
10143
+ const networkFee = solActive ? solFlow.cost ? `~${(solFlow.cost.lamports / 1e9).toFixed(6)} SOL` : "Paid in SOL" : nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
7911
10144
  const eta = durationLabel(meta?.duration);
7912
10145
  const rate = hasQuote && receive && Number(normalizedAmount) > 0 ? (Number(receive) / Number(normalizedAmount)).toFixed(6) : null;
7913
10146
  const rateRows = hasQuote ? [{ label: "Network fee", value: networkFee }, ...eta ? [{ label: "Estimated time", value: eta }] : []] : [];
@@ -7924,8 +10157,8 @@ function ExchangeCard(props) {
7924
10157
  setTo(from);
7925
10158
  };
7926
10159
  const walletSlot = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-head-tools", children: [
7927
- connected ? /* @__PURE__ */ jsxRuntime.jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }) : null,
7928
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-wallet", "data-connected": connected || void 0, onClick: connected ? void 0 : wallet.connect, disabled: wallet.connecting, children: connected ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
10160
+ connected2 ? /* @__PURE__ */ jsxRuntime.jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }) : null,
10161
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-wallet", "data-connected": connected2 || void 0, onClick: connected2 ? void 0 : wallet.connect, disabled: wallet.connecting, children: connected2 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
7929
10162
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
7930
10163
  " ",
7931
10164
  shortAddress2(wallet.account)
@@ -7973,7 +10206,7 @@ function ExchangeCard(props) {
7973
10206
  }
7974
10207
  );
7975
10208
  const rateBox = (open) => /* @__PURE__ */ jsxRuntime.jsx(RateBox, { rate, fromSymbol: from?.symbol ?? "", fromLogoUrl: fromToken?.logoUrl, toTicker, rows: rateRows, defaultOpen: open, paused: quotePaused });
7976
- const sheetBody = sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
10209
+ const sheetBody = recipientState.open ? /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: toTicker }) : sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
7977
10210
  QuoteSheet,
7978
10211
  {
7979
10212
  onClose: closeSheet,
@@ -7990,8 +10223,33 @@ function ExchangeCard(props) {
7990
10223
  legs: selected && selected.legs.length > 1 ? selected.legs : void 0
7991
10224
  }
7992
10225
  ) : null;
10226
+ const connectPayer = async () => {
10227
+ const result = await solanaWallet.connect();
10228
+ setPayerChooser(Array.isArray(result) && result.length > 1);
10229
+ };
10230
+ const solanaCta = !solanaWallet.address ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
10231
+ /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: () => void connectPayer(), busy: solanaWallet.status === "connecting", children: "Connect Solana wallet" }),
10232
+ payerChooser ? solanaWallet.wallets.map((w) => /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => void solanaWallet.connect(w.name).then(() => setPayerChooser(false)), disabled: solanaWallet.status === "connecting", children: w.name }, w.name)) : null,
10233
+ !solanaWallet.wallets.length ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", children: "No Solana wallet found. Install Phantom, Solflare or Backpack to pay from Solana." }) : null
10234
+ ] }) : !connected2 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
10235
+ /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect EVM wallet" }),
10236
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "8px 0 0" }, children: "Your EVM wallet owns the order and can cancel it." })
10237
+ ] }) : recipientState.missing ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.familyWallet.connecting, children: [
10238
+ "Connect ",
10239
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
10240
+ " wallet"
10241
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(
10242
+ Button,
10243
+ {
10244
+ onClick: solFlow.run,
10245
+ busy: submitting,
10246
+ disabled: !quotable || !cryptoReady || !!recipientState.error || !solFlow.plan || solFlow.insufficient || solFlow.solShort || solFlow.status === "quoting",
10247
+ children: solFlow.status === "preparing" ? "Preparing order\u2026" : solFlow.status === "submitting" ? "Submitting\u2026" : solFlow.insufficient ? "Insufficient balance" : solFlow.solShort ? "Not enough SOL for network fees" : solFlow.status === "failed" ? "Try again" : !solFlow.plan ? "Exchange" : solFlow.needsPreparation ? "Continue in wallet" : "Submit"
10248
+ }
10249
+ );
10250
+ const solanaSteps = solActive && solFlow.plan && connected2 && solanaWallet.address ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "0 0 8px" }, "data-testid": "solana-steps", children: solFlow.needsPreparation || solFlow.status === "preparing" ? "Prepare order \xB7 Submit \xB7 Track" : solFlow.status === "prepared" ? "Prepare order \u2713 \xB7 Submit \xB7 Track" : "Submit \xB7 Track" }) : null;
7993
10251
  let body;
7994
- if (hist && connected) {
10252
+ if (hist && connected2) {
7995
10253
  body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
7996
10254
  } else if (view === "from" || view === "to") {
7997
10255
  const isFrom = view === "from";
@@ -8016,6 +10274,26 @@ function ExchangeCard(props) {
8016
10274
  );
8017
10275
  } else if (sheetBody && !wide) {
8018
10276
  body = sheetBody;
10277
+ } else if (solActive && solFlow.status === "sent") {
10278
+ body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
10279
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
10280
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-success-check", "data-pending": "true", children: /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph5, {}) }),
10281
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-amt sg-mono", children: [
10282
+ solFlow.sent?.receive ?? receive,
10283
+ " ",
10284
+ solFlow.sent?.toTicker ?? toTicker
10285
+ ] }),
10286
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
10287
+ "Submitted on Solana \u2014 ZeroDelta delivers it",
10288
+ solFlow.sent?.recipient ? ` \xB7 ${shortAddress2(solFlow.sent.recipient)}` : ""
10289
+ ] })
10290
+ ] }),
10291
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
10292
+ solFlow.signature ? /* @__PURE__ */ jsxRuntime.jsx("a", { className: "sg-btn sg-btn-ghost", href: `https://solscan.io/tx/${solFlow.signature}`, target: "_blank", rel: "noopener noreferrer", children: "View on Solscan" }) : null,
10293
+ solFlow.lastTxEntry && connected2 ? /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: solFlow.lastTxEntry }), children: "View transaction" }) : null,
10294
+ /* @__PURE__ */ jsxRuntime.jsx(Button, { variant: "ghost", onClick: solFlow.reset, children: "Start a new exchange" })
10295
+ ] })
10296
+ ] });
8019
10297
  } else if (flow.status === "success" || flow.status === "pending") {
8020
10298
  body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
8021
10299
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success", children: [
@@ -8027,7 +10305,7 @@ function ExchangeCard(props) {
8027
10305
  ] }),
8028
10306
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", children: [
8029
10307
  flow.verdict?.status === "confirmed" ? "Confirmed on-chain" : "Submitted \u2014 awaiting confirmation",
8030
- props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
10308
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
8031
10309
  ] })
8032
10310
  ] }),
8033
10311
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
@@ -8038,8 +10316,19 @@ function ExchangeCard(props) {
8038
10316
  } else {
8039
10317
  const payToken = mode === "onramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You pay", symbol: from?.symbol ?? null, chainId: from?.chainId ?? null, token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") });
8040
10318
  const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, token: toToken, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") });
8041
- const cta = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
8042
- !connected && !rampMode ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: rampMode ? void 0 : flow.submit, busy: submitting, disabled: rampMode || !quotable || !cryptoReady || connected && (!flow.selected || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading"), children: ctaLabel }),
10319
+ const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
10320
+ solanaSteps,
10321
+ solanaCta,
10322
+ /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }),
10323
+ solanaWallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: solanaWallet.error }) : null,
10324
+ wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
10325
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
10326
+ !connected2 && !rampMode ? /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : recipientState.missing && !rampMode && !submitting ? /* @__PURE__ */ jsxRuntime.jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
10327
+ "Connect ",
10328
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
10329
+ " wallet"
10330
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: rampMode ? void 0 : flow.submit, busy: submitting, disabled: needsRecipient || rampMode || !quotable || !cryptoReady || connected2 && (!flow.selected || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading"), children: ctaLabel }),
10331
+ !rampMode ? /* @__PURE__ */ jsxRuntime.jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null,
8043
10332
  wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
8044
10333
  ] });
8045
10334
  const notices = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
@@ -8184,5 +10473,10 @@ function mount(el, config) {
8184
10473
  root.render(react.createElement(Comp, variant === "rwa" ? { ...props, product: "rwa" } : props));
8185
10474
  return () => root.unmount();
8186
10475
  }
10476
+ /*! Bundled license information:
10477
+
10478
+ @noble/ed25519/index.js:
10479
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
10480
+ */
8187
10481
 
8188
10482
  exports.mount = mount;