@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.
@@ -91,7 +91,10 @@ var CANONICAL_ESCROW = Object.freeze({
91
91
  // Plume
92
92
  });
93
93
  var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
94
- var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {};
94
+ var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {
95
+ 9745: 2500n * 10n ** 18n,
96
+ 98866: 5000n * 10n ** 18n
97
+ };
95
98
  function maxNativeFeeWei(chainId) {
96
99
  return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
97
100
  }
@@ -209,6 +212,247 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
209
212
  1151111081099710: "Solana"
210
213
  });
211
214
 
215
+ // src/core/solana.ts
216
+ var SOLANA_CHAIN_ID = 1151111081099710;
217
+ function isSolanaChainId(value) {
218
+ return Number(value) === SOLANA_CHAIN_ID;
219
+ }
220
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
221
+ function base58Encode(bytes) {
222
+ let zeros = 0;
223
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
224
+ let value = 0n;
225
+ for (const byte of bytes) value = value << 8n | BigInt(byte);
226
+ let out = "";
227
+ while (value > 0n) {
228
+ out = BASE58_ALPHABET[Number(value % 58n)] + out;
229
+ value /= 58n;
230
+ }
231
+ return "1".repeat(zeros) + out;
232
+ }
233
+ function base58Decode(text) {
234
+ let value = 0n;
235
+ for (const char of text) {
236
+ const digit = BASE58_ALPHABET.indexOf(char);
237
+ if (digit < 0) return null;
238
+ value = value * 58n + BigInt(digit);
239
+ }
240
+ const body = [];
241
+ while (value > 0n) {
242
+ body.unshift(Number(value & 0xffn));
243
+ value >>= 8n;
244
+ }
245
+ let zeros = 0;
246
+ while (zeros < text.length && text[zeros] === "1") zeros += 1;
247
+ return new Uint8Array([...new Array(zeros).fill(0), ...body]);
248
+ }
249
+ function isSolanaAddress(value) {
250
+ const text = typeof value === "string" ? value.trim() : "";
251
+ return text.length >= 32 && text.length <= 44 && base58Decode(text)?.length === 32;
252
+ }
253
+ function solanaKeyHex(value) {
254
+ if (!isSolanaAddress(value)) return null;
255
+ return `0x${Array.from(base58Decode(value.trim()), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
256
+ }
257
+ function hexToSolanaKey(value) {
258
+ if (!/^0x[0-9a-fA-F]{64}$/.test(value)) return null;
259
+ return base58Encode(Uint8Array.from(value.slice(2).match(/../g), (byte) => Number.parseInt(byte, 16)));
260
+ }
261
+ var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
262
+ var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
263
+ var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
264
+ var pin = (symbol, decimals, bridge, tokenProgram) => Object.freeze({ symbol, decimals, bridge, tokenProgram });
265
+ var SOLANA_DESTINATION_ASSETS = Object.freeze({
266
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: pin("USDC", 6, "cctp", TOKEN_PROGRAM),
267
+ "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": pin("PYUSD", 6, "layerzero", TOKEN_2022_PROGRAM),
268
+ DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT: pin("USDE", 9, "layerzero", TOKEN_PROGRAM),
269
+ "2u1tszSeqZ3qBWF3uNGPFc8TzMk2tdiwknnRMWGWjGWH": pin("USDG", 6, "layerzero", TOKEN_2022_PROGRAM),
270
+ AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
271
+ });
272
+ function solanaDestinationAsset(mint) {
273
+ const key = typeof mint === "string" ? mint.trim() : "";
274
+ return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
275
+ }
276
+ function solanaBridgeOf(token) {
277
+ const pinned = solanaDestinationAsset(token.address);
278
+ if (!pinned || pinned.symbol !== token.symbol.trim().toUpperCase()) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
279
+ return pinned.bridge;
280
+ }
281
+ var K = new Uint32Array([
282
+ 1116352408,
283
+ 1899447441,
284
+ 3049323471,
285
+ 3921009573,
286
+ 961987163,
287
+ 1508970993,
288
+ 2453635748,
289
+ 2870763221,
290
+ 3624381080,
291
+ 310598401,
292
+ 607225278,
293
+ 1426881987,
294
+ 1925078388,
295
+ 2162078206,
296
+ 2614888103,
297
+ 3248222580,
298
+ 3835390401,
299
+ 4022224774,
300
+ 264347078,
301
+ 604807628,
302
+ 770255983,
303
+ 1249150122,
304
+ 1555081692,
305
+ 1996064986,
306
+ 2554220882,
307
+ 2821834349,
308
+ 2952996808,
309
+ 3210313671,
310
+ 3336571891,
311
+ 3584528711,
312
+ 113926993,
313
+ 338241895,
314
+ 666307205,
315
+ 773529912,
316
+ 1294757372,
317
+ 1396182291,
318
+ 1695183700,
319
+ 1986661051,
320
+ 2177026350,
321
+ 2456956037,
322
+ 2730485921,
323
+ 2820302411,
324
+ 3259730800,
325
+ 3345764771,
326
+ 3516065817,
327
+ 3600352804,
328
+ 4094571909,
329
+ 275423344,
330
+ 430227734,
331
+ 506948616,
332
+ 659060556,
333
+ 883997877,
334
+ 958139571,
335
+ 1322822218,
336
+ 1537002063,
337
+ 1747873779,
338
+ 1955562222,
339
+ 2024104815,
340
+ 2227730452,
341
+ 2361852424,
342
+ 2428436474,
343
+ 2756734187,
344
+ 3204031479,
345
+ 3329325298
346
+ ]);
347
+ function sha256(data) {
348
+ const bitLen = data.length * 8;
349
+ const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
350
+ padded.set(data);
351
+ padded[data.length] = 128;
352
+ const view = new DataView(padded.buffer);
353
+ view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
354
+ view.setUint32(padded.length - 4, bitLen >>> 0);
355
+ const h = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
356
+ const w = new Uint32Array(64);
357
+ const rotr = (x, n) => x >>> n | x << 32 - n;
358
+ for (let off = 0; off < padded.length; off += 64) {
359
+ for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
360
+ for (let i = 16; i < 64; i += 1) {
361
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
362
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
363
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
364
+ }
365
+ let [a, b, c, d, e, f, g, hh] = h;
366
+ for (let i = 0; i < 64; i += 1) {
367
+ const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] >>> 0;
368
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
369
+ hh = g;
370
+ g = f;
371
+ f = e;
372
+ e = d + t1 >>> 0;
373
+ d = c;
374
+ c = b;
375
+ b = a;
376
+ a = t1 + t2 >>> 0;
377
+ }
378
+ h[0] = h[0] + a >>> 0;
379
+ h[1] = h[1] + b >>> 0;
380
+ h[2] = h[2] + c >>> 0;
381
+ h[3] = h[3] + d >>> 0;
382
+ h[4] = h[4] + e >>> 0;
383
+ h[5] = h[5] + f >>> 0;
384
+ h[6] = h[6] + g >>> 0;
385
+ h[7] = h[7] + hh >>> 0;
386
+ }
387
+ const out = new Uint8Array(32);
388
+ const outView = new DataView(out.buffer);
389
+ for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h[i]);
390
+ return out;
391
+ }
392
+ var P = 2n ** 255n - 19n;
393
+ var mod = (a) => (a % P + P) % P;
394
+ var pow = (base, exp) => {
395
+ let result = 1n;
396
+ let b = mod(base);
397
+ for (let e = exp; e > 0n; e >>= 1n) {
398
+ if (e & 1n) result = result * b % P;
399
+ b = b * b % P;
400
+ }
401
+ return result;
402
+ };
403
+ var D = mod(-121665n * pow(121666n, P - 2n));
404
+ function isOnEd25519Curve(bytes) {
405
+ let y = 0n;
406
+ for (let i = 31; i >= 0; i -= 1) y = y << 8n | BigInt(bytes[i]);
407
+ y = mod(y & (1n << 255n) - 1n);
408
+ const yy = y * y % P;
409
+ const u = mod(yy - 1n);
410
+ const v = mod(D * yy + 1n);
411
+ if (v === 0n) return u === 0n;
412
+ const x2 = u * pow(v, P - 2n) % P;
413
+ return x2 === 0n || pow(x2, (P - 1n) / 2n) === 1n;
414
+ }
415
+ function keyBytes(base58) {
416
+ const bytes = base58Decode(base58);
417
+ if (!bytes || bytes.length !== 32) throw new Error("Not a valid Solana address.");
418
+ return bytes;
419
+ }
420
+ function findProgramAddress(seeds, programId) {
421
+ const program = keyBytes(programId);
422
+ const marker = new TextEncoder().encode("ProgramDerivedAddress");
423
+ for (let bump = 255; bump >= 1; bump -= 1) {
424
+ const parts = [...seeds, Uint8Array.of(bump), program, marker];
425
+ const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
426
+ let at = 0;
427
+ for (const part of parts) {
428
+ buf.set(part, at);
429
+ at += part.length;
430
+ }
431
+ const candidate = sha256(buf);
432
+ if (!isOnEd25519Curve(candidate)) return candidate;
433
+ }
434
+ throw new Error("Could not derive a program address.");
435
+ }
436
+ function associatedTokenAddress(owner, mint, tokenProgram) {
437
+ return base58Encode(findProgramAddress([keyBytes(owner), keyBytes(tokenProgram), keyBytes(mint)], ASSOCIATED_TOKEN_PROGRAM));
438
+ }
439
+ function expectedSolanaDelivery(recipient2, mint) {
440
+ if (!isSolanaAddress(recipient2)) throw new Error("Not a valid Solana address.");
441
+ const pinned = solanaDestinationAsset(mint);
442
+ if (!pinned) throw new Error("This Solana token is not supported for delivery; refusing to sign.");
443
+ const target = pinned.bridge === "cctp" ? associatedTokenAddress(recipient2.trim(), mint.trim(), pinned.tokenProgram) : recipient2.trim();
444
+ return solanaKeyHex(target);
445
+ }
446
+ function checkSolanaReceiver(request, intended, mint) {
447
+ if (!isSolanaAddress(intended)) throw new Error("Not a valid Solana address.");
448
+ if (request.destinationReceiverOwner !== intended.trim()) throw new Error("The quote was not made out to your Solana recipient; refusing to sign.");
449
+ const receiver = request.destinationReceiver || "";
450
+ const display = hexToSolanaKey(receiver);
451
+ if (!display) throw new Error("The quote carries no Solana delivery account; refusing to sign.");
452
+ if (request.destinationReceiverBase58 && request.destinationReceiverBase58 !== display) throw new Error("The quote names two different Solana delivery accounts; refusing to sign.");
453
+ 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.");
454
+ }
455
+
212
456
  // src/core/address.ts
213
457
  function symbolKey(value) {
214
458
  return String(value || "").trim().toUpperCase();
@@ -225,66 +469,26 @@ function assertAddress(value, label) {
225
469
  if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label} is not a valid EVM address.`);
226
470
  return normalized;
227
471
  }
