@glacislabs/stablegenie-zerodelta 4.18.2 → 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
@@ -581,6 +581,58 @@ 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);
@@ -679,7 +732,15 @@ var STEP_LABEL = {
679
732
  arrived: "Arrived",
680
733
  filled: "Filled",
681
734
  outbound_bridging: "Bridging",
682
- 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"
683
744
  };
684
745
  var label = (name) => STEP_LABEL[name] ?? name.replace(/_/g, " ");
685
746
  function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
@@ -688,12 +749,14 @@ function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
688
749
  case "delivered":
689
750
  return "Delivered";
690
751
  case "failed":
752
+ if (delivery.status === "cancelled" && delivery.refunded) return "Cancelled \u2014 refunded to the owner";
691
753
  return delivery.status === "cancelled" ? "Cancelled \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
692
754
  case "attention":
693
755
  return delivery.status === "cancel_pending" ? "Being cancelled \u2014 not delivered" : "Waiting to be claimed \u2014 open the transaction";
694
756
  case "in-progress": {
695
757
  if (delivery.status === "continuing") return "On its way \u2014 final leg next";
696
758
  const next = delivery.steps.find((s) => !s.done);
759
+ if (next?.name === "route") return "On its way";
697
760
  return next ? `On its way \u2014 ${label(next.name).toLowerCase()} next` : "On its way";
698
761
  }
699
762
  case "unavailable":
@@ -915,7 +978,7 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
915
978
  8453: "Base",
916
979
  9745: "Plasma",
917
980
  34443: "Mode",
918
- 42161: "Arbitrum One",
981
+ 42161: "Arbitrum",
919
982
  // "Avalanche", as the dApp prints it since zd-dapp#582 (from ZD Heavy's /chains). The widget's
920
983
  // registry read lists no row for a payout-only chain, so this table is what names it here.
921
984
  43114: "Avalanche",
@@ -991,8 +1054,8 @@ var SOLANA_DESTINATION_ASSETS = Object.freeze({
991
1054
  AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
992
1055
  });
993
1056
  function solanaDestinationAsset(mint) {
994
- const key = typeof mint === "string" ? mint.trim() : "";
995
- 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;
996
1059
  }
997
1060
  function solanaBridgeOf(token) {
998
1061
  const pinned = solanaDestinationAsset(token.address);
@@ -1366,9 +1429,9 @@ function hexBytes(hex) {
1366
1429
  if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
1367
1430
  return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
1368
1431
  }
1369
- function solanaKeyBytes(key) {
1370
- if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
1371
- 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);
1372
1435
  }
1373
1436
  var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1374
1437
  function base64Decode(text) {
@@ -1714,16 +1777,16 @@ function tokenTicker(token) {
1714
1777
  }
1715
1778
  function tickerOn(tokens, chainId, symbol) {
1716
1779
  if (!symbol || !chainId || !tokens?.length) return symbol;
1717
- const key = symbolKey(symbol);
1718
- 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);
1719
1782
  return deployment ? tokenTicker(deployment) : symbol;
1720
1783
  }
1721
1784
 
1722
1785
  // src/core/availability.ts
1723
1786
  function assetClassOf(symbol) {
1724
- const key = symbolKey(symbol);
1725
- if (TRADEABLE_RWA_ASSETS.has(key)) return "rwa";
1726
- 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";
1727
1790
  return null;
1728
1791
  }
1729
1792
  var NEST_VAULT_SHARES = /* @__PURE__ */ new Set(["NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON"]);
@@ -1832,8 +1895,8 @@ function buildCatalogue(input) {
1832
1895
  if (product === "rwa") return true;
1833
1896
  if (execution.has(chainId) || token.isChainedDestination === true) return true;
1834
1897
  if (!isExecutableBridge(token)) return false;
1835
- const key = tokenKey(token.chainId, token.address);
1836
- return source2.has(key) || destination.has(key);
1898
+ const key2 = tokenKey(token.chainId, token.address);
1899
+ return source2.has(key2) || destination.has(key2);
1837
1900
  });
1838
1901
  const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
1839
1902
  const catalogue = ready ? projectedCatalogue : allowed;
@@ -1877,8 +1940,8 @@ function tokenEnabled(token) {
1877
1940
  return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
1878
1941
  }
1879
1942
  function findToken(tokens, chainId, symbol) {
1880
- const key = symbolKey(symbol);
1881
- 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;
1882
1945
  }
1883
1946
  function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
1884
1947
  const invoiceKey = symbolKey(invoiceAsset);
@@ -1912,10 +1975,10 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
1912
1975
  const chainId = Number(token.chainId);
1913
1976
  const chain2 = chainById(chains, chainId);
1914
1977
  if (!chainSelectable(chain2, chainId)) continue;
1915
- const key = tokenKey(chainId, token.address);
1916
- if (seen.has(key)) continue;
1978
+ const key2 = tokenKey(chainId, token.address);
1979
+ if (seen.has(key2)) continue;
1917
1980
  if (refusal(token)) continue;
1918
- seen.add(key);
1981
+ seen.add(key2);
1919
1982
  const payKey = symbolKey(token.symbol);
1920
1983
  const direct2 = chainId === invoiceChain && payKey === invoiceKey;
1921
1984
  options.push({
@@ -2101,7 +2164,7 @@ function normalizePreview(request, quote, to, amount) {
2101
2164
  async function quoteSolanaSource(api, input) {
2102
2165
  const { from, to, amount } = selections(input, await api.fetchTokens());
2103
2166
  const request = makeRequest(input, from, to, amount);
2104
- 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 });
2105
2168
  const preview = normalizePreview(request, quote, to, input.amountIn);
2106
2169
  quoteRequests.set(preview, { api, request: clone(request) });
2107
2170
  return preview;
@@ -2115,7 +2178,7 @@ async function previewSolanaSource(api, input) {
2115
2178
  raw(amount, "input amount", true);
2116
2179
  const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
2117
2180
  const request = body;
2118
- 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 });
2119
2182
  const option = quote?.options?.[0];
2120
2183
  if (!option) throw new Error("Native quote returned no options.");
2121
2184
  const receive = raw(option.finalAmount, "quoted output", true);
@@ -2472,8 +2535,8 @@ function historyKey(value) {
2472
2535
  var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
2473
2536
  function tokenAt(tokens, chainId, address) {
2474
2537
  if (!address) return void 0;
2475
- const key = historyKey(address);
2476
- 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);
2477
2540
  }
2478
2541
  function amountOf(raw2, token, rowDecimals, rowAmount) {
2479
2542
  const decimals = token ? Number(token.decimals) : Number(rowDecimals);
@@ -2559,13 +2622,13 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
2559
2622
  const out = [];
2560
2623
  const seen = /* @__PURE__ */ new Set();
2561
2624
  for (const entry of local) {
2562
- const key = historyKey(entry.hash);
2563
- if (seen.has(key)) continue;
2564
- seen.add(key);
2565
- 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);
2566
2629
  out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
2567
2630
  }
2568
- 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);
2569
2632
  return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
2570
2633
  }
2571
2634
 
