@glacislabs/stablegenie-zerodelta 4.12.0 → 4.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
262
- }
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;
483
+ function chainAddressKey(chainId, value) {
484
+ const text = String(value || "");
485
+ return isSolanaChainId(chainId) ? text.trim() : text.toLowerCase();
272
486
  }
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
@@ -363,8 +567,6 @@ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
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();
@@ -385,12 +587,14 @@ function decodeSubmitOrderCalldata(data) {
385
587
  const w = word(byteOffset);
386
588
  return w === null || w > MAX_UINT64 ? null : w;
387
589
  };
388
- const evmBytesAt = (byteOffset) => {
590
+ const keyBytesAt = (byteOffset) => {
389
591
  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)}`;
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
599
  if (word(0) !== 64n) return null;
396
600
  if (word(32) === null) return null;
@@ -399,12 +603,12 @@ function decodeSubmitOrderCalldata(data) {
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
609
  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);
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
614
  const bidTokenAmount = word(base + 64);
@@ -414,14 +618,17 @@ function decodeSubmitOrderCalldata(data) {
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,477 @@ 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 denied(value) {
1365
+ return typeof value === "string" ? value.toUpperCase() === "DENY" : !!value && typeof value === "object" && denied(value.decision);
1366
+ }
1367
+ async function checkActiveScreens(api, input) {
1368
+ const addresses = [...new Set([input.owner, input.sender, recipient(input)].map((a) => a.startsWith("0x") ? a.toLowerCase() : a))];
1369
+ const screens = await Promise.all(addresses.map(async (address) => {
1370
+ try {
1371
+ return await api.screenWallet(address);
1372
+ } catch {
1373
+ return void 0;
1374
+ }
1375
+ }));
1376
+ if (screens.some((screen) => screen?.blocked === true)) throw new Error("Owner, paying Solana wallet or recipient is blocked by screening.");
1377
+ }
1378
+ function jsonGuards(input, preview, tokens, chains) {
1379
+ const { from, to, amount } = selections(input, tokens), request = preview.request, option = preview.option;
1380
+ const wanted = makeRequest(input, from, to, amount);
1381
+ for (const k of ["inputChain", "outputChain", "inputToken", "outputToken", "inputAmount", "destinationWallet", "sender"]) {
1382
+ if (request[k] !== wanted[k]) throw new Error(`Native quote request mismatch (${k}).`);
1383
+ }
1384
+ if (!same(request.owners.evm, input.owner)) throw new Error("Native quote owner mismatch.");
1385
+ const now = Math.floor(Date.now() / 1e3), deadline = Number(request.deadline);
1386
+ if (!/^\d+$/.test(request.deadline) || !Number.isSafeInteger(deadline) || deadline <= now || deadline > now + 86400) throw new Error("Invalid requested deadline.");
1387
+ if (preview.quote.expiresAt && !(Date.parse(preview.quote.expiresAt) > Date.now())) throw new Error("Solana quote expired; request a fresh quote.");
1388
+ 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.");
1389
+ if (input.cost && !input.cost.sufficient) throw new Error("Insufficient SOL for order fees and rent.");
1390
+ if (JSON.stringify(option) !== JSON.stringify(preview.quote.options[0])) throw new Error("Selected native option mismatch.");
1391
+ if (JSON.stringify(preview.txData) !== JSON.stringify(option.txData)) throw new Error("Preview transactions differ from native option.");
1392
+ if (preview.receiveRaw !== option.finalAmount || preview.receive !== formatUnits(option.finalAmount, assetDecimals(to))) throw new Error("Displayed receive amount differs from quote.");
1393
+ checkSolanaPlan(option.txData);
1394
+ const orders = option.orderRequests;
1395
+ if (!Array.isArray(orders) || !orders.length || orders.length > 16) throw new Error("No valid Solana order requests.");
1396
+ const first = orders[0], last = orders[orders.length - 1];
1397
+ if (first.bidToken !== from.address) throw new Error("Source token mismatch.");
1398
+ if (raw(first.bidTokenAmount, "bid amount", true) !== amount) throw new Error("Bid amount differs from typed amount.");
1399
+ const askToken = isSolanaChainId(input.toChainId) ? solanaKeyHex(to.address) : to.address;
1400
+ if (!same(last.askToken, askToken) || chain(last.destinationChainId) !== String(input.toChainId)) throw new Error("Destination token or chain mismatch.");
1401
+ if (last.askTokenBase58 && last.askTokenBase58 !== to.address) throw new Error("Destination mint mismatch.");
1402
+ for (let i = 0; i < orders.length; i++) {
1403
+ const order = orders[i];
1404
+ if (!same(assertAddress(order.owner, "Order owner"), input.owner)) throw new Error("Order owner differs from connected EVM wallet.");
1405
+ raw(order.askTokenAmount, "ask amount", true);
1406
+ raw(order.bidTokenAmount, "bid amount", true);
1407
+ chain(order.destinationChainId);
1408
+ chain(order.executionChainId);
1409
+ if (!/^0x(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(order.askToken)) throw new Error("Invalid ask token bytes.");
1410
+ if (isSolanaChainId(order.destinationChainId)) {
1411
+ if (order !== last || !isSolanaChainId(input.toChainId)) throw new Error("Unexpected Solana intermediate order.");
1412
+ solanaBridgeOf(to);
1413
+ checkSolanaReceiver(order, recipient(input), to.address);
1414
+ } else if (!same(assertAddress(order.destinationReceiver, "Order receiver"), isSolanaChainId(input.toChainId) ? input.owner : recipient(input))) throw new Error("Order receiver mismatch.");
1415
+ 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.");
1416
+ if (i) {
1417
+ const previous = orders[i - 1];
1418
+ if (!same(previous.askToken, assertAddress(order.bidToken, "Follow-up bid token")) || String(previous.destinationChainId) !== String(order.executionChainId)) throw new Error("Disconnected route legs.");
1419
+ if (BigInt(previous.askTokenAmount) !== BigInt(order.bidTokenAmount)) throw new Error("Route legs disagree on the amount handed over; refusing to sign.");
1420
+ }
1421
+ }
1422
+ const quoteForScale = { ...option, orderRequests: orders };
1423
+ const execution = Number(last.executionChainId);
1424
+ 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.");
1425
+ const askScale = askTokenDecimals(quoteForScale, tokens, from, to), finalScale = assetDecimals(to);
1426
+ const final = BigInt(raw(option.finalAmount, "final amount", true)), slip = BigInt(input.slippageBps ?? 0);
1427
+ const minFinal = final * (10000n - slip) / 10000n;
1428
+ 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.");
1429
+ 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.");
1430
+ const registry = chains.find((c) => Number(c.chainId) === SOLANA_CHAIN_ID);
1431
+ const contracts = registry?.contracts;
1432
+ const program = checkSolanaProgram(option.escrowAddress, input.pinnedProgram ?? CANONICAL_SOLANA_PROGRAM, contracts?.escrow || registry?.escrowContract);
1433
+ const marker = option.partnerId ?? preview.quote.partnerId;
1434
+ 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.");
1435
+ const ask = BigInt(first.askTokenAmount);
1436
+ return {
1437
+ program,
1438
+ signer: input.sender,
1439
+ mint: from.address,
1440
+ owner: input.owner,
1441
+ askToken: first.askToken,
1442
+ minAskTokenAmount: ask.toString(),
1443
+ maxAskTokenAmount: ask.toString(),
1444
+ bidTokenAmount: amount,
1445
+ destinationReceiver: first.destinationReceiver,
1446
+ destinationChainId: String(first.destinationChainId),
1447
+ executionChainId: String(first.executionChainId),
1448
+ deadline: request.deadline,
1449
+ partnerId: marker == null ? null : String(marker),
1450
+ nextOrders: orders.slice(1)
1451
+ };
1452
+ }
1453
+ async function buildSolanaSourcePlan(api, input, quoted) {
1454
+ const [tokens, chains] = await Promise.all([api.fetchTokens(), api.fetchChains()]);
1455
+ const served = quoted ?? await quoteSolanaSource(api, input), original = quoteRequests.get(served);
1456
+ 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.");
1457
+ const preview = clone(served);
1458
+ const expected = jsonGuards(input, preview, tokens, chains);
1459
+ await checkActiveScreens(api, input);
1460
+ const plan = freeze({ preview, expected, txData: preview.option.txData });
1461
+ const receiveFloor = (BigInt(preview.receiveRaw) * BigInt(1e4 - (input.slippageBps ?? 0)) / 10000n).toString();
1462
+ states.set(plan, {
1463
+ api,
1464
+ input: clone(input),
1465
+ plan,
1466
+ failed: false,
1467
+ busy: false,
1468
+ originalReceive: BigInt(input.minReceiveRaw ?? "0") > BigInt(receiveFloor) ? input.minReceiveRaw : receiveFloor,
1469
+ signatures: [],
1470
+ done: 0
1471
+ });
1472
+ return plan;
1473
+ }
1474
+ function createSolanaRpc(api) {
1475
+ return async (method, params) => {
1476
+ const body = await api.apiRequest("/solana-rpc", {
1477
+ method: "POST",
1478
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
1479
+ timeoutMs: 15e3
1480
+ });
1481
+ if (body.error || body.result === void 0) throw new Error(body.error?.message || "Invalid Solana RPC response.");
1482
+ return body.result;
1483
+ };
1484
+ }
1485
+ var SolanaSendError = class extends Error {
1486
+ constructor(message, signature, sentAt) {
1487
+ super(message);
1488
+ this.signature = signature;
1489
+ this.sentAt = sentAt;
1490
+ this.name = "SolanaSendError";
1491
+ }
1492
+ signature;
1493
+ sentAt;
1494
+ };
1495
+ async function executeSolanaPlan(input) {
1496
+ const signature = await runSolanaPlan(input, false);
1497
+ if (!signature) throw new Error("Missing final Solana submit.");
1498
+ return signature;
1499
+ }
1500
+ async function executeSolanaPlanStaged(input) {
1501
+ const signature = await runSolanaPlan(input, true);
1502
+ return signature ? { status: "sent", signature } : { status: "prepared" };
1503
+ }
1504
+ function solanaPlanNeedsPreparation(plan) {
1505
+ const state = states.get(plan);
1506
+ const live = state?.plan ?? plan;
1507
+ return live.txData.slice(state?.done ?? 0).some((tx) => tx.actionType !== "submit");
1508
+ }
1509
+ async function runSolanaPlan(input, stopBeforeSubmit) {
1510
+ const state = states.get(input.plan);
1511
+ if (!state) throw new Error("Build a Solana source plan with this engine before executing.");
1512
+ if (state.sent) return state.sent;
1513
+ if (state.busy || activeSigners.has(input.signer.publicKey)) throw new Error("Solana execution already in progress.");
1514
+ if (input.signer.publicKey !== state.input.sender || typeof input.signer.signTransaction !== "function") throw new Error("Connected Solana signer mismatch.");
1515
+ state.busy = true;
1516
+ activeSigners.add(input.signer.publicKey);
1517
+ let index = 0, completedBeforeRun = state.signatures.length;
1518
+ const progress = (stage) => {
1519
+ const pending = inFlight.get(input.signer.publicKey);
1520
+ try {
1521
+ input.onProgress?.({ stage, index: completedBeforeRun + index, total: completedBeforeRun + state.plan.txData.length, signatures: [...state.signatures], inFlight: pending ? { signature: pending.signature, at: pending.at } : null });
1522
+ } catch {
1523
+ }
1524
+ };
1525
+ try {
1526
+ progress("preparing");
1527
+ const pending = inFlight.get(input.signer.publicKey);
1528
+ if (pending) {
1529
+ const height = await input.rpc("getBlockHeight", [{ commitment: "confirmed" }]).catch(() => void 0);
1530
+ const status = (await input.rpc("getSignatureStatuses", [[pending.signature], { searchTransactionHistory: true }])).value?.[0];
1531
+ if (status?.err) inFlight.delete(input.signer.publicKey);
1532
+ else if (["confirmed", "finalized"].includes(status?.confirmationStatus)) {
1533
+ inFlight.delete(input.signer.publicKey);
1534
+ if (!pending.state.signatures.includes(pending.signature)) pending.state.signatures.push(pending.signature);
1535
+ if (pending.final) {
1536
+ pending.state.sent = pending.signature;
1537
+ reportSolana(pending.state, pending.signature);
1538
+ if (pending.state !== state) throw new Error(`The previous order was broadcast (${pending.signature}); review it before starting this order.`);
1539
+ progress("sent");
1540
+ return pending.signature;
1541
+ }
1542
+ } else {
1543
+ if (status || height === void 0 || pending.lastValidBlockHeight === void 0 || height <= pending.lastValidBlockHeight) {
1544
+ throw new SolanaSendError("The last transaction may still land; wait for it before retrying.", pending.signature, pending.at);
1545
+ }
1546
+ inFlight.delete(input.signer.publicKey);
1547
+ }
1548
+ }
1549
+ if (state.failed) {
1550
+ const retried = await buildSolanaSourcePlan(state.api, { ...state.input, minReceiveRaw: state.originalReceive });
1551
+ 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.");
1552
+ state.plan = retried;
1553
+ state.done = 0;
1554
+ state.failed = false;
1555
+ }
1556
+ const plan = state.plan;
1557
+ checkSolanaPlan(plan.txData);
1558
+ for (const tx of plan.txData) {
1559
+ const parsed = parseSolanaTransaction(base64Decode(tx.transaction));
1560
+ verifySolanaTransaction(parsed, plan.expected, await resolveSolanaKeys(parsed, input.rpc), tx.actionType === "submit");
1561
+ }
1562
+ for (const tx of plan.txData) if (tx.buildData) await cosignSolanaEvent(base64Decode(tx.transaction), plan.expected.signer, tx.buildData);
1563
+ completedBeforeRun = state.signatures.length;
1564
+ const startAt = state.done;
1565
+ for (index = startAt; index < plan.txData.length; index++) {
1566
+ if (stopBeforeSubmit && plan.txData[index].actionType === "submit" && index > startAt) {
1567
+ progress("ready");
1568
+ return null;
1569
+ }
1570
+ if (Number(plan.expected.deadline) <= Math.floor(Date.now() / 1e3)) throw new Error("Order deadline expired before signature.");
1571
+ await checkActiveScreens(state.api, state.input);
1572
+ const tx = plan.txData[index], parsed = parseSolanaTransaction(base64Decode(tx.transaction));
1573
+ const keys = await resolveSolanaKeys(parsed, input.rpc);
1574
+ const buffer = verifySolanaTransaction(parsed, plan.expected, keys, tx.actionType === "submit");
1575
+ if (buffer) {
1576
+ const account = await input.rpc("getAccountInfo", [buffer, { encoding: "base64", commitment: "confirmed" }]);
1577
+ checkSolanaRouteBuffer(account.value, plan.expected);
1578
+ }
1579
+ const latest = await input.rpc("getLatestBlockhash", [{ commitment: "confirmed" }]);
1580
+ let bytes = overwriteBlockhash(parsed.bytes, latest.value.blockhash);
1581
+ if (tx.buildData) bytes = await cosignSolanaEvent(bytes, plan.expected.signer, tx.buildData);
1582
+ verifySolanaTransaction(parseSolanaTransaction(bytes), plan.expected, keys, tx.actionType === "submit");
1583
+ progress("signing");
1584
+ const signed = new Uint8Array(await input.signer.signTransaction(new Uint8Array(bytes)));
1585
+ assertWalletMessage(bytes, signed);
1586
+ verifySolanaTransaction(parseSolanaTransaction(signed), plan.expected, keys, tx.actionType === "submit");
1587
+ const signedTx = parseSolanaTransaction(signed);
1588
+ const signature = base58Encode(signed.subarray(signedTx.signatureOffset, signedTx.signatureOffset + 64)), at = Date.now();
1589
+ const lastValidBlockHeight = Number.isSafeInteger(latest.value?.lastValidBlockHeight) ? latest.value.lastValidBlockHeight : void 0;
1590
+ inFlight.set(input.signer.publicKey, { signature, at, final: tx.actionType === "submit", state, lastValidBlockHeight });
1591
+ progress("sending");
1592
+ try {
1593
+ const returned = await input.rpc("sendTransaction", [base64Encode(signed), { encoding: "base64", skipPreflight: false, preflightCommitment: "confirmed", maxRetries: 3 }]);
1594
+ if (returned !== signature) throw new Error("RPC returned a different signature.");
1595
+ if (tx.actionType !== "submit") await pollSolanaConfirmation(input.rpc, signature);
1596
+ } catch (error) {
1597
+ throw new SolanaSendError(error instanceof Error ? error.message : String(error), signature, at);
1598
+ }
1599
+ inFlight.delete(input.signer.publicKey);
1600
+ state.signatures.push(signature);
1601
+ state.done = index + 1;
1602
+ if (tx.actionType === "submit") {
1603
+ state.sent = signature;
1604
+ reportSolana(state, signature);
1605
+ progress("sent");
1606
+ return signature;
1607
+ }
1608
+ progress("ready");
1609
+ }
1610
+ throw new Error("Missing final Solana submit.");
1611
+ } catch (error) {
1612
+ state.failed = true;
1613
+ progress("failed");
1614
+ throw error;
1615
+ } finally {
1616
+ state.busy = false;
1617
+ activeSigners.delete(input.signer.publicKey);
1618
+ }
1619
+ }
1620
+ function reportSolana(state, signature) {
1621
+ try {
1622
+ void state.api.reportSubmission?.({ txHash: signature, chainId: SOLANA_CHAIN_ID, wallet: state.input.owner, stage: "submitted" }).catch(() => {
1623
+ });
1624
+ } catch {
1625
+ }
1626
+ }
1627
+ async function readSolanaBalance(rpc, owner, mint) {
1628
+ try {
1629
+ solanaKeyBytes(owner);
1630
+ solanaKeyBytes(mint);
1631
+ const result = await rpc("getTokenAccountsByOwner", [owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" }]);
1632
+ if (!Array.isArray(result.value)) throw new Error("Invalid token accounts.");
1633
+ let total = 0n, decimals;
1634
+ for (const item of result.value) {
1635
+ const amount = item.account?.data?.parsed?.info?.tokenAmount;
1636
+ if (!amount || !Number.isInteger(amount.decimals) || amount.decimals < 0 || decimals !== void 0 && decimals !== amount.decimals) throw new Error("Invalid token balance.");
1637
+ decimals = amount.decimals;
1638
+ total += BigInt(raw(amount.amount, "token balance"));
1639
+ }
1640
+ return total;
1641
+ } catch {
1642
+ return void 0;
1643
+ }
1644
+ }
1645
+ async function simulateSolanaCost(rpc, plan) {
1646
+ checkSolanaPlan(plan.txData);
1647
+ const signer = plan.expected.signer;
1648
+ const before = await rpc("getAccountInfo", [signer, { encoding: "base64", commitment: "confirmed" }]);
1649
+ const sim = await rpc("simulateTransaction", [plan.txData[0].transaction, { encoding: "base64", sigVerify: false, replaceRecentBlockhash: true, accounts: { addresses: [signer], encoding: "base64" } }]);
1650
+ if (sim.value?.err) throw new Error(`Simulation failed: ${JSON.stringify(sim.value.err)}`);
1651
+ const balanceLamports = before.value?.lamports ?? 0, post = sim.value?.accounts?.[0]?.lamports;
1652
+ if (!Number.isSafeInteger(balanceLamports) || balanceLamports < 0 || post !== void 0 && (!Number.isSafeInteger(post) || post < 0)) throw new Error("Invalid simulation lamports.");
1653
+ const lamports = typeof post === "number" ? Math.max(0, balanceLamports - post) : 0;
1654
+ return { lamports, balanceLamports, sufficient: balanceLamports >= lamports };
1655
+ }
1656
+
1657
+ // src/core/escrow.ts
1658
+ function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
1659
+ const fromQuote = normalizeAddress(quoteEscrow);
1660
+ const fromChains = normalizeAddress(chainsEscrow);
1661
+ if (!fromChains || fromChains === ZERO_ADDRESS) {
1662
+ throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
1663
+ }
1664
+ if (!fromQuote || fromQuote === ZERO_ADDRESS) {
1665
+ throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
1666
+ }
1667
+ if (fromQuote !== fromChains) {
1668
+ throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
1669
+ }
1670
+ const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
1671
+ if (pinned && pinned !== fromChains) {
1672
+ throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
1673
+ }
1674
+ return fromChains;
1675
+ }
1676
+ function isLayerZeroRoute(quote, option = {}) {
1677
+ const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
1678
+ return bridge.includes("layerzero") || bridge.includes("layer zero");
1679
+ }
1680
+ function sourceAssetKey(quote, option = {}) {
1681
+ return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
1682
+ }
1683
+ function requiresNativeBridgeFee(quote, option = {}) {
1684
+ const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
1685
+ const execChainId = Number(quote?.executionChainId);
1686
+ if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
1687
+ return false;
1688
+ }
1689
+ const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
1690
+ if (canonical) return canonical === "layerzero";
1691
+ return isLayerZeroRoute(quote, option);
1692
+ }
1693
+ function applyLayerZeroBuffer(quote, option = {}) {
1694
+ const gas = BigInt(quote?.gasCostSource || "0");
1695
+ if (gas <= 0n) return 0n;
1696
+ if (!requiresNativeBridgeFee(quote, option)) return 0n;
1697
+ return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
1698
+ }
1699
+
726
1700
  // src/core/native-fee.ts
727
1701
  function routeNativeValue(route) {
728
1702
  try {
729
- const raw = route?.quote?.msgValue;
730
- if (raw === void 0 || raw === null || raw === "") return 0n;
731
- const value = BigInt(raw);
1703
+ const raw2 = route?.quote?.msgValue;
1704
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return 0n;
1705
+ const value = BigInt(raw2);
732
1706
  return value > 0n ? value : 0n;
733
1707
  } catch {
734
1708
  return 0n;
@@ -763,6 +1737,11 @@ function nativeFeeShortMessage(check, symbol, chainName) {
763
1737
  }
764
1738
 
765
1739
  // src/core/route-health.ts
1740
+ function healthLaneKey(value) {
1741
+ if (typeof value !== "string") return "";
1742
+ const match = /^(\d+):([^>]+)>(\d+):(.+)$/.exec(value);
1743
+ return match ? laneKey(match[1], match[2], match[3], match[4]) : "";
1744
+ }
766
1745
  var EMPTY = /* @__PURE__ */ new Map();
767
1746
  var NO_LIMITS = /* @__PURE__ */ new Map();
768
1747
  function laneAvailabilityState(lane) {
@@ -782,7 +1761,7 @@ function suppressedLanes(health) {
782
1761
  const out = /* @__PURE__ */ new Map();
783
1762
  for (const lane of health.lanes) {
784
1763
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
785
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
1764
+ const key = healthLaneKey(lane.laneKey);
786
1765
  if (!key) continue;
787
1766
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
788
1767
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
@@ -802,7 +1781,7 @@ function limitedLanes(health) {
802
1781
  const out = /* @__PURE__ */ new Map();
803
1782
  for (const lane of health.lanes) {
804
1783
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
805
- const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
1784
+ const key = healthLaneKey(lane.laneKey);
806
1785
  const limit = lane.availability?.limit;
807
1786
  if (!key || !limit || typeof limit !== "object") continue;
808
1787
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
@@ -825,14 +1804,14 @@ function limitedLanes(health) {
825
1804
  }
826
1805
  function exceedsLaneLimit(limit, amount, bidDecimals) {
827
1806
  if (limit?.side !== "bid" || !BASE_UNITS.test(limit.maxAmount)) return false;
828
- let raw;
1807
+ let raw2;
829
1808
  try {
830
- raw = parseUnitsDecimal(amount, bidDecimals);
1809
+ raw2 = parseUnitsDecimal(amount, bidDecimals);
831
1810
  } catch {
832
1811
  return false;
833
1812
  }
834
1813
  const scale = Math.max(bidDecimals, limit.decimals);
835
- return scaleDecimals(raw, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
1814
+ return scaleDecimals(raw2, bidDecimals, scale) > scaleDecimals(BigInt(limit.maxAmount), limit.decimals, scale);
836
1815
  }
837
1816
  function laneLimitAmount(limit) {
838
1817
  return formatUnits(limit.maxAmount, limit.decimals);
@@ -998,12 +1977,12 @@ function stripBundlePrefix(head) {
998
1977
  if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
999
1978
  return { head, source: null };
1000
1979
  }
1001
- function complianceReasonHead(raw) {
1002
- return stripBundlePrefix((raw.split(":")[0] ?? "").trim()).head;
1980
+ function complianceReasonHead(raw2) {
1981
+ return stripBundlePrefix((raw2.split(":")[0] ?? "").trim()).head;
1003
1982
  }
1004
- function usd(raw) {
1005
- const n = Number(raw);
1006
- if (!Number.isFinite(n)) return `$${raw}`;
1983
+ function usd(raw2) {
1984
+ const n = Number(raw2);
1985
+ if (!Number.isFinite(n)) return `$${raw2}`;
1007
1986
  return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
1008
1987
  }
1009
1988
  function capFromDetail(detail) {
@@ -1014,8 +1993,8 @@ function categoryPhrase(detail) {
1014
1993
  const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
1015
1994
  return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
1016
1995
  }
1017
- function humanizeComplianceReason(raw) {
1018
- const [headRaw, ...restParts] = raw.split(":");
1996
+ function humanizeComplianceReason(raw2) {
1997
+ const [headRaw, ...restParts] = raw2.split(":");
1019
1998
  const detail = restParts.join(":").trim();
1020
1999
  const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
1021
2000
  const scope = source === "legislation" ? "applicable regulations" : "the applicable policy";
@@ -1092,8 +2071,8 @@ var CHECK_HEADS = {
1092
2071
  function distinctScreenedWallets(compliance) {
1093
2072
  const seen = /* @__PURE__ */ new Set();
1094
2073
  const wallets = [];
1095
- for (const raw of compliance?.screenedWallets ?? []) {
1096
- const address = raw?.trim();
2074
+ for (const raw2 of compliance?.screenedWallets ?? []) {
2075
+ const address = raw2?.trim();
1097
2076
  if (!address) continue;
1098
2077
  const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
1099
2078
  if (seen.has(key)) continue;
@@ -1113,11 +2092,11 @@ function screeningLabel(wallets) {
1113
2092
  function complianceChecks(compliance, cv = complianceView(compliance)) {
1114
2093
  if (cv.tone === "neutral") return [];
1115
2094
  const byControl = /* @__PURE__ */ new Map();
1116
- for (const raw of compliance?.reasons ?? []) {
1117
- const head = complianceReasonHead(raw);
2095
+ for (const raw2 of compliance?.reasons ?? []) {
2096
+ const head = complianceReasonHead(raw2);
1118
2097
  const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
1119
2098
  if (!id) continue;
1120
- byControl.set(id, [...byControl.get(id) ?? [], raw]);
2099
+ byControl.set(id, [...byControl.get(id) ?? [], raw2]);
1121
2100
  }
1122
2101
  const screenedWallets = distinctScreenedWallets(compliance);
1123
2102
  const wallets = screenedWallets.length;
@@ -1141,8 +2120,8 @@ function complianceControlsEvaluated(compliance, cv = complianceView(compliance)
1141
2120
  const checks = complianceChecks(compliance, cv);
1142
2121
  if (checks.length === 0) return 0;
1143
2122
  const named = /* @__PURE__ */ new Set();
1144
- for (const raw of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
1145
- const name = raw?.trim();
2123
+ for (const raw2 of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
2124
+ const name = raw2?.trim();
1146
2125
  if (name) named.add(name.toLowerCase());
1147
2126
  }
1148
2127
  return checks.length + named.size;
@@ -1182,8 +2161,8 @@ var BLOCK_CATEGORY_LABELS = {
1182
2161
  };
1183
2162
  var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
1184
2163
  function blockLabelFor(categories) {
1185
- for (const raw of categories) {
1186
- const label = BLOCK_CATEGORY_LABELS[String(raw || "").trim().toUpperCase()];
2164
+ for (const raw2 of categories) {
2165
+ const label = BLOCK_CATEGORY_LABELS[String(raw2 || "").trim().toUpperCase()];
1187
2166
  if (label) return label;
1188
2167
  }
1189
2168
  return BLOCK_LABEL_DEFAULT;
@@ -1204,8 +2183,8 @@ var REASON_TAGS = {
1204
2183
  dest_chain_not_allowed: "Chain not allowed",
1205
2184
  jurisdiction_out_of_scope: "Out of scope"
1206
2185
  };
1207
- function complianceReasonTag(raw) {
1208
- const head = complianceReasonHead(raw);
2186
+ function complianceReasonTag(raw2) {
2187
+ const head = complianceReasonHead(raw2);
1209
2188
  return REASON_TAGS[head] ?? head.replace(/_/g, " ");
1210
2189
  }
1211
2190
  function complianceTagOf(compliance) {
@@ -1268,8 +2247,8 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1268
2247
  const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
1269
2248
  const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
1270
2249
  const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
1271
- const enforcePayCeiling = (raw) => {
1272
- if (maxPayRaw > 0n && BigInt(raw) > maxPayRaw) {
2250
+ const enforcePayCeiling = (raw2) => {
2251
+ if (maxPayRaw > 0n && BigInt(raw2) > maxPayRaw) {
1273
2252
  throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
1274
2253
  }
1275
2254
  };
@@ -1293,7 +2272,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1293
2272
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
1294
2273
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1295
2274
  }
1296
- const guaranteed = BigInt(quote?.toAmount || "0");
2275
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1297
2276
  const final = finalOf(quote);
1298
2277
  if (final > bestFinal) {
1299
2278
  bestFinal = final;
@@ -1330,7 +2309,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
1330
2309
  directTransfer: false,
1331
2310
  quote: best,
1332
2311
  youPayRaw: bestGuess.toString(),
1333
- recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
2312
+ recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
1334
2313
  targetRaw: targetRaw.toString(),
1335
2314
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
1336
2315
  meetsTarget: bestFinal >= targetRaw,
@@ -1352,7 +2331,7 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
1352
2331
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
1353
2332
  throw new Error("ZeroDelta echoed a different input amount than requested.");
1354
2333
  }
1355
- const guaranteed = BigInt(quote?.toAmount || "0");
2334
+ const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
1356
2335
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
1357
2336
  return {
1358
2337
  directTransfer: false,
@@ -1383,13 +2362,19 @@ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChain
1383
2362
  const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + lifetimeSeconds));
1384
2363
  const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
1385
2364
  if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
2365
+ const solana = isSolanaChainId(order.destinationChainId || destination.chainId);
2366
+ const keyBytes2 = (value, label) => {
2367
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(value || ""))) throw new Error(`${label} is not a valid 32-byte Solana key.`);
2368
+ return String(value).toLowerCase();
2369
+ };
1386
2370
  return {
1387
2371
  owner: assertAddress(order.owner || payer, "Order owner"),
1388
2372
  bidToken: assertAddress(order.bidToken, "Bid token"),
1389
2373
  bidTokenAmount: String(order.bidTokenAmount || "0"),
1390
- askToken: assertAddress(order.askToken, "Ask token"),
2374
+ askToken: solana ? keyBytes2(order.askToken, "Ask token") : assertAddress(order.askToken, "Ask token"),
1391
2375
  askTokenAmount: String(order.askTokenAmount || "0"),
1392
- destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
2376
+ destinationReceiver: solana ? keyBytes2(order.destinationReceiver, "Destination receiver") : assertAddress(order.destinationReceiver || (isSolanaChainId(destination.chainId) ? payer : destination.address), "Destination receiver"),
2377
+ ...solana ? { destinationReceiverOwner: order.destinationReceiverOwner, destinationReceiverBase58: order.destinationReceiverBase58, askTokenBase58: order.askTokenBase58 } : {},
1393
2378
  destinationChainId: String(order.destinationChainId || destination.chainId),
1394
2379
  executionChainId,
1395
2380
  deadline
@@ -1401,17 +2386,24 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
1401
2386
  (request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, void 0, lifetimeSeconds) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
1402
2387
  );
1403
2388
  }
1404
- function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
2389
+ function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
1405
2390
  const list = orders?.length ? orders : [order];
1406
2391
  const sourceOrder = list[0];
1407
2392
  const finalOrder = list[list.length - 1];
1408
2393
  const now = Math.floor(Date.now() / 1e3);
1409
2394
  const deadline = Number(sourceOrder.deadline || 0);
2395
+ const solana = isSolanaChainId(destination.chainId);
2396
+ if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
2397
+ throw new Error("This Solana token is not supported for delivery; refusing to sign.");
2398
+ }
1410
2399
  for (const current of list) {
1411
2400
  if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
1412
2401
  throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
1413
2402
  }
1414
- if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(destination.address)) {
2403
+ if (isSolanaChainId(current.destinationChainId)) {
2404
+ if (current !== finalOrder || !solana) throw new Error("Unexpected Solana intermediate order; refusing to sign.");
2405
+ checkSolanaReceiver(current, destination.address, destinationToken.address);
2406
+ } else if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(solana ? payer : destination.address)) {
1415
2407
  throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
1416
2408
  }
1417
2409
  if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
@@ -1421,9 +2413,10 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1421
2413
  if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
1422
2414
  throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
1423
2415
  }
1424
- if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
2416
+ if (solana ? finalOrder.askToken.toLowerCase() !== solanaKeyHex(destinationToken.address) : normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
1425
2417
  throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
1426
2418
  }
2419
+ 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
2420
  if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
1428
2421
  throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
1429
2422
  }
@@ -1442,10 +2435,12 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
1442
2435
  if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
1443
2436
  throw new Error("ZeroDelta quote returned a non-positive output amount.");
1444
2437
  }
1445
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
2438
+ const askDecimals = askTokenDecimals(quote, tokens, option, destinationToken);
2439
+ const covers = (raw2) => askCovers(BigInt(finalOrder.askTokenAmount || "0"), BigInt(raw2 || "0"), askDecimals, assetDecimals(destinationToken));
2440
+ if (!covers(result.targetRaw)) {
1446
2441
  throw new Error("ZeroDelta quote would not cover the requested destination amount.");
1447
2442
  }
1448
- if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
2443
+ if (!covers(result.recipientReceivesRaw) || !covers(finalOf(quote).toString())) {
1449
2444
  throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
1450
2445
  }
1451
2446
  const maxDeadline = maxDeadlineSeconds(quote);
@@ -1477,8 +2472,8 @@ function routeDeltaLabel(result, quote) {
1477
2472
  return "~0";
1478
2473
  }
1479
2474
  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;
2475
+ const raw2 = quote.partnerId;
2476
+ return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
1482
2477
  }
1483
2478
  function optionTicker(option) {
1484
2479
  return option.ticker || option.symbol;
@@ -1489,14 +2484,15 @@ function routeLabelFor(option, destinationToken, result) {
1489
2484
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
1490
2485
  }
1491
2486
  function tokenAt(tokens, chainId, address) {
1492
- const wanted = normalizeAddress(address);
2487
+ const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
2488
+ const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
1493
2489
  if (!wanted || !tokens?.length) return void 0;
1494
- return tokens.find((t) => Number(t.chainId) === Number(chainId) && normalizeAddress(t.address) === wanted);
2490
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
1495
2491
  }
1496
- function legAmount(raw, decimals) {
2492
+ function legAmount(raw2, decimals) {
1497
2493
  if (decimals === void 0) return "";
1498
2494
  try {
1499
- return formatUnits(raw || "0", decimals);
2495
+ return formatUnits(raw2 || "0", decimals);
1500
2496
  } catch {
1501
2497
  return "";
1502
2498
  }
@@ -1527,7 +2523,7 @@ function buildLegs(orders, ctx) {
1527
2523
  toTicker,
1528
2524
  toChainId,
1529
2525
  toChainName: chainNameOf(toChainId, ctx.chains),
1530
- toAmount: legAmount(order.askTokenAmount, toDecimals),
2526
+ toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
1531
2527
  executionChainId,
1532
2528
  executionChainName: chainNameOf(executionChainId, ctx.chains)
1533
2529
  });
@@ -1631,8 +2627,12 @@ async function buildRoute({
1631
2627
  const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
1632
2628
  const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId, recommendedDeadlineSeconds(quote));
1633
2629
  const order = orders[0];
1634
- assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
1635
- const needsNativeFee = requiresNativeBridgeFee(quote, option);
2630
+ assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens });
2631
+ const echoedExecution = Number(quote.executionChainId || 0);
2632
+ if (echoedExecution > 0 && echoedExecution !== Number(order.executionChainId)) {
2633
+ throw new Error("ZeroDelta quote declares a different execution chain than its order; refusing to sign.");
2634
+ }
2635
+ const needsNativeFee = requiresNativeBridgeFee({ ...quote, executionChainId: order.executionChainId }, option);
1636
2636
  if (needsNativeFee) {
1637
2637
  let rawFee;
1638
2638
  try {
@@ -1676,7 +2676,7 @@ async function buildRoute({
1676
2676
  },
1677
2677
  routeLabel: routeLabelFor(option, destinationToken, result),
1678
2678
  deltaLabel: routeDeltaLabel(result, quote),
1679
- legs: buildLegs(orders, { option, destinationToken, chains, tokens }),
2679
+ legs: buildLegs(orders, { option, destinationToken, chains, tokens, quote }),
1680
2680
  transactions: [
1681
2681
  {
1682
2682
  id: "approve",
@@ -1709,6 +2709,7 @@ async function buildRoute({
1709
2709
  gasCostSource: quote.gasCostSource,
1710
2710
  msgValue: valueRaw.toString(),
1711
2711
  deadline: order.deadline,
2712
+ ...isSolanaChainId(destination.chainId) ? { destinationReceiver: orders[orders.length - 1].destinationReceiver, destinationReceiverOwner: destination.address } : {},
1712
2713
  partnerId: partnerId === NO_PARTNER_ID ? void 0 : partnerId,
1713
2714
  iterations: result.iterations,
1714
2715
  // Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
@@ -1724,10 +2725,10 @@ var CHANNEL_HEADER = "x-zd-channel";
1724
2725
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
1725
2726
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
1726
2727
  var WIDGET_CHANNEL = "widget";
1727
- var WIDGET_VERSION = "4.12.0" ;
2728
+ var WIDGET_VERSION = "4.13.0" ;
1728
2729
  var MAX_CHANNEL_VERSION_LEN = 32;
1729
- function sanitizeVersion(raw) {
1730
- const v = String(raw).trim();
2730
+ function sanitizeVersion(raw2) {
2731
+ const v = String(raw2).trim();
1731
2732
  if (!v) return "";
1732
2733
  const capped = v.length > MAX_CHANNEL_VERSION_LEN ? v.slice(0, MAX_CHANNEL_VERSION_LEN) : v;
1733
2734
  return /^[\x20-\x7e]+$/.test(capped) ? capped : "";
@@ -1930,9 +2931,9 @@ function createApiClient(cfg) {
1930
2931
  if (nowFresh(cache.chains)) return Promise.resolve(cache.chains.value);
1931
2932
  return once("chains", async () => {
1932
2933
  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 };
2934
+ const normalized = (Array.isArray(chains) ? chains : []).map((chain2) => ({ ...chain2, chainId: Number(chain2.chainId) })).map((chain2) => {
2935
+ const escrow = isSolanaChainId(chain2.chainId) && isSolanaAddress(chain2.escrowContract) ? chain2.escrowContract : normalizeAddress(chain2.escrowContract);
2936
+ return escrow ? { ...chain2, escrowContract: escrow } : { ...chain2, escrowContract: void 0 };
1936
2937
  });
1937
2938
  cache.chains = { at: Date.now(), value: normalized };
1938
2939
  return normalized;
@@ -2035,14 +3036,16 @@ function createApiClient(cfg) {
2035
3036
  async function screenWallet(address, chainId) {
2036
3037
  const addr = String(address || "").trim();
2037
3038
  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 ?? ""}`;
