@glacislabs/stablegenie-zerodelta 4.18.1 → 4.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mount.cjs CHANGED
@@ -575,12 +575,64 @@ var init_ed255192 = __esm({
575
575
  });
576
576
 
577
577
  // src/core/delivery.ts
578
- var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "expired", "failed"]);
579
- var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim"]);
578
+ var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "failed"]);
579
+ var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim", "expired"]);
580
580
  var TRACKING = Object.freeze({ phase: "tracking", status: "", steps: [] });
581
581
  var word = (v) => typeof v === "string" ? v.trim().toLowerCase() : "";
582
582
  var STEP_ORDER = { submitted: 0, arrived: 1, filled: 2, delivered: 3 };
583
583
  var STATUS_REACHED = { in_progress: 1, outbound_bridging: 2, delivery_failed: 2, delivered: 3 };
584
+ var ZDH_FIRST_STEP = 20;
585
+ var ZDH_STEP = {
586
+ paid_out: "delivered",
587
+ cancelled: "cancellation_requested",
588
+ refunded: "refunded"
589
+ };
590
+ var ROUTE_MECHANICS = /* @__PURE__ */ new Set(["consumed", "step_executed", "step_filled", "returned"]);
591
+ var PROGRESS = /* @__PURE__ */ new Set(["pending", "in_progress", "outbound_bridging"]);
592
+ var MAX_STEPS = 8;
593
+ function isZdHeavy(r, steps) {
594
+ return r.protocol === "zdheavy" || steps.some((s) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP);
595
+ }
596
+ function zdHeavyDelivery(own, rawSteps) {
597
+ const named = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string");
598
+ const lite = (name) => named.some((s) => Number(s.stepNumber ?? 0) < ZDH_FIRST_STEP && s.stepName === name && s.stepStatus === "completed");
599
+ const events = named.map((s, i) => ({ s, i })).filter(({ s }) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP).sort((a, b) => (Date.parse(String(a.s.blockTimestamp ?? "")) || 0) - (Date.parse(String(b.s.blockTimestamp ?? "")) || 0) || a.i - b.i).map(({ s }) => s);
600
+ const has = (name) => events.some((e) => e.stepName === name);
601
+ const cancelled = has("cancelled");
602
+ const status = PROGRESS.has(own) && has("paid_out") && !cancelled ? "delivered" : own;
603
+ const steps = [];
604
+ const push = (name, done) => {
605
+ const last = steps[steps.length - 1];
606
+ if (last && last.name === name && last.done === done) return;
607
+ steps.push({ name, done });
608
+ };
609
+ if (lite("submitted")) push("submitted", true);
610
+ const terminal = cancelled || FAILED.has(status) || ATTENTION.has(status) || status === "delivered";
611
+ if (!cancelled && !FAILED.has(status) && !ATTENTION.has(status)) {
612
+ if (status === "delivered") {
613
+ push("route_completed", true);
614
+ } else {
615
+ push("route", false);
616
+ }
617
+ }
618
+ for (const e of events) {
619
+ const name = String(e.stepName);
620
+ if (ROUTE_MECHANICS.has(name)) continue;
621
+ if (name === "refund_parked") {
622
+ push(e.stepStatus === "recovered" ? "claimed" : "ready_to_claim", e.stepStatus === "recovered");
623
+ continue;
624
+ }
625
+ push(ZDH_STEP[name] ?? name.slice(0, 32), true);
626
+ }
627
+ if (!terminal) push("delivered", false);
628
+ const capped = steps.length > MAX_STEPS ? [...steps.slice(0, MAX_STEPS - 1), steps[steps.length - 1]] : steps;
629
+ const refunded = cancelled && has("refunded");
630
+ if (!status) return TRACKING;
631
+ if (FAILED.has(status)) return { phase: "failed", status, steps: capped, ...refunded ? { refunded } : {} };
632
+ if (ATTENTION.has(status)) return { phase: "attention", status, steps: capped };
633
+ if (status === "delivered") return { phase: "delivered", status, steps: capped };
634
+ return { phase: "in-progress", status, steps: capped };
635
+ }
584
636
  function normalizeDelivery(raw2) {
585
637
  const row = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2.data ?? raw2 : null;
586
638
  if (!row || typeof row !== "object" || Array.isArray(row)) return TRACKING;
@@ -590,6 +642,7 @@ function normalizeDelivery(raw2) {
590
642
  const own = word(r.status);
591
643
  const status = journey || own;
592
644
  const rawSteps = Array.isArray(r.steps) ? r.steps : [];
645
+ if (isZdHeavy(r, rawSteps) && !chained) return zdHeavyDelivery(own, rawSteps);
593
646
  const listed = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string").sort((a, b) => Number(a.stepNumber ?? 0) - Number(b.stepNumber ?? 0)).slice(0, 8).map((s) => ({ name: String(s.stepName).slice(0, 32), done: s.stepStatus === "completed" }));
594
647
  const reached = Math.max(STATUS_REACHED[own] ?? -1, ...listed.filter((s) => s.done).map((s) => STEP_ORDER[s.name] ?? -1));
595
648
  const steps = listed.map((s) => (STEP_ORDER[s.name] ?? Infinity) <= reached ? { ...s, done: true } : s);
@@ -633,11 +686,15 @@ function useDelivery(engine, hash2) {
633
686
  let alive = true;
634
687
  let timer2;
635
688
  let answered = false;
689
+ let waitsOnOwner = false;
636
690
  let unanswered = 0;
637
691
  const started2 = Date.now();
638
692
  setState({ hash: hash2, value: TRACKING });
639
693
  const schedule = () => {
640
- if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) return setState({ hash: hash2, value: UNAVAILABLE });
694
+ if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) {
695
+ if (waitsOnOwner) return;
696
+ return setState({ hash: hash2, value: UNAVAILABLE });
697
+ }
641
698
  timer2 = setTimeout(tick, deliveryPollDelay(Date.now() - started2));
642
699
  };
643
700
  const tick = async () => {
@@ -650,6 +707,7 @@ function useDelivery(engine, hash2) {
650
707
  return schedule();
651
708
  }
652
709
  answered = true;
710
+ waitsOnOwner = next.phase === "attention";
653
711
  setState({ hash: hash2, value: next });
654
712
  if (next.phase === "delivered" || next.phase === "failed") return;
655
713
  schedule();
@@ -674,7 +732,15 @@ var STEP_LABEL = {
674
732
  arrived: "Arrived",
675
733
  filled: "Filled",
676
734
  outbound_bridging: "Bridging",
677
- delivered: "Delivered"
735
+ delivered: "Delivered",
736
+ // ZD Heavy (core/delivery.ts; mirrors zd-dapp src/lib/zdHeavyTimeline.ts). How the order was filled
737
+ // (netted, partly netted, swapped) is the protocol's business, so the holder reads one "Filled".
738
+ route_completed: "Filled",
739
+ route: "Filled",
740
+ cancellation_requested: "Cancellation requested",
741
+ refunded: "Refunded",
742
+ ready_to_claim: "Ready to claim",
743
+ claimed: "Claimed"
678
744
  };
679
745
  var label = (name) => STEP_LABEL[name] ?? name.replace(/_/g, " ");
680
746
  function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
@@ -683,12 +749,14 @@ function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
683
749
  case "delivered":
684
750
  return "Delivered";
685
751
  case "failed":
752
+ if (delivery.status === "cancelled" && delivery.refunded) return "Cancelled \u2014 refunded to the owner";
686
753
  return delivery.status === "cancelled" ? "Cancelled \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
687
754
  case "attention":
688
755
  return delivery.status === "cancel_pending" ? "Being cancelled \u2014 not delivered" : "Waiting to be claimed \u2014 open the transaction";
689
756
  case "in-progress": {
690
757
  if (delivery.status === "continuing") return "On its way \u2014 final leg next";
691
758
  const next = delivery.steps.find((s) => !s.done);
759
+ if (next?.name === "route") return "On its way";
692
760
  return next ? `On its way \u2014 ${label(next.name).toLowerCase()} next` : "On its way";
693
761
  }
694
762
  case "unavailable":
@@ -910,7 +978,7 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
910
978
  8453: "Base",
911
979
  9745: "Plasma",
912
980
  34443: "Mode",
913
- 42161: "Arbitrum One",
981
+ 42161: "Arbitrum",
914
982
  // "Avalanche", as the dApp prints it since zd-dapp#582 (from ZD Heavy's /chains). The widget's
915
983
  // registry read lists no row for a payout-only chain, so this table is what names it here.
916
984
  43114: "Avalanche",
@@ -986,8 +1054,8 @@ var SOLANA_DESTINATION_ASSETS = Object.freeze({
986
1054
  AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
987
1055
  });
988
1056
  function solanaDestinationAsset(mint) {
989
- const key = typeof mint === "string" ? mint.trim() : "";
990
- return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
1057
+ const key2 = typeof mint === "string" ? mint.trim() : "";
1058
+ return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key2) ? SOLANA_DESTINATION_ASSETS[key2] : null;
991
1059
  }
992
1060
  function solanaBridgeOf(token) {
993
1061
  const pinned = solanaDestinationAsset(token.address);
@@ -1361,9 +1429,9 @@ function hexBytes(hex) {
1361
1429
  if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
1362
1430
  return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
1363
1431
  }
1364
- function solanaKeyBytes(key) {
1365
- if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
1366
- return base58Decode(key);
1432
+ function solanaKeyBytes(key2) {
1433
+ if (!isSolanaAddress(key2) || key2 !== key2.trim()) throw new Error("Invalid Solana public key.");
1434
+ return base58Decode(key2);
1367
1435
  }
1368
1436
  var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1369
1437
  function base64Decode(text) {
@@ -1709,16 +1777,16 @@ function tokenTicker(token) {
1709
1777
  }
1710
1778
  function tickerOn(tokens, chainId, symbol) {
1711
1779
  if (!symbol || !chainId || !tokens?.length) return symbol;
1712
- const key = symbolKey(symbol);
1713
- const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key);
1780
+ const key2 = symbolKey(symbol);
1781
+ const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key2);
1714
1782
  return deployment ? tokenTicker(deployment) : symbol;
1715
1783
  }
1716
1784
 
1717
1785
  // src/core/availability.ts
1718
1786
  function assetClassOf(symbol) {
1719
- const key = symbolKey(symbol);
1720
- if (TRADEABLE_RWA_ASSETS.has(key)) return "rwa";
1721
- if (STABLE_ASSETS.has(key)) return "stable";
1787
+ const key2 = symbolKey(symbol);
1788
+ if (TRADEABLE_RWA_ASSETS.has(key2)) return "rwa";
1789
+ if (STABLE_ASSETS.has(key2)) return "stable";
1722
1790
  return null;
1723
1791
  }
1724
1792
  var NEST_VAULT_SHARES = /* @__PURE__ */ new Set(["NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON"]);
@@ -1827,8 +1895,8 @@ function buildCatalogue(input) {
1827
1895
  if (product === "rwa") return true;
1828
1896
  if (execution.has(chainId) || token.isChainedDestination === true) return true;
1829
1897
  if (!isExecutableBridge(token)) return false;
1830
- const key = tokenKey(token.chainId, token.address);
1831
- return source2.has(key) || destination.has(key);
1898
+ const key2 = tokenKey(token.chainId, token.address);
1899
+ return source2.has(key2) || destination.has(key2);
1832
1900
  });
1833
1901
  const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
1834
1902
  const catalogue = ready ? projectedCatalogue : allowed;
@@ -1872,8 +1940,8 @@ function tokenEnabled(token) {
1872
1940
  return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
1873
1941
  }
1874
1942
  function findToken(tokens, chainId, symbol) {
1875
- const key = symbolKey(symbol);
1876
- return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key) || null;
1943
+ const key2 = symbolKey(symbol);
1944
+ return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key2) || null;
1877
1945
  }
1878
1946
  function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
1879
1947
  const invoiceKey = symbolKey(invoiceAsset);
@@ -1907,10 +1975,10 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
1907
1975
  const chainId = Number(token.chainId);
1908
1976
  const chain2 = chainById(chains, chainId);
1909
1977
  if (!chainSelectable(chain2, chainId)) continue;
1910
- const key = tokenKey(chainId, token.address);
1911
- if (seen.has(key)) continue;
1978
+ const key2 = tokenKey(chainId, token.address);
1979
+ if (seen.has(key2)) continue;
1912
1980
  if (refusal(token)) continue;
1913
- seen.add(key);
1981
+ seen.add(key2);
1914
1982
  const payKey = symbolKey(token.symbol);
1915
1983
  const direct2 = chainId === invoiceChain && payKey === invoiceKey;