@@ -2676,12 +2739,12 @@ function suppressedLanes(health) {
2676
2739
  const out = /* @__PURE__ */ new Map();
2677
2740
  for (const lane of health.lanes) {
2678
2741
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
2679
- const key = healthLaneKey(lane.laneKey);
2680
- if (!key) continue;
2742
+ const key2 = healthLaneKey(lane.laneKey);
2743
+ if (!key2) continue;
2681
2744
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
2682
2745
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
2683
2746
  const message = typeof availability?.message === "string" && availability.message ? availability.message : lane.message;
2684
- out.set(key, {
2747
+ out.set(key2, {
2685
2748
  route: typeof lane.route === "string" ? lane.route : "",
2686
2749
  code: typeof code === "string" ? code : "",
2687
2750
  message: typeof message === "string" ? message : "",
@@ -2696,15 +2759,15 @@ function limitedLanes(health) {
2696
2759
  const out = /* @__PURE__ */ new Map();
2697
2760
  for (const lane of health.lanes) {
2698
2761
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
2699
- const key = healthLaneKey(lane.laneKey);
2762
+ const key2 = healthLaneKey(lane.laneKey);
2700
2763
  const limit = lane.availability?.limit;
2701
- if (!key || !limit || typeof limit !== "object") continue;
2764
+ if (!key2 || !limit || typeof limit !== "object") continue;
2702
2765
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
2703
2766
  const maxAmount = typeof limit.maxAmount === "string" ? limit.maxAmount.trim() : "";
2704
2767
  const decimals = limit.decimals;
2705
2768
  if (!side || !BASE_UNITS.test(maxAmount) || typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
2706
2769
  const code = lane.availability?.code;
2707
- out.set(key, {
2770
+ out.set(key2, {
2708
2771
  side,
2709
2772
  token: typeof limit.token === "string" ? limit.token : "",
2710
2773
  fromChainId: Number(limit.fromChainId) || 0,
@@ -2767,10 +2830,10 @@ function resolveVaultIcon(apiBase, iconPath) {
2767
2830
  function vaultIconsBySymbol(apiBase, vaults) {
2768
2831
  const out = /* @__PURE__ */ new Map();
2769
2832
  for (const vault of vaults) {
2770
- const key = symbolKey(vault?.symbol);
2771
- if (!key || out.has(key)) continue;
2833
+ const key2 = symbolKey(vault?.symbol);
2834
+ if (!key2 || out.has(key2)) continue;
2772
2835
  const url = resolveVaultIcon(apiBase, vault?.iconMiniUrl) ?? resolveVaultIcon(apiBase, vault?.iconUrl);
2773
- if (url) out.set(key, url);
2836
+ if (url) out.set(key2, url);
2774
2837
  }
2775
2838
  return out;
2776
2839
  }
@@ -2867,7 +2930,7 @@ var CATEGORY_PHRASES = {
2867
2930
  UNKNOWN: "an unrecognized risk"
2868
2931
  };
2869
2932
  function categoryLabel(code) {
2870
- const key = code.trim().toUpperCase();
2933
+ const key2 = code.trim().toUpperCase();
2871
2934
  const LABELS = {
2872
2935
  SANCTIONS: "Sanctions",
2873
2936
  TERRORISM_FINANCING: "Terrorist financing",
@@ -2882,7 +2945,7 @@ function categoryLabel(code) {
2882
2945
  UNCLASSIFIED: "Unclassified risk",
2883
2946
  UNKNOWN: "Unclassified risk"
2884
2947
  };
2885
- return LABELS[key] ?? key.toLowerCase().replace(/_/g, " ");
2948
+ return LABELS[key2] ?? key2.toLowerCase().replace(/_/g, " ");
2886
2949
  }
2887
2950
  function cleanJurisdiction(code) {
2888
2951
  return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
@@ -2995,9 +3058,9 @@ function distinctScreenedWallets(compliance) {
2995
3058
  for (const raw2 of compliance?.screenedWallets ?? []) {
2996
3059
  const address = raw2?.trim();
2997
3060
  if (!address) continue;
2998
- const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
2999
- if (seen.has(key)) continue;
3000
- 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);
3001
3064
  wallets.push(address);
3002
3065
  }
3003
3066
  return wallets;
@@ -3108,9 +3171,9 @@ var TUNED_OUTCOMES = {
3108
3171
  UNCLASSIFIED: "flagged"
3109
3172
  };
3110
3173
  function screeningOutcomeOf(category) {
3111
- const key = category.trim().toUpperCase();
3112
- if (FLOOR_CATEGORIES.includes(key)) return "always-blocked";
3113
- 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;
3114
3177
  }
3115
3178
  var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
3116
3179
  var SCREENING_BUCKETS = [
@@ -3119,6 +3182,91 @@ var SCREENING_BUCKETS = [
3119
3182
  { outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
3120
3183
  ];
3121
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
+
3122
3270
  // src/core/solve.ts
3123
3271
  async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
3124
3272
  const destDecimals = assetDecimals(destinationToken);
@@ -3165,7 +3313,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3165
3313
  let bestGuess = guess;
3166
3314
  for (let i = 0; i < 3; i += 1) {
3167
3315
  const guessSent = guess;
3168
- const quote = await fetchQuote({
3316
+ const quote = selectQuoteOption(await fetchQuote({
3169
3317
  fromChainId: option.chainId,
3170
3318
  toChainId: Number(destination.chainId),
3171
3319
  fromToken: option.symbol,
@@ -3173,11 +3321,11 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3173
3321
  fromAmount: guessSent.toString(),
3174
3322
  owner: payer,
3175
3323
  destinationReceiver: destination.address
3176
- });
3324
+ }));
3177
3325
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
3178
3326
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3179
3327
  }
3180
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3328
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3181
3329
  const final = finalOf(quote);
3182
3330
  if (final > bestFinal) {
3183
3331
  bestFinal = final;
@@ -3214,7 +3362,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3214
3362
  directTransfer: false,
3215
3363
  quote: best,
3216
3364
  youPayRaw: bestGuess.toString(),
3217
- recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
3365
+ recipientReceivesRaw: deliveredAmount(best, isSolanaChainId(destination.chainId)).toString(),
3218
3366
  targetRaw: targetRaw.toString(),
3219
3367
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
3220
3368
  meetsTarget: bestFinal >= targetRaw,
@@ -3224,7 +3372,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3224
3372
  async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
3225
3373
  const fromRaw = BigInt(amountInRaw || "0");
3226
3374
  if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
3227
- const quote = await fetchQuote({
3375
+ const quote = selectQuoteOption(await fetchQuote({
3228
3376
  fromChainId: option.chainId,
3229
3377
  toChainId: Number(destination.chainId),
3230
3378
  fromToken: option.symbol,
@@ -3232,11 +3380,11 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3232
3380
  fromAmount: fromRaw.toString(),
3233
3381
  owner: payer,
3234
3382
  destinationReceiver: destination.address
3235
- });
3383
+ }));
3236
3384
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
3237
3385
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3238
3386
  }
3239
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3387
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3240
3388
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3241
3389
  return {
3242
3390
  directTransfer: false,
@@ -3249,6 +3397,24 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3249
3397
  iterations: 1
3250
3398
  };
3251
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
+ }
3252
3418
 
3253
3419
  // src/core/order.ts
3254
3420
  var DEFAULT_DEADLINE_SECONDS = 1800;
@@ -3368,6 +3534,954 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
3368
3534
  }
3369
3535
  }
3370
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
+
3371
4485
  // src/core/route.ts
3372
4486
  function routeDeltaLabel(result, quote) {
3373
4487
  if (result.directTransfer) return "~0";
@@ -3388,9 +4502,9 @@ function routeLabelFor(option, destinationToken, result) {
3388
4502
  const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
3389
4503
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
3390
4504
  }
3391
- function tokenAt2(tokens, chainId, address) {
3392
- const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
3393
- 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;
3394
4508
  if (!wanted || !tokens?.length) return void 0;
3395
4509
  return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
3396
4510
  }
@@ -3412,7 +4526,7 @@ function buildLegs(orders, ctx) {
3412
4526
  const order = orders[index];
3413
4527
  const isLast = index === orders.length - 1;
3414
4528
  const toChainId = Number(order.destinationChainId);
3415
- const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
4529
+ const askToken = isLast ? ctx.destinationToken : tokenAt3(ctx.tokens, toChainId, order.askToken);
3416
4530
  const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
3417
4531
  const toTicker = askToken ? tokenTicker(askToken) : "";
3418
4532
  const toDecimals = askToken ? assetDecimals(askToken) : void 0;
@@ -3439,19 +4553,42 @@ function buildLegs(orders, ctx) {
3439
4553
  }
3440
4554
  return legs;
3441
4555
  }
3442
- async function buildRoute({
3443
- option,
3444
- destination,
3445
- destinationToken,
3446
- chains,
3447
- tokens,
3448
- payer,
3449
- fetchQuote,
3450
- solve = solveExactOut,
3451
- amountInRaw,
3452
- compliance
3453
- }) {
4556
+ async function buildRoute(args) {
4557
+ const { option, destination, destinationToken, payer, fetchQuote, amountInRaw } = args;
4558
+ const solve = args.solve ?? solveExactOut;
3454
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) {
3455
4592
  const quote = result.quote;
3456
4593
  const destDecimals = assetDecimals(destinationToken);
3457
4594
  const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
@@ -3526,6 +4663,9 @@ async function buildRoute({
3526
4663
  }
3527
4664
  };
3528
4665
  }
4666
+ if (quote.protocol === "zdheavy") {
4667
+ return buildZdHeavyRoute({ option, destination, destinationToken, chains, tokens: tokens ?? [], routes: routes ?? [], payer, result });
4668
+ }
3529
4669
  const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
3530
4670
  if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
3531
4671
  const sourceChain = chainById(chains, option.chainId);
@@ -3627,12 +4767,134 @@ async function buildRoute({
3627
4767
  };
3628
4768
  }
3629
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
+
3630
4892
  // src/core/channel.ts
3631
4893
  var CHANNEL_HEADER = "x-zd-channel";
3632
4894
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
3633
4895
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
3634
4896
  var WIDGET_CHANNEL = "widget";
3635
- var WIDGET_VERSION = "4.18.2" ;
4897
+ var WIDGET_VERSION = "4.19.0" ;
3636
4898
  var MAX_CHANNEL_VERSION_LEN = 32;
3637
4899
  function sanitizeVersion(raw2) {
3638
4900
  const v = String(raw2).trim();
@@ -3724,7 +4986,7 @@ function classifyQuoteError(error) {
3724
4986
  function amountFieldError(error) {
3725
4987
  const fieldErrors = error?.fieldErrors;
3726
4988
  if (!Array.isArray(fieldErrors)) return null;
3727
- 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");
3728
4990
  const message = entry ? sanitizeMessage(entry.message, "") : "";
3729
4991
  return message || null;
3730
4992
  }
@@ -3740,7 +5002,7 @@ function wait(ms) {
3740
5002
  }
3741
5003
  var PAGE_LIMIT = 500;
3742
5004
  var MAX_PAGES = 10;
3743
- 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() });
3744
5006
  var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
3745
5007
  function registryCacheFor(scope) {
3746
5008
  if (!scope) return newRegistryCache();
@@ -3897,6 +5159,20 @@ function createApiClient(cfg) {
3897
5159
  return value;
3898
5160
  });
3899
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
+ }
3900
5176
  const priceCache = /* @__PURE__ */ new Map();
3901
5177
  async function fetchPrices(symbols) {
3902
5178
  const wanted = [...new Set(symbols.map((s) => String(s || "").toUpperCase()).filter((s) => /^[A-Z0-9]{1,16}$/.test(s)))];
@@ -3927,11 +5203,12 @@ function createApiClient(cfg) {
3927
5203
  return out;
3928
5204
  }
3929
5205
  async function fetchQuote(body, retries = 1) {
5206
+ const request = nativeQuoteRequest(body);
3930
5207
  let lastError;
3931
5208
  for (let attempt = 0; attempt <= retries; attempt += 1) {
3932
5209
  try {
3933
- const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(body), timeoutMs: 18e3 });
3934
- 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);
3935
5212
  } catch (error) {
3936
5213
  lastError = error;
3937
5214
  if (attempt >= retries || !isTransientQuoteError(error)) throw error;
@@ -3945,10 +5222,10 @@ function createApiClient(cfg) {
3945
5222
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
3946
5223
  const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3947
5224
  if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3948
- const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
3949
- 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);
3950
5227
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
3951
- const inflight = screenInflight.get(key);
5228
+ const inflight = screenInflight.get(key2);
3952
5229
  if (inflight) return inflight;
3953
5230
  const request = apiRequest("/screen/wallet", {
3954
5231
  method: "POST",
@@ -3959,12 +5236,12 @@ function createApiClient(cfg) {
3959
5236
  throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
3960
5237
  }
3961
5238
  const value = { ...screen, address: screen.address || addr };
3962
- screenCache.set(key, { at: Date.now(), value });
5239
+ screenCache.set(key2, { at: Date.now(), value });
3963
5240
  return value;
3964
5241
  }).finally(() => {
3965
- screenInflight.delete(key);
5242
+ screenInflight.delete(key2);
3966
5243
  });
3967
- screenInflight.set(key, request);
5244
+ screenInflight.set(key2, request);
3968
5245
  return request;
3969
5246
  }
3970
5247
  async function reportSubmission(report) {
@@ -3987,7 +5264,7 @@ function createApiClient(cfg) {
3987
5264
  return false;
3988
5265
  }
3989
5266
  }
3990
- 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 };
3991
5268
  }
3992
5269
 
3993
5270
  // src/core/plan.ts
@@ -4050,9 +5327,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4050
5327
  const balanceTargets = [];
4051
5328
  const seenTargets = /* @__PURE__ */ new Set();
4052
5329
  for (const option of options) {
4053
- const key = optionBalanceKey(option);
4054
- if (seenTargets.has(key)) continue;
4055
- seenTargets.add(key);
5330
+ const key2 = optionBalanceKey(option);
5331
+ if (seenTargets.has(key2)) continue;
5332
+ seenTargets.add(key2);
4056
5333
  balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
4057
5334
  }
4058
5335
  const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
@@ -4064,9 +5341,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4064
5341
  for (const raw2 of [payer, destination.address]) {
4065
5342
  const addr = String(raw2 || "").trim();
4066
5343
  if (!addr) continue;
4067
- const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
4068
- if (seenParty.has(key)) continue;
4069
- 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);
4070
5347
  parties.push(addr);
4071
5348
  }
4072
5349
  try {
@@ -4113,6 +5390,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4113
5390
  destinationToken,
4114
5391
  chains,
4115
5392
  tokens,
5393
+ routes,
4116
5394
  payer,
4117
5395
  fetchQuote: api.fetchQuote,
4118
5396
  compliance: option.direct ? directCompliance ?? void 0 : void 0
@@ -4173,7 +5451,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
4173
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))
4174
5452
  );
4175
5453
  if (!option) throw new Error("That funding option is not available for this payment right now.");
4176
- return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
5454
+ return buildRoute({ option, destination, destinationToken, chains, tokens, routes, payer, fetchQuote: api.fetchQuote });
4177
5455
  }
4178
5456
 
4179
5457
  // src/core/swap.ts
@@ -4181,13 +5459,13 @@ function validateSwap(swap = {}) {
4181
5459
  const fromChainId = Number(swap.fromChainId);
4182
5460
  const toChainId = Number(swap.toChainId);
4183
5461
  const fromToken = symbolKey(swap.fromToken);
4184
- const toToken = symbolKey(swap.toToken);
5462
+ const toToken2 = symbolKey(swap.toToken);
4185
5463
  if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
4186
5464
  if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
4187
- 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.");
4188
5466
  const amountIn = normalizeDecimalText(swap.amountIn);
4189
5467
  if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
4190
- return { fromChainId, toChainId, fromToken, toToken, amountIn };
5468
+ return { fromChainId, toChainId, fromToken, toToken: toToken2, amountIn };
4191
5469
  }
4192
5470
  function viaOf(quote, tokens) {
4193
5471
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
@@ -4237,7 +5515,7 @@ async function quoteSwapPreview(api, swap, owner) {
4237
5515
  async function buildSwapPlan(api, swap, payer, wallet = {}) {
4238
5516
  const v = validateSwap(swap);
4239
5517
  const account = assertAddress(payer, "Swap wallet");
4240
- const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
5518
+ const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
4241
5519
  const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
4242
5520
  const destToken = findToken(tokens, v.toChainId, v.toToken);
4243
5521
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
@@ -4260,7 +5538,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4260
5538
  direct: false
4261
5539
  };
4262
5540
  const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
4263
- 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 });
4264
5542
  if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
4265
5543
  route.recommended = true;
4266
5544
  return {
@@ -4281,88 +5559,6 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4281
5559
  };
4282
5560
  }
4283
5561
 
4284
- // src/core/validate-tx.ts
4285
- var lower = (v) => String(v || "").toLowerCase();
4286
- function isHexAddress(value) {
4287
- return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
4288
- }
4289
- function isHexData(value) {
4290
- return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value));
4291
- }
4292
- function isHexQuantity(value) {
4293
- return /^0x[0-9a-fA-F]+$/.test(String(value));
4294
- }
4295
- function dataWord(data, index) {
4296
- const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4297
- return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
4298
- }
4299
- function dataAddress(data, index) {
4300
- const word2 = dataWord(data, index);
4301
- return word2 ? `0x${word2.slice(24)}` : "";
4302
- }
4303
- function dataUint(data, index) {
4304
- const word2 = dataWord(data, index);
4305
- return word2 ? BigInt(`0x${word2}`) : null;
4306
- }
4307
- function rawEquals(value, expected) {
4308
- try {
4309
- return value === BigInt(expected || "0");
4310
- } catch {
4311
- return false;
4312
- }
4313
- }
4314
- function planMsgValueHex(route) {
4315
- try {
4316
- const raw2 = route?.quote?.msgValue;
4317
- if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4318
- return "0x" + BigInt(raw2).toString(16);
4319
- } catch {
4320
- return null;
4321
- }
4322
- }
4323
- function validatePlannedTransaction(tx, route, expectedRecipient) {
4324
- if (!tx || tx.mock) return true;
4325
- if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
4326
- const data = String(tx.data || "0x").toLowerCase();
4327
- const selector = data.slice(0, 10);
4328
- const value = lower(tx.value || "0x0");
4329
- if (tx.kind === "transfer") {
4330
- if (value !== "0x0") return false;
4331
- return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4332
- }
4333
- if (tx.kind === "approve") {
4334
- if (value !== "0x0") return false;
4335
- 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);
4336
- }
4337
- if (tx.kind === "submitOrder") {
4338
- const expected = planMsgValueHex(route);
4339
- if (expected === null || value !== lower(expected)) return false;
4340
- if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
4341
- const decoded = decodeSubmitOrderCalldata(data);
4342
- if (!decoded) return false;
4343
- const first = decoded.orders[0];
4344
- const last = decoded.orders[decoded.orders.length - 1];
4345
- 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));
4346
- }
4347
- return false;
4348
- }
4349
- function solanaDeliveryMatches(encoded, recipient2, mint) {
4350
- try {
4351
- return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4352
- } catch {
4353
- return false;
4354
- }
4355
- }
4356
- async function allowanceCovers(tx, account, ethCall2) {
4357
- if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4358
- try {
4359
- const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
4360
- return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4361
- } catch {
4362
- return false;
4363
- }
4364
- }
4365
-
4366
5562
  // src/core/verify.ts
4367
5563
  var TX_VERIFY_ATTEMPTS = 5;
4368
5564
  var TX_VERIFY_INTERVAL_MS = 2500;
@@ -4507,9 +5703,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4507
5703
  const seen = /* @__PURE__ */ new Set();
4508
5704
  for (const target of targets) {
4509
5705
  if (!target || !isAddress(target.tokenAddress)) continue;
4510
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4511
- if (seen.has(key)) continue;
4512
- seen.add(key);
5706
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5707
+ if (seen.has(key2)) continue;
5708
+ seen.add(key2);
4513
5709
  const chainId = Number(target.chainId);
4514
5710
  const group = groups.get(chainId) || [];
4515
5711
  group.push(target);
@@ -4518,8 +5714,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4518
5714
  function record(target, hex) {
4519
5715
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
4520
5716
  const raw2 = BigInt(hex || "0x0").toString();
4521
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4522
- 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)) };
4523
5719
  return true;
4524
5720
  }
4525
5721
  async function readOne(rpcUrl, target) {
@@ -4565,7 +5761,18 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4565
5761
  return null;
4566
5762
  }
4567
5763
  }
4568
- 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 };
4569
5776
  }