228
- function resolveSwapReceiver(recipient, payer) {
472
+ function resolveSwapReceiver(recipient2, payer, destinationChainId) {
229
473
  const payerAddr = assertAddress(payer, "Swap wallet");
230
- if (recipient === void 0 || recipient === null || recipient === "") return payerAddr;
231
- const normalized = normalizeAddress(recipient);
474
+ if (isSolanaChainId(destinationChainId)) return assertChainAddress(destinationChainId, recipient2, "Deposit recipient");
475
+ if (recipient2 === void 0 || recipient2 === null || recipient2 === "") return payerAddr;
476
+ const normalized = normalizeAddress(recipient2);
232
477
  if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
233
478
  return normalized;
234
479
  }
235
-
236
- // src/core/units.ts
237
- function assetDecimals(token) {
238
- const sym = symbolKey(token?.symbol);
239
- const registry = Number(token?.decimals);
240
- const canonical = CANONICAL_DECIMALS[sym];
241
- if (canonical !== void 0) {
242
- if (!Number.isInteger(registry)) {
243
- throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
244
- }
245
- if (registry !== canonical) {
246
- throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
247
- }
248
- return canonical;
249
- }
250
- if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
251
- throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
252
- }
253
- return registry;
480
+ function isChainAddress(chainId, value) {
481
+ return isSolanaChainId(chainId) ? isSolanaAddress(value) : isAddress(value);
254
482
  }
255
- function normalizeDecimalText(value) {
256
- const text = String(value || "").trim().replace(/\s+/g, "");
257
- if (!text) return "";
258
- if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
259
- if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
260
- if (text.includes(",")) return "";
261
- return text;
483
+ function chainAddressKey(chainId, value) {
484
+ const text = String(value || "");
485
+ return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
262
486
  }
263
- function parseUnitsDecimal(amount, decimals) {
264
- const text = normalizeDecimalText(amount);
265
- if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
266
- const [whole, frac = ""] = text.split(".");
267
- if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
268
- const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
269
- const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
270
- if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
271
- return value;
272
- }
273
- function scaleDecimals(amount, fromDecimals, toDecimals) {
274
- if (toDecimals === fromDecimals) return amount;
275
- if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
276
- return amount / 10n ** BigInt(fromDecimals - toDecimals);
277
- }
278
- function formatUnits(raw, decimals, maxDecimals = 6) {
279
- const value = BigInt(raw || "0");
280
- const base = 10n ** BigInt(decimals);
281
- const whole = value / base;
282
- const fracFull = (value % base).toString().padStart(decimals, "0");
283
- const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
284
- return frac ? `${whole}.${frac}` : whole.toString();
285
- }
286
- function finalOf(quote) {
287
- return BigInt(quote?.finalAmount || quote?.toAmount || "0");
487
+ function assertChainAddress(chainId, value, label) {
488
+ if (!isSolanaChainId(chainId)) return assertAddress(value, label);
489
+ if (!String(value || "").trim()) throw new Error("Connect a Solana wallet or enter a Solana recipient address.");
490
+ if (!isSolanaAddress(value)) throw new Error("Not a valid Solana address.");
491
+ return String(value).trim();
288
492
  }
289
493
 
290
494
  // src/core/abi.ts
@@ -357,14 +561,12 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
357
561
  const tuples = orders.map(encodeOrderTuple);
358
562
  let offset = 32n * BigInt(tuples.length);
359
563
  const offsets = tuples.map((tuple) => {
360
- const word = uintWord(offset);
564
+ const word2 = uintWord(offset);
361
565
  offset += BigInt(tuple.length / 2);
362
- return word;
566
+ return word2;
363
567
  }).join("");
364
568
  return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
365
569
  }
366
- var EVM_BYTES_PAYLOAD_BYTES = 64;
367
- var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
368
570
  var MAX_DECODED_ORDERS = 16;
369
571
  function decodeSubmitOrderCalldata(data) {
370
572
  const hex = strip0x(String(data || "")).toLowerCase();
@@ -372,56 +574,61 @@ function decodeSubmitOrderCalldata(data) {
372
574
  if (`0x${hex.slice(0, 8)}` !== SUBMIT_ORDER_SELECTOR) return null;
373
575
  const body = hex.slice(8);
374
576
  const totalBytes = body.length / 2;
375
- const word = (byteOffset) => {
577
+ const word2 = (byteOffset) => {
376
578
  if (!Number.isSafeInteger(byteOffset) || byteOffset < 0 || byteOffset + 32 > totalBytes) return null;
377
579
  return BigInt(`0x${body.slice(byteOffset * 2, byteOffset * 2 + 64)}`);
378
580
  };
379
581
  const addressAt = (byteOffset) => {
380
- const w = word(byteOffset);
582
+ const w = word2(byteOffset);
381
583
  if (w === null || w >= 1n << 160n) return null;
382
584
  return `0x${w.toString(16).padStart(40, "0")}`;
383
585
  };
384
586
  const uint64At = (byteOffset) => {
385
- const w = word(byteOffset);
587
+ const w = word2(byteOffset);
386
588
  return w === null || w > MAX_UINT64 ? null : w;
387
589
  };
388
- const evmBytesAt = (byteOffset) => {
389
- const len = word(byteOffset);
390
- if (len !== 20n) return null;
391
- const content = body.slice((byteOffset + 32) * 2, (byteOffset + 64) * 2);
392
- if (content.length !== 64 || !content.endsWith("0".repeat(24))) return null;
393
- return `0x${content.slice(0, 40)}`;
590
+ const keyBytesAt = (byteOffset) => {
591
+ const len = word2(byteOffset);
592
+ if (len !== 20n && len !== 32n) return null;
593
+ const length = Number(len);
594
+ const padded = Math.ceil(length / 32) * 32;
595
+ const content = body.slice((byteOffset + 32) * 2, (byteOffset + 32 + padded) * 2);
596
+ if (content.length !== padded * 2 || content.slice(length * 2) !== "0".repeat((padded - length) * 2)) return null;
597
+ return { value: `0x${content.slice(0, length * 2)}`, size: 32 + padded };
394
598
  };
395
- if (word(0) !== 64n) return null;
396
- if (word(32) === null) return null;
599
+ if (word2(0) !== 64n) return null;
600
+ if (word2(32) === null) return null;
397
601
  const partnerId = `0x${body.slice(64, 128)}`;
398
- const count = word(64);
602
+ const count = word2(64);
399
603
  if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
400
604
  const n = Number(count);
401
605
  const arrayBase = 96;
402
- if (totalBytes !== arrayBase + 32 * n + EVM_ORDER_TUPLE_BYTES * n) return null;
606
+ let next = arrayBase + 32 * n;
403
607
  const orders = [];
404
608
  for (let i = 0; i < n; i += 1) {
405
- const rel = word(arrayBase + i * 32);
406
- if (rel === null || rel !== BigInt(32 * n + EVM_ORDER_TUPLE_BYTES * i)) return null;
407
- const base = arrayBase + Number(rel);
609
+ const rel = word2(arrayBase + i * 32);
610
+ if (rel === null || rel !== BigInt(next - arrayBase)) return null;
611
+ const base = next;
408
612
  const owner = addressAt(base);
409
613
  const bidToken = addressAt(base + 32);
410
- const bidTokenAmount = word(base + 64);
411
- const askOffset = word(base + 96);
412
- const askTokenAmount = word(base + 128);
413
- const receiverOffset = word(base + 160);
614
+ const bidTokenAmount = word2(base + 64);
615
+ const askOffset = word2(base + 96);
616
+ const askTokenAmount = word2(base + 128);
617
+ const receiverOffset = word2(base + 160);
414
618
  const destinationChainId = uint64At(base + 192);
415
619
  const executionChainId = uint64At(base + 224);
416
620
  const deadline = uint64At(base + 256);
417
- 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)) {
621
+ if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES) {
418
622
  return null;
419
623
  }
420
- const askToken = evmBytesAt(base + Number(askOffset));
421
- const destinationReceiver = evmBytesAt(base + Number(receiverOffset));
624
+ const askToken = keyBytesAt(base + Number(askOffset));
625
+ if (!askToken || receiverOffset !== ORDER_HEAD_BYTES + BigInt(askToken.size)) return null;
626
+ const destinationReceiver = keyBytesAt(base + Number(receiverOffset));
422
627
  if (askToken === null || destinationReceiver === null) return null;
423
- orders.push({ owner, bidToken, bidTokenAmount, askToken, askTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline });
628
+ next = base + Number(ORDER_HEAD_BYTES) + askToken.size + destinationReceiver.size;
629
+ orders.push({ owner, bidToken, bidTokenAmount, askToken: askToken.value, askTokenAmount, destinationReceiver: destinationReceiver.value, destinationChainId, executionChainId, deadline });
424
630
  }
631
+ if (next !== totalBytes) return null;
425
632
  return { partnerId, orders };
426
633
  }
427
634
  function toHexQuantity(value) {
@@ -429,47 +636,349 @@ function toHexQuantity(value) {
429
636
  return `0x${n.toString(16)}`;
430
637
  }
431
638
 
432
- // src/core/escrow.ts
433
- function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
434
- const fromQuote = normalizeAddress(quoteEscrow);
435
- const fromChains = normalizeAddress(chainsEscrow);
436
- if (!fromChains || fromChains === ZERO_ADDRESS) {
437
- throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
639
+ // src/core/solana-tx.ts
640
+ function bytesEqual(a, b) {
641
+ return a.length === b.length && a.every((v, i) => v === b[i]);
642
+ }
643
+ function hexBytes(hex) {
644
+ const h = strip0x(hex);
645
+ if (h.length % 2 || !/^[a-fA-F0-9]*$/.test(h)) throw new Error("Invalid hex bytes.");
646
+ return Uint8Array.from(h.match(/../g) || [], (v) => Number.parseInt(v, 16));
647
+ }
648
+ function solanaKeyBytes(key) {
649
+ if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
650
+ return base58Decode(key);
651
+ }
652
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
653
+ function base64Decode(text) {
654
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) throw new Error("Invalid base64.");
655
+ const out = [];
656
+ let value = 0, bits = 0;
657
+ for (const ch of text.replace(/=+$/, "")) {
658
+ value = value << 6 | B64.indexOf(ch);
659
+ bits += 6;
660
+ if (bits >= 8) {
661
+ bits -= 8;
662
+ out.push(value >> bits & 255);
663
+ }
438
664
  }
439
- if (!fromQuote || fromQuote === ZERO_ADDRESS) {
440
- throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
665
+ const bytes = Uint8Array.from(out);
666
+ if (base64Encode(bytes) !== text) throw new Error("Noncanonical base64.");
667
+ return bytes;
668
+ }
669
+ function base64Encode(bytes) {
670
+ let out = "";
671
+ for (let i = 0; i < bytes.length; i += 3) {
672
+ const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
673
+ out += B64[n >>> 18 & 63] + B64[n >>> 12 & 63] + (i + 1 < bytes.length ? B64[n >>> 6 & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
441
674
  }
442
- if (fromQuote !== fromChains) {
443
- throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
675
+ return out;
676
+ }
677
+ var Reader = class {
678
+ constructor(bytes) {
679
+ this.bytes = bytes;
680
+ }
681
+ bytes;
682
+ at = 0;
683
+ take(n) {
684
+ if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error("Truncated Solana data.");
685
+ const v = this.bytes.slice(this.at, this.at + n);
686
+ this.at += n;
687
+ return v;
688
+ }
689
+ byte() {
690
+ return this.take(1)[0];
691
+ }
692
+ compact() {
693
+ let n = 0;
694
+ for (let i = 0; i < 3; i++) {
695
+ const b = this.byte();
696
+ if (i === 2 && b > 3) throw new Error("Invalid compact-u16.");
697
+ n |= (b & 127) << 7 * i;
698
+ if (!(b & 128)) {
699
+ if (i && b === 0) throw new Error("Noncanonical compact-u16.");
700
+ return n;
701
+ }
702
+ }
703
+ throw new Error("Invalid compact-u16.");
444
704
  }
445
- const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
446
- if (pinned && pinned !== fromChains) {
447
- throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
705
+ u64() {
706
+ const b = this.take(8);
707
+ let n = 0n;
708
+ for (let i = 7; i >= 0; i--) n = n << 8n | BigInt(b[i]);
709
+ return n;
448
710
  }
449
- return fromChains;
711
+ vec() {
712
+ const b = this.take(4);
713
+ return this.take(new DataView(b.buffer).getUint32(0, true));
714
+ }
715
+ end() {
716
+ if (this.at !== this.bytes.length) throw new Error("Trailing Solana data.");
717
+ }
718
+ };
719
+ function parseSolanaTransaction(input) {
720
+ const bytes = new Uint8Array(input), r = new Reader(bytes);
721
+ const count = r.compact(), signatureOffset = r.at;
722
+ if (count < 1 || count > 127) throw new Error("Invalid signature count.");
723
+ r.take(count * 64);
724
+ const messageOffset = r.at, first = r.byte();
725
+ if (first & 128 && first !== 128) throw new Error("Unsupported Solana message version.");
726
+ const version = first === 128 ? 0 : "legacy";
727
+ const requiredSignatures = version === 0 ? r.byte() : first;
728
+ const readonlySigned = r.byte(), readonlyUnsigned = r.byte();
729
+ const keyCount = r.compact();
730
+ if (requiredSignatures !== count || requiredSignatures > keyCount || readonlySigned >= count || readonlyUnsigned > keyCount - count || keyCount > 256) throw new Error("Invalid Solana message header.");
731
+ const staticKeys = Array.from({ length: keyCount }, () => base58Encode(r.take(32)));
732
+ const blockhashOffset = r.at;
733
+ r.take(32);
734
+ const instructions = Array.from({ length: r.compact() }, () => {
735
+ const programIdIndex = r.byte();
736
+ const accounts = Array.from(r.take(r.compact()));
737
+ return { programIdIndex, accounts, data: r.take(r.compact()) };
738
+ });
739
+ const lookups = version === 0 ? Array.from({ length: r.compact() }, () => ({
740
+ address: base58Encode(r.take(32)),
741
+ writable: Array.from(r.take(r.compact())),
742
+ readonly: Array.from(r.take(r.compact()))
743
+ })) : [];
744
+ r.end();
745
+ const all = keyCount + lookups.reduce((n, l) => n + l.writable.length + l.readonly.length, 0);
746
+ if (all > 256 || instructions.some((ix) => ix.programIdIndex >= keyCount || ix.accounts.some((i) => i >= all))) throw new Error("Invalid Solana account index.");
747
+ return { bytes, messageOffset, blockhashOffset, version, requiredSignatures, signatureOffset, staticKeys, instructions, lookups };
748
+ }
749
+ function serializeSolanaTransaction(tx) {
750
+ return new Uint8Array(tx.bytes);
751
+ }
752
+ function overwriteBlockhash(input, blockhash) {
753
+ const tx = parseSolanaTransaction(input), out = new Uint8Array(input);
754
+ out.set(solanaKeyBytes(blockhash), tx.blockhashOffset);
755
+ return out;
450
756
  }
451
- function isLayerZeroRoute(quote, option = {}) {
452
- const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
453
- return bridge.includes("layerzero") || bridge.includes("layer zero");
757
+ function placeSignature(input, publicKey, signature) {
758
+ const tx = parseSolanaTransaction(input), index = tx.staticKeys.slice(0, tx.requiredSignatures).indexOf(publicKey);
759
+ if (index < 0 || signature.length !== 64) throw new Error("Missing Solana signer slot.");
760
+ const out = new Uint8Array(input);
761
+ out.set(signature, tx.signatureOffset + index * 64);
762
+ return out;
454
763
  }
455
- function sourceAssetKey(quote, option = {}) {
456
- return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
764
+ function assertWalletMessage(original, signed) {
765
+ const a = parseSolanaTransaction(original), b = parseSolanaTransaction(signed);
766
+ if (!bytesEqual(a.bytes.subarray(a.messageOffset), b.bytes.subarray(b.messageOffset))) throw new Error("The wallet modified the transaction message; refusing to send.");
767
+ for (let i = 1; i < a.requiredSignatures; i++) {
768
+ const start = a.signatureOffset + 64 * i;
769
+ 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.");
770
+ }
771
+ if (!b.bytes.subarray(b.signatureOffset, b.signatureOffset + 64).some(Boolean)) throw new Error("The wallet returned no fee-payer signature.");
772
+ }
773
+ var SUBMIT_ORDER_DISCRIMINATOR = [230, 150, 200, 53, 92, 208, 109, 108];
774
+ function isSubmitOrder(data) {
775
+ return data.length >= 8 && SUBMIT_ORDER_DISCRIMINATOR.every((v, i) => data[i] === v);
776
+ }
777
+ function decodeSolanaSubmitOrder(data) {
778
+ if (!isSubmitOrder(data)) throw new Error("Not a submit_order instruction.");
779
+ const r = new Reader(data);
780
+ r.take(8);
781
+ const owner = r.take(20), askToken = r.vec();
782
+ let askTokenAmount = 0n;
783
+ for (const b of r.take(32)) askTokenAmount = askTokenAmount << 8n | BigInt(b);
784
+ const bidTokenAmount = r.u64(), destinationReceiver = r.vec(), destinationChainId = r.u64(), executionChainId = r.u64(), deadline = r.u64();
785
+ const tag = r.byte();
786
+ if (tag !== 0 && tag !== 1) throw new Error("Invalid submit_order partner tag.");
787
+ const partnerId = tag === 1 ? r.take(32) : null;
788
+ r.end();
789
+ return { owner, askToken, askTokenAmount, bidTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline, partnerId };
790
+ }
791
+ function verifySolanaSubmit(p, e) {
792
+ const fail = (field) => {
793
+ throw new Error(`Solana order mismatch (${field}); refusing to sign.`);
794
+ };
795
+ if (hexBytes(e.owner).length !== 20 || !bytesEqual(p.owner, hexBytes(e.owner))) fail("owner");
796
+ if (!bytesEqual(p.askToken, hexBytes(e.askToken))) fail("ask token");
797
+ if (p.askTokenAmount <= 0n) fail("non-positive output");
798
+ if (p.askTokenAmount < BigInt(e.minAskTokenAmount)) fail("minimum received");
799
+ if (p.askTokenAmount > BigInt(e.maxAskTokenAmount)) fail("maximum received");
800
+ if (p.bidTokenAmount !== BigInt(e.bidTokenAmount)) fail("amount sent");
801
+ if (!bytesEqual(p.destinationReceiver, hexBytes(e.destinationReceiver))) fail("receiver");
802
+ if (p.destinationChainId !== BigInt(e.destinationChainId)) fail("destination chain");
803
+ if (p.executionChainId !== BigInt(e.executionChainId)) fail("execution chain");
804
+ if (p.deadline !== BigInt(e.deadline)) fail("deadline");
805
+ if (p.partnerId !== null !== (e.partnerId !== null)) fail("subsidy marker");
806
+ }
807
+ var PREPARATION_INSTRUCTIONS = [
808
+ { discriminator: [225, 205, 234, 143, 17, 186, 50, 220], signer: 2 },
809
+ // create_profile
810
+ { discriminator: [223, 99, 118, 101, 213, 29, 215, 137], signer: 3 },
811
+ // initialize_buffer_data
812
+ { discriminator: [105, 254, 33, 182, 188, 80, 204, 204], signer: 3 },
813
+ // write_buffer_data
814
+ { discriminator: [179, 249, 129, 154, 80, 167, 138, 18], signer: 3 },
815
+ // finalize_buffer_data
816
+ { discriminator: [23, 25, 65, 45, 74, 9, 223, 23], signer: 2 }
817
+ // close_buffer_data
818
+ ];
819
+ var SUBMIT_SIGNER_ACCOUNT = 11;
820
+ function preparationInstruction(data) {
821
+ return data.length >= 8 ? PREPARATION_INSTRUCTIONS.find((p) => p.discriminator.every((byte, i) => data[i] === byte)) : void 0;
822
+ }
823
+ function isPreparationInstruction(data) {
824
+ return preparationInstruction(data) !== void 0;
825
+ }
826
+ function verifySolanaTransaction(tx, expected, keys, mustSubmit) {
827
+ if (tx.staticKeys[0] !== expected.signer) throw new Error("Wrong Solana fee payer; refusing to sign.");
828
+ if (!mustSubmit && tx.requiredSignatures !== 1) throw new Error("Unexpected co-signer on a preparation step; refusing to sign.");
829
+ let submits = 0, buffer = null;
830
+ for (const ix of tx.instructions) {
831
+ if (tx.staticKeys[ix.programIdIndex] !== expected.program) throw new Error("Foreign program instruction; refusing to sign.");
832
+ const preparation = preparationInstruction(ix.data);
833
+ if (!isSubmitOrder(ix.data) && !preparation) throw new Error("Unexpected ZeroDelta instruction; refusing to sign.");
834
+ const signerSlot = preparation ? preparation.signer : SUBMIT_SIGNER_ACCOUNT;
835
+ if (keys[ix.accounts[signerSlot]] !== expected.signer) throw new Error("ZeroDelta instruction names another signer; refusing to sign.");
836
+ if (!isSubmitOrder(ix.data)) continue;
837
+ submits++;
838
+ verifySolanaSubmit(decodeSolanaSubmitOrder(ix.data), expected);
839
+ if (keys[ix.accounts[1]] !== expected.mint) throw new Error("Wrong source mint; refusing to sign.");
840
+ buffer = keys[ix.accounts[8]] ?? null;
841
+ if (!buffer) throw new Error("Missing route buffer; refusing to sign.");
842
+ }
843
+ if (submits !== (mustSubmit ? 1 : 0)) throw new Error("Expected exactly one submit_order in submit and none in preparation; refusing to sign.");
844
+ return buffer;
845
+ }
846
+ function parseAddressLookupTable(data) {
847
+ 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.");
848
+ return Array.from({ length: (data.length - 56) / 32 }, (_, i) => base58Encode(data.subarray(56 + 32 * i, 88 + 32 * i)));
849
+ }
850
+ async function resolveSolanaKeys(tx, rpc) {
851
+ if (!tx.lookups.length) return [...tx.staticKeys];
852
+ const result = await rpc("getMultipleAccounts", [tx.lookups.map((l) => l.address), { encoding: "base64", commitment: "confirmed" }]);
853
+ if (!Array.isArray(result.value) || result.value.length !== tx.lookups.length) throw new Error("Missing lookup tables.");
854
+ const writable = [], readonly = [];
855
+ tx.lookups.forEach((lookup, i) => {
856
+ const account = result.value[i];
857
+ if (account?.owner !== "AddressLookupTab1e1111111111111111111111111" || account.data[1] !== "base64") throw new Error("Invalid lookup table account.");
858
+ const table = parseAddressLookupTable(base64Decode(account.data[0]));
859
+ for (const [indexes, into] of [[lookup.writable, writable], [lookup.readonly, readonly]]) for (const index of indexes) {
860
+ if (!table[index]) throw new Error("Lookup table index out of range.");
861
+ into.push(table[index]);
862
+ }
863
+ });
864
+ return [...tx.staticKeys, ...writable, ...readonly];
865
+ }
866
+ function encodeNextSolanaOrders(legs) {
867
+ return legs.length ? hexBytes(`0x${uintWord(32)}${encodeSubmitOrder(legs).slice(10 + 128)}`) : new Uint8Array();
868
+ }
869
+ function checkSolanaRouteBuffer(account, expected) {
870
+ if (!account || account.owner !== expected.program || account.data[1] !== "base64") throw new Error("Route buffer is not a ZeroDelta account.");
871
+ const d = base64Decode(account.data[0]);
872
+ if (d.length < 53) throw new Error("Route buffer truncated.");
873
+ if (base58Encode(d.subarray(9, 41)) !== expected.signer) throw new Error("Route buffer signer mismatch.");
874
+ const len = new DataView(d.buffer, d.byteOffset + 49, 4).getUint32(0, true);
875
+ if (d.length < 53 + len || !bytesEqual(d.subarray(53, 53 + len), encodeNextSolanaOrders(expected.nextOrders))) throw new Error("Route buffer legs mismatch.");
876
+ }
877
+ function checkSolanaProgram(gateway, pinned, registry) {
878
+ const program = gateway || registry || "";
879
+ solanaKeyBytes(program);
880
+ if (pinned ? program !== pinned : gateway && registry && gateway !== registry) throw new Error("Solana program does not match pin or chains registry.");
881
+ return program;
882
+ }
883
+ function checkSolanaPlan(txs) {
884
+ 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.");
885
+ }
886
+ async function deriveSolanaEvent(signer, salt) {
887
+ const s = hexBytes(salt), material = new Uint8Array(32 + s.length);
888
+ material.set(solanaKeyBytes(signer));
889
+ material.set(s, 32);
890
+ const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", material));
891
+ const { eventPublicKey } = await import('./ed25519-GAMEXARB.js');
892
+ return { seed, publicKey: base58Encode(await eventPublicKey(seed)) };
893
+ }
894
+ async function cosignSolanaEvent(bytes, signer, build) {
895
+ const event = await deriveSolanaEvent(signer, build.salt);
896
+ if (event.publicKey !== build.messageSentEventData) throw new Error("Event buildData key mismatch; refusing to sign.");
897
+ const tx = parseSolanaTransaction(bytes);
898
+ const { eventSignature } = await import('./ed25519-GAMEXARB.js');
899
+ return placeSignature(bytes, event.publicKey, await eventSignature(tx.bytes.subarray(tx.messageOffset), event.seed));
900
+ }
901
+ async function pollSolanaConfirmation(rpc, signature) {
902
+ const deadline = Date.now() + 9e4;
903
+ while (Date.now() < deadline) {
904
+ const { value } = await rpc("getSignatureStatuses", [[signature]]);
905
+ const status = value?.[0];
906
+ if (status?.err) throw new Error(`Transaction failed on chain: ${JSON.stringify(status.err)}`);
907
+ if (["confirmed", "finalized"].includes(status?.confirmationStatus)) return;
908
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
909
+ }
910
+ throw new Error("Transaction confirmation timed out; check the signature before retrying.");
457
911
  }
458
- function requiresNativeBridgeFee(quote, option = {}) {
459
- const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
460
- const execChainId = Number(quote?.executionChainId);
461
- if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
462
- return false;
912
+
913
+ // src/core/units.ts
914
+ function assetDecimals(token) {
915
+ const sym = symbolKey(token?.symbol);
916
+ const registry = Number(token?.decimals);
917
+ const canonical = isSolanaChainId(token?.chainId) ? solanaDestinationAsset(token?.address)?.decimals : CANONICAL_DECIMALS[sym];
918
+ if (canonical !== void 0) {
919
+ if (!Number.isInteger(registry)) {
920
+ throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
921
+ }
922
+ if (registry !== canonical) {
923
+ throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
924
+ }
925
+ return canonical;
463
926
  }
464
- const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
465
- if (canonical) return canonical === "layerzero";
466
- return isLayerZeroRoute(quote, option);
927
+ if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
928
+ throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
929
+ }
930
+ return registry;
467
931
  }
468
- function applyLayerZeroBuffer(quote, option = {}) {
469
- const gas = BigInt(quote?.gasCostSource || "0");
470
- if (gas <= 0n) return 0n;
471
- if (!requiresNativeBridgeFee(quote, option)) return 0n;
472
- return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
932
+ function normalizeDecimalText(value) {
933
+ const text = String(value || "").trim().replace(/\s+/g, "");
934
+ if (!text) return "";
935
+ if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
936
+ if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
937
+ if (text.includes(",")) return "";
938
+ return text;
939
+ }
940
+ function parseUnitsDecimal(amount, decimals) {
941
+ const text = normalizeDecimalText(amount);
942
+ if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
943
+ const [whole, frac = ""] = text.split(".");
944
+ if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
945
+ const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
946
+ const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
947
+ if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
948
+ return value;
949
+ }
950
+ function scaleDecimals(amount, fromDecimals, toDecimals) {
951
+ if (toDecimals === fromDecimals) return amount;
952
+ if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
953
+ return amount / 10n ** BigInt(fromDecimals - toDecimals);
954
+ }
955
+ function formatUnits(raw2, decimals, maxDecimals = 6) {
956
+ const value = BigInt(raw2 || "0");
957
+ const base = 10n ** BigInt(decimals);
958
+ const whole = value / base;
959
+ const fracFull = (value % base).toString().padStart(decimals, "0");
960
+ const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
961
+ return frac ? `${whole}.${frac}` : whole.toString();
962
+ }
963
+ function finalOf(quote) {
964
+ return BigInt(quote?.finalAmount || quote?.toAmount || "0");
965
+ }
966
+
967
+ // src/core/ask-scale.ts
968
+ function askTokenDecimals(quote, tokens, _from, to) {
969
+ const requests = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
970
+ const execution = Number(requests[requests.length - 1]?.executionChainId || quote.executionChainId);
971
+ if (!Number.isSafeInteger(execution) || execution <= 0) throw new Error("Could not verify the quote amount precision.");
972
+ if (execution === Number(to.chainId)) return assetDecimals(to);
973
+ const row = tokens.find((token) => Number(token.chainId) === execution && symbolKey(token.symbol) === symbolKey(to.symbol));
974
+ if (row) return assetDecimals(row);
975
+ if (isSolanaChainId(to.chainId)) throw new Error("Could not verify the quote amount precision.");
976
+ return assetDecimals(to);
977
+ }
978
+ function askCovers(ask, final, askDecimals, finalDecimals) {
979
+ if (![askDecimals, finalDecimals].every((n) => Number.isInteger(n) && n >= 0 && n <= 36)) throw new Error("Could not verify the quote amount precision.");
980
+ const shift = askDecimals - finalDecimals;
981
+ return shift >= 0 ? ask >= final * 10n ** BigInt(shift) : ask * 10n ** BigInt(-shift) >= final;
473
982
  }
474
983
 
475
984
  // src/core/ticker.ts
@@ -510,7 +1019,7 @@ function counterpartTokens(tokens, selected) {
510
1019
  return tokens.filter((token) => assetClassOf(token.symbol) === want);
511
1020
  }
512
1021
  function tokenKey(chainId, address) {
513
- return `${Number(chainId)}:${String(address || "").toLowerCase()}`;
1022
+ return `${Number(chainId)}:${chainAddressKey(chainId, address)}`;
514
1023
  }
515
1024
  function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
516
1025
  return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
@@ -596,7 +1105,7 @@ function buildCatalogue(input) {
596
1105
  const id = Number(route.toChainId);
597
1106
  if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
598
1107
  }
599
- const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
1108
+ const allowed = tokens.filter((token) => token.isEnabled !== false && isChainAddress(token.chainId, token.address) && allowedAssets.has(symbolKey(token.symbol)));
600
1109
  const projectedCatalogue = allowed.filter((token) => {
601
1110
  if (!chainIds.has(Number(token.chainId))) return false;
602
1111
  if (product === "rwa") return true;
@@ -630,23 +1139,23 @@ function buildCatalogue(input) {
630
1139
 
631
1140
  // src/core/options.ts
632
1141
  function chainNameOf(chainId, chains) {
633
- const chain = chains.find((item) => Number(item.chainId) === Number(chainId));
634
- return chain?.displayName || chain?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
1142
+ const chain2 = chains.find((item) => Number(item.chainId) === Number(chainId));
1143
+ return chain2?.displayName || chain2?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
635
1144
  }
636
1145
  function chainById(chains, chainId) {
637
- return chains.find((chain) => Number(chain.chainId) === Number(chainId)) || null;
1146
+ return chains.find((chain2) => Number(chain2.chainId) === Number(chainId)) || null;
638
1147
  }
639
1148
  function isDeliverable(symbol, chainId) {
640
1149
  if (Number(chainId) === 8453 && symbolKey(symbol) === "USDT") return false;
641
1150
  return true;
642
1151
  }
643
- function chainSelectable(chain, chainId) {
1152
+ function chainSelectable(chain2, chainId) {
644
1153
  if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
645
- if (!chain) return true;
646
- return chain.isEnabled !== false;
1154
+ if (!chain2) return true;
1155
+ return chain2.isEnabled !== false;
647
1156
  }
648
1157
  function tokenEnabled(token) {
649
- return token?.isEnabled !== false && isAddress(token?.address) && Number.isFinite(Number(token?.chainId));
1158
+ return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
650
1159
  }
651
1160
  function findToken(tokens, chainId, symbol) {
652
1161
  const key = symbolKey(symbol);
@@ -682,8 +1191,8 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
682
1191
  for (const token of universe) {
683
1192
  if (!tokenEnabled(token)) continue;
684
1193
  const chainId = Number(token.chainId);
685
- const chain = chainById(chains, chainId);
686
- if (!chainSelectable(chain, chainId)) continue;
1194
+ const chain2 = chainById(chains, chainId);
1195
+ if (!chainSelectable(chain2, chainId)) continue;
687
1196
  const key = tokenKey(chainId, token.address);
688
1197
  if (seen.has(key)) continue;
689
1198
  if (refusal(token)) continue;
@@ -723,12 +1232,645 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
723
1232
  return options;
724
1233
  }
725
1234
 
1235
+ // src/core/solana-source.ts
1236
+ var CANONICAL_SOLANA_PROGRAM = "zd1E5feCJLNYaPPsBAYkCPMKGVnipYf8God9h917W33";
1237
+ var MAX_ASK_OVER_FINAL_BPS = 200n;
1238
+ var states = /* @__PURE__ */ new WeakMap();
1239
+ var quoteRequests = /* @__PURE__ */ new WeakMap();
1240
+ var inFlight = /* @__PURE__ */ new Map();
1241
+ var activeSigners = /* @__PURE__ */ new Set();
1242
+ var clone = (value) => JSON.parse(JSON.stringify(value));
1243
+ function freeze(value) {
1244
+ if (value && typeof value === "object") {
1245
+ for (const v of Object.values(value)) freeze(v);
1246
+ Object.freeze(value);
1247
+ }
1248
+ return value;
1249
+ }
1250
+ function raw(value, label, positive = false) {
1251
+ if (typeof value !== "string" || !/^\d+$/.test(value) || positive && BigInt(value) <= 0n || BigInt(value) >= 1n << 256n) throw new Error(`Invalid ${label}.`);
1252
+ return value;
1253
+ }
1254
+ function chain(value) {
1255
+ const text = String(value);
1256
+ if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) >= 1n << 64n) throw new Error("Invalid order chain.");
1257
+ return text;
1258
+ }
1259
+ function same(a, b) {
1260
+ return a.toLowerCase() === b.toLowerCase();
1261
+ }
1262
+ function recipient(input) {
1263
+ const to = input.recipient || (isSolanaChainId(input.toChainId) ? input.sender : input.owner);
1264
+ if (!isChainAddress(input.toChainId, to)) throw new Error("Invalid destination recipient.");
1265
+ return chainAddressKey(input.toChainId, to);
1266
+ }
1267
+ function validateInput(input) {
1268
+ if (input.fromChainId !== void 0 && input.fromChainId !== SOLANA_CHAIN_ID) throw new Error("Solana source chain required.");
1269
+ if (!Number.isSafeInteger(input.toChainId) || input.toChainId <= 0) throw new Error("Invalid destination chain.");
1270
+ if (!SUPPORTED_ASSETS.has(symbolKey(input.fromToken)) || !SUPPORTED_ASSETS.has(symbolKey(input.toToken))) throw new Error("Unsupported Solana source asset.");
1271
+ assertAddress(input.owner, "EVM order owner");
1272
+ solanaKeyBytes(input.sender);
1273
+ recipient(input);
1274
+ const span = input.deadlineSpanSeconds ?? 7200, slip = input.slippageBps ?? 0;
1275
+ if (!Number.isInteger(span) || span < 1 || span > 86400) throw new Error("Invalid Solana deadline span.");
1276
+ if (!Number.isInteger(slip) || slip < 0 || slip > 1e4) throw new Error("Invalid slippage tolerance.");
1277
+ }
1278
+ function selections(input, tokens) {
1279
+ validateInput(input);
1280
+ const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
1281
+ if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
1282
+ solanaKeyBytes(from.address);
1283
+ assertPinnedSolanaSource(from);
1284
+ if (!isChainAddress(input.toChainId, to.address)) throw new Error("Invalid destination token.");
1285
+ const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
1286
+ raw(amount, "input amount", true);
1287
+ if (BigInt(amount) >= 1n << 64n) throw new Error("Solana bid exceeds u64.");
1288
+ return { from, to, amount };
1289
+ }
1290
+ function assertPinnedSolanaSource(token) {
1291
+ const pinned = solanaDestinationAsset(token.address);
1292
+ if (!pinned || pinned.symbol !== symbolKey(token.symbol) || pinned.decimals !== Number(token.decimals)) {
1293
+ throw new Error("This Solana token is not supported for payment; refusing to sign.");
1294
+ }
1295
+ }
1296
+ function makeRequest(input, from, to, amount) {
1297
+ return {
1298
+ inputChain: SOLANA_CHAIN_ID,
1299
+ outputChain: input.toChainId,
1300
+ inputToken: from.symbol,
1301
+ outputToken: to.symbol,
1302
+ inputAmount: amount,
1303
+ owners: { evm: input.owner },
1304
+ destinationWallet: recipient(input),
1305
+ sender: input.sender,
1306
+ deadline: String(Math.floor(Date.now() / 1e3) + (input.deadlineSpanSeconds ?? 7200))
1307
+ };
1308
+ }
1309
+ function normalizePreview(request, quote, to, amount) {
1310
+ const option = quote?.options?.[0];
1311
+ if (!option) throw new Error("Native quote returned no options.");
1312
+ const receive = raw(option.finalAmount, "quoted output", true);
1313
+ return {
1314
+ receive: formatUnits(receive, assetDecimals(to)),
1315
+ receiveRaw: receive,
1316
+ fromAmount: amount,
1317
+ fromToken: request.inputToken,
1318
+ toToken: request.outputToken,
1319
+ bridge: option.bridge || "",
1320
+ feeBps: Number(option.feeBps || 0),
1321
+ estimatedDuration: Number(option.estimatedTimeSec || 0),
1322
+ via: null,
1323
+ nativeFeeRaw: String(option.gasCostSource || "0"),
1324
+ quote,
1325
+ option,
1326
+ txData: option.txData,
1327
+ request
1328
+ };
1329
+ }
1330
+ async function quoteSolanaSource(api, input) {
1331
+ const { from, to, amount } = selections(input, await api.fetchTokens());
1332
+ const request = makeRequest(input, from, to, amount);
1333
+ const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1334
+ const preview = normalizePreview(request, quote, to, input.amountIn);
1335
+ quoteRequests.set(preview, { api, request: clone(request) });
1336
+ return preview;
1337
+ }
1338
+ async function previewSolanaSource(api, input) {
1339
+ const tokens = await api.fetchTokens();
1340
+ const from = findToken(tokens, SOLANA_CHAIN_ID, symbolKey(input.fromToken)), to = findToken(tokens, input.toChainId, symbolKey(input.toToken));
1341
+ if (!from || !to) throw new Error("Selected token is not enabled on its chain.");
1342
+ assertPinnedSolanaSource(from);
1343
+ const amount = parseUnitsDecimal(input.amountIn, assetDecimals(from)).toString();
1344
+ raw(amount, "input amount", true);
1345
+ const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
1346
+ const request = body;
1347
+ const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1348
+ const option = quote?.options?.[0];
1349
+ if (!option) throw new Error("Native quote returned no options.");
1350
+ const receive = raw(option.finalAmount, "quoted output", true);
1351
+ return {
1352
+ receive: formatUnits(receive, assetDecimals(to)),
1353
+ receiveRaw: receive,
1354
+ fromAmount: input.amountIn,
1355
+ fromToken: request.inputToken,
1356
+ toToken: request.outputToken,
1357
+ bridge: option.bridge || "",
1358
+ feeBps: Number(option.feeBps || 0),
1359
+ estimatedDuration: Number(option.estimatedTimeSec || 0),
1360
+ via: null,
1361
+ nativeFeeRaw: "0"
1362
+ };
1363
+ }
1364
+ function solanaQuoteCompliance(quote) {
1365
+ for (const value of [quote?.complianceDecision, quote?.compliance]) {
1366
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1367
+ }
1368
+ return void 0;
1369
+ }
1370
+ function denied(value) {
1371
+ return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
1372
+ }
1373
+ async function checkActiveScreens(api, input) {
1374
+ const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
1375
+ const screens = await Promise.all(addresses.map(async (address) => {
1376
+ try {
1377
+ return await api.screenWallet(address);
1378
+ } catch {
1379
+ return void 0;
1380
+ }
1381
+ }));
1382
+ if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
1383
+ }
1384
+ function jsonGuards(input, preview, tokens, chains) {
1385
+ const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
1386
+ const wanted = makeRequest(input, from, to, amount);
1387
+ for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
1388
+ if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
1389
+ }
1390
+ if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
1391
+ const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
1392
+ if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
1393
+ if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
1394
+ 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.");
1395
+ if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
1396
+ if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
1397
+ if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
1398
+ if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
1399
+ checkSolanaPlan(option.txData);
1400
+ const orders = option.orderRequests;
1401
+ if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
1402
+ const first = orders[0], last = orders[orders.length - 1];
1403
+ if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
1404
+ if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
1405
+ const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
1406
+ if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
1407
+ if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
1408
+ for (let i = 0; i < orders.length; i++) {
1409
+ const order = orders[i];
1410
+ if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
1411
+ raw(order.askTokenAmount, "ask amount", true);
1412
+ raw(order.bidTokenAmount, "bid amount", true);
1413
+ chain(order.destinationChainId);
1414
+ chain(order.executionChainId);
1415
+ if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
1416
+ if (isSolanaChainId(order.destinationChainId)) {
1417
+ if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
1418
+ solanaBridgeOf(to);
1419
+ checkSolanaReceiver(order, recipient(input), to.address);
1420
+ } else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
1421
+ 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.");
1422
+ if (i) {
1423
+ const previous = orders[i - 1];
1424
+ if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
1425
+ if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
1426
+ }
1427
+ }
1428
+ const quoteForScale = { ...option, orderRequests: orders };
1429
+ const execution = Number(last.executionChainId);
1430
+ 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.");
1431
+ const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
1432
+ const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
1433
+ const minFinal = final * (10000n - slip) / 10000n;
1434
+ 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.");
1435
+ 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.");
1436
+ const registry = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
1437
+ const contracts = registry?.contracts;
1438
+ const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry?.escrowContract);
1439
+ const marker = option.partnerId ?? preview.quote.partnerId;
1440
+ 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.");
1441
+ const ask = BigInt(first.askTokenAmount);
1442
+ return {
1443
+ program,
1444
+ signer: input.sender,
1445
+ mint: from.address,
1446
+ owner: input.owner,
1447
+ askToken: first.askToken,
1448
+ minAskTokenAmount: ask.toString(),
1449
+ maxAskTokenAmount: ask.toString(),
1450
+ bidTokenAmount: amount,
1451
+ destinationReceiver: first.destinationReceiver,
1452
+ destinationChainId: String(first.destinationChainId),
1453
+ executionChainId: String(first.executionChainId),
1454
+ deadline: request.deadline,
1455
+ partnerId: marker == null ? null : String(marker),
1456
+ nextOrders: orders.slice(1)
1457
+ };
1458
+ }
1459
+ async function buildSolanaSourcePlan(api, input, quoted) {
1460
+ const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
1461
+ const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
1462
+ 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.");
1463
+ const preview = clone(served);
1464
+ const expected = jsonGuards(input, preview, tokens, chains);
1465
+ await checkActiveScreens(api, input);
1466
+ const plan = freeze({ preview, expected, txData: preview.option.txData });
1467
+ const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
1468
+ states.set(plan, {
1469
+ api,
1470
+ input: clone(input),
1471
+ plan,
1472
+ failed: false,
1473
+ busy: false,
1474
+ originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
1475
+ signatures: [],
1476
+ done: 0
1477
+ });
1478
+ return plan;
1479
+ }
1480
+ function createSolanaRpc(api) {
1481
+ return async (method, params) => {
1482
+ const body = await api.apiRequest("/solana-rpc", {
1483
+ method: "POST",
1484
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
1485
+ timeoutMs: 15e3
1486
+ });
1487
+ if (body.error && solanaLamportShortfall(body.error.data?.logs) !== null) throw new Error(SOL_SHORTFALL_MESSAGE);
1488
+ if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
1489
+ return body.result;
1490
+ };
1491
+ }
1492
+ var SolanaSendError = class extends Error {
1493
+ constructor(message, signature, sentAt) {
1494
+ super(message);
1495
+ this.signature = signature;
1496
+ this.sentAt = sentAt;
1497
+ this.name = "SolanaSendError";
1498
+ }
1499
+ signature;
1500
+ sentAt;
1501
+ };
1502
+ async function executeSolanaPlan(input) {
1503
+ const signature = await runSolanaPlan(input, false);
1504
+ if (!signature) throw new Error("Missing final Solana submit.");
1505
+ return signature;
1506
+ }
1507
+ async function executeSolanaPlanStaged(input) {
1508
+ const signature = await runSolanaPlan(input, true);
1509
+ return signature ? { status: "sent", signature } : { status: "prepared" };
1510
+ }
1511
+ function solanaPlanNeedsPreparation(plan) {
1512
+ const state = states.get(plan);
1513
+ const live = state?.plan ?? plan;
1514
+ return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
1515
+ }
1516
+ async function runSolanaPlan(input, stopBeforeSubmit) {
1517
+ const state = states.get(input.plan);
1518
+ if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
1519
+ if (state.sent) return state.sent;
1520
+ if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
1521
+ if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
1522
+ state.busy = true;
1523
+ activeSigners.add(input.signer.publicKey);
1524
+ let index = 0, completedBeforeRun = state.signatures.length;
1525
+ const progress = (stage) => {
1526
+ const pending = inFlight.get(input.signer.publicKey);
1527
+ try {
1528
+ input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
1529
+ } catch {
1530
+ }
1531
+ };
1532
+ try {
1533
+ progress("preparing");
1534
+ const pending = inFlight.get(input.signer.publicKey);
1535
+ if (pending) {
1536
+ const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
1537
+ const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
1538
+ if (status?.err) inFlight.delete(input.signer.publicKey);
1539
+ else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
1540
+ inFlight.delete(input.signer.publicKey);
1541
+ if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
1542
+ if (pending.final) {
1543
+ pending.state.sent = pending.signature;
1544
+ reportSolana(pending.state, pending.signature);
1545
+ if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
1546
+ progress("sent");
1547
+ return pending.signature;
1548
+ }
1549
+ } else {
1550
+ if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
1551
+ throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
1552
+ }
1553
+ inFlight.delete(input.signer.publicKey);
1554
+ }
1555
+ }
1556
+ if (state.failed) {
1557
+ const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
1558
+ 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.");
1559
+ state.plan = retried;
1560
+ state.done = 0;
1561
+ state.failed = false;
1562
+ }
1563
+ const plan = state.plan;
1564
+ checkSolanaPlan(plan.txData);
1565
+ for (const tx of plan.txData) {
1566
+ const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
1567
+ verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
1568
+ }
1569
+ for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
1570
+ completedBeforeRun = state.signatures.length;
1571
+ const startAt = state.done;
1572
+ for (index = startAt; index < plan.txData.length; index++) {
1573
+ if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
1574
+ progress("ready");
1575
+ return null;
1576
+ }
1577
+ if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
1578
+ await checkActiveScreens(state.api, state.input);
1579
+ const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
1580
+ const keys = await resolveSolanaKeys(parsed, input.rpc);
1581
+ const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
1582
+ if (buffer) {
1583
+ const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
1584
+ checkSolanaRouteBuffer(account.value, plan.expected);
1585
+ }
1586
+ const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
1587
+ let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
1588
+ if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
1589
+ verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
1590
+ progress("signing");
1591
+ const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
1592
+ assertWalletMessage(bytes, signed);
1593
+ verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
1594
+ const signedTx = parseSolanaTransaction(signed);
1595
+ const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
1596
+ const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
1597
+ inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
1598
+ progress("sending");
1599
+ try {
1600
+ const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
1601
+ if (returned !== signature) throw new Error("RPC returned a different signature.");
1602
+ if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
1603
+ } catch (error) {
1604
+ throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
1605
+ }
1606
+ inFlight.delete(input.signer.publicKey);
1607
+ state.signatures.push(signature);
1608
+ state.done = index + 1;
1609
+ if (tx.actionType === "submit") {
1610
+ state.sent = signature;
1611
+ reportSolana(state, signature);
1612
+ progress("sent");
1613
+ return signature;
1614
+ }
1615
+ progress("ready");
1616
+ }
1617
+ throw new Error("Missing final Solana submit.");
1618
+ } catch (error) {
1619
+ state.failed = true;
1620
+ progress("failed");
1621
+ throw error;
1622
+ } finally {
1623
+ state.busy = false;
1624
+ activeSigners.delete(input.signer.publicKey);
1625
+ }
1626
+ }
1627
+ function reportSolana(state, signature) {
1628
+ try {
1629
+ void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
1630
+ });
1631
+ } catch {
1632
+ }
1633
+ }
1634
+ async function readSolanaBalance(rpc, owner, mint) {
1635
+ try {
1636
+ solanaKeyBytes(owner);
1637
+ solanaKeyBytes(mint);
1638
+ const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
1639
+ if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
1640
+ let total = 0n, decimals;
1641
+ for (const item of result.value) {
1642
+ const amount = item.account?.data?.parsed?.info?.tokenAmount;
1643
+ if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
1644
+ decimals = amount.decimals;
1645
+ total += BigInt(raw(amount.amount, "token balance"));
1646
+ }
1647
+ return total;
1648
+ } catch {
1649
+ return void 0;
1650
+ }
1651
+ }
1652
+ function solanaLamportShortfall(logs) {
1653
+ if (!Array.isArray(logs)) return null;
1654
+ for (const line of logs) {
1655
+ const m = /insufficient lamports (\d+), need (\d+)/.exec(String(line));
1656
+ if (m) {
1657
+ const need = Number(m[2]);
1658
+ return Number.isSafeInteger(need) && need > 0 ? need : null;
1659
+ }
1660
+ }
1661
+ return null;
1662
+ }
1663
+ 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.";
1664
+ async function simulateSolanaCost(rpc, plan) {
1665
+ checkSolanaPlan(plan.txData);
1666
+ const signer = plan.expected.signer;
1667
+ const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
1668
+ const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
1669
+ const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
1670
+ if (sim.value?.err) {
1671
+ const need = solanaLamportShortfall(sim.value.logs);
1672
+ if (need !== null && Number.isSafeInteger(balanceLamports)) return { lamports: need, balanceLamports, sufficient: false };
1673
+ throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
1674
+ }
1675
+ if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
1676
+ const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
1677
+ return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
1678
+ }
1679
+
1680
+ // src/core/delivery.ts
1681
+ var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "expired", "failed"]);
1682
+ var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim"]);
1683
+ var TRACKING = Object.freeze({ phase: "tracking", status: "", steps: [] });
1684
+ var word = (v) => typeof v === "string" ? v.trim().toLowerCase() : "";
1685
+ function normalizeDelivery(raw2) {
1686
+ const row = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2.data ?? raw2 : null;
1687
+ if (!row || typeof row !== "object" || Array.isArray(row)) return TRACKING;
1688
+ const r = row;
1689
+ const chained = r.isChained === true || Array.isArray(r.legs) && r.legs.length > 1;
1690
+ const journey = word(r.journeyStatus);
1691
+ const own = word(r.status);
1692
+ const status = journey || own;
1693
+ const rawSteps = Array.isArray(r.steps) ? r.steps : [];
1694
+ 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" }));
1695
+ if (!status) return TRACKING;
1696
+ if (FAILED.has(status)) return { phase: "failed", status, steps };
1697
+ if (ATTENTION.has(status)) return { phase: "attention", status, steps };
1698
+ if (status === "delivered" && !(chained && !journey)) return { phase: "delivered", status, steps: steps.map((s) => ({ ...s, done: true })) };
1699
+ return { phase: "in-progress", status: status === "delivered" ? "continuing" : status, steps };
1700
+ }
1701
+ var HASH = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
1702
+ function sameOrder(raw2, hash) {
1703
+ const row = raw2 && typeof raw2 === "object" ? raw2.data ?? raw2 : null;
1704
+ const got = row && typeof row === "object" ? row.txHash : void 0;
1705
+ if (typeof got !== "string" || !got) return false;
1706
+ return hash.startsWith("0x") ? got.toLowerCase() === hash.toLowerCase() : got === hash;
1707
+ }
1708
+ async function fetchDelivery(api, hash) {
1709
+ if (typeof hash !== "string" || !HASH.test(hash)) return TRACKING;
1710
+ try {
1711
+ const raw2 = await api.apiRequest(`/transactions/${hash}`, { timeoutMs: 8e3 });
1712
+ return sameOrder(raw2, hash) ? normalizeDelivery(raw2) : TRACKING;
1713
+ } catch {
1714
+ return TRACKING;
1715
+ }
1716
+ }
1717
+
1718
+ // src/core/history.ts
1719
+ var WALLET_HISTORY_LIMIT = 50;
1720
+ var HASH2 = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
1721
+ var WALLET = /^(?:0x[0-9a-fA-F]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})$/;
1722
+ function historyKey(value) {
1723
+ return value.startsWith("0x") ? value.toLowerCase() : value;
1724
+ }
1725
+ var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
1726
+ function tokenAt(tokens, chainId, address) {
1727
+ if (!address) return void 0;
1728
+ const key = historyKey(address);
1729
+ return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key);
1730
+ }
1731
+ function amountOf(raw2, token, rowDecimals, rowAmount) {
1732
+ const decimals = token ? Number(token.decimals) : Number(rowDecimals);
1733
+ if (/^\d{1,78}$/.test(raw2) && Number.isInteger(decimals) && decimals > 0 && decimals <= 36) return formatUnits(raw2, decimals);
1734
+ return Number(rowDecimals) > 0 && /^\d+(?:\.\d+)?$/.test(rowAmount) ? rowAmount.slice(0, 40) : "";
1735
+ }
1736
+ function historyEntryFromOrder(raw2, tokens) {
1737
+ if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return null;
1738
+ const r = raw2;
1739
+ const hash = str(r.txHash);
1740
+ if (!HASH2.test(hash)) return null;
1741
+ const fromChainId = Number(r.sourceChainId) || 0;
1742
+ const toChainId = Number(r.finalDestChainId ?? r.destChainId) || 0;
1743
+ const from = tokenAt(tokens, fromChainId, str(r.fromTokenAddress));
1744
+ const toAddress = str(r.finalToTokenAddress) || str(r.toTokenAddress);
1745
+ const to = tokenAt(tokens, toChainId, toAddress);
1746
+ const fromAsset = (from?.symbol ?? str(r.fromTokenSymbol)).slice(0, 10);
1747
+ const toAsset = (to?.symbol ?? (str(r.finalToTokenSymbol) || str(r.toTokenSymbol))).slice(0, 10);
1748
+ const payAmount = amountOf(str(r.fromTokenRawAmount), from, r.fromTokenDecimals, str(r.fromTokenAmount));
1749
+ 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));
1750
+ const delivery = normalizeDelivery(r).phase;
1751
+ const wallet = str(r.wallet);
1752
+ const receiver = str(r.destinationReceiver);
1753
+ const at = str(r.createdAt) || str(r.submittedAt);
1754
+ return {
1755
+ kind: "swap",
1756
+ hash,
1757
+ txKind: "submitOrder",
1758
+ chainId: fromChainId || null,
1759
+ chainName: "",
1760
+ fromAsset,
1761
+ toAsset,
1762
+ fromTicker: from ? tokenTicker(from).slice(0, 12) : void 0,
1763
+ toTicker: to ? tokenTicker(to).slice(0, 12) : void 0,
1764
+ payAmount,
1765
+ receiveAmount,
1766
+ account: WALLET.test(wallet) ? historyKey(wallet) : "",
1767
+ recipient: WALLET.test(receiver) ? receiver : "",
1768
+ settlement: "escrow",
1769
+ status: "submitted",
1770
+ at: Number.isNaN(Date.parse(at)) ? (/* @__PURE__ */ new Date(0)).toISOString() : new Date(at).toISOString(),
1771
+ delivery: delivery === "tracking" || delivery === "unavailable" ? void 0 : delivery,
1772
+ legs: [
1773
+ {
1774
+ index: 1,
1775
+ fromAsset,
1776
+ fromTicker: from ? tokenTicker(from).slice(0, 12) : void 0,
1777
+ fromChainId,
1778
+ fromChainName: "",
1779
+ fromAmount: payAmount,
1780
+ toAsset,
1781
+ toTicker: to ? tokenTicker(to).slice(0, 12) : void 0,
1782
+ toChainId,
1783
+ toChainName: "",
1784
+ toAmount: receiveAmount,
1785
+ executionChainId: Number(r.executionChainId) || 0,
1786
+ executionChainName: ""
1787
+ }
1788
+ ]
1789
+ };
1790
+ }
1791
+ async function fetchWalletHistory(api, wallets) {
1792
+ const asked = [...new Set(wallets.filter((w) => WALLET.test(w)).map(historyKey))];
1793
+ if (!asked.length) return [];
1794
+ const tokens = await api.fetchTokens().catch(() => []);
1795
+ const reads = await Promise.all(
1796
+ asked.map(async (wallet) => {
1797
+ try {
1798
+ const rows = await api.apiRequest(`/transactions?wallet=${encodeURIComponent(wallet)}&limit=${WALLET_HISTORY_LIMIT}`, { timeoutMs: 1e4 });
1799
+ if (!Array.isArray(rows)) return null;
1800
+ return rows.filter((row) => historyKey(str(row?.wallet)) === wallet).map((row) => historyEntryFromOrder(row, tokens));
1801
+ } catch {
1802
+ return null;
1803
+ }
1804
+ })
1805
+ );
1806
+ if (reads.every((read) => read === null)) return null;
1807
+ return reads.flatMap((read) => read ?? []).filter((e) => e !== null);
1808
+ }
1809
+ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
1810
+ const byHash = /* @__PURE__ */ new Map();
1811
+ for (const entry of remote ?? []) if (!byHash.has(historyKey(entry.hash))) byHash.set(historyKey(entry.hash), entry);
1812
+ const out = [];
1813
+ const seen = /* @__PURE__ */ new Set();
1814
+ for (const entry of local) {
1815
+ const key = historyKey(entry.hash);
1816
+ if (seen.has(key)) continue;
1817
+ seen.add(key);
1818
+ const known = byHash.get(key);
1819
+ out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
1820
+ }
1821
+ for (const [key, entry] of byHash) if (!seen.has(key)) out.push(entry);
1822
+ return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
1823
+ }
1824
+
1825
+ // src/core/escrow.ts
1826
+ function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
1827
+ const fromQuote = normalizeAddress(quoteEscrow);
1828
+ const fromChains = normalizeAddress(chainsEscrow);
1829
+ if (!fromChains || fromChains === ZERO_ADDRESS) {
1830
+ throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
1831
+ }
1832
+ if (!fromQuote || fromQuote === ZERO_ADDRESS) {
1833
+ throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
1834
+ }
1835
+ if (fromQuote !== fromChains) {
1836
+ throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
1837
+ }
1838
+ const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
1839
+ if (pinned && pinned !== fromChains) {
1840
+ throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
1841
+ }
1842
+ return fromChains;
1843
+ }
1844
+ function isLayerZeroRoute(quote, option = {}) {
1845
+ const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
1846
+ return bridge.includes("layerzero") || bridge.includes("layer zero");
1847
+ }
1848
+ function sourceAssetKey(quote, option = {}) {
1849
+ return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
1850
+ }
1851
+ function requiresNativeBridgeFee(quote, option = {}) {
1852
+ const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
1853
+ const execChainId = Number(quote?.executionChainId);
1854
+ if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
1855
+ return false;
1856
+ }
1857
+ const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
1858
+ if (canonical) return canonical === "layerzero";
1859
+ return isLayerZeroRoute(quote, option);
1860
+ }
1861
+ function applyLayerZeroBuffer(quote, option = {}) {
1862
+ const gas = BigInt(quote?.gasCostSource || "0");
1863
+ if (gas <= 0n) return 0n;
1864
+ if (!requiresNativeBridgeFee(quote, option)) return 0n;
1865
+ return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
1866
+ }
1867
+
726
1868
  // src/core/native-fee.ts