3039
+ const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3040
+ if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3041
+ const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
2039
3042
  const hit = screenCache.get(key);
2040
3043
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
2041
3044
  const inflight = screenInflight.get(key);
2042
3045
  if (inflight) return inflight;
2043
3046
  const request = apiRequest("/screen/wallet", {
2044
3047
  method: "POST",
2045
- body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
3048
+ body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
2046
3049
  timeoutMs: 12e3
2047
3050
  }).then((screen) => {
2048
3051
  if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
@@ -2082,7 +3085,7 @@ function createApiClient(cfg) {
2082
3085
 
2083
3086
  // src/core/plan.ts
2084
3087
  function optionBalanceKey(option) {
2085
- return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
3088
+ return `${Number(option.chainId)}:${chainAddressKey(option.chainId, option.address)}`;
2086
3089
  }
2087
3090
  function hasPositiveBalance(option, balances) {
2088
3091
  try {
@@ -2092,7 +3095,8 @@ function hasPositiveBalance(option, balances) {
2092
3095
  }
2093
3096
  }
2094
3097
  function validateDestination(destination) {
2095
- assertAddress(destination.address, "Destination address");
3098
+ const address = assertChainAddress(destination.chainId, destination.address, "Destination address");
3099
+ if (isSolanaChainId(destination.chainId)) destination.address = address;
2096
3100
  const chainId = Number(destination.chainId);
2097
3101
  const asset = symbolKey(destination.asset);
2098
3102
  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
@@ -2150,8 +3154,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
2150
3154
  if (directOptions.length) {
2151
3155
  const parties = [];
2152
3156
  const seenParty = /* @__PURE__ */ new Set();
2153
- for (const raw of [payer, destination.address]) {
2154
- const addr = String(raw || "").trim();
3157
+ for (const raw2 of [payer, destination.address]) {
3158
+ const addr = String(raw2 || "").trim();
2155
3159
  if (!addr) continue;
2156
3160
  const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
2157
3161
  if (seenParty.has(key)) continue;
@@ -2259,7 +3263,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
2259
3263
  if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
2260
3264
  const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
2261
3265
  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))
3266
+ (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
3267
  );
2264
3268
  if (!option) throw new Error("That funding option is not available for this payment right now.");
2265
3269
  return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
@@ -2282,8 +3286,10 @@ function viaOf(quote, tokens) {
2282
3286
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
2283
3287
  if (orders.length < 2) return null;
2284
3288
  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;
3289
+ const chainId = Number(first?.destinationChainId);
3290
+ const address = isSolanaChainId(chainId) ? hexToSolanaKey(first?.askToken || "") : first?.askToken;
3291
+ const wanted = isChainAddress(chainId, address) ? chainAddressKey(chainId, address) : null;
3292
+ const token = wanted ? tokens.find((t) => Number(t.chainId) === Number(first?.destinationChainId) && chainAddressKey(chainId, t.address) === wanted) : void 0;
2287
3293
  return token ? tokenTicker(token) : "";
2288
3294
  }
2289
3295
  async function quoteSwapPreview(api, swap, owner) {
@@ -2295,7 +3301,7 @@ async function quoteSwapPreview(api, swap, owner) {
2295
3301
  if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
2296
3302
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2297
3303
  const account = normalizeAddress(owner) || PREVIEW_OWNER;
2298
- const previewReceiver = normalizeAddress(swap.recipient) || account;
3304
+ const previewReceiver = isSolanaChainId(v.toChainId) ? isChainAddress(v.toChainId, swap.recipient) ? chainAddressKey(v.toChainId, swap.recipient) : void 0 : normalizeAddress(swap.recipient) || account;
2299
3305
  const quote = await api.fetchQuote({
2300
3306
  fromChainId: v.fromChainId,
2301
3307
  toChainId: v.toChainId,
@@ -2303,7 +3309,7 @@ async function quoteSwapPreview(api, swap, owner) {
2303
3309
  toToken: destToken.symbol,
2304
3310
  fromAmount: amountInRaw.toString(),
2305
3311
  owner: account,
2306
- destinationReceiver: previewReceiver
3312
+ ...previewReceiver ? { destinationReceiver: previewReceiver } : {}
2307
3313
  });
2308
3314
  const final = finalOf(quote);
2309
3315
  return {
@@ -2328,7 +3334,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
2328
3334
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
2329
3335
  if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
2330
3336
  const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
2331
- const receiver = resolveSwapReceiver(swap.recipient, account);
3337
+ const receiver = resolveSwapReceiver(swap.recipient, account, v.toChainId);
2332
3338
  const option = {
2333
3339
  symbol: sourceToken.symbol,
2334
3340
  symbolKey: symbolKey(sourceToken.symbol),
@@ -2398,9 +3404,9 @@ function rawEquals(value, expected) {
2398
3404
  }
2399
3405
  function planMsgValueHex(route) {
2400
3406
  try {
2401
- const raw = route?.quote?.msgValue;
2402
- if (raw === void 0 || raw === null || raw === "") return "0x0";
2403
- return "0x" + BigInt(raw).toString(16);
3407
+ const raw2 = route?.quote?.msgValue;
3408
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
3409
+ return "0x" + BigInt(raw2).toString(16);
2404
3410
  } catch {
2405
3411
  return null;
2406
3412
  }
@@ -2427,15 +3433,22 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
2427
3433
  if (!decoded) return false;
2428
3434
  const first = decoded.orders[0];
2429
3435
  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);
3436
+ 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
3437
  }
2432
3438
  return false;
2433
3439
  }
3440
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
3441
+ try {
3442
+ return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
3443
+ } catch {
3444
+ return false;
3445
+ }
3446
+ }
2434
3447
  async function allowanceCovers(tx, account, ethCall) {
2435
3448
  if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
2436
3449
  try {
2437
- const raw = await ethCall(tx.token, encodeAllowance(account, tx.spender));
2438
- return BigInt(raw || "0x0") >= BigInt(tx.amountRaw || "0");
3450
+ const raw2 = await ethCall(tx.token, encodeAllowance(account, tx.spender));
3451
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
2439
3452
  } catch {
2440
3453
  return false;
2441
3454
  }
@@ -2473,8 +3486,13 @@ var stableGenieIntentSchema = {
2473
3486
  type: "object",
2474
3487
  additionalProperties: false,
2475
3488
  required: ["address", "chainId", "asset", "amount"],
3489
+ // The engine performs the decoded 32-byte check; the schema filters the address alphabet.
3490
+ oneOf: [
3491
+ { properties: { chainId: { const: SOLANA_CHAIN_ID }, address: { pattern: "^[1-9A-HJ-NP-Za-km-z]{32,44}$" } } },
3492
+ { properties: { chainId: { not: { const: SOLANA_CHAIN_ID } }, address: { pattern: "^0x[a-fA-F0-9]{40}$" } } }
3493
+ ],
2476
3494
  properties: {
2477
- address: { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" },
3495
+ address: { type: "string" },
2478
3496
  // A DESTINATION chain, so it is bounded by shape, not by the escrow-chain list: a payment may
2479
3497
  // be delivered on any chain the gateway publishes a route to (~31 of them), while only the
2480
3498
  // nine escrow chains can SEND one. See validateDestination in plan.ts.
@@ -2501,9 +3519,9 @@ var TX_VERIFY_ATTEMPTS = 5;
2501
3519
  var TX_VERIFY_INTERVAL_MS = 2500;
2502
3520
  var TX_VERIFY_FETCH_MS = 5e3;
2503
3521
  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];
3522
+ function registryRpc(chain2) {
3523
+ if (!chain2) return "";
3524
+ const candidates = [chain2.rpcUrl, Array.isArray(chain2.rpcUrls) ? chain2.rpcUrls[0] : null, chain2.publicRpcUrl, chain2.rpc, chain2.rpcEndpoint];
2507
3525
  const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
2508
3526
  return found || "";
2509
3527
  }
@@ -2650,9 +3668,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
2650
3668
  }
2651
3669
  function record(target, hex) {
2652
3670
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
2653
- const raw = BigInt(hex || "0x0").toString();
3671
+ const raw2 = BigInt(hex || "0x0").toString();
2654
3672
  const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
2655
- out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
3673
+ out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
2656
3674
  return true;
2657
3675
  }
2658
3676
  async function readOne(rpcUrl, target) {
@@ -2718,9 +3736,9 @@ function isSameOriginPath(value) {
2718
3736
  return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
2719
3737
  }
2720
3738
  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;
3739
+ const raw2 = value ?? DEFAULT_WIDGET_API_BASE;
3740
+ if (isSameOriginPath(raw2)) return raw2.replace(/\/+$/, "") || "/";
3741
+ return parseAllowedApiBase(raw2) || DEFAULT_WIDGET_API_BASE;
2724
3742
  }
2725
3743
  function canAttachApiKey(apiBase, trustedOrigin) {
2726
3744
  if (isSameOriginPath(apiBase)) return true;
@@ -2759,31 +3777,33 @@ ${canAttachApiKey(apiBase, config.trustedApiOrigin) ? String(config.apiKey || ""
2759
3777
  }
2760
3778
 
2761
3779
  // src/core/index.ts
3780
+ var SOURCE_CHAIN_IDS_WITH_SOLANA = /* @__PURE__ */ new Set([...SUPPORTED_CHAIN_IDS, SOLANA_CHAIN_ID]);
2762
3781
  function sanitizeLegs(legs) {
2763
3782
  if (!Array.isArray(legs) || !legs.length) return void 0;
2764
3783
  const text = (v, max) => String(v ?? "").slice(0, max);
2765
- const chain = (v) => Number(v) || 0;
3784
+ const chain2 = (v) => Number(v) || 0;
2766
3785
  const ticker = (value, asset) => safeTicker(value, asset) || void 0;
2767
3786
  return legs.slice(0, 8).map((leg, i) => ({
2768
3787
  index: Number(leg?.index) || i + 1,
2769
3788
  fromAsset: text(leg?.fromAsset, 12),
2770
3789
  fromTicker: ticker(leg?.fromTicker, text(leg?.fromAsset, 12)),
2771
- fromChainId: chain(leg?.fromChainId),
3790
+ fromChainId: chain2(leg?.fromChainId),
2772
3791
  fromChainName: text(leg?.fromChainName, 40),
2773
3792
  fromAmount: text(leg?.fromAmount, 40),
2774
3793
  toAsset: text(leg?.toAsset, 12),
2775
3794
  toTicker: ticker(leg?.toTicker, text(leg?.toAsset, 12)),
2776
- toChainId: chain(leg?.toChainId),
3795
+ toChainId: chain2(leg?.toChainId),
2777
3796
  toChainName: text(leg?.toChainName, 40),
2778
3797
  toAmount: text(leg?.toAmount, 40),
2779
- executionChainId: chain(leg?.executionChainId),
3798
+ executionChainId: chain2(leg?.executionChainId),
2780
3799
  executionChainName: text(leg?.executionChainName, 40)
2781
3800
  }));
2782
3801
  }
2783
3802
  function sanitizeTxEntry(entry) {
2784
3803
  return {
2785
3804
  kind: entry.kind === "swap" ? "swap" : "payment",
2786
- hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
3805
+ // A Solana source records its base58 signature, exact case (lowercasing base58 changes it).
3806
+ 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
3807
  txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
2788
3808
  chainId: Number(entry.chainId) || null,
2789
3809
  chainName: String(entry.chainName || "").slice(0, 40),
@@ -2794,7 +3814,7 @@ function sanitizeTxEntry(entry) {
2794
3814
  payAmount: String(entry.payAmount || "").slice(0, 40),
2795
3815
  receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
2796
3816
  account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
2797
- recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
3817
+ recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : isSolanaAddress(entry.recipient) ? String(entry.recipient).trim() : "",
2798
3818
  settlement: entry.settlement === "direct" ? "direct" : "escrow",
2799
3819
  status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
2800
3820
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2805,6 +3825,7 @@ function createEngine(config = {}) {
2805
3825
  const resolved = resolveConfig(config);
2806
3826
  const api = createApiClient(resolved);
2807
3827
  const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
3828
+ const solanaRpc = createSolanaRpc(api);
2808
3829
  return {
2809
3830
  api,
2810
3831
  verifier,
@@ -2815,7 +3836,7 @@ function createEngine(config = {}) {
2815
3836
  fetchRouteHealth: api.fetchRouteHealth,
2816
3837
  fetchQuote: api.fetchQuote,
2817
3838
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
2818
- fetchCatalogue: async (allowedAssets, product) => {
3839
+ fetchCatalogue: async (allowedAssets, product, options) => {
2819
3840
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
2820
3841
  api.fetchChains().catch(() => []),
2821
3842
  api.fetchTokens().catch(() => []),
@@ -2832,7 +3853,9 @@ function createEngine(config = {}) {
2832
3853
  routes,
2833
3854
  product,
2834
3855
  ...allowed ? { allowedAssets: allowed } : {},
2835
- supportedChainIds: SUPPORTED_CHAIN_IDS,
3856
+ // Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
3857
+ // Solana-source flow). Every EVM signing path still refuses it: it never joins the EVM pins.
3858
+ supportedChainIds: options?.solanaSources ? SOURCE_CHAIN_IDS_WITH_SOLANA : SUPPORTED_CHAIN_IDS,
2836
3859
  brokenLanes: suppressedLanes(health),
2837
3860
  // Same read, same degraded mode: a null health response limits nothing.
2838
3861
  limitedLanes: limitedLanes(health),
@@ -2843,6 +3866,13 @@ function createEngine(config = {}) {
2843
3866
  quotePayOption: (request, payer, option, wallet) => quotePayOption(api, request, payer, option, wallet),
2844
3867
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
2845
3868
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
3869
+ quoteSolanaSource: (input) => quoteSolanaSource(api, input),
3870
+ buildSolanaSourcePlan: (input, preview) => buildSolanaSourcePlan(api, input, preview),
3871
+ executeSolanaPlan: (input) => executeSolanaPlan({ ...input, rpc: input.rpc ?? solanaRpc }),
3872
+ executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
3873
+ previewSolanaSource: (input) => previewSolanaSource(api, input),
3874
+ readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
3875
+ simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
2846
3876
  payerNonceBaseline: verifier.payerNonceBaseline,
2847
3877
  verifySubmittedTx: verifier.verifySubmittedTx,
2848
3878
  readBalances: verifier.readBalances,
@@ -2859,4 +3889,4 @@ function createEngine(config = {}) {
2859
3889
  };
2860
3890
  }
2861
3891
 
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 };
3892
+ 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, 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, TRADEABLE_RWA_ASSETS, TUNABLE_CATEGORIES, 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, fetchPaymentPlan, finalOf, findProgramAddress, findToken, foldTicker, formatJurisdiction, formatNative, formatUnits, hasReachableDestination, hexBytes, hexToSolanaKey, 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, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, 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, solanaPlanNeedsPreparation, solveExactIn, solveExactOut, sourceKeys, stableGenieIntentSchema, strip0x, suppressedLanes, symbolKey, tickerOn, toHexQuantity, tokenEnabled, tokenKey, tokenTicker, txMatchesPlan, uint64Word, uintWord, unattributedComplianceReasons, validateDestination, validatePlannedTransaction, validateSwap, vaultIconsBySymbol, verifySolanaSubmit, verifySolanaTransaction, withVaultArtwork };