4570
5777
 
4571
5778
  // src/core/config.ts
@@ -4686,6 +5893,7 @@ function createEngine(config = {}) {
4686
5893
  fetchRouteHealth: api.fetchRouteHealth,
4687
5894
  fetchQuote: api.fetchQuote,
4688
5895
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
5896
+ fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
4689
5897
  fetchCatalogue: async (allowedAssets, product, options) => {
4690
5898
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
4691
5899
  api.fetchChains().catch(() => []),
@@ -5129,7 +6337,13 @@ function useFlow(args) {
5129
6337
  statusRef.current = status;
5130
6338
  const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
5131
6339
  const routes = plan?.routes ?? [];
5132
- 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]);
5133
6347
  const reload = react.useCallback(() => setNonce((n) => n + 1), []);
5134
6348
  const addRoute = react.useCallback((route) => {
5135
6349
  setPlan((p) => p ? { ...p, routes: [...p.routes.filter((r) => r.id !== route.id), route] } : p);
@@ -5184,11 +6398,11 @@ function useFlow(args) {
5184
6398
  if (!wallet.account || !src?.tokenAddress || src.decimals == null) return;
5185
6399
  (async () => {
5186
6400
  try {
5187
- const key = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
6401
+ const key2 = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
5188
6402
  const balances = await engine.readBalances(wallet.account, [
5189
6403
  { chainId: Number(src.chainId), tokenAddress: src.tokenAddress, decimals: Number(src.decimals) }
5190
6404
  ]);
5191
- const entry = balances[key];
6405
+ const entry = balances[key2];
5192
6406
  if (!entry) return;
5193
6407
  const need = parseUnitsDecimal(src.payAmount || src.amount, src.decimals);
5194
6408
  if (alive) setInsufficient(BigInt(entry.raw) < need);
@@ -5252,6 +6466,8 @@ function useFlow(args) {
5252
6466
  throw new Error(nativeFeeShortMessage(check2, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
5253
6467
  }
5254
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);
5255
6471
  const minNonce = await engine.payerNonceBaseline(Number(sourceChainId), account);
5256
6472
  const txs = route.transactions;
5257
6473
  let settleHash = "";
@@ -5267,7 +6483,7 @@ function useFlow(args) {
5267
6483
  patch(tx.id, "done");
5268
6484
  continue;
5269
6485
  }
5270
- if (!validatePlannedTransaction(tx, route, recipient2)) {
6486
+ if (!validatePlannedTransaction(tx, route, recipient2, heavyExpected ? { ...heavyExpected, nowSec: Math.floor(Date.now() / 1e3) } : void 0)) {
5271
6487
  throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
5272
6488
  }
5273
6489
  patch(tx.id, "active");
@@ -5338,6 +6554,98 @@ function useFlow(args) {
5338
6554
  busyRef.current = false;
5339
6555
  }
5340
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]);
5341
6649
  const quoteReady = status === "ready" && !!plan;
5342
6650
  const quotePaused = quoteReady && idle2;
5343
6651
  const quoteStale = quoteReady && (idle2 || planAt < returnedAt2);
@@ -5359,7 +6667,10 @@ function useFlow(args) {
5359
6667
  quoteStale,
5360
6668
  submit,
5361
6669
  reload,
5362
- addRoute
6670
+ addRoute,
6671
+ compare,
6672
+ selectOption,
6673
+ promotions
5363
6674
  };
5364
6675
  }
5365
6676
  var RETRY_DELAYS_MS = [800, 2400, 6e3];
@@ -5427,9 +6738,9 @@ function useHoldings(engine, account, routes, initialBalances) {
5427
6738
  const seeded = {};
5428
6739
  const missing = [];
5429
6740
  for (const target of targets) {
5430
- const key = balanceKey(target.chainId, target.tokenAddress);
5431
- const balance = initialBalances?.[key];
5432
- if (balance) seeded[key] = balance;
6741
+ const key2 = balanceKey(target.chainId, target.tokenAddress);
6742
+ const balance = initialBalances?.[key2];
6743
+ if (balance) seeded[key2] = balance;
5433
6744
  else missing.push(target);
5434
6745
  }
5435
6746
  setBalances(seeded);
@@ -6953,7 +8264,7 @@ function priceOf(prices, symbol) {
6953
8264
  const p = prices?.[String(symbol).toUpperCase()];
6954
8265
  return typeof p === "number" && Number.isFinite(p) ? p : void 0;
6955
8266
  }
6956
- function buildGroup(key, members, prices) {
8267
+ function buildGroup(key2, members, prices) {
6957
8268
  const tokens = members.map((m) => m.token);
6958
8269
  let amount = null;
6959
8270
  let usd2 = null;
@@ -6965,7 +8276,7 @@ function buildGroup(key, members, prices) {
6965
8276
  }
6966
8277
  const first = members[0].token;
6967
8278
  return {
6968
- key,
8279
+ key: key2,
6969
8280
  symbol: dominantSymbol(tokens),
6970
8281
  name: String(first.name || first.symbol),
6971
8282
  logoUrl: first.logoUrl,
@@ -6986,15 +8297,15 @@ function groupDeployments(deployments, prices) {
6986
8297
  const order = [];
6987
8298
  const members = /* @__PURE__ */ new Map();
6988
8299
  for (const d of [...deployments].sort(byDeployment)) {
6989
- const key = String(d.token.symbol).toUpperCase();
6990
- const list = members.get(key);
8300
+ const key2 = String(d.token.symbol).toUpperCase();
8301
+ const list = members.get(key2);
6991
8302
  if (list) list.push(d);
6992
8303
  else {
6993
- members.set(key, [d]);
6994
- order.push(key);
8304
+ members.set(key2, [d]);
8305
+ order.push(key2);
6995
8306
  }
6996
8307
  }
6997
- 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);
6998
8309
  }
6999
8310
  var CHAIN_ALIASES = {
7000
8311
  56: ["bsc", "binance"],
@@ -7002,10 +8313,10 @@ var CHAIN_ALIASES = {
7002
8313
  43114: ["avax"]
7003
8314
  };
7004
8315
  function labelForms(label2) {
7005
- const lower2 = label2.trim().toLowerCase();
7006
- if (!lower2) return [];
7007
- const compact = lower2.replace(/[^a-z0-9]/g, "");
7008
- 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];
7009
8320
  }
7010
8321
  function buildChainSearchTerms(chains) {
7011
8322
  const byId = /* @__PURE__ */ new Map();
@@ -7268,14 +8579,14 @@ function TokenSelect(props) {
7268
8579
  const groups = react.useMemo(() => {
7269
8580
  const deployments = [];
7270
8581
  for (const token of props.tokens) {
7271
- const key = rowKey(token);
7272
- const n = Number(props.balances?.[key]?.formatted);
7273
- const st = props.optionStates?.[key];
8582
+ const key2 = rowKey(token);
8583
+ const n = Number(props.balances?.[key2]?.formatted);
8584
+ const st = props.optionStates?.[key2];
7274
8585
  if (st?.disabled && !WALLET_STATE_REASONS.has(String(st.reason))) continue;
7275
8586
  deployments.push({
7276
8587
  token,
7277
- key,
7278
- balance: showBalances && props.balances?.[key] && Number.isFinite(n) ? n : null,
8588
+ key: key2,
8589
+ balance: showBalances && props.balances?.[key2] && Number.isFinite(n) ? n : null,
7279
8590
  disabled: !!st?.disabled,
7280
8591
  // The line under a greyed row says why. Callers send either a sentence in `reason` (the
7281
8592
  // exchange's "cannot be delivered on this chain") or a machine code there with the words in
@@ -7647,7 +8958,7 @@ function WidgetShell(props) {
7647
8958
  }
7648
8959
  );
7649
8960
  }
7650
- function shortAddress2(a) {
8961
+ function shortAddress3(a) {
7651
8962
  if (!a) return "";
7652
8963
  return `${a.slice(0, 6)}\u2026${a.slice(-4)}`;
7653
8964
  }
@@ -7916,13 +9227,13 @@ function useTxHistory(account) {
7916
9227
  react.useEffect(() => {
7917
9228
  setEntries(readTxHistory(account));
7918
9229
  if (typeof window === "undefined" || !account) return;
7919
- const key = txHistoryKey(account);
9230
+ const key2 = txHistoryKey(account);
7920
9231
  const onLocal = (e) => {
7921
9232
  const detail = e.detail;
7922
9233
  if (!detail?.account || detail.account === account.toLowerCase()) setEntries(readTxHistory(account));
7923
9234
  };
7924
9235
  const onStorage = (e) => {
7925
- if (e.key === key) setEntries(readTxHistory(account));
9236
+ if (e.key === key2) setEntries(readTxHistory(account));
7926
9237
  };
7927
9238
  window.addEventListener(TX_HISTORY_EVENT, onLocal);
7928
9239
  window.addEventListener("storage", onStorage);
@@ -7938,10 +9249,10 @@ var hidden2 = () => typeof document !== "undefined" && document.visibilityState
7938
9249
  var travelling = (entries) => !!entries?.some((e) => e.delivery === "in-progress" || e.delivery === "attention");
7939
9250
  function useWalletHistory(engine, wallets) {
7940
9251
  const [entries, setEntries] = react.useState(null);
7941
- const key = wallets.filter((w) => !!w).join("|");
9252
+ const key2 = wallets.filter((w) => !!w).join("|");
7942
9253
  react.useEffect(() => {
7943
9254
  setEntries(null);
7944
- if (!engine || !key) return;
9255
+ if (!engine || !key2) return;
7945
9256
  let alive = true;
7946
9257
  let timer2;
7947
9258
  let started2 = Date.now();
@@ -7949,7 +9260,7 @@ function useWalletHistory(engine, wallets) {
7949
9260
  if (timer2) clearTimeout(timer2);
7950
9261
  timer2 = void 0;
7951
9262
  if (!hidden2()) {
7952
- const next = await engine.fetchWalletHistory(key.split("|"));
9263
+ const next = await engine.fetchWalletHistory(key2.split("|"));
7953
9264
  if (!alive) return;
7954
9265
  if (next) setEntries(next);
7955
9266
  if (!travelling(next)) return;
@@ -7968,7 +9279,7 @@ function useWalletHistory(engine, wallets) {
7968
9279
  if (timer2) clearTimeout(timer2);
7969
9280
  if (typeof window !== "undefined") window.removeEventListener(TX_HISTORY_EVENT, onRecorded);
7970
9281
  };
7971
- }, [engine, key]);
9282
+ }, [engine, key2]);
7972
9283
  return entries;
7973
9284
  }
7974
9285
  function BackGlyph() {
@@ -8105,15 +9416,15 @@ function TxPair(props) {
8105
9416
  ] });
8106
9417
  }
8107
9418
  function logoFor(art, symbol, chainId) {
8108
- const key = symbolKey(symbol);
8109
- if (!key) return void 0;
9419
+ const key2 = symbolKey(symbol);
9420
+ if (!key2) return void 0;
8110
9421
  const tokens = art.tokens;
8111
9422
  if (tokens?.length) {
8112
- const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) === key);
8113
- 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;
8114
9425
  if (found) return found;
8115
9426
  }
8116
- return art.vaultIcons?.get(key);
9427
+ return art.vaultIcons?.get(key2);
8117
9428
  }
8118
9429
  function TxHistoryList(props) {
8119
9430
  if (!props.entries.length) {
@@ -8190,7 +9501,7 @@ function TxDetail(props) {
8190
9501
  ] }),
8191
9502
  e.recipient ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
8192
9503
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Recipient" }),
8193
- /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress2(e.recipient) })
9504
+ /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress3(e.recipient) })
8194
9505
  ] }) : null,
8195
9506
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
8196
9507
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Settlement" }),
@@ -8227,7 +9538,7 @@ function TxHistoryPanel(props) {
8227
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, {}) }),
8228
9539
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-title", children: [
8229
9540
  selected ? "Transaction" : "Transaction history",
8230
- 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
8231
9542
  ] })
8232
9543
  ] }),