1916
1984
  options.push({
@@ -2096,7 +2164,7 @@ function normalizePreview(request, quote, to, amount) {
2096
2164
  async function quoteSolanaSource(api, input) {
2097
2165
  const { from, to, amount } = selections(input, await api.fetchTokens());
2098
2166
  const request = makeRequest(input, from, to, amount);
2099
- const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
2167
+ const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
2100
2168
  const preview = normalizePreview(request, quote, to, input.amountIn);
2101
2169
  quoteRequests.set(preview, { api, request: clone(request) });
2102
2170
  return preview;
@@ -2110,7 +2178,7 @@ async function previewSolanaSource(api, input) {
2110
2178
  raw(amount, "input amount", true);
2111
2179
  const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
2112
2180
  const request = body;
2113
- const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
2181
+ const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
2114
2182
  const option = quote?.options?.[0];
2115
2183
  if (!option) throw new Error("Native quote returned no options.");
2116
2184
  const receive = raw(option.finalAmount, "quoted output", true);
@@ -2467,8 +2535,8 @@ function historyKey(value) {
2467
2535
  var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
2468
2536
  function tokenAt(tokens, chainId, address) {
2469
2537
  if (!address) return void 0;
2470
- const key = historyKey(address);
2471
- return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key);
2538
+ const key2 = historyKey(address);
2539
+ return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key2);
2472
2540
  }
2473
2541
  function amountOf(raw2, token, rowDecimals, rowAmount) {
2474
2542
  const decimals = token ? Number(token.decimals) : Number(rowDecimals);
@@ -2554,13 +2622,13 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
2554
2622
  const out = [];
2555
2623
  const seen = /* @__PURE__ */ new Set();
2556
2624
  for (const entry of local) {
2557
- const key = historyKey(entry.hash);
2558
- if (seen.has(key)) continue;
2559
- seen.add(key);
2560
- const known = byHash.get(key);
2625
+ const key2 = historyKey(entry.hash);
2626
+ if (seen.has(key2)) continue;
2627
+ seen.add(key2);
2628
+ const known = byHash.get(key2);
2561
2629
  out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
2562
2630
  }
2563
- for (const [key, entry] of byHash) if (!seen.has(key)) out.push(entry);
2631
+ for (const [key2, entry] of byHash) if (!seen.has(key2)) out.push(entry);
2564
2632
  return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
2565
2633
  }
2566
2634
 
@@ -2671,12 +2739,12 @@ function suppressedLanes(health) {
2671
2739
  const out = /* @__PURE__ */ new Map();
2672
2740
  for (const lane of health.lanes) {
2673
2741
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
2674
- const key = healthLaneKey(lane.laneKey);
2675
- if (!key) continue;
2742
+ const key2 = healthLaneKey(lane.laneKey);
2743
+ if (!key2) continue;
2676
2744
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
2677
2745
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
2678
2746
  const message = typeof availability?.message === "string" && availability.message ? availability.message : lane.message;
2679
- out.set(key, {
2747
+ out.set(key2, {
2680
2748
  route: typeof lane.route === "string" ? lane.route : "",
2681
2749
  code: typeof code === "string" ? code : "",
2682
2750
  message: typeof message === "string" ? message : "",
@@ -2691,15 +2759,15 @@ function limitedLanes(health) {
2691
2759
  const out = /* @__PURE__ */ new Map();
2692
2760
  for (const lane of health.lanes) {
2693
2761
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
2694
- const key = healthLaneKey(lane.laneKey);
2762
+ const key2 = healthLaneKey(lane.laneKey);
2695
2763
  const limit = lane.availability?.limit;
2696
- if (!key || !limit || typeof limit !== "object") continue;
2764
+ if (!key2 || !limit || typeof limit !== "object") continue;
2697
2765
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
2698
2766
  const maxAmount = typeof limit.maxAmount === "string" ? limit.maxAmount.trim() : "";
2699
2767
  const decimals = limit.decimals;
2700
2768
  if (!side || !BASE_UNITS.test(maxAmount) || typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
2701
2769
  const code = lane.availability?.code;
2702
- out.set(key, {
2770
+ out.set(key2, {
2703
2771
  side,
2704
2772
  token: typeof limit.token === "string" ? limit.token : "",
2705
2773
  fromChainId: Number(limit.fromChainId) || 0,
@@ -2762,10 +2830,10 @@ function resolveVaultIcon(apiBase, iconPath) {
2762
2830
  function vaultIconsBySymbol(apiBase, vaults) {
2763
2831
  const out = /* @__PURE__ */ new Map();
2764
2832
  for (const vault of vaults) {
2765
- const key = symbolKey(vault?.symbol);
2766
- if (!key || out.has(key)) continue;
2833
+ const key2 = symbolKey(vault?.symbol);
2834
+ if (!key2 || out.has(key2)) continue;
2767
2835
  const url = resolveVaultIcon(apiBase, vault?.iconMiniUrl) ?? resolveVaultIcon(apiBase, vault?.iconUrl);
2768
- if (url) out.set(key, url);
2836
+ if (url) out.set(key2, url);
2769
2837
  }
2770
2838
  return out;
2771
2839
  }
@@ -2862,7 +2930,7 @@ var CATEGORY_PHRASES = {
2862
2930
  UNKNOWN: "an unrecognized risk"
2863
2931
  };
2864
2932
  function categoryLabel(code) {
2865
- const key = code.trim().toUpperCase();
2933
+ const key2 = code.trim().toUpperCase();
2866
2934
  const LABELS = {
2867
2935
  SANCTIONS: "Sanctions",
2868
2936
  TERRORISM_FINANCING: "Terrorist financing",
@@ -2877,7 +2945,7 @@ function categoryLabel(code) {
2877
2945
  UNCLASSIFIED: "Unclassified risk",
2878
2946
  UNKNOWN: "Unclassified risk"
2879
2947
  };
2880
- return LABELS[key] ?? key.toLowerCase().replace(/_/g, " ");
2948
+ return LABELS[key2] ?? key2.toLowerCase().replace(/_/g, " ");
2881
2949
  }
2882
2950
  function cleanJurisdiction(code) {
2883
2951
  return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
@@ -2990,9 +3058,9 @@ function distinctScreenedWallets(compliance) {
2990
3058
  for (const raw2 of compliance?.screenedWallets ?? []) {
2991
3059
  const address = raw2?.trim();
2992
3060
  if (!address) continue;
2993
- const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
2994
- if (seen.has(key)) continue;
2995
- seen.add(key);
3061
+ const key2 = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
3062
+ if (seen.has(key2)) continue;
3063
+ seen.add(key2);
2996
3064
  wallets.push(address);
2997
3065
  }
2998
3066
  return wallets;
@@ -3103,9 +3171,9 @@ var TUNED_OUTCOMES = {
3103
3171
  UNCLASSIFIED: "flagged"
3104
3172
  };
3105
3173
  function screeningOutcomeOf(category) {
3106
- const key = category.trim().toUpperCase();
3107
- if (FLOOR_CATEGORIES.includes(key)) return "always-blocked";
3108
- return TUNED_OUTCOMES[key] ?? null;
3174
+ const key2 = category.trim().toUpperCase();
3175
+ if (FLOOR_CATEGORIES.includes(key2)) return "always-blocked";
3176
+ return TUNED_OUTCOMES[key2] ?? null;
3109
3177
  }
3110
3178
  var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
3111
3179
  var SCREENING_BUCKETS = [
@@ -3114,6 +3182,91 @@ var SCREENING_BUCKETS = [
3114
3182
  { outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
3115
3183
  ];
3116
3184
 
3185
+ // src/core/zdheavy-routers.ts
3186
+ var ZDHEAVY_ROUTER_TEST05 = "0x94c5cC7f4689AD7B0Abd0975F4C8E159e4633251";
3187
+ var ZDHEAVY_ROUTER_TEST04 = "0x72EA420DCE5BE939062E527b49388479d7171379";
3188
+ var ZDHEAVY_ROUTER_DEV = "0xD813690937324417cFBE12E742dD53054F90dF04";
3189
+ var ZDHEAVY_ROUTER_DEV_V6 = "0xa6155b1505378e6C9871483c55375dcBBB16f897";
3190
+ var ZDHEAVY_ROUTER_PROD = "0x7D50305f2855Bf2225FE51E15858b4BA0C0844e1";
3191
+ var ZDHEAVY_DEV_CHAINS = [1, 10, 56, 130, 137, 143, 146, 1329, 1672, 4663, 5e3, 8453, 9745, 42161, 43114, 57073, 98866];
3192
+ var ZDHEAVY_SANDBOX_CHAINS = [8453, 9745, 42161];
3193
+ var ZDHEAVY_ROUTER_ADDRESSES = Object.fromEntries(
3194
+ ZDHEAVY_DEV_CHAINS.map((id) => [
3195
+ id,
3196
+ ZDHEAVY_SANDBOX_CHAINS.includes(id) ? [ZDHEAVY_ROUTER_TEST05, ZDHEAVY_ROUTER_TEST04, ZDHEAVY_ROUTER_DEV, ZDHEAVY_ROUTER_DEV_V6, ZDHEAVY_ROUTER_PROD] : [ZDHEAVY_ROUTER_DEV, ZDHEAVY_ROUTER_DEV_V6, ZDHEAVY_ROUTER_PROD]
3197
+ ])
3198
+ );
3199
+ function zdHeavyRouterPinned(chainId, router) {
3200
+ if (typeof router !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(router)) return false;
3201
+ const want = router.toLowerCase();
3202
+ return (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).some((a) => a.toLowerCase() === want);
3203
+ }
3204
+
3205
+ // src/core/quote-option.ts
3206
+ function zdHeavyExecutable(q) {
3207
+ const order = q.execution?.order;
3208
+ const chainId = typeof q.fromChainId === "number" ? q.fromChainId : Number(order?.chainNumber);
3209
+ return q.protocol === "zdheavy" && q.payloadStatus === "resolved-offchain-signed" && !!order && !!q.rootHash && Array.isArray(q.txData) && q.txData.some((tx) => (tx.actionType === "submit" || tx.actionType === "submitOrder") && typeof tx.to === "string" && typeof tx.data === "string") && zdHeavyRouterPinned(chainId, order.router);
3210
+ }
3211
+ function liteExecutable(q) {
3212
+ return q.protocol !== "zdheavy" && Array.isArray(q.orderRequests) && q.orderRequests.length > 0;
3213
+ }
3214
+ function selectQuoteOption(quote) {
3215
+ if (!Array.isArray(quote.options)) return quote;
3216
+ const option = quote.options.find(zdHeavyExecutable) ?? quote.options.find((q) => q.protocol !== "zdheavy" && !!q.orderRequests?.length);
3217
+ if (!option) throw new Error("ZeroDelta quote has no executable option.");
3218
+ const gatewayOptions = [];
3219
+ let gatewayOptionIndex = -1;
3220
+ for (const o of quote.options) {
3221
+ if (!o || typeof o !== "object" || Array.isArray(o)) continue;
3222
+ if (o === option) gatewayOptionIndex = gatewayOptions.length;
3223
+ gatewayOptions.push(projectOption(quote, o));
3224
+ }
3225
+ return { ...projectOption(quote, option), gatewayOptions, gatewayOptionIndex };
3226
+ }
3227
+ function projectOption(quote, option) {
3228
+ const { fromChainId, toChainId, fromToken, toToken: toToken2, fromAmount } = quote;
3229
+ const last = option.orderRequests?.[option.orderRequests.length - 1];
3230
+ const { entersNetting, gasSponsored, gatewayOptions: _g, gatewayOptionIndex: _i, ...rest } = option;
3231
+ return {
3232
+ ...rest,
3233
+ ...entersNetting === true ? { entersNetting: true } : {},
3234
+ ...gasSponsored === true ? { gasSponsored: true } : {},
3235
+ fromChainId,
3236
+ toChainId,
3237
+ fromToken,
3238
+ toToken: toToken2,
3239
+ fromAmount,
3240
+ quoteId: quote.quoteId,
3241
+ toAmount: String(last?.askTokenAmount ?? option.outputAmount ?? option.toAmount ?? ""),
3242
+ finalAmount: String(option.finalAmount || last?.askTokenAmount || option.outputAmount || ""),
3243
+ compliance: complianceDecision(quote),
3244
+ estimatedDuration: option.estimatedTimeSec ?? option.estimatedDuration
3245
+ };
3246
+ }
3247
+ function complianceDecision(quote) {
3248
+ const decision = quote.complianceDecision ?? quote.compliance;
3249
+ return decision && typeof decision === "object" && !Array.isArray(decision) ? decision : void 0;
3250
+ }
3251
+ function normalizeQuoteResponse(response, request) {
3252
+ const quote = Array.isArray(response?.options) ? selectQuoteOption({
3253
+ ...response,
3254
+ fromChainId: request.inputChain,
3255
+ toChainId: request.outputChain,
3256
+ fromToken: request.inputToken,
3257
+ toToken: request.outputToken,
3258
+ fromAmount: request.inputAmount
3259
+ }) : response;
3260
+ if (quote?.gatewayOptions) quote.gatewayOptions = quote.gatewayOptions.map(numericExecutionChain);
3261
+ return numericExecutionChain(quote);
3262
+ }
3263
+ function numericExecutionChain(quote) {
3264
+ return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
3265
+ }
3266
+ function deliveredAmount(quote, solanaDestination) {
3267
+ return BigInt(quote.protocol === "zdheavy" || solanaDestination ? quote.finalAmount || quote.toAmount || "0" : quote.toAmount || "0");
3268
+ }
3269
+
3117
3270
  // src/core/solve.ts
3118
3271
  async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
3119
3272
  const destDecimals = assetDecimals(destinationToken);
@@ -3160,7 +3313,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3160
3313
  let bestGuess = guess;
3161
3314
  for (let i = 0; i < 3; i += 1) {
3162
3315
  const guessSent = guess;
3163
- const quote = await fetchQuote({
3316
+ const quote = selectQuoteOption(await fetchQuote({
3164
3317
  fromChainId: option.chainId,
3165
3318
  toChainId: Number(destination.chainId),
3166
3319
  fromToken: option.symbol,
@@ -3168,11 +3321,11 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3168
3321
  fromAmount: guessSent.toString(),
3169
3322
  owner: payer,
3170
3323
  destinationReceiver: destination.address
3171
- });
3324
+ }));
3172
3325
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
3173
3326
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3174
3327
  }
3175
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3328
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3176
3329
  const final = finalOf(quote);
3177
3330
  if (final > bestFinal) {
3178
3331
  bestFinal = final;
@@ -3209,7 +3362,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3209
3362
  directTransfer: false,
3210
3363
  quote: best,
3211
3364
  youPayRaw: bestGuess.toString(),
3212
- recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
3365
+ recipientReceivesRaw: deliveredAmount(best, isSolanaChainId(destination.chainId)).toString(),
3213
3366
  targetRaw: targetRaw.toString(),
3214
3367
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
3215
3368
  meetsTarget: bestFinal >= targetRaw,
@@ -3219,7 +3372,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3219
3372
  async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
3220
3373
  const fromRaw = BigInt(amountInRaw || "0");
3221
3374
  if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
3222
- const quote = await fetchQuote({
3375
+ const quote = selectQuoteOption(await fetchQuote({
3223
3376
  fromChainId: option.chainId,
3224
3377
  toChainId: Number(destination.chainId),
3225
3378
  fromToken: option.symbol,
@@ -3227,11 +3380,11 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3227
3380
  fromAmount: fromRaw.toString(),
3228
3381
  owner: payer,
3229
3382
  destinationReceiver: destination.address
3230
- });
3383
+ }));
3231
3384
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
3232
3385
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3233
3386
  }
3234
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3387
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3235
3388
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3236
3389
  return {
3237
3390
  directTransfer: false,
@@ -3244,6 +3397,24 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3244
3397
  iterations: 1
3245
3398
  };
3246
3399
  }
3400
+ function resultForOption(result, option, mode, destinationChainId) {
3401
+ if (result.directTransfer) throw new Error("A direct transfer has no other option.");
3402
+ if (BigInt(option.fromAmount || "0") !== BigInt(result.youPayRaw)) throw new Error("ZeroDelta echoed a different input amount than requested.");
3403
+ const guaranteed = deliveredAmount(option, isSolanaChainId(destinationChainId));
3404
+ if (mode === "exact-in") {
3405
+ if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3406
+ return { ...result, quote: option, recipientReceivesRaw: guaranteed.toString(), targetRaw: guaranteed.toString(), overageBps: 0, meetsTarget: true };
3407
+ }
3408
+ const targetRaw = BigInt(result.targetRaw);
3409
+ const final = finalOf(option);
3410
+ return {
3411
+ ...result,
3412
+ quote: option,
3413
+ recipientReceivesRaw: guaranteed.toString(),
3414
+ overageBps: targetRaw > 0n ? Number((final - targetRaw) * 10000n / targetRaw) : 0,
3415
+ meetsTarget: final >= targetRaw
3416
+ };
3417
+ }
3247
3418
 
3248
3419
  // src/core/order.ts
3249
3420
  var DEFAULT_DEADLINE_SECONDS = 1800;
@@ -3363,6 +3534,954 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
3363
3534
  }
3364
3535
  }
3365
3536
 
3537
+ // src/core/checksum.ts
3538
+ var RC = [
3539
+ 0x0000000000000001n,
3540
+ 0x0000000000008082n,
3541
+ 0x800000000000808an,
3542
+ 0x8000000080008000n,
3543
+ 0x000000000000808bn,
3544
+ 0x0000000080000001n,
3545
+ 0x8000000080008081n,
3546
+ 0x8000000000008009n,
3547
+ 0x000000000000008an,
3548
+ 0x0000000000000088n,
3549
+ 0x0000000080008009n,
3550
+ 0x000000008000000an,
3551
+ 0x000000008000808bn,
3552
+ 0x800000000000008bn,
3553
+ 0x8000000000008089n,
3554
+ 0x8000000000008003n,
3555
+ 0x8000000000008002n,
3556
+ 0x8000000000000080n,
3557
+ 0x000000000000800an,
3558
+ 0x800000008000000an,
3559
+ 0x8000000080008081n,
3560
+ 0x8000000000008080n,
3561
+ 0x0000000080000001n,
3562
+ 0x8000000080008008n
3563
+ ];
3564
+ var ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14];
3565
+ var MASK = (1n << 64n) - 1n;
3566
+ var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
3567
+ function keccakF(s) {
3568
+ for (let round = 0; round < 24; round++) {
3569
+ const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
3570
+ for (let x = 0; x < 5; x++) {
3571
+ const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
3572
+ for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
3573
+ }
3574
+ const b = new Array(25);
3575
+ for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(s[x + 5 * y], ROT[x + 5 * y]);
3576
+ for (let x = 0; x < 5; x++) for (let y = 0; y < 25; y += 5) s[y + x] = b[y + x] ^ ~b[y + (x + 1) % 5] & MASK & b[y + (x + 2) % 5];
3577
+ s[0] = s[0] ^ RC[round];
3578
+ }
3579
+ }
3580
+ function keccak256Hex(bytes) {
3581
+ const rate = 136;
3582
+ const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
3583
+ padded.set(bytes);
3584
+ padded[bytes.length] = padded[bytes.length] ^ 1;
3585
+ padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
3586
+ const s = new Array(25).fill(0n);
3587
+ for (let off = 0; off < padded.length; off += rate) {
3588
+ for (let i = 0; i < rate / 8; i++) {
3589
+ let lane = 0n;
3590
+ for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
3591
+ s[i] = s[i] ^ lane;
3592
+ }
3593
+ keccakF(s);
3594
+ }
3595
+ let out = "";
3596
+ for (let i = 0; i < 4; i++) for (let j = 0; j < 8; j++) out += Number(s[i] >> BigInt(8 * j) & 0xffn).toString(16).padStart(2, "0");
3597
+ return out;
3598
+ }
3599
+ function toChecksumAddress(address) {
3600
+ const lower3 = address.slice(2).toLowerCase();
3601
+ const hash2 = keccak256Hex(new TextEncoder().encode(lower3));
3602
+ let out = "0x";
3603
+ for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower3[i].toUpperCase() : lower3[i];
3604
+ return out;
3605
+ }
3606
+ function hasValidChecksum(address) {
3607
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
3608
+ const body = address.slice(2);
3609
+ if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
3610
+ return toChecksumAddress(address) === address;
3611
+ }
3612
+
3613
+ // src/core/zdheavy-codec.ts
3614
+ var concat = (parts) => "0x" + parts.map((p) => p.slice(2)).join("");
3615
+ var hexToBytes2 = (h2) => Uint8Array.from(h2.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
3616
+ var toBytes = (s) => new TextEncoder().encode(s);
3617
+ var toHex = (v, opts) => "0x" + (typeof v === "bigint" ? v.toString(16).padStart((opts?.size ?? 0) * 2, "0") : Array.from(v, (b) => b.toString(16).padStart(2, "0")).join(""));
3618
+ var keccak256 = (h2) => "0x" + keccak256Hex(hexToBytes2(h2));
3619
+ var STEP_VERSION = 5;
3620
+ var MAX_STEPS2 = 8;
3621
+ var StepKind = {
3622
+ LOCAL_PAYOUT: 1,
3623
+ REMOTE_PAYOUT: 2,
3624
+ SEND: 3,
3625
+ SWAP: 4,
3626
+ EXECUTE: 5,
3627
+ NET: 6,
3628
+ SUBSIDY: 7
3629
+ };
3630
+ var ZdHeavyCodecError = class extends Error {
3631
+ constructor(message) {
3632
+ super(message);
3633
+ this.name = "ZdHeavyCodecError";
3634
+ }
3635
+ };
3636
+ function checkedHex(value, length) {
3637
+ if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value) || length !== void 0 && value.length !== 2 + length * 2) {
3638
+ throw new ZdHeavyCodecError(`Expected ${length === void 0 ? "byte-aligned" : length + "-byte"} hex`);
3639
+ }
3640
+ return value.toLowerCase();
3641
+ }
3642
+ function uint(value, bytes) {
3643
+ if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bytes * 8)) {
3644
+ throw new ZdHeavyCodecError(`Value outside uint${bytes * 8}`);
3645
+ }
3646
+ return toHex(value, { size: bytes });
3647
+ }
3648
+ var Reader2 = class {
3649
+ bytes;
3650
+ offset = 0;
3651
+ constructor(step) {
3652
+ this.bytes = hexToBytes2(checkedHex(step));
3653
+ }
3654
+ take(n) {
3655
+ if (this.offset + n > this.bytes.length) throw new ZdHeavyCodecError("Short step");
3656
+ const result = this.bytes.slice(this.offset, this.offset + n);
3657
+ this.offset += n;
3658
+ return result;
3659
+ }
3660
+ hex(n) {
3661
+ return toHex(this.take(n));
3662
+ }
3663
+ uint(n) {
3664
+ let result = 0n;
3665
+ for (const byte of this.take(n)) result = result << 8n | BigInt(byte);
3666
+ return result;
3667
+ }
3668
+ number(n) {
3669
+ return Number(this.uint(n));
3670
+ }
3671
+ address() {
3672
+ const n = this.number(1);
3673
+ if (n === 0 || n > 64) throw new ZdHeavyCodecError("Address length must be 1..64");
3674
+ return this.hex(n);
3675
+ }
3676
+ bytes16() {
3677
+ return this.hex(this.number(2));
3678
+ }
3679
+ adapters() {
3680
+ const count = this.number(1);
3681
+ if (count > 8) throw new ZdHeavyCodecError("Too many bridge adapters");
3682
+ return Array.from({ length: count }, () => this.number(2));
3683
+ }
3684
+ end() {
3685
+ if (this.offset !== this.bytes.length) throw new ZdHeavyCodecError("Trailing step bytes");
3686
+ }
3687
+ };
3688
+ function decodeStep(step) {
3689
+ const r = new Reader2(step);
3690
+ if (r.number(1) !== STEP_VERSION) throw new ZdHeavyCodecError("Unsupported step version");
3691
+ const kind = r.number(2);
3692
+ if (kind < 1 || kind > 7) throw new ZdHeavyCodecError("Unknown step kind");
3693
+ const chainId = r.uint(8);
3694
+ const count = r.number(1);
3695
+ if (kind !== StepKind.SWAP && count !== 0) throw new ZdHeavyCodecError("Unexpected allowances");
3696
+ const allowances = Array.from({ length: count }, () => ({
3697
+ pathwayId: r.number(1),
3698
+ maxShareBps: r.number(2),
3699
+ params: r.bytes16()
3700
+ }));
3701
+ const base = { chainId, allowances };
3702
+ let result;
3703
+ switch (kind) {
3704
+ case StepKind.LOCAL_PAYOUT:
3705
+ result = { ...base, kind: "LOCAL_PAYOUT", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16) };
3706
+ break;
3707
+ case StepKind.REMOTE_PAYOUT:
3708
+ result = {
3709
+ ...base,
3710
+ kind: "REMOTE_PAYOUT",
3711
+ token: r.address(),
3712
+ receiverChainId: r.uint(8),
3713
+ receiver: r.address(),
3714
+ bridgeAdapters: r.adapters(),
3715
+ maxFee: r.uint(16),
3716
+ minAmountOut: r.uint(16)
3717
+ };
3718
+ break;
3719
+ case StepKind.SEND:
3720
+ result = {
3721
+ ...base,
3722
+ kind: "SEND",
3723
+ token: r.address(),
3724
+ dstChainId: r.uint(8),
3725
+ bridgeAdapters: r.adapters(),
3726
+ maxFee: r.uint(16),
3727
+ inUnit: r.uint(16),
3728
+ outUnit: r.uint(16)
3729
+ };
3730
+ break;
3731
+ case StepKind.SWAP:
3732
+ result = { ...base, kind: "SWAP", tokenIn: r.address(), tokenOut: r.address(), expectedIn: r.uint(16), minOut: r.uint(16) };
3733
+ break;
3734
+ case StepKind.EXECUTE:
3735
+ result = { ...base, kind: "EXECUTE", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16), gasLimit: r.uint(8), data: r.bytes16() };
3736
+ break;
3737
+ case StepKind.NET: {
3738
+ const token = r.address(), pathwayId = r.number(1), arriveStep = r.number(1);
3739
+ const params = r.hex(78);
3740
+ const t = new Reader2(params);
3741
+ const terms = {
3742
+ nettingDeadline: t.uint(8),
3743
+ dstDomain: t.number(4),
3744
+ dstAsset: t.hex(32),
3745
+ inUnit: t.uint(16),
3746
+ outUnit: t.uint(16),
3747
+ complianceClass: t.number(2)
3748
+ };
3749
+ result = { chainId, allowances: [{ pathwayId, maxShareBps: 0, params }], kind: "NET", token, pathwayId, arriveStep, terms };
3750
+ break;
3751
+ }
3752
+ case StepKind.SUBSIDY:
3753
+ result = { ...base, kind: "SUBSIDY", token: r.address(), minIn: r.uint(16), amountOut: r.uint(16) };
3754
+ break;
3755
+ default:
3756
+ throw new ZdHeavyCodecError("Unknown step kind");
3757
+ }
3758
+ r.end();
3759
+ return result;
3760
+ }
3761
+ function routerWord(addr) {
3762
+ return concat([toHex(new Uint8Array(12)), checkedHex(addr, 20)]);
3763
+ }
3764
+ function ownerWord(addr) {
3765
+ return routerWord(addr);
3766
+ }
3767
+ function encodeOrderHeader(serial, router, ownerType, owner) {
3768
+ if (!Number.isInteger(ownerType) || ownerType < 0 || ownerType > 255) throw new ZdHeavyCodecError("Invalid ownerType");
3769
+ return concat(["0x050000", uint(serial, 8), routerWord(router), uint(BigInt(ownerType), 1), checkedHex(owner, 32)]);
3770
+ }
3771
+ function orderIdOf(expiryDate, header, steps) {
3772
+ if (steps.length < 1 || steps.length > MAX_STEPS2) throw new ZdHeavyCodecError("Step count must be 1..8");
3773
+ return keccak256(
3774
+ concat([toHex(toBytes("ZD/ORDER")), uint(expiryDate, 8), keccak256(checkedHex(header)), ...steps.map((step) => keccak256(checkedHex(step)))])
3775
+ );
3776
+ }
3777
+ var ZDHEAVY_SUBMIT_SELECTOR = "0x1a579a0c";
3778
+ var ZDHEAVY_PARTNER_SUBMIT_SELECTOR = "0xdd3d9749";
3779
+ var ZDHEAVY_QUOTE_SELECTOR = "0x3cfc3141";
3780
+ function decodeZdHeavySubmit(data) {
3781
+ const hex = checkedHex(data);
3782
+ const selector = hex.slice(0, 10);
3783
+ if (selector !== ZDHEAVY_SUBMIT_SELECTOR && selector !== ZDHEAVY_PARTNER_SUBMIT_SELECTOR) {
3784
+ throw new ZdHeavyCodecError("Expected submitOrder");
3785
+ }
3786
+ const body = hex.slice(10);
3787
+ const size = body.length / 2;
3788
+ const fail = () => {
3789
+ throw new ZdHeavyCodecError("Invalid submitOrder calldata");
3790
+ };
3791
+ const word2 = (at, bits = 256) => {
3792
+ if (!Number.isSafeInteger(at) || at < 0 || at + 32 > size) return fail();
3793
+ const n2 = BigInt(`0x${body.slice(at * 2, (at + 32) * 2)}`);
3794
+ if (n2 >= 1n << BigInt(bits)) return fail();
3795
+ return n2;
3796
+ };
3797
+ const fixed = (at) => {
3798
+ word2(at);
3799
+ return `0x${body.slice(at * 2, (at + 32) * 2)}`;
3800
+ };
3801
+ const offset = (at, expected) => {
3802
+ if (word2(at) !== BigInt(expected)) fail();
3803
+ };
3804
+ const bytes = (at) => {
3805
+ const n2 = word2(at);
3806
+ if (n2 > BigInt(size - at - 32)) return fail();
3807
+ const length = Number(n2);
3808
+ const end = at + 32 + Math.ceil(length / 32) * 32;
3809
+ if (end > size || /[^0]/.test(body.slice((at + 32 + length) * 2, end * 2))) return fail();
3810
+ return { value: `0x${body.slice((at + 32) * 2, (at + 32 + length) * 2)}`, end };
3811
+ };
3812
+ const base = selector === ZDHEAVY_SUBMIT_SELECTOR ? 32 : 64;
3813
+ offset(0, base);
3814
+ const partnerId = base === 64 ? fixed(32) : null;
3815
+ const serial = word2(base, 64);
3816
+ const ownerType = Number(word2(base + 32, 8));
3817
+ const owner = fixed(base + 64);
3818
+ const expiryDate = word2(base + 160, 64);
3819
+ offset(base + 96, 224);
3820
+ const ownerSignature = bytes(base + 224);
3821
+ offset(base + 128, ownerSignature.end - base);
3822
+ const array = ownerSignature.end;
3823
+ const count = word2(array);
3824
+ if (count > BigInt(Math.floor((size - array - 32) / 32))) return fail();
3825
+ const n = Number(count);
3826
+ const arrayBase = array + 32;
3827
+ let next = arrayBase + n * 32;
3828
+ const steps = [];
3829
+ for (let i = 0; i < n; i++) {
3830
+ offset(arrayBase + i * 32, next - arrayBase);
3831
+ const step = bytes(next);
3832
+ steps.push(step.value);
3833
+ next = step.end;
3834
+ }
3835
+ offset(base + 192, next - base);
3836
+ const q = next;
3837
+ const amountIn = word2(q, 128);
3838
+ const fee = { input: word2(q + 32, 128), native: word2(q + 64, 128) };
3839
+ const quoteId = fixed(q + 96);
3840
+ const requestId = fixed(q + 128);
3841
+ const expiresAt = word2(q + 160, 64);
3842
+ offset(q + 192, 224);
3843
+ const signature = bytes(q + 224);
3844
+ if (signature.end !== size) return fail();
3845
+ return {
3846
+ submission: {
3847
+ serial,
3848
+ ownerType,
3849
+ owner,
3850
+ ownerSignature: ownerSignature.value,
3851
+ steps,
3852
+ expiryDate,
3853
+ quote: { amountIn, fee, quoteId, requestId, expiresAt, signature: signature.value }
3854
+ },
3855
+ partnerId
3856
+ };
3857
+ }
3858
+ function quoteSubmitCalldata(data) {
3859
+ decodeZdHeavySubmit(data);
3860
+ const tuple = data.slice(data.slice(0, 10).toLowerCase() === ZDHEAVY_SUBMIT_SELECTOR ? 74 : 138);
3861
+ return `${ZDHEAVY_QUOTE_SELECTOR}${uintWord(32)}${tuple}`;
3862
+ }
3863
+
3864
+ // src/core/zdheavy-check.ts
3865
+ var isAddress2 = hasValidChecksum;
3866
+ var getAddress = (s) => toChecksumAddress(s);
3867
+ var refuse = (what) => ({
3868
+ ok: false,
3869
+ reason: `The ZD Heavy order the gateway built does not match the order shown (${what}) \u2014 refusing to sign.`
3870
+ });
3871
+ var lower = (v) => typeof v === "string" ? v.toLowerCase() : "";
3872
+ function big2(v) {
3873
+ if (v === void 0 || v === null || v === "") return null;
3874
+ try {
3875
+ return BigInt(v);
3876
+ } catch {
3877
+ return null;
3878
+ }
3879
+ }
3880
+ var sameBig = (a, b) => big2(b) === a;
3881
+ var sameAddr = (a, b) => !!b && lower(a) === lower(b);
3882
+ function checkZdHeavyRouter(chainId, router) {
3883
+ if (!router || !isAddress2(router)) return { ok: false, reason: "No valid ZD Heavy router address for this chain \u2014 refusing to sign." };
3884
+ const address = getAddress(router);
3885
+ const pinned = (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).map((a) => getAddress(a));
3886
+ if (!pinned.includes(address)) {
3887
+ return { ok: false, reason: `Router ${address} is not a trusted ZD Heavy router on this chain \u2014 refusing to sign.` };
3888
+ }
3889
+ return { ok: true, address };
3890
+ }
3891
+ function checkZdHeavyValue(txValue, quotedSubmit) {
3892
+ if (quotedSubmit === void 0) return { ok: false, reason: "The router\u2019s submit fee could not be read \u2014 refusing to sign." };
3893
+ if (big2(txValue) !== quotedSubmit) return { ok: false, reason: "The transaction carries a native value the router did not quote \u2014 refusing to sign." };
3894
+ return { ok: true };
3895
+ }
3896
+ function sameAllowances(d, j) {
3897
+ if (d.kind !== "SWAP") return true;
3898
+ const want = j.allowances ?? [];
3899
+ if (want.length !== d.allowances.length) return false;
3900
+ return d.allowances.every((a, i) => {
3901
+ const w = want[i];
3902
+ return a.pathwayId === w.pathwayId && a.maxShareBps === w.maxShareBps && lower(a.params) === lower(w.params && w.params !== "" ? w.params : "0x");
3903
+ });
3904
+ }
3905
+ function sameAdapters(a, b) {
3906
+ const w = b ?? [];
3907
+ return a.length === w.length && a.every((x, i) => x === w[i]);
3908
+ }
3909
+ function sameStep(d, j) {
3910
+ if (d.kind !== String(j.kind).toUpperCase()) return false;
3911
+ if (!sameBig(d.chainId, j.chainId)) return false;
3912
+ if (!sameAllowances(d, j)) return false;
3913
+ switch (d.kind) {
3914
+ case "SWAP":
3915
+ return sameAddr(d.tokenIn, j.tokenIn) && sameAddr(d.tokenOut, j.tokenOut) && sameBig(d.expectedIn, j.expectedIn) && sameBig(d.minOut, j.minOut);
3916
+ case "LOCAL_PAYOUT":
3917
+ return sameAddr(d.token, j.token) && sameAddr(d.receiver, j.receiver) && sameBig(d.minAmountOut, j.minAmountOut);
3918
+ case "REMOTE_PAYOUT":
3919
+ return sameAddr(d.token, j.token) && sameBig(d.receiverChainId, j.receiverChainId) && sameAddr(d.receiver, j.receiver) && sameAdapters(d.bridgeAdapters, j.bridgeAdapters) && sameBig(d.maxFee, j.maxFee) && sameBig(d.minAmountOut, j.minAmountOut);
3920
+ case "SEND":
3921
+ return sameAddr(d.token, j.token) && sameBig(d.dstChainId, j.dstChainId) && sameAdapters(d.bridgeAdapters, j.bridgeAdapters) && sameBig(d.maxFee, j.maxFee) && sameBig(d.inUnit, j.inUnit) && sameBig(d.outUnit, j.outUnit);
3922
+ case "SUBSIDY":
3923
+ return sameAddr(d.token, j.token) && sameBig(d.minIn, j.minIn) && sameBig(d.amountOut, j.amountOut);
3924
+ case "NET": {
3925
+ const t = j.terms;
3926
+ if (!t) return false;
3927
+ const domainOfAsset = Number(BigInt(t.dstAsset) >> 224n);
3928
+ return sameAddr(d.token, j.token) && d.pathwayId === j.pathwayId && d.arriveStep === j.arriveStep && sameBig(d.terms.nettingDeadline, t.nettingDeadline) && d.terms.dstDomain === domainOfAsset && lower(d.terms.dstAsset) === lower(t.dstAsset) && sameBig(d.terms.inUnit, t.inUnit) && sameBig(d.terms.outUnit, t.outUnit);
3929
+ }
3930
+ default:
3931
+ return false;
3932
+ }
3933
+ }
3934
+ function checkSubmit(tx, e) {
3935
+ if (tx.chainId !== String(e.chainId)) return refuse("chain");
3936
+ if (!sameAddr(e.router, tx.to)) return refuse("router");
3937
+ let decoded;
3938
+ try {
3939
+ decoded = decodeZdHeavySubmit(tx.data);
3940
+ } catch {
3941
+ return refuse("not a router submitOrder");
3942
+ }
3943
+ const { submission: s, partnerId } = decoded;
3944
+ const order = e.order;
3945
+ if (!order) return refuse("no order");
3946
+ const wantPartner = typeof e.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(e.partnerId) ? lower(e.partnerId) : null;
3947
+ if ((partnerId ? lower(partnerId) : null) !== wantPartner) return refuse("partner id");
3948
+ if (!isAddress2(e.owner)) return refuse("owner");
3949
+ if (s.ownerType !== 1 || lower(s.owner) !== lower(ownerWord(e.owner))) return refuse("owner");
3950
+ if (s.ownerSignature !== "0x") return refuse("owner signature");
3951
+ if (!s.quote.signature || s.quote.signature === "0x") return refuse("no API signature");
3952
+ if (order.chainNumber !== e.chainId || !sameAddr(e.router, order.router)) return refuse("router");
3953
+ if (s.steps.length < 1 || s.steps.length > MAX_STEPS2 || s.steps.length !== order.steps.length) return refuse("number of steps");
3954
+ const steps = [];
3955
+ for (let i = 0; i < s.steps.length; i++) {
3956
+ let d;
3957
+ try {
3958
+ d = decodeStep(s.steps[i]);
3959
+ } catch {
3960
+ return refuse(`step ${i} encoding`);
3961
+ }
3962
+ if (d.kind === "EXECUTE") return refuse(`step ${i} kind EXECUTE`);
3963
+ if (!sameStep(d, order.steps[i])) return refuse(`step ${i}`);
3964
+ steps.push(d);
3965
+ }
3966
+ const first = steps[0];
3967
+ if (first.chainId !== BigInt(e.chainId)) return refuse("source chain");
3968
+ const firstToken = first.kind === "SWAP" ? first.tokenIn : "token" in first ? first.token : "";
3969
+ if (!sameAddr(e.fromToken, firstToken) || !sameAddr(e.fromToken, order.tokenIn)) return refuse("source token");
3970
+ const last = steps[steps.length - 1];
3971
+ if (steps.slice(0, -1).some((d) => d.kind === "LOCAL_PAYOUT" || d.kind === "REMOTE_PAYOUT")) return refuse("payout before the last step");
3972
+ if (last.kind !== "LOCAL_PAYOUT" && last.kind !== "REMOTE_PAYOUT") return refuse("no payout");
3973
+ const deliveryChain = last.kind === "LOCAL_PAYOUT" ? last.chainId : last.receiverChainId;
3974
+ if (deliveryChain !== BigInt(e.toChainId)) return refuse("destination chain");
3975
+ if (last.kind === "LOCAL_PAYOUT") {
3976
+ if (!sameAddr(e.toToken, last.token)) return refuse("destination token");
3977
+ } else {
3978
+ if (!e.remotePayoutToken?.(last.token, Number(last.chainId))) return refuse("destination token of a cross-chain payout");
3979
+ }
3980
+ if (!sameAddr(e.receiver, last.receiver)) return refuse("receiver");
3981
+ const amountIn = big2(order.amountIn);
3982
+ const feeInput = big2(order.fee.input);
3983
+ const feeNative = big2(order.fee.native);
3984
+ if (amountIn === null || feeInput === null || feeNative === null) return refuse("amount");
3985
+ if (s.quote.amountIn !== amountIn || s.quote.fee.input !== feeInput || s.quote.fee.native !== feeNative) return refuse("amount");
3986
+ if (amountIn + feeInput !== e.amountRaw || big2(order.grossIn) !== e.amountRaw) return refuse("amount");
3987
+ if (s.expiryDate !== BigInt(order.expiryDate) || s.quote.expiresAt !== BigInt(order.expiresAt)) return refuse("expiry");
3988
+ if (s.expiryDate <= BigInt(e.nowSec) || s.quote.expiresAt <= BigInt(e.nowSec)) return refuse("expired");
3989
+ if (last.kind === "REMOTE_PAYOUT" && last.maxFee >= last.minAmountOut) return refuse("minimum out");
3990
+ const floor = last.kind === "REMOTE_PAYOUT" ? last.minAmountOut - last.maxFee : last.minAmountOut;
3991
+ if (floor <= 0n || floor !== e.finalAmount) return refuse("minimum out");
3992
+ let orderId;
3993
+ try {
3994
+ orderId = orderIdOf(s.expiryDate, encodeOrderHeader(s.serial, getAddress(e.router), 1, s.owner), s.steps);
3995
+ } catch {
3996
+ return refuse("order id");
3997
+ }
3998
+ if (!e.rootHash || lower(orderId) !== lower(e.rootHash)) return refuse("order id");
3999
+ return { ok: true, floor, orderId };
4000
+ }
4001
+ function checkZdHeavySubmit(tx, e) {
4002
+ try {
4003
+ return checkSubmit(tx, e);
4004
+ } catch {
4005
+ return refuse("malformed order");
4006
+ }
4007
+ }
4008
+
4009
+ // src/core/asset-identity.ts
4010
+ function key(chainId, address) {
4011
+ const id = Number(chainId);
4012
+ return Number.isSafeInteger(id) && id > 0 && typeof address === "string" && isChainAddress(id, address) ? tokenKey(id, address) : null;
4013
+ }
4014
+ function sameAssetDeployment(tokens, routes, a, b) {
4015
+ const ka = key(a.chainId, a.address);
4016
+ const kb = key(b.chainId, b.address);
4017
+ if (!ka || !kb) return false;
4018
+ const parent = /* @__PURE__ */ new Map();
4019
+ const find = (k) => {
4020
+ const p = parent.get(k);
4021
+ if (p === void 0) {
4022
+ parent.set(k, k);
4023
+ return k;
4024
+ }
4025
+ if (p === k) return k;
4026
+ const root = find(p);
4027
+ parent.set(k, root);
4028
+ return root;
4029
+ };
4030
+ const join = (x, y) => {
4031
+ if (x && y) parent.set(find(y), find(x));
4032
+ };
4033
+ for (const r of routes) {
4034
+ if (r.isEnabled === false) continue;
4035
+ const from = key(r.fromChainId, r.fromAddress);
4036
+ const to = key(r.toChainId, r.toAddress);
4037
+ join(from, to);
4038
+ const home = key(r.homeChainId, r.homeTokenAddress);
4039
+ join(from, home);
4040
+ join(to, home);
4041
+ }
4042
+ for (const t of tokens) join(key(t.chainId, t.address), key(t.homeChainId, t.homeTokenAddress));
4043
+ return parent.has(ka) && parent.has(kb) && find(ka) === find(kb);
4044
+ }
4045
+
4046
+ // src/core/validate-tx.ts
4047
+ var lower2 = (v) => String(v || "").toLowerCase();
4048
+ function isHexAddress(value) {
4049
+ return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
4050
+ }
4051
+ function isHexData(value) {
4052
+ return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value || "0x"));
4053
+ }
4054
+ function isHexQuantity(value) {
4055
+ return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
4056
+ }
4057
+ function dataWord(data, index) {
4058
+ const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4059
+ return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
4060
+ }
4061
+ function dataAddress(data, index) {
4062
+ const word2 = dataWord(data, index);
4063
+ return word2 ? `0x${word2.slice(24)}` : "";
4064
+ }
4065
+ function dataUint(data, index) {
4066
+ const word2 = dataWord(data, index);
4067
+ return word2 ? BigInt(`0x${word2}`) : null;
4068
+ }
4069
+ function rawEquals(value, expected) {
4070
+ try {
4071
+ return value === BigInt(expected || "0");
4072
+ } catch {
4073
+ return false;
4074
+ }
4075
+ }
4076
+ function planMsgValueHex(route) {
4077
+ try {
4078
+ const raw2 = route?.quote?.msgValue;
4079
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4080
+ return "0x" + BigInt(raw2).toString(16);
4081
+ } catch {
4082
+ return null;
4083
+ }
4084
+ }
4085
+ function validatePlannedTransaction(tx, route, expectedRecipient, heavyExpected) {
4086
+ if (!tx || tx.mock) return true;
4087
+ if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
4088
+ const data = String(tx.data || "0x").toLowerCase();
4089
+ const selector = data.slice(0, 10);
4090
+ const value = lower2(tx.value || "0x0");
4091
+ if (tx.kind === "transfer") {
4092
+ if (value !== "0x0") return false;
4093
+ return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower2(tx.to) === lower2(tx.token) && lower2(dataAddress(data, 0)) === lower2(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4094
+ }
4095
+ if (tx.kind === "approve") {
4096
+ if (route.zdHeavy) {
4097
+ return !!heavyExpected && tx.chainId === heavyExpected.chainId && lower2(tx.to) === lower2(heavyExpected.fromToken) && lower2(data) === lower2(encodeApprove(heavyExpected.router, heavyExpected.amountRaw)) && BigInt(value) === 0n;
4098
+ }
4099
+ if (value !== "0x0") return false;
4100
+ return selector === "0x095ea7b3" && isHexAddress(tx.token) && isHexAddress(tx.spender) && lower2(tx.to) === lower2(tx.token) && lower2(dataAddress(data, 0)) === lower2(tx.spender) && rawEquals(dataUint(data, 1), tx.amountRaw);
4101
+ }
4102
+ if (tx.kind === "submitOrder") {
4103
+ if (route.zdHeavy) {
4104
+ const expectedValue = planMsgValueHex(route);
4105
+ return expectedValue !== null && value === lower2(expectedValue) && !!heavyExpected && checkZdHeavySubmit({ ...tx, chainId: String(tx.chainId) }, heavyExpected).ok;
4106
+ }
4107
+ const expected = planMsgValueHex(route);
4108
+ if (expected === null || value !== lower2(expected)) return false;
4109
+ if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower2(tx.to) !== lower2(tx.escrow)) return false;
4110
+ const decoded = decodeSubmitOrderCalldata(data);
4111
+ if (!decoded) return false;
4112
+ const first = decoded.orders[0];
4113
+ const last = decoded.orders[decoded.orders.length - 1];
4114
+ return decoded.partnerId === lower2(route.quote?.partnerId || NO_PARTNER_ID) && lower2(first.bidToken) === lower2(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower2(last.askToken) === lower2(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) : lower2(last.destinationReceiver) === lower2(expectedRecipient));
4115
+ }
4116
+ return false;
4117
+ }
4118
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
4119
+ try {
4120
+ return lower2(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4121
+ } catch {
4122
+ return false;
4123
+ }
4124
+ }
4125
+ async function allowanceCovers(tx, account, ethCall2) {
4126
+ if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4127
+ try {
4128
+ const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
4129
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4130
+ } catch {
4131
+ return false;
4132
+ }
4133
+ }
4134
+
4135
+ // src/core/zdheavy-route.ts
4136
+ function zdHeavyExpected(route, owner, receiver, tokens, routes) {
4137
+ const heavy = route.zdHeavy;
4138
+ if (!heavy) throw new Error("Missing ZD Heavy order.");
4139
+ const pin2 = checkZdHeavyRouter(route.source.chainId, heavy.order.router);
4140
+ if (!pin2.ok) throw new Error(pin2.reason);
4141
+ if (route.source.amount !== formatUnits(heavy.amountRaw, route.source.decimals) || route.source.payAmount !== route.source.amount || route.receive.amount !== formatUnits(heavy.finalAmount, route.receive.decimals))
4142
+ throw new Error("ZD Heavy display amount mismatch.");
4143
+ return {
4144
+ chainId: route.source.chainId,
4145
+ router: pin2.address,
4146
+ owner,
4147
+ receiver,
4148
+ fromToken: route.source.tokenAddress,
4149
+ toToken: route.receive.tokenAddress,
4150
+ toChainId: route.receive.chainId,
4151
+ amountRaw: BigInt(heavy.amountRaw),
4152
+ finalAmount: BigInt(heavy.finalAmount),
4153
+ order: heavy.order,
4154
+ rootHash: heavy.rootHash,
4155
+ partnerId: route.quote.partnerId,
4156
+ nowSec: Math.floor(Date.now() / 1e3),
4157
+ remotePayoutToken: (token, chainId) => sameAssetDeployment(tokens, routes, { chainId, address: token }, { chainId: route.receive.chainId, address: route.receive.tokenAddress })
4158
+ };
4159
+ }
4160
+ function validateZdHeavyPlan(route, expected) {
4161
+ if (route.transactions.length !== 2 || route.transactions[0].kind !== "approve" || route.transactions[1].kind !== "submitOrder") {
4162
+ throw new Error("ZD Heavy requires exactly approve then submitOrder; refusing to sign.");
4163
+ }
4164
+ for (const tx of route.transactions) {
4165
+ if (tx.mock || tx.chainId !== expected.chainId || !validatePlannedTransaction(tx, route, expected.receiver, expected)) {
4166
+ throw new Error("ZD Heavy transaction does not match the reviewed plan; refusing to sign.");
4167
+ }
4168
+ }
4169
+ const submit = route.transactions[1];
4170
+ const checked = checkZdHeavySubmit({ ...submit, chainId: String(submit.chainId) }, expected);
4171
+ if (!checked.ok) throw new Error(checked.reason);
4172
+ return checked.floor;
4173
+ }
4174
+ async function preflightZdHeavyPlan(route, expected, readFee) {
4175
+ validateZdHeavyPlan(route, expected);
4176
+ const tx = route.transactions[1];
4177
+ const value = checkZdHeavyValue(tx.value, await readFee(expected.chainId, expected.router, tx.data));
4178
+ if (!value.ok) throw new Error(value.reason);
4179
+ }
4180
+
4181
+ // src/core/zdheavy-build.ts
4182
+ function buildZdHeavyRoute(ctx) {
4183
+ const { option, destination, destinationToken, chains, result } = ctx;
4184
+ const q = result.quote;
4185
+ if (!zdHeavyExecutable(q)) throw new Error("ZD Heavy quote is not signed and executable.");
4186
+ const order = q.execution.order;
4187
+ const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
4188
+ const decimals = assetDecimals(destinationToken);
4189
+ const receiveAmount = formatUnits(result.recipientReceivesRaw, decimals);
4190
+ const partnerId = typeof q.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(q.partnerId) ? q.partnerId : void 0;
4191
+ const route = {
4192
+ id: `zdh-${option.chainId}-${option.symbolKey}-${destination.chainId}-${destinationToken.symbol}`,
4193
+ recommended: false,
4194
+ state: result.meetsTarget ? "ROUTE" : "SHORT",
4195
+ source: {
4196
+ asset: option.symbol,
4197
+ ticker: option.ticker || option.symbol,
4198
+ chainId: option.chainId,
4199
+ chainName: option.chainName,
4200
+ tokenAddress: option.address,
4201
+ decimals: option.decimals,
4202
+ amount: sourceAmount,
4203
+ payAmount: sourceAmount
4204
+ },
4205
+ receive: {
4206
+ asset: destinationToken.symbol,
4207
+ ticker: tokenTicker(destinationToken),
4208
+ chainId: Number(destination.chainId),
4209
+ chainName: chainNameOf(Number(destination.chainId), chains),
4210
+ tokenAddress: destinationToken.address,
4211
+ decimals,
4212
+ amount: receiveAmount
4213
+ },
4214
+ routeLabel: "Settle on ZeroDelta via ZD Heavy.",
4215
+ deltaLabel: result.meetsTarget ? "~0" : "Below requested amount",
4216
+ legs: [
4217
+ {
4218
+ index: 1,
4219
+ fromAsset: option.symbol,
4220
+ fromTicker: option.ticker || option.symbol,
4221
+ fromChainId: option.chainId,
4222
+ fromChainName: option.chainName,
4223
+ fromAmount: sourceAmount,
4224
+ toAsset: destinationToken.symbol,
4225
+ toTicker: tokenTicker(destinationToken),
4226
+ toChainId: Number(destination.chainId),
4227
+ toChainName: chainNameOf(Number(destination.chainId), chains),
4228
+ toAmount: receiveAmount,
4229
+ executionChainId: option.chainId,
4230
+ executionChainName: option.chainName
4231
+ }
4232
+ ],
4233
+ transactions: q.txData.map((tx, i) => {
4234
+ const submit = tx.actionType === "submit" || tx.actionType === "submitOrder";
4235
+ if (tx.actionType !== "approve" && !submit) throw new Error("Unexpected ZD Heavy transaction action.");
4236
+ if (typeof tx.value !== "string" || !/^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(tx.value)) throw new Error("Invalid ZD Heavy native value.");
4237
+ return {
4238
+ id: submit ? "submit-order" : `approve-${i}`,
4239
+ kind: submit ? "submitOrder" : "approve",
4240
+ label: submit ? "Submit ZeroDelta order" : `Approve ${option.ticker || option.symbol}`,
4241
+ chainId: Number(tx.chainId),
4242
+ to: tx.to,
4243
+ data: tx.data,
4244
+ // The gateway publishes decimal wei; EIP-1193 requires a hex quantity.
4245
+ // Calldata and targets remain the gateway's exact bytes.
4246
+ value: toHexQuantity(tx.value),
4247
+ token: option.address,
4248
+ spender: order.router,
4249
+ amountRaw: result.youPayRaw
4250
+ };
4251
+ }),
4252
+ quote: {
4253
+ bridge: q.bridge,
4254
+ feeBps: q.feeBps,
4255
+ estimatedDuration: q.estimatedDuration,
4256
+ gasCostSource: q.gasCostSource,
4257
+ iterations: result.iterations,
4258
+ compliance: q.compliance,
4259
+ partnerId,
4260
+ zeroDeltaFeeCentibips: q.zeroDeltaFeeCentibips,
4261
+ zeroDeltaFeeNative: q.zeroDeltaFeeNative
4262
+ },
4263
+ zdHeavy: { order, rootHash: q.rootHash, amountRaw: result.youPayRaw, finalAmount: result.recipientReceivesRaw, floor: "" }
4264
+ };
4265
+ if (route.transactions.length === 2) route.quote.msgValue = BigInt(route.transactions[1].value).toString();
4266
+ const expected = zdHeavyExpected(route, ctx.payer, destination.address, ctx.tokens, ctx.routes);
4267
+ route.zdHeavy.floor = validateZdHeavyPlan(route, expected).toString();
4268
+ return route;
4269
+ }
4270
+
4271
+ // src/core/quote-compare.ts
4272
+ var WAIT_MIN_SEC = 180;
4273
+ var WAIT_MAX_SEC = 7200;
4274
+ function clampWait(sec) {
4275
+ if (!Number.isFinite(sec)) return WAIT_MIN_SEC;
4276
+ return Math.min(WAIT_MAX_SEC, Math.max(WAIT_MIN_SEC, sec));
4277
+ }
4278
+ var hasTime = (o) => Number.isFinite(o.estimatedDuration) && o.estimatedDuration > 0;
4279
+ function selectableOptions(options) {
4280
+ return options.filter((o) => !o.unavailable);
4281
+ }
4282
+ function bestOutputOption(options) {
4283
+ return selectableOptions(options).reduce((best, o) => !best || o.amount > best.amount ? o : best, void 0);
4284
+ }
4285
+ function fastestOption(options) {
4286
+ const selectable = selectableOptions(options);
4287
+ const labelled = selectable.find((o) => o.label?.toLowerCase() === "fastest");
4288
+ if (labelled) return labelled;
4289
+ return selectable.filter(hasTime).reduce((f, o) => !f || o.estimatedDuration < f.estimatedDuration ? o : f, void 0);
4290
+ }
4291
+ function proposedWait(options) {
4292
+ const best = bestOutputOption(options);
4293
+ return clampWait(best && hasTime(best) ? best.estimatedDuration : WAIT_MIN_SEC);
4294
+ }
4295
+ function pickForWait(options, waitSec) {
4296
+ const within = selectableOptions(options).filter((o) => hasTime(o) && o.estimatedDuration <= waitSec);
4297
+ return bestOutputOption(within) ?? fastestOption(options);
4298
+ }
4299
+ var MAX_QUOTE_CARDS = 3;
4300
+ function visibleOptions(options, waitSec, selectedId) {
4301
+ if (options.length <= MAX_QUOTE_CARDS) return [...options];
4302
+ const selectable = selectableOptions(options);
4303
+ if (selectable.length === 0) return options.slice(0, MAX_QUOTE_CARDS);
4304
+ const chosen = selectable.find((o) => o.id === selectedId) ?? pickForWait(options, waitSec);
4305
+ const gasless = bestOutputOption(selectable.filter((o) => o.gasSponsored));
4306
+ const netting = bestOutputOption(selectable.filter((o) => o.entersNetting));
4307
+ const ids = new Set([chosen?.id, fastestOption(options)?.id, gasless?.id, netting?.id].filter((id) => !!id));
4308
+ const keep = new Set([...ids].slice(0, MAX_QUOTE_CARDS));
4309
+ return options.filter((o) => keep.has(o.id));
4310
+ }
4311
+ function parity(options, inputUsd, toUnitUsd) {
4312
+ const priced = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
4313
+ if (!priced(inputUsd) || !priced(toUnitUsd)) return { kind: "unknown" };
4314
+ const reaching = selectableOptions(options).filter((o) => hasTime(o) && o.amount * toUnitUsd >= inputUsd);
4315
+ const earliest = reaching.reduce(
4316
+ (e, o) => !e || o.estimatedDuration < e.estimatedDuration || o.estimatedDuration === e.estimatedDuration && o.amount > e.amount ? o : e,
4317
+ void 0
4318
+ );
4319
+ return earliest ? { kind: "at", option: earliest, timeSec: earliest.estimatedDuration } : { kind: "unavailable" };
4320
+ }
4321
+ function extraVsFastest(options, selectedId) {
4322
+ const selected = selectableOptions(options).find((o) => o.id === selectedId);
4323
+ const fastest = fastestOption(options);
4324
+ if (!selected || !fastest) return null;
4325
+ const extra = selected.amount - fastest.amount;
4326
+ return extra > 1e-9 ? extra : null;
4327
+ }
4328
+ function routeBadges(options) {
4329
+ const field = options.filter((o) => !o.unavailable);
4330
+ const out = /* @__PURE__ */ new Map();
4331
+ if (field.length < 2) return out;
4332
+ const best = (pick, better) => field.reduce((acc, o) => {
4333
+ const value = pick(o);
4334
+ if (value === null) return acc;
4335
+ const accValue = acc ? pick(acc) : null;
4336
+ return accValue === null || better(value, accValue) ? o : acc;
4337
+ }, null);
4338
+ const bestReturn = best(
4339
+ (o) => o.amount,
4340
+ (a, b) => a > b
4341
+ );
4342
+ const fastest = best(
4343
+ (o) => o.estimatedDuration,
4344
+ (a, b) => a < b
4345
+ );
4346
+ const lowestFee = best(
4347
+ (o) => o.feeUsd,
4348
+ (a, b) => a < b
4349
+ );
4350
+ if (bestReturn) out.set(bestReturn.id, "Best return");
4351
+ if (fastest && !out.has(fastest.id)) out.set(fastest.id, "Fastest");
4352
+ if (lowestFee && !out.has(lowestFee.id)) out.set(lowestFee.id, "Lowest fee");
4353
+ return out;
4354
+ }
4355
+ function routeShapeLabel(option) {
4356
+ if (!option) return null;
4357
+ if (option.kind === "transfer") return "Transfer";
4358
+ const middle = option.hops.slice(1, -1);
4359
+ if (middle.length === 0) return "Direct";
4360
+ return `Via ${middle.map((h2) => h2.ticker).join(" \xB7 ")}`;
4361
+ }
4362
+ function cornerTags(options, option, parityState) {
4363
+ if (option.unavailable) return [];
4364
+ if (option.kind === "transfer") return [{ text: "Transfer", tone: "brand" }];
4365
+ const tags = [];
4366
+ const labelledFastest = selectableOptions(options).some((o) => o.label?.toLowerCase() === "fastest");
4367
+ if (parityState.kind === "at" && parityState.option.id === option.id) tags.push({ text: "Target 1:1", tone: "brand" });
4368
+ else if (option.entersNetting) tags.push({ text: "Potential best return", tone: "brand" });
4369
+ else if (option.label?.toLowerCase() === "fastest") tags.push({ text: "Fastest", tone: "brand" });
4370
+ else if (option.gasSponsored) tags.push({ text: "Gasless", tone: "purple" });
4371
+ else {
4372
+ const badge = routeBadges(options).get(option.id);
4373
+ const text = badge === "Fastest" && labelledFastest ? void 0 : badge ?? routeShapeLabel(option) ?? void 0;
4374
+ if (text) tags.push({ text, tone: "brand" });
4375
+ }
4376
+ if (option.entersNetting) tags.push({ text: "Netting", tone: "green" });
4377
+ return tags;
4378
+ }
4379
+ function compareFeeUsd(option, fromUsd) {
4380
+ const centibips = option.feeCentibips;
4381
+ if (centibips === void 0 || option.feeNative) return null;
4382
+ if (centibips === 0) return 0;
4383
+ return typeof fromUsd === "number" && Number.isFinite(fromUsd) && fromUsd > 0 ? fromUsd * centibips / 1e6 : null;
4384
+ }
4385
+ function priceCompareOptions(options, fromUsd) {
4386
+ return options.map((o) => ({ ...o, feeUsd: compareFeeUsd(o, fromUsd) }));
4387
+ }
4388
+ var ZD_HEAVY_KEY_PREFIX = "zdheavy:";
4389
+ function zdHeavyOptionKey(q) {
4390
+ return q.label ? `${ZD_HEAVY_KEY_PREFIX}${q.label}:${String(q.escrowAddress ?? "").toLowerCase()}` : `${ZD_HEAVY_KEY_PREFIX}id:${q.optionId ?? ""}`;
4391
+ }
4392
+ function zdHeavyUnavailableStatus(q) {
4393
+ return zdHeavyExecutable(q) ? void 0 : typeof q.payloadStatus === "string" && q.payloadStatus ? q.payloadStatus : "unknown";
4394
+ }
4395
+ function tokenAt2(tokens, chainId, address) {
4396
+ const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
4397
+ const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
4398
+ if (!wanted || !tokens?.length) return void 0;
4399
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
4400
+ }
4401
+ function hopFor(tokens, address, chainId, fallback) {
4402
+ const token = tokenAt2(tokens, chainId, address);
4403
+ return { address, chainId, ticker: token ? tokenTicker(token) : fallback ?? "Unknown" };
4404
+ }
4405
+ function compareHops(quote, ctx) {
4406
+ if (quote.protocol === "zdheavy") {
4407
+ const order = quote.execution?.order;
4408
+ if (!order || !Array.isArray(order.steps) || !order.steps.length) return [];
4409
+ const first = order.steps[0];
4410
+ const hops2 = [hopFor(ctx.tokens, String(first.tokenIn ?? first.token ?? order.tokenIn ?? ""), Number(order.chainNumber), ctx.from.ticker)];
4411
+ const push = (address, chainId, fallback) => {
4412
+ if (!address || chainId === void 0) return;
4413
+ const previous = hops2[hops2.length - 1];
4414
+ if (previous.address.toLowerCase() === address.toLowerCase() && previous.chainId === Number(chainId)) return;
4415
+ hops2.push(hopFor(ctx.tokens, address, Number(chainId), fallback));
4416
+ };
4417
+ order.steps.forEach((s, i) => {
4418
+ const n = order.steps[i + 1];
4419
+ const p = hops2[hops2.length - 1];
4420
+ if (s.kind === "SWAP") push(s.tokenOut, s.chainId);
4421
+ else if (s.kind === "SEND") push(n?.tokenIn ?? n?.token, s.dstChainId, p.ticker);
4422
+ else if (s.kind === "LOCAL_PAYOUT") push(s.token, s.chainId, ctx.to.ticker);
4423
+ else if (s.kind === "REMOTE_PAYOUT") push(ctx.to.address, s.receiverChainId, ctx.to.ticker);
4424
+ });
4425
+ return hops2;
4426
+ }
4427
+ const requests = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
4428
+ if (!requests.length) return [];
4429
+ const hops = [hopFor(ctx.tokens, String(requests[0].bidToken ?? ""), Number(quote.fromChainId), ctx.from.ticker)];
4430
+ requests.forEach((request, i) => {
4431
+ const last = i === requests.length - 1;
4432
+ hops.push(hopFor(ctx.tokens, String(request.askToken ?? ""), Number(request.destinationChainId || quote.toChainId), last ? ctx.to.ticker : void 0));
4433
+ });
4434
+ return hops;
4435
+ }
4436
+ var shortAddress2 = (address) => address.slice(0, 10).toLowerCase();
4437
+ function compareOptionOf(quote, ctx) {
4438
+ const heavy = quote.protocol === "zdheavy";
4439
+ if (!heavy && !liteExecutable(quote)) return null;
4440
+ const hops = compareHops(quote, ctx);
4441
+ if (hops.length < 2 && !heavy) return null;
4442
+ let amountRaw;
4443
+ let amount;
4444
+ try {
4445
+ amountRaw = BigInt(quote.finalAmount || quote.toAmount || "");
4446
+ amount = Number(formatUnits(amountRaw, ctx.to.decimals, ctx.to.decimals));
4447
+ } catch {
4448
+ return null;
4449
+ }
4450
+ const centibips = quote.zeroDeltaFeeCentibips;
4451
+ const native = quote.zeroDeltaFeeNative;
4452
+ const feeNative = typeof native === "string" && /^\d+$/.test(native) && BigInt(native) > 0n;
4453
+ const feeCentibips = typeof centibips === "number" && Number.isSafeInteger(centibips) && centibips >= 0 ? centibips : void 0;
4454
+ const unavailable = heavy ? zdHeavyUnavailableStatus(quote) : void 0;
4455
+ const option = {
4456
+ // The path, not the amount: the amount moves on every re-quote, and a key that changes would drop a pick.
4457
+ id: heavy ? zdHeavyOptionKey(quote) : hops.map((h2) => `${h2.chainId}:${shortAddress2(h2.address)}`).join(">"),
4458
+ ...typeof quote.label === "string" && quote.label ? { label: quote.label } : {},
4459
+ ...unavailable ? { unavailable } : {},
4460
+ amount,
4461
+ amountRaw: amountRaw.toString(),
4462
+ estimatedDuration: Number(quote.estimatedDuration) || 0,
4463
+ feeUsd: null,
4464
+ ...feeCentibips !== void 0 ? { feeCentibips } : {},
4465
+ ...feeNative ? { feeNative: true } : {},
4466
+ hops,
4467
+ ...quote.entersNetting === true ? { entersNetting: true } : {},
4468
+ ...quote.gasSponsored === true ? { gasSponsored: true } : {}
4469
+ };
4470
+ option.feeUsd = compareFeeUsd(option);
4471
+ return option;
4472
+ }
4473
+ function compareOptionsOf(quote, ctx) {
4474
+ const all = quote.gatewayOptions?.length ? quote.gatewayOptions : [quote];
4475
+ const seen = /* @__PURE__ */ new Set();
4476
+ const byIndex = all.map((q) => {
4477
+ const row = compareOptionOf(q, ctx);
4478
+ if (!row || seen.has(row.id)) return null;
4479
+ seen.add(row.id);
4480
+ return row;
4481
+ });
4482
+ return { options: byIndex.filter((o) => !!o), byIndex };
4483
+ }
4484
+
3366
4485
  // src/core/route.ts
3367
4486
  function routeDeltaLabel(result, quote) {
3368
4487
  if (result.directTransfer) return "~0";
@@ -3383,9 +4502,9 @@ function routeLabelFor(option, destinationToken, result) {
3383
4502
  const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
3384
4503
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
3385
4504
  }
3386
- function tokenAt2(tokens, chainId, address) {
3387
- const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
3388
- const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
4505
+ function tokenAt3(tokens, chainId, address) {
4506
+ const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
4507
+ const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
3389
4508
  if (!wanted || !tokens?.length) return void 0;
3390
4509
  return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
3391
4510
  }
@@ -3407,7 +4526,7 @@ function buildLegs(orders, ctx) {
3407
4526
  const order = orders[index];
3408
4527
  const isLast = index === orders.length - 1;
3409
4528
  const toChainId = Number(order.destinationChainId);
3410
- const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
4529
+ const askToken = isLast ? ctx.destinationToken : tokenAt3(ctx.tokens, toChainId, order.askToken);
3411
4530
  const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
3412
4531
  const toTicker = askToken ? tokenTicker(askToken) : "";
3413
4532
  const toDecimals = askToken ? assetDecimals(askToken) : void 0;
@@ -3434,19 +4553,42 @@ function buildLegs(orders, ctx) {
3434
4553
  }
3435
4554
  return legs;
3436
4555
  }
3437
- async function buildRoute({
3438
- option,
3439
- destination,
3440
- destinationToken,
3441
- chains,
3442
- tokens,
3443
- payer,
3444
- fetchQuote,
3445
- solve = solveExactOut,
3446
- amountInRaw,
3447
- compliance
3448
- }) {
4556
+ async function buildRoute(args) {
4557
+ const { option, destination, destinationToken, payer, fetchQuote, amountInRaw } = args;
4558
+ const solve = args.solve ?? solveExactOut;
3449
4559
  const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
4560
+ const route = routeFromResult(args, result);
4561
+ return result.directTransfer ? route : withQuoteOptions(route, args, result, solve === solveExactIn ? "exact-in" : "exact-out");
4562
+ }
4563
+ function withQuoteOptions(route, args, result, mode) {
4564
+ const { option, destination, destinationToken } = args;
4565
+ const quote = result.quote;
4566
+ const { byIndex } = compareOptionsOf(quote, {
4567
+ tokens: args.tokens,
4568
+ from: { chainId: option.chainId, address: option.address, ticker: optionTicker(option) },
4569
+ to: { chainId: Number(destination.chainId), address: destinationToken.address, ticker: tokenTicker(destinationToken), decimals: assetDecimals(destinationToken) }
4570
+ });
4571
+ const selectedIndex = quote.gatewayOptions?.length ? quote.gatewayOptionIndex ?? -1 : 0;
4572
+ const built = [];
4573
+ const refused = /* @__PURE__ */ new Set();
4574
+ (quote.gatewayOptions ?? []).forEach((candidate, index) => {
4575
+ const row = byIndex[index];
4576
+ if (!row || row.unavailable || index === selectedIndex) return;
4577
+ try {
4578
+ built.push({ index, route: routeFromResult(args, resultForOption(result, candidate, mode, destination.chainId)) });
4579
+ } catch {
4580
+ refused.add(index);
4581
+ }
4582
+ });
4583
+ const options = [];
4584
+ byIndex.forEach((row, index) => {
4585
+ if (row) options.push(refused.has(index) ? { ...row, unavailable: "refused-by-widget" } : row);
4586
+ });
4587
+ const selectedOptionId = byIndex[selectedIndex]?.id;
4588
+ const alternatives = built.map(({ index, route: alt }) => ({ ...alt, id: route.id, options, selectedOptionId: byIndex[index].id }));
4589
+ return { ...route, options, ...selectedOptionId ? { selectedOptionId } : {}, ...alternatives.length ? { alternatives } : {} };
4590
+ }
4591
+ function routeFromResult({ option, destination, destinationToken, chains, tokens, routes, payer, compliance }, result) {
3450
4592
  const quote = result.quote;
3451
4593
  const destDecimals = assetDecimals(destinationToken);
3452
4594
  const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
@@ -3521,6 +4663,9 @@ async function buildRoute({
3521
4663
  }
3522
4664
  };
3523
4665
  }
4666
+ if (quote.protocol === "zdheavy") {
4667
+ return buildZdHeavyRoute({ option, destination, destinationToken, chains, tokens: tokens ?? [], routes: routes ?? [], payer, result });
4668
+ }
3524
4669
  const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
3525
4670
  if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
3526
4671
  const sourceChain = chainById(chains, option.chainId);
@@ -3622,12 +4767,134 @@ async function buildRoute({
3622
4767
  };
3623
4768
  }
3624
4769
 
4770
+ // src/core/promotions.ts
4771
+ var CENTIBIPS_PER_UNIT = 1e6;
4772
+ function toToken(raw2) {
4773
+ if (!raw2 || typeof raw2 !== "object") return void 0;
4774
+ const r = raw2;
4775
+ const chainId = Number(r.chainId);
4776
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) return void 0;
4777
+ if (typeof r.address !== "string" || !r.address) return void 0;
4778
+ if (typeof r.symbol !== "string" || !r.symbol) return void 0;
4779
+ return { chainId, address: r.address, symbol: r.symbol };
4780
+ }
4781
+ function parsePromotion(raw2, now = Date.now()) {
4782
+ if (!raw2 || typeof raw2 !== "object") return void 0;
4783
+ const r = raw2;
4784
+ if (typeof r.id !== "string" || !r.id) return void 0;
4785
+ if (r.kind !== "token" && r.kind !== "pair") return void 0;
4786
+ const destination = toToken(r.destination);
4787
+ if (!destination) return void 0;
4788
+ const source2 = r.kind === "pair" ? toToken(r.source) : void 0;
4789
+ if (r.kind === "pair" && !source2) return void 0;
4790
+ const bonusCentibips = Number(r.bonusCentibips);
4791
+ if (!Number.isSafeInteger(bonusCentibips) || bonusCentibips <= 0) return void 0;
4792
+ if (r.fundedBy !== "issuer" && r.fundedBy !== "zerodelta") return void 0;
4793
+ if (typeof r.startsAt !== "string" || typeof r.endsAt !== "string") return void 0;
4794
+ const starts = Date.parse(r.startsAt);
4795
+ const ends = Date.parse(r.endsAt);
4796
+ if (!Number.isFinite(starts) || !Number.isFinite(ends) || !(starts <= now && now < ends)) return void 0;
4797
+ let maxBonusAmount;
4798
+ if (r.maxBonusAmount !== void 0) {
4799
+ if (typeof r.maxBonusAmount !== "string" || !/^[1-9]\d*$/.test(r.maxBonusAmount)) return void 0;
4800
+ maxBonusAmount = r.maxBonusAmount;
4801
+ }
4802
+ return {
4803
+ id: r.id,
4804
+ kind: r.kind,
4805
+ destination,
4806
+ ...source2 ? { source: source2 } : {},
4807
+ bonusCentibips,
4808
+ ...maxBonusAmount ? { maxBonusAmount } : {},
4809
+ fundedBy: r.fundedBy,
4810
+ ...typeof r.funderName === "string" && r.funderName ? { funderName: r.funderName } : {},
4811
+ startsAt: r.startsAt,
4812
+ endsAt: r.endsAt
4813
+ };
4814
+ }
4815
+ function parsePromotions(rows, now = Date.now()) {
4816
+ if (!Array.isArray(rows)) return [];
4817
+ return rows.map((row) => parsePromotion(row, now)).filter((p) => !!p);
4818
+ }
4819
+ function sameAddress(a, b) {
4820
+ return a.startsWith("0x") && b.startsWith("0x") ? a.toLowerCase() === b.toLowerCase() : a === b;
4821
+ }
4822
+ function sameToken(t, chainId, address) {
4823
+ return t.chainId === chainId && sameAddress(t.address, address);
4824
+ }
4825
+ function promotedAssets(promotions) {
4826
+ const bySymbol = /* @__PURE__ */ new Map();
4827
+ for (const p of promotions) {
4828
+ if (p.kind !== "token") continue;
4829
+ const key2 = p.destination.symbol.toUpperCase();
4830
+ const asset = bySymbol.get(key2) ?? { symbol: p.destination.symbol, maxCentibips: 0, networks: [], fundedBy: p.fundedBy };
4831
+ asset.networks.push({ promotion: p, chainId: p.destination.chainId, address: p.destination.address, bonusCentibips: p.bonusCentibips });
4832
+ if (p.bonusCentibips > asset.maxCentibips) {
4833
+ asset.maxCentibips = p.bonusCentibips;
4834
+ asset.fundedBy = p.fundedBy;
4835
+ }
4836
+ bySymbol.set(key2, asset);
4837
+ }
4838
+ const assets = [...bySymbol.values()];
4839
+ for (const a of assets) a.networks.sort((x, y) => y.bonusCentibips - x.bonusCentibips || x.chainId - y.chainId);
4840
+ return assets.sort((a, b) => b.maxCentibips - a.maxCentibips || a.symbol.localeCompare(b.symbol));
4841
+ }
4842
+ function promotionFor(promotions, ends) {
4843
+ let best;
4844
+ for (const p of promotions) {
4845
+ if (!sameToken(p.destination, ends.toChainId, ends.toAddress)) continue;
4846
+ if (p.kind === "pair") {
4847
+ if (!p.source || ends.fromChainId === void 0 || !ends.fromAddress) continue;
4848
+ if (!sameToken(p.source, ends.fromChainId, ends.fromAddress)) continue;
4849
+ }
4850
+ if (!best || p.bonusCentibips > best.bonusCentibips) best = p;
4851
+ }
4852
+ return best;
4853
+ }
4854
+ function pairPromotionsInto(promotions, chainId, address) {
4855
+ return promotions.filter((p) => p.kind === "pair" && sameToken(p.destination, chainId, address));
4856
+ }
4857
+ function estimateBonus(amount, promotion) {
4858
+ if (amount <= 0n) return 0n;
4859
+ const bonus = amount * BigInt(promotion.bonusCentibips) / BigInt(CENTIBIPS_PER_UNIT);
4860
+ if (promotion.maxBonusAmount) {
4861
+ const cap = BigInt(promotion.maxBonusAmount);
4862
+ return bonus > cap ? cap : bonus;
4863
+ }
4864
+ return bonus;
4865
+ }
4866
+ /* @__PURE__ */ new Set([...STABLE_ASSETS, "GHO", "USD0", "USDF"]);
4867
+
4868
+ // src/core/quote-request.ts
4869
+ function nativeQuoteRequest(body) {
4870
+ const inputChain = Number(body.fromChainId);
4871
+ const owner = typeof body.owner === "string" && body.owner ? body.owner : void 0;
4872
+ const destinationWallet = typeof body.destinationReceiver === "string" && body.destinationReceiver ? body.destinationReceiver : void 0;
4873
+ const owners = owner ? isSolanaChainId(inputChain) && isSolanaAddress(owner) ? { svm: owner } : { evm: owner } : void 0;
4874
+ const sender = typeof body.sender === "string" ? body.sender : !isSolanaChainId(inputChain) ? owner : void 0;
4875
+ return {
4876
+ inputChain,
4877
+ outputChain: Number(body.toChainId),
4878
+ inputToken: String(body.fromToken ?? ""),
4879
+ outputToken: String(body.toToken ?? ""),
4880
+ inputAmount: String(body.fromAmount ?? ""),
4881
+ ...owners ? { owners } : {},
4882
+ ...destinationWallet ? { destinationWallet } : {},
4883
+ ...sender && owners && destinationWallet ? { sender } : {},
4884
+ // No new deadline, latency limit or subject is invented for EVM quoting. The
4885
+ // gateway derives the subject from owners when this caller has no explicit one.
4886
+ ...body.deadline !== void 0 ? { deadline: String(body.deadline) } : {},
4887
+ ...typeof body.maxTimeSec === "number" ? { maxTimeSec: body.maxTimeSec } : {},
4888
+ ...typeof body.subjectId === "string" ? { subjectId: body.subjectId } : {}
4889
+ };
4890
+ }
4891
+
3625
4892
  // src/core/channel.ts
3626
4893
  var CHANNEL_HEADER = "x-zd-channel";
3627
4894
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
3628
4895
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
3629
4896
  var WIDGET_CHANNEL = "widget";
3630
- var WIDGET_VERSION = "4.18.1" ;
4897
+ var WIDGET_VERSION = "4.19.0" ;
3631
4898
  var MAX_CHANNEL_VERSION_LEN = 32;
3632
4899
  function sanitizeVersion(raw2) {
3633
4900
  const v = String(raw2).trim();
@@ -3719,7 +4986,7 @@ function classifyQuoteError(error) {
3719
4986
  function amountFieldError(error) {
3720
4987
  const fieldErrors = error?.fieldErrors;
3721
4988
  if (!Array.isArray(fieldErrors)) return null;
3722
- const entry = fieldErrors.find((e) => e && typeof e === "object" && e.field === "fromAmount" && typeof e.message === "string");
4989
+ const entry = fieldErrors.find((e) => e && typeof e === "object" && (e.field === "fromAmount" || e.field === "inputAmount") && typeof e.message === "string");
3723
4990
  const message = entry ? sanitizeMessage(entry.message, "") : "";
3724
4991
  return message || null;
3725
4992
  }
@@ -3735,7 +5002,7 @@ function wait(ms) {
3735
5002
  }
3736
5003
  var PAGE_LIMIT = 500;
3737
5004
  var MAX_PAGES = 10;
3738
- var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, inflight: /* @__PURE__ */ new Map() });
5005
+ var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, promotions: null, inflight: /* @__PURE__ */ new Map() });
3739
5006
  var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
3740
5007
  function registryCacheFor(scope) {
3741
5008
  if (!scope) return newRegistryCache();
@@ -3892,6 +5159,20 @@ function createApiClient(cfg) {
3892
5159
  return value;
3893
5160
  });
3894
5161
  }
5162
+ function fetchPromotions() {
5163
+ if (nowFresh(cache.promotions)) return Promise.resolve(parsePromotions(cache.promotions.value));
5164
+ return once("promotions", async () => {
5165
+ let value = [];
5166
+ try {
5167
+ const rows = await apiRequest("/promotions", { timeoutMs: 8e3 });
5168
+ value = Array.isArray(rows) ? rows : [];
5169
+ } catch {
5170
+ value = [];
5171
+ }
5172
+ cache.promotions = { at: Date.now(), value };
5173
+ return parsePromotions(value);
5174
+ });
5175
+ }
3895
5176
  const priceCache = /* @__PURE__ */ new Map();
3896
5177
  async function fetchPrices(symbols) {
3897
5178
  const wanted = [...new Set(symbols.map((s) => String(s || "").toUpperCase()).filter((s) => /^[A-Z0-9]{1,16}$/.test(s)))];
@@ -3922,11 +5203,12 @@ function createApiClient(cfg) {
3922
5203
  return out;
3923
5204
  }
3924
5205
  async function fetchQuote(body, retries = 1) {
5206
+ const request = nativeQuoteRequest(body);
3925
5207
  let lastError;
3926
5208
  for (let attempt = 0; attempt <= retries; attempt += 1) {
3927
5209
  try {
3928
- const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(body), timeoutMs: 18e3 });
3929
- return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
5210
+ const quote = await apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
5211
+ return normalizeQuoteResponse(quote, request);
3930
5212
  } catch (error) {
3931
5213
  lastError = error;
3932
5214
  if (attempt >= retries || !isTransientQuoteError(error)) throw error;
@@ -3940,10 +5222,10 @@ function createApiClient(cfg) {
3940
5222
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
3941
5223
  const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3942
5224
  if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3943
- const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
3944
- const hit = screenCache.get(key);
5225
+ const key2 = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
5226
+ const hit = screenCache.get(key2);
3945
5227
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
3946
- const inflight = screenInflight.get(key);
5228
+ const inflight = screenInflight.get(key2);
3947
5229
  if (inflight) return inflight;
3948
5230
  const request = apiRequest("/screen/wallet", {
3949
5231
  method: "POST",
@@ -3954,12 +5236,12 @@ function createApiClient(cfg) {
3954
5236
  throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
3955
5237
  }
3956
5238
  const value = { ...screen, address: screen.address || addr };
3957
- screenCache.set(key, { at: Date.now(), value });
5239
+ screenCache.set(key2, { at: Date.now(), value });
3958
5240
  return value;
3959
5241
  }).finally(() => {
3960
- screenInflight.delete(key);
5242
+ screenInflight.delete(key2);
3961
5243
  });
3962
- screenInflight.set(key, request);
5244
+ screenInflight.set(key2, request);
3963
5245
  return request;
3964
5246
  }
3965
5247
  async function reportSubmission(report) {
@@ -3982,7 +5264,7 @@ function createApiClient(cfg) {
3982
5264
  return false;
3983
5265
  }
3984
5266
  }
3985
- return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchQuote, screenWallet, reportSubmission, apiBase };
5267
+ return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchPromotions, fetchQuote, screenWallet, reportSubmission, apiBase };
3986
5268
  }
3987
5269
 
3988
5270
  // src/core/plan.ts
@@ -4045,9 +5327,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4045
5327
  const balanceTargets = [];
4046
5328
  const seenTargets = /* @__PURE__ */ new Set();
4047
5329
  for (const option of options) {
4048
- const key = optionBalanceKey(option);
4049
- if (seenTargets.has(key)) continue;
4050
- seenTargets.add(key);
5330
+ const key2 = optionBalanceKey(option);
5331
+ if (seenTargets.has(key2)) continue;
5332
+ seenTargets.add(key2);
4051
5333
  balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
4052
5334
  }
4053
5335
  const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
@@ -4059,9 +5341,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4059
5341
  for (const raw2 of [payer, destination.address]) {
4060
5342
  const addr = String(raw2 || "").trim();
4061
5343
  if (!addr) continue;
4062
- const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
4063
- if (seenParty.has(key)) continue;
4064
- seenParty.add(key);
5344
+ const key2 = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
5345
+ if (seenParty.has(key2)) continue;
5346
+ seenParty.add(key2);
4065
5347
  parties.push(addr);
4066
5348
  }
4067
5349
  try {
@@ -4108,6 +5390,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4108
5390
  destinationToken,
4109
5391
  chains,
4110
5392
  tokens,
5393
+ routes,
4111
5394
  payer,
4112
5395
  fetchQuote: api.fetchQuote,
4113
5396
  compliance: option.direct ? directCompliance ?? void 0 : void 0
@@ -4168,7 +5451,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
4168
5451
  (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
4169
5452
  );
4170
5453
  if (!option) throw new Error("That funding option is not available for this payment right now.");
4171
- return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
5454
+ return buildRoute({ option, destination, destinationToken, chains, tokens, routes, payer, fetchQuote: api.fetchQuote });
4172
5455
  }
4173
5456
 
4174
5457
  // src/core/swap.ts
@@ -4176,13 +5459,13 @@ function validateSwap(swap = {}) {
4176
5459
  const fromChainId = Number(swap.fromChainId);
4177
5460
  const toChainId = Number(swap.toChainId);
4178
5461
  const fromToken = symbolKey(swap.fromToken);
4179
- const toToken = symbolKey(swap.toToken);
5462
+ const toToken2 = symbolKey(swap.toToken);
4180
5463
  if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
4181
5464
  if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
4182
- if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken)) throw new Error("Unsupported swap asset.");
5465
+ if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken2)) throw new Error("Unsupported swap asset.");
4183
5466
  const amountIn = normalizeDecimalText(swap.amountIn);
4184
5467
  if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
4185
- return { fromChainId, toChainId, fromToken, toToken, amountIn };
5468
+ return { fromChainId, toChainId, fromToken, toToken: toToken2, amountIn };
4186
5469
  }
4187
5470
  function viaOf(quote, tokens) {
4188
5471
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
@@ -4232,7 +5515,7 @@ async function quoteSwapPreview(api, swap, owner) {
4232
5515
  async function buildSwapPlan(api, swap, payer, wallet = {}) {
4233
5516
  const v = validateSwap(swap);
4234
5517
  const account = assertAddress(payer, "Swap wallet");
4235
- const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
5518
+ const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
4236
5519
  const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
4237
5520
  const destToken = findToken(tokens, v.toChainId, v.toToken);
4238
5521
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
@@ -4255,7 +5538,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4255
5538
  direct: false
4256
5539
  };
4257
5540
  const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
4258
- const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
5541
+ const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, routes, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
4259
5542
  if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
4260
5543
  route.recommended = true;
4261
5544
  return {
@@ -4276,88 +5559,6 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4276
5559
  };
4277
5560
  }
4278
5561
 
4279
- // src/core/validate-tx.ts
4280
- var lower = (v) => String(v || "").toLowerCase();
4281
- function isHexAddress(value) {
4282
- return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
4283
- }
4284
- function isHexData(value) {
4285
- return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value));
4286
- }
4287
- function isHexQuantity(value) {
4288
- return /^0x[0-9a-fA-F]+$/.test(String(value));
4289
- }
4290
- function dataWord(data, index) {
4291
- const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4292
- return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
4293
- }
4294
- function dataAddress(data, index) {
4295
- const word2 = dataWord(data, index);
4296
- return word2 ? `0x${word2.slice(24)}` : "";
4297
- }
4298
- function dataUint(data, index) {
4299
- const word2 = dataWord(data, index);
4300
- return word2 ? BigInt(`0x${word2}`) : null;
4301
- }
4302
- function rawEquals(value, expected) {
4303
- try {
4304
- return value === BigInt(expected || "0");
4305
- } catch {
4306
- return false;
4307
- }
4308
- }
4309
- function planMsgValueHex(route) {
4310
- try {
4311
- const raw2 = route?.quote?.msgValue;
4312
- if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4313
- return "0x" + BigInt(raw2).toString(16);
4314
- } catch {
4315
- return null;
4316
- }
4317
- }
4318
- function validatePlannedTransaction(tx, route, expectedRecipient) {
4319
- if (!tx || tx.mock) return true;
4320
- if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
4321
- const data = String(tx.data || "0x").toLowerCase();
4322
- const selector = data.slice(0, 10);
4323
- const value = lower(tx.value || "0x0");
4324
- if (tx.kind === "transfer") {
4325
- if (value !== "0x0") return false;
4326
- return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4327
- }
4328
- if (tx.kind === "approve") {
4329
- if (value !== "0x0") return false;
4330
- return selector === "0x095ea7b3" && isHexAddress(tx.token) && isHexAddress(tx.spender) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(tx.spender) && rawEquals(dataUint(data, 1), tx.amountRaw);
4331
- }
4332
- if (tx.kind === "submitOrder") {
4333
- const expected = planMsgValueHex(route);
4334
- if (expected === null || value !== lower(expected)) return false;
4335
- if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
4336
- const decoded = decodeSubmitOrderCalldata(data);
4337
- if (!decoded) return false;
4338
- const first = decoded.orders[0];
4339
- const last = decoded.orders[decoded.orders.length - 1];
4340
- 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));
4341
- }
4342
- return false;
4343
- }
4344
- function solanaDeliveryMatches(encoded, recipient2, mint) {
4345
- try {
4346
- return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4347
- } catch {
4348
- return false;
4349
- }
4350
- }
4351
- async function allowanceCovers(tx, account, ethCall2) {
4352
- if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4353
- try {
4354
- const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
4355
- return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4356
- } catch {
4357
- return false;
4358
- }
4359
- }
4360
-
4361
5562
  // src/core/verify.ts
4362
5563
  var TX_VERIFY_ATTEMPTS = 5;
4363
5564
  var TX_VERIFY_INTERVAL_MS = 2500;
@@ -4502,9 +5703,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4502
5703
  const seen = /* @__PURE__ */ new Set();
4503
5704
  for (const target of targets) {
4504
5705
  if (!target || !isAddress(target.tokenAddress)) continue;
4505
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4506
- if (seen.has(key)) continue;
4507
- seen.add(key);
5706
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5707
+ if (seen.has(key2)) continue;
5708
+ seen.add(key2);
4508
5709
  const chainId = Number(target.chainId);
4509
5710
  const group = groups.get(chainId) || [];
4510
5711
  group.push(target);
@@ -4513,8 +5714,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4513
5714
  function record(target, hex) {
4514
5715
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
4515
5716
  const raw2 = BigInt(hex || "0x0").toString();
4516
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4517
- out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
5717
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5718
+ out[key2] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
4518
5719
  return true;
4519
5720
  }
4520
5721
  async function readOne(rpcUrl, target) {
@@ -4560,7 +5761,18 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4560
5761
  return null;
4561
5762
  }
4562
5763
  }
4563
- return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance };
5764
+ async function readZdHeavySubmitFee(chainId, to, data) {
5765
+ try {
5766
+ const override = rpcOverrides[Number(chainId)];
5767
+ const rpc = override && /^https?:\/\//i.test(override) ? override : BUNDLED_RPC[Number(chainId)];
5768
+ if (!rpc) return void 0;
5769
+ const result = await rpcCall(rpc, "eth_call", [{ to, data: quoteSubmitCalldata(data) }, "latest"]);
5770
+ return typeof result === "string" && /^0x[0-9a-fA-F]{64}$/.test(result) ? BigInt(result) : void 0;
5771
+ } catch {
5772
+ return void 0;
5773
+ }
5774
+ }
5775
+ return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance, readZdHeavySubmitFee };
4564
5776
  }
