@glacislabs/stablegenie-zerodelta 4.12.0 → 4.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,575 @@
1
1
  'use strict';
2
2
 
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // node_modules/@noble/ed25519/index.js
14
+ var ed25519_exports = {};
15
+ __export(ed25519_exports, {
16
+ Point: () => Point,
17
+ etc: () => etc,
18
+ getPublicKey: () => getPublicKey,
19
+ getPublicKeyAsync: () => getPublicKeyAsync,
20
+ hash: () => hash,
21
+ hashes: () => hashes,
22
+ keygen: () => keygen,
23
+ keygenAsync: () => keygenAsync,
24
+ sign: () => sign,
25
+ signAsync: () => signAsync,
26
+ utils: () => utils,
27
+ verify: () => verify,
28
+ verifyAsync: () => verifyAsync
29
+ });
30
+ 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;
31
+ var init_ed25519 = __esm({
32
+ "node_modules/@noble/ed25519/index.js"() {
33
+ ed25519_CURVE = {
34
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
35
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
36
+ h: 8n,
37
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
38
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
39
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
40
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
41
+ };
42
+ ({ p: P2, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE);
43
+ L = 32;
44
+ L2 = 64;
45
+ captureTrace = (...args) => {
46
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
47
+ Error.captureStackTrace(...args);
48
+ }
49
+ };
50
+ err = (message = "") => {
51
+ const e = new Error(message);
52
+ captureTrace(e, err);
53
+ throw e;
54
+ };
55
+ isBig = (n) => typeof n === "bigint";
56
+ isStr = (s) => typeof s === "string";
57
+ isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
58
+ abytes = (value, length, title = "") => {
59
+ const bytes = isBytes(value);
60
+ const len = value?.length;
61
+ const needsLen = length !== void 0;
62
+ if (!bytes || needsLen && len !== length) {
63
+ const prefix = title && `"${title}" `;
64
+ const ofLen = needsLen ? ` of length ${length}` : "";
65
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
66
+ err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
67
+ }
68
+ return value;
69
+ };
70
+ u8n = (len) => new Uint8Array(len);
71
+ u8fr = (buf) => Uint8Array.from(buf);
72
+ padh = (n, pad) => n.toString(16).padStart(pad, "0");
73
+ bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
74
+ C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
75
+ _ch = (ch) => {
76
+ if (ch >= C._0 && ch <= C._9)
77
+ return ch - C._0;
78
+ if (ch >= C.A && ch <= C.F)
79
+ return ch - (C.A - 10);
80
+ if (ch >= C.a && ch <= C.f)
81
+ return ch - (C.a - 10);
82
+ return;
83
+ };
84
+ hexToBytes = (hex) => {
85
+ const e = "hex invalid";
86
+ if (!isStr(hex))
87
+ return err(e);
88
+ const hl = hex.length;
89
+ const al = hl / 2;
90
+ if (hl % 2)
91
+ return err(e);
92
+ const array = u8n(al);
93
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
94
+ const n1 = _ch(hex.charCodeAt(hi));
95
+ const n2 = _ch(hex.charCodeAt(hi + 1));
96
+ if (n1 === void 0 || n2 === void 0)
97
+ return err(e);
98
+ array[ai] = n1 * 16 + n2;
99
+ }
100
+ return array;
101
+ };
102
+ cr = () => globalThis?.crypto;
103
+ subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
104
+ concatBytes = (...arrs) => {
105
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
106
+ let pad = 0;
107
+ arrs.forEach((a) => {
108
+ r.set(a, pad);
109
+ pad += a.length;
110
+ });
111
+ return r;
112
+ };
113
+ randomBytes = (len = L) => {
114
+ const c = cr();
115
+ return c.getRandomValues(u8n(len));
116
+ };
117
+ big = BigInt;
118
+ assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
119
+ M = (a, b = P2) => {
120
+ const r = a % b;
121
+ return r >= 0n ? r : b + r;
122
+ };
123
+ modN = (a) => M(a, N);
124
+ invert = (num, md) => {
125
+ if (num === 0n || md <= 0n)
126
+ err("no inverse n=" + num + " mod=" + md);
127
+ let a = M(num, md), b = md, x = 0n, u = 1n;
128
+ while (a !== 0n) {
129
+ const q = b / a, r = b % a;
130
+ const m = x - u * q;
131
+ b = a, a = r, x = u, u = m;
132
+ }
133
+ return b === 1n ? M(x, md) : err("no inverse");
134
+ };
135
+ callHash = (name) => {
136
+ const fn = hashes[name];
137
+ if (typeof fn !== "function")
138
+ err("hashes." + name + " not set");
139
+ return fn;
140
+ };
141
+ hash = (msg) => callHash("sha512")(msg);
142
+ apoint = (p) => p instanceof Point ? p : err("Point expected");
143
+ B256 = 2n ** 256n;
144
+ Point = class _Point {
145
+ static BASE;
146
+ static ZERO;
147
+ X;
148
+ Y;
149
+ Z;
150
+ T;
151
+ constructor(X, Y, Z, T) {
152
+ const max = B256;
153
+ this.X = assertRange(X, 0n, max);
154
+ this.Y = assertRange(Y, 0n, max);
155
+ this.Z = assertRange(Z, 1n, max);
156
+ this.T = assertRange(T, 0n, max);
157
+ Object.freeze(this);
158
+ }
159
+ static CURVE() {
160
+ return ed25519_CURVE;
161
+ }
162
+ static fromAffine(p) {
163
+ return new _Point(p.x, p.y, 1n, M(p.x * p.y));
164
+ }
165
+ /** RFC8032 5.1.3: Uint8Array to Point. */
166
+ static fromBytes(hex, zip215 = false) {
167
+ const d = _d;
168
+ const normed = u8fr(abytes(hex, L));
169
+ const lastByte = hex[31];
170
+ normed[31] = lastByte & -129;
171
+ const y = bytesToNumLE(normed);
172
+ const max = zip215 ? B256 : P2;
173
+ assertRange(y, 0n, max);
174
+ const y2 = M(y * y);
175
+ const u = M(y2 - 1n);
176
+ const v = M(d * y2 + 1n);
177
+ let { isValid, value: x } = uvRatio(u, v);
178
+ if (!isValid)
179
+ err("bad point: y not sqrt");
180
+ const isXOdd = (x & 1n) === 1n;
181
+ const isLastByteOdd = (lastByte & 128) !== 0;
182
+ if (!zip215 && x === 0n && isLastByteOdd)
183
+ err("bad point: x==0, isLastByteOdd");
184
+ if (isLastByteOdd !== isXOdd)
185
+ x = M(-x);
186
+ return new _Point(x, y, 1n, M(x * y));
187
+ }
188
+ static fromHex(hex, zip215) {
189
+ return _Point.fromBytes(hexToBytes(hex), zip215);
190
+ }
191
+ get x() {
192
+ return this.toAffine().x;
193
+ }
194
+ get y() {
195
+ return this.toAffine().y;
196
+ }
197
+ /** Checks if the point is valid and on-curve. */
198
+ assertValidity() {
199
+ const a = _a;
200
+ const d = _d;
201
+ const p = this;
202
+ if (p.is0())
203
+ return err("bad point: ZERO");
204
+ const { X, Y, Z, T } = p;
205
+ const X2 = M(X * X);
206
+ const Y2 = M(Y * Y);
207
+ const Z2 = M(Z * Z);
208
+ const Z4 = M(Z2 * Z2);
209
+ const aX2 = M(X2 * a);
210
+ const left = M(Z2 * M(aX2 + Y2));
211
+ const right = M(Z4 + M(d * M(X2 * Y2)));
212
+ if (left !== right)
213
+ return err("bad point: equation left != right (1)");
214
+ const XY = M(X * Y);
215
+ const ZT = M(Z * T);
216
+ if (XY !== ZT)
217
+ return err("bad point: equation left != right (2)");
218
+ return this;
219
+ }
220
+ /** Equality check: compare points P&Q. */
221
+ equals(other) {
222
+ const { X: X1, Y: Y1, Z: Z1 } = this;
223
+ const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
224
+ const X1Z2 = M(X1 * Z2);
225
+ const X2Z1 = M(X2 * Z1);
226
+ const Y1Z2 = M(Y1 * Z2);
227
+ const Y2Z1 = M(Y2 * Z1);
228
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
229
+ }
230
+ is0() {
231
+ return this.equals(I);
232
+ }
233
+ /** Flip point over y coordinate. */
234
+ negate() {
235
+ return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
236
+ }
237
+ /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
238
+ double() {
239
+ const { X: X1, Y: Y1, Z: Z1 } = this;
240
+ const a = _a;
241
+ const A = M(X1 * X1);
242
+ const B = M(Y1 * Y1);
243
+ const C2 = M(2n * M(Z1 * Z1));
244
+ const D2 = M(a * A);
245
+ const x1y1 = X1 + Y1;
246
+ const E = M(M(x1y1 * x1y1) - A - B);
247
+ const G2 = D2 + B;
248
+ const F = G2 - C2;
249
+ const H = D2 - B;
250
+ const X3 = M(E * F);
251
+ const Y3 = M(G2 * H);
252
+ const T3 = M(E * H);
253
+ const Z3 = M(F * G2);
254
+ return new _Point(X3, Y3, Z3, T3);
255
+ }
256
+ /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
257
+ add(other) {
258
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
259
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
260
+ const a = _a;
261
+ const d = _d;
262
+ const A = M(X1 * X2);
263
+ const B = M(Y1 * Y2);
264
+ const C2 = M(T1 * d * T2);
265
+ const D2 = M(Z1 * Z2);
266
+ const E = M((X1 + Y1) * (X2 + Y2) - A - B);
267
+ const F = M(D2 - C2);
268
+ const G2 = M(D2 + C2);
269
+ const H = M(B - a * A);
270
+ const X3 = M(E * F);
271
+ const Y3 = M(G2 * H);
272
+ const T3 = M(E * H);
273
+ const Z3 = M(F * G2);
274
+ return new _Point(X3, Y3, Z3, T3);
275
+ }
276
+ subtract(other) {
277
+ return this.add(apoint(other).negate());
278
+ }
279
+ /**
280
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
281
+ * Uses {@link wNAF} for base point.
282
+ * Uses fake point to mitigate side-channel leakage.
283
+ * @param n scalar by which point is multiplied
284
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
285
+ */
286
+ multiply(n, safe = true) {
287
+ if (!safe && (n === 0n || this.is0()))
288
+ return I;
289
+ assertRange(n, 1n, N);
290
+ if (n === 1n)
291
+ return this;
292
+ if (this.equals(G))
293
+ return wNAF(n).p;
294
+ let p = I;
295
+ let f = G;
296
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
297
+ if (n & 1n)
298
+ p = p.add(d);
299
+ else if (safe)
300
+ f = f.add(d);
301
+ }
302
+ return p;
303
+ }
304
+ multiplyUnsafe(scalar) {
305
+ return this.multiply(scalar, false);
306
+ }
307
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
308
+ toAffine() {
309
+ const { X, Y, Z } = this;
310
+ if (this.equals(I))
311
+ return { x: 0n, y: 1n };
312
+ const iz = invert(Z, P2);
313
+ if (M(Z * iz) !== 1n)
314
+ err("invalid inverse");
315
+ const x = M(X * iz);
316
+ const y = M(Y * iz);
317
+ return { x, y };
318
+ }
319
+ toBytes() {
320
+ const { x, y } = this.assertValidity().toAffine();
321
+ const b = numTo32bLE(y);
322
+ b[31] |= x & 1n ? 128 : 0;
323
+ return b;
324
+ }
325
+ toHex() {
326
+ return bytesToHex(this.toBytes());
327
+ }
328
+ clearCofactor() {
329
+ return this.multiply(big(h), false);
330
+ }
331
+ isSmallOrder() {
332
+ return this.clearCofactor().is0();
333
+ }
334
+ isTorsionFree() {
335
+ let p = this.multiply(N / 2n, false).double();
336
+ if (N % 2n)
337
+ p = p.add(this);
338
+ return p.is0();
339
+ }
340
+ };
341
+ G = new Point(Gx, Gy, 1n, M(Gx * Gy));
342
+ I = new Point(0n, 1n, 1n, 0n);
343
+ Point.BASE = G;
344
+ Point.ZERO = I;
345
+ numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
346
+ bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
347
+ pow2 = (x, power) => {
348
+ let r = x;
349
+ while (power-- > 0n) {
350
+ r *= r;
351
+ r %= P2;
352
+ }
353
+ return r;
354
+ };
355
+ pow_2_252_3 = (x) => {
356
+ const x2 = x * x % P2;
357
+ const b2 = x2 * x % P2;
358
+ const b4 = pow2(b2, 2n) * b2 % P2;
359
+ const b5 = pow2(b4, 1n) * x % P2;
360
+ const b10 = pow2(b5, 5n) * b5 % P2;
361
+ const b20 = pow2(b10, 10n) * b10 % P2;
362
+ const b40 = pow2(b20, 20n) * b20 % P2;
363
+ const b80 = pow2(b40, 40n) * b40 % P2;
364
+ const b160 = pow2(b80, 80n) * b80 % P2;
365
+ const b240 = pow2(b160, 80n) * b80 % P2;
366
+ const b250 = pow2(b240, 10n) * b10 % P2;
367
+ const pow_p_5_8 = pow2(b250, 2n) * x % P2;
368
+ return { pow_p_5_8, b2 };
369
+ };
370
+ RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
371
+ uvRatio = (u, v) => {
372
+ const v3 = M(v * v * v);
373
+ const v7 = M(v3 * v3 * v);
374
+ const pow3 = pow_2_252_3(u * v7).pow_p_5_8;
375
+ let x = M(u * v3 * pow3);
376
+ const vx2 = M(v * x * x);
377
+ const root1 = x;
378
+ const root2 = M(x * RM1);
379
+ const useRoot1 = vx2 === u;
380
+ const useRoot2 = vx2 === M(-u);
381
+ const noRoot = vx2 === M(-u * RM1);
382
+ if (useRoot1)
383
+ x = root1;
384
+ if (useRoot2 || noRoot)
385
+ x = root2;
386
+ if ((M(x) & 1n) === 1n)
387
+ x = M(-x);
388
+ return { isValid: useRoot1 || useRoot2, value: x };
389
+ };
390
+ modL_LE = (hash2) => modN(bytesToNumLE(hash2));
391
+ sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
392
+ sha512s = (...m) => callHash("sha512")(concatBytes(...m));
393
+ hash2extK = (hashed) => {
394
+ const head = hashed.slice(0, L);
395
+ head[0] &= 248;
396
+ head[31] &= 127;
397
+ head[31] |= 64;
398
+ const prefix = hashed.slice(L, L2);
399
+ const scalar = modL_LE(head);
400
+ const point = G.multiply(scalar);
401
+ const pointBytes = point.toBytes();
402
+ return { head, prefix, scalar, point, pointBytes };
403
+ };
404
+ getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
405
+ getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
406
+ getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
407
+ getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
408
+ hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
409
+ hashFinishS = (res) => res.finish(sha512s(res.hashable));
410
+ _sign = (e, rBytes, msg) => {
411
+ const { pointBytes: P3, scalar: s } = e;
412
+ const r = modL_LE(rBytes);
413
+ const R = G.multiply(r).toBytes();
414
+ const hashable = concatBytes(R, P3, msg);
415
+ const finish = (hashed) => {
416
+ const S = modN(r + modL_LE(hashed) * s);
417
+ return abytes(concatBytes(R, numTo32bLE(S)), L2);
418
+ };
419
+ return { hashable, finish };
420
+ };
421
+ signAsync = async (message, secretKey) => {
422
+ const m = abytes(message);
423
+ const e = await getExtendedPublicKeyAsync(secretKey);
424
+ const rBytes = await sha512a(e.prefix, m);
425
+ return hashFinishA(_sign(e, rBytes, m));
426
+ };
427
+ sign = (message, secretKey) => {
428
+ const m = abytes(message);
429
+ const e = getExtendedPublicKey(secretKey);
430
+ const rBytes = sha512s(e.prefix, m);
431
+ return hashFinishS(_sign(e, rBytes, m));
432
+ };
433
+ defaultVerifyOpts = { zip215: true };
434
+ _verify = (sig, msg, pub, opts = defaultVerifyOpts) => {
435
+ sig = abytes(sig, L2);
436
+ msg = abytes(msg);
437
+ pub = abytes(pub, L);
438
+ const { zip215 } = opts;
439
+ let A;
440
+ let R;
441
+ let s;
442
+ let SB;
443
+ let hashable = Uint8Array.of();
444
+ try {
445
+ A = Point.fromBytes(pub, zip215);
446
+ R = Point.fromBytes(sig.slice(0, L), zip215);
447
+ s = bytesToNumLE(sig.slice(L, L2));
448
+ SB = G.multiply(s, false);
449
+ hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
450
+ } catch (error) {
451
+ }
452
+ const finish = (hashed) => {
453
+ if (SB == null)
454
+ return false;
455
+ if (!zip215 && A.isSmallOrder())
456
+ return false;
457
+ const k = modL_LE(hashed);
458
+ const RkA = R.add(A.multiply(k, false));
459
+ return RkA.add(SB.negate()).clearCofactor().is0();
460
+ };
461
+ return { hashable, finish };
462
+ };
463
+ verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
464
+ verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));
465
+ etc = {
466
+ bytesToHex,
467
+ hexToBytes,
468
+ concatBytes,
469
+ mod: M,
470
+ invert,
471
+ randomBytes
472
+ };
473
+ hashes = {
474
+ sha512Async: async (message) => {
475
+ const s = subtle();
476
+ const m = concatBytes(message);
477
+ return u8n(await s.digest("SHA-512", m.buffer));
478
+ },
479
+ sha512: void 0
480
+ };
481
+ randomSecretKey = (seed = randomBytes(L)) => seed;
482
+ keygen = (seed) => {
483
+ const secretKey = randomSecretKey(seed);
484
+ const publicKey = getPublicKey(secretKey);
485
+ return { secretKey, publicKey };
486
+ };
487
+ keygenAsync = async (seed) => {
488
+ const secretKey = randomSecretKey(seed);
489
+ const publicKey = await getPublicKeyAsync(secretKey);
490
+ return { secretKey, publicKey };
491
+ };
492
+ utils = {
493
+ getExtendedPublicKeyAsync,
494
+ getExtendedPublicKey,
495
+ randomSecretKey
496
+ };
497
+ W = 8;
498
+ scalarBits = 256;
499
+ pwindows = Math.ceil(scalarBits / W) + 1;
500
+ pwindowSize = 2 ** (W - 1);
501
+ precompute = () => {
502
+ const points = [];
503
+ let p = G;
504
+ let b = p;
505
+ for (let w = 0; w < pwindows; w++) {
506
+ b = p;
507
+ points.push(b);
508
+ for (let i = 1; i < pwindowSize; i++) {
509
+ b = b.add(p);
510
+ points.push(b);
511
+ }
512
+ p = b.double();
513
+ }
514
+ return points;
515
+ };
516
+ Gpows = void 0;
517
+ ctneg = (cnd, p) => {
518
+ const n = p.negate();
519
+ return cnd ? n : p;
520
+ };
521
+ wNAF = (n) => {
522
+ const comp = Gpows || (Gpows = precompute());
523
+ let p = I;
524
+ let f = G;
525
+ const pow_2_w = 2 ** W;
526
+ const maxNum = pow_2_w;
527
+ const mask = big(pow_2_w - 1);
528
+ const shiftBy = big(W);
529
+ for (let w = 0; w < pwindows; w++) {
530
+ let wbits = Number(n & mask);
531
+ n >>= shiftBy;
532
+ if (wbits > pwindowSize) {
533
+ wbits -= maxNum;
534
+ n += 1n;
535
+ }
536
+ const off = w * pwindowSize;
537
+ const offF = off;
538
+ const offP = off + Math.abs(wbits) - 1;
539
+ const isEven = w % 2 !== 0;
540
+ const isNeg = wbits < 0;
541
+ if (wbits === 0) {
542
+ f = f.add(ctneg(isEven, comp[offF]));
543
+ } else {
544
+ p = p.add(ctneg(isNeg, comp[offP]));
545
+ }
546
+ }
547
+ if (n !== 0n)
548
+ err("invalid wnaf");
549
+ return { p, f };
550
+ };
551
+ }
552
+ });
553
+
554
+ // src/core/ed25519.ts
555
+ var ed25519_exports2 = {};
556
+ __export(ed25519_exports2, {
557
+ eventPublicKey: () => eventPublicKey,
558
+ eventSignature: () => eventSignature
559
+ });
560
+ async function eventPublicKey(seed) {
561
+ const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
562
+ return ed.getPublicKeyAsync(seed);
563
+ }
564
+ async function eventSignature(message, seed) {
565
+ const ed = await Promise.resolve().then(() => (init_ed25519(), ed25519_exports));
566
+ return ed.signAsync(message, seed);
567
+ }
568
+ var init_ed255192 = __esm({
569
+ "src/core/ed25519.ts"() {
570
+ }
571
+ });
572
+
3
573
  // src/core/constants.ts