8233
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 })
@@ -8409,8 +9720,8 @@ function onSolanaAccountChange(info, cb) {
8409
9720
  }
8410
9721
  }) ?? (() => {
8411
9722
  });
8412
- const changed = (key) => {
8413
- const address = validAddress(key);
9723
+ const changed = (key2) => {
9724
+ const address = validAddress(key2);
8414
9725
  connected.set(provider, address ? [{ address }] : []);
8415
9726
  cb(address);
8416
9727
  };
@@ -8582,82 +9893,6 @@ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
8582
9893
  const recipientFor = (account) => required ? recipient2 || "" : hostRecipient || custom.evm || account;
8583
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 };
8584
9895
  }
8585
-
8586
- // src/core/checksum.ts
8587
- var RC = [
8588
- 0x0000000000000001n,
8589
- 0x0000000000008082n,
8590
- 0x800000000000808an,
8591
- 0x8000000080008000n,
8592
- 0x000000000000808bn,
8593
- 0x0000000080000001n,
8594
- 0x8000000080008081n,
8595
- 0x8000000000008009n,
8596
- 0x000000000000008an,
8597
- 0x0000000000000088n,
8598
- 0x0000000080008009n,
8599
- 0x000000008000000an,
8600
- 0x000000008000808bn,
8601
- 0x800000000000008bn,
8602
- 0x8000000000008089n,
8603
- 0x8000000000008003n,
8604
- 0x8000000000008002n,
8605
- 0x8000000000000080n,
8606
- 0x000000000000800an,
8607
- 0x800000008000000an,
8608
- 0x8000000080008081n,
8609
- 0x8000000000008080n,
8610
- 0x0000000080000001n,
8611
- 0x8000000080008008n
8612
- ];
8613
- 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];
8614
- var MASK = (1n << 64n) - 1n;
8615
- var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
8616
- function keccakF(s) {
8617
- for (let round = 0; round < 24; round++) {
8618
- const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
8619
- for (let x = 0; x < 5; x++) {
8620
- const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
8621
- for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
8622
- }
8623
- const b = new Array(25);
8624
- 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]);
8625
- 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];
8626
- s[0] = s[0] ^ RC[round];
8627
- }
8628
- }
8629
- function keccak256Hex(bytes) {
8630
- const rate = 136;
8631
- const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
8632
- padded.set(bytes);
8633
- padded[bytes.length] = padded[bytes.length] ^ 1;
8634
- padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
8635
- const s = new Array(25).fill(0n);
8636
- for (let off = 0; off < padded.length; off += rate) {
8637
- for (let i = 0; i < rate / 8; i++) {
8638
- let lane = 0n;
8639
- for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
8640
- s[i] = s[i] ^ lane;
8641
- }
8642
- keccakF(s);
8643
- }
8644
- let out = "";
8645
- 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");
8646
- return out;
8647
- }
8648
- function toChecksumAddress(address) {
8649
- const lower2 = address.slice(2).toLowerCase();
8650
- const hash2 = keccak256Hex(new TextEncoder().encode(lower2));
8651
- let out = "0x";
8652
- for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower2[i].toUpperCase() : lower2[i];
8653
- return out;
8654
- }
8655
- function hasValidChecksum(address) {
8656
- if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
8657
- const body = address.slice(2);
8658
- if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
8659
- return toChecksumAddress(address) === address;
8660
- }
8661
9896
  function ArrowLeft() {
8662
9897
  return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
8663
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" }),
@@ -9338,7 +10573,7 @@ function IdentityLine(props) {
9338
10573
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-link-id", children: [
9339
10574
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-icon", children: /* @__PURE__ */ jsxRuntime.jsx(WalletGlyph, {}) }),
9340
10575
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-link-id-text", children: [
9341
- /* @__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" }),
9342
10577
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-secondary", children: props.email ? props.email : props.account ? "Connected wallet" : "Connect your wallet to continue" })
9343
10578
  ] }),
9344
10579
  props.account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }) : null
@@ -9485,9 +10720,9 @@ function PaymentIsland(props) {
9485
10720
  const optionStates = react.useMemo(() => {
9486
10721
  const map = {};
9487
10722
  for (const a of annotated) {
9488
- const key = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
10723
+ const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
9489
10724
  if (!a.balance || holdings.loading) {
9490
- map[key] = { disabled: false, reason: "checking" };
10725
+ map[key2] = { disabled: false, reason: "checking" };
9491
10726
  continue;
9492
10727
  }
9493
10728
  let zero = false;
@@ -9496,9 +10731,9 @@ function PaymentIsland(props) {
9496
10731
  } catch {
9497
10732
  zero = false;
9498
10733
  }
9499
- if (zero) map[key] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
9500
- 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}` };
9501
- 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 };
9502
10737
  }
9503
10738
  return map;
9504
10739
  }, [annotated, holdings.loading]);
@@ -9538,19 +10773,19 @@ function PaymentIsland(props) {
9538
10773
  if (!catalogue?.ready) return void 0;
9539
10774
  const states2 = {};
9540
10775
  for (const token of catalogue.tokens) {
9541
- const key = balanceKey(Number(token.chainId), token.address);
10776
+ const key2 = balanceKey(Number(token.chainId), token.address);
9542
10777
  const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
9543
10778
  if (measured) {
9544
- states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
10779
+ states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
9545
10780
  continue;
9546
10781
  }
9547
10782
  const verdict = destinationAvailability(token, catalogue, exFromToken);
9548
10783
  if (verdict === "available") {
9549
10784
  const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
9550
- 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)) };
9551
10786
  continue;
9552
10787
  }
9553
- states2[key] = {
10788
+ states2[key2] = {
9554
10789
  disabled: true,
9555
10790
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
9556
10791
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
@@ -9563,9 +10798,9 @@ function PaymentIsland(props) {
9563
10798
  const seen = /* @__PURE__ */ new Set();
9564
10799
  const list = [];
9565
10800
  for (const r of visibleRoutes) {
9566
- const key = balanceKey(r.source.chainId, r.source.tokenAddress);
9567
- if (seen.has(key)) continue;
9568
- seen.add(key);
10801
+ const key2 = balanceKey(r.source.chainId, r.source.tokenAddress);
10802
+ if (seen.has(key2)) continue;
10803
+ seen.add(key2);
9569
10804
  const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
9570
10805
  list.push(
9571
10806
  reg ?? {
@@ -9905,7 +11140,7 @@ function PaymentIsland(props) {
9905
11140
  ] }),
9906
11141
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
9907
11142
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
9908
- (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)}` : ""
9909
11144
  ] }),
9910
11145
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
9911
11146
  ] }),
@@ -10218,9 +11453,9 @@ function PayCard(props) {
10218
11453
  const optionStates = react.useMemo(() => {
10219
11454
  const map = {};
10220
11455
  for (const a of annotated) {
10221
- const key = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
11456
+ const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
10222
11457
  if (!a.balance || holdings.loading) {
10223
- map[key] = { disabled: false, reason: "checking" };
11458
+ map[key2] = { disabled: false, reason: "checking" };
10224
11459
  continue;
10225
11460
  }
10226
11461
  let zero = false;
@@ -10230,23 +11465,23 @@ function PayCard(props) {
10230
11465
  zero = false;
10231
11466
  }
10232
11467
  if (zero) {
10233
- 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" };
10234
11469
  } else if (a.affordable === false) {
10235
- 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}` };
10236
11471
  } else {
10237
- map[key] = { disabled: false };
11472
+ map[key2] = { disabled: false };
10238
11473
  }