4565
5777
 
4566
5778
  // src/core/config.ts
@@ -4681,6 +5893,7 @@ function createEngine(config = {}) {
4681
5893
  fetchRouteHealth: api.fetchRouteHealth,
4682
5894
  fetchQuote: api.fetchQuote,
4683
5895
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
5896
+ fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
4684
5897
  fetchCatalogue: async (allowedAssets, product, options) => {
4685
5898
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
4686
5899
  api.fetchChains().catch(() => []),
@@ -5124,7 +6337,13 @@ function useFlow(args) {
5124
6337
  statusRef.current = status;
5125
6338
  const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
5126
6339
  const routes = plan?.routes ?? [];
5127
- const selected = react.useMemo(() => routes.find((r) => r.id === selectedId) ?? routes.find((r) => r.recommended) ?? routes[0] ?? null, [routes, selectedId]);
6340
+ const baseSelected = react.useMemo(() => routes.find((r) => r.id === selectedId) ?? routes.find((r) => r.recommended) ?? routes[0] ?? null, [routes, selectedId]);
6341
+ const [pickedOptionId, setPickedOptionId] = react.useState(null);
6342
+ const selected = react.useMemo(() => {
6343
+ if (!baseSelected || !pickedOptionId || pickedOptionId === baseSelected.selectedOptionId) return baseSelected;
6344
+ const alt = baseSelected.alternatives?.find((r) => r.selectedOptionId === pickedOptionId);
6345
+ return alt ? { ...alt, recommended: baseSelected.recommended } : baseSelected;
6346
+ }, [baseSelected, pickedOptionId]);
5128
6347
  const reload = react.useCallback(() => setNonce((n) => n + 1), []);
5129
6348
  const addRoute = react.useCallback((route) => {
5130
6349
  setPlan((p) => p ? { ...p, routes: [...p.routes.filter((r) => r.id !== route.id), route] } : p);
@@ -5179,11 +6398,11 @@ function useFlow(args) {
5179
6398
  if (!wallet.account || !src?.tokenAddress || src.decimals == null) return;
5180
6399
  (async () => {
5181
6400
  try {
5182
- const key = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
6401
+ const key2 = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
5183
6402
  const balances = await engine.readBalances(wallet.account, [
5184
6403
  { chainId: Number(src.chainId), tokenAddress: src.tokenAddress, decimals: Number(src.decimals) }
5185
6404
  ]);
5186
- const entry = balances[key];
6405
+ const entry = balances[key2];
5187
6406
  if (!entry) return;
5188
6407
  const need = parseUnitsDecimal(src.payAmount || src.amount, src.decimals);
5189
6408
  if (alive) setInsufficient(BigInt(entry.raw) < need);
@@ -5247,6 +6466,8 @@ function useFlow(args) {
5247
6466
  throw new Error(nativeFeeShortMessage(check2, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
5248
6467
  }
5249
6468
  }
6469
+ const heavyExpected = route.zdHeavy ? zdHeavyExpected(route, account, recipient2, ...await Promise.all([engine.fetchTokens(), engine.fetchRoutes()])) : void 0;
6470
+ if (heavyExpected) await preflightZdHeavyPlan(route, heavyExpected, engine.verifier.readZdHeavySubmitFee);
5250
6471
  const minNonce = await engine.payerNonceBaseline(Number(sourceChainId), account);
5251
6472
  const txs = route.transactions;
5252
6473
  let settleHash = "";
@@ -5262,7 +6483,7 @@ function useFlow(args) {
5262
6483
  patch(tx.id, "done");
5263
6484
  continue;
5264
6485
  }
5265
- if (!validatePlannedTransaction(tx, route, recipient2)) {
6486
+ if (!validatePlannedTransaction(tx, route, recipient2, heavyExpected ? { ...heavyExpected, nowSec: Math.floor(Date.now() / 1e3) } : void 0)) {
5266
6487
  throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
5267
6488
  }
5268
6489
  patch(tx.id, "active");
@@ -5333,6 +6554,98 @@ function useFlow(args) {
5333
6554
  busyRef.current = false;
5334
6555
  }
5335
6556
  }, [selected, wallet.provider, wallet.account, engine, kind, recipientFor, onSuccess, onError]);
6557
+ const [prices, setPrices] = react.useState(null);
6558
+ const priceKey = baseSelected?.options?.length ? `${baseSelected.source.asset}|${baseSelected.receive.asset}` : "";
6559
+ react.useEffect(() => {
6560
+ if (!priceKey || typeof engine.fetchPrices !== "function") return;
6561
+ let alive = true;
6562
+ const [from, to] = priceKey.split("|");
6563
+ (async () => {
6564
+ try {
6565
+ const p = await engine.fetchPrices([from, to]);
6566
+ const next = { key: priceKey, from: p[from.toUpperCase()], to: p[to.toUpperCase()] };
6567
+ if (alive) setPrices((prev) => prev && prev.key === next.key && prev.from === next.from && prev.to === next.to ? prev : next);
6568
+ } catch {
6569
+ }
6570
+ })();
6571
+ return () => {
6572
+ alive = false;
6573
+ };
6574
+ }, [engine, priceKey]);
6575
+ const compare = react.useMemo(() => {
6576
+ const base = baseSelected;
6577
+ if (!base?.options?.length) return null;
6578
+ const priced = prices?.key === priceKey ? prices : null;
6579
+ const inputAmount = Number(base.source.payAmount || base.source.amount);
6580
+ const fromUsd = priced?.from && Number.isFinite(inputAmount) ? inputAmount * priced.from : null;
6581
+ const options = priceCompareOptions(base.options, fromUsd);
6582
+ const selectedOptionId = selected?.selectedOptionId ?? null;
6583
+ const parityState = parity(options, fromUsd, priced?.to ?? null);
6584
+ return {
6585
+ options,
6586
+ visibleOptions: visibleOptions(options, proposedWait(options), selectedOptionId),
6587
+ selectedId: selectedOptionId,
6588
+ proposedWait: proposedWait(options),
6589
+ parity: parityState,
6590
+ extraVsFastest: extraVsFastest(options, selectedOptionId),
6591
+ tags: Object.fromEntries(options.map((o) => [o.id, cornerTags(options, o, parityState)])),
6592
+ pickForWait: (waitSec) => pickForWait(options, waitSec)
6593
+ };
6594
+ }, [baseSelected, selected, prices, priceKey]);
6595
+ const selectOption = react.useCallback(
6596
+ (optionId) => {
6597
+ if (busyRef.current || !baseSelected) return false;
6598
+ const signable = optionId === baseSelected.selectedOptionId || !!baseSelected.alternatives?.some((r) => r.selectedOptionId === optionId);
6599
+ if (!signable) return false;
6600
+ setPickedOptionId(optionId === baseSelected.selectedOptionId ? null : optionId);
6601
+ return true;
6602
+ },
6603
+ [baseSelected]
6604
+ );
6605
+ const [promotionList, setPromotionList] = react.useState([]);
6606
+ react.useEffect(() => {
6607
+ if (!enabled) return;
6608
+ let alive = true;
6609
+ (async () => {
6610
+ try {
6611
+ if (typeof engine.fetchPromotions !== "function") return;
6612
+ const read = await engine.fetchPromotions();
6613
+ const list = Array.isArray(read) ? read : [];
6614
+ if (alive) setPromotionList((prev) => JSON.stringify(prev) === JSON.stringify(list) ? prev : list);
6615
+ } catch {
6616
+ }
6617
+ })();
6618
+ return () => {
6619
+ alive = false;
6620
+ };
6621
+ }, [engine, enabled]);
6622
+ const promotions = react.useMemo(() => {
6623
+ const route = selected;
6624
+ const toAddress = route?.receive.tokenAddress;
6625
+ const forSelection = route && toAddress ? promotionFor(promotionList, {
6626
+ fromChainId: Number(route.source.chainId),
6627
+ ...route.source.tokenAddress ? { fromAddress: route.source.tokenAddress } : {},
6628
+ toChainId: Number(route.receive.chainId),
6629
+ toAddress
6630
+ }) : void 0;
6631
+ let bonusEstimateRaw = null;
6632
+ if (forSelection && route) {
6633
+ const pickedRow = route.options?.find((o) => o.id === route.selectedOptionId);
6634
+ try {
6635
+ const delivered = pickedRow ? BigInt(pickedRow.amountRaw) : parseUnitsDecimal(route.receive.amount, Number(route.receive.decimals));
6636
+ bonusEstimateRaw = estimateBonus(delivered, forSelection).toString();
6637
+ } catch {
6638
+ bonusEstimateRaw = null;
6639
+ }
6640
+ }
6641
+ return {
6642
+ all: promotionList,
6643
+ promotedAssets: promotedAssets(promotionList),
6644
+ forSelection,
6645
+ pairsInto: route && toAddress ? pairPromotionsInto(promotionList, Number(route.receive.chainId), toAddress) : [],
6646
+ bonusEstimateRaw
6647
+ };
6648
+ }, [promotionList, selected]);
5336
6649
  const quoteReady = status === "ready" && !!plan;
5337
6650
  const quotePaused = quoteReady && idle2;
5338
6651
  const quoteStale = quoteReady && (idle2 || planAt < returnedAt2);
@@ -5354,7 +6667,10 @@ function useFlow(args) {
5354
6667
  quoteStale,
5355
6668
  submit,
5356
6669
  reload,
5357
- addRoute
6670
+ addRoute,
6671
+ compare,
6672
+ selectOption,
6673
+ promotions
5358
6674
  };
5359
6675
  }
5360
6676
  var RETRY_DELAYS_MS = [800, 2400, 6e3];
@@ -5422,9 +6738,9 @@ function useHoldings(engine, account, routes, initialBalances) {
5422
6738
  const seeded = {};
5423
6739
  const missing = [];
5424
6740
  for (const target of targets) {
5425
- const key = balanceKey(target.chainId, target.tokenAddress);
5426
- const balance = initialBalances?.[key];
5427
- if (balance) seeded[key] = balance;
6741
+ const key2 = balanceKey(target.chainId, target.tokenAddress);
6742
+ const balance = initialBalances?.[key2];
6743
+ if (balance) seeded[key2] = balance;
5428
6744
  else missing.push(target);
5429
6745
  }
5430
6746
  setBalances(seeded);
@@ -6948,7 +8264,7 @@ function priceOf(prices, symbol) {
6948
8264
  const p = prices?.[String(symbol).toUpperCase()];
6949
8265
  return typeof p === "number" && Number.isFinite(p) ? p : void 0;
6950
8266
  }
6951
- function buildGroup(key, members, prices) {
8267
+ function buildGroup(key2, members, prices) {
6952
8268
  const tokens = members.map((m) => m.token);
6953
8269
  let amount = null;
6954
8270
  let usd2 = null;
@@ -6960,7 +8276,7 @@ function buildGroup(key, members, prices) {
6960
8276
  }
6961
8277
  const first = members[0].token;
6962
8278
  return {
6963
- key,
8279
+ key: key2,
6964
8280
  symbol: dominantSymbol(tokens),
6965
8281
  name: String(first.name || first.symbol),
6966
8282
  logoUrl: first.logoUrl,
@@ -6981,15 +8297,15 @@ function groupDeployments(deployments, prices) {
6981
8297
  const order = [];
6982
8298
  const members = /* @__PURE__ */ new Map();
6983
8299
  for (const d of [...deployments].sort(byDeployment)) {
6984
- const key = String(d.token.symbol).toUpperCase();
6985
- const list = members.get(key);
8300
+ const key2 = String(d.token.symbol).toUpperCase();
8301
+ const list = members.get(key2);
6986
8302
  if (list) list.push(d);
6987
8303
  else {
6988
- members.set(key, [d]);
6989
- order.push(key);
8304
+ members.set(key2, [d]);
8305
+ order.push(key2);
6990
8306
  }
6991
8307
  }
6992
- return order.map((key) => buildGroup(key, members.get(key), prices)).sort(byPickability);
8308
+ return order.map((key2) => buildGroup(key2, members.get(key2), prices)).sort(byPickability);
6993
8309
  }
6994
8310
  var CHAIN_ALIASES = {
6995
8311
  56: ["bsc", "binance"],
@@ -6997,10 +8313,10 @@ var CHAIN_ALIASES = {
6997
8313
  43114: ["avax"]
6998
8314
  };
6999
8315
  function labelForms(label2) {
7000
- const lower2 = label2.trim().toLowerCase();
7001
- if (!lower2) return [];
7002
- const compact = lower2.replace(/[^a-z0-9]/g, "");
7003
- return compact && compact !== lower2 ? [lower2, compact] : [lower2];
8316
+ const lower3 = label2.trim().toLowerCase();
8317
+ if (!lower3) return [];
8318
+ const compact = lower3.replace(/[^a-z0-9]/g, "");
8319
+ return compact && compact !== lower3 ? [lower3, compact] : [lower3];
7004
8320
  }
7005
8321
  function buildChainSearchTerms(chains) {
7006
8322
  const byId = /* @__PURE__ */ new Map();
@@ -7263,14 +8579,14 @@ function TokenSelect(props) {
7263
8579
  const groups = react.useMemo(() => {
7264
8580
  const deployments = [];
7265
8581
  for (const token of props.tokens) {
7266
- const key = rowKey(token);
7267
- const n = Number(props.balances?.[key]?.formatted);
7268
- const st = props.optionStates?.[key];
8582
+ const key2 = rowKey(token);
8583
+ const n = Number(props.balances?.[key2]?.formatted);
8584
+ const st = props.optionStates?.[key2];
7269
8585
  if (st?.disabled && !WALLET_STATE_REASONS.has(String(st.reason))) continue;
7270
8586
  deployments.push({
7271
8587
  token,
7272
- key,
7273
- balance: showBalances && props.balances?.[key] && Number.isFinite(n) ? n : null,
8588
+ key: key2,
8589
+ balance: showBalances && props.balances?.[key2] && Number.isFinite(n) ? n : null,
7274
8590
  disabled: !!st?.disabled,
7275
8591
  // The line under a greyed row says why. Callers send either a sentence in `reason` (the
7276
8592
  // exchange's "cannot be delivered on this chain") or a machine code there with the words in
@@ -7642,7 +8958,7 @@ function WidgetShell(props) {
7642
8958
  }
7643
8959
  );
7644
8960
  }
7645
- function shortAddress2(a) {
8961
+ function shortAddress3(a) {
7646
8962
  if (!a) return "";
7647
8963
  return `${a.slice(0, 6)}\u2026${a.slice(-4)}`;
7648
8964
  }
@@ -7911,13 +9227,13 @@ function useTxHistory(account) {
7911
9227
  react.useEffect(() => {
7912
9228
  setEntries(readTxHistory(account));
7913
9229
  if (typeof window === "undefined" || !account) return;
7914
- const key = txHistoryKey(account);
9230
+ const key2 = txHistoryKey(account);
7915
9231
  const onLocal = (e) => {
7916
9232
  const detail = e.detail;
7917
9233
  if (!detail?.account || detail.account === account.toLowerCase()) setEntries(readTxHistory(account));
7918
9234
  };
7919
9235
  const onStorage = (e) => {
7920
- if (e.key === key) setEntries(readTxHistory(account));
9236
+ if (e.key === key2) setEntries(readTxHistory(account));
7921
9237
  };
7922
9238
  window.addEventListener(TX_HISTORY_EVENT, onLocal);
7923
9239
  window.addEventListener("storage", onStorage);
@@ -7933,32 +9249,37 @@ var hidden2 = () => typeof document !== "undefined" && document.visibilityState
7933
9249
  var travelling = (entries) => !!entries?.some((e) => e.delivery === "in-progress" || e.delivery === "attention");
7934
9250
  function useWalletHistory(engine, wallets) {
7935
9251
  const [entries, setEntries] = react.useState(null);
7936
- const key = wallets.filter((w) => !!w).join("|");
9252
+ const key2 = wallets.filter((w) => !!w).join("|");
7937
9253
  react.useEffect(() => {
7938
9254
  setEntries(null);
7939
- if (!engine || !key) return;
9255
+ if (!engine || !key2) return;
7940
9256
  let alive = true;
7941
9257
  let timer2;
9258
+ let started2 = Date.now();
7942
9259
  const read = async () => {
7943
9260
  if (timer2) clearTimeout(timer2);
7944
9261
  timer2 = void 0;
7945
9262
  if (!hidden2()) {
7946
- const next = await engine.fetchWalletHistory(key.split("|"));
9263
+ const next = await engine.fetchWalletHistory(key2.split("|"));
7947
9264
  if (!alive) return;
7948
9265
  if (next) setEntries(next);
7949
9266
  if (!travelling(next)) return;
7950
9267
  }
9268
+ if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) return;
7951
9269
  timer2 = setTimeout(read, WALLET_HISTORY_REFRESH_MS);
7952
9270
  };
7953
9271
  void read();
7954
- const onRecorded = () => void read();
9272
+ const onRecorded = () => {
9273
+ started2 = Date.now();
9274
+ void read();
9275
+ };
7955
9276
  if (typeof window !== "undefined") window.addEventListener(TX_HISTORY_EVENT, onRecorded);
7956
9277
  return () => {
7957
9278
  alive = false;
7958
9279
  if (timer2) clearTimeout(timer2);
7959
9280
  if (typeof window !== "undefined") window.removeEventListener(TX_HISTORY_EVENT, onRecorded);
7960
9281
  };
7961
- }, [engine, key]);
9282
+ }, [engine, key2]);
7962
9283
  return entries;
7963
9284
  }
7964
9285
  function BackGlyph() {
@@ -8095,15 +9416,15 @@ function TxPair(props) {
8095
9416
  ] });
8096
9417
  }
8097
9418
  function logoFor(art, symbol, chainId) {
8098
- const key = symbolKey(symbol);
8099
- if (!key) return void 0;
9419
+ const key2 = symbolKey(symbol);
9420
+ if (!key2) return void 0;
8100
9421
  const tokens = art.tokens;
8101
9422
  if (tokens?.length) {
8102
- const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) === key);
8103
- const found = (sameChain ?? tokens.find((t) => symbolKey(t.symbol) === key))?.logoUrl;
9423
+ const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) === key2);
9424
+ const found = (sameChain ?? tokens.find((t) => symbolKey(t.symbol) === key2))?.logoUrl;
8104
9425
  if (found) return found;
8105
9426
  }
8106
- return art.vaultIcons?.get(key);
9427
+ return art.vaultIcons?.get(key2);
8107
9428
  }
8108
9429
  function TxHistoryList(props) {
8109
9430
  if (!props.entries.length) {
@@ -8180,7 +9501,7 @@ function TxDetail(props) {
8180
9501
  ] }),
8181
9502
  e.recipient ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
8182
9503
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Recipient" }),
8183
- /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress2(e.recipient) })
9504
+ /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress3(e.recipient) })
8184
9505
  ] }) : null,
8185
9506
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
8186
9507
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Settlement" }),
@@ -8217,7 +9538,7 @@ function TxHistoryPanel(props) {
8217
9538
  /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", autoFocus: true, ref: backRef, className: "sg-back", onClick: selected ? () => setSelectedHash(null) : props.onBack, "aria-label": "Back", children: /* @__PURE__ */ jsxRuntime.jsx(BackGlyph, {}) }),
8218
9539
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-title", children: [
8219
9540
  selected ? "Transaction" : "Transaction history",
8220
- account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress2(account) }) : null
9541
+ account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress3(account) }) : null
8221
9542
  ] })