4
574
  var DEFAULT_WIDGET_API_BASE = "/api/widget/v1";
5
575
  var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146, 98866]);
@@ -93,7 +663,10 @@ var CANONICAL_ESCROW = Object.freeze({
93
663
  // Plume
94
664
  });
95
665
  var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
96
- var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {};
666
+ var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
667
+ 9745: 2500n * 10n ** 18n,
668
+ 98866: 5000n * 10n ** 18n
669
+ };
97
670
  function maxNativeFeeWei(chainId) {
98
671
  return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
99
672
  }
@@ -211,6 +784,247 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
211
784
  1151111081099710: "Solana"
212
785
  });
213
786
 
787
+ // src/core/solana.ts
788
+ var SOLANA_CHAIN_ID = 1151111081099710;
789
+ function isSolanaChainId(value) {
790
+ return Number(value) === SOLANA_CHAIN_ID;
791
+ }
792
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
793
+ function base58Encode(bytes) {
794
+ let zeros = 0;
795
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
796
+ let value = 0n;
797
+ for (const byte of bytes) value = value << 8n | BigInt(byte);
798
+ let out = "";
799
+ while (value > 0n) {
800
+ out = BASE58_ALPHABET[Number(value % 58n)] + out;
801
+ value /= 58n;
802
+ }
803
+ return "1".repeat(zeros) + out;
804
+ }
805
+ function base58Decode(text) {
806
+ let value = 0n;
807
+ for (const char of text) {
808
+ const digit = BASE58_ALPHABET.indexOf(char);
809
+ if (digit < 0) return null;
810
+ value = value * 58n + BigInt(digit);
811
+ }
812
+ const body = [];
813
+ while (value > 0n) {
814
+ body.unshift(Number(value & 0xffn));
815
+ value >>= 8n;
816
+ }
817
+ let zeros = 0;
818
+ while (zeros < text.length && text[zeros] === "1") zeros += 1;
819
+ return new Uint8Array([...new Array(zeros).fill(0), ...body]);
820
+ }
821
+ function isSolanaAddress(value) {
822
+ const text = typeof value === "string" ? value.trim() : "";
823
+ return text.length >= 32 && text.length <= 44 && base58Decode(text)?.length === 32;
824
+ }
825
+ function solanaKeyHex(value) {
826
+ if (!isSolanaAddress(value)) return null;
827
+ return `0x${Array.from(base58Decode(value.trim()), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
828
+ }
829
+ function hexToSolanaKey(value) {
830
+ if (!/^0x[0-9a-fA-F]{64}$/.test(value)) return null;
831
+ return base58Encode(Uint8Array.from(value.slice(2).match(/../g), (byte) => Number.parseInt(byte, 16)));
832
+ }
833
+ var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
834
+ var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
835
+ var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
836
+ var pin = (symbol, decimals, bridge, tokenProgram) => Object.freeze({ symbol, decimals, bridge, tokenProgram });
837
+ var SOLANA_DESTINATION_ASSETS = Object.freeze({
838
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: pin("USDC", 6, "cctp", TOKEN_PROGRAM),
839
+ "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": pin("PYUSD", 6, "layerzero", TOKEN_2022_PROGRAM),
840
+ DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT: pin("USDE", 9, "layerzero", TOKEN_PROGRAM),
841
+ "2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": pin("USDG", 6, "layerzero", TOKEN_2022_PROGRAM),
842
+ AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
843
+ });
844
+ function solanaDestinationAsset(mint) {
845
+ const key = typeof mint === "string" ? mint.trim() : "";
846
+ return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
847
+ }
848
+ function solanaBridgeOf(token) {
849
+ const pinned = solanaDestinationAsset(token.address);
850
+ if (!pinned || pinned.symbol !== token.symbol.trim().toUpperCase()) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
851
+ return pinned.bridge;
852
+ }
853
+ var K = new Uint32Array([
854
+ 1116352408,
855
+ 1899447441,
856
+ 3049323471,
857
+ 3921009573,
858
+ 961987163,
859
+ 1508970993,
860
+ 2453635748,
861
+ 2870763221,
862
+ 3624381080,
863
+ 310598401,
864
+ 607225278,
865
+ 1426881987,
866
+ 1925078388,
867
+ 2162078206,
868
+ 2614888103,
869
+ 3248222580,
870
+ 3835390401,
871
+ 4022224774,
872
+ 264347078,
873
+ 604807628,
874
+ 770255983,
875
+ 1249150122,
876
+ 1555081692,
877
+ 1996064986,
878
+ 2554220882,
879
+ 2821834349,
880
+ 2952996808,
881
+ 3210313671,
882
+ 3336571891,
883
+ 3584528711,
884
+ 113926993,
885
+ 338241895,
886
+ 666307205,
887
+ 773529912,
888
+ 1294757372,
889
+ 1396182291,
890
+ 1695183700,
891
+ 1986661051,
892
+ 2177026350,
893
+ 2456956037,
894
+ 2730485921,
895
+ 2820302411,
896
+ 3259730800,
897
+ 3345764771,
898
+ 3516065817,
899
+ 3600352804,
900
+ 4094571909,
901
+ 275423344,
902
+ 430227734,
903
+ 506948616,
904
+ 659060556,
905
+ 883997877,
906
+ 958139571,
907
+ 1322822218,
908
+ 1537002063,
909
+ 1747873779,
910
+ 1955562222,
911
+ 2024104815,
912
+ 2227730452,
913
+ 2361852424,
914
+ 2428436474,
915
+ 2756734187,
916
+ 3204031479,
917
+ 3329325298
918
+ ]);
919
+ function sha256(data) {
920
+ const bitLen = data.length * 8;
921
+ const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
922
+ padded.set(data);
923
+ padded[data.length] = 128;
924
+ const view = new DataView(padded.buffer);
925
+ view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
926
+ view.setUint32(padded.length - 4, bitLen >>> 0);
927
+ const h2 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
928
+ const w = new Uint32Array(64);
929
+ const rotr = (x, n) => x >>> n | x << 32 - n;
930
+ for (let off = 0; off < padded.length; off += 64) {
931
+ for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
932
+ for (let i = 16; i < 64; i += 1) {
933
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
934
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
935
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
936
+ }
937
+ let [a, b, c, d, e, f, g, hh] = h2;
938
+ for (let i = 0; i < 64; i += 1) {
939
+ const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
940
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
941
+ hh = g;
942
+ g = f;
943
+ f = e;
944
+ e = d + t1 >>> 0;
945
+ d = c;
946
+ c = b;
947
+ b = a;
948
+ a = t1 + t2 >>> 0;
949
+ }
950
+ h2[0] = h2[0] + a >>> 0;
951
+ h2[1] = h2[1] + b >>> 0;
952
+ h2[2] = h2[2] + c >>> 0;
953
+ h2[3] = h2[3] + d >>> 0;
954
+ h2[4] = h2[4] + e >>> 0;
955
+ h2[5] = h2[5] + f >>> 0;
956
+ h2[6] = h2[6] + g >>> 0;
957
+ h2[7] = h2[7] + hh >>> 0;
958
+ }
959
+ const out = new Uint8Array(32);
960
+ const outView = new DataView(out.buffer);
961
+ for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h2[i]);
962
+ return out;
963
+ }
964
+ var P = 2n ** 255n - 19n;
965
+ var mod = (a) => (a % P + P) % P;
966
+ var pow = (base, exp) => {
967
+ let result = 1n;
968
+ let b = mod(base);
969
+ for (let e = exp; e > 0n; e >>= 1n) {
970
+ if (e & 1n) result = result * b % P;
971
+ b = b * b % P;
972
+ }
973
+ return result;
974
+ };
975
+ var D = mod(-121665n * pow(121666n, P - 2n));
976
+ function isOnEd25519Curve(bytes) {
977
+ let y = 0n;
978
+ for (let i = 31; i >= 0; i -= 1) y = y << 8n | BigInt(bytes[i]);
979
+ y = mod(y & (1n << 255n) - 1n);
980
+ const yy = y * y % P;
981
+ const u = mod(yy - 1n);
982
+ const v = mod(D * yy + 1n);
983
+ if (v === 0n) return u === 0n;
984
+ const x2 = u * pow(v, P - 2n) % P;
985
+ return x2 === 0n || pow(x2, (P - 1n) / 2n) === 1n;
986
+ }
987
+ function keyBytes(base58) {
988
+ const bytes = base58Decode(base58);
989
+ if (!bytes || bytes.length !== 32) throw new Error("Not a valid Solana address.");
990
+ return bytes;
991
+ }
992
+ function findProgramAddress(seeds, programId) {
993
+ const program = keyBytes(programId);
994
+ const marker = new TextEncoder().encode("ProgramDerivedAddress");
995
+ for (let bump = 255; bump >= 1; bump -= 1) {
996
+ const parts = [...seeds, Uint8Array.of(bump), program, marker];
997
+ const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
998
+ let at = 0;
999
+ for (const part of parts) {
1000
+ buf.set(part, at);
1001
+ at += part.length;
1002
+ }
1003
+ const candidate = sha256(buf);
1004
+ if (!isOnEd25519Curve(candidate)) return candidate;
1005
+ }
1006
+ throw new Error("Could not derive a program address.");
1007
+ }
1008
+ function associatedTokenAddress(owner, mint, tokenProgram) {
1009
+ return base58Encode(findProgramAddress([keyBytes(owner), keyBytes(tokenProgram), keyBytes(mint)], ASSOCIATED_TOKEN_PROGRAM));
1010
+ }
1011
+ function expectedSolanaDelivery(recipient2, mint) {
1012
+ if (!isSolanaAddress(recipient2)) throw new Error("Not a valid Solana address.");
1013
+ const pinned = solanaDestinationAsset(mint);
1014
+ if (!pinned) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
1015
+ const target = pinned.bridge === "cctp" ? associatedTokenAddress(recipient2.trim(), mint.trim(), pinned.tokenProgram) : recipient2.trim();
1016
+ return solanaKeyHex(target);
1017
+ }
1018
+ function checkSolanaReceiver(request, intended, mint) {
1019
+ if (!isSolanaAddress(intended)) throw new Error("Not a valid Solana address.");
1020
+ if (request.destinationReceiverOwner !== intended.trim()) throw new Error("The quote was not made out to your Solana recipient; refusing to sign.");
1021
+ const receiver = request.destinationReceiver || "";
1022
+ const display = hexToSolanaKey(receiver);
1023
+ if (!display) throw new Error("The quote carries no Solana delivery account; refusing to sign.");
1024
+ if (request.destinationReceiverBase58 && request.destinationReceiverBase58 !== display) throw new Error("The quote names two different Solana delivery accounts; refusing to sign.");
1025
+ 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.");
1026
+ }
1027
+
214
1028
  // src/core/address.ts
215
1029
  function symbolKey(value) {
216
1030
  return String(value || "").trim().toUpperCase();
@@ -227,66 +1041,26 @@ function assertAddress(value, label) {
227
1041
  if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label} is not a valid EVM address.`);
228
1042
  return normalized;
229
1043
  }