10239
11474
  }
10240
11475
  for (const o of unquoted) {
10241
- const key = balanceKey(o.chainId, o.address);
10242
- if (map[key]) continue;
11476
+ const key2 = balanceKey(o.chainId, o.address);
11477
+ if (map[key2]) continue;
10243
11478
  let zero = false;
10244
11479
  try {
10245
- zero = BigInt(listBalances[key]?.raw ?? "x") === 0n;
11480
+ zero = BigInt(listBalances[key2]?.raw ?? "x") === 0n;
10246
11481
  } catch {
10247
11482
  zero = false;
10248
11483
  }
10249
- 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 };
10250
11485
  }
10251
11486
  return map;
10252
11487
  }, [annotated, holdings.loading, unquoted, listBalances]);
@@ -10260,9 +11495,9 @@ function PayCard(props) {
10260
11495
  const seen = /* @__PURE__ */ new Set();
10261
11496
  const list = [];
10262
11497
  const push = (chainId, address, fallback) => {
10263
- const key = balanceKey(chainId, address);
10264
- if (seen.has(key)) return;
10265
- seen.add(key);
11498
+ const key2 = balanceKey(chainId, address);
11499
+ if (seen.has(key2)) return;
11500
+ seen.add(key2);
10266
11501
  list.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
10267
11502
  };
10268
11503
  for (const r of visibleRoutes) {
@@ -10336,13 +11571,13 @@ function PayCard(props) {
10336
11571
  const option = unquoted.find((o) => o.chainId === pick.chainId && o.symbolKey === symbolKey(pick.symbol));
10337
11572
  closeSelector();
10338
11573
  if (!option || !wallet.account) return;
10339
- const key = balanceKey(option.chainId, option.address);
10340
- setPricing(key);
11574
+ const key2 = balanceKey(option.chainId, option.address);
11575
+ setPricing(key2);
10341
11576
  userPicked.current = true;
10342
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(() => {
10343
- setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key]));
11578
+ setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key2]));
10344
11579
  setPickError(`${option.ticker || option.symbol} on ${option.chainName} cannot settle this payment right now. Pick another way to pay.`);