8222
9543
  ] }),
8223
9544
  selected ? /* @__PURE__ */ jsxRuntime.jsx(TxDetail, { entry: selected, tokens: props.tokens, vaultIcons: props.vaultIcons }) : /* @__PURE__ */ jsxRuntime.jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
@@ -8399,8 +9720,8 @@ function onSolanaAccountChange(info, cb) {
8399
9720
  }
8400
9721
  }) ?? (() => {
8401
9722
  });
8402
- const changed = (key) => {
8403
- const address = validAddress(key);
9723
+ const changed = (key2) => {
9724
+ const address = validAddress(key2);
8404
9725
  connected.set(provider, address ? [{ address }] : []);
8405
9726
  cb(address);
8406
9727
  };
@@ -8572,82 +9893,6 @@ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
8572
9893
  const recipientFor = (account) => required ? recipient2 || "" : hostRecipient || custom.evm || account;
8573
9894
  return { recipientFamily, recipientChainId: destinationChainId, recipient: recipient2, shown, typed, recipientFor, managed, missing, error, wallet, familyWallet, wallets, open: open && managed, show: () => setOpen(true), close, selectAddress, connect, triggerRef };
8574
9895
  }
8575
-
8576
- // src/core/checksum.ts
8577
- var RC = [
8578
- 0x0000000000000001n,
8579
- 0x0000000000008082n,
8580
- 0x800000000000808an,
8581
- 0x8000000080008000n,
8582
- 0x000000000000808bn,
8583
- 0x0000000080000001n,
8584
- 0x8000000080008081n,
8585
- 0x8000000000008009n,
8586
- 0x000000000000008an,
8587
- 0x0000000000000088n,
8588
- 0x0000000080008009n,
8589
- 0x000000008000000an,
8590
- 0x000000008000808bn,
8591
- 0x800000000000008bn,
8592
- 0x8000000000008089n,
8593
- 0x8000000000008003n,
8594
- 0x8000000000008002n,
8595
- 0x8000000000000080n,
8596
- 0x000000000000800an,
8597
- 0x800000008000000an,
8598
- 0x8000000080008081n,
8599
- 0x8000000000008080n,
8600
- 0x0000000080000001n,
8601
- 0x8000000080008008n
8602
- ];
8603
- var ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14];
8604
- var MASK = (1n << 64n) - 1n;
8605
- var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
8606
- function keccakF(s) {
8607
- for (let round = 0; round < 24; round++) {
8608
- const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
8609
- for (let x = 0; x < 5; x++) {
8610
- const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
8611
- for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
8612
- }
8613
- const b = new Array(25);
8614
- for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(s[x + 5 * y], ROT[x + 5 * y]);
8615
- for (let x = 0; x < 5; x++) for (let y = 0; y < 25; y += 5) s[y + x] = b[y + x] ^ ~b[y + (x + 1) % 5] & MASK & b[y + (x + 2) % 5];
8616
- s[0] = s[0] ^ RC[round];
8617
- }
8618
- }
8619
- function keccak256Hex(bytes) {
8620
- const rate = 136;
8621
- const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
8622
- padded.set(bytes);
8623
- padded[bytes.length] = padded[bytes.length] ^ 1;
8624
- padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
8625
- const s = new Array(25).fill(0n);
8626
- for (let off = 0; off < padded.length; off += rate) {
8627
- for (let i = 0; i < rate / 8; i++) {
8628
- let lane = 0n;
8629
- for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
8630
- s[i] = s[i] ^ lane;
8631
- }
8632
- keccakF(s);
8633
- }
8634
- let out = "";
8635
- for (let i = 0; i < 4; i++) for (let j = 0; j < 8; j++) out += Number(s[i] >> BigInt(8 * j) & 0xffn).toString(16).padStart(2, "0");
8636
- return out;
8637
- }
8638
- function toChecksumAddress(address) {
8639
- const lower2 = address.slice(2).toLowerCase();
8640
- const hash2 = keccak256Hex(new TextEncoder().encode(lower2));
8641
- let out = "0x";
8642
- for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower2[i].toUpperCase() : lower2[i];
8643
- return out;
8644
- }
8645
- function hasValidChecksum(address) {
8646
- if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
8647
- const body = address.slice(2);
8648
- if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
8649
- return toChecksumAddress(address) === address;
8650
- }
8651
9896
  function ArrowLeft() {
8652
9897
  return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
8653
9898
  /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M6.38 3.95312L2.33333 7.99979L6.38 12.0465", stroke: "currentColor", strokeWidth: "1.2", strokeMiterlimit: "10", strokeLinecap: "round", strokeLinejoin: "round" }),
@@ -9328,7 +10573,7 @@ function IdentityLine(props) {
9328
10573
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-link-id", children: [
9329
10574
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-icon", children: /* @__PURE__ */ jsxRuntime.jsx(WalletGlyph, {}) }),
9330
10575
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-link-id-text", children: [
9331
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-primary", children: props.account ? shortAddress2(props.account) : "ZeroDelta Link" }),
10576
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-primary", children: props.account ? shortAddress3(props.account) : "ZeroDelta Link" }),
9332
10577
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-secondary", children: props.email ? props.email : props.account ? "Connected wallet" : "Connect your wallet to continue" })
9333
10578
  ] }),
