@glacislabs/stablegenie-zerodelta 4.18.2 → 4.20.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/index.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":
@@ -918,7 +981,7 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
918
981
  8453: "Base",
919
982
  9745: "Plasma",
920
983
  34443: "Mode",
921
- 42161: "Arbitrum One",
984
+ 42161: "Arbitrum",
922
985
  // "Avalanche", as the dApp prints it since zd-dapp#582 (from ZD Heavy's /chains). The widget's
923
986
  // registry read lists no row for a payout-only chain, so this table is what names it here.
924
987
  43114: "Avalanche",
@@ -994,8 +1057,8 @@ var SOLANA_DESTINATION_ASSETS = Object.freeze({
994
1057
  AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
995
1058
  });
996
1059
  function solanaDestinationAsset(mint) {
997
- const key = typeof mint === "string" ? mint.trim() : "";
998
- return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
1060
+ const key2 = typeof mint === "string" ? mint.trim() : "";
1061
+ return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key2) ? SOLANA_DESTINATION_ASSETS[key2] : null;
999
1062
  }
1000
1063
  function solanaBridgeOf(token) {
1001
1064
  const pinned = solanaDestinationAsset(token.address);
@@ -1369,9 +1432,9 @@ function hexBytes(hex) {
1369
1432
  if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
1370
1433
  return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
1371
1434
  }
1372
- function solanaKeyBytes(key) {
1373
- if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
1374
- return base58Decode(key);
1435
+ function solanaKeyBytes(key2) {
1436
+ if (!isSolanaAddress(key2) || key2 !== key2.trim()) throw new Error("Invalid Solana public key.");
1437
+ return base58Decode(key2);
1375
1438
  }
1376
1439
  var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1377
1440
  function base64Decode(text) {
@@ -1717,16 +1780,16 @@ function tokenTicker(token) {
1717
1780
  }
1718
1781
  function tickerOn(tokens, chainId, symbol) {
1719
1782
  if (!symbol || !chainId || !tokens?.length) return symbol;
1720
- const key = symbolKey(symbol);
1721
- const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key);
1783
+ const key2 = symbolKey(symbol);
1784
+ const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key2);
1722
1785
  return deployment ? tokenTicker(deployment) : symbol;
1723
1786
  }
1724
1787
 
1725
1788
  // src/core/availability.ts
1726
1789
  function assetClassOf(symbol) {
1727
- const key = symbolKey(symbol);
1728
- if (TRADEABLE_RWA_ASSETS.has(key)) return "rwa";
1729
- if (STABLE_ASSETS.has(key)) return "stable";
1790
+ const key2 = symbolKey(symbol);
1791
+ if (TRADEABLE_RWA_ASSETS.has(key2)) return "rwa";
1792
+ if (STABLE_ASSETS.has(key2)) return "stable";
1730
1793
  return null;
1731
1794
  }
1732
1795
  var NEST_VAULT_SHARES = /* @__PURE__ */ new Set(["NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON"]);
@@ -1835,8 +1898,8 @@ function buildCatalogue(input) {
1835
1898
  if (product === "rwa") return true;
1836
1899
  if (execution.has(chainId) || token.isChainedDestination === true) return true;
1837
1900
  if (!isExecutableBridge(token)) return false;
1838
- const key = tokenKey(token.chainId, token.address);
1839
- return source2.has(key) || destination.has(key);
1901
+ const key2 = tokenKey(token.chainId, token.address);
1902
+ return source2.has(key2) || destination.has(key2);
1840
1903
  });
1841
1904
  const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
1842
1905
  const catalogue = ready ? projectedCatalogue : allowed;
@@ -1880,8 +1943,8 @@ function tokenEnabled(token) {
1880
1943
  return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
1881
1944
  }
1882
1945
  function findToken(tokens, chainId, symbol) {
1883
- const key = symbolKey(symbol);
1884
- return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key) || null;
1946
+ const key2 = symbolKey(symbol);
1947
+ return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key2) || null;
1885
1948
  }
1886
1949
  function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
1887
1950
  const invoiceKey = symbolKey(invoiceAsset);
@@ -1915,10 +1978,10 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
1915
1978
  const chainId = Number(token.chainId);
1916
1979
  const chain2 = chainById(chains, chainId);
1917
1980
  if (!chainSelectable(chain2, chainId)) continue;
1918
- const key = tokenKey(chainId, token.address);
1919
- if (seen.has(key)) continue;
1981
+ const key2 = tokenKey(chainId, token.address);
1982
+ if (seen.has(key2)) continue;
1920
1983
  if (refusal(token)) continue;
1921
- seen.add(key);
1984
+ seen.add(key2);
1922
1985
  const payKey = symbolKey(token.symbol);
1923
1986
  const direct2 = chainId === invoiceChain && payKey === invoiceKey;