727
1869
  function routeNativeValue(route) {
728
1870
  try {
729
- const raw = route?.quote?.msgValue;
730
- if (raw === void 0 || raw === null || raw === "") return 0n;
731
- const value = BigInt(raw);
1871
+ const raw2 = route?.quote?.msgValue;
1872
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
1873
+ const value = BigInt(raw2);
732
1874
  return value > 0n ? value : 0n;
733
1875
  } catch {
734
1876
  return 0n;
@@ -763,6 +1905,11 @@ function nativeFeeShortMessage(check, symbol, chainName) {
763
1905
  }
764
1906
 
765
1907
  // src/core/route-health.ts
1908
+ function healthLaneKey(value) {
1909
+ if (typeof value !== "string") return "";
1910
+ const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
1911
+ return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
1912
+ }
766
1913
  var EMPTY = /* @__PURE__ */ new Map();
767
1914
  var NO_LIMITS = /* @__PURE__ */ new Map();
768
1915
  function laneAvailabilityState(lane) {
@@ -782,7 +1929,7 @@ function suppressedLanes(health) {
782
1929
  const out = /* @__PURE__ */ new Map();
783
1930
  for (const lane of health.lanes) {
784
1931
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
785
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
1932
+ const key = healthLaneKey(lane.laneKey);
786
1933
  if (!key) continue;
787
1934
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
788
1935
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
@@ -802,7 +1949,7 @@ function limitedLanes(health) {
802
1949
  const out = /* @__PURE__ */ new Map();
803
1950
  for (const lane of health.lanes) {
804
1951
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
805
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
1952
+ const key = healthLaneKey(lane.laneKey);
806
1953
  const limit = lane.availability?.limit;
807
1954
  if (!key || !limit || typeof limit !== "object") continue;
808
1955
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
@@ -825,14 +1972,14 @@ function limitedLanes(health) {
825
1972
  }
826
1973
  function exceedsLaneLimit(limit, amount, bidDecimals) {
827
1974
  if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
828
- let raw;
1975
+ let raw2;
829
1976
  try {
830
- raw = parseUnitsDecimal(amount, bidDecimals);
1977
+ raw2 = parseUnitsDecimal(amount, bidDecimals);
831
1978
  } catch {
832
1979
  return false;
833
1980
  }
834
1981
  const scale = Math.max(bidDecimals, limit.decimals);
835
- return scaleDecimals(raw, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
1982
+ return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
836
1983
  }
837
1984
  function laneLimitAmount(limit) {
838
1985
  return formatUnits(limit.maxAmount, limit.decimals);
@@ -929,11 +2076,11 @@ function complianceView(compliance, hasQuote = true) {
929
2076
  };
930
2077
  }
931
2078
  if (decision === "REVIEW" || decision === "REMEDIATE") {
932
- const word = decision.toLowerCase();
2079
+ const word2 = decision.toLowerCase();
933
2080
  return {
934
2081
  tone: "warn",
935
- label: `Compliance: ${word} required`,
936
- headline: `Manual ${word} required`,
2082
+ label: `Compliance: ${word2} required`,
2083
+ headline: `Manual ${word2} required`,
937
2084
  blocked: false,
938
2085
  needsAction: true,
939
2086
  screened
@@ -998,12 +2145,12 @@ function stripBundlePrefix(head) {
998
2145
  if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
999
2146
  return { head, source: null };
1000
2147
  }
1001
- function complianceReasonHead(raw) {
1002
- return stripBundlePrefix((raw.split(":")[0] ?? "").trim()).head;
2148
+ function complianceReasonHead(raw2) {
2149
+ return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
1003
2150
  }
1004
- function usd(raw) {
1005
- const n = Number(raw);
1006
- if (!Number.isFinite(n)) return `$${raw}`;
2151
+ function usd(raw2) {
2152
+ const n = Number(raw2);
2153
+ if (!Number.isFinite(n)) return `$${raw2}`;
1007
2154
  return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
1008
2155
  }
1009
2156
  function capFromDetail(detail) {
@@ -1014,8 +2161,8 @@ function categoryPhrase(detail) {
1014
2161
  const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
1015
2162
  return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
1016
2163
  }
1017
- function humanizeComplianceReason(raw) {
1018
- const [headRaw, ...restParts] = raw.split(":");
2164
+ function humanizeComplianceReason(raw2) {
2165
+ const [headRaw, ...restParts] = raw2.split(":");
1019
2166
  const detail = restParts.join(":").trim();
1020
2167
  const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
1021
2168
  const scope = source === "legislation" ? "applicable regulations" : "the applicable policy";
@@ -1092,8 +2239,8 @@ var CHECK_HEADS = {
1092
2239
  function distinctScreenedWallets(compliance) {
1093
2240
  const seen = /* @__PURE__ */ new Set();
1094
2241
  const wallets = [];
1095
- for (const raw of compliance?.screenedWallets ?? []) {
1096
- const address = raw?.trim();
2242
+ for (const raw2 of compliance?.screenedWallets ?? []) {
2243
+ const address = raw2?.trim();
1097
2244
  if (!address) continue;
1098
2245
  const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
1099
2246
  if (seen.has(key)) continue;
@@ -1113,11 +2260,11 @@ function screeningLabel(wallets) {
1113
2260
  function complianceChecks(compliance, cv = complianceView(compliance)) {
1114
2261
  if (cv.tone === "neutral") return [];
1115
2262
  const byControl = /* @__PURE__ */ new Map();
1116
- for (const raw of compliance?.reasons ?? []) {
1117
- const head = complianceReasonHead(raw);
2263
+ for (const raw2 of compliance?.reasons ?? []) {
2264
+ const head = complianceReasonHead(raw2);
1118
2265
  const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
1119
2266
  if (!id) continue;
1120
- byControl.set(id, [...byControl.get(id) ?? [], raw]);
2267
+ byControl.set(id, [...byControl.get(id) ?? [], raw2]);
1121
2268
  }
1122
2269
  const screenedWallets = distinctScreenedWallets(compliance);
1123
2270
  const wallets = screenedWallets.length;
@@ -1141,8 +2288,8 @@ function complianceControlsEvaluated(compliance, cv = complianceView(compliance)
1141
2288
  const checks = complianceChecks(compliance, cv);
1142
2289
  if (checks.length === 0) return 0;
1143
2290
  const named = /* @__PURE__ */ new Set();
1144
- for (const raw of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
1145
- const name = raw?.trim();
2291
+ for (const raw2 of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
2292
+ const name = raw2?.trim();
1146
2293
  if (name) named.add(name.toLowerCase());
1147
2294
  }
1148
2295
  return checks.length + named.size;
@@ -1182,8 +2329,8 @@ var BLOCK_CATEGORY_LABELS = {
1182
2329
  };
1183
2330
  var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
1184
2331
  function blockLabelFor(categories) {
1185
- for (const raw of categories) {
1186
- const label = BLOCK_CATEGORY_LABELS[String(raw || "").trim().toUpperCase()];
2332
+ for (const raw2 of categories) {
2333
+ const label = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
1187
2334
  if (label) return label;
1188
2335
  }
1189
2336
  return BLOCK_LABEL_DEFAULT;
@@ -1204,8 +2351,8 @@ var REASON_TAGS = {
1204
2351
  dest_chain_not_allowed: "Chain not allowed",
1205
2352
  jurisdiction_out_of_scope: "Out of scope"
1206
2353
  };
1207
- function complianceReasonTag(raw) {
1208
- const head = complianceReasonHead(raw);
2354
+ function complianceReasonTag(raw2) {
2355
+ const head = complianceReasonHead(raw2);
1209
2356
  return REASON_TAGS[head] ?? head.replace(/_/g, " ");
1210
2357
  }
1211
2358
  function complianceTagOf(compliance) {
@@ -1268,8 +2415,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1268
2415
  const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
1269
2416
  const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
1270
2417
  const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
1271
- const enforcePayCeiling = (raw) => {
1272
- if (maxPayRaw > 0n && BigInt(raw) > maxPayRaw) {
2418
+ const enforcePayCeiling = (raw2) => {
2419
+ if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
1273
2420
  throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
1274
2421
  }
1275
2422
  };
@@ -1293,7 +2440,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1293
2440
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
1294
2441
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1295
2442
  }
1296
- const guaranteed = BigInt(quote?.toAmount || "0");
2443
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1297
2444
  const final = finalOf(quote);
1298
2445
  if (final > bestFinal) {
1299
2446
  bestFinal = final;
@@ -1330,7 +2477,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1330
2477
  directTransfer: false,
1331
2478
  quote: best,
1332
2479
  youPayRaw: bestGuess.toString(),
1333
- recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
2480
+ recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
1334
2481
  targetRaw: targetRaw.toString(),
1335
2482
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
1336
2483
  meetsTarget: bestFinal >= targetRaw,
@@ -1352,7 +2499,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
1352
2499
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
1353
2500
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1354
2501
  }
1355
- const guaranteed = BigInt(quote?.toAmount || "0");
2502
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1356
2503
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
1357
2504
  return {
1358
2505
  directTransfer: false,
@@ -1383,13 +2530,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
1383
2530
  const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
1384
2531
  const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
1385
2532
  if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
2533
+ const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
2534
+ const keyBytes2 = (value, label) => {
2535
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label} is not a valid 32-byte Solana key.`);
2536
+ return String(value).toLowerCase();
2537
+ };
1386
2538
  return {
1387
2539
  owner: assertAddress(order.owner || payer, "Order owner"),
1388
2540
  bidToken: assertAddress(order.bidToken, "Bid token"),
1389
2541
  bidTokenAmount: String(order.bidTokenAmount || "0"),
1390
- askToken: assertAddress(order.askToken, "Ask token"),
2542
+ askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
1391
2543
  askTokenAmount: String(order.askTokenAmount || "0"),
1392
- destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
2544
+ destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
2545
+ ...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
1393
2546
  destinationChainId: String(order.destinationChainId || destination.chainId),
1394
2547
  executionChainId,
1395
2548
  deadline
@@ -1401,17 +2554,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
1401
2554
  (request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
1402
2555
  );
1403
2556
  }
1404
- function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
2557
+ function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
1405
2558
  const list = orders?.length ? orders : [order];
1406
2559
  const sourceOrder = list[0];
1407
2560
  const finalOrder = list[list.length - 1];
1408
2561
  const now = Math.floor(Date.now() / 1e3);
1409
2562
  const deadline = Number(sourceOrder.deadline || 0);
2563
+ const solana = isSolanaChainId(destination.chainId);
2564
+ if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
2565
+ throw new Error("This Solana token is not supported for delivery; refusing to sign.");
2566
+ }
1410
2567
  for (const current of list) {
1411
2568
  if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
1412
2569
  throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
1413
2570
  }
1414
- if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(destination.address)) {
2571
+ if (isSolanaChainId(current.destinationChainId)) {
2572
+ if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
2573
+ checkSolanaReceiver(current, destination.address, destinationToken.address);
2574
+ } else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
1415
2575
  throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
1416
2576
  }
1417
2577
  if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
@@ -1421,9 +2581,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1421
2581
  if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
1422
2582
  throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
1423
2583
  }
1424
- if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
2584
+ if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
1425
2585
  throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
1426
2586
  }
2587
+ 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.");
1427
2588
  if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
1428
2589
  throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
1429
2590
  }
@@ -1442,10 +2603,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1442
2603
  if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
1443
2604
  throw new Error("ZeroDelta quote returned a non-positive output amount.");
1444
2605
  }
1445
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
2606
+ const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
2607
+ const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
2608
+ if (!covers(result.targetRaw)) {
1446
2609
  throw new Error("ZeroDelta quote would not cover the requested destination amount.");
1447
2610
  }
1448
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
2611
+ if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
1449
2612
  throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
1450
2613
  }
1451
2614
  const maxDeadline = maxDeadlineSeconds(quote);
@@ -1477,8 +2640,8 @@ function routeDeltaLabel(result, quote) {
1477
2640
  return "~0";
1478
2641
  }
1479
2642
  function quotePartnerId(quote) {
1480
- const raw = quote.partnerId;
1481
- return typeof raw === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw) ? raw.toLowerCase() : NO_PARTNER_ID;
2643
+ const raw2 = quote.partnerId;
2644
+ return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
1482
2645
  }
1483
2646
  function optionTicker(option) {
1484
2647
  return option.ticker || option.symbol;
@@ -1488,15 +2651,16 @@ function routeLabelFor(option, destinationToken, result) {
1488
2651
  const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
1489
2652
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
1490
2653
  }
1491
- function tokenAt(tokens, chainId, address) {
1492
- const wanted = normalizeAddress(address);
2654
+ function tokenAt2(tokens, chainId, address) {
2655
+ const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
2656
+ const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
1493
2657
  if (!wanted || !tokens?.length) return void 0;
1494
- return tokens.find((t) => Number(t.chainId) === Number(chainId) && normalizeAddress(t.address) === wanted);
2658
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
1495
2659
  }
1496
- function legAmount(raw, decimals) {
2660
+ function legAmount(raw2, decimals) {
1497
2661
  if (decimals === void 0) return "";
1498
2662
  try {
1499
- return formatUnits(raw || "0", decimals);
2663
+ return formatUnits(raw2 || "0", decimals);
1500
2664
  } catch {
1501
2665
  return "";
1502
2666
  }
@@ -1511,7 +2675,7 @@ function buildLegs(orders, ctx) {
1511
2675
  const order = orders[index];
1512
2676
  const isLast = index === orders.length - 1;
1513
2677
  const toChainId = Number(order.destinationChainId);
1514
- const askToken = isLast ? ctx.destinationToken : tokenAt(ctx.tokens, toChainId, order.askToken);
2678
+ const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
1515
2679
  const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
1516
2680
  const toTicker = askToken ? tokenTicker(askToken) : "";
1517
2681
  const toDecimals = askToken ? assetDecimals(askToken) : void 0;
@@ -1527,7 +2691,7 @@ function buildLegs(orders, ctx) {
1527
2691
  toTicker,
1528
2692
  toChainId,
1529
2693
  toChainName: chainNameOf(toChainId, ctx.chains),
1530
- toAmount: legAmount(order.askTokenAmount, toDecimals),
2694
+ toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
1531
2695
  executionChainId,
1532
2696
  executionChainName: chainNameOf(executionChainId, ctx.chains)
1533
2697
  });
@@ -1631,8 +2795,12 @@ async function buildRoute({
1631
2795
  const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
1632
2796
  const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
1633
2797
  const order = orders[0];
1634
- assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
1635
- const needsNativeFee = requiresNativeBridgeFee(quote, option);
2798
+ assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
2799
+ const echoedExecution = Number(quote.executionChainId || 0);
2800
+ if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
2801
+ throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
2802
+ }
2803
+ const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
1636
2804
  if (needsNativeFee) {
1637
2805
  let rawFee;
1638
2806
  try {
@@ -1676,7 +2844,7 @@ async function buildRoute({
1676
2844
  },
1677
2845
  routeLabel: routeLabelFor(option, destinationToken, result),
1678
2846
  deltaLabel: routeDeltaLabel(result, quote),
1679
- legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
2847
+ legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
1680
2848
  transactions: [
1681
2849
  {
1682
2850
  id: "approve",
@@ -1709,6 +2877,7 @@ async function buildRoute({
1709
2877
  gasCostSource: quote.gasCostSource,
1710
2878
  msgValue: valueRaw.toString(),
1711
2879
  deadline: order.deadline,
2880
+ ...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
1712
2881
  partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
1713
2882
  iterations: result.iterations,
1714
2883
  // Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
@@ -1724,10 +2893,10 @@ var CHANNEL_HEADER = "x-zd-channel";
1724
2893
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
1725
2894
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
1726
2895
  var WIDGET_CHANNEL = "widget";
1727
- var WIDGET_VERSION = "4.12.0" ;
2896
+ var WIDGET_VERSION = "4.13.1" ;
1728
2897
  var MAX_CHANNEL_VERSION_LEN = 32;
1729
- function sanitizeVersion(raw) {
1730
- const v = String(raw).trim();
2898
+ function sanitizeVersion(raw2) {
2899
+ const v = String(raw2).trim();
1731
2900
  if (!v) return "";
1732
2901
  const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
1733
2902
  return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
@@ -1930,9 +3099,9 @@ function createApiClient(cfg) {
1930
3099
  if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
1931
3100
  return once("chains", async () => {
1932
3101
  const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
1933
- const normalized = (Array.isArray(chains) ? chains : []).map((chain) => ({ ...chain, chainId: Number(chain.chainId) })).map((chain) => {
1934
- const escrow = normalizeAddress(chain.escrowContract);
1935
- return escrow ? { ...chain, escrowContract: escrow } : { ...chain, escrowContract: void 0 };
3102
+ const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
3103
+ const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
3104
+ return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
1936
3105
  });
1937
3106
  cache.chains = { at: Date.now(), value: normalized };
1938
3107
  return normalized;
@@ -2035,14 +3204,16 @@ function createApiClient(cfg) {
2035
3204
  async function screenWallet(address, chainId) {
2036
3205
  const addr = String(address || "").trim();
2037
3206
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
2038
- const key = `${/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr}|${chainId ?? ""}`;
3207
+ const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3208
+ if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3209
+ const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
2039
3210
  const hit = screenCache.get(key);
2040
3211
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
2041
3212
  const inflight = screenInflight.get(key);
2042
3213
  if (inflight) return inflight;
2043
3214
  const request = apiRequest("/screen/wallet", {
2044
3215
  method: "POST",
2045
- body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
3216
+ body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
2046
3217
  timeoutMs: 12e3
2047
3218
  }).then((screen) => {
2048
3219
  if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
@@ -2082,7 +3253,7 @@ function createApiClient(cfg) {
2082
3253
 
2083
3254
  // src/core/plan.ts
2084
3255
  function optionBalanceKey(option) {
2085
- return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
3256
+ return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
2086
3257
  }
2087
3258
  function hasPositiveBalance(option, balances) {
2088
3259
  try {
@@ -2092,7 +3263,8 @@ function hasPositiveBalance(option, balances) {
2092
3263
  }
2093
3264
  }
2094
3265
  function validateDestination(destination) {
2095
- assertAddress(destination.address, "Destination address");
3266
+ const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
3267
+ if (isSolanaChainId(destination.chainId)) destination.address = address;
2096
3268
  const chainId = Number(destination.chainId);
2097
3269
  const asset = symbolKey(destination.asset);
2098
3270
  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
@@ -2150,8 +3322,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
2150
3322
  if (directOptions.length) {
2151
3323
  const parties = [];
2152
3324
  const seenParty = /* @__PURE__ */ new Set();
2153
- for (const raw of [payer, destination.address]) {
2154
- const addr = String(raw || "").trim();
3325
+ for (const raw2 of [payer, destination.address]) {
3326
+ const addr = String(raw2 || "").trim();
2155
3327
  if (!addr) continue;
2156
3328
  const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
2157
3329
  if (seenParty.has(key)) continue;
@@ -2259,7 +3431,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
2259
3431
  if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
2260
3432
  const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
2261
3433
  const option = buildPayOptions({ invoiceAsset: destination.asset, invoiceChainId: destination.chainId, tokens, routes, chains, walletChainId: wallet.chainId, catalogue }).find(
2262
- (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && o.address.toLowerCase() === String(picked.address).toLowerCase() && (!allowedFunding || allowedFunding.has(o.symbolKey))
3434
+ (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
2263
3435
  );
2264
3436
  if (!option) throw new Error("That funding option is not available for this payment right now.");
2265
3437
  return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
@@ -2282,8 +3454,10 @@ function viaOf(quote, tokens) {
2282
3454
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
2283
3455
  if (orders.length < 2) return null;
2284
3456
  const first = orders[0];
2285
- const wanted = normalizeAddress(first?.askToken);
2286
- const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && normalizeAddress(t.address) === wanted) : void 0;
3457
+ const chainId = Number(first?.destinationChainId);
3458
+ const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
3459
+ const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
3460
+ const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
2287
3461
  return token ? tokenTicker(token) : "";
2288
3462
  }
2289
3463
  async function quoteSwapPreview(api, swap, owner) {
@@ -2295,7 +3469,7 @@ async function quoteSwapPreview(api, swap, owner) {
2295
3469
  if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
2296
3470
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2297
3471
  const account = normalizeAddress(owner) || PREVIEW_OWNER;
2298
- const previewReceiver = normalizeAddress(swap.recipient) || account;
3472
+ const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
2299
3473
  const quote = await api.fetchQuote({
2300
3474
  fromChainId: v.fromChainId,
2301
3475
  toChainId: v.toChainId,
@@ -2303,7 +3477,7 @@ async function quoteSwapPreview(api, swap, owner) {
2303
3477
  toToken: destToken.symbol,
2304
3478
  fromAmount: amountInRaw.toString(),
2305
3479
  owner: account,
2306
- destinationReceiver: previewReceiver
3480
+ ...previewReceiver ? { destinationReceiver: previewReceiver } : {}
2307
3481
  });
2308
3482
  const final = finalOf(quote);
2309
3483
  return {
@@ -2328,7 +3502,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
2328
3502
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
2329
3503
  if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
2330
3504
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2331
- const receiver = resolveSwapReceiver(swap.recipient, account);
3505
+ const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
2332
3506
  const option = {
2333
3507
  symbol: sourceToken.symbol,
2334
3508
  symbolKey: symbolKey(sourceToken.symbol),
@@ -2378,16 +3552,16 @@ function isHexQuantity(value) {
2378
3552
  return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
2379
3553
  }
2380
3554
  function dataWord(data, index) {
2381
- const word = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
2382
- return /^[a-fA-F0-9]{64}$/.test(word) ? word : "";
3555
+ const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
3556
+ return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
2383
3557
  }
2384
3558
  function dataAddress(data, index) {
2385
- const word = dataWord(data, index);
2386
- return word ? `0x${word.slice(24)}` : "";
3559
+ const word2 = dataWord(data, index);
3560
+ return word2 ? `0x${word2.slice(24)}` : "";
2387
3561
  }
2388
3562
  function dataUint(data, index) {
2389
- const word = dataWord(data, index);
2390
- return word ? BigInt(`0x${word}`) : null;
3563
+ const word2 = dataWord(data, index);
3564
+ return word2 ? BigInt(`0x${word2}`) : null;
2391
3565
  }
2392
3566
  function rawEquals(value, expected) {
2393
3567
  try {
@@ -2398,9 +3572,9 @@ function rawEquals(value, expected) {
2398
3572
  }
2399
3573
  function planMsgValueHex(route) {
2400
3574
  try {
2401
- const raw = route?.quote?.msgValue;
2402
- if (raw === void 0 || raw === null || raw === "") return "0x0";
2403
- return "0x" + BigInt(raw).toString(16);
3575
+ const raw2 = route?.quote?.msgValue;
3576
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
3577
+ return "0x" + BigInt(raw2).toString(16);
2404
3578
  } catch {
2405
3579
  return null;
2406
3580
  }
@@ -2427,15 +3601,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
2427
3601
  if (!decoded) return false;
2428
3602
  const first = decoded.orders[0];
2429
3603
  const last = decoded.orders[decoded.orders.length - 1];
2430
- 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);
3604
+ 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));
2431
3605
  }
2432
3606
  return false;
2433
3607
  }
3608
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
3609
+ try {
3610
+ return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
3611
+ } catch {
3612
+ return false;
3613
+ }
3614
+ }
2434
3615
  async function allowanceCovers(tx, account, ethCall) {
2435
3616
  if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
2436
3617
  try {
2437
- const raw = await ethCall(tx.token, encodeAllowance(account, tx.spender));
2438
- return BigInt(raw || "0x0") >= BigInt(tx.amountRaw || "0");
3618
+ const raw2 = await ethCall(tx.token, encodeAllowance(account, tx.spender));
3619
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
2439
3620
  } catch {
2440
3621
  return false;
2441
3622
  }
@@ -2473,8 +3654,13 @@ var stableGenieIntentSchema = {
2473
3654
  type: "object",
2474
3655
  additionalProperties: false,
2475
3656
  required: ["address", "chainId", "asset", "amount"],
3657
+ // The engine performs the decoded 32-byte check; the schema filters the address alphabet.
3658
+ oneOf: [
3659
+ { properties: { chainId: { const: SOLANA_CHAIN_ID }, address: { pattern: "^[1-9A-HJ-NP-Za-km-z]{32,44}$" } } },
3660
+ { properties: { chainId: { not: { const: SOLANA_CHAIN_ID } }, address: { pattern: "^0x[a-fA-F0-9]{40}$" } } }
3661
+ ],
2476
3662
  properties: {
2477
- address: { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" },
3663
+ address: { type: "string" },
2478
3664
  // A DESTINATION chain, so it is bounded by shape, not by the escrow-chain list: a payment may
2479
3665
  // be delivered on any chain the gateway publishes a route to (~31 of them), while only the
2480
3666
  // nine escrow chains can SEND one. See validateDestination in plan.ts.
@@ -2501,9 +3687,9 @@ var TX_VERIFY_ATTEMPTS = 5;
2501
3687
  var TX_VERIFY_INTERVAL_MS = 2500;
2502
3688
  var TX_VERIFY_FETCH_MS = 5e3;
2503
3689
  var TX_VERIFY_DEADLINE_MS = 18e3;
2504
- function registryRpc(chain) {
2505
- if (!chain) return "";
2506
- const candidates = [chain.rpcUrl, Array.isArray(chain.rpcUrls) ? chain.rpcUrls[0] : null, chain.publicRpcUrl, chain.rpc, chain.rpcEndpoint];
3690
+ function registryRpc(chain2) {
3691
+ if (!chain2) return "";
3692
+ const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
2507
3693
  const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
2508
3694
  return found || "";
2509
3695
  }
@@ -2650,9 +3836,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2650
3836
  }
2651
3837
  function record(target, hex) {
2652
3838
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
2653
- const raw = BigInt(hex || "0x0").toString();
3839
+ const raw2 = BigInt(hex || "0x0").toString();
2654
3840
  const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
2655
- out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
3841
+ out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
2656
3842
  return true;
2657
3843
  }
2658
3844
  async function readOne(rpcUrl, target) {
@@ -2718,9 +3904,9 @@ function isSameOriginPath(value) {
2718
3904
  return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
2719
3905
  }
2720
3906
  function resolveApiBase(value) {
2721
- const raw = value ?? DEFAULT_WIDGET_API_BASE;
2722
- if (isSameOriginPath(raw)) return raw.replace(/\/+$/, "") || "/";
2723
- return parseAllowedApiBase(raw) || DEFAULT_WIDGET_API_BASE;
3907
+ const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
3908
+ if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
3909
+ return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
2724
3910
  }
2725
3911
  function canAttachApiKey(apiBase, trustedOrigin) {
2726
3912
  if (isSameOriginPath(apiBase)) return true;
@@ -2759,31 +3945,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
2759
3945
  }
2760
3946
 
2761
3947
  // src/core/index.ts
3948
+ var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
2762
3949
  function sanitizeLegs(legs) {
2763
3950
  if (!Array.isArray(legs) || !legs.length) return void 0;
2764
3951
  const text = (v, max) => String(v ?? "").slice(0, max);
2765
- const chain = (v) => Number(v) || 0;
3952
+ const chain2 = (v) => Number(v) || 0;
2766
3953
  const ticker = (value, asset) => safeTicker(value, asset) || void 0;
2767
3954
  return legs.slice(0, 8).map((leg, i) => ({
2768
3955
  index: Number(leg?.index) || i + 1,
2769
3956
  fromAsset: text(leg?.fromAsset, 12),
2770
3957
  fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
2771
- fromChainId: chain(leg?.fromChainId),
3958
+ fromChainId: chain2(leg?.fromChainId),
2772
3959
  fromChainName: text(leg?.fromChainName, 40),
2773
3960
  fromAmount: text(leg?.fromAmount, 40),
2774
3961
  toAsset: text(leg?.toAsset, 12),
2775
3962
  toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
2776
- toChainId: chain(leg?.toChainId),
3963
+ toChainId: chain2(leg?.toChainId),
2777
3964
  toChainName: text(leg?.toChainName, 40),
2778
3965
  toAmount: text(leg?.toAmount, 40),
2779
- executionChainId: chain(leg?.executionChainId),
3966
+ executionChainId: chain2(leg?.executionChainId),
2780
3967
  executionChainName: text(leg?.executionChainName, 40)
2781
3968
  }));
2782
3969
  }
2783
3970
  function sanitizeTxEntry(entry) {
2784
3971
  return {
2785
3972
  kind: entry.kind === "swap" ? "swap" : "payment",
2786
- hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
3973
+ // A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
3974
+ 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) : "",
2787
3975
  txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
2788
3976
  chainId: Number(entry.chainId) || null,
2789
3977
  chainName: String(entry.chainName || "").slice(0, 40),
@@ -2794,7 +3982,7 @@ function sanitizeTxEntry(entry) {
2794
3982
  payAmount: String(entry.payAmount || "").slice(0, 40),
2795
3983
  receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
2796
3984
  account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
2797
- recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
3985
+ recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
2798
3986
  settlement: entry.settlement === "direct" ? "direct" : "escrow",
2799
3987
  status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
2800
3988
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2805,6 +3993,7 @@ function createEngine(config = {}) {
2805
3993
  const resolved = resolveConfig(config);
2806
3994
  const api = createApiClient(resolved);
2807
3995
  const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
3996
+ const solanaRpc = createSolanaRpc(api);
2808
3997
  return {
2809
3998
  api,
2810
3999
  verifier,
@@ -2815,7 +4004,7 @@ function createEngine(config = {}) {
2815
4004
  fetchRouteHealth: api.fetchRouteHealth,
2816
4005
  fetchQuote: api.fetchQuote,
2817
4006
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
2818
- fetchCatalogue: async (allowedAssets, product) => {
4007
+ fetchCatalogue: async (allowedAssets, product, options) => {
2819
4008
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
2820
4009
  api.fetchChains().catch(() => []),
2821
4010
  api.fetchTokens().catch(() => []),
@@ -2832,7 +4021,9 @@ function createEngine(config = {}) {
2832
4021
  routes,
2833
4022
  product,
2834
4023
  ...allowed ? { allowedAssets: allowed } : {},
2835
- supportedChainIds: SUPPORTED_CHAIN_IDS,
4024
+ // Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
4025
+ // Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
4026
+ supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
2836
4027
  brokenLanes: suppressedLanes(health),
2837
4028
  // Same read, same degraded mode: a null health response limits nothing.
2838
4029
  limitedLanes: limitedLanes(health),
@@ -2843,6 +4034,15 @@ function createEngine(config = {}) {
2843
4034
  quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
2844
4035
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
2845
4036
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
4037
+ quoteSolanaSource: (input) => quoteSolanaSource(api, input),
4038
+ buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
4039
+ executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
4040
+ executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
4041
+ previewSolanaSource: (input) => previewSolanaSource(api, input),
4042
+ trackDelivery: (hash) => fetchDelivery(api, hash),
4043
+ fetchWalletHistory: (wallets) => fetchWalletHistory(api, wallets),
4044
+ readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
4045
+ simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
2846
4046
  payerNonceBaseline: verifier.payerNonceBaseline,
2847
4047
  verifySubmittedTx: verifier.verifySubmittedTx,
2848
4048
  readBalances: verifier.readBalances,
@@ -2859,4 +4059,4 @@ function createEngine(config = {}) {
2859
4059
  };
2860
4060
  }
2861
4061
 
2862
- export { API_CACHE_TTL_MS, BLOCK_LABEL_DEFAULT, BUNDLED_NATIVE_SYMBOL, BUNDLED_RPC, CANONICAL_DECIMALS, CANONICAL_ESCROW, CANONICAL_INBOUND_BRIDGE, CHAIN_DISPLAY_NAMES, COMPLIANCE_CHECK_ORDER, COMPLIANCE_DENY_LABEL, DEFAULT_WIDGET_API_BASE, DIRECT_CHECK_IDS, DIRECT_SCOPE_NOTE, ERC20_ALLOWANCE_SELECTOR, ERC20_APPROVE_SELECTOR, ERC20_BALANCEOF_SELECTOR, ERC20_TRANSFER_SELECTOR, EXECUTABLE_STABLE_ASSETS, FLOOR_CATEGORIES, LZ_FEE_BUFFER_BPS, MAX_LZ_MSG_VALUE_WEI, MAX_LZ_MSG_VALUE_WEI_BY_CHAIN, MAX_QUOTE_CANDIDATES, MAX_SAME_CLASS_PAY_BPS, MAX_UINT64, NO_PARTNER_ID, PREVIEW_OWNER, QUOTE_BUFFER_BPS, SAME_CLASS_STABLE, SCREENING_BUCKETS, SCREEN_CACHE_TTL_MS, STABLEGENIE_INTENT_TTL_MS, STABLEGENIE_INTENT_VERSION, STABLEGENIE_SUPPORTED_ASSETS, STABLEGENIE_SUPPORTED_CHAIN_IDS, STABLE_ASSETS, SUBMIT_ORDER_SELECTOR, SUPPORTED_ASSETS, SUPPORTED_CHAIN_IDS, TRADEABLE_RWA_ASSETS, TUNABLE_CATEGORIES, ZERO_ADDRESS, addressWord, allowanceCovers, amountFieldError, apiError, applyLayerZeroBuffer, assertAddress, assertQuoteMatchesSelection, assetClassOf, assetDecimals, blockLabelFor, brokenLaneFor, brokenLaneReason, buildCatalogue, buildPayOptions, buildRoute, buildSwapPlan, bytes32Word, bytesPayload, canAttachApiKey, categoryLabel, chainById, chainNameOf, chainSelectable, checkEscrow, checkNativeFee, classifyQuoteError, complianceChecks, complianceControlsEvaluated, complianceControlsLine, complianceReasonHead, complianceReasonTag, complianceTagOf, complianceView, counterpartTokens, createApiClient, createEngine, createVerifier, decodeSubmitOrderCalldata, destinationAvailability, destinationKeys, directComplianceFromScreens, distinctScreenedWallets, encodeAllowance, encodeApprove, encodeBalanceOf, encodeSubmitOrder, encodeTransfer, exceedsLaneLimit, executableRoutes, executionChainIds, fetchPaymentPlan, finalOf, findToken, foldTicker, formatJurisdiction, formatNative, formatUnits, hasReachableDestination, hubDeliverableSymbols, humanizeComplianceReason, isAddress, isDeliverable, isExecutableBridge, isHexAddress, isHexData, isHexQuantity, isKnownUnbridgeable, isLayerZeroRoute, isSourceToken, laneAvailabilityState, laneKey, laneKeys, laneLimitAmount, laneLimitError, laneLimitFor, laneLimitHint, laneLimitSymbol, limitedLanes, maxDeadlineSeconds, maxNativeFeeWei, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, normalizeOrderRequest, normalizeOrderRequests, parseAllowedApiBase, parseUnitsDecimal, planErrorSummary, planMsgValueHex, productAssets, quotePartnerId, quotePayOption, quoteSwapPreview, recommendedDeadlineSeconds, registryRpc, requiresNativeBridgeFee, resolveApiBase, resolveConfig, resolveSwapReceiver, resolveVaultIcon, routeNativeValue, safeTicker, scaleDecimals, screeningOutcomeOf, solveExactIn, solveExactOut, sourceKeys, stableGenieIntentSchema, strip0x, suppressedLanes, symbolKey, tickerOn, toHexQuantity, tokenEnabled, tokenKey, tokenTicker, txMatchesPlan, uint64Word, uintWord, unattributedComplianceReasons, validateDestination, validatePlannedTransaction, validateSwap, vaultIconsBySymbol, withVaultArtwork };
4062
+ export { API_CACHE_TTL_MS, BLOCK_LABEL_DEFAULT, BUNDLED_NATIVE_SYMBOL, BUNDLED_RPC, CANONICAL_DECIMALS, CANONICAL_ESCROW, CANONICAL_INBOUND_BRIDGE, CANONICAL_SOLANA_PROGRAM, CHAIN_DISPLAY_NAMES, COMPLIANCE_CHECK_ORDER, COMPLIANCE_DENY_LABEL, DEFAULT_WIDGET_API_BASE, DIRECT_CHECK_IDS, DIRECT_SCOPE_NOTE, ERC20_ALLOWANCE_SELECTOR, ERC20_APPROVE_SELECTOR, ERC20_BALANCEOF_SELECTOR, ERC20_TRANSFER_SELECTOR, EXECUTABLE_STABLE_ASSETS, FLOOR_CATEGORIES, LZ_FEE_BUFFER_BPS, MAX_LZ_MSG_VALUE_WEI, MAX_LZ_MSG_VALUE_WEI_BY_CHAIN, MAX_QUOTE_CANDIDATES, MAX_SAME_CLASS_PAY_BPS, MAX_UINT64, NO_PARTNER_ID, PREVIEW_OWNER, QUOTE_BUFFER_BPS, SAME_CLASS_STABLE, SCREENING_BUCKETS, SCREEN_CACHE_TTL_MS, SOLANA_CHAIN_ID, SOLANA_DESTINATION_ASSETS, SOL_SHORTFALL_MESSAGE, STABLEGENIE_INTENT_TTL_MS, STABLEGENIE_INTENT_VERSION, STABLEGENIE_SUPPORTED_ASSETS, STABLEGENIE_SUPPORTED_CHAIN_IDS, STABLE_ASSETS, SUBMIT_ORDER_DISCRIMINATOR, SUBMIT_ORDER_SELECTOR, SUPPORTED_ASSETS, SUPPORTED_CHAIN_IDS, SolanaSendError, TRACKING, TRADEABLE_RWA_ASSETS, TUNABLE_CATEGORIES, WALLET_HISTORY_LIMIT, ZERO_ADDRESS, addressWord, allowanceCovers, amountFieldError, apiError, applyLayerZeroBuffer, askCovers, askTokenDecimals, assertAddress, assertChainAddress, assertQuoteMatchesSelection, assertWalletMessage, assetClassOf, assetDecimals, associatedTokenAddress, base58Decode, base58Encode, base64Decode, base64Encode, blockLabelFor, brokenLaneFor, brokenLaneReason, buildCatalogue, buildPayOptions, buildRoute, buildSolanaSourcePlan, buildSwapPlan, bytes32Word, bytesEqual, bytesPayload, canAttachApiKey, categoryLabel, chainAddressKey, chainById, chainNameOf, chainSelectable, checkEscrow, checkNativeFee, checkSolanaPlan, checkSolanaProgram, checkSolanaReceiver, checkSolanaRouteBuffer, classifyQuoteError, complianceChecks, complianceControlsEvaluated, complianceControlsLine, complianceReasonHead, complianceReasonTag, complianceTagOf, complianceView, cosignSolanaEvent, counterpartTokens, createApiClient, createEngine, createSolanaRpc, createVerifier, decodeSolanaSubmitOrder, decodeSubmitOrderCalldata, deriveSolanaEvent, destinationAvailability, destinationKeys, directComplianceFromScreens, distinctScreenedWallets, encodeAllowance, encodeApprove, encodeBalanceOf, encodeNextSolanaOrders, encodeSubmitOrder, encodeTransfer, exceedsLaneLimit, executableRoutes, executeSolanaPlan, executeSolanaPlanStaged, executionChainIds, expectedSolanaDelivery, fetchDelivery, fetchPaymentPlan, fetchWalletHistory, finalOf, findProgramAddress, findToken, foldTicker, formatJurisdiction, formatNative, formatUnits, hasReachableDestination, hexBytes, hexToSolanaKey, historyEntryFromOrder, historyKey, hubDeliverableSymbols, humanizeComplianceReason, isAddress, isChainAddress, isDeliverable, isExecutableBridge, isHexAddress, isHexData, isHexQuantity, isKnownUnbridgeable, isLayerZeroRoute, isOnEd25519Curve, isPreparationInstruction, isSolanaAddress, isSolanaChainId, isSourceToken, isSubmitOrder, laneAvailabilityState, laneKey, laneKeys, laneLimitAmount, laneLimitError, laneLimitFor, laneLimitHint, laneLimitSymbol, limitedLanes, maxDeadlineSeconds, maxNativeFeeWei, mergeHistory, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, normalizeDelivery, normalizeOrderRequest, normalizeOrderRequests, overwriteBlockhash, parseAddressLookupTable, parseAllowedApiBase, parseSolanaTransaction, parseUnitsDecimal, placeSignature, planErrorSummary, planMsgValueHex, pollSolanaConfirmation, previewSolanaSource, productAssets, quotePartnerId, quotePayOption, quoteSolanaSource, quoteSwapPreview, readSolanaBalance, recommendedDeadlineSeconds, registryRpc, requiresNativeBridgeFee, resolveApiBase, resolveConfig, resolveSolanaKeys, resolveSwapReceiver, resolveVaultIcon, routeNativeValue, safeTicker, scaleDecimals, screeningOutcomeOf, serializeSolanaTransaction, sha256, simulateSolanaCost, solanaBridgeOf, solanaDestinationAsset, solanaKeyBytes, solanaKeyHex, solanaLamportShortfall, solanaPlanNeedsPreparation, solanaQuoteCompliance, solveExactIn, solveExactOut, sourceKeys, stableGenieIntentSchema, strip0x, suppressedLanes, symbolKey, tickerOn, toHexQuantity, tokenEnabled, tokenKey, tokenTicker, txMatchesPlan, uint64Word, uintWord, unattributedComplianceReasons, validateDestination, validatePlannedTransaction, validateSwap, vaultIconsBySymbol, verifySolanaSubmit, verifySolanaTransaction, withVaultArtwork };