9334
10579
  props.account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }) : null
@@ -9475,9 +10720,9 @@ function PaymentIsland(props) {
9475
10720
  const optionStates = react.useMemo(() => {
9476
10721
  const map = {};
9477
10722
  for (const a of annotated) {
9478
- const key = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
10723
+ const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
9479
10724
  if (!a.balance || holdings.loading) {
9480
- map[key] = { disabled: false, reason: "checking" };
10725
+ map[key2] = { disabled: false, reason: "checking" };
9481
10726
  continue;
9482
10727
  }
9483
10728
  let zero = false;
@@ -9486,9 +10731,9 @@ function PaymentIsland(props) {
9486
10731
  } catch {
9487
10732
  zero = false;
9488
10733
  }
9489
- if (zero) map[key] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
9490
- else if (a.affordable === false) map[key] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
9491
- else map[key] = { disabled: false };
10734
+ if (zero) map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
10735
+ else if (a.affordable === false) map[key2] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
10736
+ else map[key2] = { disabled: false };
9492
10737
  }
9493
10738
  return map;
9494
10739
  }, [annotated, holdings.loading]);
@@ -9528,19 +10773,19 @@ function PaymentIsland(props) {
9528
10773
  if (!catalogue?.ready) return void 0;
9529
10774
  const states2 = {};
9530
10775
  for (const token of catalogue.tokens) {
9531
- const key = balanceKey(Number(token.chainId), token.address);
10776
+ const key2 = balanceKey(Number(token.chainId), token.address);
9532
10777
  const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
9533
10778
  if (measured) {
9534
- states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
10779
+ states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
9535
10780
  continue;
9536
10781
  }
9537
10782
  const verdict = destinationAvailability(token, catalogue, exFromToken);
9538
10783
  if (verdict === "available") {
9539
10784
  const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
9540
- if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
10785
+ if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
9541
10786
  continue;
9542
10787
  }
9543
- states2[key] = {
10788
+ states2[key2] = {
9544
10789
  disabled: true,
9545
10790
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
9546
10791
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
@@ -9553,9 +10798,9 @@ function PaymentIsland(props) {
9553
10798
  const seen = /* @__PURE__ */ new Set();
9554
10799
  const list = [];
9555
10800
  for (const r of visibleRoutes) {
9556
- const key = balanceKey(r.source.chainId, r.source.tokenAddress);
9557
- if (seen.has(key)) continue;
9558
- seen.add(key);
10801
+ const key2 = balanceKey(r.source.chainId, r.source.tokenAddress);
10802
+ if (seen.has(key2)) continue;
10803
+ seen.add(key2);
9559
10804
  const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
9560
10805
  list.push(
9561
10806
  reg ?? {
@@ -9895,7 +11140,7 @@ function PaymentIsland(props) {
9895
11140
  ] }),
9896
11141
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
9897
11142
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
9898
- (flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : ""
11143
+ (flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : ""
9899
11144
  ] }),
9900
11145
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
9901
11146
  ] }),
@@ -10208,9 +11453,9 @@ function PayCard(props) {
10208
11453
  const optionStates = react.useMemo(() => {
10209
11454
  const map = {};
10210
11455
  for (const a of annotated) {
10211
- const key = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
11456
+ const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
10212
11457
  if (!a.balance || holdings.loading) {
10213
- map[key] = { disabled: false, reason: "checking" };
11458
+ map[key2] = { disabled: false, reason: "checking" };
10214
11459
  continue;
10215
11460
  }
10216
11461
  let zero = false;
@@ -10220,23 +11465,23 @@ function PayCard(props) {
10220
11465
  zero = false;
10221
11466
  }
10222
11467
  if (zero) {
10223
- map[key] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
11468
+ map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
10224
11469
  } else if (a.affordable === false) {
10225
- map[key] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
11470
+ map[key2] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
10226
11471
  } else {
10227
- map[key] = { disabled: false };
11472
+ map[key2] = { disabled: false };
10228
11473
  }
10229
11474
  }
10230
11475
  for (const o of unquoted) {
10231
- const key = balanceKey(o.chainId, o.address);
10232
- if (map[key]) continue;
11476
+ const key2 = balanceKey(o.chainId, o.address);
11477
+ if (map[key2]) continue;
10233
11478
  let zero = false;
10234
11479
  try {
10235
- zero = BigInt(listBalances[key]?.raw ?? "x") === 0n;
11480
+ zero = BigInt(listBalances[key2]?.raw ?? "x") === 0n;
10236
11481
  } catch {
10237
11482
  zero = false;
10238
11483
  }
10239
- map[key] = zero ? { disabled: true, reason: "no-balance", hint: "No balance on this chain" } : { disabled: false };
11484
+ map[key2] = zero ? { disabled: true, reason: "no-balance", hint: "No balance on this chain" } : { disabled: false };
10240
11485
  }
10241
11486
  return map;
10242
11487
  }, [annotated, holdings.loading, unquoted, listBalances]);
@@ -10250,9 +11495,9 @@ function PayCard(props) {
10250
11495
  const seen = /* @__PURE__ */ new Set();
10251
11496
  const list = [];
10252
11497
  const push = (chainId, address, fallback) => {
10253
- const key = balanceKey(chainId, address);
10254
- if (seen.has(key)) return;
10255
- seen.add(key);
11498
+ const key2 = balanceKey(chainId, address);
11499
+ if (seen.has(key2)) return;
11500
+ seen.add(key2);
10256
11501
  list.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
10257
11502
  };
10258
11503
  for (const r of visibleRoutes) {
@@ -10326,13 +11571,13 @@ function PayCard(props) {
10326
11571
  const option = unquoted.find((o) => o.chainId === pick.chainId && o.symbolKey === symbolKey(pick.symbol));
10327
11572
  closeSelector();
10328
11573
  if (!option || !wallet.account) return;
10329
- const key = balanceKey(option.chainId, option.address);
10330
- setPricing(key);
11574
+ const key2 = balanceKey(option.chainId, option.address);
11575
+ setPricing(key2);
10331
11576
  userPicked.current = true;
10332
11577
  engine.quotePayOption({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, wallet.account, { chainId: option.chainId, address: option.address }, { chainId: wallet.chainId ?? void 0, fundingAssets: planFundingAssets }).then((route) => flow.addRoute(route)).catch(() => {
10333
- setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key]));
11578
+ setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key2]));
10334
11579
  setPickError(`${option.ticker || option.symbol} on ${option.chainName} cannot settle this payment right now. Pick another way to pay.`);
10335
- }).finally(() => setPricing((cur) => cur === key ? null : cur));
11580
+ }).finally(() => setPricing((cur) => cur === key2 ? null : cur));
10336
11581
  };