1924
1987
  options.push({
@@ -2104,7 +2167,7 @@ function normalizePreview(request, quote, to, amount) {
2104
2167
  async function quoteSolanaSource(api, input) {
2105
2168
  const { from, to, amount } = selections(input, await api.fetchTokens());
2106
2169
  const request = makeRequest(input, from, to, amount);
2107
- const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
2170
+ const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
2108
2171
  const preview = normalizePreview(request, quote, to, input.amountIn);
2109
2172
  quoteRequests.set(preview, { api, request: clone(request) });
2110
2173
  return preview;
@@ -2118,7 +2181,7 @@ async function previewSolanaSource(api, input) {
2118
2181
  raw(amount, "input amount", true);
2119
2182
  const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
2120
2183
  const request = body;
2121
- const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
2184
+ const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
2122
2185
  const option = quote?.options?.[0];
2123
2186
  if (!option) throw new Error("Native quote returned no options.");
2124
2187
  const receive = raw(option.finalAmount, "quoted output", true);
@@ -2475,8 +2538,8 @@ function historyKey(value) {
2475
2538
  var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
2476
2539
  function tokenAt(tokens, chainId, address) {
2477
2540
  if (!address) return void 0;
2478
- const key = historyKey(address);
2479
- return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key);
2541
+ const key2 = historyKey(address);
2542
+ return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key2);
2480
2543
  }
2481
2544
  function amountOf(raw2, token, rowDecimals, rowAmount) {
2482
2545
  const decimals = token ? Number(token.decimals) : Number(rowDecimals);
@@ -2562,13 +2625,13 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
2562
2625
  const out = [];
2563
2626
  const seen = /* @__PURE__ */ new Set();
2564
2627
  for (const entry of local) {
2565
- const key = historyKey(entry.hash);
2566
- if (seen.has(key)) continue;
2567
- seen.add(key);
2568
- const known = byHash.get(key);
2628
+ const key2 = historyKey(entry.hash);
2629
+ if (seen.has(key2)) continue;
2630
+ seen.add(key2);
2631
+ const known = byHash.get(key2);
2569
2632
  out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
2570
2633
  }
2571
- for (const [key, entry] of byHash) if (!seen.has(key)) out.push(entry);
2634
+ for (const [key2, entry] of byHash) if (!seen.has(key2)) out.push(entry);
2572
2635
  return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
2573
2636
  }
2574
2637
 
@@ -2679,12 +2742,12 @@ function suppressedLanes(health) {
2679
2742
  const out = /* @__PURE__ */ new Map();
2680
2743
  for (const lane of health.lanes) {
2681
2744
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
2682
- const key = healthLaneKey(lane.laneKey);
2683
- if (!key) continue;
2745
+ const key2 = healthLaneKey(lane.laneKey);
2746
+ if (!key2) continue;
2684
2747
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
2685
2748
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
2686
2749
  const message = typeof availability?.message === "string" && availability.message ? availability.message : lane.message;
2687
- out.set(key, {
2750
+ out.set(key2, {
2688
2751
  route: typeof lane.route === "string" ? lane.route : "",
2689
2752
  code: typeof code === "string" ? code : "",
2690
2753
  message: typeof message === "string" ? message : "",
@@ -2699,15 +2762,15 @@ function limitedLanes(health) {
2699
2762
  const out = /* @__PURE__ */ new Map();
2700
2763
  for (const lane of health.lanes) {
2701
2764
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
2702
- const key = healthLaneKey(lane.laneKey);
2765
+ const key2 = healthLaneKey(lane.laneKey);
2703
2766
  const limit = lane.availability?.limit;
2704
- if (!key || !limit || typeof limit !== "object") continue;
2767
+ if (!key2 || !limit || typeof limit !== "object") continue;
2705
2768
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
2706
2769
  const maxAmount = typeof limit.maxAmount === "string" ? limit.maxAmount.trim() : "";
2707
2770
  const decimals = limit.decimals;
2708
2771
  if (!side || !BASE_UNITS.test(maxAmount) || typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
2709
2772
  const code = lane.availability?.code;
2710
- out.set(key, {
2773
+ out.set(key2, {
2711
2774
  side,
2712
2775
  token: typeof limit.token === "string" ? limit.token : "",
2713
2776
  fromChainId: Number(limit.fromChainId) || 0,
@@ -2770,10 +2833,10 @@ function resolveVaultIcon(apiBase, iconPath) {
2770
2833
  function vaultIconsBySymbol(apiBase, vaults) {
2771
2834
  const out = /* @__PURE__ */ new Map();
2772
2835
  for (const vault of vaults) {
2773
- const key = symbolKey(vault?.symbol);
2774
- if (!key || out.has(key)) continue;
2836
+ const key2 = symbolKey(vault?.symbol);
2837
+ if (!key2 || out.has(key2)) continue;
2775
2838
  const url = resolveVaultIcon(apiBase, vault?.iconMiniUrl) ?? resolveVaultIcon(apiBase, vault?.iconUrl);
2776
- if (url) out.set(key, url);
2839
+ if (url) out.set(key2, url);
2777
2840
  }
2778
2841
  return out;
2779
2842
  }
@@ -2870,7 +2933,7 @@ var CATEGORY_PHRASES = {
2870
2933
  UNKNOWN: "an unrecognized risk"
2871
2934
  };
2872
2935
  function categoryLabel(code) {
2873
- const key = code.trim().toUpperCase();
2936
+ const key2 = code.trim().toUpperCase();
2874
2937
  const LABELS = {
2875
2938
  SANCTIONS: "Sanctions",
2876
2939
  TERRORISM_FINANCING: "Terrorist financing",
@@ -2885,7 +2948,7 @@ function categoryLabel(code) {
2885
2948
  UNCLASSIFIED: "Unclassified risk",
2886
2949
  UNKNOWN: "Unclassified risk"
2887
2950
  };
2888
- return LABELS[key] ?? key.toLowerCase().replace(/_/g, " ");
2951
+ return LABELS[key2] ?? key2.toLowerCase().replace(/_/g, " ");
2889
2952
  }
2890
2953
  function cleanJurisdiction(code) {
2891
2954
  return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
@@ -2998,9 +3061,9 @@ function distinctScreenedWallets(compliance) {
2998
3061
  for (const raw2 of compliance?.screenedWallets ?? []) {
2999
3062
  const address = raw2?.trim();
3000
3063
  if (!address) continue;
3001
- const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
3002
- if (seen.has(key)) continue;
3003
- seen.add(key);
3064
+ const key2 = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
3065
+ if (seen.has(key2)) continue;
3066
+ seen.add(key2);
3004
3067
  wallets.push(address);
3005
3068
  }
3006
3069
  return wallets;
@@ -3127,9 +3190,9 @@ var TUNED_OUTCOMES = {
3127
3190
  UNCLASSIFIED: "flagged"
3128
3191
  };
3129
3192
  function screeningOutcomeOf(category) {
3130
- const key = category.trim().toUpperCase();
3131
- if (FLOOR_CATEGORIES.includes(key)) return "always-blocked";
3132
- return TUNED_OUTCOMES[key] ?? null;
3193
+ const key2 = category.trim().toUpperCase();
3194
+ if (FLOOR_CATEGORIES.includes(key2)) return "always-blocked";
3195
+ return TUNED_OUTCOMES[key2] ?? null;
3133
3196
  }
3134
3197
  var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
3135
3198
  var SCREENING_BUCKETS = [
@@ -3138,6 +3201,91 @@ var SCREENING_BUCKETS = [
3138
3201
  { outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
3139
3202
  ];
3140
3203
 
3204
+ // src/core/zdheavy-routers.ts
3205
+ var ZDHEAVY_ROUTER_TEST05 = "0x94c5cC7f4689AD7B0Abd0975F4C8E159e4633251";
3206
+ var ZDHEAVY_ROUTER_TEST04 = "0x72EA420DCE5BE939062E527b49388479d7171379";
3207
+ var ZDHEAVY_ROUTER_DEV = "0xD813690937324417cFBE12E742dD53054F90dF04";
3208
+ var ZDHEAVY_ROUTER_DEV_V6 = "0xa6155b1505378e6C9871483c55375dcBBB16f897";
3209
+ var ZDHEAVY_ROUTER_PROD = "0x7D50305f2855Bf2225FE51E15858b4BA0C0844e1";
3210
+ var ZDHEAVY_DEV_CHAINS = [1, 10, 56, 130, 137, 143, 146, 1329, 1672, 4663, 5e3, 8453, 9745, 42161, 43114, 57073, 98866];
3211
+ var ZDHEAVY_SANDBOX_CHAINS = [8453, 9745, 42161];
3212
+ var ZDHEAVY_ROUTER_ADDRESSES = Object.fromEntries(
3213
+ ZDHEAVY_DEV_CHAINS.map((id) => [
3214
+ id,
3215
+ 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]
3216
+ ])
3217
+ );
3218
+ function zdHeavyRouterPinned(chainId, router) {
3219
+ if (typeof router !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(router)) return false;
3220
+ const want = router.toLowerCase();
3221
+ return (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).some((a) => a.toLowerCase() === want);
3222
+ }
3223
+
3224
+ // src/core/quote-option.ts
3225
+ function zdHeavyExecutable(q) {
3226
+ const order = q.execution?.order;
3227
+ const chainId = typeof q.fromChainId === "number" ? q.fromChainId : Number(order?.chainNumber);
3228
+ 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);
3229
+ }
3230
+ function liteExecutable(q) {
3231
+ return q.protocol !== "zdheavy" && Array.isArray(q.orderRequests) && q.orderRequests.length > 0;
3232
+ }
3233
+ function selectQuoteOption(quote) {
3234
+ if (!Array.isArray(quote.options)) return quote;
3235
+ const option = quote.options.find(zdHeavyExecutable) ?? quote.options.find((q) => q.protocol !== "zdheavy" && !!q.orderRequests?.length);
3236
+ if (!option) throw new Error("ZeroDelta quote has no executable option.");
3237
+ const gatewayOptions = [];
3238
+ let gatewayOptionIndex = -1;
3239
+ for (const o of quote.options) {
3240
+ if (!o || typeof o !== "object" || Array.isArray(o)) continue;
3241
+ if (o === option) gatewayOptionIndex = gatewayOptions.length;
3242
+ gatewayOptions.push(projectOption(quote, o));
3243
+ }
3244
+ return { ...projectOption(quote, option), gatewayOptions, gatewayOptionIndex };
3245
+ }
3246
+ function projectOption(quote, option) {
3247
+ const { fromChainId, toChainId, fromToken, toToken: toToken2, fromAmount } = quote;
3248
+ const last = option.orderRequests?.[option.orderRequests.length - 1];
3249
+ const { entersNetting, gasSponsored, gatewayOptions: _g, gatewayOptionIndex: _i, ...rest } = option;
3250
+ return {
3251
+ ...rest,
3252
+ ...entersNetting === true ? { entersNetting: true } : {},
3253
+ ...gasSponsored === true ? { gasSponsored: true } : {},
3254
+ fromChainId,
3255
+ toChainId,
3256
+ fromToken,
3257
+ toToken: toToken2,
3258
+ fromAmount,
3259
+ quoteId: quote.quoteId,
3260
+ toAmount: String(last?.askTokenAmount ?? option.outputAmount ?? option.toAmount ?? ""),
3261
+ finalAmount: String(option.finalAmount || last?.askTokenAmount || option.outputAmount || ""),
3262
+ compliance: complianceDecision(quote),
3263
+ estimatedDuration: option.estimatedTimeSec ?? option.estimatedDuration
3264
+ };
3265
+ }
3266
+ function complianceDecision(quote) {
3267
+ const decision = quote.complianceDecision ?? quote.compliance;
3268
+ return decision && typeof decision === "object" && !Array.isArray(decision) ? decision : void 0;
3269
+ }
3270
+ function normalizeQuoteResponse(response, request) {
3271
+ const quote = Array.isArray(response?.options) ? selectQuoteOption({
3272
+ ...response,
3273
+ fromChainId: request.inputChain,
3274
+ toChainId: request.outputChain,
3275
+ fromToken: request.inputToken,
3276
+ toToken: request.outputToken,
3277
+ fromAmount: request.inputAmount
3278
+ }) : response;
3279
+ if (quote?.gatewayOptions) quote.gatewayOptions = quote.gatewayOptions.map(numericExecutionChain);
3280
+ return numericExecutionChain(quote);
3281
+ }
3282
+ function numericExecutionChain(quote) {
3283
+ return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
3284
+ }
3285
+ function deliveredAmount(quote, solanaDestination) {
3286
+ return BigInt(quote.protocol === "zdheavy" || solanaDestination ? quote.finalAmount || quote.toAmount || "0" : quote.toAmount || "0");
3287
+ }
3288
+
3141
3289
  // src/core/solve.ts
3142
3290
  async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
3143
3291
  const destDecimals = assetDecimals(destinationToken);
@@ -3184,7 +3332,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3184
3332
  let bestGuess = guess;
3185
3333
  for (let i = 0; i < 3; i += 1) {
3186
3334
  const guessSent = guess;
3187
- const quote = await fetchQuote({
3335
+ const quote = selectQuoteOption(await fetchQuote({
3188
3336
  fromChainId: option.chainId,
3189
3337
  toChainId: Number(destination.chainId),
3190
3338
  fromToken: option.symbol,
@@ -3192,11 +3340,11 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3192
3340
  fromAmount: guessSent.toString(),
3193
3341
  owner: payer,
3194
3342
  destinationReceiver: destination.address
3195
- });
3343
+ }));
3196
3344
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
3197
3345
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3198
3346
  }
3199
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3347
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3200
3348
  const final = finalOf(quote);
3201
3349
  if (final > bestFinal) {
3202
3350
  bestFinal = final;
@@ -3233,7 +3381,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3233
3381
  directTransfer: false,
3234
3382
  quote: best,
3235
3383
  youPayRaw: bestGuess.toString(),
3236
- recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
3384
+ recipientReceivesRaw: deliveredAmount(best, isSolanaChainId(destination.chainId)).toString(),
3237
3385
  targetRaw: targetRaw.toString(),
3238
3386
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
3239
3387
  meetsTarget: bestFinal >= targetRaw,
@@ -3243,7 +3391,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3243
3391
  async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
3244
3392
  const fromRaw = BigInt(amountInRaw || "0");
3245
3393
  if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
3246
- const quote = await fetchQuote({
3394
+ const quote = selectQuoteOption(await fetchQuote({
3247
3395
  fromChainId: option.chainId,
3248
3396
  toChainId: Number(destination.chainId),
3249
3397
  fromToken: option.symbol,
@@ -3251,11 +3399,11 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3251
3399
  fromAmount: fromRaw.toString(),
3252
3400
  owner: payer,
3253
3401
  destinationReceiver: destination.address
3254
- });
3402
+ }));
3255
3403
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
3256
3404
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3257
3405
  }
3258
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3406
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3259
3407
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3260
3408
  return {
3261
3409
  directTransfer: false,
@@ -3268,6 +3416,24 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3268
3416
  iterations: 1
3269
3417
  };
3270
3418
  }
3419
+ function resultForOption(result, option, mode, destinationChainId) {
3420
+ if (result.directTransfer) throw new Error("A direct transfer has no other option.");
3421
+ if (BigInt(option.fromAmount || "0") !== BigInt(result.youPayRaw)) throw new Error("ZeroDelta echoed a different input amount than requested.");
3422
+ const guaranteed = deliveredAmount(option, isSolanaChainId(destinationChainId));
3423
+ if (mode === "exact-in") {
3424
+ if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3425
+ return { ...result, quote: option, recipientReceivesRaw: guaranteed.toString(), targetRaw: guaranteed.toString(), overageBps: 0, meetsTarget: true };
3426
+ }
3427
+ const targetRaw = BigInt(result.targetRaw);
3428
+ const final = finalOf(option);
3429
+ return {
3430
+ ...result,
3431
+ quote: option,
3432
+ recipientReceivesRaw: guaranteed.toString(),
3433
+ overageBps: targetRaw > 0n ? Number((final - targetRaw) * 10000n / targetRaw) : 0,
3434
+ meetsTarget: final >= targetRaw
3435
+ };
3436
+ }
3271
3437
 
3272
3438
  // src/core/order.ts
3273
3439
  var DEFAULT_DEADLINE_SECONDS = 1800;
@@ -3387,134 +3553,1173 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
3387
3553
  }
3388
3554
  }
3389
3555
 
3390
- // src/core/route.ts
3391
- function routeDeltaLabel(result, quote) {
3392
- if (result.directTransfer) return "~0";
3393
- if (!result.meetsTarget) return "Below requested amount";
3394
- if (result.overageBps > 0) return `+${(result.overageBps / 100).toFixed(2)}% buffer`;
3395
- if (quote.feeBps) return `${quote.feeBps} bps fee`;
3396
- return "~0";
3556
+ // src/core/checksum.ts
3557
+ var RC = [
3558
+ 0x0000000000000001n,
3559
+ 0x0000000000008082n,
3560
+ 0x800000000000808an,
3561
+ 0x8000000080008000n,
3562
+ 0x000000000000808bn,
3563
+ 0x0000000080000001n,
3564
+ 0x8000000080008081n,
3565
+ 0x8000000000008009n,
3566
+ 0x000000000000008an,
3567
+ 0x0000000000000088n,
3568
+ 0x0000000080008009n,
3569
+ 0x000000008000000an,
3570
+ 0x000000008000808bn,
3571
+ 0x800000000000008bn,
3572
+ 0x8000000000008089n,
3573
+ 0x8000000000008003n,
3574
+ 0x8000000000008002n,
3575
+ 0x8000000000000080n,
3576
+ 0x000000000000800an,
3577
+ 0x800000008000000an,
3578
+ 0x8000000080008081n,
3579
+ 0x8000000000008080n,
3580
+ 0x0000000080000001n,
3581
+ 0x8000000080008008n
3582
+ ];
3583
+ 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];
3584
+ var MASK = (1n << 64n) - 1n;
3585
+ var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
3586
+ function keccakF(s) {
3587
+ for (let round = 0; round < 24; round++) {
3588
+ const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
3589
+ for (let x = 0; x < 5; x++) {
3590
+ const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
3591
+ for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
3592
+ }
3593
+ const b = new Array(25);
3594
+ 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]);
3595
+ 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];
3596
+ s[0] = s[0] ^ RC[round];
3597
+ }
3397
3598
  }
3398
- function quotePartnerId(quote) {
3399
- const raw2 = quote.partnerId;
3400
- return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
3599
+ function keccak256Hex(bytes) {
3600
+ const rate = 136;
3601
+ const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
3602
+ padded.set(bytes);
3603
+ padded[bytes.length] = padded[bytes.length] ^ 1;
3604
+ padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
3605
+ const s = new Array(25).fill(0n);
3606
+ for (let off = 0; off < padded.length; off += rate) {
3607
+ for (let i = 0; i < rate / 8; i++) {
3608
+ let lane = 0n;
3609
+ for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
3610
+ s[i] = s[i] ^ lane;
3611
+ }
3612
+ keccakF(s);
3613
+ }
3614
+ let out = "";
3615
+ 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");
3616
+ return out;
3401
3617
  }
3402
- function optionTicker(option) {
3403
- return option.ticker || option.symbol;
3618
+ function toChecksumAddress(address) {
3619
+ const lower3 = address.slice(2).toLowerCase();
3620
+ const hash2 = keccak256Hex(new TextEncoder().encode(lower3));
3621
+ let out = "0x";
3622
+ for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower3[i].toUpperCase() : lower3[i];
3623
+ return out;
3404
3624
  }
3405
- function routeLabelFor(option, destinationToken, result) {
3406
- if (result.directTransfer) return "Direct transfer: asset and chain already match.";
3407
- const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
3408
- return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
3625
+ function hasValidChecksum(address) {
3626
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
3627
+ const body = address.slice(2);
3628
+ if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
3629
+ return toChecksumAddress(address) === address;
3409
3630
  }
3410
- function tokenAt2(tokens, chainId, address) {
3411
- const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
3412
- const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
3413
- if (!wanted || !tokens?.length) return void 0;
3414
- return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
3631
+
3632
+ // src/core/zdheavy-codec.ts
3633
+ var concat = (parts) => "0x" + parts.map((p) => p.slice(2)).join("");
3634
+ var hexToBytes2 = (h2) => Uint8Array.from(h2.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
3635
+ var toBytes = (s) => new TextEncoder().encode(s);
3636
+ 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(""));
3637
+ var keccak256 = (h2) => "0x" + keccak256Hex(hexToBytes2(h2));
3638
+ var STEP_VERSION = 5;
3639
+ var MAX_STEPS2 = 8;
3640
+ var StepKind = {
3641
+ LOCAL_PAYOUT: 1,
3642
+ REMOTE_PAYOUT: 2,
3643
+ SEND: 3,
3644
+ SWAP: 4,
3645
+ EXECUTE: 5,
3646
+ NET: 6,
3647
+ SUBSIDY: 7
3648
+ };
3649
+ var ZdHeavyCodecError = class extends Error {
3650
+ constructor(message) {
3651
+ super(message);
3652
+ this.name = "ZdHeavyCodecError";
3653
+ }
3654
+ };
3655
+ function checkedHex(value, length) {
3656
+ if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value) || length !== void 0 && value.length !== 2 + length * 2) {
3657
+ throw new ZdHeavyCodecError(`Expected ${length === void 0 ? "byte-aligned" : length + "-byte"} hex`);
3658
+ }
3659
+ return value.toLowerCase();
3415
3660
  }
3416
- function legAmount(raw2, decimals) {
3417
- if (decimals === void 0) return "";
3661
+ function uint(value, bytes) {
3662
+ if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bytes * 8)) {
3663
+ throw new ZdHeavyCodecError(`Value outside uint${bytes * 8}`);
3664
+ }
3665
+ return toHex(value, { size: bytes });
3666
+ }
3667
+ var Reader2 = class {
3668
+ bytes;
3669
+ offset = 0;
3670
+ constructor(step) {
3671
+ this.bytes = hexToBytes2(checkedHex(step));
3672
+ }
3673
+ take(n) {
3674
+ if (this.offset + n > this.bytes.length) throw new ZdHeavyCodecError("Short step");
3675
+ const result = this.bytes.slice(this.offset, this.offset + n);
3676
+ this.offset += n;
3677
+ return result;
3678
+ }
3679
+ hex(n) {
3680
+ return toHex(this.take(n));
3681
+ }
3682
+ uint(n) {
3683
+ let result = 0n;
3684
+ for (const byte of this.take(n)) result = result << 8n | BigInt(byte);
3685
+ return result;
3686
+ }
3687
+ number(n) {
3688
+ return Number(this.uint(n));
3689
+ }
3690
+ address() {
3691
+ const n = this.number(1);
3692
+ if (n === 0 || n > 64) throw new ZdHeavyCodecError("Address length must be 1..64");
3693
+ return this.hex(n);
3694
+ }
3695
+ bytes16() {
3696
+ return this.hex(this.number(2));
3697
+ }
3698
+ adapters() {
3699
+ const count = this.number(1);
3700
+ if (count > 8) throw new ZdHeavyCodecError("Too many bridge adapters");
3701
+ return Array.from({ length: count }, () => this.number(2));
3702
+ }
3703
+ end() {
3704
+ if (this.offset !== this.bytes.length) throw new ZdHeavyCodecError("Trailing step bytes");
3705
+ }
3706
+ };
3707
+ function decodeStep(step) {
3708
+ const r = new Reader2(step);
3709
+ if (r.number(1) !== STEP_VERSION) throw new ZdHeavyCodecError("Unsupported step version");
3710
+ const kind = r.number(2);
3711
+ if (kind < 1 || kind > 7) throw new ZdHeavyCodecError("Unknown step kind");
3712
+ const chainId = r.uint(8);
3713
+ const count = r.number(1);
3714
+ if (kind !== StepKind.SWAP && count !== 0) throw new ZdHeavyCodecError("Unexpected allowances");
3715
+ const allowances = Array.from({ length: count }, () => ({
3716
+ pathwayId: r.number(1),
3717
+ maxShareBps: r.number(2),
3718
+ params: r.bytes16()
3719
+ }));
3720
+ const base = { chainId, allowances };
3721
+ let result;
3722
+ switch (kind) {
3723
+ case StepKind.LOCAL_PAYOUT:
3724
+ result = { ...base, kind: "LOCAL_PAYOUT", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16) };
3725
+ break;
3726
+ case StepKind.REMOTE_PAYOUT:
3727
+ result = {
3728
+ ...base,
3729
+ kind: "REMOTE_PAYOUT",
3730
+ token: r.address(),
3731
+ receiverChainId: r.uint(8),
3732
+ receiver: r.address(),
3733
+ bridgeAdapters: r.adapters(),
3734
+ maxFee: r.uint(16),
3735
+ minAmountOut: r.uint(16)
3736
+ };
3737
+ break;
3738
+ case StepKind.SEND:
3739
+ result = {
3740
+ ...base,
3741
+ kind: "SEND",
3742
+ token: r.address(),
3743
+ dstChainId: r.uint(8),
3744
+ bridgeAdapters: r.adapters(),
3745
+ maxFee: r.uint(16),
3746
+ inUnit: r.uint(16),
3747
+ outUnit: r.uint(16)
3748
+ };
3749
+ break;
3750
+ case StepKind.SWAP:
3751
+ result = { ...base, kind: "SWAP", tokenIn: r.address(), tokenOut: r.address(), expectedIn: r.uint(16), minOut: r.uint(16) };
3752
+ break;
3753
+ case StepKind.EXECUTE:
3754
+ result = { ...base, kind: "EXECUTE", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16), gasLimit: r.uint(8), data: r.bytes16() };
3755
+ break;
3756
+ case StepKind.NET: {
3757
+ const token = r.address(), pathwayId = r.number(1), arriveStep = r.number(1);
3758
+ const params = r.hex(78);
3759
+ const t = new Reader2(params);
3760
+ const terms = {
3761
+ nettingDeadline: t.uint(8),
3762
+ dstDomain: t.number(4),
3763
+ dstAsset: t.hex(32),
3764
+ inUnit: t.uint(16),
3765
+ outUnit: t.uint(16),
3766
+ complianceClass: t.number(2)
3767
+ };
3768
+ result = { chainId, allowances: [{ pathwayId, maxShareBps: 0, params }], kind: "NET", token, pathwayId, arriveStep, terms };
3769
+ break;
3770
+ }
3771
+ case StepKind.SUBSIDY:
3772
+ result = { ...base, kind: "SUBSIDY", token: r.address(), minIn: r.uint(16), amountOut: r.uint(16) };
3773
+ break;
3774
+ default:
3775
+ throw new ZdHeavyCodecError("Unknown step kind");
3776
+ }
3777
+ r.end();
3778
+ return result;
3779
+ }
3780
+ function routerWord(addr) {
3781
+ return concat([toHex(new Uint8Array(12)), checkedHex(addr, 20)]);
3782
+ }
3783
+ function ownerWord(addr) {
3784
+ return routerWord(addr);
3785
+ }
3786
+ function encodeOrderHeader(serial, router, ownerType, owner) {
3787
+ if (!Number.isInteger(ownerType) || ownerType < 0 || ownerType > 255) throw new ZdHeavyCodecError("Invalid ownerType");
3788
+ return concat(["0x050000", uint(serial, 8), routerWord(router), uint(BigInt(ownerType), 1), checkedHex(owner, 32)]);
3789
+ }
3790
+ function orderIdOf(expiryDate, header, steps) {
3791
+ if (steps.length < 1 || steps.length > MAX_STEPS2) throw new ZdHeavyCodecError("Step count must be 1..8");
3792
+ return keccak256(
3793
+ concat([toHex(toBytes("ZD/ORDER")), uint(expiryDate, 8), keccak256(checkedHex(header)), ...steps.map((step) => keccak256(checkedHex(step)))])
3794
+ );
3795
+ }
3796
+ var ZDHEAVY_SUBMIT_SELECTOR = "0x1a579a0c";
3797
+ var ZDHEAVY_PARTNER_SUBMIT_SELECTOR = "0xdd3d9749";
3798
+ var ZDHEAVY_QUOTE_SELECTOR = "0x3cfc3141";
3799
+ function decodeZdHeavySubmit(data) {
3800
+ const hex = checkedHex(data);
3801
+ const selector = hex.slice(0, 10);
3802
+ if (selector !== ZDHEAVY_SUBMIT_SELECTOR && selector !== ZDHEAVY_PARTNER_SUBMIT_SELECTOR) {
3803
+ throw new ZdHeavyCodecError("Expected submitOrder");
3804
+ }
3805
+ const body = hex.slice(10);
3806
+ const size = body.length / 2;
3807
+ const fail = () => {
3808
+ throw new ZdHeavyCodecError("Invalid submitOrder calldata");
3809
+ };
3810
+ const word2 = (at, bits = 256) => {
3811
+ if (!Number.isSafeInteger(at) || at < 0 || at + 32 > size) return fail();
3812
+ const n2 = BigInt(`0x${body.slice(at * 2, (at + 32) * 2)}`);
3813
+ if (n2 >= 1n << BigInt(bits)) return fail();
3814
+ return n2;
3815
+ };
3816
+ const fixed = (at) => {
3817
+ word2(at);
3818
+ return `0x${body.slice(at * 2, (at + 32) * 2)}`;
3819
+ };
3820
+ const offset = (at, expected) => {
3821
+ if (word2(at) !== BigInt(expected)) fail();
3822
+ };
3823
+ const bytes = (at) => {
3824
+ const n2 = word2(at);
3825
+ if (n2 > BigInt(size - at - 32)) return fail();
3826
+ const length = Number(n2);
3827
+ const end = at + 32 + Math.ceil(length / 32) * 32;
3828
+ if (end > size || /[^0]/.test(body.slice((at + 32 + length) * 2, end * 2))) return fail();
3829
+ return { value: `0x${body.slice((at + 32) * 2, (at + 32 + length) * 2)}`, end };
3830
+ };
3831
+ const base = selector === ZDHEAVY_SUBMIT_SELECTOR ? 32 : 64;
3832
+ offset(0, base);
3833
+ const partnerId = base === 64 ? fixed(32) : null;
3834
+ const serial = word2(base, 64);
3835
+ const ownerType = Number(word2(base + 32, 8));
3836
+ const owner = fixed(base + 64);
3837
+ const expiryDate = word2(base + 160, 64);
3838
+ offset(base + 96, 224);
3839
+ const ownerSignature = bytes(base + 224);
3840
+ offset(base + 128, ownerSignature.end - base);
3841
+ const array = ownerSignature.end;
3842
+ const count = word2(array);
3843
+ if (count > BigInt(Math.floor((size - array - 32) / 32))) return fail();
3844
+ const n = Number(count);
3845
+ const arrayBase = array + 32;
3846
+ let next = arrayBase + n * 32;
3847
+ const steps = [];
3848
+ for (let i = 0; i < n; i++) {
3849
+ offset(arrayBase + i * 32, next - arrayBase);
3850
+ const step = bytes(next);
3851
+ steps.push(step.value);
3852
+ next = step.end;
3853
+ }
3854
+ offset(base + 192, next - base);
3855
+ const q = next;
3856
+ const amountIn = word2(q, 128);
3857
+ const fee = { input: word2(q + 32, 128), native: word2(q + 64, 128) };
3858
+ const quoteId = fixed(q + 96);
3859
+ const requestId = fixed(q + 128);
3860
+ const expiresAt = word2(q + 160, 64);
3861
+ offset(q + 192, 224);
3862
+ const signature = bytes(q + 224);
3863
+ if (signature.end !== size) return fail();
3864
+ return {
3865
+ submission: {
3866
+ serial,
3867
+ ownerType,
3868
+ owner,
3869
+ ownerSignature: ownerSignature.value,
3870
+ steps,
3871
+ expiryDate,
3872
+ quote: { amountIn, fee, quoteId, requestId, expiresAt, signature: signature.value }
3873
+ },
3874
+ partnerId
3875
+ };
3876
+ }
3877
+ function quoteSubmitCalldata(data) {
3878
+ decodeZdHeavySubmit(data);
3879
+ const tuple = data.slice(data.slice(0, 10).toLowerCase() === ZDHEAVY_SUBMIT_SELECTOR ? 74 : 138);
3880
+ return `${ZDHEAVY_QUOTE_SELECTOR}${uintWord(32)}${tuple}`;
3881
+ }
3882
+
3883
+ // src/core/zdheavy-check.ts
3884
+ var isAddress2 = hasValidChecksum;
3885
+ var getAddress = (s) => toChecksumAddress(s);
3886
+ var refuse = (what) => ({
3887
+ ok: false,
3888
+ reason: `The ZD Heavy order the gateway built does not match the order shown (${what}) \u2014 refusing to sign.`
3889
+ });
3890
+ var lower = (v) => typeof v === "string" ? v.toLowerCase() : "";
3891
+ function big2(v) {
3892
+ if (v === void 0 || v === null || v === "") return null;
3418
3893
  try {
3419
- return formatUnits(raw2 || "0", decimals);
3894
+ return BigInt(v);
3420
3895
  } catch {
3421
- return "";
3896
+ return null;
3422
3897
  }
3423
3898
  }
3424
- function buildLegs(orders, ctx) {
3425
- const legs = [];
3426
- let fromChainId = ctx.option.chainId;
3427
- let fromAsset = ctx.option.symbol;
3428
- let fromTicker = optionTicker(ctx.option);
3429
- let fromDecimals = ctx.option.decimals;
3430
- for (let index = 0; index < orders.length; index += 1) {
3431
- const order = orders[index];
3432
- const isLast = index === orders.length - 1;
3433
- const toChainId = Number(order.destinationChainId);
3434
- const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
3435
- const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
3436
- const toTicker = askToken ? tokenTicker(askToken) : "";
3437
- const toDecimals = askToken ? assetDecimals(askToken) : void 0;
3438
- const executionChainId = Number(order.executionChainId);
3439
- legs.push({
3440
- index: index + 1,
3441
- fromAsset,
3442
- fromTicker,
3443
- fromChainId,
3444
- fromChainName: chainNameOf(fromChainId, ctx.chains),
3445
- fromAmount: legAmount(order.bidTokenAmount, fromDecimals),
3446
- toAsset,
3447
- toTicker,
3448
- toChainId,
3449
- toChainName: chainNameOf(toChainId, ctx.chains),
3450
- toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
3451
- executionChainId,
3452
- executionChainName: chainNameOf(executionChainId, ctx.chains)
3453
- });
3454
- fromChainId = toChainId;
3455
- fromAsset = toAsset;
3456
- fromTicker = toTicker;
3457
- fromDecimals = toDecimals;
3899
+ var sameBig = (a, b) => big2(b) === a;
3900
+ var sameAddr = (a, b) => !!b && lower(a) === lower(b);
3901
+ function checkZdHeavyRouter(chainId, router) {
3902
+ if (!router || !isAddress2(router)) return { ok: false, reason: "No valid ZD Heavy router address for this chain \u2014 refusing to sign." };
3903
+ const address = getAddress(router);
3904
+ const pinned = (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).map((a) => getAddress(a));
3905
+ if (!pinned.includes(address)) {
3906
+ return { ok: false, reason: `Router ${address} is not a trusted ZD Heavy router on this chain \u2014 refusing to sign.` };
3907
+ }
3908
+ return { ok: true, address };
3909
+ }
3910
+ function checkZdHeavyValue(txValue, quotedSubmit) {
3911
+ if (quotedSubmit === void 0) return { ok: false, reason: "The router\u2019s submit fee could not be read \u2014 refusing to sign." };
3912
+ if (big2(txValue) !== quotedSubmit) return { ok: false, reason: "The transaction carries a native value the router did not quote \u2014 refusing to sign." };
3913
+ return { ok: true };
3914
+ }
3915
+ function sameAllowances(d, j) {
3916
+ if (d.kind !== "SWAP") return true;
3917
+ const want = j.allowances ?? [];
3918
+ if (want.length !== d.allowances.length) return false;
3919
+ return d.allowances.every((a, i) => {
3920
+ const w = want[i];
3921
+ return a.pathwayId === w.pathwayId && a.maxShareBps === w.maxShareBps && lower(a.params) === lower(w.params && w.params !== "" ? w.params : "0x");
3922
+ });
3923
+ }
3924
+ function sameAdapters(a, b) {
3925
+ const w = b ?? [];
3926
+ return a.length === w.length && a.every((x, i) => x === w[i]);
3927
+ }
3928
+ function sameStep(d, j) {
3929
+ if (d.kind !== String(j.kind).toUpperCase()) return false;
3930
+ if (!sameBig(d.chainId, j.chainId)) return false;
3931
+ if (!sameAllowances(d, j)) return false;
3932
+ switch (d.kind) {
3933
+ case "SWAP":
3934
+ return sameAddr(d.tokenIn, j.tokenIn) && sameAddr(d.tokenOut, j.tokenOut) && sameBig(d.expectedIn, j.expectedIn) && sameBig(d.minOut, j.minOut);
3935
+ case "LOCAL_PAYOUT":
3936
+ return sameAddr(d.token, j.token) && sameAddr(d.receiver, j.receiver) && sameBig(d.minAmountOut, j.minAmountOut);
3937
+ case "REMOTE_PAYOUT":
3938
+ 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);
3939
+ case "SEND":
3940
+ 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);
3941
+ case "SUBSIDY":
3942
+ return sameAddr(d.token, j.token) && sameBig(d.minIn, j.minIn) && sameBig(d.amountOut, j.amountOut);
3943
+ case "NET": {
3944
+ const t = j.terms;
3945
+ if (!t) return false;
3946
+ const domainOfAsset = Number(BigInt(t.dstAsset) >> 224n);
3947
+ 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);
3948
+ }
3949
+ default:
3950
+ return false;
3458
3951
  }
3459
- return legs;
3460
3952
  }
3461
- async function buildRoute({
3462
- option,
3463
- destination,
3464
- destinationToken,
3465
- chains,
3466
- tokens,
3467
- payer,
3468
- fetchQuote,
3469
- solve = solveExactOut,
3470
- amountInRaw,
3471
- compliance
3472
- }) {
3473
- const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
3474
- const quote = result.quote;
3475
- const destDecimals = assetDecimals(destinationToken);
3476
- const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
3477
- const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
3478
- if (result.directTransfer) {
3479
- return {
3480
- id: `direct-${option.symbolKey}-${option.chainId}`,
3481
- recommended: false,
3482
- state: "DIRECT",
3483
- source: {
3484
- asset: option.symbol,
3485
- ticker: optionTicker(option),
3486
- chainId: option.chainId,
3487
- chainName: option.chainName,
3488
- tokenAddress: option.address,
3489
- decimals: option.decimals,
3490
- amount: sourceAmount,
3491
- payAmount: sourceAmount
3492
- },
3493
- receive: {
3494
- asset: destinationToken.symbol,
3495
- ticker: tokenTicker(destinationToken),
3496
- chainId: Number(destination.chainId),
3497
- chainName: chainNameOf(Number(destination.chainId), chains),
3498
- tokenAddress: destinationToken.address,
3499
- decimals: destDecimals,
3500
- amount: receiveAmount
3501
- },
3502
- routeLabel: routeLabelFor(option, destinationToken, result),
3503
- deltaLabel: routeDeltaLabel(result, quote),
3504
- // A direct transfer submits no order at all, but it is still ONE hop and history renders the
3505
- // same shape for it — an empty `legs` would leave "one order or two?" unanswerable for it alone.
3506
- legs: [
3507
- {
3508
- index: 1,
3509
- fromAsset: option.symbol,
3510
- fromTicker: optionTicker(option),
3511
- fromChainId: option.chainId,
3512
- fromChainName: option.chainName,
3513
- fromAmount: sourceAmount,
3514
- toAsset: destinationToken.symbol,
3515
- toTicker: tokenTicker(destinationToken),
3516
- toChainId: Number(destination.chainId),
3517
- toChainName: chainNameOf(Number(destination.chainId), chains),
3953
+ function checkSubmit(tx, e) {
3954
+ if (tx.chainId !== String(e.chainId)) return refuse("chain");
3955
+ if (!sameAddr(e.router, tx.to)) return refuse("router");
3956
+ let decoded;
3957
+ try {
3958
+ decoded = decodeZdHeavySubmit(tx.data);
3959
+ } catch {
3960
+ return refuse("not a router submitOrder");
3961
+ }
3962
+ const { submission: s, partnerId } = decoded;
3963
+ const order = e.order;
3964
+ if (!order) return refuse("no order");
3965
+ const wantPartner = typeof e.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(e.partnerId) ? lower(e.partnerId) : null;
3966
+ if ((partnerId ? lower(partnerId) : null) !== wantPartner) return refuse("partner id");
3967
+ if (!isAddress2(e.owner)) return refuse("owner");
3968
+ if (s.ownerType !== 1 || lower(s.owner) !== lower(ownerWord(e.owner))) return refuse("owner");
3969
+ if (s.ownerSignature !== "0x") return refuse("owner signature");
3970
+ if (!s.quote.signature || s.quote.signature === "0x") return refuse("no API signature");
3971
+ if (order.chainNumber !== e.chainId || !sameAddr(e.router, order.router)) return refuse("router");
3972
+ if (s.steps.length < 1 || s.steps.length > MAX_STEPS2 || s.steps.length !== order.steps.length) return refuse("number of steps");
3973
+ const steps = [];
3974
+ for (let i = 0; i < s.steps.length; i++) {
3975
+ let d;
3976
+ try {
3977
+ d = decodeStep(s.steps[i]);
3978
+ } catch {
3979
+ return refuse(`step ${i} encoding`);
3980
+ }
3981
+ if (d.kind === "EXECUTE") return refuse(`step ${i} kind EXECUTE`);
3982
+ if (!sameStep(d, order.steps[i])) return refuse(`step ${i}`);
3983
+ steps.push(d);
3984
+ }
3985
+ const first = steps[0];
3986
+ if (first.chainId !== BigInt(e.chainId)) return refuse("source chain");
3987
+ const firstToken = first.kind === "SWAP" ? first.tokenIn : "token" in first ? first.token : "";
3988
+ if (!sameAddr(e.fromToken, firstToken) || !sameAddr(e.fromToken, order.tokenIn)) return refuse("source token");
3989
+ const last = steps[steps.length - 1];
3990
+ if (steps.slice(0, -1).some((d) => d.kind === "LOCAL_PAYOUT" || d.kind === "REMOTE_PAYOUT")) return refuse("payout before the last step");
3991
+ if (last.kind !== "LOCAL_PAYOUT" && last.kind !== "REMOTE_PAYOUT") return refuse("no payout");
3992
+ const deliveryChain = last.kind === "LOCAL_PAYOUT" ? last.chainId : last.receiverChainId;
3993
+ if (deliveryChain !== BigInt(e.toChainId)) return refuse("destination chain");
3994
+ if (last.kind === "LOCAL_PAYOUT") {
3995
+ if (!sameAddr(e.toToken, last.token)) return refuse("destination token");
3996
+ } else {
3997
+ if (!e.remotePayoutToken?.(last.token, Number(last.chainId))) return refuse("destination token of a cross-chain payout");
3998
+ }
3999
+ if (!sameAddr(e.receiver, last.receiver)) return refuse("receiver");
4000
+ const amountIn = big2(order.amountIn);
4001
+ const feeInput = big2(order.fee.input);
4002
+ const feeNative = big2(order.fee.native);
4003
+ if (amountIn === null || feeInput === null || feeNative === null) return refuse("amount");
4004
+ if (s.quote.amountIn !== amountIn || s.quote.fee.input !== feeInput || s.quote.fee.native !== feeNative) return refuse("amount");
4005
+ if (amountIn + feeInput !== e.amountRaw || big2(order.grossIn) !== e.amountRaw) return refuse("amount");
4006
+ if (s.expiryDate !== BigInt(order.expiryDate) || s.quote.expiresAt !== BigInt(order.expiresAt)) return refuse("expiry");
4007
+ if (s.expiryDate <= BigInt(e.nowSec) || s.quote.expiresAt <= BigInt(e.nowSec)) return refuse("expired");
4008
+ if (last.kind === "REMOTE_PAYOUT" && last.maxFee >= last.minAmountOut) return refuse("minimum out");
4009
+ const floor = last.kind === "REMOTE_PAYOUT" ? last.minAmountOut - last.maxFee : last.minAmountOut;
4010
+ if (floor <= 0n || floor !== e.finalAmount) return refuse("minimum out");
4011
+ let orderId;
4012
+ try {
4013
+ orderId = orderIdOf(s.expiryDate, encodeOrderHeader(s.serial, getAddress(e.router), 1, s.owner), s.steps);
4014
+ } catch {
4015
+ return refuse("order id");
4016
+ }
4017
+ if (!e.rootHash || lower(orderId) !== lower(e.rootHash)) return refuse("order id");
4018
+ return { ok: true, floor, orderId };
4019
+ }
4020
+ function checkZdHeavySubmit(tx, e) {
4021
+ try {
4022
+ return checkSubmit(tx, e);
4023
+ } catch {
4024
+ return refuse("malformed order");
4025
+ }
4026
+ }
4027
+
4028
+ // src/core/asset-identity.ts
4029
+ function key(chainId, address) {
4030
+ const id = Number(chainId);
4031
+ return Number.isSafeInteger(id) && id > 0 && typeof address === "string" && isChainAddress(id, address) ? tokenKey(id, address) : null;
4032
+ }
4033
+ function sameAssetDeployment(tokens, routes, a, b) {
4034
+ const ka = key(a.chainId, a.address);
4035
+ const kb = key(b.chainId, b.address);
4036
+ if (!ka || !kb) return false;
4037
+ const parent = /* @__PURE__ */ new Map();
4038
+ const find = (k) => {
4039
+ const p = parent.get(k);
4040
+ if (p === void 0) {
4041
+ parent.set(k, k);
4042
+ return k;
4043
+ }
4044
+ if (p === k) return k;
4045
+ const root = find(p);
4046
+ parent.set(k, root);
4047
+ return root;
4048
+ };
4049
+ const join = (x, y) => {
4050
+ if (x && y) parent.set(find(y), find(x));
4051
+ };
4052
+ for (const r of routes) {
4053
+ if (r.isEnabled === false) continue;
4054
+ const from = key(r.fromChainId, r.fromAddress);
4055
+ const to = key(r.toChainId, r.toAddress);
4056
+ join(from, to);
4057
+ const home = key(r.homeChainId, r.homeTokenAddress);
4058
+ join(from, home);
4059
+ join(to, home);
4060
+ }
4061
+ for (const t of tokens) join(key(t.chainId, t.address), key(t.homeChainId, t.homeTokenAddress));
4062
+ return parent.has(ka) && parent.has(kb) && find(ka) === find(kb);
4063
+ }
4064
+
4065
+ // src/core/validate-tx.ts
4066
+ var lower2 = (v) => String(v || "").toLowerCase();
4067
+ function isHexAddress(value) {
4068
+ return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
4069
+ }
4070
+ function isHexData(value) {
4071
+ return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value || "0x"));
4072
+ }
4073
+ function isHexQuantity(value) {
4074
+ return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
4075
+ }
4076
+ function dataWord(data, index) {
4077
+ const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4078
+ return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
4079
+ }
4080
+ function dataAddress(data, index) {
4081
+ const word2 = dataWord(data, index);
4082
+ return word2 ? `0x${word2.slice(24)}` : "";
4083
+ }
4084
+ function dataUint(data, index) {
4085
+ const word2 = dataWord(data, index);
4086
+ return word2 ? BigInt(`0x${word2}`) : null;
4087
+ }
4088
+ function rawEquals(value, expected) {
4089
+ try {
4090
+ return value === BigInt(expected || "0");
4091
+ } catch {
4092
+ return false;
4093
+ }
4094
+ }
4095
+ function planMsgValueHex(route) {
4096
+ try {
4097
+ const raw2 = route?.quote?.msgValue;
4098
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4099
+ return "0x" + BigInt(raw2).toString(16);
4100
+ } catch {
4101
+ return null;
4102
+ }
4103
+ }
4104
+ function validatePlannedTransaction(tx, route, expectedRecipient, heavyExpected) {
4105
+ if (!tx || tx.mock) return true;
4106
+ if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
4107
+ const data = String(tx.data || "0x").toLowerCase();
4108
+ const selector = data.slice(0, 10);
4109
+ const value = lower2(tx.value || "0x0");
4110
+ if (tx.kind === "transfer") {
4111
+ if (value !== "0x0") return false;
4112
+ return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower2(tx.to) === lower2(tx.token) && lower2(dataAddress(data, 0)) === lower2(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4113
+ }
4114
+ if (tx.kind === "approve") {
4115
+ if (route.zdHeavy) {
4116
+ return !!heavyExpected && tx.chainId === heavyExpected.chainId && lower2(tx.to) === lower2(heavyExpected.fromToken) && lower2(data) === lower2(encodeApprove(heavyExpected.router, heavyExpected.amountRaw)) && BigInt(value) === 0n;
4117
+ }
4118
+ if (value !== "0x0") return false;
4119
+ 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);
4120
+ }
4121
+ if (tx.kind === "submitOrder") {
4122
+ if (route.zdHeavy) {
4123
+ const expectedValue = planMsgValueHex(route);
4124
+ return expectedValue !== null && value === lower2(expectedValue) && !!heavyExpected && checkZdHeavySubmit({ ...tx, chainId: String(tx.chainId) }, heavyExpected).ok;
4125
+ }
4126
+ const expected = planMsgValueHex(route);
4127
+ if (expected === null || value !== lower2(expected)) return false;
4128
+ if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower2(tx.to) !== lower2(tx.escrow)) return false;
4129
+ const decoded = decodeSubmitOrderCalldata(data);
4130
+ if (!decoded) return false;
4131
+ const first = decoded.orders[0];
4132
+ const last = decoded.orders[decoded.orders.length - 1];
4133
+ 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));
4134
+ }
4135
+ return false;
4136
+ }
4137
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
4138
+ try {
4139
+ return lower2(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4140
+ } catch {
4141
+ return false;
4142
+ }
4143
+ }
4144
+ async function allowanceCovers(tx, account, ethCall2) {
4145
+ if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4146
+ try {
4147
+ const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
4148
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4149
+ } catch {
4150
+ return false;
4151
+ }
4152
+ }
4153
+
4154
+ // src/core/zdheavy-route.ts
4155
+ function zdHeavyExpected(route, owner, receiver, tokens, routes) {
4156
+ const heavy = route.zdHeavy;
4157
+ if (!heavy) throw new Error("Missing ZD Heavy order.");
4158
+ const pin2 = checkZdHeavyRouter(route.source.chainId, heavy.order.router);
4159
+ if (!pin2.ok) throw new Error(pin2.reason);
4160
+ 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))
4161
+ throw new Error("ZD Heavy display amount mismatch.");
4162
+ return {
4163
+ chainId: route.source.chainId,
4164
+ router: pin2.address,
4165
+ owner,
4166
+ receiver,
4167
+ fromToken: route.source.tokenAddress,
4168
+ toToken: route.receive.tokenAddress,
4169
+ toChainId: route.receive.chainId,
4170
+ amountRaw: BigInt(heavy.amountRaw),
4171
+ finalAmount: BigInt(heavy.finalAmount),
4172
+ order: heavy.order,
4173
+ rootHash: heavy.rootHash,
4174
+ partnerId: route.quote.partnerId,
4175
+ nowSec: Math.floor(Date.now() / 1e3),
4176
+ remotePayoutToken: (token, chainId) => sameAssetDeployment(tokens, routes, { chainId, address: token }, { chainId: route.receive.chainId, address: route.receive.tokenAddress })
4177
+ };
4178
+ }
4179
+ function validateZdHeavyPlan(route, expected) {
4180
+ if (route.transactions.length !== 2 || route.transactions[0].kind !== "approve" || route.transactions[1].kind !== "submitOrder") {
4181
+ throw new Error("ZD Heavy requires exactly approve then submitOrder; refusing to sign.");
4182
+ }
4183
+ for (const tx of route.transactions) {
4184
+ if (tx.mock || tx.chainId !== expected.chainId || !validatePlannedTransaction(tx, route, expected.receiver, expected)) {
4185
+ throw new Error("ZD Heavy transaction does not match the reviewed plan; refusing to sign.");
4186
+ }
4187
+ }
4188
+ const submit = route.transactions[1];
4189
+ const checked = checkZdHeavySubmit({ ...submit, chainId: String(submit.chainId) }, expected);
4190
+ if (!checked.ok) throw new Error(checked.reason);
4191
+ return checked.floor;
4192
+ }
4193
+ async function preflightZdHeavyPlan(route, expected, readFee) {
4194
+ validateZdHeavyPlan(route, expected);
4195
+ const tx = route.transactions[1];
4196
+ const value = checkZdHeavyValue(tx.value, await readFee(expected.chainId, expected.router, tx.data));
4197
+ if (!value.ok) throw new Error(value.reason);
4198
+ }
4199
+
4200
+ // src/core/zdheavy-build.ts
4201
+ function buildZdHeavyRoute(ctx) {
4202
+ const { option, destination, destinationToken, chains, result } = ctx;
4203
+ const q = result.quote;
4204
+ if (!zdHeavyExecutable(q)) throw new Error("ZD Heavy quote is not signed and executable.");
4205
+ const order = q.execution.order;
4206
+ const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
4207
+ const decimals = assetDecimals(destinationToken);
4208
+ const receiveAmount = formatUnits(result.recipientReceivesRaw, decimals);
4209
+ const partnerId = typeof q.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(q.partnerId) ? q.partnerId : void 0;
4210
+ const route = {
4211
+ id: `zdh-${option.chainId}-${option.symbolKey}-${destination.chainId}-${destinationToken.symbol}`,
4212
+ recommended: false,
4213
+ state: result.meetsTarget ? "ROUTE" : "SHORT",
4214
+ source: {
4215
+ asset: option.symbol,
4216
+ ticker: option.ticker || option.symbol,
4217
+ chainId: option.chainId,
4218
+ chainName: option.chainName,
4219
+ tokenAddress: option.address,
4220
+ decimals: option.decimals,
4221
+ amount: sourceAmount,
4222
+ payAmount: sourceAmount
4223
+ },
4224
+ receive: {
4225
+ asset: destinationToken.symbol,
4226
+ ticker: tokenTicker(destinationToken),
4227
+ chainId: Number(destination.chainId),
4228
+ chainName: chainNameOf(Number(destination.chainId), chains),
4229
+ tokenAddress: destinationToken.address,
4230
+ decimals,
4231
+ amount: receiveAmount
4232
+ },
4233
+ routeLabel: "Settle on ZeroDelta via ZD Heavy.",
4234
+ deltaLabel: result.meetsTarget ? "~0" : "Below requested amount",
4235
+ legs: [
4236
+ {
4237
+ index: 1,
4238
+ fromAsset: option.symbol,
4239
+ fromTicker: option.ticker || option.symbol,
4240
+ fromChainId: option.chainId,
4241
+ fromChainName: option.chainName,
4242
+ fromAmount: sourceAmount,
4243
+ toAsset: destinationToken.symbol,
4244
+ toTicker: tokenTicker(destinationToken),
4245
+ toChainId: Number(destination.chainId),
4246
+ toChainName: chainNameOf(Number(destination.chainId), chains),
4247
+ toAmount: receiveAmount,
4248
+ executionChainId: option.chainId,
4249
+ executionChainName: option.chainName
4250
+ }
4251
+ ],
4252
+ transactions: q.txData.map((tx, i) => {
4253
+ const submit = tx.actionType === "submit" || tx.actionType === "submitOrder";
4254
+ if (tx.actionType !== "approve" && !submit) throw new Error("Unexpected ZD Heavy transaction action.");
4255
+ if (typeof tx.value !== "string" || !/^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(tx.value)) throw new Error("Invalid ZD Heavy native value.");
4256
+ return {
4257
+ id: submit ? "submit-order" : `approve-${i}`,
4258
+ kind: submit ? "submitOrder" : "approve",
4259
+ label: submit ? "Submit ZeroDelta order" : `Approve ${option.ticker || option.symbol}`,
4260
+ chainId: Number(tx.chainId),
4261
+ to: tx.to,
4262
+ data: tx.data,
4263
+ // The gateway publishes decimal wei; EIP-1193 requires a hex quantity.
4264
+ // Calldata and targets remain the gateway's exact bytes.
4265
+ value: toHexQuantity(tx.value),
4266
+ token: option.address,
4267
+ spender: order.router,
4268
+ amountRaw: result.youPayRaw
4269
+ };
4270
+ }),
4271
+ quote: {
4272
+ bridge: q.bridge,
4273
+ feeBps: q.feeBps,
4274
+ estimatedDuration: q.estimatedDuration,
4275
+ gasCostSource: q.gasCostSource,
4276
+ iterations: result.iterations,
4277
+ compliance: q.compliance,
4278
+ partnerId,
4279
+ zeroDeltaFeeCentibips: q.zeroDeltaFeeCentibips,
4280
+ zeroDeltaFeeNative: q.zeroDeltaFeeNative
4281
+ },
4282
+ zdHeavy: { order, rootHash: q.rootHash, amountRaw: result.youPayRaw, finalAmount: result.recipientReceivesRaw, floor: "" }
4283
+ };
4284
+ if (route.transactions.length === 2) route.quote.msgValue = BigInt(route.transactions[1].value).toString();
4285
+ const expected = zdHeavyExpected(route, ctx.payer, destination.address, ctx.tokens, ctx.routes);
4286
+ route.zdHeavy.floor = validateZdHeavyPlan(route, expected).toString();
4287
+ return route;
4288
+ }
4289
+
4290
+ // src/core/quote-compare.ts
4291
+ var WAIT_MIN_SEC = 180;
4292
+ var WAIT_MAX_SEC = 7200;
4293
+ var WAIT_STEP_SEC = 60;
4294
+ function clampWait(sec) {
4295
+ if (!Number.isFinite(sec)) return WAIT_MIN_SEC;
4296
+ return Math.min(WAIT_MAX_SEC, Math.max(WAIT_MIN_SEC, sec));
4297
+ }
4298
+ var WAIT_POINTS = [
4299
+ [WAIT_MIN_SEC, 0],
4300
+ [1800, 0.295],
4301
+ [2700, 0.4725],
4302
+ [WAIT_MAX_SEC, 1]
4303
+ ];
4304
+ var FIGMA_TRAVEL_PX = 400;
4305
+ function waitScaleFor(travelPx) {
4306
+ if (!Number.isFinite(travelPx) || travelPx >= FIGMA_TRAVEL_PX || travelPx < 200) return WAIT_POINTS;
4307
+ return WAIT_POINTS.map(
4308
+ ([sec, fraction], i) => i === 0 || i === WAIT_POINTS.length - 1 ? [sec, fraction] : [sec, fraction * FIGMA_TRAVEL_PX / travelPx]
4309
+ );
4310
+ }
4311
+ var WAIT_POSITIONS = 1e3;
4312
+ function waitFraction(sec, points = WAIT_POINTS) {
4313
+ const s = clampWait(sec);
4314
+ for (let i = 1; i < points.length; i++) {
4315
+ const [s1, f1] = points[i];
4316
+ if (s <= s1) {
4317
+ const [s0, f0] = points[i - 1];
4318
+ return f0 + (s - s0) / (s1 - s0) * (f1 - f0);
4319
+ }
4320
+ }
4321
+ return 1;
4322
+ }
4323
+ function waitFromFraction(fraction, points = WAIT_POINTS) {
4324
+ const f = Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0;
4325
+ for (let i = 1; i < points.length; i++) {
4326
+ const [s1, f1] = points[i];
4327
+ if (f <= f1) {
4328
+ const [s0, f0] = points[i - 1];
4329
+ return s0 + (f - f0) / (f1 - f0) * (s1 - s0);
4330
+ }
4331
+ }
4332
+ return WAIT_MAX_SEC;
4333
+ }
4334
+ function snapWait(sec) {
4335
+ return clampWait(Math.round(sec / WAIT_STEP_SEC) * WAIT_STEP_SEC);
4336
+ }
4337
+ function waitLabel(sec) {
4338
+ const min = Math.round(clampWait(sec) / 60);
4339
+ if (min >= 60 && min % 60 === 0) return `Up to ${min / 60} ${min === 60 ? "hour" : "hours"}`;
4340
+ return `Up to ${min} min`;
4341
+ }
4342
+ var hasTime = (o) => Number.isFinite(o.estimatedDuration) && o.estimatedDuration > 0;
4343
+ function selectableOptions(options) {
4344
+ return options.filter((o) => !o.unavailable);
4345
+ }
4346
+ function bestOutputOption(options) {
4347
+ return selectableOptions(options).reduce((best, o) => !best || o.amount > best.amount ? o : best, void 0);
4348
+ }
4349
+ function fastestOption(options) {
4350
+ const selectable = selectableOptions(options);
4351
+ const labelled = selectable.find((o) => o.label?.toLowerCase() === "fastest");
4352
+ if (labelled) return labelled;
4353
+ return selectable.filter(hasTime).reduce((f, o) => !f || o.estimatedDuration < f.estimatedDuration ? o : f, void 0);
4354
+ }
4355
+ function proposedWait(options) {
4356
+ const best = bestOutputOption(options);
4357
+ return clampWait(best && hasTime(best) ? best.estimatedDuration : WAIT_MIN_SEC);
4358
+ }
4359
+ function pickForWait(options, waitSec) {
4360
+ const within = selectableOptions(options).filter((o) => hasTime(o) && o.estimatedDuration <= waitSec);
4361
+ return bestOutputOption(within) ?? fastestOption(options);
4362
+ }
4363
+ var MAX_QUOTE_CARDS = 3;
4364
+ function visibleOptions(options, waitSec, selectedId) {
4365
+ if (options.length <= MAX_QUOTE_CARDS) return nettingFirst(options);
4366
+ const selectable = selectableOptions(options);
4367
+ if (selectable.length === 0) return nettingFirst(options.slice(0, MAX_QUOTE_CARDS));
4368
+ const chosen = selectable.find((o) => o.id === selectedId) ?? pickForWait(options, waitSec);
4369
+ const gasless = bestOutputOption(selectable.filter((o) => o.gasSponsored));
4370
+ const netting = bestOutputOption(selectable.filter((o) => o.entersNetting));
4371
+ const ids = new Set([chosen?.id, fastestOption(options)?.id, gasless?.id, netting?.id].filter((id) => !!id));
4372
+ const keep = new Set([...ids].slice(0, MAX_QUOTE_CARDS));
4373
+ return nettingFirst(options.filter((o) => keep.has(o.id)));
4374
+ }
4375
+ function nettingFirst(options) {
4376
+ return [...options.filter((o) => o.entersNetting), ...options.filter((o) => !o.entersNetting)];
4377
+ }
4378
+ function compareDuration(seconds) {
4379
+ if (!Number.isFinite(seconds) || seconds <= 0) return "--";
4380
+ if (seconds < 60) return `~${Math.round(seconds)} s`;
4381
+ return `~${Math.round(seconds / 60)} min`;
4382
+ }
4383
+ function parity(options, inputUsd, toUnitUsd) {
4384
+ const priced = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
4385
+ if (!priced(inputUsd) || !priced(toUnitUsd)) return { kind: "unknown" };
4386
+ const reaching = selectableOptions(options).filter((o) => hasTime(o) && o.amount * toUnitUsd >= inputUsd);
4387
+ const earliest = reaching.reduce(
4388
+ (e, o) => !e || o.estimatedDuration < e.estimatedDuration || o.estimatedDuration === e.estimatedDuration && o.amount > e.amount ? o : e,
4389
+ void 0
4390
+ );
4391
+ return earliest ? { kind: "at", option: earliest, timeSec: earliest.estimatedDuration } : { kind: "unavailable" };
4392
+ }
4393
+ function extraVsFastest(options, selectedId) {
4394
+ const selected = selectableOptions(options).find((o) => o.id === selectedId);
4395
+ const fastest = fastestOption(options);
4396
+ if (!selected || !fastest) return null;
4397
+ const extra = selected.amount - fastest.amount;
4398
+ return extra > 1e-9 ? extra : null;
4399
+ }
4400
+ function routeBadges(options) {
4401
+ const field = options.filter((o) => !o.unavailable);
4402
+ const out = /* @__PURE__ */ new Map();
4403
+ if (field.length < 2) return out;
4404
+ const best = (pick, better) => field.reduce((acc, o) => {
4405
+ const value = pick(o);
4406
+ if (value === null) return acc;
4407
+ const accValue = acc ? pick(acc) : null;
4408
+ return accValue === null || better(value, accValue) ? o : acc;
4409
+ }, null);
4410
+ const bestReturn = best(
4411
+ (o) => o.amount,
4412
+ (a, b) => a > b
4413
+ );
4414
+ const fastest = best(
4415
+ (o) => o.estimatedDuration,
4416
+ (a, b) => a < b
4417
+ );
4418
+ const lowestFee = best(
4419
+ (o) => o.feeUsd,
4420
+ (a, b) => a < b
4421
+ );
4422
+ if (bestReturn) out.set(bestReturn.id, "Best return");
4423
+ if (fastest && !out.has(fastest.id)) out.set(fastest.id, "Fastest");
4424
+ if (lowestFee && !out.has(lowestFee.id)) out.set(lowestFee.id, "Lowest fee");
4425
+ return out;
4426
+ }
4427
+ function routeShapeLabel(option) {
4428
+ if (!option) return null;
4429
+ if (option.kind === "transfer") return "Transfer";
4430
+ const middle = option.hops.slice(1, -1);
4431
+ if (middle.length === 0) return "Direct";
4432
+ return `Via ${middle.map((h2) => h2.ticker).join(" \xB7 ")}`;
4433
+ }
4434
+ function cornerTags(options, option, parityState) {
4435
+ if (option.unavailable) return [];
4436
+ if (option.kind === "transfer") return [{ text: "Transfer", tone: "brand" }];
4437
+ if (option.entersNetting) return [{ text: "Best return", tone: "green" }];
4438
+ const tags = [];
4439
+ const labelledFastest = selectableOptions(options).some((o) => o.label?.toLowerCase() === "fastest");
4440
+ if (parityState.kind === "at" && parityState.option.id === option.id) tags.push({ text: "Target 1:1", tone: "brand" });
4441
+ else if (option.label?.toLowerCase() === "fastest") tags.push({ text: "Fastest", tone: "brand" });
4442
+ else if (option.gasSponsored) tags.push({ text: "Gasless", tone: "purple" });
4443
+ else {
4444
+ const badge = routeBadges(options).get(option.id);
4445
+ const text = badge === "Fastest" && labelledFastest ? void 0 : badge ?? routeShapeLabel(option) ?? void 0;
4446
+ if (text) tags.push({ text, tone: "brand" });
4447
+ }
4448
+ return tags;
4449
+ }
4450
+ function humanAmount(n, maxFrac = 6) {
4451
+ if (!Number.isFinite(n)) return String(n);
4452
+ if (n === 0) return "0";
4453
+ const digits = Math.min(Math.max(0, Math.trunc(maxFrac)), 8);
4454
+ const fixed = n.toFixed(digits);
4455
+ const out = fixed.includes(".") ? fixed.replace(/\.?0+$/, "") : fixed;
4456
+ if (Number(out) === 0) return `<${digits > 0 ? `0.${"0".repeat(digits - 1)}1` : "1"}`;
4457
+ const match = out.match(/^([+-]?)(\d+)(\.\d+)?$/);
4458
+ return match ? `${match[1]}${match[2].replace(/\B(?=(\d{3})+(?!\d))/g, ",")}${match[3] ?? ""}` : out;
4459
+ }
4460
+ function compareAmount(value) {
4461
+ const text = humanAmount(value, 6);
4462
+ if (text.startsWith("<")) return text;
4463
+ const [whole, fraction = ""] = text.split(".");
4464
+ return fraction.length >= 2 ? text : `${whole}.${fraction.padEnd(2, "0")}`;
4465
+ }
4466
+ function compareFeeUsd(option, fromUsd) {
4467
+ const centibips = option.feeCentibips;
4468
+ if (centibips === void 0 || option.feeNative) return null;
4469
+ if (centibips === 0) return 0;
4470
+ return typeof fromUsd === "number" && Number.isFinite(fromUsd) && fromUsd > 0 ? fromUsd * centibips / 1e6 : null;
4471
+ }
4472
+ function priceCompareOptions(options, fromUsd) {
4473
+ return options.map((o) => ({ ...o, feeUsd: compareFeeUsd(o, fromUsd) }));
4474
+ }
4475
+ var ZD_HEAVY_KEY_PREFIX = "zdheavy:";
4476
+ function zdHeavyOptionKey(q) {
4477
+ return q.label ? `${ZD_HEAVY_KEY_PREFIX}${q.label}:${String(q.escrowAddress ?? "").toLowerCase()}` : `${ZD_HEAVY_KEY_PREFIX}id:${q.optionId ?? ""}`;
4478
+ }
4479
+ function zdHeavyUnavailableStatus(q) {
4480
+ return zdHeavyExecutable(q) ? void 0 : typeof q.payloadStatus === "string" && q.payloadStatus ? q.payloadStatus : "unknown";
4481
+ }
4482
+ function tokenAt2(tokens, chainId, address) {
4483
+ const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
4484
+ const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
4485
+ if (!wanted || !tokens?.length) return void 0;
4486
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
4487
+ }
4488
+ function hopFor(tokens, address, chainId, fallback) {
4489
+ const token = tokenAt2(tokens, chainId, address);
4490
+ return { address, chainId, ticker: token ? tokenTicker(token) : fallback ?? "Unknown" };
4491
+ }
4492
+ function compareHops(quote, ctx) {
4493
+ if (quote.protocol === "zdheavy") {
4494
+ const order = quote.execution?.order;
4495
+ if (!order || !Array.isArray(order.steps) || !order.steps.length) return [];
4496
+ const first = order.steps[0];
4497
+ const hops2 = [hopFor(ctx.tokens, String(first.tokenIn ?? first.token ?? order.tokenIn ?? ""), Number(order.chainNumber), ctx.from.ticker)];
4498
+ const push = (address, chainId, fallback) => {
4499
+ if (!address || chainId === void 0) return;
4500
+ const previous = hops2[hops2.length - 1];
4501
+ if (previous.address.toLowerCase() === address.toLowerCase() && previous.chainId === Number(chainId)) return;
4502
+ hops2.push(hopFor(ctx.tokens, address, Number(chainId), fallback));
4503
+ };
4504
+ order.steps.forEach((s, i) => {
4505
+ const n = order.steps[i + 1];
4506
+ const p = hops2[hops2.length - 1];
4507
+ if (s.kind === "SWAP") push(s.tokenOut, s.chainId);
4508
+ else if (s.kind === "SEND") push(n?.tokenIn ?? n?.token, s.dstChainId, p.ticker);
4509
+ else if (s.kind === "LOCAL_PAYOUT") push(s.token, s.chainId, ctx.to.ticker);
4510
+ else if (s.kind === "REMOTE_PAYOUT") push(ctx.to.address, s.receiverChainId, ctx.to.ticker);
4511
+ });
4512
+ return hops2;
4513
+ }
4514
+ const requests = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
4515
+ if (!requests.length) return [];
4516
+ const hops = [hopFor(ctx.tokens, String(requests[0].bidToken ?? ""), Number(quote.fromChainId), ctx.from.ticker)];
4517
+ requests.forEach((request, i) => {
4518
+ const last = i === requests.length - 1;
4519
+ hops.push(hopFor(ctx.tokens, String(request.askToken ?? ""), Number(request.destinationChainId || quote.toChainId), last ? ctx.to.ticker : void 0));
4520
+ });
4521
+ return hops;
4522
+ }
4523
+ var shortAddress2 = (address) => address.slice(0, 10).toLowerCase();
4524
+ function compareOptionOf(quote, ctx) {
4525
+ const heavy = quote.protocol === "zdheavy";
4526
+ if (!heavy && !liteExecutable(quote)) return null;
4527
+ const hops = compareHops(quote, ctx);
4528
+ if (hops.length < 2 && !heavy) return null;
4529
+ let amountRaw;
4530
+ let amount;
4531
+ try {
4532
+ amountRaw = BigInt(quote.finalAmount || quote.toAmount || "");
4533
+ amount = Number(formatUnits(amountRaw, ctx.to.decimals, ctx.to.decimals));
4534
+ } catch {
4535
+ return null;
4536
+ }
4537
+ const centibips = quote.zeroDeltaFeeCentibips;
4538
+ const native = quote.zeroDeltaFeeNative;
4539
+ const feeNative = typeof native === "string" && /^\d+$/.test(native) && BigInt(native) > 0n;
4540
+ const feeCentibips = typeof centibips === "number" && Number.isSafeInteger(centibips) && centibips >= 0 ? centibips : void 0;
4541
+ const unavailable = heavy ? zdHeavyUnavailableStatus(quote) : void 0;
4542
+ const option = {
4543
+ // The path, not the amount: the amount moves on every re-quote, and a key that changes would drop a pick.
4544
+ id: heavy ? zdHeavyOptionKey(quote) : hops.map((h2) => `${h2.chainId}:${shortAddress2(h2.address)}`).join(">"),
4545
+ ...typeof quote.label === "string" && quote.label ? { label: quote.label } : {},
4546
+ ...unavailable ? { unavailable } : {},
4547
+ amount,
4548
+ amountRaw: amountRaw.toString(),
4549
+ estimatedDuration: Number(quote.estimatedDuration) || 0,
4550
+ feeUsd: null,
4551
+ ...feeCentibips !== void 0 ? { feeCentibips } : {},
4552
+ ...feeNative ? { feeNative: true } : {},
4553
+ hops,
4554
+ ...quote.entersNetting === true ? { entersNetting: true } : {},
4555
+ ...quote.gasSponsored === true ? { gasSponsored: true } : {}
4556
+ };
4557
+ option.feeUsd = compareFeeUsd(option);
4558
+ return option;
4559
+ }
4560
+ function compareOptionsOf(quote, ctx) {
4561
+ const all = quote.gatewayOptions?.length ? quote.gatewayOptions : [quote];
4562
+ const seen = /* @__PURE__ */ new Set();
4563
+ const byIndex = all.map((q) => {
4564
+ const row = compareOptionOf(q, ctx);
4565
+ if (!row || seen.has(row.id)) return null;
4566
+ seen.add(row.id);
4567
+ return row;
4568
+ });
4569
+ return { options: byIndex.filter((o) => !!o), byIndex };
4570
+ }
4571
+
4572
+ // src/core/route.ts
4573
+ function routeDeltaLabel(result, quote) {
4574
+ if (result.directTransfer) return "~0";
4575
+ if (!result.meetsTarget) return "Below requested amount";
4576
+ if (result.overageBps > 0) return `+${(result.overageBps / 100).toFixed(2)}% buffer`;
4577
+ if (quote.feeBps) return `${quote.feeBps} bps fee`;
4578
+ return "~0";
4579
+ }
4580
+ function quotePartnerId(quote) {
4581
+ const raw2 = quote.partnerId;
4582
+ return typeof raw2 === "string" && /^0x[0-9a-fA-F]{64}$/.test(raw2) ? raw2.toLowerCase() : NO_PARTNER_ID;
4583
+ }
4584
+ function optionTicker(option) {
4585
+ return option.ticker || option.symbol;
4586
+ }
4587
+ function routeLabelFor(option, destinationToken, result) {
4588
+ if (result.directTransfer) return "Direct transfer: asset and chain already match.";
4589
+ const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
4590
+ return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
4591
+ }
4592
+ function tokenAt3(tokens, chainId, address) {
4593
+ const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
4594
+ const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
4595
+ if (!wanted || !tokens?.length) return void 0;
4596
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
4597
+ }
4598
+ function legAmount(raw2, decimals) {
4599
+ if (decimals === void 0) return "";
4600
+ try {
4601
+ return formatUnits(raw2 || "0", decimals);
4602
+ } catch {
4603
+ return "";
4604
+ }
4605
+ }
4606
+ function buildLegs(orders, ctx) {
4607
+ const legs = [];
4608
+ let fromChainId = ctx.option.chainId;
4609
+ let fromAsset = ctx.option.symbol;
4610
+ let fromTicker = optionTicker(ctx.option);
4611
+ let fromDecimals = ctx.option.decimals;
4612
+ for (let index = 0; index < orders.length; index += 1) {
4613
+ const order = orders[index];
4614
+ const isLast = index === orders.length - 1;
4615
+ const toChainId = Number(order.destinationChainId);
4616
+ const askToken = isLast ? ctx.destinationToken : tokenAt3(ctx.tokens, toChainId, order.askToken);
4617
+ const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
4618
+ const toTicker = askToken ? tokenTicker(askToken) : "";
4619
+ const toDecimals = askToken ? assetDecimals(askToken) : void 0;
4620
+ const executionChainId = Number(order.executionChainId);
4621
+ legs.push({
4622
+ index: index + 1,
4623
+ fromAsset,
4624
+ fromTicker,
4625
+ fromChainId,
4626
+ fromChainName: chainNameOf(fromChainId, ctx.chains),
4627
+ fromAmount: legAmount(order.bidTokenAmount, fromDecimals),
4628
+ toAsset,
4629
+ toTicker,
4630
+ toChainId,
4631
+ toChainName: chainNameOf(toChainId, ctx.chains),
4632
+ toAmount: legAmount(order.askTokenAmount, isLast ? askTokenDecimals(ctx.quote, ctx.tokens || [], ctx.option, ctx.destinationToken) : toDecimals),
4633
+ executionChainId,
4634
+ executionChainName: chainNameOf(executionChainId, ctx.chains)
4635
+ });
4636
+ fromChainId = toChainId;
4637
+ fromAsset = toAsset;
4638
+ fromTicker = toTicker;
4639
+ fromDecimals = toDecimals;
4640
+ }
4641
+ return legs;
4642
+ }
4643
+ async function buildRoute(args) {
4644
+ const { option, destination, destinationToken, payer, fetchQuote, amountInRaw } = args;
4645
+ const solve = args.solve ?? solveExactOut;
4646
+ const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
4647
+ const route = routeFromResult(args, result);
4648
+ return result.directTransfer ? route : withQuoteOptions(route, args, result, solve === solveExactIn ? "exact-in" : "exact-out");
4649
+ }
4650
+ function withQuoteOptions(route, args, result, mode) {
4651
+ const { option, destination, destinationToken } = args;
4652
+ const quote = result.quote;
4653
+ const { byIndex } = compareOptionsOf(quote, {
4654
+ tokens: args.tokens,
4655
+ from: { chainId: option.chainId, address: option.address, ticker: optionTicker(option) },
4656
+ to: { chainId: Number(destination.chainId), address: destinationToken.address, ticker: tokenTicker(destinationToken), decimals: assetDecimals(destinationToken) }
4657
+ });
4658
+ const selectedIndex = quote.gatewayOptions?.length ? quote.gatewayOptionIndex ?? -1 : 0;
4659
+ const built = [];
4660
+ const refused = /* @__PURE__ */ new Set();
4661
+ (quote.gatewayOptions ?? []).forEach((candidate, index) => {
4662
+ const row = byIndex[index];
4663
+ if (!row || row.unavailable || index === selectedIndex) return;
4664
+ try {
4665
+ built.push({ index, route: routeFromResult(args, resultForOption(result, candidate, mode, destination.chainId)) });
4666
+ } catch {
4667
+ refused.add(index);
4668
+ }
4669
+ });
4670
+ const options = [];
4671
+ byIndex.forEach((row, index) => {
4672
+ if (row) options.push(refused.has(index) ? { ...row, unavailable: "refused-by-widget" } : row);
4673
+ });
4674
+ const selectedOptionId = byIndex[selectedIndex]?.id;
4675
+ const alternatives = built.map(({ index, route: alt }) => ({ ...alt, id: route.id, options, selectedOptionId: byIndex[index].id }));
4676
+ return { ...route, options, ...selectedOptionId ? { selectedOptionId } : {}, ...alternatives.length ? { alternatives } : {} };
4677
+ }
4678
+ function routeFromResult({ option, destination, destinationToken, chains, tokens, routes, payer, compliance }, result) {
4679
+ const quote = result.quote;
4680
+ const destDecimals = assetDecimals(destinationToken);
4681
+ const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
4682
+ const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
4683
+ if (result.directTransfer) {
4684
+ return {
4685
+ id: `direct-${option.symbolKey}-${option.chainId}`,
4686
+ recommended: false,
4687
+ state: "DIRECT",
4688
+ source: {
4689
+ asset: option.symbol,
4690
+ ticker: optionTicker(option),
4691
+ chainId: option.chainId,
4692
+ chainName: option.chainName,
4693
+ tokenAddress: option.address,
4694
+ decimals: option.decimals,
4695
+ amount: sourceAmount,
4696
+ payAmount: sourceAmount
4697
+ },
4698
+ receive: {
4699
+ asset: destinationToken.symbol,
4700
+ ticker: tokenTicker(destinationToken),
4701
+ chainId: Number(destination.chainId),
4702
+ chainName: chainNameOf(Number(destination.chainId), chains),
4703
+ tokenAddress: destinationToken.address,
4704
+ decimals: destDecimals,
4705
+ amount: receiveAmount
4706
+ },
4707
+ routeLabel: routeLabelFor(option, destinationToken, result),
4708
+ deltaLabel: routeDeltaLabel(result, quote),
4709
+ // A direct transfer submits no order at all, but it is still ONE hop and history renders the
4710
+ // same shape for it — an empty `legs` would leave "one order or two?" unanswerable for it alone.
4711
+ legs: [
4712
+ {
4713
+ index: 1,
4714
+ fromAsset: option.symbol,
4715
+ fromTicker: optionTicker(option),
4716
+ fromChainId: option.chainId,
4717
+ fromChainName: option.chainName,
4718
+ fromAmount: sourceAmount,
4719
+ toAsset: destinationToken.symbol,
4720
+ toTicker: tokenTicker(destinationToken),
4721
+ toChainId: Number(destination.chainId),
4722
+ toChainName: chainNameOf(Number(destination.chainId), chains),
3518
4723
  toAmount: receiveAmount,
3519
4724
  executionChainId: option.chainId,
3520
4725
  executionChainName: option.chainName
@@ -3545,6 +4750,9 @@ async function buildRoute({
3545
4750
  }
3546
4751
  };
3547
4752
  }
4753
+ if (quote.protocol === "zdheavy") {
4754
+ return buildZdHeavyRoute({ option, destination, destinationToken, chains, tokens: tokens ?? [], routes: routes ?? [], payer, result });
4755
+ }
3548
4756
  const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
3549
4757
  if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
3550
4758
  const sourceChain = chainById(chains, option.chainId);
@@ -3646,12 +4854,134 @@ async function buildRoute({
3646
4854
  };
3647
4855
  }
3648
4856
 
4857
+ // src/core/promotions.ts
4858
+ var CENTIBIPS_PER_UNIT = 1e6;
4859
+ function toToken(raw2) {
4860
+ if (!raw2 || typeof raw2 !== "object") return void 0;
4861
+ const r = raw2;
4862
+ const chainId = Number(r.chainId);
4863
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) return void 0;
4864
+ if (typeof r.address !== "string" || !r.address) return void 0;
4865
+ if (typeof r.symbol !== "string" || !r.symbol) return void 0;
4866
+ return { chainId, address: r.address, symbol: r.symbol };
4867
+ }
4868
+ function parsePromotion(raw2, now = Date.now()) {
4869
+ if (!raw2 || typeof raw2 !== "object") return void 0;
4870
+ const r = raw2;
4871
+ if (typeof r.id !== "string" || !r.id) return void 0;
4872
+ if (r.kind !== "token" && r.kind !== "pair") return void 0;
4873
+ const destination = toToken(r.destination);
4874
+ if (!destination) return void 0;
4875
+ const source2 = r.kind === "pair" ? toToken(r.source) : void 0;
4876
+ if (r.kind === "pair" && !source2) return void 0;
4877
+ const bonusCentibips = Number(r.bonusCentibips);
4878
+ if (!Number.isSafeInteger(bonusCentibips) || bonusCentibips <= 0) return void 0;
4879
+ if (r.fundedBy !== "issuer" && r.fundedBy !== "zerodelta") return void 0;
4880
+ if (typeof r.startsAt !== "string" || typeof r.endsAt !== "string") return void 0;
4881
+ const starts = Date.parse(r.startsAt);
4882
+ const ends = Date.parse(r.endsAt);
4883
+ if (!Number.isFinite(starts) || !Number.isFinite(ends) || !(starts <= now && now < ends)) return void 0;
4884
+ let maxBonusAmount;
4885
+ if (r.maxBonusAmount !== void 0) {
4886
+ if (typeof r.maxBonusAmount !== "string" || !/^[1-9]\d*$/.test(r.maxBonusAmount)) return void 0;
4887
+ maxBonusAmount = r.maxBonusAmount;
4888
+ }
4889
+ return {
4890
+ id: r.id,
4891
+ kind: r.kind,
4892
+ destination,
4893
+ ...source2 ? { source: source2 } : {},
4894
+ bonusCentibips,
4895
+ ...maxBonusAmount ? { maxBonusAmount } : {},
4896
+ fundedBy: r.fundedBy,
4897
+ ...typeof r.funderName === "string" && r.funderName ? { funderName: r.funderName } : {},
4898
+ startsAt: r.startsAt,
4899
+ endsAt: r.endsAt
4900
+ };
4901
+ }
4902
+ function parsePromotions(rows, now = Date.now()) {
4903
+ if (!Array.isArray(rows)) return [];
4904
+ return rows.map((row) => parsePromotion(row, now)).filter((p) => !!p);
4905
+ }
4906
+ function sameAddress(a, b) {
4907
+ return a.startsWith("0x") && b.startsWith("0x") ? a.toLowerCase() === b.toLowerCase() : a === b;
4908
+ }
4909
+ function sameToken(t, chainId, address) {
4910
+ return t.chainId === chainId && sameAddress(t.address, address);
4911
+ }
4912
+ function promotedAssets(promotions) {
4913
+ const bySymbol = /* @__PURE__ */ new Map();
4914
+ for (const p of promotions) {
4915
+ if (p.kind !== "token") continue;
4916
+ const key2 = p.destination.symbol.toUpperCase();
4917
+ const asset = bySymbol.get(key2) ?? { symbol: p.destination.symbol, maxCentibips: 0, networks: [], fundedBy: p.fundedBy };
4918
+ asset.networks.push({ promotion: p, chainId: p.destination.chainId, address: p.destination.address, bonusCentibips: p.bonusCentibips });
4919
+ if (p.bonusCentibips > asset.maxCentibips) {
4920
+ asset.maxCentibips = p.bonusCentibips;
4921
+ asset.fundedBy = p.fundedBy;
4922
+ }
4923
+ bySymbol.set(key2, asset);
4924
+ }
4925
+ const assets = [...bySymbol.values()];
4926
+ for (const a of assets) a.networks.sort((x, y) => y.bonusCentibips - x.bonusCentibips || x.chainId - y.chainId);
4927
+ return assets.sort((a, b) => b.maxCentibips - a.maxCentibips || a.symbol.localeCompare(b.symbol));
4928
+ }
4929
+ function promotionFor(promotions, ends) {
4930
+ let best;
4931
+ for (const p of promotions) {
4932
+ if (!sameToken(p.destination, ends.toChainId, ends.toAddress)) continue;
4933
+ if (p.kind === "pair") {
4934
+ if (!p.source || ends.fromChainId === void 0 || !ends.fromAddress) continue;
4935
+ if (!sameToken(p.source, ends.fromChainId, ends.fromAddress)) continue;
4936
+ }
4937
+ if (!best || p.bonusCentibips > best.bonusCentibips) best = p;
4938
+ }
4939
+ return best;
4940
+ }
4941
+ function pairPromotionsInto(promotions, chainId, address) {
4942
+ return promotions.filter((p) => p.kind === "pair" && sameToken(p.destination, chainId, address));
4943
+ }
4944
+ function estimateBonus(amount, promotion) {
4945
+ if (amount <= 0n) return 0n;
4946
+ const bonus = amount * BigInt(promotion.bonusCentibips) / BigInt(CENTIBIPS_PER_UNIT);
4947
+ if (promotion.maxBonusAmount) {
4948
+ const cap = BigInt(promotion.maxBonusAmount);
4949
+ return bonus > cap ? cap : bonus;
4950
+ }
4951
+ return bonus;
4952
+ }
4953
+ /* @__PURE__ */ new Set([...STABLE_ASSETS, "GHO", "USD0", "USDF"]);
4954
+
4955
+ // src/core/quote-request.ts
4956
+ function nativeQuoteRequest(body) {
4957
+ const inputChain = Number(body.fromChainId);
4958
+ const owner = typeof body.owner === "string" && body.owner ? body.owner : void 0;
4959
+ const destinationWallet = typeof body.destinationReceiver === "string" && body.destinationReceiver ? body.destinationReceiver : void 0;
4960
+ const owners = owner ? isSolanaChainId(inputChain) && isSolanaAddress(owner) ? { svm: owner } : { evm: owner } : void 0;
4961
+ const sender = typeof body.sender === "string" ? body.sender : !isSolanaChainId(inputChain) ? owner : void 0;
4962
+ return {
4963
+ inputChain,
4964
+ outputChain: Number(body.toChainId),
4965
+ inputToken: String(body.fromToken ?? ""),
4966
+ outputToken: String(body.toToken ?? ""),
4967
+ inputAmount: String(body.fromAmount ?? ""),
4968
+ ...owners ? { owners } : {},
4969
+ ...destinationWallet ? { destinationWallet } : {},
4970
+ ...sender && owners && destinationWallet ? { sender } : {},
4971
+ // No new deadline, latency limit or subject is invented for EVM quoting. The
4972
+ // gateway derives the subject from owners when this caller has no explicit one.
4973
+ ...body.deadline !== void 0 ? { deadline: String(body.deadline) } : {},
4974
+ ...typeof body.maxTimeSec === "number" ? { maxTimeSec: body.maxTimeSec } : {},
4975
+ ...typeof body.subjectId === "string" ? { subjectId: body.subjectId } : {}
4976
+ };
4977
+ }
4978
+
3649
4979
  // src/core/channel.ts
3650
4980
  var CHANNEL_HEADER = "x-zd-channel";
3651
4981
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
3652
4982
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
3653
4983
  var WIDGET_CHANNEL = "widget";
3654
- var WIDGET_VERSION = "4.18.2" ;
4984
+ var WIDGET_VERSION = "4.20.0" ;
3655
4985
  var MAX_CHANNEL_VERSION_LEN = 32;
3656
4986
  function sanitizeVersion(raw2) {
3657
4987
  const v = String(raw2).trim();
@@ -3688,6 +5018,20 @@ function isReportableSubmission(report) {
3688
5018
  return typeof wallet === "string" && /^0x[0-9a-fA-F]{40}$/.test(wallet);
3689
5019
  }
3690
5020
 
5021
+ // src/core/quote-refusals.ts
5022
+ var GATE_REFUSALS = /* @__PURE__ */ new Set(["ROUTE_UNHEALTHY", "ROUTE_UNMEASURED", "GATE_UNAVAILABLE"]);
5023
+ function quoteRefusalCopy(code) {
5024
+ return code && GATE_REFUSALS.has(code) ? "This route is not available right now. Try again in a moment, or pick another token or network." : void 0;
5025
+ }
5026
+ var DETERMINISTIC_REFUSALS = /* @__PURE__ */ new Set(["ROUTE_UNHEALTHY", "ROUTE_UNMEASURED", "ROUTE_BLOCKED", "PAIR_HALTED", "PROTOCOL_DISABLED"]);
5027
+ var TRANSIENT_REFUSALS = /* @__PURE__ */ new Set(["GATE_UNAVAILABLE", "MARKET_HALTED"]);
5028
+ function gateRefusalRetryable(code) {
5029
+ if (!code) return void 0;
5030
+ if (DETERMINISTIC_REFUSALS.has(code)) return false;
5031
+ if (TRANSIENT_REFUSALS.has(code)) return true;
5032
+ return void 0;
5033
+ }
5034
+
3691
5035
  // src/core/api.ts
3692
5036
  function apiError(message, props = {}) {
3693
5037
  const err2 = new Error(message);
@@ -3743,7 +5087,7 @@ function classifyQuoteError(error) {
3743
5087
  function amountFieldError(error) {
3744
5088
  const fieldErrors = error?.fieldErrors;
3745
5089
  if (!Array.isArray(fieldErrors)) return null;
3746
- const entry = fieldErrors.find((e) => e && typeof e === "object" && e.field === "fromAmount" && typeof e.message === "string");
5090
+ const entry = fieldErrors.find((e) => e && typeof e === "object" && (e.field === "fromAmount" || e.field === "inputAmount") && typeof e.message === "string");
3747
5091
  const message = entry ? sanitizeMessage(entry.message, "") : "";
3748
5092
  return message || null;
3749
5093
  }
@@ -3751,6 +5095,8 @@ function nowFresh(entry) {
3751
5095
  return !!entry && Date.now() - entry.at < API_CACHE_TTL_MS;
3752
5096
  }
3753
5097
  function isTransientQuoteError(error) {
5098
+ const gate = gateRefusalRetryable(error?.code);
5099
+ if (gate !== void 0) return gate;
3754
5100
  if (error?.code === "BRIDGE_RATE_LIMITED" || Array.isArray(error?.fieldErrors) && error.fieldErrors.length > 0) return false;
3755
5101
  return error?.code === "gateway_timeout" || error?.status === 502 || error?.status === 503 || error?.status === 504 || /failed to get swap quote|timeout|temporar/i.test(error?.message || "");
3756
5102
  }
@@ -3759,7 +5105,7 @@ function wait(ms) {
3759
5105
  }
3760
5106
  var PAGE_LIMIT = 500;
3761
5107
  var MAX_PAGES = 10;
3762
- var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, inflight: /* @__PURE__ */ new Map() });
5108
+ var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, promotions: null, inflight: /* @__PURE__ */ new Map() });
3763
5109
  var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
3764
5110
  function registryCacheFor(scope) {
3765
5111
  if (!scope) return newRegistryCache();
@@ -3821,9 +5167,10 @@ function createApiClient(cfg) {
3821
5167
  }
3822
5168
  }
3823
5169
  if (!response.ok) {
3824
- throw apiError(apiMessage(json, `ZeroDelta request failed (${response.status}).`), {
5170
+ const code = json?.error?.code || json?.code || (response.status >= 502 ? "gateway_timeout" : "api_error");
5171
+ throw apiError(quoteRefusalCopy(code) ?? apiMessage(json, `ZeroDelta request failed (${response.status}).`), {
3825
5172
  status: response.status,
3826
- code: json?.error?.code || json?.code || (response.status >= 502 ? "gateway_timeout" : "api_error"),
5173
+ code,
3827
5174
  fieldErrors: json?.error?.fieldErrors || json?.fieldErrors,
3828
5175
  limits: json?.error?.limits || json?.limits,
3829
5176
  reasons: json?.error?.reasons || json?.reasons
@@ -3916,6 +5263,20 @@ function createApiClient(cfg) {
3916
5263
  return value;
3917
5264
  });
3918
5265
  }
5266
+ function fetchPromotions() {
5267
+ if (nowFresh(cache.promotions)) return Promise.resolve(parsePromotions(cache.promotions.value));
5268
+ return once("promotions", async () => {
5269
+ let value = [];
5270
+ try {
5271
+ const rows = await apiRequest("/promotions", { timeoutMs: 8e3 });
5272
+ value = Array.isArray(rows) ? rows : [];
5273
+ } catch {
5274
+ value = [];
5275
+ }
5276
+ cache.promotions = { at: Date.now(), value };
5277
+ return parsePromotions(value);
5278
+ });
5279
+ }
3919
5280
  const priceCache = /* @__PURE__ */ new Map();
3920
5281
  async function fetchPrices(symbols) {
3921
5282
  const wanted = [...new Set(symbols.map((s) => String(s || "").toUpperCase()).filter((s) => /^[A-Z0-9]{1,16}$/.test(s)))];
@@ -3946,11 +5307,12 @@ function createApiClient(cfg) {
3946
5307
  return out;
3947
5308
  }
3948
5309
  async function fetchQuote(body, retries = 1) {
5310
+ const request = nativeQuoteRequest(body);
3949
5311
  let lastError;
3950
5312
  for (let attempt = 0; attempt <= retries; attempt += 1) {
3951
5313
  try {
3952
- const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(body), timeoutMs: 18e3 });
3953
- return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
5314
+ const quote = await apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
5315
+ return normalizeQuoteResponse(quote, request);
3954
5316
  } catch (error) {
3955
5317
  lastError = error;
3956
5318
  if (attempt >= retries || !isTransientQuoteError(error)) throw error;
@@ -3964,10 +5326,10 @@ function createApiClient(cfg) {
3964
5326
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
3965
5327
  const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3966
5328
  if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3967
- const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
3968
- const hit = screenCache.get(key);
5329
+ const key2 = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
5330
+ const hit = screenCache.get(key2);
3969
5331
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
3970
- const inflight = screenInflight.get(key);
5332
+ const inflight = screenInflight.get(key2);
3971
5333
  if (inflight) return inflight;
3972
5334
  const request = apiRequest("/screen/wallet", {
3973
5335
  method: "POST",
@@ -3978,12 +5340,12 @@ function createApiClient(cfg) {
3978
5340
  throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
3979
5341
  }
3980
5342
  const value = { ...screen, address: screen.address || addr };
3981
- screenCache.set(key, { at: Date.now(), value });
5343
+ screenCache.set(key2, { at: Date.now(), value });
3982
5344
  return value;
3983
5345
  }).finally(() => {
3984
- screenInflight.delete(key);
5346
+ screenInflight.delete(key2);
3985
5347
  });
3986
- screenInflight.set(key, request);
5348
+ screenInflight.set(key2, request);
3987
5349
  return request;
3988
5350
  }
3989
5351
  async function reportSubmission(report) {
@@ -4006,7 +5368,7 @@ function createApiClient(cfg) {
4006
5368
  return false;
4007
5369
  }
4008
5370
  }
4009
- return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchQuote, screenWallet, reportSubmission, apiBase };
5371
+ return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchPromotions, fetchQuote, screenWallet, reportSubmission, apiBase };
4010
5372
  }
4011
5373
 
4012
5374
  // src/core/plan.ts
@@ -4069,9 +5431,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4069
5431
  const balanceTargets = [];
4070
5432
  const seenTargets = /* @__PURE__ */ new Set();
4071
5433
  for (const option of options) {
4072
- const key = optionBalanceKey(option);
4073
- if (seenTargets.has(key)) continue;
4074
- seenTargets.add(key);
5434
+ const key2 = optionBalanceKey(option);
5435
+ if (seenTargets.has(key2)) continue;
5436
+ seenTargets.add(key2);
4075
5437
  balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
4076
5438
  }
4077
5439
  const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
@@ -4083,9 +5445,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4083
5445
  for (const raw2 of [payer, destination.address]) {
4084
5446
  const addr = String(raw2 || "").trim();
4085
5447
  if (!addr) continue;
4086
- const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
4087
- if (seenParty.has(key)) continue;
4088
- seenParty.add(key);
5448
+ const key2 = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
5449
+ if (seenParty.has(key2)) continue;
5450
+ seenParty.add(key2);
4089
5451
  parties.push(addr);
4090
5452
  }
4091
5453
  try {
@@ -4132,6 +5494,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4132
5494
  destinationToken,
4133
5495
  chains,
4134
5496
  tokens,
5497
+ routes,
4135
5498
  payer,
4136
5499
  fetchQuote: api.fetchQuote,
4137
5500
  compliance: option.direct ? directCompliance ?? void 0 : void 0
@@ -4192,7 +5555,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
4192
5555
  (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
4193
5556
  );
4194
5557
  if (!option) throw new Error("That funding option is not available for this payment right now.");
4195
- return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
5558
+ return buildRoute({ option, destination, destinationToken, chains, tokens, routes, payer, fetchQuote: api.fetchQuote });
4196
5559
  }
4197
5560
 
4198
5561
  // src/core/swap.ts
@@ -4200,13 +5563,13 @@ function validateSwap(swap = {}) {
4200
5563
  const fromChainId = Number(swap.fromChainId);
4201
5564
  const toChainId = Number(swap.toChainId);
4202
5565
  const fromToken = symbolKey(swap.fromToken);
4203
- const toToken = symbolKey(swap.toToken);
5566
+ const toToken2 = symbolKey(swap.toToken);
4204
5567
  if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
4205
5568
  if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
4206
- if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken)) throw new Error("Unsupported swap asset.");
5569
+ if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken2)) throw new Error("Unsupported swap asset.");
4207
5570
  const amountIn = normalizeDecimalText(swap.amountIn);
4208
5571
  if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
4209
- return { fromChainId, toChainId, fromToken, toToken, amountIn };
5572
+ return { fromChainId, toChainId, fromToken, toToken: toToken2, amountIn };
4210
5573
  }
4211
5574
  function viaOf(quote, tokens) {
4212
5575
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
@@ -4256,7 +5619,7 @@ async function quoteSwapPreview(api, swap, owner) {
4256
5619
  async function buildSwapPlan(api, swap, payer, wallet = {}) {
4257
5620
  const v = validateSwap(swap);
4258
5621
  const account = assertAddress(payer, "Swap wallet");
4259
- const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
5622
+ const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
4260
5623
  const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
4261
5624
  const destToken = findToken(tokens, v.toChainId, v.toToken);
4262
5625
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
@@ -4279,7 +5642,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4279
5642
  direct: false
4280
5643
  };
4281
5644
  const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
4282
- const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
5645
+ const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, routes, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
4283
5646
  if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
4284
5647
  route.recommended = true;
4285
5648
  return {
@@ -4300,88 +5663,6 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4300
5663
  };
4301
5664
  }
4302
5665
 
4303
- // src/core/validate-tx.ts
4304
- var lower = (v) => String(v || "").toLowerCase();
4305
- function isHexAddress(value) {
4306
- return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
4307
- }
4308
- function isHexData(value) {
4309
- return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value));
4310
- }
4311
- function isHexQuantity(value) {
4312
- return /^0x[0-9a-fA-F]+$/.test(String(value));
4313
- }
4314
- function dataWord(data, index) {
4315
- const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4316
- return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
4317
- }
4318
- function dataAddress(data, index) {
4319
- const word2 = dataWord(data, index);
4320
- return word2 ? `0x${word2.slice(24)}` : "";
4321
- }
4322
- function dataUint(data, index) {
4323
- const word2 = dataWord(data, index);
4324
- return word2 ? BigInt(`0x${word2}`) : null;
4325
- }
4326
- function rawEquals(value, expected) {
4327
- try {
4328
- return value === BigInt(expected || "0");
4329
- } catch {
4330
- return false;
4331
- }
4332
- }
4333
- function planMsgValueHex(route) {
4334
- try {
4335
- const raw2 = route?.quote?.msgValue;
4336
- if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4337
- return "0x" + BigInt(raw2).toString(16);
4338
- } catch {
4339
- return null;
4340
- }
4341
- }
4342
- function validatePlannedTransaction(tx, route, expectedRecipient) {
4343
- if (!tx || tx.mock) return true;
4344
- if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
4345
- const data = String(tx.data || "0x").toLowerCase();
4346
- const selector = data.slice(0, 10);
4347
- const value = lower(tx.value || "0x0");
4348
- if (tx.kind === "transfer") {
4349
- if (value !== "0x0") return false;
4350
- return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4351
- }
4352
- if (tx.kind === "approve") {
4353
- if (value !== "0x0") return false;
4354
- 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);
4355
- }
4356
- if (tx.kind === "submitOrder") {
4357
- const expected = planMsgValueHex(route);
4358
- if (expected === null || value !== lower(expected)) return false;
4359
- if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
4360
- const decoded = decodeSubmitOrderCalldata(data);
4361
- if (!decoded) return false;
4362
- const first = decoded.orders[0];
4363
- const last = decoded.orders[decoded.orders.length - 1];
4364
- 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));
4365
- }
4366
- return false;
4367
- }
4368
- function solanaDeliveryMatches(encoded, recipient2, mint) {
4369
- try {
4370
- return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4371
- } catch {
4372
- return false;
4373
- }
4374
- }
4375
- async function allowanceCovers(tx, account, ethCall2) {
4376
- if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4377
- try {
4378
- const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
4379
- return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4380
- } catch {
4381
- return false;
4382
- }
4383
- }
4384
-
4385
5666
  // src/core/verify.ts
4386
5667
  var TX_VERIFY_ATTEMPTS = 5;
4387
5668
  var TX_VERIFY_INTERVAL_MS = 2500;
@@ -4526,9 +5807,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4526
5807
  const seen = /* @__PURE__ */ new Set();
4527
5808
  for (const target of targets) {
4528
5809
  if (!target || !isAddress(target.tokenAddress)) continue;
4529
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4530
- if (seen.has(key)) continue;
4531
- seen.add(key);
5810
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5811
+ if (seen.has(key2)) continue;
5812
+ seen.add(key2);
4532
5813
  const chainId = Number(target.chainId);
4533
5814
  const group = groups.get(chainId) || [];
4534
5815
  group.push(target);
@@ -4537,8 +5818,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4537
5818
  function record(target, hex) {
4538
5819
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
4539
5820
  const raw2 = BigInt(hex || "0x0").toString();
4540
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4541
- out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
5821
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5822
+ out[key2] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
4542
5823
  return true;
4543
5824
  }
4544
5825
  async function readOne(rpcUrl, target) {
@@ -4584,7 +5865,18 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4584
5865
  return null;
4585
5866
  }
4586
5867
  }
4587
- return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance };
5868
+ async function readZdHeavySubmitFee(chainId, to, data) {
5869
+ try {
5870
+ const override = rpcOverrides[Number(chainId)];
5871
+ const rpc = override && /^https?:\/\//i.test(override) ? override : BUNDLED_RPC[Number(chainId)];
5872
+ if (!rpc) return void 0;
5873
+ const result = await rpcCall(rpc, "eth_call", [{ to, data: quoteSubmitCalldata(data) }, "latest"]);
5874
+ return typeof result === "string" && /^0x[0-9a-fA-F]{64}$/.test(result) ? BigInt(result) : void 0;
5875
+ } catch {
5876
+ return void 0;
5877
+ }
5878
+ }
5879
+ return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance, readZdHeavySubmitFee };
4588
5880
  }
4589
5881
 
4590
5882
  // src/core/config.ts
@@ -4705,6 +5997,7 @@ function createEngine(config = {}) {
4705
5997
  fetchRouteHealth: api.fetchRouteHealth,
4706
5998
  fetchQuote: api.fetchQuote,
4707
5999
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
6000
+ fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
4708
6001
  fetchCatalogue: async (allowedAssets, product, options) => {
4709
6002
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
4710
6003
  api.fetchChains().catch(() => []),
@@ -5148,7 +6441,13 @@ function useFlow(args) {
5148
6441
  statusRef.current = status;
5149
6442
  const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
5150
6443
  const routes = plan?.routes ?? [];
5151
- const selected = react.useMemo(() => routes.find((r) => r.id === selectedId) ?? routes.find((r) => r.recommended) ?? routes[0] ?? null, [routes, selectedId]);
6444
+ const baseSelected = react.useMemo(() => routes.find((r) => r.id === selectedId) ?? routes.find((r) => r.recommended) ?? routes[0] ?? null, [routes, selectedId]);
6445
+ const [pickedOptionId, setPickedOptionId] = react.useState(null);
6446
+ const selected = react.useMemo(() => {
6447
+ if (!baseSelected || !pickedOptionId || pickedOptionId === baseSelected.selectedOptionId) return baseSelected;
6448
+ const alt = baseSelected.alternatives?.find((r) => r.selectedOptionId === pickedOptionId);
6449
+ return alt ? { ...alt, recommended: baseSelected.recommended } : baseSelected;
6450
+ }, [baseSelected, pickedOptionId]);
5152
6451
  const reload = react.useCallback(() => setNonce((n) => n + 1), []);
5153
6452
  const addRoute = react.useCallback((route) => {
5154
6453
  setPlan((p) => p ? { ...p, routes: [...p.routes.filter((r) => r.id !== route.id), route] } : p);
@@ -5203,11 +6502,11 @@ function useFlow(args) {
5203
6502
  if (!wallet.account || !src?.tokenAddress || src.decimals == null) return;
5204
6503
  (async () => {
5205
6504
  try {
5206
- const key = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
6505
+ const key2 = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
5207
6506
  const balances = await engine.readBalances(wallet.account, [
5208
6507
  { chainId: Number(src.chainId), tokenAddress: src.tokenAddress, decimals: Number(src.decimals) }
5209
6508
  ]);
5210
- const entry = balances[key];
6509
+ const entry = balances[key2];
5211
6510
  if (!entry) return;
5212
6511
  const need = parseUnitsDecimal(src.payAmount || src.amount, src.decimals);
5213
6512
  if (alive) setInsufficient(BigInt(entry.raw) < need);
@@ -5271,6 +6570,8 @@ function useFlow(args) {
5271
6570
  throw new Error(nativeFeeShortMessage(check2, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
5272
6571
  }
5273
6572
  }
6573
+ const heavyExpected = route.zdHeavy ? zdHeavyExpected(route, account, recipient2, ...await Promise.all([engine.fetchTokens(), engine.fetchRoutes()])) : void 0;
6574
+ if (heavyExpected) await preflightZdHeavyPlan(route, heavyExpected, engine.verifier.readZdHeavySubmitFee);
5274
6575
  const minNonce = await engine.payerNonceBaseline(Number(sourceChainId), account);
5275
6576
  const txs = route.transactions;
5276
6577
  let settleHash = "";
@@ -5286,7 +6587,7 @@ function useFlow(args) {
5286
6587
  patch(tx.id, "done");
5287
6588
  continue;
5288
6589
  }
5289
- if (!validatePlannedTransaction(tx, route, recipient2)) {
6590
+ if (!validatePlannedTransaction(tx, route, recipient2, heavyExpected ? { ...heavyExpected, nowSec: Math.floor(Date.now() / 1e3) } : void 0)) {
5290
6591
  throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
5291
6592
  }
5292
6593
  patch(tx.id, "active");
@@ -5357,6 +6658,98 @@ function useFlow(args) {
5357
6658
  busyRef.current = false;
5358
6659
  }
5359
6660
  }, [selected, wallet.provider, wallet.account, engine, kind, recipientFor, onSuccess, onError]);
6661
+ const [prices, setPrices] = react.useState(null);
6662
+ const priceKey = baseSelected?.options?.length ? `${baseSelected.source.asset}|${baseSelected.receive.asset}` : "";
6663
+ react.useEffect(() => {
6664
+ if (!priceKey || typeof engine.fetchPrices !== "function") return;
6665
+ let alive = true;
6666
+ const [from, to] = priceKey.split("|");
6667
+ (async () => {
6668
+ try {
6669
+ const p = await engine.fetchPrices([from, to]);
6670
+ const next = { key: priceKey, from: p[from.toUpperCase()], to: p[to.toUpperCase()] };
6671
+ if (alive) setPrices((prev) => prev && prev.key === next.key && prev.from === next.from && prev.to === next.to ? prev : next);
6672
+ } catch {
6673
+ }
6674
+ })();
6675
+ return () => {
6676
+ alive = false;
6677
+ };
6678
+ }, [engine, priceKey]);
6679
+ const compare = react.useMemo(() => {
6680
+ const base = baseSelected;
6681
+ if (!base?.options?.length) return null;
6682
+ const priced = prices?.key === priceKey ? prices : null;
6683
+ const inputAmount = Number(base.source.payAmount || base.source.amount);
6684
+ const fromUsd = priced?.from && Number.isFinite(inputAmount) ? inputAmount * priced.from : null;
6685
+ const options = priceCompareOptions(base.options, fromUsd);
6686
+ const selectedOptionId = selected?.selectedOptionId ?? null;
6687
+ const parityState = parity(options, fromUsd, priced?.to ?? null);
6688
+ return {
6689
+ options,
6690
+ visibleOptions: visibleOptions(options, proposedWait(options), selectedOptionId),
6691
+ selectedId: selectedOptionId,
6692
+ proposedWait: proposedWait(options),
6693
+ parity: parityState,
6694
+ extraVsFastest: extraVsFastest(options, selectedOptionId),
6695
+ tags: Object.fromEntries(options.map((o) => [o.id, cornerTags(options, o, parityState)])),
6696
+ pickForWait: (waitSec) => pickForWait(options, waitSec)
6697
+ };
6698
+ }, [baseSelected, selected, prices, priceKey]);
6699
+ const selectOption = react.useCallback(
6700
+ (optionId) => {
6701
+ if (busyRef.current || !baseSelected) return false;
6702
+ const signable = optionId === baseSelected.selectedOptionId || !!baseSelected.alternatives?.some((r) => r.selectedOptionId === optionId);
6703
+ if (!signable) return false;
6704
+ setPickedOptionId(optionId === baseSelected.selectedOptionId ? null : optionId);
6705
+ return true;
6706
+ },
6707
+ [baseSelected]
6708
+ );
6709
+ const [promotionList, setPromotionList] = react.useState([]);
6710
+ react.useEffect(() => {
6711
+ if (!enabled) return;
6712
+ let alive = true;
6713
+ (async () => {
6714
+ try {
6715
+ if (typeof engine.fetchPromotions !== "function") return;
6716
+ const read = await engine.fetchPromotions();
6717
+ const list = Array.isArray(read) ? read : [];
6718
+ if (alive) setPromotionList((prev) => JSON.stringify(prev) === JSON.stringify(list) ? prev : list);
6719
+ } catch {
6720
+ }
6721
+ })();
6722
+ return () => {
6723
+ alive = false;
6724
+ };
6725
+ }, [engine, enabled]);
6726
+ const promotions = react.useMemo(() => {
6727
+ const route = selected;
6728
+ const toAddress = route?.receive.tokenAddress;
6729
+ const forSelection = route && toAddress ? promotionFor(promotionList, {
6730
+ fromChainId: Number(route.source.chainId),
6731
+ ...route.source.tokenAddress ? { fromAddress: route.source.tokenAddress } : {},
6732
+ toChainId: Number(route.receive.chainId),
6733
+ toAddress
6734
+ }) : void 0;
6735
+ let bonusEstimateRaw = null;
6736
+ if (forSelection && route) {
6737
+ const pickedRow = route.options?.find((o) => o.id === route.selectedOptionId);
6738
+ try {
6739
+ const delivered = pickedRow ? BigInt(pickedRow.amountRaw) : parseUnitsDecimal(route.receive.amount, Number(route.receive.decimals));
6740
+ bonusEstimateRaw = estimateBonus(delivered, forSelection).toString();
6741
+ } catch {
6742
+ bonusEstimateRaw = null;
6743
+ }
6744
+ }
6745
+ return {
6746
+ all: promotionList,
6747
+ promotedAssets: promotedAssets(promotionList),
6748
+ forSelection,
6749
+ pairsInto: route && toAddress ? pairPromotionsInto(promotionList, Number(route.receive.chainId), toAddress) : [],
6750
+ bonusEstimateRaw
6751
+ };
6752
+ }, [promotionList, selected]);
5360
6753
  const quoteReady = status === "ready" && !!plan;
5361
6754
  const quotePaused = quoteReady && idle2;
5362
6755
  const quoteStale = quoteReady && (idle2 || planAt < returnedAt2);
@@ -5378,10 +6771,18 @@ function useFlow(args) {
5378
6771
  quoteStale,
5379
6772
  submit,
5380
6773
  reload,
5381
- addRoute
6774
+ addRoute,
6775
+ compare,
6776
+ selectOption,
6777
+ promotions
5382
6778
  };
5383
6779
  }
5384
6780
  var RETRY_DELAYS_MS = [800, 2400, 6e3];
6781
+ var CATALOGUE_REFRESH_MS = 6e4 + 250;
6782
+ function catalogueSignature(c) {
6783
+ const ids = (list) => list.map((t) => `${Number(t.chainId)}:${String(t.address).toLowerCase()}`).join(",");
6784
+ return [ids(c.tokens), ids(c.sources), [...c.source].sort().join(","), [...c.destination].sort().join(","), [...c.lanes ?? []].sort().join(","), [...c.brokenLanes?.keys() ?? []].sort().join(","), [...c.limitedLanes.keys()].sort().join(",")].join("|");
6785
+ }
5385
6786
  function useCatalogue(engine, options = {}) {
5386
6787
  const { allowedAssets, product, solanaSources } = options;
5387
6788
  const enabled = options.enabled !== false;
@@ -5398,7 +6799,10 @@ function useCatalogue(engine, options = {}) {
5398
6799
  engine.fetchCatalogue(allowedAssets, product, solanaSources ? { solanaSources: true } : void 0).then((next) => {
5399
6800
  if (!alive) return;
5400
6801
  setCatalogue(next);
5401
- if (next.ready) return;
6802
+ if (next.ready) {
6803
+ timer2 = setTimeout(refresh, CATALOGUE_REFRESH_MS);
6804
+ return;
6805
+ }
5402
6806
  if (attempt >= RETRY_DELAYS_MS.length) {
5403
6807
  setFailed(true);
5404
6808
  return;
@@ -5406,6 +6810,23 @@ function useCatalogue(engine, options = {}) {
5406
6810
  timer2 = setTimeout(read, RETRY_DELAYS_MS[attempt++]);
5407
6811
  });
5408
6812
  };
6813
+ const refresh = () => {
6814
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
6815
+ timer2 = setTimeout(refresh, CATALOGUE_REFRESH_MS);
6816
+ return;
6817
+ }
6818
+ if (isUserIdle()) {
6819
+ timer2 = setTimeout(refresh, CATALOGUE_REFRESH_MS);
6820
+ return;
6821
+ }
6822
+ engine.fetchCatalogue(allowedAssets, product, solanaSources ? { solanaSources: true } : void 0).then((next) => {
6823
+ if (!alive) return;
6824
+ if (next.ready) setCatalogue((prev) => prev?.ready && catalogueSignature(prev) === catalogueSignature(next) ? prev : next);
6825
+ }).catch(() => {
6826
+ }).finally(() => {
6827
+ if (alive) timer2 = setTimeout(refresh, CATALOGUE_REFRESH_MS);
6828
+ });
6829
+ };
5409
6830
  read();
5410
6831
  return () => {
5411
6832
  alive = false;
@@ -5446,9 +6867,9 @@ function useHoldings(engine, account, routes, initialBalances) {
5446
6867
  const seeded = {};
5447
6868
  const missing = [];
5448
6869
  for (const target of targets) {
5449
- const key = balanceKey(target.chainId, target.tokenAddress);
5450
- const balance = initialBalances?.[key];
5451
- if (balance) seeded[key] = balance;
6870
+ const key2 = balanceKey(target.chainId, target.tokenAddress);
6871
+ const balance = initialBalances?.[key2];
6872
+ if (balance) seeded[key2] = balance;
5452
6873
  else missing.push(target);
5453
6874
  }
5454
6875
  setBalances(seeded);
@@ -6393,6 +7814,217 @@ button.sg-rcp-row:focus-visible{outline:2px solid var(--sg-accent);outline-offse
6393
7814
  .sg-widget[data-sg-side]:has(>.sg-ws){display:flex;flex-direction:column}
6394
7815
  .sg-widget[data-sg-side]>.sg-ws{flex:1 1 auto}
6395
7816
  @media (prefers-reduced-motion:reduce){.sg-ws{animation:none}.sg-ws-spin{animation:none}}
7817
+ /* \u2500\u2500 Compliance details screen (ComplianceDetails) \u2014 Figma Widget Playground 3238:16033 / 16419 / 16879 / 17276 / 17894 \u2500\u2500 */
7818
+ .sg-cd{--sg-cd-r:min(var(--sg-radius-control),20px);--sg-t50:color-mix(in srgb,var(--sg-text) 50%,transparent);--sg-t25:color-mix(in srgb,var(--sg-text) 25%,transparent);display:flex;flex-direction:column;gap:12px;width:100%;box-sizing:border-box;animation:sg-cp-in var(--sg-motion-fast) var(--sg-ease-out-soft) both}
7819
+ .sg-cd:focus{outline:none}
7820
+ .sg-cd-back{position:relative;align-self:flex-start;display:inline-flex;align-items:center;gap:10px;margin:0 0 12px;padding:0;border:0;background:transparent;color:var(--sg-t50);font:inherit;font-size:14px;font-weight:500;line-height:1.2;cursor:pointer;transition:color 120ms ease}
7821
+ .sg-cd-back::after{content:"";position:absolute;inset:-12px -10px}
7822
+ .sg-cd-back:hover{color:var(--sg-text)}
7823
+ .sg-cd-back:focus-visible{outline:2px solid var(--sg-accent);outline-offset:4px;border-radius:6px}
7824
+ .sg-cd-title{margin:0;font-family:var(--sg-font-display);font-size:16px;font-weight:600;line-height:19.2px;letter-spacing:.32px;color:var(--sg-t90)}
7825
+ .sg-cd-tabs{display:flex;align-items:stretch;gap:0;padding:4px;border:1px solid var(--sg-border);border-radius:calc(var(--sg-cd-r) - 4px)}
7826
+ .sg-cd-tab{flex:1 0 0;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-width:0;padding:13px 8px;border:0;border-radius:calc(var(--sg-cd-r) - 4px);background:transparent;color:var(--sg-t50);font:inherit;font-size:10px;font-weight:700;line-height:14px;text-transform:uppercase;letter-spacing:.2px;white-space:nowrap;cursor:pointer;transition:background 120ms ease,color 120ms ease}
7827
+ .sg-cd-tab:hover{color:var(--sg-text)}
7828
+ .sg-cd-tab[data-active="true"]{background:color-mix(in srgb,var(--sg-accent) 8%,transparent);color:var(--sg-accent)}
7829
+ .sg-cd-tab:focus-visible{outline:2px solid var(--sg-accent);outline-offset:-2px}
7830
+ .sg-cd-tab-count{font-weight:700;color:var(--sg-t25)}
7831
+ .sg-cd-tab[data-active="true"] .sg-cd-tab-count{color:color-mix(in srgb,var(--sg-accent) 50%,transparent)}
7832
+ .sg-cd-panel{display:flex;flex-direction:column;gap:6px;margin-top:-4px}
7833
+ .sg-cd-card{display:flex;flex-direction:column;gap:20px;padding:16px;border:1px solid var(--sg-border);border-radius:var(--sg-cd-r)}
7834
+ .sg-cd-card-head{display:flex;align-items:center;gap:8px}
7835
+ .sg-cd-card-glyph{display:flex;flex:0 0 auto;color:var(--sg-accent)}
7836
+ .sg-cd-card-title{margin:0;font-size:15px;font-weight:500;line-height:1.2;color:var(--sg-t90)}
7837
+ .sg-cd-summary{display:flex;flex-direction:column;gap:4px}
7838
+ .sg-cd-summary-head{display:flex;align-items:center;gap:8px;color:var(--sg-ok-ink)}
7839
+ .sg-cd-summary-head[data-tone="neutral"]{color:var(--sg-t60)}
7840
+ .sg-cd-summary-head[data-tone="blocked"],.sg-cd-summary-head[data-tone="warn"]{color:var(--sg-danger)}
7841
+ .sg-cd-summary-title{font-size:14px;font-weight:500;line-height:1.2;color:var(--sg-t90)}
7842
+ .sg-cd-summary-head[data-tone="blocked"] .sg-cd-summary-title,.sg-cd-summary-head[data-tone="warn"] .sg-cd-summary-title{color:var(--sg-danger)}
7843
+ .sg-cd-summary-sub{margin:0;padding-left:24px;font-size:13px;line-height:1.2;color:var(--sg-t50)}
7844
+ .sg-cd-checks{list-style:none;margin:2px 0 -1px;padding:0;display:flex;flex-direction:column;gap:12px}
7845
+ .sg-cd-card:has(.sg-cd-facts){gap:16px}
7846
+ .sg-cd-check-line{display:flex;align-items:center;gap:8px;min-width:0}
7847
+ .sg-cd-check-mark{display:flex;flex:0 0 auto;width:12px;justify-content:center;color:var(--sg-ok-ink)}
7848
+ .sg-cd-check-mark[data-ok="false"]{color:var(--sg-danger)}
7849
+ .sg-cd-check-label{font-size:14px;line-height:17px;color:var(--sg-t90)}
7850
+ .sg-cd-check[data-ok="false"] .sg-cd-check-label{color:var(--sg-danger)}
7851
+ .sg-cd-check-note,.sg-cd-check-reason{display:block;padding-left:26px;margin-top:3px;font-size:12px;line-height:1.4;color:var(--sg-t60);overflow-wrap:anywhere}
7852
+ .sg-cd-check-reason{color:var(--sg-danger)}
7853
+ .sg-cd-orphans{list-style:none;margin:0;padding:0 0 0 26px;display:flex;flex-direction:column;gap:3px;font-size:12px;line-height:1.4;color:var(--sg-danger)}
7854
+ .sg-cd-scope{margin:0;font-size:12px;line-height:1.45;color:var(--sg-t60)}
7855
+ .sg-cd-flags{margin:0;font-size:14px;color:var(--sg-t90)}
7856
+ .sg-cd-facts{margin:0;display:flex;flex-direction:column;gap:10px;padding-left:24px}
7857
+ .sg-cd-fact{display:grid;grid-template-columns:94px minmax(0,1fr);align-items:baseline;gap:0}
7858
+ .sg-cd-fact dt{font-size:13px;line-height:17px;color:var(--sg-t50)}
7859
+ .sg-cd-fact dd{margin:0;min-width:0;font-size:14px;line-height:17px;color:var(--sg-t90);overflow-wrap:anywhere}
7860
+ .sg-cd-policies{gap:6px}
7861
+ .sg-cd-policy{display:flex;flex-direction:column}
7862
+ .sg-cd-policy-head{position:relative;z-index:1;display:flex;align-items:center;gap:12px;width:100%;box-sizing:border-box;padding:21px 17px;border:1px solid var(--sg-border);border-radius:var(--sg-cd-r);background:var(--sg-bg);color:inherit;font:inherit;text-align:left}
7863
+ button.sg-cd-policy-head{cursor:pointer;transition:border-color 120ms ease}
7864
+ button.sg-cd-policy-head:hover{border-color:color-mix(in srgb,var(--sg-accent) 40%,var(--sg-border))}
7865
+ button.sg-cd-policy-head:focus-visible{outline:2px solid var(--sg-accent);outline-offset:2px}
7866
+ .sg-cd-policy-mark{display:flex;flex:0 0 auto;color:color-mix(in srgb,var(--sg-text) 45%,transparent)}
7867
+ .sg-cd-policy-text{display:flex;flex:1 1 auto;min-width:0;flex-direction:column;gap:6px}
7868
+ .sg-cd-policy-name{font-size:16px;font-weight:500;line-height:1.2;color:var(--sg-t90);overflow-wrap:anywhere}
7869
+ .sg-cd-policy-sub{font-size:14px;line-height:18px;color:var(--sg-t60)}
7870
+ .sg-cd-policy-chev{display:flex;flex:0 0 auto;color:var(--sg-t90)}
7871
+ .sg-cd-policy-body{display:flex;flex-direction:column;gap:6px;margin-top:-24px;padding:40px 16px 16px;border-radius:var(--sg-cd-r);background:color-mix(in srgb,var(--sg-accent) 8%,transparent);animation:sg-cp-in var(--sg-motion-fast) var(--sg-ease-out-soft) both}
7872
+ .sg-cd-bucket{position:relative;display:flex;flex-direction:column;gap:12px;padding:12px 16px;border-radius:var(--sg-cd-r);background:var(--sg-bg)}
7873
+ .sg-cd-bucket-head{display:flex;flex-wrap:wrap;align-items:flex-end;justify-content:space-between;gap:4px 8px}
7874
+ .sg-cd-bucket[data-outcome] .sg-cd-bucket-head:has(.sg-cd-hint){justify-content:flex-start;align-items:center;gap:8px}
7875
+ .sg-cd-bucket-title{font-size:14px;font-weight:500;line-height:16px;color:var(--sg-t90)}
7876
+ .sg-cd-bucket-detail{font-size:12px;line-height:14px;color:var(--sg-t50)}
7877
+ .sg-cd-cats{list-style:none;margin:0;padding:0 0 0 8px;display:flex;flex-direction:column;gap:4px}
7878
+ .sg-cd-cats li{display:flex;align-items:center;gap:12px;font-size:13px;line-height:18px;color:var(--sg-t90)}
7879
+ .sg-cd-dot{flex:0 0 auto;width:4px;height:4px;border-radius:999px;background:var(--sg-t90)}
7880
+ .sg-cd-bucket[data-outcome="flagged"] .sg-cd-dot{background:var(--sg-accent);opacity:.8}
7881
+ .sg-cd-cats li .sg-cd-hint{margin-left:-6px}
7882
+ .sg-cd-hint{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:20px;height:20px;padding:0;border:0;border-radius:999px;background:transparent;color:var(--sg-t60);cursor:pointer;transition:color 120ms ease}
7883
+ .sg-cd-hint{position:relative}
7884
+ .sg-cd-hint::after{content:"";position:absolute;inset:-12px}
7885
+ .sg-cd-hint:hover,.sg-cd-hint[aria-expanded="true"]{color:var(--sg-accent)}
7886
+ .sg-cd-hint:focus-visible{outline:2px solid var(--sg-accent);outline-offset:1px}
7887
+ .sg-cd-tip{position:absolute;z-index:3;left:0;right:0;top:100%;margin-top:2px;padding:10px 12px;border-radius:12px;background:var(--sg-text);color:var(--sg-bg);font-size:12px;font-weight:400;line-height:1.4;text-align:left;pointer-events:none;box-shadow:0 6px 20px rgba(0,0,0,.18)}
7888
+ .sg-cd-cats li,.sg-cd-bucket-head{position:relative}
7889
+ .sg-cd-policy-version{margin:0;padding:4px 4px 0;font-size:12px;line-height:14px;color:var(--sg-t60);overflow-wrap:anywhere}
7890
+ /* Wide's second panel (layout="side", 280px): the same screen on a denser scale \u2014 Figma 3238:16419 / 18187 / 18446 */
7891
+ .sg-cd[data-layout="side"] .sg-cd-back{font-size:12px;font-weight:400;line-height:16px;margin-bottom:4px}
7892
+ .sg-cd[data-layout="side"] .sg-cd-title{margin-bottom:4px;font-family:inherit;font-size:16px;font-weight:500;line-height:1.2;letter-spacing:0}
7893
+ .sg-cd[data-layout="side"] .sg-cd-panel{margin-top:-8px}
7894
+ .sg-cd[data-layout="side"] .sg-cd-card{padding:16px 12px;gap:16px}
7895
+ .sg-cd[data-layout="side"] .sg-cd-card:has(.sg-cd-facts){gap:16px}
7896
+ .sg-cd[data-layout="side"] .sg-cd-card-title{font-size:14px}
7897
+ .sg-cd[data-layout="side"] .sg-cd-summary-head,.sg-cd[data-layout="side"] .sg-cd-card-head{gap:8px}
7898
+ .sg-cd[data-layout="side"] .sg-cd-summary-sub{padding-left:0;font-size:13px;line-height:16px}
7899
+ .sg-cd[data-layout="side"] .sg-cd-checks{gap:12px}
7900
+ .sg-cd[data-layout="side"] .sg-cd-check-label,.sg-cd[data-layout="side"] .sg-cd-fact dt,.sg-cd[data-layout="side"] .sg-cd-fact dd{font-size:13px;line-height:16px}
7901
+ .sg-cd[data-layout="side"] .sg-cd-facts{padding-left:24px;gap:10px}
7902
+ .sg-cd[data-layout="side"] .sg-cd-policy-head{gap:6px;padding:21px 13px}
7903
+ .sg-cd[data-layout="side"] .sg-cd-policy-text{gap:2px}
7904
+ .sg-cd[data-layout="side"] .sg-cd-policy-name{font-size:14px;line-height:1.2}
7905
+ .sg-cd[data-layout="side"] .sg-cd-policy-sub{font-size:13px;line-height:1.4}
7906
+ .sg-cd[data-layout="side"] .sg-cd-policy-mark svg{width:16px;height:16px}
7907
+ .sg-cd[data-layout="side"] .sg-cd-policy-body{padding:32px 8px 16px}
7908
+ .sg-cd[data-layout="side"] .sg-cd-bucket{gap:8px;padding:12px 16px;border-radius:16px}
7909
+ @media (prefers-reduced-motion:reduce){.sg-cd,.sg-cd-policy-body{animation:none}}
7910
+ /* \u2500\u2500 Compare quotes \u2014 Figma Widget Playground 3237:13270 / 3237:13581 / 3237:13897 / 3237:14224 (2026-11-13) \u2500\u2500 */
7911
+ .sg-widget{--sg-a5:color-mix(in srgb,var(--sg-accent) 5%,transparent);--sg-a8:color-mix(in srgb,var(--sg-accent) 8%,transparent);--sg-a50:color-mix(in srgb,var(--sg-accent) 50%,transparent);--sg-purple:#4f24b4;--sg-green-12:color-mix(in srgb,var(--sg-ok-ink) 12%,transparent);--sg-cq-dot:#8fb8b4}
7912
+ .sg-widget[data-sg-mode="dark"]{--sg-purple:#b79cff;--sg-cq-dot:color-mix(in srgb,var(--sg-text) 50%,transparent)}
7913
+ .sg-ws-titlerow{display:flex;align-items:center;gap:12px}
7914
+ .sg-cq-refresh{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:0;border-radius:4px;background:transparent;color:var(--sg-accent);cursor:pointer}
7915
+ .sg-cq-refresh:focus-visible,.sg-cq-main:focus-visible,.sg-cq-route-toggle:focus-visible,.sg-cq-info:focus-visible,.sg-cq-gap:focus-visible{outline:2px solid var(--sg-accent);outline-offset:2px}
7916
+ .sg-cq-spin{animation:sg-spin 900ms linear infinite}
7917
+ .sg-cq{display:flex;flex-direction:column;gap:16px}
7918
+ .sg-cq-wait{display:flex;flex-direction:column;gap:20px;padding:16px 12px 20px;border-radius:24px;background:var(--sg-a5)}
7919
+ .sg-cq-wait-top{display:flex;flex-direction:column;gap:8px}
7920
+ .sg-cq-wait-row{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;font-size:13px;line-height:1.4;color:var(--sg-t80)}
7921
+ .sg-cq-wait-scale{display:flex;flex-direction:column;gap:12px}
7922
+ .sg-cq-track{position:relative;width:100%;height:20px}
7923
+ .sg-cq-range{position:absolute;inset:0;z-index:1;width:100%;height:100%;margin:0;padding:0;border-radius:10px;opacity:0;cursor:pointer;appearance:none;-webkit-appearance:none}
7924
+ .sg-cq-rail{position:absolute;inset:0;overflow:hidden;border-radius:10px;border:1px solid color-mix(in srgb,var(--sg-bg) 80%,transparent);background:var(--sg-a8) repeating-linear-gradient(120deg,transparent 0 5.06px,color-mix(in srgb,var(--sg-bg) 30%,transparent) 5.06px 9.06px)}
7925
+ .sg-cq-range:focus-visible~.sg-cq-rail{outline:2px solid var(--sg-accent);outline-offset:2px}
7926
+ .sg-cq-thumb{position:absolute;left:2px;top:2px;bottom:2px;display:flex;align-items:center;justify-content:flex-end;border-radius:8px;border:1px solid var(--sg-bg);background:var(--sg-accent)}
7927
+ .sg-cq-thumb svg{flex:0 0 auto;margin-right:1px}
7928
+ .sg-cq-ends{position:relative;display:flex;align-items:center;justify-content:space-between;font-size:12px;font-weight:500;line-height:1.2;color:var(--sg-t50)}
7929
+ .sg-cq-parity{position:absolute;top:calc(50% + 2px);transform:translate(-50%,-50%);display:flex;flex-direction:column;align-items:center;padding:4px 8px;border-radius:8px;background:var(--sg-a8);font-size:11px;line-height:1.3;text-align:center;color:color-mix(in srgb,var(--sg-accent) 80%,var(--sg-text))}
7930
+ .sg-cq-parity-none{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);white-space:nowrap;font-size:11px;font-weight:400;color:var(--sg-t50)}
7931
+ .sg-cq-rule{height:1px;margin-top:-1px;background:var(--sg-a12)}
7932
+ .sg-cq-extra{display:flex;flex-wrap:nowrap;align-items:center;justify-content:space-between;gap:8px}
7933
+ .sg-cq-extra-icon{flex:0 0 auto;align-self:center;display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:999px;background:var(--sg-green-12);color:var(--sg-ok-ink)}
7934
+ .sg-cq-extra-icon svg{width:16px;height:16px}
7935
+ .sg-cq-extra-text{display:flex;flex:0 1 auto;min-width:0;flex-direction:column;justify-content:center;gap:0;margin-right:auto}
7936
+ .sg-cq-parity{white-space:nowrap}
7937
+ .sg-ws:has(.sg-cq) .sg-ws-top{gap:24px}
7938
+ .sg-cq-info,.sg-cq-gap{padding:0;border:0;background:transparent;font:inherit}
7939
+ .sg-cq-extra-label{display:flex;align-items:center;gap:6px;white-space:nowrap;font-size:12px;line-height:1.2;color:var(--sg-t50)}
7940
+ .sg-cq-extra-amt{white-space:nowrap;font-size:16px;font-weight:500;line-height:1.2;color:var(--sg-t90)}
7941
+ .sg-cq-extra-note{align-self:center;flex:0 0 auto;margin-left:auto;min-width:0;white-space:nowrap;text-align:right;font-size:9px;line-height:1.2;color:var(--sg-t50)}
7942
+ .sg-cq-info{display:inline-flex;border-radius:4px;color:var(--sg-t50);cursor:help}
7943
+ .sg-cq-list{display:flex;flex-direction:column;gap:8px}
7944
+ .sg-cq-empty{margin:0;padding:24px 0;text-align:center;font-size:13px;line-height:1.4;color:var(--sg-t50)}
7945
+ .sg-cq-card{position:relative;display:flex;flex-direction:column;gap:16px;overflow:clip;padding:16px 12px;border-radius:20px;border:1px solid var(--sg-a12);background:var(--sg-bg)}
7946
+ .sg-cq-card[data-selected]{border-color:color-mix(in srgb,var(--sg-accent) 80%,transparent)}
7947
+ .sg-cq-card[data-unavailable]{background:var(--sg-a4);opacity:.6;filter:grayscale(1)}
7948
+ .sg-cq-main{display:flex;flex-direction:column;align-items:flex-start;gap:20px;width:100%;padding:0;border:0;border-radius:20px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
7949
+ .sg-cq-main:disabled{cursor:not-allowed}
7950
+ .sg-cq-head{display:flex;align-items:flex-start;gap:8px;width:100%;padding-right:min(150px,42%)}
7951
+ .sg-cq-radio{flex:0 0 auto;display:grid;place-items:center;width:16px;height:16px;margin-top:1.6px;border-radius:999px;border:1px solid var(--sg-a50)}
7952
+ .sg-cq-radio[data-on]{border-color:var(--sg-accent)}
7953
+ .sg-cq-radio[data-on]::after{content:"";width:8px;height:8px;border-radius:999px;background:var(--sg-accent)}
7954
+ .sg-cq-amount{min-width:0;font-size:16px;font-weight:500;line-height:1.2;color:var(--sg-t90)}
7955
+ .sg-cq-sr{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
7956
+ .sg-cq-tag{position:absolute;top:-2px;right:-2px;display:flex;align-items:center;gap:8px;padding:10px 32px 12px;border-radius:0 0 0 40px;background:var(--sg-a8);font-size:12px;font-weight:500;line-height:1.4;letter-spacing:.12px}
7957
+ .sg-cq-tag[data-kind="netting"]{background:var(--sg-green-12)}
7958
+ .sg-cq-tag[data-kind="purple"]{background:color-mix(in srgb,var(--sg-purple) 8%,transparent)}
7959
+ .sg-cq-tag-item{display:flex;align-items:center;gap:8px;white-space:nowrap}
7960
+ .sg-cq-tag-dot{width:4px;height:4px;border-radius:999px;background:var(--sg-cq-dot)}
7961
+ .sg-overlay[data-sg-overlay="drawer"] .sg-cq[data-layout="card"] .sg-cq-tag{padding:10px 20px 12px;border-radius:0 0 0 32px;font-size:11px;letter-spacing:.11px;gap:6px}
7962
+ .sg-cq-tag [data-tone="brand"]{color:var(--sg-accent)}
7963
+ .sg-cq-tag [data-tone="green"]{color:var(--sg-ok-ink)}
7964
+ .sg-cq-tag [data-tone="purple"]{color:var(--sg-purple)}
7965
+ .sg-widget[data-sg-mode="dark"] .sg-cq-tag [data-tone="brand"]{color:var(--sg-info)}
7966
+ .sg-cq-stats{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;padding:0 12px 0 24px}
7967
+ .sg-cq-cols{display:flex;align-items:center;gap:32px;white-space:nowrap}
7968
+ .sg-cq-col{display:flex;flex-direction:column;justify-content:center;gap:6px}
7969
+ .sg-cq-col-label{font-size:10px;font-weight:500;line-height:1.2;text-transform:uppercase;color:var(--sg-t50)}
7970
+ .sg-cq-col-value{font-size:14px;line-height:1.2;color:var(--sg-text)}
7971
+ .sg-cq-note{width:125px;text-align:right;font-size:12px;line-height:1.2;color:var(--sg-t50)}
7972
+ .sg-cq-why{padding-left:24px;font-size:13px;line-height:1.3;color:var(--sg-t50)}
7973
+ .sg-cq-route{display:flex;flex-direction:column;gap:10px;padding-left:24px}
7974
+ .sg-cq-route-toggle{display:flex;align-items:center;gap:4px;width:fit-content;padding:0;border:0;border-radius:4px;background:transparent;font:inherit;font-size:10px;font-weight:500;line-height:1.2;text-transform:uppercase;color:var(--sg-t50);cursor:pointer}
7975
+ .sg-cq-route-toggle svg{color:var(--sg-text)}
7976
+ .sg-cq-hops{display:flex;flex-wrap:wrap;align-items:flex-start;gap:4px}
7977
+ .sg-cq-hop{display:flex;align-items:flex-start;gap:4px}
7978
+ .sg-cq-arrow{flex:0 0 auto;color:var(--sg-accent)}
7979
+ .sg-cq-hop-body{display:flex;flex-direction:column;gap:4px}
7980
+ .sg-cq-hop-name{display:flex;align-items:center;gap:4px;font-size:14px;line-height:1.2;color:var(--sg-text)}
7981
+ .sg-cq-hop-chain{white-space:nowrap;font-size:12px;line-height:1.2;color:var(--sg-t50)}
7982
+ .sg-cq .sg-tok[data-size="xxs"] .sg-tok-badge{min-width:8px;width:8px;height:8px;right:-1px;bottom:-1px;border-width:1px;border-color:var(--sg-bg);font-size:4px;padding:0}
7983
+ .sg-cq .sg-tok[data-size="xs"] .sg-tok-badge{min-width:11px;width:11px;height:11px;right:-3px;bottom:-3px;border-width:1px;border-color:var(--sg-bg);font-size:4px;padding:0}
7984
+ /* Back-link and gap scoped to Compare quotes (Figma: 14px t50 compact, 12px t50 wide, 24px/16px to the title). */
7985
+ .sg-ws:has(.sg-cq) .sg-ws-back{font-size:14px;font-weight:500;color:var(--sg-t50)}
7986
+ .sg-dialog .sg-ws:has(.sg-cq):not([data-wide]) .sg-ws-top{gap:16px}
7987
+ /* Wide: compact cards, the tag a centred band across the card's top, the route as inline marks */
7988
+ .sg-cq[data-layout="side"] .sg-cq-card{gap:12px;padding:0 0 16px;border-radius:20px}
7989
+ .sg-cq[data-layout="side"] .sg-cq-tag{position:static;justify-content:center;width:100%;padding:2px 20px 4px;border-radius:0;font-size:11px;line-height:1.4;letter-spacing:.11px;gap:6px}
7990
+ .sg-ws[data-wide]:has(.sg-cq) .sg-ws-top{gap:16px}
7991
+ .sg-ws[data-wide]:has(.sg-cq) .sg-ws-title{font-size:16px}
7992
+ .sg-ws[data-wide]:has(.sg-cq) .sg-ws-back{font-size:12px;font-weight:400;color:var(--sg-t50)}
7993
+ .sg-cq[data-layout="side"]{gap:12px}
7994
+ .sg-cq[data-layout="side"] .sg-cq-wait{padding:16px 12px 20px;gap:20px}
7995
+ .sg-cq[data-layout="side"] .sg-cq-rule{margin-bottom:-8px}
7996
+ .sg-cq[data-layout="side"] .sg-cq-card:not(:has(.sg-cq-tag)){padding-top:12px}
7997
+ .sg-cq[data-layout="side"] .sg-cq-main{gap:20px;padding:0 12px;border-radius:0}
7998
+ .sg-cq[data-layout="side"] .sg-cq-head{padding-right:0!important}
7999
+ .sg-cq[data-layout="side"] .sg-cq-amount{font-size:15px}
8000
+ .sg-cq[data-layout="side"] .sg-cq-stats{padding:0}
8001
+ .sg-cq[data-layout="side"] .sg-cq-cols{gap:20px}
8002
+ .sg-cq[data-layout="side"] .sg-cq-col{gap:4px}
8003
+ .sg-cq[data-layout="side"] .sg-cq-col-label{font-size:9px}
8004
+ .sg-cq[data-layout="side"] .sg-cq-col-value{font-size:13px}
8005
+ .sg-cq[data-layout="side"] .sg-cq-card[data-selected]{border-color:color-mix(in srgb,var(--sg-accent) 50%,transparent)}
8006
+ .sg-cq[data-layout="side"] .sg-cq-extra-amt{font-size:15px}
8007
+ .sg-cq[data-layout="side"] .sg-cq-extra-label{gap:4px}
8008
+ .sg-cq[data-layout="side"] .sg-cq-info svg{width:12px;height:12px}
8009
+ .sg-cq[data-layout="side"] .sg-cq-card:not(:has(.sg-cq-tag)) .sg-cq-main{padding-top:0}
8010
+ .sg-cq-route-icons{display:flex;align-items:center;gap:2px}
8011
+ .sg-cq-route-icons .sg-cq-arrow{width:10px;height:10px}
8012
+ .sg-cq-hop-inline{display:flex;align-items:center;gap:2px}
8013
+ .sg-cq-hop-inline>span{display:flex}
8014
+ .sg-cq-gap{display:inline-flex;padding:0 2px;border-radius:4px;color:var(--sg-accent);text-decoration:underline;cursor:help}
8015
+ .sg-cq[data-layout="side"] .sg-cq-wait-scale .sg-cq-parity{flex-direction:row;gap:4px}
8016
+ /* Below Figma's widths the cards must shrink, not clip (narrow page; container = the sheet). */
8017
+ .sg-ws:has(.sg-cq){container-type:inline-size}
8018
+ @container (max-width:300px){
8019
+ .sg-cq-head{padding-right:0!important}
8020
+ .sg-cq-stats{flex-wrap:wrap;gap:8px;padding-left:0}
8021
+ .sg-cq-cols{flex-wrap:wrap;gap:12px;white-space:normal}
8022
+ .sg-cq-note{width:auto;max-width:100%;text-align:left}
8023
+ .sg-cq-route-icons{flex-wrap:wrap}
8024
+ .sg-cq-extra{flex-wrap:wrap}
8025
+ .sg-cq-extra-note{margin-left:0;text-align:left}
8026
+ }
8027
+ @media (prefers-reduced-motion:reduce){.sg-cq-spin{animation:none}}
6396
8028
  `;
6397
8029
  var injected = false;
6398
8030
  function injectStyles() {
@@ -6972,7 +8604,7 @@ function priceOf(prices, symbol) {
6972
8604
  const p = prices?.[String(symbol).toUpperCase()];
6973
8605
  return typeof p === "number" && Number.isFinite(p) ? p : void 0;
6974
8606
  }
6975
- function buildGroup(key, members, prices) {
8607
+ function buildGroup(key2, members, prices) {
6976
8608
  const tokens = members.map((m) => m.token);
6977
8609
  let amount = null;
6978
8610
  let usd2 = null;
@@ -6984,7 +8616,7 @@ function buildGroup(key, members, prices) {
6984
8616
  }
6985
8617
  const first = members[0].token;
6986
8618
  return {
6987
- key,
8619
+ key: key2,
6988
8620
  symbol: dominantSymbol(tokens),
6989
8621
  name: String(first.name || first.symbol),
6990
8622
  logoUrl: first.logoUrl,
@@ -7005,15 +8637,15 @@ function groupDeployments(deployments, prices) {
7005
8637
  const order = [];
7006
8638
  const members = /* @__PURE__ */ new Map();
7007
8639
  for (const d of [...deployments].sort(byDeployment)) {
7008
- const key = String(d.token.symbol).toUpperCase();
7009
- const list = members.get(key);
8640
+ const key2 = String(d.token.symbol).toUpperCase();
8641
+ const list = members.get(key2);
7010
8642
  if (list) list.push(d);
7011
8643
  else {
7012
- members.set(key, [d]);
7013
- order.push(key);
8644
+ members.set(key2, [d]);
8645
+ order.push(key2);
7014
8646
  }
7015
8647
  }
7016
- return order.map((key) => buildGroup(key, members.get(key), prices)).sort(byPickability);
8648
+ return order.map((key2) => buildGroup(key2, members.get(key2), prices)).sort(byPickability);
7017
8649
  }
7018
8650
  var CHAIN_ALIASES = {
7019
8651
  56: ["bsc", "binance"],
@@ -7021,10 +8653,10 @@ var CHAIN_ALIASES = {
7021
8653
  43114: ["avax"]
7022
8654
  };
7023
8655
  function labelForms(label2) {
7024
- const lower2 = label2.trim().toLowerCase();
7025
- if (!lower2) return [];
7026
- const compact = lower2.replace(/[^a-z0-9]/g, "");
7027
- return compact && compact !== lower2 ? [lower2, compact] : [lower2];
8656
+ const lower3 = label2.trim().toLowerCase();
8657
+ if (!lower3) return [];
8658
+ const compact = lower3.replace(/[^a-z0-9]/g, "");
8659
+ return compact && compact !== lower3 ? [lower3, compact] : [lower3];
7028
8660
  }
7029
8661
  function buildChainSearchTerms(chains) {
7030
8662
  const byId = /* @__PURE__ */ new Map();
@@ -7077,7 +8709,7 @@ function groupDecimal2(value) {
7077
8709
  if (!match) return value;
7078
8710
  return `${match[1]}${match[2].replace(/\B(?=(\d{3})+(?!\d))/g, ",")}${match[3] ?? ""}`;
7079
8711
  }
7080
- function humanAmount(n, maxFrac = 6) {
8712
+ function humanAmount2(n, maxFrac = 6) {
7081
8713
  if (!Number.isFinite(n)) return String(n);
7082
8714
  if (n === 0) return "0";
7083
8715
  const digits = Math.min(Math.max(0, Math.trunc(maxFrac)), 8);
@@ -7213,7 +8845,7 @@ function BalanceColumn(props) {
7213
8845
  return /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-pk-bal", children: [
7214
8846
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-pk-bal-usd sg-mono", children: props.usd == null ? "\u2014" : formatBalanceUsd(props.usd) }),
7215
8847
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-pk-bal-amt sg-mono", children: [
7216
- humanAmount(props.amount, 6),
8848
+ humanAmount2(props.amount, 6),
7217
8849
  " ",
7218
8850
  props.symbol
7219
8851
  ] })
@@ -7287,14 +8919,14 @@ function TokenSelect(props) {
7287
8919
  const groups = react.useMemo(() => {
7288
8920
  const deployments = [];
7289
8921
  for (const token of props.tokens) {
7290
- const key = rowKey(token);
7291
- const n = Number(props.balances?.[key]?.formatted);
7292
- const st = props.optionStates?.[key];
8922
+ const key2 = rowKey(token);
8923
+ const n = Number(props.balances?.[key2]?.formatted);
8924
+ const st = props.optionStates?.[key2];
7293
8925
  if (st?.disabled && !WALLET_STATE_REASONS.has(String(st.reason))) continue;
7294
8926
  deployments.push({
7295
8927
  token,
7296
- key,
7297
- balance: showBalances && props.balances?.[key] && Number.isFinite(n) ? n : null,
8928
+ key: key2,
8929
+ balance: showBalances && props.balances?.[key2] && Number.isFinite(n) ? n : null,
7298
8930
  disabled: !!st?.disabled,
7299
8931
  // The line under a greyed row says why. Callers send either a sentence in `reason` (the
7300
8932
  // exchange's "cannot be delivered on this chain") or a machine code there with the words in
@@ -7666,7 +9298,7 @@ function WidgetShell(props) {
7666
9298
  }
7667
9299
  );
7668
9300
  }
7669
- function shortAddress2(a) {
9301
+ function shortAddress3(a) {
7670
9302
  if (!a) return "";
7671
9303
  return `${a.slice(0, 6)}\u2026${a.slice(-4)}`;
7672
9304
  }
@@ -7935,13 +9567,13 @@ function useTxHistory(account) {
7935
9567
  react.useEffect(() => {
7936
9568
  setEntries(readTxHistory(account));
7937
9569
  if (typeof window === "undefined" || !account) return;
7938
- const key = txHistoryKey(account);
9570
+ const key2 = txHistoryKey(account);
7939
9571
  const onLocal = (e) => {
7940
9572
  const detail = e.detail;
7941
9573
  if (!detail?.account || detail.account === account.toLowerCase()) setEntries(readTxHistory(account));
7942
9574
  };
7943
9575
  const onStorage = (e) => {
7944
- if (e.key === key) setEntries(readTxHistory(account));
9576
+ if (e.key === key2) setEntries(readTxHistory(account));
7945
9577
  };
7946
9578
  window.addEventListener(TX_HISTORY_EVENT, onLocal);
7947
9579
  window.addEventListener("storage", onStorage);
@@ -7957,10 +9589,10 @@ var hidden2 = () => typeof document !== "undefined" && document.visibilityState
7957
9589
  var travelling = (entries) => !!entries?.some((e) => e.delivery === "in-progress" || e.delivery === "attention");
7958
9590
  function useWalletHistory(engine, wallets) {
7959
9591
  const [entries, setEntries] = react.useState(null);
7960
- const key = wallets.filter((w) => !!w).join("|");
9592
+ const key2 = wallets.filter((w) => !!w).join("|");
7961
9593
  react.useEffect(() => {
7962
9594
  setEntries(null);
7963
- if (!engine || !key) return;
9595
+ if (!engine || !key2) return;
7964
9596
  let alive = true;
7965
9597
  let timer2;
7966
9598
  let started2 = Date.now();
@@ -7968,7 +9600,7 @@ function useWalletHistory(engine, wallets) {
7968
9600
  if (timer2) clearTimeout(timer2);
7969
9601
  timer2 = void 0;
7970
9602
  if (!hidden2()) {
7971
- const next = await engine.fetchWalletHistory(key.split("|"));
9603
+ const next = await engine.fetchWalletHistory(key2.split("|"));
7972
9604
  if (!alive) return;
7973
9605
  if (next) setEntries(next);
7974
9606
  if (!travelling(next)) return;
@@ -7987,7 +9619,7 @@ function useWalletHistory(engine, wallets) {
7987
9619
  if (timer2) clearTimeout(timer2);
7988
9620
  if (typeof window !== "undefined") window.removeEventListener(TX_HISTORY_EVENT, onRecorded);
7989
9621
  };
7990
- }, [engine, key]);
9622
+ }, [engine, key2]);
7991
9623
  return entries;
7992
9624
  }
7993
9625
  function BackGlyph() {
@@ -8124,15 +9756,15 @@ function TxPair(props) {
8124
9756
  ] });
8125
9757
  }
8126
9758
  function logoFor(art, symbol, chainId) {
8127
- const key = symbolKey(symbol);
8128
- if (!key) return void 0;
9759
+ const key2 = symbolKey(symbol);
9760
+ if (!key2) return void 0;
8129
9761
  const tokens = art.tokens;
8130
9762
  if (tokens?.length) {
8131
- const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) === key);
8132
- const found = (sameChain ?? tokens.find((t) => symbolKey(t.symbol) === key))?.logoUrl;
9763
+ const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) === key2);
9764
+ const found = (sameChain ?? tokens.find((t) => symbolKey(t.symbol) === key2))?.logoUrl;
8133
9765
  if (found) return found;
8134
9766
  }
8135
- return art.vaultIcons?.get(key);
9767
+ return art.vaultIcons?.get(key2);
8136
9768
  }
8137
9769
  function TxHistoryList(props) {
8138
9770
  if (!props.entries.length) {
@@ -8209,7 +9841,7 @@ function TxDetail(props) {
8209
9841
  ] }),
8210
9842
  e.recipient ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
8211
9843
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Recipient" }),
8212
- /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress2(e.recipient) })
9844
+ /* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress3(e.recipient) })
8213
9845
  ] }) : null,
8214
9846
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
8215
9847
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Settlement" }),
@@ -8246,7 +9878,7 @@ function TxHistoryPanel(props) {
8246
9878
  /* @__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, {}) }),
8247
9879
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-title", children: [
8248
9880
  selected ? "Transaction" : "Transaction history",
8249
- account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress2(account) }) : null
9881
+ account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress3(account) }) : null
8250
9882
  ] })
8251
9883
  ] }),
8252
9884
  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 })
@@ -8428,8 +10060,8 @@ function onSolanaAccountChange(info, cb) {
8428
10060
  }
8429
10061
  }) ?? (() => {
8430
10062
  });
8431
- const changed = (key) => {
8432
- const address = validAddress(key);
10063
+ const changed = (key2) => {
10064
+ const address = validAddress(key2);
8433
10065
  connected.set(provider, address ? [{ address }] : []);
8434
10066
  cb(address);
8435
10067
  };
@@ -8586,96 +10218,20 @@ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
8586
10218
  else opts.evm?.connect();
8587
10219
  return;
8588
10220
  }
8589
- if (wallet.address && !name) {
8590
- selectAddress("");
8591
- return;
8592
- }
8593
- if (!name && wallet.wallets.length !== 1) {
8594
- setOpen(true);
8595
- return;
8596
- }
8597
- const address = await wallet.connect(name);
8598
- if (typeof address === "string") selectAddress("");
8599
- else setOpen(true);
8600
- };
8601
- const recipientFor = (account) => required ? recipient2 || "" : hostRecipient || custom.evm || account;
8602
- 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 };
8603
- }
8604
-
8605
- // src/core/checksum.ts
8606
- var RC = [
8607
- 0x0000000000000001n,
8608
- 0x0000000000008082n,
8609
- 0x800000000000808an,
8610
- 0x8000000080008000n,
8611
- 0x000000000000808bn,
8612
- 0x0000000080000001n,
8613
- 0x8000000080008081n,
8614
- 0x8000000000008009n,
8615
- 0x000000000000008an,
8616
- 0x0000000000000088n,
8617
- 0x0000000080008009n,
8618
- 0x000000008000000an,
8619
- 0x000000008000808bn,
8620
- 0x800000000000008bn,
8621
- 0x8000000000008089n,
8622
- 0x8000000000008003n,
8623
- 0x8000000000008002n,
8624
- 0x8000000000000080n,
8625
- 0x000000000000800an,
8626
- 0x800000008000000an,
8627
- 0x8000000080008081n,
8628
- 0x8000000000008080n,
8629
- 0x0000000080000001n,
8630
- 0x8000000080008008n
8631
- ];
8632
- 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];
8633
- var MASK = (1n << 64n) - 1n;
8634
- var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
8635
- function keccakF(s) {
8636
- for (let round = 0; round < 24; round++) {
8637
- const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
8638
- for (let x = 0; x < 5; x++) {
8639
- const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
8640
- for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
10221
+ if (wallet.address && !name) {
10222
+ selectAddress("");
10223
+ return;
8641
10224
  }
8642
- const b = new Array(25);
8643
- 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]);
8644
- 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];
8645
- s[0] = s[0] ^ RC[round];
8646
- }
8647
- }
8648
- function keccak256Hex(bytes) {
8649
- const rate = 136;
8650
- const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
8651
- padded.set(bytes);
8652
- padded[bytes.length] = padded[bytes.length] ^ 1;
8653
- padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
8654
- const s = new Array(25).fill(0n);
8655
- for (let off = 0; off < padded.length; off += rate) {
8656
- for (let i = 0; i < rate / 8; i++) {
8657
- let lane = 0n;
8658
- for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
8659
- s[i] = s[i] ^ lane;
10225
+ if (!name && wallet.wallets.length !== 1) {
10226
+ setOpen(true);
10227
+ return;
8660
10228
  }
8661
- keccakF(s);
8662
- }
8663
- let out = "";
8664
- 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");
8665
- return out;
8666
- }
8667
- function toChecksumAddress(address) {
8668
- const lower2 = address.slice(2).toLowerCase();
8669
- const hash2 = keccak256Hex(new TextEncoder().encode(lower2));
8670
- let out = "0x";
8671
- for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower2[i].toUpperCase() : lower2[i];
8672
- return out;
8673
- }
8674
- function hasValidChecksum(address) {
8675
- if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
8676
- const body = address.slice(2);
8677
- if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
8678
- return toChecksumAddress(address) === address;
10229
+ const address = await wallet.connect(name);
10230
+ if (typeof address === "string") selectAddress("");
10231
+ else setOpen(true);
10232
+ };
10233
+ const recipientFor = (account) => required ? recipient2 || "" : hostRecipient || custom.evm || account;
10234
+ 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 };
8679
10235
  }
8680
10236
  function ArrowLeft() {
8681
10237
  return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
@@ -8771,34 +10327,64 @@ function SheetFrame(props) {
8771
10327
  document.addEventListener("keydown", onKey, true);
8772
10328
  return () => document.removeEventListener("keydown", onKey, true);
8773
10329
  }, []);
8774
- return /* @__PURE__ */ jsxRuntime.jsxs(
8775
- "div",
8776
- {
8777
- className: "sg-ws",
8778
- "data-wide": props.wide || void 0,
8779
- role: "dialog",
8780
- "aria-modal": "true",
8781
- "aria-label": props.label,
8782
- ref: sheetRef,
8783
- tabIndex: -1,
8784
- style: props.minHeight ? { minHeight: props.minHeight } : void 0,
8785
- children: [
8786
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-top", children: [
8787
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-head", children: [
8788
- /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-ws-back", onClick: () => closeRef.current(), children: [
8789
- /* @__PURE__ */ jsxRuntime.jsx(ArrowLeft, {}),
8790
- props.backLabel ?? "Back to Exchange"
10330
+ return (
10331
+ // biome-ignore lint/a11y/noStaticElementInteractions: role is "region" or "dialog" — both carry semantics; the Tab trap only runs for the modal (dialog) case.
10332
+ // biome-ignore lint/a11y/useAriaPropsSupportedByRole: aria-modal is set only when role is "dialog" (asRegion is false); a region never receives it.
10333
+ /* @__PURE__ */ jsxRuntime.jsxs(
10334
+ "div",
10335
+ {
10336
+ className: "sg-ws",
10337
+ "data-wide": props.wide || void 0,
10338
+ role: props.asRegion ? "region" : "dialog",
10339
+ "aria-modal": props.asRegion ? void 0 : "true",
10340
+ "aria-label": props.label,
10341
+ ref: sheetRef,
10342
+ tabIndex: -1,
10343
+ onKeyDown: props.trapFocus ? (event) => {
10344
+ if (event.key !== "Tab") return;
10345
+ const root = sheetRef.current;
10346
+ if (!root) return;
10347
+ const focusable = Array.from(
10348
+ root.querySelectorAll('a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')
10349
+ ).filter((el) => el.offsetParent !== null || el === document.activeElement);
10350
+ if (focusable.length === 0) {
10351
+ event.preventDefault();
10352
+ root.focus();
10353
+ return;
10354
+ }
10355
+ const first = focusable[0];
10356
+ const last = focusable[focusable.length - 1];
10357
+ const active = document.activeElement;
10358
+ if (event.shiftKey && (active === first || active === root)) {
10359
+ event.preventDefault();
10360
+ last.focus();
10361
+ } else if (!event.shiftKey && active === last) {
10362
+ event.preventDefault();
10363
+ first.focus();
10364
+ }
10365
+ } : void 0,
10366
+ style: props.minHeight ? { minHeight: props.minHeight } : void 0,
10367
+ children: [
10368
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-top", children: [
10369
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-head", children: [
10370
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-ws-back", onClick: () => closeRef.current(), children: [
10371
+ /* @__PURE__ */ jsxRuntime.jsx(ArrowLeft, {}),
10372
+ props.backLabel ?? "Back to Exchange"
10373
+ ] }),
10374
+ props.wide || props.hideClose ? null : /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-ws-close", onClick: () => closeRef.current(), "aria-label": `Close ${props.label.toLowerCase()}`, children: /* @__PURE__ */ jsxRuntime.jsx(CloseX, {}) })
8791
10375
  ] }),
8792
- props.wide ? null : /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-ws-close", onClick: () => closeRef.current(), "aria-label": `Close ${props.label.toLowerCase()}`, children: /* @__PURE__ */ jsxRuntime.jsx(CloseX, {}) })
10376
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-main", children: [
10377
+ props.titleAddon ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-titlerow", children: [
10378
+ /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "sg-ws-title", id: titleId, children: props.title }),
10379
+ props.titleAddon
10380
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "sg-ws-title", id: titleId, children: props.title }),
10381
+ props.children
10382
+ ] })
8793
10383
  ] }),
8794
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ws-main", children: [
8795
- /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "sg-ws-title", id: titleId, children: props.title }),
8796
- props.children
8797
- ] })
8798
- ] }),
8799
- props.footer ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-ws-foot", children: props.footer }) : null
8800
- ]
8801
- }
10384
+ props.footer ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-ws-foot", children: props.footer }) : null
10385
+ ]
10386
+ }
10387
+ )
8802
10388
  );
8803
10389
  }
8804
10390
  function WalletChip(props) {
@@ -9357,7 +10943,7 @@ function IdentityLine(props) {
9357
10943
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-link-id", children: [
9358
10944
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-icon", children: /* @__PURE__ */ jsxRuntime.jsx(WalletGlyph, {}) }),
9359
10945
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-link-id-text", children: [
9360
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-primary", children: props.account ? shortAddress2(props.account) : "ZeroDelta Link" }),
10946
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-primary", children: props.account ? shortAddress3(props.account) : "ZeroDelta Link" }),
9361
10947
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-secondary", children: props.email ? props.email : props.account ? "Connected wallet" : "Connect your wallet to continue" })
9362
10948
  ] }),
9363
10949
  props.account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }) : null
@@ -9504,9 +11090,9 @@ function PaymentIsland(props) {
9504
11090
  const optionStates = react.useMemo(() => {
9505
11091
  const map = {};
9506
11092
  for (const a of annotated) {
9507
- const key = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
11093
+ const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
9508
11094
  if (!a.balance || holdings.loading) {
9509
- map[key] = { disabled: false, reason: "checking" };
11095
+ map[key2] = { disabled: false, reason: "checking" };
9510
11096
  continue;
9511
11097
  }
9512
11098
  let zero = false;
@@ -9515,9 +11101,9 @@ function PaymentIsland(props) {
9515
11101
  } catch {
9516
11102
  zero = false;
9517
11103
  }
9518
- if (zero) map[key] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
9519
- 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}` };
9520
- else map[key] = { disabled: false };
11104
+ if (zero) map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
11105
+ 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}` };
11106
+ else map[key2] = { disabled: false };
9521
11107
  }
9522
11108
  return map;
9523
11109
  }, [annotated, holdings.loading]);
@@ -9557,19 +11143,19 @@ function PaymentIsland(props) {
9557
11143
  if (!catalogue?.ready) return void 0;
9558
11144
  const states2 = {};
9559
11145
  for (const token of catalogue.tokens) {
9560
- const key = balanceKey(Number(token.chainId), token.address);
11146
+ const key2 = balanceKey(Number(token.chainId), token.address);
9561
11147
  const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
9562
11148
  if (measured) {
9563
- states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
11149
+ states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
9564
11150
  continue;
9565
11151
  }
9566
11152
  const verdict = destinationAvailability(token, catalogue, exFromToken);
9567
11153
  if (verdict === "available") {
9568
11154
  const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
9569
- if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
11155
+ if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
9570
11156
  continue;
9571
11157
  }
9572
- states2[key] = {
11158
+ states2[key2] = {
9573
11159
  disabled: true,
9574
11160
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
9575
11161
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
@@ -9582,9 +11168,9 @@ function PaymentIsland(props) {
9582
11168
  const seen = /* @__PURE__ */ new Set();
9583
11169
  const list = [];
9584
11170
  for (const r of visibleRoutes) {
9585
- const key = balanceKey(r.source.chainId, r.source.tokenAddress);
9586
- if (seen.has(key)) continue;
9587
- seen.add(key);
11171
+ const key2 = balanceKey(r.source.chainId, r.source.tokenAddress);
11172
+ if (seen.has(key2)) continue;
11173
+ seen.add(key2);
9588
11174
  const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
9589
11175
  list.push(
9590
11176
  reg ?? {
@@ -9924,7 +11510,7 @@ function PaymentIsland(props) {
9924
11510
  ] }),
9925
11511
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
9926
11512
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
9927
- (flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : ""
11513
+ (flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : ""
9928
11514
  ] }),
9929
11515
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
9930
11516
  ] }),
@@ -10100,6 +11686,7 @@ function PillLauncher(props) {
10100
11686
  const openAs = props.openAs === "drawer" ? "drawer" : "modal";
10101
11687
  const [open, setOpen] = react.useState(!!props.defaultOpen);
10102
11688
  const buttonRef = react.useRef(null);
11689
+ const dialogRef = react.useRef(null);
10103
11690
  const close = () => {
10104
11691
  setOpen(false);
10105
11692
  requestAnimationFrame(() => buttonRef.current?.focus());
@@ -10107,7 +11694,32 @@ function PillLauncher(props) {
10107
11694
  react.useEffect(() => {
10108
11695
  if (!open) return;
10109
11696
  const onKey = (e) => {
10110
- if (e.key === "Escape") close();
11697
+ if (e.key === "Escape") {
11698
+ close();
11699
+ return;
11700
+ }
11701
+ if (e.key !== "Tab") return;
11702
+ const root = dialogRef.current;
11703
+ if (!root) return;
11704
+ const list = Array.from(root.querySelectorAll("a[href],button,input,select,textarea,[tabindex]")).filter(
11705
+ (el) => el.tabIndex >= 0 && !el.hasAttribute("disabled") && el.getClientRects().length > 0
11706
+ );
11707
+ if (list.length === 0) {
11708
+ e.preventDefault();
11709
+ return;
11710
+ }
11711
+ const first = list[0];
11712
+ const last = list[list.length - 1];
11713
+ const idx = list.indexOf(document.activeElement);
11714
+ if (e.shiftKey) {
11715
+ if (idx <= 0) {
11716
+ e.preventDefault();
11717
+ last.focus();
11718
+ }
11719
+ } else if (idx === -1 || idx === list.length - 1) {
11720
+ e.preventDefault();
11721
+ first.focus();
11722
+ }
10111
11723
  };
10112
11724
  document.addEventListener("keydown", onKey);
10113
11725
  return () => document.removeEventListener("keydown", onKey);
@@ -10122,7 +11734,7 @@ function PillLauncher(props) {
10122
11734
  ] }),
10123
11735
  open ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-overlay", "data-sg-overlay": openAs, children: [
10124
11736
  /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-overlay-scrim", tabIndex: -1, "aria-label": "Close", onClick: close }),
10125
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-dialog", role: "dialog", "aria-modal": "true", "aria-label": props.verb, children: props.children(close, openAs) })
11737
+ /* @__PURE__ */ jsxRuntime.jsx("div", { ref: dialogRef, className: "sg-dialog", role: "dialog", "aria-modal": "true", "aria-label": props.verb, children: props.children(close, openAs) })
10126
11738
  ] }) : null
10127
11739
  ] });
10128
11740
  }
@@ -10237,9 +11849,9 @@ function PayCard(props) {
10237
11849
  const optionStates = react.useMemo(() => {
10238
11850
  const map = {};
10239
11851
  for (const a of annotated) {
10240
- const key = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
11852
+ const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
10241
11853
  if (!a.balance || holdings.loading) {
10242
- map[key] = { disabled: false, reason: "checking" };
11854
+ map[key2] = { disabled: false, reason: "checking" };
10243
11855
  continue;
10244
11856
  }
10245
11857
  let zero = false;
@@ -10249,23 +11861,23 @@ function PayCard(props) {
10249
11861
  zero = false;
10250
11862
  }
10251
11863
  if (zero) {
10252
- map[key] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
11864
+ map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
10253
11865
  } else if (a.affordable === false) {
10254
- map[key] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
11866
+ map[key2] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
10255
11867
  } else {
10256
- map[key] = { disabled: false };
11868
+ map[key2] = { disabled: false };
10257
11869
  }
10258
11870
  }
10259
11871
  for (const o of unquoted) {
10260
- const key = balanceKey(o.chainId, o.address);
10261
- if (map[key]) continue;
11872
+ const key2 = balanceKey(o.chainId, o.address);
11873
+ if (map[key2]) continue;
10262
11874
  let zero = false;
10263
11875
  try {
10264
- zero = BigInt(listBalances[key]?.raw ?? "x") === 0n;
11876
+ zero = BigInt(listBalances[key2]?.raw ?? "x") === 0n;
10265
11877
  } catch {
10266
11878
  zero = false;
10267
11879
  }
10268
- map[key] = zero ? { disabled: true, reason: "no-balance", hint: "No balance on this chain" } : { disabled: false };
11880
+ map[key2] = zero ? { disabled: true, reason: "no-balance", hint: "No balance on this chain" } : { disabled: false };
10269
11881
  }
10270
11882
  return map;
10271
11883
  }, [annotated, holdings.loading, unquoted, listBalances]);
@@ -10279,9 +11891,9 @@ function PayCard(props) {
10279
11891
  const seen = /* @__PURE__ */ new Set();
10280
11892
  const list = [];
10281
11893
  const push = (chainId, address, fallback) => {
10282
- const key = balanceKey(chainId, address);
10283
- if (seen.has(key)) return;
10284
- seen.add(key);
11894
+ const key2 = balanceKey(chainId, address);
11895
+ if (seen.has(key2)) return;
11896
+ seen.add(key2);
10285
11897
  list.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
10286
11898
  };
10287
11899
  for (const r of visibleRoutes) {
@@ -10355,13 +11967,13 @@ function PayCard(props) {
10355
11967
  const option = unquoted.find((o) => o.chainId === pick.chainId && o.symbolKey === symbolKey(pick.symbol));
10356
11968
  closeSelector();
10357
11969
  if (!option || !wallet.account) return;
10358
- const key = balanceKey(option.chainId, option.address);
10359
- setPricing(key);
11970
+ const key2 = balanceKey(option.chainId, option.address);
11971
+ setPricing(key2);
10360
11972
  userPicked.current = true;
10361
11973
  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(() => {
10362
- setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key]));
11974
+ setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key2]));
10363
11975
  setPickError(`${option.ticker || option.symbol} on ${option.chainName} cannot settle this payment right now. Pick another way to pay.`);
10364
- }).finally(() => setPricing((cur) => cur === key ? null : cur));
11976
+ }).finally(() => setPricing((cur) => cur === key2 ? null : cur));
10365
11977
  };
10366
11978
  const parked = !isLiveMethod(method);
10367
11979
  const submitting = flow.status === "submitting";
@@ -10394,7 +12006,7 @@ function PayCard(props) {
10394
12006
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-wallet", "data-connected": "true", children: [
10395
12007
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
10396
12008
  " ",
10397
- shortAddress2(wallet.account)
12009
+ shortAddress3(wallet.account)
10398
12010
  ] })
10399
12011
  ] }) : /* @__PURE__ */ jsxRuntime.jsx("span", {});
10400
12012
  const nativeWei = sel ? routeNativeValue(sel) : 0n;
@@ -10434,7 +12046,7 @@ function PayCard(props) {
10434
12046
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
10435
12047
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
10436
12048
  " \xB7 ",
10437
- shortAddress2(props.recipient)
12049
+ shortAddress3(props.recipient)
10438
12050
  ] }),
10439
12051
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
10440
12052
  ] }),
@@ -10602,7 +12214,7 @@ function StableGenieSwap(props) {
10602
12214
  ] }),
10603
12215
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
10604
12216
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
10605
- recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
12217
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
10606
12218
  ] }),
10607
12219
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
10608
12220
  ] }),
@@ -10666,7 +12278,7 @@ function useSolanaSourceFlow(args) {
10666
12278
  const planArgs = react.useRef(null);
10667
12279
  const changedWhileBusy = react.useRef(false);
10668
12280
  const addressed = Boolean(owner && payer && recipient2);
10669
- const key = keyOf(args);
12281
+ const key2 = keyOf(args);
10670
12282
  react.useEffect(() => {
10671
12283
  const id = ++req.current;
10672
12284
  if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
@@ -10700,7 +12312,7 @@ function useSolanaSourceFlow(args) {
10700
12312
  const quoted = await engine.quoteSolanaSource(input);
10701
12313
  const built = await engine.buildSolanaSourcePlan(input, quoted);
10702
12314
  if (id !== req.current) return;
10703
- planKey.current = key;
12315
+ planKey.current = key2;
10704
12316
  planArgs.current = { ...latest.current };
10705
12317
  setPreview(quoted);
10706
12318
  setPlan(built);
@@ -10716,7 +12328,7 @@ function useSolanaSourceFlow(args) {
10716
12328
  }
10717
12329
  }, 350);
10718
12330
  return () => clearTimeout(timer2);
10719
- }, [engine, enabled, key, addressed, nonce]);
12331
+ }, [engine, enabled, key2, addressed, nonce]);
10720
12332
  react.useEffect(() => {
10721
12333
  let alive = true;
10722
12334
  setBalanceRaw(void 0);
@@ -10795,6 +12407,658 @@ function useSolanaSourceFlow(args) {
10795
12407
  }, []);
10796
12408
  return { status, preview, plan, error, balanceRaw, cost, progress, signature, lastTxEntry, sent, addressed, needsPreparation, insufficient, solShort, run, reset };
10797
12409
  }
12410
+ function BackArrow() {
12411
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M19 12H5m6-6-6 6 6 6", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" }) });
12412
+ }
12413
+ function ChevronDown2({ up = false }) {
12414
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", style: up ? { transform: "rotate(180deg)" } : void 0, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m6 9 6 6 6-6", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }) });
12415
+ }
12416
+ function PolicyShield() {
12417
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", "aria-hidden": "true", children: [
12418
+ /* @__PURE__ */ jsxRuntime.jsx(
12419
+ "path",
12420
+ {
12421
+ d: "M17.0089 5.8002V7.3252C17.0089 7.85853 16.7589 8.35853 16.3255 8.66686L7.15885 15.3835C6.56719 15.8169 5.75885 15.8169 5.17552 15.3752L3.97552 14.4752C3.43385 14.0669 2.99219 13.1835 2.99219 12.5085V5.8002C2.99219 4.86686 3.70885 3.83353 4.58385 3.50853L9.14219 1.8002C9.61719 1.6252 10.3839 1.6252 10.8589 1.8002L15.4172 3.50853C16.2922 3.83353 17.0089 4.86686 17.0089 5.8002Z",
12422
+ fill: "currentColor"
12423
+ }
12424
+ ),
12425
+ /* @__PURE__ */ jsxRuntime.jsx(
12426
+ "path",
12427
+ {
12428
+ d: "M15.682 10.2829C16.232 9.88287 17.007 10.2745 17.007 10.9579V12.5245C17.007 13.1995 16.5654 14.0745 16.0237 14.4829L11.4654 17.8912C11.0654 18.1829 10.532 18.3329 9.9987 18.3329C9.46537 18.3329 8.93204 18.1829 8.53204 17.8829L7.84037 17.3662C7.39037 17.0329 7.39037 16.3579 7.84871 16.0245L15.682 10.2829Z",
12429
+ fill: "currentColor"
12430
+ }
12431
+ )
12432
+ ] });
12433
+ }
12434
+ function InfoSquare() {
12435
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: [
12436
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "2", y: "2", width: "20", height: "20", rx: "6", fill: "currentColor" }),
12437
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12 10.8v6", stroke: "var(--sg-bg)", strokeWidth: "2.1", strokeLinecap: "round" }),
12438
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "12", cy: "7.7", r: "1.25", fill: "var(--sg-bg)" })
12439
+ ] });
12440
+ }
12441
+ function InfoOutline() {
12442
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: [
12443
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "12", cy: "12", r: "9.2", stroke: "currentColor", strokeWidth: "1.7" }),
12444
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12 11v5.4", stroke: "currentColor", strokeWidth: "1.9", strokeLinecap: "round" }),
12445
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "12", cy: "7.8", r: "1.15", fill: "currentColor" })
12446
+ ] });
12447
+ }
12448
+ var FLAGGED_CATEGORY_HINTS = {
12449
+ "High-risk entity": "An entity associated with elevated financial-crime risk based on available screening data.",
12450
+ "Politically exposed person (PEP)": "A person who holds or has held a prominent public function, including close associates and family members.",
12451
+ "Unknown / unclassified": "The screening provider could not confidently assign the entity to a known risk category.",
12452
+ "Unclassified risk": "The screening provider could not confidently assign the entity to a known risk category."
12453
+ };
12454
+ var POLICY_DETAILS = {
12455
+ "always-blocked": "Cannot be changed or disabled",
12456
+ blocked: "Stops the order",
12457
+ flagged: "Does not automatically block"
12458
+ };
12459
+ function Hint({ id, label: label2, text, hint }) {
12460
+ const tipId = react.useId();
12461
+ const open = hint.open === id;
12462
+ const ptr = react.useRef("");
12463
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
12464
+ /* @__PURE__ */ jsxRuntime.jsx(
12465
+ "button",
12466
+ {
12467
+ type: "button",
12468
+ className: "sg-cd-hint",
12469
+ "data-sg-hint": "",
12470
+ "aria-label": `About ${label2}`,
12471
+ "aria-expanded": open,
12472
+ "aria-describedby": open ? tipId : void 0,
12473
+ onPointerEnter: (e) => {
12474
+ ptr.current = e.pointerType;
12475
+ if (e.pointerType === "mouse") hint.setOpen(id);
12476
+ },
12477
+ onPointerLeave: (e) => {
12478
+ if (e.pointerType === "mouse") hint.setOpen(null);
12479
+ },
12480
+ onClick: () => {
12481
+ hint.setOpen(ptr.current === "mouse" ? id : open ? null : id);
12482
+ ptr.current = "";
12483
+ },
12484
+ onBlur: () => {
12485
+ ptr.current = "";
12486
+ },
12487
+ children: /* @__PURE__ */ jsxRuntime.jsx(InfoOutline, {})
12488
+ }
12489
+ ),
12490
+ open ? /* @__PURE__ */ jsxRuntime.jsx("span", { role: "tooltip", id: tipId, className: "sg-cd-tip", children: text }) : null
12491
+ ] });
12492
+ }
12493
+ function CheckRow2({ check: check2, hideNote }) {
12494
+ const label2 = check2.id === "risk" ? check2.ok ? "Risk screening passed" : "Risk screening failed" : check2.label;
12495
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: "sg-cd-check", "data-ok": check2.ok, children: [
12496
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cd-check-line", children: [
12497
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-mark", "data-ok": check2.ok, children: check2.ok ? /* @__PURE__ */ jsxRuntime.jsx(Tick, { size: 12 }) : /* @__PURE__ */ jsxRuntime.jsx(Cross, { size: 12 }) }),
12498
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-label", children: label2 }),
12499
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: check2.ok ? " \u2014 passed" : " \u2014 failed" })
12500
+ ] }),
12501
+ check2.note && !hideNote ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-note", children: check2.note }) : null,
12502
+ check2.reasons.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-reason", children: humanizeComplianceReason(reason) }, reason))
12503
+ ] });
12504
+ }
12505
+ function Fact2({ label: label2, value, title, mono = false }) {
12506
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-fact", children: [
12507
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: label2 }),
12508
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { title, className: mono ? "sg-mono" : void 0, children: value })
12509
+ ] });
12510
+ }
12511
+ function QuoteChecks2(props) {
12512
+ const { compliance, cv, checks } = props;
12513
+ const allPassed = cv.tone === "ok" && checks.length > 0 && checks.every((c) => c.ok);
12514
+ const summary = allPassed ? "All checks passed" : cv.label;
12515
+ const orphans = unattributedComplianceReasons(compliance, cv);
12516
+ const wallets = distinctScreenedWallets(compliance);
12517
+ const jurisdiction = formatJurisdiction(compliance?.sourceJurisdiction, compliance?.sourceCountry);
12518
+ const hasDetails = Boolean(jurisdiction || wallets.length || compliance?.checkId);
12519
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-panel", children: [
12520
+ /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cd-card", children: [
12521
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-summary", children: [
12522
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cd-summary-head", "data-tone": cv.tone, children: [
12523
+ cv.tone === "blocked" || cv.tone === "warn" ? /* @__PURE__ */ jsxRuntime.jsx(CloseCircle, {}) : cv.tone === "neutral" ? /* @__PURE__ */ jsxRuntime.jsx(PendingCircle, {}) : /* @__PURE__ */ jsxRuntime.jsx(TickCircle, {}),
12524
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-summary-title", children: summary })
12525
+ ] }),
12526
+ checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cd-summary-sub", children: [
12527
+ checks.length,
12528
+ " check",
12529
+ checks.length === 1 ? " was" : "s were",
12530
+ " completed for this quote"
12531
+ ] }) : (
12532
+ // No decision was issued. Listing the controls here would be ticks for a verdict nobody gave,
12533
+ // and an unconfigured gate is not a set of passed checks.
12534
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-summary-sub", children: "The gateway returned no compliance decision for this quote, so there is nothing to show. It is not a failed check." })
12535
+ )
12536
+ ] }),
12537
+ checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cd-checks", children: checks.map((check2) => (
12538
+ // The Figma row carries no sub-line: with ONE screened wallet the note would repeat the
12539
+ // address Quote details names two cards down. Any other note (a count of wallets) stays.
12540
+ /* @__PURE__ */ jsxRuntime.jsx(CheckRow2, { check: check2, hideNote: check2.id === "screening" && wallets.length === 1 && hasDetails }, check2.id)
12541
+ )) }) : null,
12542
+ orphans.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cd-orphans", children: orphans.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: humanizeComplianceReason(reason) }, reason)) }) : null,
12543
+ props.direct && checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-scope", children: DIRECT_SCOPE_NOTE }) : null
12544
+ ] }),
12545
+ compliance?.flaggedCategories?.length ? /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cd-card", children: [
12546
+ /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "sg-cd-card-title", children: "Flagged, not blocking" }),
12547
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-flags", children: compliance.flaggedCategories.map(categoryLabel).join(" \xB7 ") }),
12548
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-scope", children: "The policy records these and still allows the payment. They do not stop settlement." })
12549
+ ] }) : null,
12550
+ hasDetails ? /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cd-card", children: [
12551
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-card-head", children: [
12552
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-card-glyph", children: /* @__PURE__ */ jsxRuntime.jsx(InfoSquare, {}) }),
12553
+ /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "sg-cd-card-title", children: "Quote details" })
12554
+ ] }),
12555
+ /* @__PURE__ */ jsxRuntime.jsxs("dl", { className: "sg-cd-facts", children: [
12556
+ jurisdiction ? /* @__PURE__ */ jsxRuntime.jsx(Fact2, { label: "Jurisdiction", value: jurisdiction }) : null,
12557
+ wallets.map((w, i) => /* @__PURE__ */ jsxRuntime.jsx(Fact2, { label: wallets.length > 1 ? i === 0 ? "Payer" : "Recipient" : "Wallet", value: shortAddr(w), title: w, mono: false }, w)),
12558
+ compliance?.checkId ? /* @__PURE__ */ jsxRuntime.jsx(Fact2, { label: "Check ID", value: compliance.checkId, mono: true }) : null
12559
+ ] })
12560
+ ] }) : null
12561
+ ] });
12562
+ }
12563
+ function riskRuleCount() {
12564
+ return SCREENING_BUCKETS.reduce((total, bucket) => total + bucket.categories.length, 0);
12565
+ }
12566
+ function appliedPolicies(compliance) {
12567
+ const names = compliance?.appliedPolicyNames ?? [];
12568
+ const legislation = compliance?.appliedLegislation ?? [];
12569
+ const applied = Boolean(compliance?.decision || compliance?.policyVersion?.trim()) || names.length > 0;
12570
+ if (!applied) return [];
12571
+ const ids = compliance?.appliedPolicyIds ?? [];
12572
+ const summary = `${riskRuleCount()} risk rules`;
12573
+ const statements = legislation.map((name, i) => ({ id: `legislation-${i}-${name}`, name, summary: null, buckets: null }));
12574
+ if (names.length === 0) return [{ id: "zd-screening-matrix", name: "Transaction screening", summary, buckets: SCREENING_BUCKETS }, ...statements];
12575
+ if (names.length === 1) return [{ id: ids[0] ?? names[0], name: names[0], summary, buckets: SCREENING_BUCKETS }, ...statements];
12576
+ return [
12577
+ ...names.map((name, i) => ({ id: ids[i] ?? `${name}-${i}`, name, summary: null, buckets: null })),
12578
+ ...statements,
12579
+ { id: "zd-screening-matrix", name: "Transaction screening", summary, buckets: SCREENING_BUCKETS }
12580
+ ];
12581
+ }
12582
+ function PolicyBuckets({ policyId, layout, hint }) {
12583
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: SCREENING_BUCKETS.map((bucket) => {
12584
+ const detail = POLICY_DETAILS[bucket.outcome];
12585
+ const bucketHint = `${policyId}:${bucket.outcome}`;
12586
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-bucket", "data-outcome": bucket.outcome, children: [
12587
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-bucket-head", children: [
12588
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-bucket-title", children: bucket.title }),
12589
+ layout === "side" ? /* @__PURE__ */ jsxRuntime.jsx(Hint, { id: bucketHint, label: bucket.title, text: detail, hint }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-bucket-detail", children: detail })
12590
+ ] }),
12591
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cd-cats", children: bucket.categories.map((category) => {
12592
+ const text = bucket.outcome === "flagged" ? FLAGGED_CATEGORY_HINTS[category] : void 0;
12593
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { children: [
12594
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-dot", "aria-hidden": "true" }),
12595
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: category }),
12596
+ text ? /* @__PURE__ */ jsxRuntime.jsx(Hint, { id: `${policyId}:${category}`, label: category, text, hint }) : null
12597
+ ] }, category);
12598
+ }) })
12599
+ ] }, bucket.outcome);
12600
+ }) });
12601
+ }
12602
+ function PolicyRow({
12603
+ policy,
12604
+ open,
12605
+ onToggle,
12606
+ layout,
12607
+ hint,
12608
+ policyVersion
12609
+ }) {
12610
+ const bodyId = react.useId();
12611
+ const head = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
12612
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-policy-mark", children: /* @__PURE__ */ jsxRuntime.jsx(PolicyShield, {}) }),
12613
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cd-policy-text", children: [
12614
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-policy-name", children: policy.name }),
12615
+ policy.summary ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-policy-sub", children: policy.summary }) : null
12616
+ ] }),
12617
+ policy.buckets ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-policy-chev", children: /* @__PURE__ */ jsxRuntime.jsx(ChevronDown2, { up: open }) }) : null
12618
+ ] });
12619
+ if (!policy.buckets) return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cd-policy", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cd-policy-head", "data-static": "", children: head }) });
12620
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-policy", "data-open": open, children: [
12621
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cd-policy-head", "aria-expanded": open, "aria-controls": bodyId, onClick: onToggle, children: head }),
12622
+ open ? /* @__PURE__ */ jsxRuntime.jsxs("div", { id: bodyId, className: "sg-cd-policy-body", children: [
12623
+ /* @__PURE__ */ jsxRuntime.jsx(PolicyBuckets, { policyId: policy.id, layout, hint }),
12624
+ policyVersion ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "sg-cd-policy-version sg-mono", children: [
12625
+ "Policy version ",
12626
+ policyVersion
12627
+ ] }) : null
12628
+ ] }) : null
12629
+ ] });
12630
+ }
12631
+ function AppliedPolicies({ policies, layout, hint, policyVersion }) {
12632
+ const [openId, setOpenId] = react.useState(() => policies.find((p) => p.buckets)?.id ?? null);
12633
+ if (policies.length === 0) {
12634
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cd-panel", children: /* @__PURE__ */ jsxRuntime.jsx("section", { className: "sg-cd-card", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-summary", children: [
12635
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cd-summary-head", "data-tone": "neutral", children: [
12636
+ /* @__PURE__ */ jsxRuntime.jsx(PendingCircle, {}),
12637
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-summary-title", children: "No policy decision was returned" })
12638
+ ] }),
12639
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-summary-sub", children: "There is no applied policy to show for this quote. It is not a failed check." })
12640
+ ] }) }) });
12641
+ }
12642
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cd-panel sg-cd-policies", children: policies.map((policy) => /* @__PURE__ */ jsxRuntime.jsx(
12643
+ PolicyRow,
12644
+ {
12645
+ policy,
12646
+ open: openId === policy.id,
12647
+ onToggle: () => setOpenId(openId === policy.id ? null : policy.id),
12648
+ layout,
12649
+ hint,
12650
+ policyVersion: openId === policy.id ? policyVersion : void 0
12651
+ },
12652
+ policy.id
12653
+ )) });
12654
+ }
12655
+ function ComplianceDetails(props) {
12656
+ const [tab, setTab] = react.useState("checks");
12657
+ const [hintOpen, setHintOpen] = react.useState(null);
12658
+ const rootRef = react.useRef(null);
12659
+ const ids = react.useId();
12660
+ const compliance = props.compliance ?? null;
12661
+ const cv = complianceView(compliance, props.hasQuote ?? true);
12662
+ const allChecks = complianceChecks(compliance, cv);
12663
+ const checks = props.direct ? allChecks.filter((c) => DIRECT_CHECK_IDS.includes(c.id)) : allChecks;
12664
+ const policies = appliedPolicies(compliance);
12665
+ const policyVersion = compliance?.policyVersion?.trim() || void 0;
12666
+ const onBackRef = react.useRef(props.onBack);
12667
+ onBackRef.current = props.onBack;
12668
+ const hintRef = react.useRef(hintOpen);
12669
+ hintRef.current = hintOpen;
12670
+ react.useEffect(() => {
12671
+ rootRef.current?.focus({ preventScroll: true });
12672
+ const onKey = (e) => {
12673
+ if (e.key !== "Escape") return;
12674
+ e.stopPropagation();
12675
+ if (hintRef.current) setHintOpen(null);
12676
+ else onBackRef.current();
12677
+ };
12678
+ const onPointer = (e) => {
12679
+ if (hintRef.current && !e.target?.closest?.("[data-sg-hint]")) setHintOpen(null);
12680
+ };
12681
+ document.addEventListener("keydown", onKey, true);
12682
+ document.addEventListener("pointerdown", onPointer, true);
12683
+ return () => {
12684
+ document.removeEventListener("keydown", onKey, true);
12685
+ document.removeEventListener("pointerdown", onPointer, true);
12686
+ };
12687
+ }, []);
12688
+ const tabKeys = (e) => {
12689
+ const order = ["checks", "policy"];
12690
+ let next = null;
12691
+ if (e.key === "Home") next = order[0];
12692
+ else if (e.key === "End") next = order[order.length - 1];
12693
+ else if (e.key === "ArrowRight") next = order[(order.indexOf(tab) + 1) % order.length];
12694
+ else if (e.key === "ArrowLeft") next = order[(order.indexOf(tab) - 1 + order.length) % order.length];
12695
+ if (next === null) return;
12696
+ e.preventDefault();
12697
+ setTab(next);
12698
+ document.getElementById(`${ids}-tab-${next}`)?.focus();
12699
+ };
12700
+ const hint = { open: hintOpen, setOpen: setHintOpen };
12701
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "sg-cd", "data-layout": props.layout, "aria-label": "Compliance details", ref: rootRef, tabIndex: -1, children: [
12702
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-cd-back", onClick: props.onBack, children: [
12703
+ /* @__PURE__ */ jsxRuntime.jsx(BackArrow, {}),
12704
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "Back to Exchange" })
12705
+ ] }),
12706
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "sg-cd-title", children: "Compliance details" }),
12707
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cd-tabs", role: "tablist", "aria-label": "Compliance details sections", children: [
12708
+ /* @__PURE__ */ jsxRuntime.jsx(
12709
+ "button",
12710
+ {
12711
+ type: "button",
12712
+ role: "tab",
12713
+ id: `${ids}-tab-checks`,
12714
+ "aria-selected": tab === "checks",
12715
+ "aria-controls": `${ids}-panel`,
12716
+ tabIndex: tab === "checks" ? 0 : -1,
12717
+ "data-active": tab === "checks",
12718
+ className: "sg-cd-tab",
12719
+ onClick: () => setTab("checks"),
12720
+ onKeyDown: tabKeys,
12721
+ children: "Quote checks"
12722
+ }
12723
+ ),
12724
+ /* @__PURE__ */ jsxRuntime.jsxs(
12725
+ "button",
12726
+ {
12727
+ type: "button",
12728
+ role: "tab",
12729
+ id: `${ids}-tab-policy`,
12730
+ "aria-selected": tab === "policy",
12731
+ "aria-controls": `${ids}-panel`,
12732
+ tabIndex: tab === "policy" ? 0 : -1,
12733
+ "data-active": tab === "policy",
12734
+ className: "sg-cd-tab",
12735
+ onClick: () => setTab("policy"),
12736
+ onKeyDown: tabKeys,
12737
+ children: [
12738
+ "Applied policies",
12739
+ policies.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-tab-count", children: policies.length }) : null
12740
+ ]
12741
+ }
12742
+ )
12743
+ ] }),
12744
+ /* @__PURE__ */ jsxRuntime.jsx("div", { id: `${ids}-panel`, role: "tabpanel", "aria-labelledby": `${ids}-tab-${tab}`, children: tab === "checks" ? /* @__PURE__ */ jsxRuntime.jsx(QuoteChecks2, { compliance, cv, checks, direct: !!props.direct }) : /* @__PURE__ */ jsxRuntime.jsx(AppliedPolicies, { policies, layout: props.layout, hint, policyVersion }) })
12745
+ ] });
12746
+ }
12747
+ function RefreshGlyph({ spinning }) {
12748
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { className: spinning ? "sg-cq-spin" : void 0, width: "16", height: "16", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M4.22639 4.22667C4.71306 3.74 5.28639 3.35333 5.91972 3.08667C6.57972 2.80667 7.27306 2.66667 7.99306 2.66667V1.33333C7.09306 1.33333 6.21972 1.50667 5.39972 1.86C4.60639 2.19333 3.89306 2.68 3.27972 3.28667C2.66639 3.9 2.18639 4.61333 1.85306 5.40667C1.50639 6.22667 1.32639 7.1 1.32639 8C1.32639 8.9 1.49972 9.77333 1.85306 10.5933C2.18639 11.3867 2.66639 12.1 3.27972 12.7133C3.39306 12.8267 3.51306 12.9267 3.62639 13.0333L1.99306 14.6667H5.99306V10.6667L4.57306 12.0867C4.45306 11.9867 4.33306 11.88 4.22639 11.7667C3.7398 11.2804 3.3506 10.7057 3.07972 10.0733C2.79972 9.41333 2.65972 8.72 2.65972 8C2.65972 7.28 2.79972 6.58 3.07972 5.92667C3.34639 5.29333 3.73306 4.72 4.22639 4.23333V4.22667ZM12.7131 3.28667C12.5997 3.17333 12.4797 3.07333 12.3664 2.96667L13.9997 1.33333H9.99972V5.33333L11.4197 3.91333C11.5397 4.01333 11.6597 4.12 11.7664 4.23333C12.2597 4.72667 12.6397 5.29333 12.9131 5.92667C13.1931 6.58667 13.3331 7.28 13.3331 8C13.3331 8.72 13.1931 9.42 12.9131 10.0733C12.6464 10.7067 12.2597 11.28 11.7664 11.7667C11.2797 12.2533 10.7064 12.64 10.0731 12.9067C9.41306 13.1867 8.71972 13.3267 7.99972 13.3267V14.66C8.89972 14.66 9.77306 14.4867 10.5931 14.1333C11.3864 13.8 12.0997 13.3133 12.7131 12.7067C13.3264 12.0933 13.8064 11.38 14.1397 10.5867C14.4864 9.76667 14.6664 8.89333 14.6664 7.99333C14.6664 7.09333 14.4931 6.22 14.1397 5.4C13.8068 4.60714 13.3222 3.88698 12.7131 3.28V3.28667Z" }) });
12749
+ }
12750
+ function SliderGrip() {
12751
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "28", height: "12", viewBox: "0 0 28 12", fill: "none", "aria-hidden": "true", children: [
12752
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "0.5", y: "0.5", width: "27", height: "11", rx: "5.5", fill: "rgba(255,255,255,0.3)" }),
12753
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M11 3l3 3-3 3M15 3l3 3-3 3", stroke: "#fff", strokeWidth: "1.1", strokeLinecap: "round", strokeLinejoin: "round" })
12754
+ ] });
12755
+ }
12756
+ function WalletAddGlyph() {
12757
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", children: [
12758
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M9.95 1.84167L7.94167 6.51667H5.93333C5.6 6.51667 5.275 6.54167 4.95833 6.60833L5.79167 4.60833L5.825 4.53333L5.875 4.4C5.9 4.34167 5.91667 4.29167 5.94167 4.25C6.90833 2.00833 7.99167 1.30833 9.95 1.84167Z" }),
12759
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M15.6083 6.74167L15.5917 6.73333C15.0917 6.59167 14.5833 6.51667 14.0667 6.51667H8.85L10.725 2.15833L10.75 2.1C10.8667 2.14167 10.9917 2.2 11.1167 2.24167L12.9583 3.01667C13.9833 3.44167 14.7 3.88333 15.1417 4.41667C15.2167 4.51667 15.2833 4.60833 15.35 4.71667C15.425 4.83333 15.4833 4.95 15.5167 5.075C15.55 5.15 15.575 5.21667 15.5917 5.29167C15.7167 5.71667 15.725 6.2 15.6083 6.74167Z" }),
12760
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M15.2417 7.93333C14.8667 7.825 14.475 7.76667 14.0667 7.76667H5.93333C5.36667 7.76667 4.83333 7.875 4.33333 8.09167C2.88333 8.71667 1.86667 10.1583 1.86667 11.8333V13.4583C1.86667 13.6583 1.88333 13.85 1.90833 14.05C2.09167 16.7 3.50833 18.1167 6.15833 18.2917C6.35 18.3167 6.54167 18.3333 6.75 18.3333H13.25C16.3333 18.3333 17.9583 16.8667 18.1167 13.95C18.125 13.7917 18.1333 13.625 18.1333 13.4583V11.8333C18.1333 9.99167 16.9083 8.44167 15.2417 7.93333ZM12.0833 13.4917H10.625V15C10.625 15.3417 10.3417 15.625 10 15.625C9.65833 15.625 9.375 15.3417 9.375 15V13.4917H7.91667C7.575 13.4917 7.29167 13.2167 7.29167 12.8667C7.29167 12.525 7.575 12.2417 7.91667 12.2417H9.375V10.8333C9.375 10.4917 9.65833 10.2083 10 10.2083C10.3417 10.2083 10.625 10.4917 10.625 10.8333V12.2417H12.0833C12.425 12.2417 12.7083 12.525 12.7083 12.8667C12.7083 13.2167 12.425 13.4917 12.0833 13.4917Z" })
12761
+ ] });
12762
+ }
12763
+ function ChevronGlyph2({ up }) {
12764
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": "true", style: up ? { transform: "scaleY(-1)" } : void 0, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M2.5 4.5 6 8l3.5-3.5", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" }) });
12765
+ }
12766
+ function ArrowGlyph2() {
12767
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { className: "sg-cq-arrow", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3.5 8h9M9 4.5 12.5 8 9 11.5", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" }) });
12768
+ }
12769
+ function InfoGlyph() {
12770
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": "true", children: [
12771
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "7", cy: "7", r: "5.6", stroke: "currentColor", strokeWidth: "1" }),
12772
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M7 6.2v3.4", stroke: "currentColor", strokeWidth: "1.1", strokeLinecap: "round" }),
12773
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "7", cy: "4.5", r: ".7", fill: "currentColor" })
12774
+ ] });
12775
+ }
12776
+ function unavailableCopy(status) {
12777
+ return status === "unsigned-cross-chain-off" ? "Cross-chain orders are not enabled yet" : status === "router-unresolved" || status === "escrow-unresolved" ? "Not available on this network yet" : "Not available right now";
12778
+ }
12779
+ function compareFeeLabel(usd2) {
12780
+ if (usd2 === null) return "--";
12781
+ if (!Number.isFinite(usd2) || usd2 <= 0) return "$0.00";
12782
+ if (usd2 >= 0.01) return `$${usd2.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
12783
+ if (usd2 < 1e-6) return "<$0.000001";
12784
+ return `$${usd2.toLocaleString("en-US", { maximumSignificantDigits: 2 })}`;
12785
+ }
12786
+ function logoOf(tokens, hop) {
12787
+ const wanted = hop.address.toLowerCase();
12788
+ return tokens.find((t) => Number(t.chainId) === hop.chainId && String(t.address).toLowerCase() === wanted)?.logoUrl;
12789
+ }
12790
+ var WIDE_SCALE_TRAVEL_PX = 189 * 228 / 130;
12791
+ function thumbWidth(fraction) {
12792
+ return `max(32px, calc((100% - 4px) * ${fraction}))`;
12793
+ }
12794
+ function CompareQuotes(props) {
12795
+ const side = props.layout === "side";
12796
+ const sliderId = react.useId();
12797
+ const options = props.compare?.options ?? [];
12798
+ const selectedId = props.compare?.selectedId ?? null;
12799
+ const selected = options.find((o) => o.id === selectedId && !o.unavailable)?.id ?? options.find((o) => !o.unavailable)?.id ?? null;
12800
+ const picked = options.find((o) => o.id === selectedId && !o.unavailable);
12801
+ const [movedWait, setMovedWait] = react.useState(null);
12802
+ const wait2 = movedWait ?? (picked ? clampWait(picked.estimatedDuration) : proposedWait(options));
12803
+ const [openRoutes, setOpenRoutes] = react.useState(() => /* @__PURE__ */ new Set());
12804
+ const parityState = props.compare?.parity ?? { kind: "unknown" };
12805
+ const extra = props.compare ? extraVsFastest(options, selected) : null;
12806
+ const selectedOption = options.find((o) => o.id === selected);
12807
+ const anySelectable = options.some((o) => !o.unavailable);
12808
+ const moveWait = (sec) => {
12809
+ setMovedWait(sec);
12810
+ const pick = pickForWait(options, sec);
12811
+ if (pick && pick.id !== selected) props.onSelect(pick.id);
12812
+ };
12813
+ const pickCard = (option) => {
12814
+ if (props.onSelect(option.id)) setMovedWait(clampWait(option.estimatedDuration));
12815
+ };
12816
+ const toggleRoute = (id) => setOpenRoutes((prev) => {
12817
+ const next = new Set(prev);
12818
+ if (next.has(id)) next.delete(id);
12819
+ else next.add(id);
12820
+ return next;
12821
+ });
12822
+ const trackRef = react.useRef(null);
12823
+ const listRef = react.useRef(null);
12824
+ const [travel, setTravel] = react.useState(400);
12825
+ react.useLayoutEffect(() => {
12826
+ const el = trackRef.current;
12827
+ if (!el) return;
12828
+ const measure = () => setTravel(el.offsetWidth - 4);
12829
+ measure();
12830
+ if (typeof ResizeObserver === "undefined") return;
12831
+ const ro = new ResizeObserver(measure);
12832
+ ro.observe(el);
12833
+ return () => ro.disconnect();
12834
+ }, [anySelectable]);
12835
+ const scale = react.useMemo(() => waitScaleFor(side ? WIDE_SCALE_TRAVEL_PX : travel), [side, travel]);
12836
+ const pct = waitFraction(wait2, scale) * 100;
12837
+ const shown = react.useMemo(() => visibleOptions(options, wait2, selected), [options, wait2, selected]);
12838
+ const rovingId = shown.find((o) => o.id === selected && !o.unavailable)?.id ?? shown.find((o) => !o.unavailable)?.id ?? null;
12839
+ const refresh = props.onRefresh ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cq-refresh", onClick: props.onRefresh, "aria-label": "Refresh quotes", "aria-busy": props.refreshing || void 0, children: /* @__PURE__ */ jsxRuntime.jsx(RefreshGlyph, { spinning: !!props.refreshing }) }) : void 0;
12840
+ return /* @__PURE__ */ jsxRuntime.jsx(SheetFrame, { label: "Compare quotes", title: "Compare quotes", titleAddon: refresh, hideClose: true, wide: side, asRegion: !props.modal, trapFocus: props.modal, onClose: props.onBack, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq", "data-layout": props.layout, children: [
12841
+ anySelectable ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-wait", "data-testid": "compare-wait", children: [
12842
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-wait-top", children: [
12843
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-wait-row", children: [
12844
+ /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: sliderId, children: "I'm willing to wait" }),
12845
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-testid": "compare-wait-label", children: waitLabel(wait2) })
12846
+ ] }),
12847
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-wait-scale", children: [
12848
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { ref: trackRef, className: "sg-cq-track", children: [
12849
+ /* @__PURE__ */ jsxRuntime.jsx(
12850
+ "input",
12851
+ {
12852
+ id: sliderId,
12853
+ className: "sg-cq-range",
12854
+ type: "range",
12855
+ min: 0,
12856
+ max: WAIT_POSITIONS,
12857
+ step: 1,
12858
+ value: Math.round(pct * WAIT_POSITIONS / 100),
12859
+ "aria-valuetext": waitLabel(wait2),
12860
+ onChange: (e) => moveWait(snapWait(waitFromFraction(Number(e.target.value) / WAIT_POSITIONS, scale))),
12861
+ onKeyDown: (e) => {
12862
+ const dir = e.key === "ArrowRight" || e.key === "ArrowUp" ? 1 : e.key === "ArrowLeft" || e.key === "ArrowDown" ? -1 : 0;
12863
+ if (dir === 0) return;
12864
+ e.preventDefault();
12865
+ moveWait(snapWait(wait2 + dir * WAIT_STEP_SEC));
12866
+ }
12867
+ }
12868
+ ),
12869
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cq-rail", "aria-hidden": "true" }),
12870
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cq-thumb", "aria-hidden": "true", style: { width: thumbWidth(pct / 100) }, children: /* @__PURE__ */ jsxRuntime.jsx(SliderGrip, {}) })
12871
+ ] }),
12872
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-ends", children: [
12873
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "3 min" }),
12874
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "2 h" }),
12875
+ parityState.kind === "at" ? /* @__PURE__ */ jsxRuntime.jsxs(
12876
+ "span",
12877
+ {
12878
+ className: "sg-cq-parity",
12879
+ "data-testid": "compare-parity",
12880
+ style: { left: `clamp(${side ? 60 : 44}px, calc(${thumbWidth(waitFraction(parityState.timeSec, scale))} - 13px), calc(100% - ${side ? 60 : 44}px))` },
12881
+ children: [
12882
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "1:1" }),
12883
+ " ",
12884
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: compareDuration(parityState.timeSec) })
12885
+ ]
12886
+ }
12887
+ ) : null,
12888
+ parityState.kind === "unavailable" ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-parity-none", "data-testid": "compare-parity", children: "1:1 currently unavailable" }) : null
12889
+ ] })
12890
+ ] })
12891
+ ] }),
12892
+ extra !== null ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
12893
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cq-rule", "aria-hidden": "true" }),
12894
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-extra", "data-testid": "compare-extra", children: [
12895
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-extra-icon", children: /* @__PURE__ */ jsxRuntime.jsx(WalletAddGlyph, {}) }),
12896
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-extra-text", children: [
12897
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-extra-label", children: [
12898
+ "Potential extra received",
12899
+ side ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cq-info", "aria-label": `Compared with fastest${selectedOption?.entersNetting ? ". Depends on a matching order" : ""}`, title: `Compared with fastest${selectedOption?.entersNetting ? "\nDepends on a matching order" : ""}`, children: /* @__PURE__ */ jsxRuntime.jsx(InfoGlyph, {}) }) : null
12900
+ ] }),
12901
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-extra-amt", children: [
12902
+ "+",
12903
+ compareAmount(extra),
12904
+ " ",
12905
+ props.toSymbol
12906
+ ] })
12907
+ ] }),
12908
+ side ? null : /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-extra-note", children: [
12909
+ "Compared with fastest",
12910
+ selectedOption?.entersNetting ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
12911
+ /* @__PURE__ */ jsxRuntime.jsx("br", {}),
12912
+ "Depends on a matching order"
12913
+ ] }) : null
12914
+ ] })
12915
+ ] })
12916
+ ] }) : null
12917
+ ] }) : null,
12918
+ /* @__PURE__ */ jsxRuntime.jsxs(
12919
+ "div",
12920
+ {
12921
+ role: "radiogroup",
12922
+ "aria-label": "Quotes",
12923
+ className: "sg-cq-list",
12924
+ ref: listRef,
12925
+ onKeyDown: (e) => {
12926
+ const dir = e.key === "ArrowDown" || e.key === "ArrowRight" ? 1 : e.key === "ArrowUp" || e.key === "ArrowLeft" ? -1 : 0;
12927
+ if (dir === 0) return;
12928
+ const pickable = shown.filter((o) => !o.unavailable);
12929
+ if (pickable.length === 0) return;
12930
+ e.preventDefault();
12931
+ const cur = Math.max(0, pickable.findIndex((o) => o.id === rovingId));
12932
+ const next = pickable[(cur + dir + pickable.length) % pickable.length];
12933
+ pickCard(next);
12934
+ requestAnimationFrame(() => listRef.current?.querySelector(`[data-oid="${CSS.escape(next.id)}"]`)?.focus());
12935
+ },
12936
+ children: [
12937
+ shown.map((option) => /* @__PURE__ */ jsxRuntime.jsx(
12938
+ QuoteCard,
12939
+ {
12940
+ option,
12941
+ isSelected: option.id === selected,
12942
+ tabIndex: option.id === rovingId ? 0 : -1,
12943
+ tags: cornerTags(options, option, parityState),
12944
+ toSymbol: props.toSymbol,
12945
+ side,
12946
+ routeOpen: openRoutes.has(option.id),
12947
+ tokens: props.tokens,
12948
+ chainName: props.chainName,
12949
+ onPick: () => pickCard(option),
12950
+ onToggleRoute: () => toggleRoute(option.id)
12951
+ },
12952
+ option.id
12953
+ )),
12954
+ options.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", className: "sg-cq-empty", children: props.emptyMessage ?? "No quote yet \u2014 enter an amount to get one." }) : null
12955
+ ]
12956
+ }
12957
+ )
12958
+ ] }) });
12959
+ }
12960
+ function Column({ label: label2, value }) {
12961
+ return /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-col", children: [
12962
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-col-label", children: label2 }),
12963
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-col-value", children: value })
12964
+ ] });
12965
+ }
12966
+ function HopMark({ hop, tokens, size }) {
12967
+ return /* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: hop.ticker, logoUrl: logoOf(tokens, hop), chainId: hop.chainId, size });
12968
+ }
12969
+ function QuoteCard(props) {
12970
+ const { option, tags, side } = props;
12971
+ const routeId = react.useId();
12972
+ const headRef = react.useRef(null);
12973
+ const tagRef = react.useRef(null);
12974
+ const [tagInset, setTagInset] = react.useState(null);
12975
+ react.useLayoutEffect(() => {
12976
+ const head = headRef.current;
12977
+ const tag = tagRef.current;
12978
+ if (side || !head || !tag) return setTagInset(null);
12979
+ const measure = () => setTagInset(Math.max(0, Math.ceil(head.getBoundingClientRect().right - tag.getBoundingClientRect().left) + 8));
12980
+ measure();
12981
+ if (typeof ResizeObserver === "undefined") return;
12982
+ const observer = new ResizeObserver(measure);
12983
+ observer.observe(tag);
12984
+ observer.observe(head);
12985
+ return () => observer.disconnect();
12986
+ }, [tags.length, side]);
12987
+ const netting = !!option.entersNetting;
12988
+ const gasless = !!option.gasSponsored;
12989
+ const note = netting ? "Matches your swap with an opposite order" : gasless ? "No native token needed for gas" : null;
12990
+ const nettingTag = tags.some((t) => t.tone === "green");
12991
+ const purple = tags[0]?.tone === "purple" && !nettingTag;
12992
+ const hops = option.hops;
12993
+ const collapsed = side && hops.length > 3;
12994
+ const inline = collapsed ? [hops[0], hops[1], "gap", hops[hops.length - 1]] : hops;
12995
+ const hidden3 = collapsed ? hops.slice(2, -1) : [];
12996
+ const routeIcons = /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-route-icons", "data-testid": "compare-route-inline", children: inline.map((hop, i) => /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-hop-inline", children: [
12997
+ i > 0 ? /* @__PURE__ */ jsxRuntime.jsx(ArrowGlyph2, {}) : null,
12998
+ hop === "gap" ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cq-gap", title: hidden3.map((h2) => `${h2.ticker} on ${props.chainName(h2.chainId)}`).join(" \u2192 "), "aria-label": `Also via ${hidden3.map((h2) => `${h2.ticker} on ${props.chainName(h2.chainId)}`).join(", ")}`, children: "\u2026" }) : /* @__PURE__ */ jsxRuntime.jsx("span", { title: `${hop.ticker} on ${props.chainName(hop.chainId)}`, children: /* @__PURE__ */ jsxRuntime.jsx(HopMark, { hop, tokens: props.tokens, size: "xxs" }) })
12999
+ ] }, hop === "gap" ? "gap" : `${hop.chainId}-${hop.address}-${i}`)) });
13000
+ const fee = compareFeeLabel(option.feeUsd);
13001
+ const tagEl = tags.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("span", { ref: tagRef, className: "sg-cq-tag", "data-kind": nettingTag ? "netting" : purple ? "purple" : "brand", children: tags.map((tag, i) => /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-tag-item", children: [
13002
+ i > 0 ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-tag-dot", "aria-hidden": "true" }) : null,
13003
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-tone": tag.tone, children: tag.text })
13004
+ ] }, tag.text)) }) : null;
13005
+ const body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
13006
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { ref: headRef, className: "sg-cq-head", style: tagInset === null ? void 0 : { paddingRight: tagInset }, children: [
13007
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-radio", "data-on": props.isSelected || void 0, "aria-hidden": "true" }),
13008
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-amount", children: [
13009
+ tags.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-sr", children: [
13010
+ tags.map((t) => t.text).join(", "),
13011
+ " "
13012
+ ] }) : option.label ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-sr", children: [
13013
+ option.label.toLowerCase().replace(/^./, (c) => c.toUpperCase()),
13014
+ " "
13015
+ ] }) : null,
13016
+ netting ? "~" : "",
13017
+ compareAmount(option.amount),
13018
+ " ",
13019
+ props.toSymbol
13020
+ ] })
13021
+ ] }),
13022
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-stats", children: [
13023
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-cols", children: [
13024
+ /* @__PURE__ */ jsxRuntime.jsx(Column, { label: "Est. time", value: netting ? compareDuration(option.estimatedDuration).replace(/^~/, "") : compareDuration(option.estimatedDuration) }),
13025
+ gasless ? /* @__PURE__ */ jsxRuntime.jsx(Column, { label: "Gas fee", value: "Sponsored" }) : /* @__PURE__ */ jsxRuntime.jsx(Column, { label: netting ? "Est. fee" : "Fee", value: fee }),
13026
+ side && hops.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-col", children: [
13027
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-col-label", children: "Route" }),
13028
+ routeIcons
13029
+ ] }) : null
13030
+ ] }),
13031
+ !side && note ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-note", children: note }) : null
13032
+ ] }),
13033
+ option.unavailable ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-why", children: unavailableCopy(option.unavailable) }) : null
13034
+ ] });
13035
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-card", "data-testid": "compare-quote", "data-selected": props.isSelected || void 0, "data-unavailable": option.unavailable ? true : void 0, children: [
13036
+ tagEl,
13037
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", role: "radio", "aria-checked": props.isSelected, disabled: !!option.unavailable, tabIndex: props.tabIndex, "data-oid": option.id, onClick: props.onPick, className: "sg-cq-main", children: body }),
13038
+ !side && hops.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cq-route", children: [
13039
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-cq-route-toggle", onClick: props.onToggleRoute, "aria-expanded": props.routeOpen, "aria-controls": routeId, children: [
13040
+ "Route",
13041
+ /* @__PURE__ */ jsxRuntime.jsx(ChevronGlyph2, { up: props.routeOpen })
13042
+ ] }),
13043
+ props.routeOpen ? /* @__PURE__ */ jsxRuntime.jsx("div", { id: routeId, className: "sg-cq-hops", "data-testid": "compare-route", children: hops.map((hop, i) => (
13044
+ // biome-ignore lint/suspicious/noArrayIndexKey: a route is a fixed sequence, and a token can appear twice on it.
13045
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-hop", children: [
13046
+ i > 0 ? /* @__PURE__ */ jsxRuntime.jsx(ArrowGlyph2, {}) : null,
13047
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-hop-body", children: [
13048
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-hop-name", children: [
13049
+ /* @__PURE__ */ jsxRuntime.jsx(HopMark, { hop, tokens: props.tokens, size: "xxs" }),
13050
+ hop.ticker
13051
+ ] }),
13052
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-hop-chain", children: [
13053
+ "On ",
13054
+ props.chainName(hop.chainId)
13055
+ ] })
13056
+ ] })
13057
+ ] }, `${hop.chainId}-${hop.address}-${i}`)
13058
+ )) }) : null
13059
+ ] }) : null
13060
+ ] });
13061
+ }
10798
13062
  function QuoteSheet(props) {
10799
13063
  const sheetRef = react.useRef(null);
10800
13064
  const onCloseRef = react.useRef(props.onClose);
@@ -11040,11 +13304,11 @@ function ExchangeCard(props) {
11040
13304
  const [fiatCurrency, setFiatCurrency] = react.useState(props.fiatCurrency ?? "EUR");
11041
13305
  const sellableFrom = react.useCallback((t) => t && product === "rwa" && !isSellableRwa(t) ? null : t, [product]);
11042
13306
  const fromToken = react.useMemo(() => from ? sellableFrom(findToken(tokens, from.chainId, from.symbol)) : null, [tokens, from, sellableFrom]);
11043
- const toToken = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
11044
- const toSymbol = toToken?.symbol ?? to?.symbol ?? "";
13307
+ const toToken2 = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
13308
+ const toSymbol = toToken2?.symbol ?? to?.symbol ?? "";
11045
13309
  const fromTicker = fromToken ? tokenTicker(fromToken) : from?.symbol ?? "";
11046
- const toTicker = toToken ? tokenTicker(toToken) : toSymbol;
11047
- const fromPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(sourceTokens, toToken) : sourceTokens, [product, sourceTokens, toToken]);
13310
+ const toTicker = toToken2 ? tokenTicker(toToken2) : toSymbol;
13311
+ const fromPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(sourceTokens, toToken2) : sourceTokens, [product, sourceTokens, toToken2]);
11048
13312
  const toPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(tokens, fromToken) : tokens, [product, tokens, fromToken]);