230
- function resolveSwapReceiver(recipient, payer) {
1044
+ function resolveSwapReceiver(recipient2, payer, destinationChainId) {
231
1045
  const payerAddr = assertAddress(payer, "Swap wallet");
232
- if (recipient === void 0 || recipient === null || recipient === "") return payerAddr;
233
- const normalized = normalizeAddress(recipient);
1046
+ if (isSolanaChainId(destinationChainId)) return assertChainAddress(destinationChainId, recipient2, "Deposit recipient");
1047
+ if (recipient2 === void 0 || recipient2 === null || recipient2 === "") return payerAddr;
1048
+ const normalized = normalizeAddress(recipient2);
234
1049
  if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
235
1050
  return normalized;
236
1051
  }
237
-
238
- // src/core/units.ts
239
- function assetDecimals(token) {
240
- const sym = symbolKey(token?.symbol);
241
- const registry = Number(token?.decimals);
242
- const canonical = CANONICAL_DECIMALS[sym];
243
- if (canonical !== void 0) {
244
- if (!Number.isInteger(registry)) {
245
- throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
246
- }
247
- if (registry !== canonical) {
248
- throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
249
- }
250
- return canonical;
251
- }
252
- if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
253
- throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
254
- }
255
- return registry;
1052
+ function isChainAddress(chainId, value) {
1053
+ return isSolanaChainId(chainId) ? isSolanaAddress(value) : isAddress(value);
256
1054
  }
257
- function normalizeDecimalText(value) {
258
- const text = String(value || "").trim().replace(/\s+/g, "");
259
- if (!text) return "";
260
- if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
261
- if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
262
- if (text.includes(",")) return "";
263
- return text;
1055
+ function chainAddressKey(chainId, value) {
1056
+ const text = String(value || "");
1057
+ return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
264
1058
  }
265
- function parseUnitsDecimal(amount, decimals) {
266
- const text = normalizeDecimalText(amount);
267
- if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
268
- const [whole, frac = ""] = text.split(".");
269
- if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
270
- const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
271
- const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
272
- if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
273
- return value;
274
- }
275
- function scaleDecimals(amount, fromDecimals, toDecimals) {
276
- if (toDecimals === fromDecimals) return amount;
277
- if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
278
- return amount / 10n ** BigInt(fromDecimals - toDecimals);
279
- }
280
- function formatUnits(raw, decimals, maxDecimals = 6) {
281
- const value = BigInt(raw || "0");
282
- const base = 10n ** BigInt(decimals);
283
- const whole = value / base;
284
- const fracFull = (value % base).toString().padStart(decimals, "0");
285
- const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
286
- return frac ? `${whole}.${frac}` : whole.toString();
287
- }
288
- function finalOf(quote) {
289
- return BigInt(quote?.finalAmount || quote?.toAmount || "0");
1059
+ function assertChainAddress(chainId, value, label) {
1060
+ if (!isSolanaChainId(chainId)) return assertAddress(value, label);
1061
+ if (!String(value || "").trim()) throw new Error("Connect a Solana wallet or enter a Solana recipient address.");
1062
+ if (!isSolanaAddress(value)) throw new Error("Not a valid Solana address.");
1063
+ return String(value).trim();
290
1064
  }
291
1065
 
292
1066
  // src/core/abi.ts
@@ -359,14 +1133,12 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
359
1133
  const tuples = orders.map(encodeOrderTuple);
360
1134
  let offset = 32n * BigInt(tuples.length);
361
1135
  const offsets = tuples.map((tuple) => {
362
- const word = uintWord(offset);
1136
+ const word2 = uintWord(offset);
363
1137
  offset += BigInt(tuple.length / 2);
364
- return word;
1138
+ return word2;
365
1139
  }).join("");
366
1140
  return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
367
1141
  }
368
- var EVM_BYTES_PAYLOAD_BYTES = 64;
369
- var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
370
1142
  var MAX_DECODED_ORDERS = 16;
371
1143
  function decodeSubmitOrderCalldata(data) {
372
1144
  const hex = strip0x(String(data || "")).toLowerCase();
@@ -374,56 +1146,61 @@ function decodeSubmitOrderCalldata(data) {
374
1146
  if (`0x${hex.slice(0, 8)}` !== SUBMIT_ORDER_SELECTOR) return null;
375
1147
  const body = hex.slice(8);
376
1148
  const totalBytes = body.length / 2;
377
- const word = (byteOffset) => {
1149
+ const word2 = (byteOffset) => {
378
1150
  if (!Number.isSafeInteger(byteOffset) || byteOffset < 0 || byteOffset + 32 > totalBytes) return null;
379
1151
  return BigInt(`0x${body.slice(byteOffset * 2, byteOffset * 2 + 64)}`);
380
1152
  };
381
1153
  const addressAt = (byteOffset) => {
382
- const w = word(byteOffset);
1154
+ const w = word2(byteOffset);
383
1155
  if (w === null || w >= 1n << 160n) return null;
384
1156
  return `0x${w.toString(16).padStart(40, "0")}`;
385
1157
  };
386
1158
  const uint64At = (byteOffset) => {
387
- const w = word(byteOffset);
1159
+ const w = word2(byteOffset);
388
1160
  return w === null || w > MAX_UINT64 ? null : w;
389
1161
  };
390
- const evmBytesAt = (byteOffset) => {
391
- const len = word(byteOffset);
392
- if (len !== 20n) return null;
393
- const content = body.slice((byteOffset + 32) * 2, (byteOffset + 64) * 2);
394
- if (content.length !== 64 || !content.endsWith("0".repeat(24))) return null;
395
- return `0x${content.slice(0, 40)}`;
1162
+ const keyBytesAt = (byteOffset) => {
1163
+ const len = word2(byteOffset);
1164
+ if (len !== 20n && len !== 32n) return null;
1165
+ const length = Number(len);
1166
+ const padded = Math.ceil(length / 32) * 32;
1167
+ const content = body.slice((byteOffset + 32) * 2, (byteOffset + 32 + padded) * 2);
1168
+ if (content.length !== padded * 2 || content.slice(length * 2) !== "0".repeat((padded - length) * 2)) return null;
1169
+ return { value: `0x${content.slice(0, length * 2)}`, size: 32 + padded };
396
1170
  };
397
- if (word(0) !== 64n) return null;
398
- if (word(32) === null) return null;
1171
+ if (word2(0) !== 64n) return null;
1172
+ if (word2(32) === null) return null;
399
1173
  const partnerId = `0x${body.slice(64, 128)}`;
400
- const count = word(64);
1174
+ const count = word2(64);
401
1175
  if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
402
1176
  const n = Number(count);
403
1177
  const arrayBase = 96;
404
- if (totalBytes !== arrayBase + 32 * n + EVM_ORDER_TUPLE_BYTES * n) return null;
1178
+ let next = arrayBase + 32 * n;
405
1179
  const orders = [];
406
1180
  for (let i = 0; i < n; i += 1) {
407
- const rel = word(arrayBase + i * 32);
408
- if (rel === null || rel !== BigInt(32 * n + EVM_ORDER_TUPLE_BYTES * i)) return null;
409
- const base = arrayBase + Number(rel);
1181
+ const rel = word2(arrayBase + i * 32);
1182
+ if (rel === null || rel !== BigInt(next - arrayBase)) return null;
1183
+ const base = next;
410
1184
  const owner = addressAt(base);
411
1185
  const bidToken = addressAt(base + 32);
412
- const bidTokenAmount = word(base + 64);
413
- const askOffset = word(base + 96);
414
- const askTokenAmount = word(base + 128);
415
- const receiverOffset = word(base + 160);
1186
+ const bidTokenAmount = word2(base + 64);
1187
+ const askOffset = word2(base + 96);
1188
+ const askTokenAmount = word2(base + 128);
1189
+ const receiverOffset = word2(base + 160);
416
1190
  const destinationChainId = uint64At(base + 192);
417
1191
  const executionChainId = uint64At(base + 224);
418
1192
  const deadline = uint64At(base + 256);
419
- 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)) {
1193
+ if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES) {
420
1194
  return null;
421
1195
  }
422
- const askToken = evmBytesAt(base + Number(askOffset));
423
- const destinationReceiver = evmBytesAt(base + Number(receiverOffset));
1196
+ const askToken = keyBytesAt(base + Number(askOffset));
1197
+ if (!askToken || receiverOffset !== ORDER_HEAD_BYTES + BigInt(askToken.size)) return null;
1198
+ const destinationReceiver = keyBytesAt(base + Number(receiverOffset));
424
1199
  if (askToken === null || destinationReceiver === null) return null;
425
- orders.push({ owner, bidToken, bidTokenAmount, askToken, askTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline });
1200
+ next = base + Number(ORDER_HEAD_BYTES) + askToken.size + destinationReceiver.size;
1201
+ orders.push({ owner, bidToken, bidTokenAmount, askToken: askToken.value, askTokenAmount, destinationReceiver: destinationReceiver.value, destinationChainId, executionChainId, deadline });
426
1202
  }
1203
+ if (next !== totalBytes) return null;
427
1204
  return { partnerId, orders };
428
1205
  }
429
1206
  function toHexQuantity(value) {
@@ -431,47 +1208,349 @@ function toHexQuantity(value) {
431
1208
  return `0x${n.toString(16)}`;
432
1209
  }
433
1210
 
434
- // src/core/escrow.ts
435
- function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
436
- const fromQuote = normalizeAddress(quoteEscrow);
437
- const fromChains = normalizeAddress(chainsEscrow);
438
- if (!fromChains || fromChains === ZERO_ADDRESS) {
439
- throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
1211
+ // src/core/solana-tx.ts
1212
+ function bytesEqual(a, b) {
1213
+ return a.length === b.length && a.every((v, i) => v === b[i]);
1214
+ }
1215
+ function hexBytes(hex) {
1216
+ const h2 = strip0x(hex);
1217
+ if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
1218
+ return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
1219
+ }
1220
+ function solanaKeyBytes(key) {
1221
+ if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
1222
+ return base58Decode(key);
1223
+ }
1224
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1225
+ function base64Decode(text) {
1226
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) throw new Error("Invalid base64.");
1227
+ const out = [];
1228
+ let value = 0, bits = 0;
1229
+ for (const ch of text.replace(/=+$/, "")) {
1230
+ value = value << 6 | B64.indexOf(ch);
1231
+ bits += 6;
1232
+ if (bits >= 8) {
1233
+ bits -= 8;
1234
+ out.push(value >> bits & 255);
1235
+ }
440
1236
  }
441
- if (!fromQuote || fromQuote === ZERO_ADDRESS) {
442
- throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
1237
+ const bytes = Uint8Array.from(out);
1238
+ if (base64Encode(bytes) !== text) throw new Error("Noncanonical base64.");
1239
+ return bytes;
1240
+ }
1241
+ function base64Encode(bytes) {
1242
+ let out = "";
1243
+ for (let i = 0; i < bytes.length; i += 3) {
1244
+ const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
1245
+ out += B64[n >>> 18 & 63] + B64[n >>> 12 & 63] + (i + 1 < bytes.length ? B64[n >>> 6 & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
443
1246
  }
444
- if (fromQuote !== fromChains) {
445
- throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
1247
+ return out;
1248
+ }
1249
+ var Reader = class {
1250
+ constructor(bytes) {
1251
+ this.bytes = bytes;
446
1252
  }
447
- const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
448
- if (pinned && pinned !== fromChains) {
449
- throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
1253
+ bytes;
1254
+ at = 0;
1255
+ take(n) {
1256
+ if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error("Truncated Solana data.");
1257
+ const v = this.bytes.slice(this.at, this.at + n);
1258
+ this.at += n;
1259
+ return v;
450
1260
  }
451
- return fromChains;
1261
+ byte() {
1262
+ return this.take(1)[0];
1263
+ }
1264
+ compact() {
1265
+ let n = 0;
1266
+ for (let i = 0; i < 3; i++) {
1267
+ const b = this.byte();
1268
+ if (i === 2 && b > 3) throw new Error("Invalid compact-u16.");
1269
+ n |= (b & 127) << 7 * i;
1270
+ if (!(b & 128)) {
1271
+ if (i && b === 0) throw new Error("Noncanonical compact-u16.");
1272
+ return n;
1273
+ }
1274
+ }
1275
+ throw new Error("Invalid compact-u16.");
1276
+ }
1277
+ u64() {
1278
+ const b = this.take(8);
1279
+ let n = 0n;
1280
+ for (let i = 7; i >= 0; i--) n = n << 8n | BigInt(b[i]);
1281
+ return n;
1282
+ }
1283
+ vec() {
1284
+ const b = this.take(4);
1285
+ return this.take(new DataView(b.buffer).getUint32(0, true));
1286
+ }
1287
+ end() {
1288
+ if (this.at !== this.bytes.length) throw new Error("Trailing Solana data.");
1289
+ }
1290
+ };
1291
+ function parseSolanaTransaction(input) {
1292
+ const bytes = new Uint8Array(input), r = new Reader(bytes);
1293
+ const count = r.compact(), signatureOffset = r.at;
1294
+ if (count < 1 || count > 127) throw new Error("Invalid signature count.");
1295
+ r.take(count * 64);
1296
+ const messageOffset = r.at, first = r.byte();
1297
+ if (first & 128 && first !== 128) throw new Error("Unsupported Solana message version.");
1298
+ const version = first === 128 ? 0 : "legacy";
1299
+ const requiredSignatures = version === 0 ? r.byte() : first;
1300
+ const readonlySigned = r.byte(), readonlyUnsigned = r.byte();
1301
+ const keyCount = r.compact();
1302
+ if (requiredSignatures !== count || requiredSignatures > keyCount || readonlySigned >= count || readonlyUnsigned > keyCount - count || keyCount > 256) throw new Error("Invalid Solana message header.");
1303
+ const staticKeys = Array.from({ length: keyCount }, () => base58Encode(r.take(32)));
1304
+ const blockhashOffset = r.at;
1305
+ r.take(32);
1306
+ const instructions = Array.from({ length: r.compact() }, () => {
1307
+ const programIdIndex = r.byte();
1308
+ const accounts = Array.from(r.take(r.compact()));
1309
+ return { programIdIndex, accounts, data: r.take(r.compact()) };
1310
+ });
1311
+ const lookups = version === 0 ? Array.from({ length: r.compact() }, () => ({
1312
+ address: base58Encode(r.take(32)),
1313
+ writable: Array.from(r.take(r.compact())),
1314
+ readonly: Array.from(r.take(r.compact()))
1315
+ })) : [];
1316
+ r.end();
1317
+ const all = keyCount + lookups.reduce((n, l) => n + l.writable.length + l.readonly.length, 0);
1318
+ if (all > 256 || instructions.some((ix) => ix.programIdIndex >= keyCount || ix.accounts.some((i) => i >= all))) throw new Error("Invalid Solana account index.");
1319
+ return { bytes, messageOffset, blockhashOffset, version, requiredSignatures, signatureOffset, staticKeys, instructions, lookups };
1320
+ }
1321
+ function serializeSolanaTransaction(tx) {
1322
+ return new Uint8Array(tx.bytes);
1323
+ }
1324
+ function overwriteBlockhash(input, blockhash) {
1325
+ const tx = parseSolanaTransaction(input), out = new Uint8Array(input);
1326
+ out.set(solanaKeyBytes(blockhash), tx.blockhashOffset);
1327
+ return out;
452
1328
  }
453
- function isLayerZeroRoute(quote, option = {}) {
454
- const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
455
- return bridge.includes("layerzero") || bridge.includes("layer zero");
1329
+ function placeSignature(input, publicKey, signature) {
1330
+ const tx = parseSolanaTransaction(input), index = tx.staticKeys.slice(0, tx.requiredSignatures).indexOf(publicKey);
1331
+ if (index < 0 || signature.length !== 64) throw new Error("Missing Solana signer slot.");
1332
+ const out = new Uint8Array(input);
1333
+ out.set(signature, tx.signatureOffset + index * 64);
1334
+ return out;
456
1335
  }
457
- function sourceAssetKey(quote, option = {}) {
458
- return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
1336
+ function assertWalletMessage(original, signed) {
1337
+ const a = parseSolanaTransaction(original), b = parseSolanaTransaction(signed);
1338
+ if (!bytesEqual(a.bytes.subarray(a.messageOffset), b.bytes.subarray(b.messageOffset))) throw new Error("The wallet modified the transaction message; refusing to send.");
1339
+ for (let i = 1; i < a.requiredSignatures; i++) {
1340
+ const start = a.signatureOffset + 64 * i;
1341
+ if (!bytesEqual(a.bytes.subarray(start, start + 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.");
1342
+ }
1343
+ if (!b.bytes.subarray(b.signatureOffset, b.signatureOffset + 64).some(Boolean)) throw new Error("The wallet returned no fee-payer signature.");
1344
+ }
1345
+ var SUBMIT_ORDER_DISCRIMINATOR = [230, 150, 200, 53, 92, 208, 109, 108];
1346
+ function isSubmitOrder(data) {
1347
+ return data.length >= 8 && SUBMIT_ORDER_DISCRIMINATOR.every((v, i) => data[i] === v);
1348
+ }
1349
+ function decodeSolanaSubmitOrder(data) {
1350
+ if (!isSubmitOrder(data)) throw new Error("Not a submit_order instruction.");
1351
+ const r = new Reader(data);
1352
+ r.take(8);
1353
+ const owner = r.take(20), askToken = r.vec();
1354
+ let askTokenAmount = 0n;
1355
+ for (const b of r.take(32)) askTokenAmount = askTokenAmount << 8n | BigInt(b);
1356
+ const bidTokenAmount = r.u64(), destinationReceiver = r.vec(), destinationChainId = r.u64(), executionChainId = r.u64(), deadline = r.u64();
1357
+ const tag = r.byte();
1358
+ if (tag !== 0 && tag !== 1) throw new Error("Invalid submit_order partner tag.");
1359
+ const partnerId = tag === 1 ? r.take(32) : null;
1360
+ r.end();
1361
+ return { owner, askToken, askTokenAmount, bidTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline, partnerId };
1362
+ }
1363
+ function verifySolanaSubmit(p, e) {
1364
+ const fail = (field) => {
1365
+ throw new Error(`Solana order mismatch (${field}); refusing to sign.`);
1366
+ };
1367
+ if (hexBytes(e.owner).length !== 20 || !bytesEqual(p.owner, hexBytes(e.owner))) fail("owner");
1368
+ if (!bytesEqual(p.askToken, hexBytes(e.askToken))) fail("ask token");
1369
+ if (p.askTokenAmount <= 0n) fail("non-positive output");
1370
+ if (p.askTokenAmount < BigInt(e.minAskTokenAmount)) fail("minimum received");
1371
+ if (p.askTokenAmount > BigInt(e.maxAskTokenAmount)) fail("maximum received");
1372
+ if (p.bidTokenAmount !== BigInt(e.bidTokenAmount)) fail("amount sent");
1373
+ if (!bytesEqual(p.destinationReceiver, hexBytes(e.destinationReceiver))) fail("receiver");
1374
+ if (p.destinationChainId !== BigInt(e.destinationChainId)) fail("destination chain");
1375
+ if (p.executionChainId !== BigInt(e.executionChainId)) fail("execution chain");
1376
+ if (p.deadline !== BigInt(e.deadline)) fail("deadline");
1377
+ if (p.partnerId !== null !== (e.partnerId !== null)) fail("subsidy marker");
1378
+ }
1379
+ var PREPARATION_INSTRUCTIONS = [
1380
+ { discriminator: [225, 205, 234, 143, 17, 186, 50, 220], signer: 2 },
1381
+ // create_profile
1382
+ { discriminator: [223, 99, 118, 101, 213, 29, 215, 137], signer: 3 },
1383
+ // initialize_buffer_data
1384
+ { discriminator: [105, 254, 33, 182, 188, 80, 204, 204], signer: 3 },
1385
+ // write_buffer_data
1386
+ { discriminator: [179, 249, 129, 154, 80, 167, 138, 18], signer: 3 },
1387
+ // finalize_buffer_data
1388
+ { discriminator: [23, 25, 65, 45, 74, 9, 223, 23], signer: 2 }
1389
+ // close_buffer_data
1390
+ ];
1391
+ var SUBMIT_SIGNER_ACCOUNT = 11;
1392
+ function preparationInstruction(data) {
1393
+ return data.length >= 8 ? PREPARATION_INSTRUCTIONS.find((p) => p.discriminator.every((byte, i) => data[i] === byte)) : void 0;
1394
+ }
1395
+ function isPreparationInstruction(data) {
1396
+ return preparationInstruction(data) !== void 0;
1397
+ }
1398
+ function verifySolanaTransaction(tx, expected, keys, mustSubmit) {
1399
+ if (tx.staticKeys[0] !== expected.signer) throw new Error("Wrong Solana fee payer; refusing to sign.");
1400
+ if (!mustSubmit && tx.requiredSignatures !== 1) throw new Error("Unexpected co-signer on a preparation step; refusing to sign.");
1401
+ let submits = 0, buffer = null;
1402
+ for (const ix of tx.instructions) {
1403
+ if (tx.staticKeys[ix.programIdIndex] !== expected.program) throw new Error("Foreign program instruction; refusing to sign.");
1404
+ const preparation = preparationInstruction(ix.data);
1405
+ if (!isSubmitOrder(ix.data) && !preparation) throw new Error("Unexpected ZeroDelta instruction; refusing to sign.");
1406
+ const signerSlot = preparation ? preparation.signer : SUBMIT_SIGNER_ACCOUNT;
1407
+ if (keys[ix.accounts[signerSlot]] !== expected.signer) throw new Error("ZeroDelta instruction names another signer; refusing to sign.");
1408
+ if (!isSubmitOrder(ix.data)) continue;
1409
+ submits++;
1410
+ verifySolanaSubmit(decodeSolanaSubmitOrder(ix.data), expected);
1411
+ if (keys[ix.accounts[1]] !== expected.mint) throw new Error("Wrong source mint; refusing to sign.");
1412
+ buffer = keys[ix.accounts[8]] ?? null;
1413
+ if (!buffer) throw new Error("Missing route buffer; refusing to sign.");
1414
+ }
1415
+ if (submits !== (mustSubmit ? 1 : 0)) throw new Error("Expected exactly one submit_order in submit and none in preparation; refusing to sign.");
1416
+ return buffer;
1417
+ }
1418
+ function parseAddressLookupTable(data) {
1419
+ 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.");
1420
+ return Array.from({ length: (data.length - 56) / 32 }, (_, i) => base58Encode(data.subarray(56 + 32 * i, 88 + 32 * i)));
1421
+ }
1422
+ async function resolveSolanaKeys(tx, rpc) {
1423
+ if (!tx.lookups.length) return [...tx.staticKeys];
1424
+ const result = await rpc("getMultipleAccounts", [tx.lookups.map((l) => l.address), { encoding: "base64", commitment: "confirmed" }]);
1425
+ if (!Array.isArray(result.value) || result.value.length !== tx.lookups.length) throw new Error("Missing lookup tables.");
1426
+ const writable = [], readonly = [];
1427
+ tx.lookups.forEach((lookup, i) => {
1428
+ const account = result.value[i];
1429
+ if (account?.owner !== "AddressLookupTab1e1111111111111111111111111" || account.data[1] !== "base64") throw new Error("Invalid lookup table account.");
1430
+ const table = parseAddressLookupTable(base64Decode(account.data[0]));
1431
+ for (const [indexes, into] of [[lookup.writable, writable], [lookup.readonly, readonly]]) for (const index of indexes) {
1432
+ if (!table[index]) throw new Error("Lookup table index out of range.");
1433
+ into.push(table[index]);
1434
+ }
1435
+ });
1436
+ return [...tx.staticKeys, ...writable, ...readonly];
1437
+ }
1438
+ function encodeNextSolanaOrders(legs) {
1439
+ return legs.length ? hexBytes(`0x${uintWord(32)}${encodeSubmitOrder(legs).slice(10 + 128)}`) : new Uint8Array();
1440
+ }
1441
+ function checkSolanaRouteBuffer(account, expected) {
1442
+ if (!account || account.owner !== expected.program || account.data[1] !== "base64") throw new Error("Route buffer is not a ZeroDelta account.");
1443
+ const d = base64Decode(account.data[0]);
1444
+ if (d.length < 53) throw new Error("Route buffer truncated.");
1445
+ if (base58Encode(d.subarray(9, 41)) !== expected.signer) throw new Error("Route buffer signer mismatch.");
1446
+ const len = new DataView(d.buffer, d.byteOffset + 49, 4).getUint32(0, true);
1447
+ if (d.length < 53 + len || !bytesEqual(d.subarray(53, 53 + len), encodeNextSolanaOrders(expected.nextOrders))) throw new Error("Route buffer legs mismatch.");
1448
+ }
1449
+ function checkSolanaProgram(gateway, pinned, registry) {
1450
+ const program = gateway || registry || "";
1451
+ solanaKeyBytes(program);
1452
+ if (pinned ? program !== pinned : gateway && registry && gateway !== registry) throw new Error("Solana program does not match pin or chains registry.");
1453
+ return program;
1454
+ }
1455
+ function checkSolanaPlan(txs) {
1456
+ 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.");
1457
+ }
1458
+ async function deriveSolanaEvent(signer, salt) {
1459
+ const s = hexBytes(salt), material = new Uint8Array(32 + s.length);
1460
+ material.set(solanaKeyBytes(signer));
1461
+ material.set(s, 32);
1462
+ const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", material));
1463
+ const { eventPublicKey: eventPublicKey2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
1464
+ return { seed, publicKey: base58Encode(await eventPublicKey2(seed)) };
1465
+ }
1466
+ async function cosignSolanaEvent(bytes, signer, build) {
1467
+ const event = await deriveSolanaEvent(signer, build.salt);
1468
+ if (event.publicKey !== build.messageSentEventData) throw new Error("Event buildData key mismatch; refusing to sign.");
1469
+ const tx = parseSolanaTransaction(bytes);
1470
+ const { eventSignature: eventSignature2 } = await Promise.resolve().then(() => (init_ed255192(), ed25519_exports2));
1471
+ return placeSignature(bytes, event.publicKey, await eventSignature2(tx.bytes.subarray(tx.messageOffset), event.seed));
1472
+ }
1473
+ async function pollSolanaConfirmation(rpc, signature) {
1474
+ const deadline = Date.now() + 9e4;
1475
+ while (Date.now() < deadline) {
1476
+ const { value } = await rpc("getSignatureStatuses", [[signature]]);
1477
+ const status = value?.[0];
1478
+ if (status?.err) throw new Error(`Transaction failed on chain: ${JSON.stringify(status.err)}`);
1479
+ if (["confirmed", "finalized"].includes(status?.confirmationStatus)) return;
1480
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
1481
+ }
1482
+ throw new Error("Transaction confirmation timed out; check the signature before retrying.");
459
1483
  }
460
- function requiresNativeBridgeFee(quote, option = {}) {
461
- const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
462
- const execChainId = Number(quote?.executionChainId);
463
- if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
464
- return false;
1484
+
1485
+ // src/core/units.ts
1486
+ function assetDecimals(token) {
1487
+ const sym = symbolKey(token?.symbol);
1488
+ const registry = Number(token?.decimals);
1489
+ const canonical = isSolanaChainId(token?.chainId) ? solanaDestinationAsset(token?.address)?.decimals : CANONICAL_DECIMALS[sym];
1490
+ if (canonical !== void 0) {
1491
+ if (!Number.isInteger(registry)) {
1492
+ throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
1493
+ }
1494
+ if (registry !== canonical) {
1495
+ throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
1496
+ }
1497
+ return canonical;
465
1498
  }
466
- const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
467
- if (canonical) return canonical === "layerzero";
468
- return isLayerZeroRoute(quote, option);
1499
+ if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
1500
+ throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
1501
+ }
1502
+ return registry;
469
1503
  }
470
- function applyLayerZeroBuffer(quote, option = {}) {
471
- const gas = BigInt(quote?.gasCostSource || "0");
472
- if (gas <= 0n) return 0n;
473
- if (!requiresNativeBridgeFee(quote, option)) return 0n;
474
- return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
1504
+ function normalizeDecimalText(value) {
1505
+ const text = String(value || "").trim().replace(/\s+/g, "");
1506
+ if (!text) return "";
1507
+ if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
1508
+ if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
1509
+ if (text.includes(",")) return "";
1510
+ return text;
1511
+ }
1512
+ function parseUnitsDecimal(amount, decimals) {
1513
+ const text = normalizeDecimalText(amount);
1514
+ if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
1515
+ const [whole, frac = ""] = text.split(".");
1516
+ if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
1517
+ const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
1518
+ const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
1519
+ if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
1520
+ return value;
1521
+ }
1522
+ function scaleDecimals(amount, fromDecimals, toDecimals) {
1523
+ if (toDecimals === fromDecimals) return amount;
1524
+ if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
1525
+ return amount / 10n ** BigInt(fromDecimals - toDecimals);
1526
+ }
1527
+ function formatUnits(raw2, decimals, maxDecimals = 6) {
1528
+ const value = BigInt(raw2 || "0");
1529
+ const base = 10n ** BigInt(decimals);
1530
+ const whole = value / base;
1531
+ const fracFull = (value % base).toString().padStart(decimals, "0");
1532
+ const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
1533
+ return frac ? `${whole}.${frac}` : whole.toString();
1534
+ }
1535
+ function finalOf(quote) {
1536
+ return BigInt(quote?.finalAmount || quote?.toAmount || "0");
1537
+ }
1538
+
1539
+ // src/core/ask-scale.ts
1540
+ function askTokenDecimals(quote, tokens, _from, to) {
1541
+ const requests = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
1542
+ const execution = Number(requests[requests.length - 1]?.executionChainId || quote.executionChainId);
1543
+ if (!Number.isSafeInteger(execution) || execution <= 0) throw new Error("Could not verify the quote amount precision.");
1544
+ if (execution === Number(to.chainId)) return assetDecimals(to);
1545
+ const row = tokens.find((token) => Number(token.chainId) === execution && symbolKey(token.symbol) === symbolKey(to.symbol));
1546
+ if (row) return assetDecimals(row);
1547
+ if (isSolanaChainId(to.chainId)) throw new Error("Could not verify the quote amount precision.");
1548
+ return assetDecimals(to);
1549
+ }
1550
+ function askCovers(ask, final, askDecimals, finalDecimals) {
1551
+ if (![askDecimals, finalDecimals].every((n) => Number.isInteger(n) && n >= 0 && n <= 36)) throw new Error("Could not verify the quote amount precision.");
1552
+ const shift = askDecimals - finalDecimals;
1553
+ return shift >= 0 ? ask >= final * 10n ** BigInt(shift) : ask * 10n ** BigInt(-shift) >= final;
475
1554
  }
476
1555
 
477
1556
  // src/core/ticker.ts
@@ -512,7 +1591,7 @@ function counterpartTokens(tokens, selected) {
512
1591
  return tokens.filter((token) => assetClassOf(token.symbol) === want);
513
1592
  }
514
1593
  function tokenKey(chainId, address) {
515
- return `${Number(chainId)}:${String(address || "").toLowerCase()}`;
1594
+ return `${Number(chainId)}:${chainAddressKey(chainId, address)}`;
516
1595
  }
517
1596
  function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
518
1597
  return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
@@ -598,7 +1677,7 @@ function buildCatalogue(input) {
598
1677
  const id = Number(route.toChainId);
599
1678
  if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
600
1679
  }
601
- const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
1680
+ const allowed = tokens.filter((token) => token.isEnabled !== false && isChainAddress(token.chainId, token.address) && allowedAssets.has(symbolKey(token.symbol)));
602
1681
  const projectedCatalogue = allowed.filter((token) => {
603
1682
  if (!chainIds.has(Number(token.chainId))) return false;
604
1683
  if (product === "rwa") return true;
@@ -632,23 +1711,23 @@ function buildCatalogue(input) {
632
1711
 
633
1712
  // src/core/options.ts
634
1713
  function chainNameOf(chainId, chains) {
635
- const chain = chains.find((item) => Number(item.chainId) === Number(chainId));
636
- return chain?.displayName || chain?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
1714
+ const chain2 = chains.find((item) => Number(item.chainId) === Number(chainId));
1715
+ return chain2?.displayName || chain2?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
637
1716
  }
638
1717
  function chainById(chains, chainId) {
639
- return chains.find((chain) => Number(chain.chainId) === Number(chainId)) || null;
1718
+ return chains.find((chain2) => Number(chain2.chainId) === Number(chainId)) || null;
640
1719
  }
641
1720
  function isDeliverable(symbol, chainId) {
642
1721
  if (Number(chainId) === 8453 && symbolKey(symbol) === "USDT") return false;
643
1722
  return true;
644
1723
  }
645
- function chainSelectable(chain, chainId) {
1724
+ function chainSelectable(chain2, chainId) {
646
1725
  if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
647
- if (!chain) return true;
648
- return chain.isEnabled !== false;
1726
+ if (!chain2) return true;
1727
+ return chain2.isEnabled !== false;
649
1728
  }
650
1729
  function tokenEnabled(token) {
651
- return token?.isEnabled !== false && isAddress(token?.address) && Number.isFinite(Number(token?.chainId));
1730
+ return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
652
1731
  }
653
1732
  function findToken(tokens, chainId, symbol) {
654
1733
  const key = symbolKey(symbol);
@@ -684,8 +1763,8 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
684
1763
  for (const token of universe) {
685
1764
  if (!tokenEnabled(token)) continue;
686
1765
  const chainId = Number(token.chainId);
687
- const chain = chainById(chains, chainId);
688
- if (!chainSelectable(chain, chainId)) continue;
1766
+ const chain2 = chainById(chains, chainId);
1767
+ if (!chainSelectable(chain2, chainId)) continue;
689
1768
  const key = tokenKey(chainId, token.address);
690
1769
  if (seen.has(key)) continue;
691
1770
  if (refusal(token)) continue;
@@ -725,12 +1804,645 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
725
1804
  return options;
726
1805
  }
727
1806
 
1807
+ // src/core/solana-source.ts
1808
+ var CANONICAL_SOLANA_PROGRAM = "zd1E5feCJLNYaPPsBAYkCPMKGVnipYf8God9h917W33";
1809
+ var MAX_ASK_OVER_FINAL_BPS = 200n;
1810
+ var states = /* @__PURE__ */ new WeakMap();
1811
+ var quoteRequests = /* @__PURE__ */ new WeakMap();
1812
+ var inFlight = /* @__PURE__ */ new Map();
1813
+ var activeSigners = /* @__PURE__ */ new Set();
1814
+ var clone = (value) => JSON.parse(JSON.stringify(value));
1815
+ function freeze(value) {
1816
+ if (value && typeof value === "object") {
1817
+ for (const v of Object.values(value)) freeze(v);
1818
+ Object.freeze(value);
1819
+ }
1820
+ return value;
1821
+ }
1822
+ function raw(value, label, positive = false) {
1823
+ if (typeof value !== "string" || !/^\d+$/.test(value) || positive && BigInt(value) <= 0n || BigInt(value) >= 1n << 256n) throw new Error(`Invalid ${label}.`);
1824
+ return value;
1825
+ }
1826
+ function chain(value) {
1827
+ const text = String(value);
1828
+ if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) >= 1n << 64n) throw new Error("Invalid order chain.");
1829
+ return text;
1830
+ }
1831
+ function same(a, b) {
1832
+ return a.toLowerCase() === b.toLowerCase();
1833
+ }
1834
+ function recipient(input) {
1835
+ const to = input.recipient || (isSolanaChainId(input.toChainId) ? input.sender : input.owner);
1836
+ if (!isChainAddress(input.toChainId, to)) throw new Error("Invalid destination recipient.");
1837
+ return chainAddressKey(input.toChainId, to);
1838
+ }
1839
+ function validateInput(input) {
1840
+ if (input.fromChainId !== void 0 && input.fromChainId !== SOLANA_CHAIN_ID) throw new Error("Solana source chain required.");
1841
+ if (!Number.isSafeInteger(input.toChainId) || input.toChainId <= 0) throw new Error("Invalid destination chain.");
1842
+ if (!SUPPORTED_ASSETS.has(symbolKey(input.fromToken)) || !SUPPORTED_ASSETS.has(symbolKey(input.toToken))) throw new Error("Unsupported Solana source asset.");
1843
+ assertAddress(input.owner, "EVM order owner");
1844
+ solanaKeyBytes(input.sender);
1845
+ recipient(input);
1846
+ const span = input.deadlineSpanSeconds ?? 7200, slip = input.slippageBps ?? 0;
1847
+ if (!Number.isInteger(span) || span < 1 || span > 86400) throw new Error("Invalid Solana deadline span.");
1848
+ if (!Number.isInteger(slip) || slip < 0 || slip > 1e4) throw new Error("Invalid slippage tolerance.");
1849
+ }
1850
+ function selections(input, tokens) {
1851
+ validateInput(input);
1852
+ const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
1853
+ if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
1854
+ solanaKeyBytes(from.address);
1855
+ assertPinnedSolanaSource(from);
1856
+ if (!isChainAddress(input.toChainId, to.address)) throw new Error("Invalid destination token.");
1857
+ const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
1858
+ raw(amount, "input amount", true);
1859
+ if (BigInt(amount) >= 1n << 64n) throw new Error("Solana bid exceeds u64.");
1860
+ return { from, to, amount };
1861
+ }
1862
+ function assertPinnedSolanaSource(token) {
1863
+ const pinned = solanaDestinationAsset(token.address);
1864
+ if (!pinned || pinned.symbol !== symbolKey(token.symbol) || pinned.decimals !== Number(token.decimals)) {
1865
+ throw new Error("This Solana token is not supported for payment; refusing to sign.");
1866
+ }
1867
+ }
1868
+ function makeRequest(input, from, to, amount) {
1869
+ return {
1870
+ inputChain: SOLANA_CHAIN_ID,
1871
+ outputChain: input.toChainId,
1872
+ inputToken: from.symbol,
1873
+ outputToken: to.symbol,
1874
+ inputAmount: amount,
1875
+ owners: { evm: input.owner },
1876
+ destinationWallet: recipient(input),
1877
+ sender: input.sender,
1878
+ deadline: String(Math.floor(Date.now() / 1e3) + (input.deadlineSpanSeconds ?? 7200))
1879
+ };
1880
+ }
1881
+ function normalizePreview(request, quote, to, amount) {
1882
+ const option = quote?.options?.[0];
1883
+ if (!option) throw new Error("Native quote returned no options.");
1884
+ const receive = raw(option.finalAmount, "quoted output", true);
1885
+ return {
1886
+ receive: formatUnits(receive, assetDecimals(to)),
1887
+ receiveRaw: receive,
1888
+ fromAmount: amount,
1889
+ fromToken: request.inputToken,
1890
+ toToken: request.outputToken,
1891
+ bridge: option.bridge || "",
1892
+ feeBps: Number(option.feeBps || 0),
1893
+ estimatedDuration: Number(option.estimatedTimeSec || 0),
1894
+ via: null,
1895
+ nativeFeeRaw: String(option.gasCostSource || "0"),
1896
+ quote,
1897
+ option,
1898
+ txData: option.txData,
1899
+ request
1900
+ };
1901
+ }
1902
+ async function quoteSolanaSource(api, input) {
1903
+ const { from, to, amount } = selections(input, await api.fetchTokens());
1904
+ const request = makeRequest(input, from, to, amount);
1905
+ const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1906
+ const preview = normalizePreview(request, quote, to, input.amountIn);
1907
+ quoteRequests.set(preview, { api, request: clone(request) });
1908
+ return preview;
1909
+ }
1910
+ async function previewSolanaSource(api, input) {
1911
+ const tokens = await api.fetchTokens();
1912
+ const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
1913
+ if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
1914
+ assertPinnedSolanaSource(from);
1915
+ const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
1916
+ raw(amount, "input amount", true);
1917
+ const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
1918
+ const request = body;
1919
+ const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1920
+ const option = quote?.options?.[0];
1921
+ if (!option) throw new Error("Native quote returned no options.");
1922
+ const receive = raw(option.finalAmount, "quoted output", true);
1923
+ return {
1924
+ receive: formatUnits(receive, assetDecimals(to)),
1925
+ receiveRaw: receive,
1926
+ fromAmount: input.amountIn,
1927
+ fromToken: request.inputToken,
1928
+ toToken: request.outputToken,
1929
+ bridge: option.bridge || "",
1930
+ feeBps: Number(option.feeBps || 0),
1931
+ estimatedDuration: Number(option.estimatedTimeSec || 0),
1932
+ via: null,
1933
+ nativeFeeRaw: "0"
1934
+ };
1935
+ }
1936
+ function solanaQuoteCompliance(quote) {
1937
+ for (const value of [quote?.complianceDecision, quote?.compliance]) {
1938
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1939
+ }
1940
+ return void 0;
1941
+ }
1942
+ function denied(value) {
1943
+ return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
1944
+ }
1945
+ async function checkActiveScreens(api, input) {
1946
+ const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
1947
+ const screens = await Promise.all(addresses.map(async (address) => {
1948
+ try {
1949
+ return await api.screenWallet(address);
1950
+ } catch {
1951
+ return void 0;
1952
+ }
1953
+ }));
1954
+ if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
1955
+ }
1956
+ function jsonGuards(input, preview, tokens, chains) {
1957
+ const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
1958
+ const wanted = makeRequest(input, from, to, amount);
1959
+ for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
1960
+ if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
1961
+ }
1962
+ if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
1963
+ const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
1964
+ if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
1965
+ if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
1966
+ 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.");
1967
+ if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
1968
+ if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
1969
+ if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
1970
+ if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
1971
+ checkSolanaPlan(option.txData);
1972
+ const orders = option.orderRequests;
1973
+ if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
1974
+ const first = orders[0], last = orders[orders.length - 1];
1975
+ if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
1976
+ if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
1977
+ const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
1978
+ if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
1979
+ if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
1980
+ for (let i = 0; i < orders.length; i++) {
1981
+ const order = orders[i];
1982
+ if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
1983
+ raw(order.askTokenAmount, "ask amount", true);
1984
+ raw(order.bidTokenAmount, "bid amount", true);
1985
+ chain(order.destinationChainId);
1986
+ chain(order.executionChainId);
1987
+ if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
1988
+ if (isSolanaChainId(order.destinationChainId)) {
1989
+ if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
1990
+ solanaBridgeOf(to);
1991
+ checkSolanaReceiver(order, recipient(input), to.address);
1992
+ } else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
1993
+ 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.");
1994
+ if (i) {
1995
+ const previous = orders[i - 1];
1996
+ if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
1997
+ if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
1998
+ }
1999
+ }
2000
+ const quoteForScale = { ...option, orderRequests: orders };
2001
+ const execution = Number(last.executionChainId);
2002
+ 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.");
2003
+ const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
2004
+ const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
2005
+ const minFinal = final * (10000n - slip) / 10000n;
2006
+ 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.");
2007
+ 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.");
2008
+ const registry = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
2009
+ const contracts = registry?.contracts;
2010
+ const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry?.escrowContract);
2011
+ const marker = option.partnerId ?? preview.quote.partnerId;
2012
+ 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.");
2013
+ const ask = BigInt(first.askTokenAmount);
2014
+ return {
2015
+ program,
2016
+ signer: input.sender,
2017
+ mint: from.address,
2018
+ owner: input.owner,
2019
+ askToken: first.askToken,
2020
+ minAskTokenAmount: ask.toString(),
2021
+ maxAskTokenAmount: ask.toString(),
2022
+ bidTokenAmount: amount,
2023
+ destinationReceiver: first.destinationReceiver,
2024
+ destinationChainId: String(first.destinationChainId),
2025
+ executionChainId: String(first.executionChainId),
2026
+ deadline: request.deadline,
2027
+ partnerId: marker == null ? null : String(marker),
2028
+ nextOrders: orders.slice(1)
2029
+ };
2030
+ }
2031
+ async function buildSolanaSourcePlan(api, input, quoted) {
2032
+ const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
2033
+ const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
2034
+ 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.");
2035
+ const preview = clone(served);
2036
+ const expected = jsonGuards(input, preview, tokens, chains);
2037
+ await checkActiveScreens(api, input);
2038
+ const plan = freeze({ preview, expected, txData: preview.option.txData });
2039
+ const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
2040
+ states.set(plan, {
2041
+ api,
2042
+ input: clone(input),
2043
+ plan,
2044
+ failed: false,
2045
+ busy: false,
2046
+ originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
2047
+ signatures: [],
2048
+ done: 0
2049
+ });
2050
+ return plan;
2051
+ }
2052
+ function createSolanaRpc(api) {
2053
+ return async (method, params) => {
2054
+ const body = await api.apiRequest("/solana-rpc", {
2055
+ method: "POST",
2056
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
2057
+ timeoutMs: 15e3
2058
+ });
2059
+ if (body.error && solanaLamportShortfall(body.error.data?.logs) !== null) throw new Error(SOL_SHORTFALL_MESSAGE);
2060
+ if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
2061
+ return body.result;
2062
+ };
2063
+ }
2064
+ var SolanaSendError = class extends Error {
2065
+ constructor(message, signature, sentAt) {
2066
+ super(message);
2067
+ this.signature = signature;
2068
+ this.sentAt = sentAt;
2069
+ this.name = "SolanaSendError";
2070
+ }
2071
+ signature;
2072
+ sentAt;
2073
+ };
2074
+ async function executeSolanaPlan(input) {
2075
+ const signature = await runSolanaPlan(input, false);
2076
+ if (!signature) throw new Error("Missing final Solana submit.");
2077
+ return signature;
2078
+ }
2079
+ async function executeSolanaPlanStaged(input) {
2080
+ const signature = await runSolanaPlan(input, true);
2081
+ return signature ? { status: "sent", signature } : { status: "prepared" };
2082
+ }
2083
+ function solanaPlanNeedsPreparation(plan) {
2084
+ const state = states.get(plan);
2085
+ const live = state?.plan ?? plan;
2086
+ return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
2087
+ }
2088
+ async function runSolanaPlan(input, stopBeforeSubmit) {
2089
+ const state = states.get(input.plan);
2090
+ if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
2091
+ if (state.sent) return state.sent;
2092
+ if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
2093
+ if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
2094
+ state.busy = true;
2095
+ activeSigners.add(input.signer.publicKey);
2096
+ let index = 0, completedBeforeRun = state.signatures.length;
2097
+ const progress = (stage) => {
2098
+ const pending = inFlight.get(input.signer.publicKey);
2099
+ try {
2100
+ input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
2101
+ } catch {
2102
+ }
2103
+ };
2104
+ try {
2105
+ progress("preparing");
2106
+ const pending = inFlight.get(input.signer.publicKey);
2107
+ if (pending) {
2108
+ const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
2109
+ const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
2110
+ if (status?.err) inFlight.delete(input.signer.publicKey);
2111
+ else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
2112
+ inFlight.delete(input.signer.publicKey);
2113
+ if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
2114
+ if (pending.final) {
2115
+ pending.state.sent = pending.signature;
2116
+ reportSolana(pending.state, pending.signature);
2117
+ if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
2118
+ progress("sent");
2119
+ return pending.signature;
2120
+ }
2121
+ } else {
2122
+ if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
2123
+ throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
2124
+ }
2125
+ inFlight.delete(input.signer.publicKey);
2126
+ }
2127
+ }
2128
+ if (state.failed) {
2129
+ const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
2130
+ 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.");
2131
+ state.plan = retried;
2132
+ state.done = 0;
2133
+ state.failed = false;
2134
+ }
2135
+ const plan = state.plan;
2136
+ checkSolanaPlan(plan.txData);
2137
+ for (const tx of plan.txData) {
2138
+ const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
2139
+ verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
2140
+ }
2141
+ for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
2142
+ completedBeforeRun = state.signatures.length;
2143
+ const startAt = state.done;
2144
+ for (index = startAt; index < plan.txData.length; index++) {
2145
+ if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
2146
+ progress("ready");
2147
+ return null;
2148
+ }
2149
+ if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
2150
+ await checkActiveScreens(state.api, state.input);
2151
+ const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
2152
+ const keys = await resolveSolanaKeys(parsed, input.rpc);
2153
+ const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
2154
+ if (buffer) {
2155
+ const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
2156
+ checkSolanaRouteBuffer(account.value, plan.expected);
2157
+ }
2158
+ const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
2159
+ let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
2160
+ if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
2161
+ verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
2162
+ progress("signing");
2163
+ const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
2164
+ assertWalletMessage(bytes, signed);
2165
+ verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
2166
+ const signedTx = parseSolanaTransaction(signed);
2167
+ const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
2168
+ const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
2169
+ inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
2170
+ progress("sending");
2171
+ try {
2172
+ const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
2173
+ if (returned !== signature) throw new Error("RPC returned a different signature.");
2174
+ if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
2175
+ } catch (error) {
2176
+ throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
2177
+ }
2178
+ inFlight.delete(input.signer.publicKey);
2179
+ state.signatures.push(signature);
2180
+ state.done = index + 1;
2181
+ if (tx.actionType === "submit") {
2182
+ state.sent = signature;
2183
+ reportSolana(state, signature);
2184
+ progress("sent");
2185
+ return signature;
2186
+ }
2187
+ progress("ready");
2188
+ }
2189
+ throw new Error("Missing final Solana submit.");
2190
+ } catch (error) {
2191
+ state.failed = true;
2192
+ progress("failed");
2193
+ throw error;
2194
+ } finally {
2195
+ state.busy = false;
2196
+ activeSigners.delete(input.signer.publicKey);
2197
+ }
2198
+ }
2199
+ function reportSolana(state, signature) {
2200
+ try {
2201
+ void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
2202
+ });
2203
+ } catch {
2204
+ }
2205
+ }
2206
+ async function readSolanaBalance(rpc, owner, mint) {
2207
+ try {
2208
+ solanaKeyBytes(owner);
2209
+ solanaKeyBytes(mint);
2210
+ const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
2211
+ if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
2212
+ let total = 0n, decimals;
2213
+ for (const item of result.value) {
2214
+ const amount = item.account?.data?.parsed?.info?.tokenAmount;
2215
+ if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
2216
+ decimals = amount.decimals;
2217
+ total += BigInt(raw(amount.amount, "token balance"));
2218
+ }
2219
+ return total;
2220
+ } catch {
2221
+ return void 0;
2222
+ }
2223
+ }
2224
+ function solanaLamportShortfall(logs) {
2225
+ if (!Array.isArray(logs)) return null;
2226
+ for (const line of logs) {
2227
+ const m = /insufficient lamports (\d+), need (\d+)/.exec(String(line));
2228
+ if (m) {
2229
+ const need = Number(m[2]);
2230
+ return Number.isSafeInteger(need) && need > 0 ? need : null;
2231
+ }
2232
+ }
2233
+ return null;
2234
+ }
2235
+ var SOL_SHORTFALL_MESSAGE = "Not enough SOL in this wallet for the Solana network fee and account rent. Add a little SOL and try again.";
2236
+ async function simulateSolanaCost(rpc, plan) {
2237
+ checkSolanaPlan(plan.txData);
2238
+ const signer = plan.expected.signer;
2239
+ const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
2240
+ const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
2241
+ const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
2242
+ if (sim.value?.err) {
2243
+ const need = solanaLamportShortfall(sim.value.logs);
2244
+ if (need !== null && Number.isSafeInteger(balanceLamports)) return { lamports: need, balanceLamports, sufficient: false };
2245
+ throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
2246
+ }
2247
+ if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
2248
+ const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
2249
+ return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
2250
+ }
2251
+
2252
+ // src/core/delivery.ts
2253
+ var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "expired", "failed"]);
2254
+ var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim"]);
2255
+ var TRACKING = Object.freeze({ phase: "tracking", status: "", steps: [] });
2256
+ var word = (v) => typeof v === "string" ? v.trim().toLowerCase() : "";
2257
+ function normalizeDelivery(raw2) {
2258
+ const row = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2.data ?? raw2 : null;
2259
+ if (!row || typeof row !== "object" || Array.isArray(row)) return TRACKING;
2260
+ const r = row;
2261
+ const chained = r.isChained === true || Array.isArray(r.legs) && r.legs.length > 1;
2262
+ const journey = word(r.journeyStatus);
2263
+ const own = word(r.status);
2264
+ const status = journey || own;
2265
+ const rawSteps = Array.isArray(r.steps) ? r.steps : [];
2266
+ const steps = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string").sort((a, b) => Number(a.stepNumber ?? 0) - Number(b.stepNumber ?? 0)).slice(0, 8).map((s) => ({ name: String(s.stepName).slice(0, 32), done: s.stepStatus === "completed" }));
2267
+ if (!status) return TRACKING;
2268
+ if (FAILED.has(status)) return { phase: "failed", status, steps };
2269
+ if (ATTENTION.has(status)) return { phase: "attention", status, steps };
2270
+ if (status === "delivered" && !(chained && !journey)) return { phase: "delivered", status, steps: steps.map((s) => ({ ...s, done: true })) };
2271
+ return { phase: "in-progress", status: status === "delivered" ? "continuing" : status, steps };
2272
+ }
2273
+ var HASH = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
2274
+ function sameOrder(raw2, hash2) {
2275
+ const row = raw2 && typeof raw2 === "object" ? raw2.data ?? raw2 : null;
2276
+ const got = row && typeof row === "object" ? row.txHash : void 0;
2277
+ if (typeof got !== "string" || !got) return false;
2278
+ return hash2.startsWith("0x") ? got.toLowerCase() === hash2.toLowerCase() : got === hash2;
2279
+ }
2280
+ async function fetchDelivery(api, hash2) {
2281
+ if (typeof hash2 !== "string" || !HASH.test(hash2)) return TRACKING;
2282
+ try {
2283
+ const raw2 = await api.apiRequest(`/transactions/${hash2}`, { timeoutMs: 8e3 });
2284
+ return sameOrder(raw2, hash2) ? normalizeDelivery(raw2) : TRACKING;
2285
+ } catch {
2286
+ return TRACKING;
2287
+ }
2288
+ }
2289
+
2290
+ // src/core/history.ts
2291
+ var WALLET_HISTORY_LIMIT = 50;
2292
+ var HASH2 = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
2293
+ var WALLET = /^(?:0x[0-9a-fA-F]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$/;
2294
+ function historyKey(value) {
2295
+ return value.startsWith("0x") ? value.toLowerCase() : value;
2296
+ }
2297
+ var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
2298
+ function tokenAt(tokens, chainId, address) {
2299
+ if (!address) return void 0;
2300
+ const key = historyKey(address);
2301
+ return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key);
2302
+ }
2303
+ function amountOf(raw2, token, rowDecimals, rowAmount) {
2304
+ const decimals = token ? Number(token.decimals) : Number(rowDecimals);
2305
+ if (/^\d{1,78}$/.test(raw2) && Number.isInteger(decimals) && decimals > 0 && decimals <= 36) return formatUnits(raw2, decimals);
2306
+ return Number(rowDecimals) > 0 && /^\d+(?:\.\d+)?$/.test(rowAmount) ? rowAmount.slice(0, 40) : "";
2307
+ }
2308
+ function historyEntryFromOrder(raw2, tokens) {
2309
+ if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return null;
2310
+ const r = raw2;
2311
+ const hash2 = str(r.txHash);
2312
+ if (!HASH2.test(hash2)) return null;
2313
+ const fromChainId = Number(r.sourceChainId) || 0;
2314
+ const toChainId = Number(r.finalDestChainId ?? r.destChainId) || 0;
2315
+ const from = tokenAt(tokens, fromChainId, str(r.fromTokenAddress));
2316
+ const toAddress = str(r.finalToTokenAddress) || str(r.toTokenAddress);
2317
+ const to = tokenAt(tokens, toChainId, toAddress);
2318
+ const fromAsset = (from?.symbol ?? str(r.fromTokenSymbol)).slice(0, 10);
2319
+ const toAsset = (to?.symbol ?? (str(r.finalToTokenSymbol) || str(r.toTokenSymbol))).slice(0, 10);
2320
+ const payAmount = amountOf(str(r.fromTokenRawAmount), from, r.fromTokenDecimals, str(r.fromTokenAmount));
2321
+ const receiveAmount = str(r.finalToTokenRawAmount) ? amountOf(str(r.finalToTokenRawAmount), to, r.finalToTokenDecimals, str(r.finalToTokenAmount)) : amountOf(str(r.toTokenRawAmount), to, r.toTokenDecimals, str(r.toTokenAmount));
2322
+ const delivery = normalizeDelivery(r).phase;
2323
+ const wallet = str(r.wallet);
2324
+ const receiver = str(r.destinationReceiver);
2325
+ const at = str(r.createdAt) || str(r.submittedAt);
2326
+ return {
2327
+ kind: "swap",
2328
+ hash: hash2,
2329
+ txKind: "submitOrder",
2330
+ chainId: fromChainId || null,
2331
+ chainName: "",
2332
+ fromAsset,
2333
+ toAsset,
2334
+ fromTicker: from ? tokenTicker(from).slice(0, 12) : void 0,
2335
+ toTicker: to ? tokenTicker(to).slice(0, 12) : void 0,
2336
+ payAmount,
2337
+ receiveAmount,
2338
+ account: WALLET.test(wallet) ? historyKey(wallet) : "",
2339
+ recipient: WALLET.test(receiver) ? receiver : "",
2340
+ settlement: "escrow",
2341
+ status: "submitted",
2342
+ at: Number.isNaN(Date.parse(at)) ? (/* @__PURE__ */ new Date(0)).toISOString() : new Date(at).toISOString(),
2343
+ delivery: delivery === "tracking" || delivery === "unavailable" ? void 0 : delivery,
2344
+ legs: [
2345
+ {
2346
+ index: 1,
2347
+ fromAsset,
2348
+ fromTicker: from ? tokenTicker(from).slice(0, 12) : void 0,
2349
+ fromChainId,
2350
+ fromChainName: "",
2351
+ fromAmount: payAmount,
2352
+ toAsset,
2353
+ toTicker: to ? tokenTicker(to).slice(0, 12) : void 0,
2354
+ toChainId,
2355
+ toChainName: "",
2356
+ toAmount: receiveAmount,
2357
+ executionChainId: Number(r.executionChainId) || 0,
2358
+ executionChainName: ""
2359
+ }
2360
+ ]
2361
+ };
2362
+ }
2363
+ async function fetchWalletHistory(api, wallets) {
2364
+ const asked = [...new Set(wallets.filter((w) => WALLET.test(w)).map(historyKey))];
2365
+ if (!asked.length) return [];
2366
+ const tokens = await api.fetchTokens().catch(() => []);
2367
+ const reads = await Promise.all(
2368
+ asked.map(async (wallet) => {
2369
+ try {
2370
+ const rows = await api.apiRequest(`/transactions?wallet=${encodeURIComponent(wallet)}&limit=${WALLET_HISTORY_LIMIT}`, { timeoutMs: 1e4 });
2371
+ if (!Array.isArray(rows)) return null;
2372
+ return rows.filter((row) => historyKey(str(row?.wallet)) === wallet).map((row) => historyEntryFromOrder(row, tokens));
2373
+ } catch {
2374
+ return null;
2375
+ }
2376
+ })
2377
+ );
2378
+ if (reads.every((read) => read === null)) return null;
2379
+ return reads.flatMap((read) => read ?? []).filter((e) => e !== null);
2380
+ }
2381
+ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
2382
+ const byHash = /* @__PURE__ */ new Map();
2383
+ for (const entry of remote ?? []) if (!byHash.has(historyKey(entry.hash))) byHash.set(historyKey(entry.hash), entry);
2384
+ const out = [];
2385
+ const seen = /* @__PURE__ */ new Set();
2386
+ for (const entry of local) {
2387
+ const key = historyKey(entry.hash);
2388
+ if (seen.has(key)) continue;
2389
+ seen.add(key);
2390
+ const known = byHash.get(key);
2391
+ out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
2392
+ }
2393
+ for (const [key, entry] of byHash) if (!seen.has(key)) out.push(entry);
2394
+ return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
2395
+ }
2396
+
2397
+ // src/core/escrow.ts
2398
+ function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
2399
+ const fromQuote = normalizeAddress(quoteEscrow);
2400
+ const fromChains = normalizeAddress(chainsEscrow);
2401
+ if (!fromChains || fromChains === ZERO_ADDRESS) {
2402
+ throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
2403
+ }
2404
+ if (!fromQuote || fromQuote === ZERO_ADDRESS) {
2405
+ throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
2406
+ }
2407
+ if (fromQuote !== fromChains) {
2408
+ throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
2409
+ }
2410
+ const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
2411
+ if (pinned && pinned !== fromChains) {
2412
+ throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
2413
+ }
2414
+ return fromChains;
2415
+ }
2416
+ function isLayerZeroRoute(quote, option = {}) {
2417
+ const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
2418
+ return bridge.includes("layerzero") || bridge.includes("layer zero");
2419
+ }
2420
+ function sourceAssetKey(quote, option = {}) {
2421
+ return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
2422
+ }
2423
+ function requiresNativeBridgeFee(quote, option = {}) {
2424
+ const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
2425
+ const execChainId = Number(quote?.executionChainId);
2426
+ if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
2427
+ return false;
2428
+ }
2429
+ const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
2430
+ if (canonical) return canonical === "layerzero";
2431
+ return isLayerZeroRoute(quote, option);
2432
+ }
2433
+ function applyLayerZeroBuffer(quote, option = {}) {
2434
+ const gas = BigInt(quote?.gasCostSource || "0");
2435
+ if (gas <= 0n) return 0n;
2436
+ if (!requiresNativeBridgeFee(quote, option)) return 0n;
2437
+ return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
2438
+ }
2439
+
728
2440
  // src/core/native-fee.ts
729
2441
  function routeNativeValue(route) {
730
2442
  try {
731
- const raw = route?.quote?.msgValue;
732
- if (raw === void 0 || raw === null || raw === "") return 0n;
733
- const value = BigInt(raw);
2443
+ const raw2 = route?.quote?.msgValue;
2444
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
2445
+ const value = BigInt(raw2);
734
2446
  return value > 0n ? value : 0n;
735
2447
  } catch {
736
2448
  return 0n;
@@ -765,6 +2477,11 @@ function nativeFeeShortMessage(check, symbol, chainName) {
765
2477
  }
766
2478
 
767
2479
  // src/core/route-health.ts
2480
+ function healthLaneKey(value) {
2481
+ if (typeof value !== "string") return "";
2482
+ const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
2483
+ return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
2484
+ }
768
2485
  var EMPTY = /* @__PURE__ */ new Map();
769
2486
  var NO_LIMITS = /* @__PURE__ */ new Map();
770
2487
  function laneAvailabilityState(lane) {
@@ -784,7 +2501,7 @@ function suppressedLanes(health) {
784
2501
  const out = /* @__PURE__ */ new Map();
785
2502
  for (const lane of health.lanes) {
786
2503
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
787
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
2504
+ const key = healthLaneKey(lane.laneKey);
788
2505
  if (!key) continue;
789
2506
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
790
2507
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
@@ -804,7 +2521,7 @@ function limitedLanes(health) {
804
2521
  const out = /* @__PURE__ */ new Map();
805
2522
  for (const lane of health.lanes) {
806
2523
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
807
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
2524
+ const key = healthLaneKey(lane.laneKey);
808
2525
  const limit = lane.availability?.limit;
809
2526
  if (!key || !limit || typeof limit !== "object") continue;
810
2527
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
@@ -827,14 +2544,14 @@ function limitedLanes(health) {
827
2544
  }
828
2545
  function exceedsLaneLimit(limit, amount, bidDecimals) {
829
2546
  if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
830
- let raw;
2547
+ let raw2;
831
2548
  try {
832
- raw = parseUnitsDecimal(amount, bidDecimals);
2549
+ raw2 = parseUnitsDecimal(amount, bidDecimals);
833
2550
  } catch {
834
2551
  return false;
835
2552
  }
836
2553
  const scale = Math.max(bidDecimals, limit.decimals);
837
- return scaleDecimals(raw, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
2554
+ return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
838
2555
  }
839
2556
  function laneLimitAmount(limit) {
840
2557
  return formatUnits(limit.maxAmount, limit.decimals);
@@ -931,11 +2648,11 @@ function complianceView(compliance, hasQuote = true) {
931
2648
  };
932
2649
  }
933
2650
  if (decision === "REVIEW" || decision === "REMEDIATE") {
934
- const word = decision.toLowerCase();
2651
+ const word2 = decision.toLowerCase();
935
2652
  return {
936
2653
  tone: "warn",
937
- label: `Compliance: ${word} required`,
938
- headline: `Manual ${word} required`,
2654
+ label: `Compliance: ${word2} required`,
2655
+ headline: `Manual ${word2} required`,
939
2656
  blocked: false,
940
2657
  needsAction: true,
941
2658
  screened
@@ -1000,12 +2717,12 @@ function stripBundlePrefix(head) {
1000
2717
  if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
1001
2718
  return { head, source: null };
1002
2719
  }
1003
- function complianceReasonHead(raw) {
1004
- return stripBundlePrefix((raw.split(":")[0] ?? "").trim()).head;
2720
+ function complianceReasonHead(raw2) {
2721
+ return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
1005
2722
  }
1006
- function usd(raw) {
1007
- const n = Number(raw);
1008
- if (!Number.isFinite(n)) return `$${raw}`;
2723
+ function usd(raw2) {
2724
+ const n = Number(raw2);
2725
+ if (!Number.isFinite(n)) return `$${raw2}`;
1009
2726
  return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
1010
2727
  }
1011
2728
  function capFromDetail(detail) {
@@ -1016,8 +2733,8 @@ function categoryPhrase(detail) {
1016
2733
  const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
1017
2734
  return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
1018
2735
  }
1019
- function humanizeComplianceReason(raw) {
1020
- const [headRaw, ...restParts] = raw.split(":");
2736
+ function humanizeComplianceReason(raw2) {
2737
+ const [headRaw, ...restParts] = raw2.split(":");
1021
2738
  const detail = restParts.join(":").trim();
1022
2739
  const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
1023
2740
  const scope = source === "legislation" ? "applicable regulations" : "the applicable policy";
@@ -1094,8 +2811,8 @@ var CHECK_HEADS = {
1094
2811
  function distinctScreenedWallets(compliance) {
1095
2812
  const seen = /* @__PURE__ */ new Set();
1096
2813
  const wallets = [];
1097
- for (const raw of compliance?.screenedWallets ?? []) {
1098
- const address = raw?.trim();
2814
+ for (const raw2 of compliance?.screenedWallets ?? []) {
2815
+ const address = raw2?.trim();
1099
2816
  if (!address) continue;
1100
2817
  const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
1101
2818
  if (seen.has(key)) continue;
@@ -1115,11 +2832,11 @@ function screeningLabel(wallets) {
1115
2832
  function complianceChecks(compliance, cv = complianceView(compliance)) {
1116
2833
  if (cv.tone === "neutral") return [];
1117
2834
  const byControl = /* @__PURE__ */ new Map();
1118
- for (const raw of compliance?.reasons ?? []) {
1119
- const head = complianceReasonHead(raw);
2835
+ for (const raw2 of compliance?.reasons ?? []) {
2836
+ const head = complianceReasonHead(raw2);
1120
2837
  const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
1121
2838
  if (!id) continue;
1122
- byControl.set(id, [...byControl.get(id) ?? [], raw]);
2839
+ byControl.set(id, [...byControl.get(id) ?? [], raw2]);
1123
2840
  }
1124
2841
  const screenedWallets = distinctScreenedWallets(compliance);
1125
2842
  const wallets = screenedWallets.length;
@@ -1143,8 +2860,8 @@ function complianceControlsEvaluated(compliance, cv = complianceView(compliance)
1143
2860
  const checks = complianceChecks(compliance, cv);
1144
2861
  if (checks.length === 0) return 0;
1145
2862
  const named = /* @__PURE__ */ new Set();
1146
- for (const raw of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
1147
- const name = raw?.trim();
2863
+ for (const raw2 of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
2864
+ const name = raw2?.trim();
1148
2865
  if (name) named.add(name.toLowerCase());
1149
2866
  }
1150
2867
  return checks.length + named.size;
@@ -1184,8 +2901,8 @@ var BLOCK_CATEGORY_LABELS = {
1184
2901
  };
1185
2902
  var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
1186
2903
  function blockLabelFor(categories) {
1187
- for (const raw of categories) {
1188
- const label = BLOCK_CATEGORY_LABELS[String(raw || "").trim().toUpperCase()];
2904
+ for (const raw2 of categories) {
2905
+ const label = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
1189
2906
  if (label) return label;
1190
2907
  }
1191
2908
  return BLOCK_LABEL_DEFAULT;
@@ -1206,8 +2923,8 @@ var REASON_TAGS = {
1206
2923
  dest_chain_not_allowed: "Chain not allowed",
1207
2924
  jurisdiction_out_of_scope: "Out of scope"
1208
2925
  };
1209
- function complianceReasonTag(raw) {
1210
- const head = complianceReasonHead(raw);
2926
+ function complianceReasonTag(raw2) {
2927
+ const head = complianceReasonHead(raw2);
1211
2928
  return REASON_TAGS[head] ?? head.replace(/_/g, " ");
1212
2929
  }
1213
2930
  function complianceTagOf(compliance) {
@@ -1270,8 +2987,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1270
2987
  const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
1271
2988
  const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
1272
2989
  const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
1273
- const enforcePayCeiling = (raw) => {
1274
- if (maxPayRaw > 0n && BigInt(raw) > maxPayRaw) {
2990
+ const enforcePayCeiling = (raw2) => {
2991
+ if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
1275
2992
  throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
1276
2993
  }
1277
2994
  };
@@ -1295,7 +3012,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1295
3012
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
1296
3013
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1297
3014
  }
1298
- const guaranteed = BigInt(quote?.toAmount || "0");
3015
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1299
3016
  const final = finalOf(quote);
1300
3017
  if (final > bestFinal) {
1301
3018
  bestFinal = final;
@@ -1332,7 +3049,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1332
3049
  directTransfer: false,
1333
3050
  quote: best,
1334
3051
  youPayRaw: bestGuess.toString(),
1335
- recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
3052
+ recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
1336
3053
  targetRaw: targetRaw.toString(),
1337
3054
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
1338
3055
  meetsTarget: bestFinal >= targetRaw,
@@ -1354,7 +3071,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
1354
3071
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
1355
3072
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1356
3073
  }
1357
- const guaranteed = BigInt(quote?.toAmount || "0");
3074
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1358
3075
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
1359
3076
  return {
1360
3077
  directTransfer: false,
@@ -1385,13 +3102,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
1385
3102
  const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
1386
3103
  const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
1387
3104
  if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
3105
+ const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
3106
+ const keyBytes2 = (value, label) => {
3107
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label} is not a valid 32-byte Solana key.`);
3108
+ return String(value).toLowerCase();
3109
+ };
1388
3110
  return {
1389
3111
  owner: assertAddress(order.owner || payer, "Order owner"),
1390
3112
  bidToken: assertAddress(order.bidToken, "Bid token"),
1391
3113
  bidTokenAmount: String(order.bidTokenAmount || "0"),
1392
- askToken: assertAddress(order.askToken, "Ask token"),
3114
+ askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
1393
3115
  askTokenAmount: String(order.askTokenAmount || "0"),
1394
- destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
3116
+ destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
3117
+ ...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
1395
3118
  destinationChainId: String(order.destinationChainId || destination.chainId),
1396
3119
  executionChainId,
1397
3120
  deadline
@@ -1403,17 +3126,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
1403
3126
  (request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
1404
3127
  );
1405
3128
  }
1406
- function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
3129
+ function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
1407
3130
  const list = orders?.length ? orders : [order];
1408
3131
  const sourceOrder = list[0];
1409
3132
  const finalOrder = list[list.length - 1];
1410
3133
  const now = Math.floor(Date.now() / 1e3);
1411
3134
  const deadline = Number(sourceOrder.deadline || 0);
3135
+ const solana = isSolanaChainId(destination.chainId);
3136
+ if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
3137
+ throw new Error("This Solana token is not supported for delivery; refusing to sign.");
3138
+ }
1412
3139
  for (const current of list) {
1413
3140
  if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
1414
3141
  throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
1415
3142
  }
1416
- if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(destination.address)) {
3143
+ if (isSolanaChainId(current.destinationChainId)) {
3144
+ if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
3145
+ checkSolanaReceiver(current, destination.address, destinationToken.address);
3146
+ } else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
1417
3147
  throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
1418
3148
  }
1419
3149
  if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
@@ -1423,9 +3153,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1423
3153
  if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
1424
3154
  throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
1425
3155
  }
1426
- if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
3156
+ if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
1427
3157
  throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
1428
3158
  }
3159
+ 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.");
1429
3160
  if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
1430
3161
  throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
1431
3162
  }
@@ -1444,10 +3175,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1444
3175
  if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
1445
3176
  throw new Error("ZeroDelta quote returned a non-positive output amount.");
1446
3177
  }
1447
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
3178
+ const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
3179
+ const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
3180
+ if (!covers(result.targetRaw)) {
1448
3181
  throw new Error("ZeroDelta quote would not cover the requested destination amount.");
1449
3182
  }
1450
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
3183
+ if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
1451
3184
  throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
1452
3185
  }
1453
3186
  const maxDeadline = maxDeadlineSeconds(quote);
@@ -1479,8 +3212,8 @@ function routeDeltaLabel(result, quote) {
1479
3212
  return "~0";
1480
3213
  }
1481
3214
  function quotePartnerId(quote) {
1482
- const raw = quote.partnerId;
1483
- return typeof raw === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw) ? raw.toLowerCase() : NO_PARTNER_ID;
3215
+ const raw2 = quote.partnerId;
3216
+ return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
1484
3217
  }
1485
3218
  function optionTicker(option) {
1486
3219
  return option.ticker || option.symbol;
@@ -1490,15 +3223,16 @@ function routeLabelFor(option, destinationToken, result) {
1490
3223
  const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
1491
3224
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
1492
3225
  }
1493
- function tokenAt(tokens, chainId, address) {
1494
- const wanted = normalizeAddress(address);
3226
+ function tokenAt2(tokens, chainId, address) {
3227
+ const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
3228
+ const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
1495
3229
  if (!wanted || !tokens?.length) return void 0;
1496
- return tokens.find((t) => Number(t.chainId) === Number(chainId) && normalizeAddress(t.address) === wanted);
3230
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
1497
3231
  }
1498
- function legAmount(raw, decimals) {
3232
+ function legAmount(raw2, decimals) {
1499
3233
  if (decimals === void 0) return "";
1500
3234
  try {
1501
- return formatUnits(raw || "0", decimals);
3235
+ return formatUnits(raw2 || "0", decimals);
1502
3236
  } catch {
1503
3237
  return "";
1504
3238
  }
@@ -1513,7 +3247,7 @@ function buildLegs(orders, ctx) {
1513
3247
  const order = orders[index];
1514
3248
  const isLast = index === orders.length - 1;
1515
3249
  const toChainId = Number(order.destinationChainId);
1516
- const askToken = isLast ? ctx.destinationToken : tokenAt(ctx.tokens, toChainId, order.askToken);
3250
+ const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
1517
3251
  const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
1518
3252
  const toTicker = askToken ? tokenTicker(askToken) : "";
1519
3253
  const toDecimals = askToken ? assetDecimals(askToken) : void 0;
@@ -1529,7 +3263,7 @@ function buildLegs(orders, ctx) {
1529
3263
  toTicker,
1530
3264
  toChainId,
1531
3265
  toChainName: chainNameOf(toChainId, ctx.chains),
1532
- toAmount: legAmount(order.askTokenAmount, toDecimals),
3266
+ toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
1533
3267
  executionChainId,
1534
3268
  executionChainName: chainNameOf(executionChainId, ctx.chains)
1535
3269
  });
@@ -1633,8 +3367,12 @@ async function buildRoute({
1633
3367
  const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
1634
3368
  const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
1635
3369
  const order = orders[0];
1636
- assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
1637
- const needsNativeFee = requiresNativeBridgeFee(quote, option);
3370
+ assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
3371
+ const echoedExecution = Number(quote.executionChainId || 0);
3372
+ if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
3373
+ throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
3374
+ }
3375
+ const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
1638
3376
  if (needsNativeFee) {
1639
3377
  let rawFee;
1640
3378
  try {
@@ -1678,7 +3416,7 @@ async function buildRoute({
1678
3416
  },
1679
3417
  routeLabel: routeLabelFor(option, destinationToken, result),
1680
3418
  deltaLabel: routeDeltaLabel(result, quote),
1681
- legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
3419
+ legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
1682
3420
  transactions: [
1683
3421
  {
1684
3422
  id: "approve",
@@ -1711,6 +3449,7 @@ async function buildRoute({
1711
3449
  gasCostSource: quote.gasCostSource,
1712
3450
  msgValue: valueRaw.toString(),
1713
3451
  deadline: order.deadline,
3452
+ ...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
1714
3453
  partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
1715
3454
  iterations: result.iterations,
1716
3455
  // Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
@@ -1726,10 +3465,10 @@ var CHANNEL_HEADER = "x-zd-channel";
1726
3465
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
1727
3466
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
1728
3467
  var WIDGET_CHANNEL = "widget";
1729
- var WIDGET_VERSION = "4.12.0" ;
3468
+ var WIDGET_VERSION = "4.13.1" ;
1730
3469
  var MAX_CHANNEL_VERSION_LEN = 32;
1731
- function sanitizeVersion(raw) {
1732
- const v = String(raw).trim();
3470
+ function sanitizeVersion(raw2) {
3471
+ const v = String(raw2).trim();
1733
3472
  if (!v) return "";
1734
3473
  const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
1735
3474
  return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
@@ -1765,9 +3504,9 @@ function isReportableSubmission(report) {
1765
3504
 
1766
3505
  // src/core/api.ts
1767
3506
  function apiError(message, props = {}) {
1768
- const err = new Error(message);
1769
- Object.assign(err, props);
1770
- return err;
3507
+ const err2 = new Error(message);
3508
+ Object.assign(err2, props);
3509
+ return err2;
1771
3510
  }
1772
3511
  function toQuery(params) {
1773
3512
  const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== "" && v !== null);
@@ -1785,14 +3524,14 @@ function sanitizeMessage(value, fallback) {
1785
3524
  return text.length > MAX_MESSAGE_LEN ? `${text.slice(0, MAX_MESSAGE_LEN - 1)}\u2026` : text;
1786
3525
  }
1787
3526
  function apiMessage(json, fallback) {
1788
- const err = json?.error || json;
1789
- if (err?.fieldErrors?.[0]?.message) return sanitizeMessage(err.fieldErrors[0].message, fallback);
1790
- if (Array.isArray(err?.reasons) && err.reasons.length) {
1791
- const head = sanitizeMessage(err.message, fallback);
1792
- const detail = sanitizeMessage(err.reasons.filter((r) => typeof r === "string").join(", "), "");
3527
+ const err2 = json?.error || json;
3528
+ if (err2?.fieldErrors?.[0]?.message) return sanitizeMessage(err2.fieldErrors[0].message, fallback);
3529
+ if (Array.isArray(err2?.reasons) && err2.reasons.length) {
3530
+ const head = sanitizeMessage(err2.message, fallback);
3531
+ const detail = sanitizeMessage(err2.reasons.filter((r) => typeof r === "string").join(", "), "");
1793
3532
  return detail ? `${head}: ${detail}` : head;
1794
3533
  }
1795
- return sanitizeMessage(err?.message, fallback);
3534
+ return sanitizeMessage(err2?.message, fallback);
1796
3535
  }
1797
3536
  function isStructuredComplianceBlock(error) {
1798
3537
  const code = String(error?.code || "").toUpperCase();
@@ -1932,9 +3671,9 @@ function createApiClient(cfg) {
1932
3671
  if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
1933
3672
  return once("chains", async () => {
1934
3673
  const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
1935
- const normalized = (Array.isArray(chains) ? chains : []).map((chain) => ({ ...chain, chainId: Number(chain.chainId) })).map((chain) => {
1936
- const escrow = normalizeAddress(chain.escrowContract);
1937
- return escrow ? { ...chain, escrowContract: escrow } : { ...chain, escrowContract: void 0 };
3674
+ const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
3675
+ const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
3676
+ return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
1938
3677
  });
1939
3678
  cache.chains = { at: Date.now(), value: normalized };
1940
3679
  return normalized;
@@ -2037,14 +3776,16 @@ function createApiClient(cfg) {
2037
3776
  async function screenWallet(address, chainId) {
2038
3777
  const addr = String(address || "").trim();
2039
3778
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
2040
- const key = `${/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr}|${chainId ?? ""}`;
3779
+ const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3780
+ if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3781
+ const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
2041
3782
  const hit = screenCache.get(key);
2042
3783
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
2043
3784
  const inflight = screenInflight.get(key);
2044
3785
  if (inflight) return inflight;
2045
3786
  const request = apiRequest("/screen/wallet", {
2046
3787
  method: "POST",
2047
- body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
3788
+ body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
2048
3789
  timeoutMs: 12e3
2049
3790
  }).then((screen) => {
2050
3791
  if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
@@ -2084,7 +3825,7 @@ function createApiClient(cfg) {
2084
3825
 
2085
3826
  // src/core/plan.ts
2086
3827
  function optionBalanceKey(option) {
2087
- return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
3828
+ return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
2088
3829
  }
2089
3830
  function hasPositiveBalance(option, balances) {
2090
3831
  try {
@@ -2094,7 +3835,8 @@ function hasPositiveBalance(option, balances) {
2094
3835
  }
2095
3836
  }
2096
3837
  function validateDestination(destination) {
2097
- assertAddress(destination.address, "Destination address");
3838
+ const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
3839
+ if (isSolanaChainId(destination.chainId)) destination.address = address;
2098
3840
  const chainId = Number(destination.chainId);
2099
3841
  const asset = symbolKey(destination.asset);
2100
3842
  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
@@ -2152,8 +3894,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
2152
3894
  if (directOptions.length) {
2153
3895
  const parties = [];
2154
3896
  const seenParty = /* @__PURE__ */ new Set();
2155
- for (const raw of [payer, destination.address]) {
2156
- const addr = String(raw || "").trim();
3897
+ for (const raw2 of [payer, destination.address]) {
3898
+ const addr = String(raw2 || "").trim();
2157
3899
  if (!addr) continue;
2158
3900
  const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
2159
3901
  if (seenParty.has(key)) continue;
@@ -2261,7 +4003,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
2261
4003
  if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
2262
4004
  const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
2263
4005
  const option = buildPayOptions({ invoiceAsset: destination.asset, invoiceChainId: destination.chainId, tokens, routes, chains, walletChainId: wallet.chainId, catalogue }).find(
2264
- (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && o.address.toLowerCase() === String(picked.address).toLowerCase() && (!allowedFunding || allowedFunding.has(o.symbolKey))
4006
+ (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
2265
4007
  );
2266
4008
  if (!option) throw new Error("That funding option is not available for this payment right now.");
2267
4009
  return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
@@ -2284,8 +4026,10 @@ function viaOf(quote, tokens) {
2284
4026
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
2285
4027
  if (orders.length < 2) return null;
2286
4028
  const first = orders[0];
2287
- const wanted = normalizeAddress(first?.askToken);
2288
- const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && normalizeAddress(t.address) === wanted) : void 0;
4029
+ const chainId = Number(first?.destinationChainId);
4030
+ const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
4031
+ const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
4032
+ const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
2289
4033
  return token ? tokenTicker(token) : "";
2290
4034
  }
2291
4035
  async function quoteSwapPreview(api, swap, owner) {
@@ -2297,7 +4041,7 @@ async function quoteSwapPreview(api, swap, owner) {
2297
4041
  if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
2298
4042
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2299
4043
  const account = normalizeAddress(owner) || PREVIEW_OWNER;
2300
- const previewReceiver = normalizeAddress(swap.recipient) || account;
4044
+ const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
2301
4045
  const quote = await api.fetchQuote({
2302
4046
  fromChainId: v.fromChainId,
2303
4047
  toChainId: v.toChainId,
@@ -2305,7 +4049,7 @@ async function quoteSwapPreview(api, swap, owner) {
2305
4049
  toToken: destToken.symbol,
2306
4050
  fromAmount: amountInRaw.toString(),
2307
4051
  owner: account,
2308
- destinationReceiver: previewReceiver
4052
+ ...previewReceiver ? { destinationReceiver: previewReceiver } : {}
2309
4053
  });
2310
4054
  const final = finalOf(quote);
2311
4055
  return {
@@ -2330,7 +4074,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
2330
4074
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
2331
4075
  if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
2332
4076
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2333
- const receiver = resolveSwapReceiver(swap.recipient, account);
4077
+ const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
2334
4078
  const option = {
2335
4079
  symbol: sourceToken.symbol,
2336
4080
  symbolKey: symbolKey(sourceToken.symbol),
@@ -2380,16 +4124,16 @@ function isHexQuantity(value) {
2380
4124
  return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
2381
4125
  }
2382
4126
  function dataWord(data, index) {
2383
- const word = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
2384
- return /^[a-fA-F0-9]{64}$/.test(word) ? word : "";
4127
+ const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4128
+ return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
2385
4129
  }
2386
4130
  function dataAddress(data, index) {
2387
- const word = dataWord(data, index);
2388
- return word ? `0x${word.slice(24)}` : "";
4131
+ const word2 = dataWord(data, index);
4132
+ return word2 ? `0x${word2.slice(24)}` : "";
2389
4133
  }
2390
4134
  function dataUint(data, index) {
2391
- const word = dataWord(data, index);
2392
- return word ? BigInt(`0x${word}`) : null;
4135
+ const word2 = dataWord(data, index);
4136
+ return word2 ? BigInt(`0x${word2}`) : null;
2393
4137
  }
2394
4138
  function rawEquals(value, expected) {
2395
4139
  try {
@@ -2400,9 +4144,9 @@ function rawEquals(value, expected) {
2400
4144
  }
2401
4145
  function planMsgValueHex(route) {
2402
4146
  try {
2403
- const raw = route?.quote?.msgValue;
2404
- if (raw === void 0 || raw === null || raw === "") return "0x0";
2405
- return "0x" + BigInt(raw).toString(16);
4147
+ const raw2 = route?.quote?.msgValue;
4148
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4149
+ return "0x" + BigInt(raw2).toString(16);
2406
4150
  } catch {
2407
4151
  return null;
2408
4152
  }
@@ -2429,15 +4173,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
2429
4173
  if (!decoded) return false;
2430
4174
  const first = decoded.orders[0];
2431
4175
  const last = decoded.orders[decoded.orders.length - 1];
2432
- 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);
4176
+ 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));
2433
4177
  }
2434
4178
  return false;
2435
4179
  }
4180
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
4181
+ try {
4182
+ return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4183
+ } catch {
4184
+ return false;
4185
+ }
4186
+ }
2436
4187
  async function allowanceCovers(tx, account, ethCall) {
2437
4188
  if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
2438
4189
  try {
2439
- const raw = await ethCall(tx.token, encodeAllowance(account, tx.spender));
2440
- return BigInt(raw || "0x0") >= BigInt(tx.amountRaw || "0");
4190
+ const raw2 = await ethCall(tx.token, encodeAllowance(account, tx.spender));
4191
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
2441
4192
  } catch {
2442
4193
  return false;
2443
4194
  }
@@ -2475,8 +4226,13 @@ var stableGenieIntentSchema = {
2475
4226
  type: "object",
2476
4227
  additionalProperties: false,
2477
4228
  required: ["address", "chainId", "asset", "amount"],
4229
+ // The engine performs the decoded 32-byte check; the schema filters the address alphabet.
4230
+ oneOf: [
4231
+ { properties: { chainId: { const: SOLANA_CHAIN_ID }, address: { pattern: "^[1-9A-HJ-NP-Za-km-z]{32,44}$" } } },
4232
+ { properties: { chainId: { not: { const: SOLANA_CHAIN_ID } }, address: { pattern: "^0x[a-fA-F0-9]{40}$" } } }
4233
+ ],
2478
4234
  properties: {
2479
- address: { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" },
4235
+ address: { type: "string" },
2480
4236
  // A DESTINATION chain, so it is bounded by shape, not by the escrow-chain list: a payment may
2481
4237
  // be delivered on any chain the gateway publishes a route to (~31 of them), while only the
2482
4238
  // nine escrow chains can SEND one. See validateDestination in plan.ts.
@@ -2503,9 +4259,9 @@ var TX_VERIFY_ATTEMPTS = 5;
2503
4259
  var TX_VERIFY_INTERVAL_MS = 2500;
2504
4260
  var TX_VERIFY_FETCH_MS = 5e3;
2505
4261
  var TX_VERIFY_DEADLINE_MS = 18e3;
2506
- function registryRpc(chain) {
2507
- if (!chain) return "";
2508
- const candidates = [chain.rpcUrl, Array.isArray(chain.rpcUrls) ? chain.rpcUrls[0] : null, chain.publicRpcUrl, chain.rpc, chain.rpcEndpoint];
4262
+ function registryRpc(chain2) {
4263
+ if (!chain2) return "";
4264
+ const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
2509
4265
  const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
2510
4266
  return found || "";
2511
4267
  }
@@ -2586,8 +4342,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2586
4342
  }
2587
4343
  return null;
2588
4344
  }
2589
- async function verifySubmittedTx({ chainId, hash, from, to, data, value, minNonce }) {
2590
- if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash || ""))) return { status: "mismatch" };
4345
+ async function verifySubmittedTx({ chainId, hash: hash2, from, to, data, value, minNonce }) {
4346
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash2 || ""))) return { status: "mismatch" };
2591
4347
  if (!normalizeAddress(from) || typeof minNonce !== "number") return { status: "unconfirmed", reason: "no-binding" };
2592
4348
  const rpcUrl = await chainRpcUrl(chainId);
2593
4349
  if (!rpcUrl) return { status: "unconfirmed", reason: "no-rpc" };
@@ -2598,7 +4354,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2598
4354
  if (!matched) {
2599
4355
  let tx = null;
2600
4356
  try {
2601
- tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash]);
4357
+ tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash2]);
2602
4358
  } catch {
2603
4359
  tx = null;
2604
4360
  }
@@ -2610,7 +4366,7 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2610
4366
  if (matched) {
2611
4367
  let receipt = null;
2612
4368
  try {
2613
- receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash]);
4369
+ receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash2]);
2614
4370
  } catch {
2615
4371
  receipt = null;
2616
4372
  }
@@ -2652,9 +4408,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2652
4408
  }
2653
4409
  function record(target, hex) {
2654
4410
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
2655
- const raw = BigInt(hex || "0x0").toString();
4411
+ const raw2 = BigInt(hex || "0x0").toString();
2656
4412
  const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
2657
- out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
4413
+ out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
2658
4414
  return true;
2659
4415
  }
2660
4416
  async function readOne(rpcUrl, target) {
@@ -2720,9 +4476,9 @@ function isSameOriginPath(value) {
2720
4476
  return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
2721
4477
  }
2722
4478
  function resolveApiBase(value) {
2723
- const raw = value ?? DEFAULT_WIDGET_API_BASE;
2724
- if (isSameOriginPath(raw)) return raw.replace(/\/+$/, "") || "/";
2725
- return parseAllowedApiBase(raw) || DEFAULT_WIDGET_API_BASE;
4479
+ const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
4480
+ if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
4481
+ return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
2726
4482
  }
2727
4483
  function canAttachApiKey(apiBase, trustedOrigin) {
2728
4484
  if (isSameOriginPath(apiBase)) return true;
@@ -2761,31 +4517,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
2761
4517
  }
2762
4518
 
2763
4519
  // src/core/index.ts
4520
+ var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
2764
4521
  function sanitizeLegs(legs) {
2765
4522
  if (!Array.isArray(legs) || !legs.length) return void 0;
2766
4523
  const text = (v, max) => String(v ?? "").slice(0, max);
2767
- const chain = (v) => Number(v) || 0;
4524
+ const chain2 = (v) => Number(v) || 0;
2768
4525
  const ticker = (value, asset) => safeTicker(value, asset) || void 0;
2769
4526
  return legs.slice(0, 8).map((leg, i) => ({
2770
4527
  index: Number(leg?.index) || i + 1,
2771
4528
  fromAsset: text(leg?.fromAsset, 12),
2772
4529
  fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
2773
- fromChainId: chain(leg?.fromChainId),
4530
+ fromChainId: chain2(leg?.fromChainId),
2774
4531
  fromChainName: text(leg?.fromChainName, 40),
2775
4532
  fromAmount: text(leg?.fromAmount, 40),
2776
4533
  toAsset: text(leg?.toAsset, 12),
2777
4534
  toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
2778
- toChainId: chain(leg?.toChainId),
4535
+ toChainId: chain2(leg?.toChainId),
2779
4536
  toChainName: text(leg?.toChainName, 40),
2780
4537
  toAmount: text(leg?.toAmount, 40),
2781
- executionChainId: chain(leg?.executionChainId),
4538
+ executionChainId: chain2(leg?.executionChainId),
2782
4539
  executionChainName: text(leg?.executionChainName, 40)
2783
4540
  }));
2784
4541
  }
2785
4542
  function sanitizeTxEntry(entry) {
2786
4543
  return {
2787
4544
  kind: entry.kind === "swap" ? "swap" : "payment",
2788
- hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
4545
+ // A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
4546
+ 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) : "",
2789
4547
  txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
2790
4548
  chainId: Number(entry.chainId) || null,
2791
4549
  chainName: String(entry.chainName || "").slice(0, 40),
@@ -2796,7 +4554,7 @@ function sanitizeTxEntry(entry) {
2796
4554
  payAmount: String(entry.payAmount || "").slice(0, 40),
2797
4555
  receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
2798
4556
  account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
2799
- recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
4557
+ recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
2800
4558
  settlement: entry.settlement === "direct" ? "direct" : "escrow",
2801
4559
  status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
2802
4560
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2807,6 +4565,7 @@ function createEngine(config = {}) {
2807
4565
  const resolved = resolveConfig(config);
2808
4566
  const api = createApiClient(resolved);
2809
4567
  const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
4568
+ const solanaRpc = createSolanaRpc(api);
2810
4569
  return {
2811
4570
  api,
2812
4571
  verifier,
@@ -2817,7 +4576,7 @@ function createEngine(config = {}) {
2817
4576
  fetchRouteHealth: api.fetchRouteHealth,
2818
4577
  fetchQuote: api.fetchQuote,
2819
4578
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
2820
- fetchCatalogue: async (allowedAssets, product) => {
4579
+ fetchCatalogue: async (allowedAssets, product, options) => {
2821
4580
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
2822
4581
  api.fetchChains().catch(() => []),
2823
4582
  api.fetchTokens().catch(() => []),
@@ -2834,7 +4593,9 @@ function createEngine(config = {}) {
2834
4593
  routes,
2835
4594
  product,
2836
4595
  ...allowed ? { allowedAssets: allowed } : {},
2837
- supportedChainIds: SUPPORTED_CHAIN_IDS,
4596
+ // Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
4597
+ // Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
4598
+ supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
2838
4599
  brokenLanes: suppressedLanes(health),
2839
4600
  // Same read, same degraded mode: a null health response limits nothing.
2840
4601
  limitedLanes: limitedLanes(health),
@@ -2845,6 +4606,15 @@ function createEngine(config = {}) {
2845
4606
  quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
2846
4607
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
2847
4608
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
4609
+ quoteSolanaSource: (input) => quoteSolanaSource(api, input),
4610
+ buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
4611
+ executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
4612
+ executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
4613
+ previewSolanaSource: (input) => previewSolanaSource(api, input),
4614
+ trackDelivery: (hash2) => fetchDelivery(api, hash2),
4615
+ fetchWalletHistory: (wallets) => fetchWalletHistory(api, wallets),
4616
+ readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
4617
+ simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
2848
4618
  payerNonceBaseline: verifier.payerNonceBaseline,
2849
4619
  verifySubmittedTx: verifier.verifySubmittedTx,
2850
4620
  readBalances: verifier.readBalances,
@@ -2860,6 +4630,11 @@ function createEngine(config = {}) {
2860
4630
  }
2861
4631
  };
2862
4632
  }
4633
+ /*! Bundled license information:
4634
+
4635
+ @noble/ed25519/index.js:
4636
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
4637
+ */
2863
4638
 
2864
4639
  exports.API_CACHE_TTL_MS = API_CACHE_TTL_MS;
2865
4640
  exports.BLOCK_LABEL_DEFAULT = BLOCK_LABEL_DEFAULT;
@@ -2868,6 +4643,7 @@ exports.BUNDLED_RPC = BUNDLED_RPC;
2868
4643
  exports.CANONICAL_DECIMALS = CANONICAL_DECIMALS;
2869
4644
  exports.CANONICAL_ESCROW = CANONICAL_ESCROW;
2870
4645
  exports.CANONICAL_INBOUND_BRIDGE = CANONICAL_INBOUND_BRIDGE;
4646
+ exports.CANONICAL_SOLANA_PROGRAM = CANONICAL_SOLANA_PROGRAM;
2871
4647
  exports.CHAIN_DISPLAY_NAMES = CHAIN_DISPLAY_NAMES;
2872
4648
  exports.COMPLIANCE_CHECK_ORDER = COMPLIANCE_CHECK_ORDER;
2873
4649
  exports.COMPLIANCE_DENY_LABEL = COMPLIANCE_DENY_LABEL;
@@ -2892,42 +4668,66 @@ exports.QUOTE_BUFFER_BPS = QUOTE_BUFFER_BPS;
2892
4668
  exports.SAME_CLASS_STABLE = SAME_CLASS_STABLE;
2893
4669
  exports.SCREENING_BUCKETS = SCREENING_BUCKETS;
2894
4670
  exports.SCREEN_CACHE_TTL_MS = SCREEN_CACHE_TTL_MS;
4671
+ exports.SOLANA_CHAIN_ID = SOLANA_CHAIN_ID;
4672
+ exports.SOLANA_DESTINATION_ASSETS = SOLANA_DESTINATION_ASSETS;
4673
+ exports.SOL_SHORTFALL_MESSAGE = SOL_SHORTFALL_MESSAGE;
2895
4674
  exports.STABLEGENIE_INTENT_TTL_MS = STABLEGENIE_INTENT_TTL_MS;
2896
4675
  exports.STABLEGENIE_INTENT_VERSION = STABLEGENIE_INTENT_VERSION;
2897
4676
  exports.STABLEGENIE_SUPPORTED_ASSETS = STABLEGENIE_SUPPORTED_ASSETS;
2898
4677
  exports.STABLEGENIE_SUPPORTED_CHAIN_IDS = STABLEGENIE_SUPPORTED_CHAIN_IDS;
2899
4678
  exports.STABLE_ASSETS = STABLE_ASSETS;
4679
+ exports.SUBMIT_ORDER_DISCRIMINATOR = SUBMIT_ORDER_DISCRIMINATOR;
2900
4680
  exports.SUBMIT_ORDER_SELECTOR = SUBMIT_ORDER_SELECTOR;
2901
4681
  exports.SUPPORTED_ASSETS = SUPPORTED_ASSETS;
2902
4682
  exports.SUPPORTED_CHAIN_IDS = SUPPORTED_CHAIN_IDS;
4683
+ exports.SolanaSendError = SolanaSendError;
4684
+ exports.TRACKING = TRACKING;
2903
4685
  exports.TRADEABLE_RWA_ASSETS = TRADEABLE_RWA_ASSETS;
2904
4686
  exports.TUNABLE_CATEGORIES = TUNABLE_CATEGORIES;
4687
+ exports.WALLET_HISTORY_LIMIT = WALLET_HISTORY_LIMIT;
2905
4688
  exports.ZERO_ADDRESS = ZERO_ADDRESS;
2906
4689
  exports.addressWord = addressWord;
2907
4690
  exports.allowanceCovers = allowanceCovers;
2908
4691
  exports.amountFieldError = amountFieldError;
2909
4692
  exports.apiError = apiError;
2910
4693
  exports.applyLayerZeroBuffer = applyLayerZeroBuffer;
4694
+ exports.askCovers = askCovers;
4695
+ exports.askTokenDecimals = askTokenDecimals;
2911
4696
  exports.assertAddress = assertAddress;
4697
+ exports.assertChainAddress = assertChainAddress;
2912
4698
  exports.assertQuoteMatchesSelection = assertQuoteMatchesSelection;
4699
+ exports.assertWalletMessage = assertWalletMessage;
2913
4700
  exports.assetClassOf = assetClassOf;
2914
4701
  exports.assetDecimals = assetDecimals;
4702
+ exports.associatedTokenAddress = associatedTokenAddress;
4703
+ exports.base58Decode = base58Decode;
4704
+ exports.base58Encode = base58Encode;
4705
+ exports.base64Decode = base64Decode;
4706
+ exports.base64Encode = base64Encode;
2915
4707
  exports.blockLabelFor = blockLabelFor;
2916
4708
  exports.brokenLaneFor = brokenLaneFor;
2917
4709
  exports.brokenLaneReason = brokenLaneReason;
2918
4710
  exports.buildCatalogue = buildCatalogue;
2919
4711
  exports.buildPayOptions = buildPayOptions;
2920
4712
  exports.buildRoute = buildRoute;
4713
+ exports.buildSolanaSourcePlan = buildSolanaSourcePlan;
2921
4714
  exports.buildSwapPlan = buildSwapPlan;
2922
4715
  exports.bytes32Word = bytes32Word;
4716
+ exports.bytesEqual = bytesEqual;
2923
4717
  exports.bytesPayload = bytesPayload;
2924
4718
  exports.canAttachApiKey = canAttachApiKey;
2925
4719
  exports.categoryLabel = categoryLabel;
4720
+ exports.chainAddressKey = chainAddressKey;
2926
4721
  exports.chainById = chainById;
2927
4722
  exports.chainNameOf = chainNameOf;
2928
4723
  exports.chainSelectable = chainSelectable;
2929
4724
  exports.checkEscrow = checkEscrow;
2930
4725
  exports.checkNativeFee = checkNativeFee;
4726
+ exports.checkPlan = checkSolanaPlan;
4727
+ exports.checkSolanaPlan = checkSolanaPlan;
4728
+ exports.checkSolanaProgram = checkSolanaProgram;
4729
+ exports.checkSolanaReceiver = checkSolanaReceiver;
4730
+ exports.checkSolanaRouteBuffer = checkSolanaRouteBuffer;
2931
4731
  exports.classifyQuoteError = classifyQuoteError;
2932
4732
  exports.complianceChecks = complianceChecks;
2933
4733
  exports.complianceControlsEvaluated = complianceControlsEvaluated;
@@ -2936,11 +4736,16 @@ exports.complianceReasonHead = complianceReasonHead;
2936
4736
  exports.complianceReasonTag = complianceReasonTag;
2937
4737
  exports.complianceTagOf = complianceTagOf;
2938
4738
  exports.complianceView = complianceView;
4739
+ exports.cosignSolanaEvent = cosignSolanaEvent;
2939
4740
  exports.counterpartTokens = counterpartTokens;
2940
4741
  exports.createApiClient = createApiClient;
2941
4742
  exports.createEngine = createEngine;
4743
+ exports.createSolanaRpc = createSolanaRpc;
2942
4744
  exports.createVerifier = createVerifier;
4745
+ exports.decodeSolanaSubmitOrder = decodeSolanaSubmitOrder;
4746
+ exports.decodeSubmitOrder = decodeSolanaSubmitOrder;
2943
4747
  exports.decodeSubmitOrderCalldata = decodeSubmitOrderCalldata;
4748
+ exports.deriveSolanaEvent = deriveSolanaEvent;
2944
4749
  exports.destinationAvailability = destinationAvailability;
2945
4750
  exports.destinationKeys = destinationKeys;
2946
4751
  exports.directComplianceFromScreens = directComplianceFromScreens;
@@ -2948,22 +4753,34 @@ exports.distinctScreenedWallets = distinctScreenedWallets;
2948
4753
  exports.encodeAllowance = encodeAllowance;
2949
4754
  exports.encodeApprove = encodeApprove;
2950
4755
  exports.encodeBalanceOf = encodeBalanceOf;
4756
+ exports.encodeNextSolanaOrders = encodeNextSolanaOrders;
2951
4757
  exports.encodeSubmitOrder = encodeSubmitOrder;
2952
4758
  exports.encodeTransfer = encodeTransfer;
2953
4759
  exports.exceedsLaneLimit = exceedsLaneLimit;
2954
4760
  exports.executableRoutes = executableRoutes;
4761
+ exports.executeSolanaPlan = executeSolanaPlan;
4762
+ exports.executeSolanaPlanStaged = executeSolanaPlanStaged;
2955
4763
  exports.executionChainIds = executionChainIds;
4764
+ exports.expectedSolanaDelivery = expectedSolanaDelivery;
4765
+ exports.fetchDelivery = fetchDelivery;
2956
4766
  exports.fetchPaymentPlan = fetchPaymentPlan;
4767
+ exports.fetchWalletHistory = fetchWalletHistory;
2957
4768
  exports.finalOf = finalOf;
4769
+ exports.findProgramAddress = findProgramAddress;
2958
4770
  exports.findToken = findToken;
2959
4771
  exports.foldTicker = foldTicker;
2960
4772
  exports.formatJurisdiction = formatJurisdiction;
2961
4773
  exports.formatNative = formatNative;
2962
4774
  exports.formatUnits = formatUnits;
2963
4775
  exports.hasReachableDestination = hasReachableDestination;
4776
+ exports.hexBytes = hexBytes;
4777
+ exports.hexToSolanaKey = hexToSolanaKey;
4778
+ exports.historyEntryFromOrder = historyEntryFromOrder;
4779
+ exports.historyKey = historyKey;
2964
4780
  exports.hubDeliverableSymbols = hubDeliverableSymbols;
2965
4781
  exports.humanizeComplianceReason = humanizeComplianceReason;
2966
4782
  exports.isAddress = isAddress;
4783
+ exports.isChainAddress = isChainAddress;
2967
4784
  exports.isDeliverable = isDeliverable;
2968
4785
  exports.isExecutableBridge = isExecutableBridge;
2969
4786
  exports.isHexAddress = isHexAddress;
@@ -2971,7 +4788,12 @@ exports.isHexData = isHexData;
2971
4788
  exports.isHexQuantity = isHexQuantity;
2972
4789
  exports.isKnownUnbridgeable = isKnownUnbridgeable;
2973
4790
  exports.isLayerZeroRoute = isLayerZeroRoute;
4791
+ exports.isOnEd25519Curve = isOnEd25519Curve;
4792
+ exports.isPreparationInstruction = isPreparationInstruction;
4793
+ exports.isSolanaAddress = isSolanaAddress;
4794
+ exports.isSolanaChainId = isSolanaChainId;
2974
4795
  exports.isSourceToken = isSourceToken;
4796
+ exports.isSubmitOrder = isSubmitOrder;
2975
4797
  exports.laneAvailabilityState = laneAvailabilityState;
2976
4798
  exports.laneKey = laneKey;
2977
4799
  exports.laneKeys = laneKeys;
@@ -2983,32 +4805,53 @@ exports.laneLimitSymbol = laneLimitSymbol;
2983
4805
  exports.limitedLanes = limitedLanes;
2984
4806
  exports.maxDeadlineSeconds = maxDeadlineSeconds;
2985
4807
  exports.maxNativeFeeWei = maxNativeFeeWei;
4808
+ exports.mergeHistory = mergeHistory;
2986
4809
  exports.nativeFeeShortLabel = nativeFeeShortLabel;
2987
4810
  exports.nativeFeeShortMessage = nativeFeeShortMessage;
2988
4811
  exports.nativeSymbol = nativeSymbol;
2989
4812
  exports.normalizeAddress = normalizeAddress;
2990
4813
  exports.normalizeDecimalText = normalizeDecimalText;
4814
+ exports.normalizeDelivery = normalizeDelivery;
2991
4815
  exports.normalizeOrderRequest = normalizeOrderRequest;
2992
4816
  exports.normalizeOrderRequests = normalizeOrderRequests;
4817
+ exports.overwriteBlockhash = overwriteBlockhash;
4818
+ exports.parseAddressLookupTable = parseAddressLookupTable;
2993
4819
  exports.parseAllowedApiBase = parseAllowedApiBase;
4820
+ exports.parseSolanaTransaction = parseSolanaTransaction;
2994
4821
  exports.parseUnitsDecimal = parseUnitsDecimal;
4822
+ exports.placeSignature = placeSignature;
2995
4823
  exports.planErrorSummary = planErrorSummary;
2996
4824
  exports.planMsgValueHex = planMsgValueHex;
4825
+ exports.pollSolanaConfirmation = pollSolanaConfirmation;
4826
+ exports.previewSolanaSource = previewSolanaSource;
2997
4827
  exports.productAssets = productAssets;
2998
4828
  exports.quotePartnerId = quotePartnerId;
2999
4829
  exports.quotePayOption = quotePayOption;
4830
+ exports.quoteSolanaSource = quoteSolanaSource;
3000
4831
  exports.quoteSwapPreview = quoteSwapPreview;
4832
+ exports.readSolanaBalance = readSolanaBalance;
3001
4833
  exports.recommendedDeadlineSeconds = recommendedDeadlineSeconds;
3002
4834
  exports.registryRpc = registryRpc;
3003
4835
  exports.requiresNativeBridgeFee = requiresNativeBridgeFee;
3004
4836
  exports.resolveApiBase = resolveApiBase;
3005
4837
  exports.resolveConfig = resolveConfig;
4838
+ exports.resolveSolanaKeys = resolveSolanaKeys;
3006
4839
  exports.resolveSwapReceiver = resolveSwapReceiver;
3007
4840
  exports.resolveVaultIcon = resolveVaultIcon;
3008
4841
  exports.routeNativeValue = routeNativeValue;
3009
4842
  exports.safeTicker = safeTicker;
3010
4843
  exports.scaleDecimals = scaleDecimals;
3011
4844
  exports.screeningOutcomeOf = screeningOutcomeOf;
4845
+ exports.serializeSolanaTransaction = serializeSolanaTransaction;
4846
+ exports.sha256 = sha256;
4847
+ exports.simulateSolanaCost = simulateSolanaCost;
4848
+ exports.solanaBridgeOf = solanaBridgeOf;
4849
+ exports.solanaDestinationAsset = solanaDestinationAsset;
4850
+ exports.solanaKeyBytes = solanaKeyBytes;
4851
+ exports.solanaKeyHex = solanaKeyHex;
4852
+ exports.solanaLamportShortfall = solanaLamportShortfall;
4853
+ exports.solanaPlanNeedsPreparation = solanaPlanNeedsPreparation;
4854
+ exports.solanaQuoteCompliance = solanaQuoteCompliance;
3012
4855
  exports.solveExactIn = solveExactIn;
3013
4856
  exports.solveExactOut = solveExactOut;
3014
4857
  exports.sourceKeys = sourceKeys;
@@ -3029,4 +4872,8 @@ exports.validateDestination = validateDestination;
3029
4872
  exports.validatePlannedTransaction = validatePlannedTransaction;
3030
4873
  exports.validateSwap = validateSwap;
3031
4874
  exports.vaultIconsBySymbol = vaultIconsBySymbol;
4875
+ exports.verifySolanaSubmit = verifySolanaSubmit;
4876
+ exports.verifySolanaTransaction = verifySolanaTransaction;
4877
+ exports.verifySubmit = verifySolanaSubmit;
4878
+ exports.verifyTransaction = verifySolanaTransaction;
3032
4879
  exports.withVaultArtwork = withVaultArtwork;