10337
11582
  const parked = !isLiveMethod(method);
10338
11583
  const submitting = flow.status === "submitting";
@@ -10365,7 +11610,7 @@ function PayCard(props) {
10365
11610
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-wallet", "data-connected": "true", children: [
10366
11611
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
10367
11612
  " ",
10368
- shortAddress2(wallet.account)
11613
+ shortAddress3(wallet.account)
10369
11614
  ] })
10370
11615
  ] }) : /* @__PURE__ */ jsxRuntime.jsx("span", {});
10371
11616
  const nativeWei = sel ? routeNativeValue(sel) : 0n;
@@ -10405,7 +11650,7 @@ function PayCard(props) {
10405
11650
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
10406
11651
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
10407
11652
  " \xB7 ",
10408
- shortAddress2(props.recipient)
11653
+ shortAddress3(props.recipient)
10409
11654
  ] }),
10410
11655
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
10411
11656
  ] }),
@@ -10573,7 +11818,7 @@ function StableGenieSwap(props) {
10573
11818
  ] }),
10574
11819
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
10575
11820
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
10576
- recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
11821
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
10577
11822
  ] }),
10578
11823
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
10579
11824
  ] }),
@@ -10637,7 +11882,7 @@ function useSolanaSourceFlow(args) {
10637
11882
  const planArgs = react.useRef(null);
10638
11883
  const changedWhileBusy = react.useRef(false);
10639
11884
  const addressed = Boolean(owner && payer && recipient2);
10640
- const key = keyOf(args);
11885
+ const key2 = keyOf(args);
10641
11886
  react.useEffect(() => {
10642
11887
  const id = ++req.current;
10643
11888
  if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
@@ -10671,7 +11916,7 @@ function useSolanaSourceFlow(args) {
10671
11916
  const quoted = await engine.quoteSolanaSource(input);
10672
11917
  const built = await engine.buildSolanaSourcePlan(input, quoted);
10673
11918
  if (id !== req.current) return;
10674
- planKey.current = key;
11919
+ planKey.current = key2;
10675
11920
  planArgs.current = { ...latest.current };
10676
11921
  setPreview(quoted);
10677
11922
  setPlan(built);
@@ -10687,7 +11932,7 @@ function useSolanaSourceFlow(args) {
10687
11932
  }
10688
11933
  }, 350);
10689
11934
  return () => clearTimeout(timer2);
10690
- }, [engine, enabled, key, addressed, nonce]);
11935
+ }, [engine, enabled, key2, addressed, nonce]);
10691
11936
  react.useEffect(() => {
10692
11937
  let alive = true;
10693
11938
  setBalanceRaw(void 0);
@@ -11011,11 +12256,11 @@ function ExchangeCard(props) {
11011
12256
  const [fiatCurrency, setFiatCurrency] = react.useState(props.fiatCurrency ?? "EUR");
11012
12257
  const sellableFrom = react.useCallback((t) => t && product === "rwa" && !isSellableRwa(t) ? null : t, [product]);
11013
12258
  const fromToken = react.useMemo(() => from ? sellableFrom(findToken(tokens, from.chainId, from.symbol)) : null, [tokens, from, sellableFrom]);
11014
- const toToken = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
11015
- const toSymbol = toToken?.symbol ?? to?.symbol ?? "";
12259
+ const toToken2 = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
12260
+ const toSymbol = toToken2?.symbol ?? to?.symbol ?? "";
11016
12261
  const fromTicker = fromToken ? tokenTicker(fromToken) : from?.symbol ?? "";
11017
- const toTicker = toToken ? tokenTicker(toToken) : toSymbol;
11018
- const fromPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(sourceTokens, toToken) : sourceTokens, [product, sourceTokens, toToken]);
12262
+ const toTicker = toToken2 ? tokenTicker(toToken2) : toSymbol;
12263
+ const fromPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(sourceTokens, toToken2) : sourceTokens, [product, sourceTokens, toToken2]);
11019
12264
  const toPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(tokens, fromToken) : tokens, [product, tokens, fromToken]);