11049
13313
  const rwaSeeded = react.useRef(false);
11050
13314
  react.useEffect(() => {
@@ -11061,19 +13325,19 @@ function ExchangeCard(props) {
11061
13325
  if (!catalogue?.ready) return void 0;
11062
13326
  const states2 = {};
11063
13327
  for (const token of catalogue.tokens) {
11064
- const key = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
13328
+ const key2 = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
11065
13329
  const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
11066
13330
  if (measured) {
11067
- states2[key] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
13331
+ states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
11068
13332
  continue;
11069
13333
  }
11070
13334
  const verdict = destinationAvailability(token, catalogue, fromToken);
11071
13335
  if (verdict === "available") {
11072
13336
  const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
11073
- if (limit) states2[key] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
13337
+ if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
11074
13338
  continue;
11075
13339
  }
11076
- states2[key] = {
13340
+ states2[key2] = {
11077
13341
  disabled: true,
11078
13342
  reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
11079
13343
  hint: verdict === "hub-only" ? "Not here" : "Unavailable"
@@ -11085,12 +13349,20 @@ function ExchangeCard(props) {
11085
13349
  () => destinationStates ? toPickerTokens.filter((t) => !destinationStates[`${Number(t.chainId)}:${String(t.address || "").toLowerCase()}`]?.disabled) : toPickerTokens,
11086
13350
  [toPickerTokens, destinationStates]
11087
13351
  );
13352
+ const seenReadyCatalogue = react.useRef(null);
13353
+ react.useEffect(() => {
13354
+ if (!catalogue?.ready) return;
13355
+ const first = seenReadyCatalogue.current === null;
13356
+ seenReadyCatalogue.current = catalogue;
13357
+ if (first || !to) return;
13358
+ if (destinationStates?.[`${Number(to.chainId)}:${String(findToken(tokens, to.chainId, to.symbol)?.address || "").toLowerCase()}`]?.disabled || !findToken(tokens, to.chainId, to.symbol)) setTo(null);
13359
+ }, [catalogue]);
11088
13360
  const normalizedAmount = normalizeDecimalText(amount);
11089
13361
  const amountValid = /^\d+(\.\d+)?$/.test(normalizedAmount) && Number(normalizedAmount) > 0 && Number(normalizedAmount) <= 1e9;
11090
13362
  const rampMode = mode !== "exchange";
11091
13363
  const laneLimit = react.useMemo(
11092
- () => mode === "exchange" && fromToken && toToken ? laneLimitFor(toToken, fromToken, catalogue?.limitedLanes) : void 0,
11093
- [mode, catalogue, fromToken, toToken]
13364
+ () => mode === "exchange" && fromToken && toToken2 ? laneLimitFor(toToken2, fromToken, catalogue?.limitedLanes) : void 0,
13365
+ [mode, catalogue, fromToken, toToken2]
11094
13366
  );
11095
13367
  const limitSymbol = laneLimit ? laneLimitSymbol(laneLimit, fromTicker) : "";
11096
13368
  const overLimit = react.useMemo(() => {
@@ -11244,11 +13516,11 @@ function ExchangeCard(props) {
11244
13516
  useFitText(receiveSideRef, receiveShown);
11245
13517
  const toDecimals = react.useMemo(() => {
11246
13518
  try {
11247
- return toToken ? assetDecimals(toToken) : void 0;
13519
+ return toToken2 ? assetDecimals(toToken2) : void 0;
11248
13520
  } catch {
11249
13521
  return void 0;
11250
13522
  }
11251
- }, [toToken]);
13523
+ }, [toToken2]);
11252
13524
  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;
11253
13525
  const pct = (p) => {
11254
13526
  if (!fromBal || !fromToken) return;
@@ -11262,6 +13534,7 @@ function ExchangeCard(props) {
11262
13534
  const recipientLocked = wide && recipientState.open && recipientPending;
11263
13535
  const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected2 && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
11264
13536
  const selected = addressed ? flow.selected : null;
13537
+ const compare = addressed && !solActive ? flow.compare : null;
11265
13538
  const hasQuote = Boolean(quotable && !quoting && !quoteError && receive);
11266
13539
  const nativeWei = (() => {
11267
13540
  try {
@@ -11318,10 +13591,14 @@ function ExchangeCard(props) {
11318
13591
  setView("main");
11319
13592
  requestAnimationFrame(() => (isFrom ? fromTileRef : toTileRef).current?.focus());
11320
13593
  };
13594
+ const openPicker = (v) => () => {
13595
+ setSheet(null);
13596
+ setView(v);
13597
+ };
11321
13598
  const closeSheet = () => {
11322
13599
  const was = sheet;
11323
13600
  setSheet(null);
11324
- requestAnimationFrame(() => (was === "quote" ? quoteBtnRef : complianceBtnRef).current?.focus());
13601
+ requestAnimationFrame(() => (was === "quote" || was === "compare" ? quoteBtnRef : complianceBtnRef).current?.focus());
11325
13602
  };
11326
13603
  const pctChips = mode !== "onramp" ? (
11327
13604
  // a11y note: <fieldset> carries UA styling that would have to be reset on every host page;
@@ -11351,7 +13628,7 @@ function ExchangeCard(props) {
11351
13628
  icon: /* @__PURE__ */ jsxRuntime.jsx(QuoteGlyph, {}),
11352
13629
  label: "Quote",
11353
13630
  badge: lg && hasQuote ? { text: "Best return", tone: "info" } : null,
11354
- onClick: () => setSheet("quote"),
13631
+ onClick: () => setSheet(compare ? "compare" : "quote"),
11355
13632
  disabled: !hasQuote
11356
13633
  }
11357
13634
  );
@@ -11368,7 +13645,27 @@ function ExchangeCard(props) {
11368
13645
  connect: !wallet.account ? { family: "evm", onClick: () => void wallet.connect(), busy: wallet.connecting } : !solanaWallet.address ? { family: "solana", onClick: (name) => void solanaWallet.connect(name), busy: solanaWallet.status === "connecting", choices: solanaWallet.wallets.map((w) => w.name) } : void 0,
11369
13646
  error: solanaWallet.error || wallet.error
11370
13647
  }
11371
- ) : recipientState.open ? /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, wide, onPending: wide ? setRecipientPending : void 0 }) : sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
13648
+ ) : recipientState.open ? /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, wide, onPending: wide ? setRecipientPending : void 0 }) : sheet === "compliance" ? /* @__PURE__ */ jsxRuntime.jsx(ComplianceDetails, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onBack: closeSheet, layout: wide ? "side" : "card" }) : sheet === "compare" ? (
13649
+ // Stays mounted even when `compare` is momentarily null (a refresh that is loading or failed), mirroring the
13650
+ // dapp's CompareQuotesDialog: it shows the empty/error notice in place of the cards instead of popping the
13651
+ // screen and dropping focus (zd-dapp src/components/CompareQuotesDialog.tsx uses `emptyMessage` the same way).
13652
+ /* @__PURE__ */ jsxRuntime.jsx(
13653
+ CompareQuotes,
13654
+ {
13655
+ compare,
13656
+ toSymbol: toTicker,
13657
+ tokens,
13658
+ chainName: (id) => nameOf(id) ?? `Chain ${id}`,
13659
+ onSelect: flow.selectOption,
13660
+ onBack: closeSheet,
13661
+ onRefresh: flow.reload,
13662
+ refreshing: flow.status === "loading",
13663
+ emptyMessage: flow.status === "loading" ? "Fetching quote\u2026" : quoteError || void 0,
13664
+ modal: !!props.inDialog,
13665
+ layout: wide ? "side" : "card"
13666
+ }
13667
+ )
13668
+ ) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsxRuntime.jsx(
11372
13669
  QuoteSheet,
11373
13670
  {
11374
13671
  onClose: closeSheet,
@@ -11447,7 +13744,7 @@ function ExchangeCard(props) {
11447
13744
  }
11448
13745
  );
11449
13746
  } else if (sheetBody && !wide) {
11450
- takeover = walletsOpen && !walletDetails || recipientState.open;
13747
+ takeover = walletsOpen && !walletDetails || recipientState.open || !walletsOpen && (sheet === "compare" || sheet === "compliance");
11451
13748
  body = sheetBody;
11452
13749
  } else if (solActive && solFlow.status === "sent") {
11453
13750
  body = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
@@ -11460,7 +13757,7 @@ function ExchangeCard(props) {
11460
13757
  ] }),
11461
13758
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
11462
13759
  solDelivery.phase === "tracking" ? "Submitted on Solana \u2014 tracking delivery" : deliveryHeadline(solDelivery, true),
11463
- solFlow.sent?.recipient ? ` \xB7 ${shortAddress2(solFlow.sent.recipient)}` : ""
13760
+ solFlow.sent?.recipient ? ` \xB7 ${shortAddress3(solFlow.sent.recipient)}` : ""
11464
13761
  ] }),
11465
13762
  /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: solDelivery })