10345
- }).finally(() => setPricing((cur) => cur === key ? null : cur));
11580
+ }).finally(() => setPricing((cur) => cur === key2 ? null : cur));
10346
11581
  };
10347
11582
  const parked = !isLiveMethod(method);
10348
11583
  const submitting = flow.status === "submitting";
@@ -10375,7 +11610,7 @@ function PayCard(props) {
10375
11610
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-wallet", "data-connected": "true", children: [
10376
11611
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
10377
11612
  " ",
10378
- shortAddress2(wallet.account)
11613
+ shortAddress3(wallet.account)
10379
11614
  ] })
10380
11615
  ] }) : /* @__PURE__ */ jsxRuntime.jsx("span", {});
10381
11616
  const nativeWei = sel ? routeNativeValue(sel) : 0n;
@@ -10415,7 +11650,7 @@ function PayCard(props) {
10415
11650
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
10416
11651
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
10417
11652
  " \xB7 ",
10418
- shortAddress2(props.recipient)
11653
+ shortAddress3(props.recipient)
10419
11654
  ] }),
10420
11655
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
10421
11656
  ] }),
@@ -10583,7 +11818,7 @@ function StableGenieSwap(props) {
10583
11818
  ] }),
10584
11819
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
10585
11820
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
10586
- 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)}` : ""
10587
11822
  ] }),
10588
11823
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
10589
11824
  ] }),
@@ -10647,7 +11882,7 @@ function useSolanaSourceFlow(args) {
10647
11882
  const planArgs = react.useRef(null);
10648
11883
  const changedWhileBusy = react.useRef(false);
10649
11884
  const addressed = Boolean(owner && payer && recipient2);
10650
- const key = keyOf(args);
11885
+ const key2 = keyOf(args);
10651
11886
  react.useEffect(() => {
10652
11887
  const id = ++req.current;
10653
11888
  if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
@@ -10681,7 +11916,7 @@ function useSolanaSourceFlow(args) {
10681
11916
  const quoted = await engine.quoteSolanaSource(input);
10682
11917
  const built = await engine.buildSolanaSourcePlan(input, quoted);
10683
11918
  if (id !== req.current) return;
10684
- planKey.current = key;
11919
+ planKey.current = key2;
10685
11920
  planArgs.current = { ...latest.current };
10686
11921
  setPreview(quoted);
10687
11922
  setPlan(built);
@@ -10697,7 +11932,7 @@ function useSolanaSourceFlow(args) {
10697
11932
  }
10698
11933
  }, 350);
10699
11934
  return () => clearTimeout(timer2);
10700
- }, [engine, enabled, key, addressed, nonce]);
11935
+ }, [engine, enabled, key2, addressed, nonce]);
10701
11936
  react.useEffect(() => {
10702
11937
  let alive = true;
10703
11938
  setBalanceRaw(void 0);
@@ -11021,11 +12256,11 @@ function ExchangeCard(props) {
11021
12256
  const [fiatCurrency, setFiatCurrency] = react.useState(props.fiatCurrency ?? "EUR");
11022
12257
  const sellableFrom = react.useCallback((t) => t && product === "rwa" && !isSellableRwa(t) ? null : t, [product]);
11023
12258
  const fromToken = react.useMemo(() => from ? sellableFrom(findToken(tokens, from.chainId, from.symbol)) : null, [tokens, from, sellableFrom]);
11024
- const toToken = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
11025
- 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 ?? "";
11026
12261
  const fromTicker = fromToken ? tokenTicker(fromToken) : from?.symbol ?? "";
11027
- const toTicker = toToken ? tokenTicker(toToken) : toSymbol;
11028
- 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]);
11029
12264
  const toPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(tokens, fromToken) : tokens, [product, tokens, fromToken]);
11030
12265
  const rwaSeeded = react.useRef(false);
11031
12266
  react.useEffect(() => {
@@ -11042,19 +12277,19 @@ function ExchangeCard(props) {
11042
12277
  if (!catalogue?.ready) return void 0;
11043
12278
  const states2 = {};
11044
12279
  for (const token of catalogue.tokens) {
11045
- const key = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
12280
+ const key2 = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
11046
12281
  const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
11047
12282
  if (measured) {
11048
- states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
12283
+ states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
11049
12284
  continue;
11050
12285
  }
11051
12286
  const verdict = destinationAvailability(token, catalogue, fromToken);
11052
12287
  if (verdict === "available") {
11053
12288
  const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
11054
- 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)) };
11055
12290
  continue;
11056
12291
  }
11057
- states2[key] = {
12292
+ states2[key2] = {
11058
12293
  disabled: true,
11059
12294
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
11060
12295
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
@@ -11070,8 +12305,8 @@ function ExchangeCard(props) {
11070
12305
  const amountValid = /^\d+(\.\d+)?$/.test(normalizedAmount) && Number(normalizedAmount) > 0 && Number(normalizedAmount) <= 1e9;
11071
12306
  const rampMode = mode !== "exchange";
11072
12307
  const laneLimit = react.useMemo(
11073
- () => mode === "exchange" && fromToken && toToken ? laneLimitFor(toToken, fromToken, catalogue?.limitedLanes) : void 0,
11074
- [mode, catalogue, fromToken, toToken]
12308
+ () => mode === "exchange" && fromToken && toToken2 ? laneLimitFor(toToken2, fromToken, catalogue?.limitedLanes) : void 0,
12309
+ [mode, catalogue, fromToken, toToken2]
11075
12310
  );
11076
12311
  const limitSymbol = laneLimit ? laneLimitSymbol(laneLimit, fromTicker) : "";
11077
12312
  const overLimit = react.useMemo(() => {
@@ -11225,11 +12460,11 @@ function ExchangeCard(props) {
11225
12460
  useFitText(receiveSideRef, receiveShown);
11226
12461
  const toDecimals = react.useMemo(() => {
11227
12462
  try {
11228
- return toToken ? assetDecimals(toToken) : void 0;
12463
+ return toToken2 ? assetDecimals(toToken2) : void 0;
11229
12464
  } catch {
11230
12465
  return void 0;
11231
12466
  }
11232
- }, [toToken]);
12467
+ }, [toToken2]);
11233
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;
11234
12469
  const pct = (p) => {
11235
12470
  if (!fromBal || !fromToken) return;
@@ -11441,7 +12676,7 @@ function ExchangeCard(props) {
11441
12676
  ] }),
11442
12677
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
11443
12678
  solDelivery.phase === "tracking" ? "Submitted on Solana \u2014 tracking delivery" : deliveryHeadline(solDelivery, true),
11444
- solFlow.sent?.recipient ? ` \xB7 ${shortAddress2(solFlow.sent.recipient)}` : ""
12679
+ solFlow.sent?.recipient ? ` \xB7 ${shortAddress3(solFlow.sent.recipient)}` : ""
11445
12680
  ] }),
11446
12681
  /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: solDelivery })
11447
12682
  ] }),
@@ -11462,7 +12697,7 @@ function ExchangeCard(props) {
11462
12697
  ] }),
11463
12698
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
11464
12699
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
11465
- 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)}` : ""
11466
12701
  ] }),