11020
12265
  const rwaSeeded = react.useRef(false);
11021
12266
  react.useEffect(() => {
@@ -11032,19 +12277,19 @@ function ExchangeCard(props) {
11032
12277
  if (!catalogue?.ready) return void 0;
11033
12278
  const states2 = {};
11034
12279
  for (const token of catalogue.tokens) {
11035
- const key = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
12280
+ const key2 = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
11036
12281
  const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
11037
12282
  if (measured) {
11038
- states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
12283
+ states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
11039
12284
  continue;
11040
12285
  }
11041
12286
  const verdict = destinationAvailability(token, catalogue, fromToken);
11042
12287
  if (verdict === "available") {
11043
12288
  const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
11044
- if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
12289
+ if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
11045
12290
  continue;
11046
12291
  }
11047
- states2[key] = {
12292
+ states2[key2] = {
11048
12293
  disabled: true,
11049
12294
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
11050
12295
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
@@ -11060,8 +12305,8 @@ function ExchangeCard(props) {
11060
12305
  const amountValid = /^\d+(\.\d+)?$/.test(normalizedAmount) && Number(normalizedAmount) > 0 && Number(normalizedAmount) <= 1e9;
11061
12306
  const rampMode = mode !== "exchange";
11062
12307
  const laneLimit = react.useMemo(
11063
- () => mode === "exchange" && fromToken && toToken ? laneLimitFor(toToken, fromToken, catalogue?.limitedLanes) : void 0,
11064
- [mode, catalogue, fromToken, toToken]
12308
+ () => mode === "exchange" && fromToken && toToken2 ? laneLimitFor(toToken2, fromToken, catalogue?.limitedLanes) : void 0,
12309
+ [mode, catalogue, fromToken, toToken2]
11065
12310
  );
11066
12311
  const limitSymbol = laneLimit ? laneLimitSymbol(laneLimit, fromTicker) : "";
11067
12312
  const overLimit = react.useMemo(() => {
@@ -11215,11 +12460,11 @@ function ExchangeCard(props) {
11215
12460
  useFitText(receiveSideRef, receiveShown);
11216
12461
  const toDecimals = react.useMemo(() => {
11217
12462
  try {
11218
- return toToken ? assetDecimals(toToken) : void 0;
12463
+ return toToken2 ? assetDecimals(toToken2) : void 0;
11219
12464
  } catch {
11220
12465
  return void 0;
11221
12466
  }
11222
- }, [toToken]);
12467
+ }, [toToken2]);
11223
12468
  const meta = solActive ? solFlow.preview ? { bridge: solFlow.preview.bridge || "ZeroDelta", feeBps: solFlow.preview.feeBps, duration: solFlow.preview.estimatedDuration } : null : addressed ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
11224
12469
  const pct = (p) => {
11225
12470
  if (!fromBal || !fromToken) return;
@@ -11431,7 +12676,7 @@ function ExchangeCard(props) {
11431
12676
  ] }),
11432
12677
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
11433
12678
  solDelivery.phase === "tracking" ? "Submitted on Solana \u2014 tracking delivery" : deliveryHeadline(solDelivery, true),
11434
- solFlow.sent?.recipient ? ` \xB7 ${shortAddress2(solFlow.sent.recipient)}` : ""
12679
+ solFlow.sent?.recipient ? ` \xB7 ${shortAddress3(solFlow.sent.recipient)}` : ""
11435
12680
  ] }),
11436
12681
  /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: solDelivery })
11437
12682
  ] }),