11466
13763
  ] }),
@@ -11481,7 +13778,7 @@ function ExchangeCard(props) {
11481
13778
  ] }),
11482
13779
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
11483
13780
  deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
11484
- recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress2(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress2(props.recipient)}` : ""
13781
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
11485
13782
  ] }),
11486
13783
  evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
11487
13784
  ] }),
@@ -11492,7 +13789,7 @@ function ExchangeCard(props) {
11492
13789
  ] });
11493
13790
  } else {
11494
13791
  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") });
11495
- 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") });
13792
+ 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") });
11496
13793
  const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
11497
13794
  solanaSteps,
11498
13795
  solanaCta,
@@ -11513,9 +13810,9 @@ function ExchangeCard(props) {
11513
13810
  body = wide ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
11514
13811
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-stack", children: [
11515
13812
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ft", children: [
11516
- 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") }),
13813
+ 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: openPicker("from") }),
11517
13814
  /* @__PURE__ */ jsxRuntime.jsx(FlipButton, { small: true, onClick: flip, disabled: !flippable }),
11518
- 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") })
13815
+ 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: openPicker("to") })
11519
13816
  ] }),
11520
13817
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane", "data-kind": "send", children: [
11521
13818
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane-top", children: [
@@ -11609,7 +13906,7 @@ function ExchangeCard(props) {
11609
13906
  side = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-side-body", children: [
11610
13907
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv", children: [
11611
13908
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-line", children: [
11612
- /* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl: toToken?.logoUrl, chainId: to?.chainId, size: "xs" }),
13909
+ /* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl: toToken2?.logoUrl, chainId: to?.chainId, size: "xs" }),
11613
13910
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-recv-amt", ref: receiveSideRef, children: /* @__PURE__ */ jsxRuntime.jsx(AmountText, { value: formatCalculatedAmount(receive, toDecimals), exact: receive, suffix: toTicker }) })
11614
13911
  ] }),
11615
13912
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-sub", children: [