11467
12702
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
11468
12703
  ] }),
@@ -11473,7 +12708,7 @@ function ExchangeCard(props) {
11473
12708
  ] });
11474
12709
  } else {
11475
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") });
11476
- 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") });
11477
12712
  const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
11478
12713
  solanaSteps,
11479
12714
  solanaCta,
@@ -11496,7 +12731,7 @@ function ExchangeCard(props) {
11496
12731
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ft", children: [
11497
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") }),
11498
12733
  /* @__PURE__ */ jsxRuntime.jsx(FlipButton, { small: true, onClick: flip, disabled: !flippable }),
11499
- 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") })
11500
12735
  ] }),
11501
12736
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane", "data-kind": "send", children: [
11502
12737
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane-top", children: [
@@ -11590,7 +12825,7 @@ function ExchangeCard(props) {
11590
12825
  side = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-side-body", children: [
11591
12826
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv", children: [
11592
12827
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-line", children: [
11593
- /* @__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" }),
11594
12829
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-recv-amt", ref: receiveSideRef, children: /* @__PURE__ */ jsxRuntime.jsx(AmountText, { value: formatCalculatedAmount(receive, toDecimals), exact: receive, suffix: toTicker }) })
11595
12830
  ] }),
11596
12831
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-sub", children: [