@@ -11452,7 +12697,7 @@ function ExchangeCard(props) {
11452
12697
  ] }),
11453
12698
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
11454
12699
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
11455
- recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
12700
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
11456
12701
  ] }),
11457
12702
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
11458
12703
  ] }),
@@ -11463,7 +12708,7 @@ function ExchangeCard(props) {
11463
12708
  ] });
11464
12709
  } else {
11465
12710
  const payToken = mode === "onramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You pay", symbol: from?.symbol ?? null, chainId: from?.chainId ?? null, chainName: nameOf(from?.chainId), token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") });
11466
- const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, chainName: nameOf(to?.chainId), token: toToken, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") });
12711
+ const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, chainName: nameOf(to?.chainId), token: toToken2, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") });
11467
12712
  const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
11468
12713
  solanaSteps,
11469
12714
  solanaCta,
@@ -11486,7 +12731,7 @@ function ExchangeCard(props) {
11486
12731
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ft", children: [
11487
12732
  mode === "onramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatTile, { label: "From", currency: fiatCurrency, onCurrency: setFiatCurrency }) : /* @__PURE__ */ jsxRuntime.jsx(TokenTile, { label: "From", pick: from, chainName: nameOf(from?.chainId), token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") }),
11488
12733
  /* @__PURE__ */ jsxRuntime.jsx(FlipButton, { small: true, onClick: flip, disabled: !flippable }),
11489
- mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatTile, { label: "To", currency: fiatCurrency, onCurrency: setFiatCurrency }) : /* @__PURE__ */ jsxRuntime.jsx(TokenTile, { label: "To", pick: to, chainName: nameOf(to?.chainId), token: toToken, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") })
12734
+ mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatTile, { label: "To", currency: fiatCurrency, onCurrency: setFiatCurrency }) : /* @__PURE__ */ jsxRuntime.jsx(TokenTile, { label: "To", pick: to, chainName: nameOf(to?.chainId), token: toToken2, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") })
11490
12735
  ] }),
11491
12736
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane", "data-kind": "send", children: [
11492
12737
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane-top", children: [
@@ -11580,7 +12825,7 @@ function ExchangeCard(props) {
11580
12825
  side = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-side-body", children: [
11581
12826
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv", children: [
11582
12827
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-line", children: [
11583
- /* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl: toToken?.logoUrl, chainId: to?.chainId, size: "xs" }),
12828
+ /* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl: toToken2?.logoUrl, chainId: to?.chainId, size: "xs" }),
11584
12829
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-recv-amt", ref: receiveSideRef, children: /* @__PURE__ */ jsxRuntime.jsx(AmountText, { value: formatCalculatedAmount(receive, toDecimals), exact: receive, suffix: toTicker }) })
11585
12830
  ] }),
11586
12831
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-sub", children: [