@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.
@@ -769,7 +769,7 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
769
769
  8453: "Base",
770
770
  9745: "Plasma",
771
771
  34443: "Mode",
772
- 42161: "Arbitrum One",
772
+ 42161: "Arbitrum",
773
773
  // "Avalanche", as the dApp prints it since zd-dapp#582 (from ZD Heavy's /chains). The widget's
774
774
  // registry read lists no row for a payout-only chain, so this table is what names it here.
775
775
  43114: "Avalanche",
@@ -845,8 +845,8 @@ var SOLANA_DESTINATION_ASSETS = Object.freeze({
845
845
  AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
846
846
  });
847
847
  function solanaDestinationAsset(mint) {
848
- const key = typeof mint === "string" ? mint.trim() : "";
849
- return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key) ? SOLANA_DESTINATION_ASSETS[key] : null;
848
+ const key2 = typeof mint === "string" ? mint.trim() : "";
849
+ return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key2) ? SOLANA_DESTINATION_ASSETS[key2] : null;
850
850
  }
851
851
  function solanaBridgeOf(token) {
852
852
  const pinned = solanaDestinationAsset(token.address);
@@ -1220,9 +1220,9 @@ function hexBytes(hex) {
1220
1220
  if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
1221
1221
  return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
1222
1222
  }
1223
- function solanaKeyBytes(key) {
1224
- if (!isSolanaAddress(key) || key !== key.trim()) throw new Error("Invalid Solana public key.");
1225
- return base58Decode(key);
1223
+ function solanaKeyBytes(key2) {
1224
+ if (!isSolanaAddress(key2) || key2 !== key2.trim()) throw new Error("Invalid Solana public key.");
1225
+ return base58Decode(key2);
1226
1226
  }
1227
1227
  var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1228
1228
  function base64Decode(text) {
@@ -1574,16 +1574,16 @@ function tokenTicker(token) {
1574
1574
  }
1575
1575
  function tickerOn(tokens, chainId, symbol) {
1576
1576
  if (!symbol || !chainId || !tokens?.length) return symbol;
1577
- const key = symbolKey(symbol);
1578
- const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key);
1577
+ const key2 = symbolKey(symbol);
1578
+ const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key2);
1579
1579
  return deployment ? tokenTicker(deployment) : symbol;
1580
1580
  }
1581
1581
 
1582
1582
  // src/core/availability.ts
1583
1583
  function assetClassOf(symbol) {
1584
- const key = symbolKey(symbol);
1585
- if (TRADEABLE_RWA_ASSETS.has(key)) return "rwa";
1586
- if (STABLE_ASSETS.has(key)) return "stable";
1584
+ const key2 = symbolKey(symbol);
1585
+ if (TRADEABLE_RWA_ASSETS.has(key2)) return "rwa";
1586
+ if (STABLE_ASSETS.has(key2)) return "stable";
1587
1587
  return null;
1588
1588
  }
1589
1589
  var NEST_VAULT_SHARES = /* @__PURE__ */ new Set(["NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON"]);
@@ -1692,8 +1692,8 @@ function buildCatalogue(input) {
1692
1692
  if (product === "rwa") return true;
1693
1693
  if (execution.has(chainId) || token.isChainedDestination === true) return true;
1694
1694
  if (!isExecutableBridge(token)) return false;
1695
- const key = tokenKey(token.chainId, token.address);
1696
- return source.has(key) || destination.has(key);
1695
+ const key2 = tokenKey(token.chainId, token.address);
1696
+ return source.has(key2) || destination.has(key2);
1697
1697
  });
1698
1698
  const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
1699
1699
  const catalogue = ready ? projectedCatalogue : allowed;
@@ -1741,8 +1741,8 @@ function tokenEnabled(token) {
1741
1741
  return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
1742
1742
  }
1743
1743
  function findToken(tokens, chainId, symbol) {
1744
- const key = symbolKey(symbol);
1745
- return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key) || null;
1744
+ const key2 = symbolKey(symbol);
1745
+ return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key2) || null;
1746
1746
  }
1747
1747
  function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
1748
1748
  const invoiceKey = symbolKey(invoiceAsset);
@@ -1776,10 +1776,10 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
1776
1776
  const chainId = Number(token.chainId);
1777
1777
  const chain2 = chainById(chains, chainId);
1778
1778
  if (!chainSelectable(chain2, chainId)) continue;
1779
- const key = tokenKey(chainId, token.address);
1780
- if (seen.has(key)) continue;
1779
+ const key2 = tokenKey(chainId, token.address);
1780
+ if (seen.has(key2)) continue;
1781
1781
  if (refusal(token)) continue;
1782
- seen.add(key);
1782
+ seen.add(key2);
1783
1783
  const payKey = symbolKey(token.symbol);
1784
1784
  const direct2 = chainId === invoiceChain && payKey === invoiceKey;
1785
1785
  options.push({
@@ -1965,7 +1965,7 @@ function normalizePreview(request, quote, to, amount) {
1965
1965
  async function quoteSolanaSource(api, input) {
1966
1966
  const { from, to, amount } = selections(input, await api.fetchTokens());
1967
1967
  const request = makeRequest(input, from, to, amount);
1968
- const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1968
+ const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
1969
1969
  const preview = normalizePreview(request, quote, to, input.amountIn);
1970
1970
  quoteRequests.set(preview, { api, request: clone(request) });
1971
1971
  return preview;
@@ -1979,7 +1979,7 @@ async function previewSolanaSource(api, input) {
1979
1979
  raw(amount, "input amount", true);
1980
1980
  const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
1981
1981
  const request = body;
1982
- const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
1982
+ const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
1983
1983
  const option = quote?.options?.[0];
1984
1984
  if (!option) throw new Error("Native quote returned no options.");
1985
1985
  const receive = raw(option.finalAmount, "quoted output", true);
@@ -2333,6 +2333,58 @@ var TRACKING = Object.freeze({ phase: "tracking", status: "", steps: [] });
2333
2333
  var word = (v) => typeof v === "string" ? v.trim().toLowerCase() : "";
2334
2334
  var STEP_ORDER = { submitted: 0, arrived: 1, filled: 2, delivered: 3 };
2335
2335
  var STATUS_REACHED = { in_progress: 1, outbound_bridging: 2, delivery_failed: 2, delivered: 3 };
2336
+ var ZDH_FIRST_STEP = 20;
2337
+ var ZDH_STEP = {
2338
+ paid_out: "delivered",
2339
+ cancelled: "cancellation_requested",
2340
+ refunded: "refunded"
2341
+ };
2342
+ var ROUTE_MECHANICS = /* @__PURE__ */ new Set(["consumed", "step_executed", "step_filled", "returned"]);
2343
+ var PROGRESS = /* @__PURE__ */ new Set(["pending", "in_progress", "outbound_bridging"]);
2344
+ var MAX_STEPS = 8;
2345
+ function isZdHeavy(r, steps) {
2346
+ return r.protocol === "zdheavy" || steps.some((s) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP);
2347
+ }
2348
+ function zdHeavyDelivery(own, rawSteps) {
2349
+ const named = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string");
2350
+ const lite = (name) => named.some((s) => Number(s.stepNumber ?? 0) < ZDH_FIRST_STEP && s.stepName === name && s.stepStatus === "completed");
2351
+ 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);
2352
+ const has = (name) => events.some((e) => e.stepName === name);
2353
+ const cancelled = has("cancelled");
2354
+ const status = PROGRESS.has(own) && has("paid_out") && !cancelled ? "delivered" : own;
2355
+ const steps = [];
2356
+ const push = (name, done) => {
2357
+ const last = steps[steps.length - 1];
2358
+ if (last && last.name === name && last.done === done) return;
2359
+ steps.push({ name, done });
2360
+ };
2361
+ if (lite("submitted")) push("submitted", true);
2362
+ const terminal = cancelled || FAILED.has(status) || ATTENTION.has(status) || status === "delivered";
2363
+ if (!cancelled && !FAILED.has(status) && !ATTENTION.has(status)) {
2364
+ if (status === "delivered") {
2365
+ push("route_completed", true);
2366
+ } else {
2367
+ push("route", false);
2368
+ }
2369
+ }
2370
+ for (const e of events) {
2371
+ const name = String(e.stepName);
2372
+ if (ROUTE_MECHANICS.has(name)) continue;
2373
+ if (name === "refund_parked") {
2374
+ push(e.stepStatus === "recovered" ? "claimed" : "ready_to_claim", e.stepStatus === "recovered");
2375
+ continue;
2376
+ }
2377
+ push(ZDH_STEP[name] ?? name.slice(0, 32), true);
2378
+ }
2379
+ if (!terminal) push("delivered", false);
2380
+ const capped = steps.length > MAX_STEPS ? [...steps.slice(0, MAX_STEPS - 1), steps[steps.length - 1]] : steps;
2381
+ const refunded = cancelled && has("refunded");
2382
+ if (!status) return TRACKING;
2383
+ if (FAILED.has(status)) return { phase: "failed", status, steps: capped, ...refunded ? { refunded } : {} };
2384
+ if (ATTENTION.has(status)) return { phase: "attention", status, steps: capped };
2385
+ if (status === "delivered") return { phase: "delivered", status, steps: capped };
2386
+ return { phase: "in-progress", status, steps: capped };
2387
+ }
2336
2388
  function normalizeDelivery(raw2) {
2337
2389
  const row = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2.data ?? raw2 : null;
2338
2390
  if (!row || typeof row !== "object" || Array.isArray(row)) return TRACKING;
@@ -2342,6 +2394,7 @@ function normalizeDelivery(raw2) {
2342
2394
  const own = word(r.status);
2343
2395
  const status = journey || own;
2344
2396
  const rawSteps = Array.isArray(r.steps) ? r.steps : [];
2397
+ if (isZdHeavy(r, rawSteps) && !chained) return zdHeavyDelivery(own, rawSteps);
2345
2398
  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" }));
2346
2399
  const reached = Math.max(STATUS_REACHED[own] ?? -1, ...listed.filter((s) => s.done).map((s) => STEP_ORDER[s.name] ?? -1));
2347
2400
  const steps = listed.map((s) => (STEP_ORDER[s.name] ?? Infinity) <= reached ? { ...s, done: true } : s);
@@ -2378,8 +2431,8 @@ function historyKey(value) {
2378
2431
  var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
2379
2432
  function tokenAt(tokens, chainId, address) {
2380
2433
  if (!address) return void 0;
2381
- const key = historyKey(address);
2382
- return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key);
2434
+ const key2 = historyKey(address);
2435
+ return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key2);
2383
2436
  }
2384
2437
  function amountOf(raw2, token, rowDecimals, rowAmount) {
2385
2438
  const decimals = token ? Number(token.decimals) : Number(rowDecimals);
@@ -2465,13 +2518,13 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
2465
2518
  const out = [];
2466
2519
  const seen = /* @__PURE__ */ new Set();
2467
2520
  for (const entry of local) {
2468
- const key = historyKey(entry.hash);
2469
- if (seen.has(key)) continue;
2470
- seen.add(key);
2471
- const known = byHash.get(key);
2521
+ const key2 = historyKey(entry.hash);
2522
+ if (seen.has(key2)) continue;
2523
+ seen.add(key2);
2524
+ const known = byHash.get(key2);
2472
2525
  out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
2473
2526
  }
2474
- for (const [key, entry] of byHash) if (!seen.has(key)) out.push(entry);
2527
+ for (const [key2, entry] of byHash) if (!seen.has(key2)) out.push(entry);
2475
2528
  return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
2476
2529
  }
2477
2530
 
@@ -2582,12 +2635,12 @@ function suppressedLanes(health) {
2582
2635
  const out = /* @__PURE__ */ new Map();
2583
2636
  for (const lane of health.lanes) {
2584
2637
  if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
2585
- const key = healthLaneKey(lane.laneKey);
2586
- if (!key) continue;
2638
+ const key2 = healthLaneKey(lane.laneKey);
2639
+ if (!key2) continue;
2587
2640
  const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
2588
2641
  const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
2589
2642
  const message = typeof availability?.message === "string" && availability.message ? availability.message : lane.message;
2590
- out.set(key, {
2643
+ out.set(key2, {
2591
2644
  route: typeof lane.route === "string" ? lane.route : "",
2592
2645
  code: typeof code === "string" ? code : "",
2593
2646
  message: typeof message === "string" ? message : "",
@@ -2602,15 +2655,15 @@ function limitedLanes(health) {
2602
2655
  const out = /* @__PURE__ */ new Map();
2603
2656
  for (const lane of health.lanes) {
2604
2657
  if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
2605
- const key = healthLaneKey(lane.laneKey);
2658
+ const key2 = healthLaneKey(lane.laneKey);
2606
2659
  const limit = lane.availability?.limit;
2607
- if (!key || !limit || typeof limit !== "object") continue;
2660
+ if (!key2 || !limit || typeof limit !== "object") continue;
2608
2661
  const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
2609
2662
  const maxAmount = typeof limit.maxAmount === "string" ? limit.maxAmount.trim() : "";
2610
2663
  const decimals = limit.decimals;
2611
2664
  if (!side || !BASE_UNITS.test(maxAmount) || typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
2612
2665
  const code = lane.availability?.code;
2613
- out.set(key, {
2666
+ out.set(key2, {
2614
2667
  side,
2615
2668
  token: typeof limit.token === "string" ? limit.token : "",
2616
2669
  fromChainId: Number(limit.fromChainId) || 0,
@@ -2673,10 +2726,10 @@ function resolveVaultIcon(apiBase, iconPath) {
2673
2726
  function vaultIconsBySymbol(apiBase, vaults) {
2674
2727
  const out = /* @__PURE__ */ new Map();
2675
2728
  for (const vault of vaults) {
2676
- const key = symbolKey(vault?.symbol);
2677
- if (!key || out.has(key)) continue;
2729
+ const key2 = symbolKey(vault?.symbol);
2730
+ if (!key2 || out.has(key2)) continue;
2678
2731
  const url = resolveVaultIcon(apiBase, vault?.iconMiniUrl) ?? resolveVaultIcon(apiBase, vault?.iconUrl);
2679
- if (url) out.set(key, url);
2732
+ if (url) out.set(key2, url);
2680
2733
  }
2681
2734
  return out;
2682
2735
  }
@@ -2773,7 +2826,7 @@ var CATEGORY_PHRASES = {
2773
2826
  UNKNOWN: "an unrecognized risk"
2774
2827
  };
2775
2828
  function categoryLabel(code) {
2776
- const key = code.trim().toUpperCase();
2829
+ const key2 = code.trim().toUpperCase();
2777
2830
  const LABELS = {
2778
2831
  SANCTIONS: "Sanctions",
2779
2832
  TERRORISM_FINANCING: "Terrorist financing",
@@ -2788,7 +2841,7 @@ function categoryLabel(code) {
2788
2841
  UNCLASSIFIED: "Unclassified risk",
2789
2842
  UNKNOWN: "Unclassified risk"
2790
2843
  };
2791
- return LABELS[key] ?? key.toLowerCase().replace(/_/g, " ");
2844
+ return LABELS[key2] ?? key2.toLowerCase().replace(/_/g, " ");
2792
2845
  }
2793
2846
  function cleanJurisdiction(code) {
2794
2847
  return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
@@ -2901,9 +2954,9 @@ function distinctScreenedWallets(compliance) {
2901
2954
  for (const raw2 of compliance?.screenedWallets ?? []) {
2902
2955
  const address = raw2?.trim();
2903
2956
  if (!address) continue;
2904
- const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
2905
- if (seen.has(key)) continue;
2906
- seen.add(key);
2957
+ const key2 = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
2958
+ if (seen.has(key2)) continue;
2959
+ seen.add(key2);
2907
2960
  wallets.push(address);
2908
2961
  }
2909
2962
  return wallets;
@@ -3030,9 +3083,9 @@ var TUNED_OUTCOMES = {
3030
3083
  UNCLASSIFIED: "flagged"
3031
3084
  };
3032
3085
  function screeningOutcomeOf(category) {
3033
- const key = category.trim().toUpperCase();
3034
- if (FLOOR_CATEGORIES.includes(key)) return "always-blocked";
3035
- return TUNED_OUTCOMES[key] ?? null;
3086
+ const key2 = category.trim().toUpperCase();
3087
+ if (FLOOR_CATEGORIES.includes(key2)) return "always-blocked";
3088
+ return TUNED_OUTCOMES[key2] ?? null;
3036
3089
  }
3037
3090
  var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
3038
3091
  var SCREENING_BUCKETS = [
@@ -3041,6 +3094,91 @@ var SCREENING_BUCKETS = [
3041
3094
  { outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
3042
3095
  ];
3043
3096
 
3097
+ // src/core/zdheavy-routers.ts
3098
+ var ZDHEAVY_ROUTER_TEST05 = "0x94c5cC7f4689AD7B0Abd0975F4C8E159e4633251";
3099
+ var ZDHEAVY_ROUTER_TEST04 = "0x72EA420DCE5BE939062E527b49388479d7171379";
3100
+ var ZDHEAVY_ROUTER_DEV = "0xD813690937324417cFBE12E742dD53054F90dF04";
3101
+ var ZDHEAVY_ROUTER_DEV_V6 = "0xa6155b1505378e6C9871483c55375dcBBB16f897";
3102
+ var ZDHEAVY_ROUTER_PROD = "0x7D50305f2855Bf2225FE51E15858b4BA0C0844e1";
3103
+ var ZDHEAVY_DEV_CHAINS = [1, 10, 56, 130, 137, 143, 146, 1329, 1672, 4663, 5e3, 8453, 9745, 42161, 43114, 57073, 98866];
3104
+ var ZDHEAVY_SANDBOX_CHAINS = [8453, 9745, 42161];
3105
+ var ZDHEAVY_ROUTER_ADDRESSES = Object.fromEntries(
3106
+ ZDHEAVY_DEV_CHAINS.map((id) => [
3107
+ id,
3108
+ 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]
3109
+ ])
3110
+ );
3111
+ function zdHeavyRouterPinned(chainId, router) {
3112
+ if (typeof router !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(router)) return false;
3113
+ const want = router.toLowerCase();
3114
+ return (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).some((a) => a.toLowerCase() === want);
3115
+ }
3116
+
3117
+ // src/core/quote-option.ts
3118
+ function zdHeavyExecutable(q) {
3119
+ const order = q.execution?.order;
3120
+ const chainId = typeof q.fromChainId === "number" ? q.fromChainId : Number(order?.chainNumber);
3121
+ 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);
3122
+ }
3123
+ function liteExecutable(q) {
3124
+ return q.protocol !== "zdheavy" && Array.isArray(q.orderRequests) && q.orderRequests.length > 0;
3125
+ }
3126
+ function selectQuoteOption(quote) {
3127
+ if (!Array.isArray(quote.options)) return quote;
3128
+ const option = quote.options.find(zdHeavyExecutable) ?? quote.options.find((q) => q.protocol !== "zdheavy" && !!q.orderRequests?.length);
3129
+ if (!option) throw new Error("ZeroDelta quote has no executable option.");
3130
+ const gatewayOptions = [];
3131
+ let gatewayOptionIndex = -1;
3132
+ for (const o of quote.options) {
3133
+ if (!o || typeof o !== "object" || Array.isArray(o)) continue;
3134
+ if (o === option) gatewayOptionIndex = gatewayOptions.length;
3135
+ gatewayOptions.push(projectOption(quote, o));
3136
+ }
3137
+ return { ...projectOption(quote, option), gatewayOptions, gatewayOptionIndex };
3138
+ }
3139
+ function projectOption(quote, option) {
3140
+ const { fromChainId, toChainId, fromToken, toToken: toToken2, fromAmount } = quote;
3141
+ const last = option.orderRequests?.[option.orderRequests.length - 1];
3142
+ const { entersNetting, gasSponsored, gatewayOptions: _g, gatewayOptionIndex: _i, ...rest } = option;
3143
+ return {
3144
+ ...rest,
3145
+ ...entersNetting === true ? { entersNetting: true } : {},
3146
+ ...gasSponsored === true ? { gasSponsored: true } : {},
3147
+ fromChainId,
3148
+ toChainId,
3149
+ fromToken,
3150
+ toToken: toToken2,
3151
+ fromAmount,
3152
+ quoteId: quote.quoteId,
3153
+ toAmount: String(last?.askTokenAmount ?? option.outputAmount ?? option.toAmount ?? ""),
3154
+ finalAmount: String(option.finalAmount || last?.askTokenAmount || option.outputAmount || ""),
3155
+ compliance: complianceDecision(quote),
3156
+ estimatedDuration: option.estimatedTimeSec ?? option.estimatedDuration
3157
+ };
3158
+ }
3159
+ function complianceDecision(quote) {
3160
+ const decision = quote.complianceDecision ?? quote.compliance;
3161
+ return decision && typeof decision === "object" && !Array.isArray(decision) ? decision : void 0;
3162
+ }
3163
+ function normalizeQuoteResponse(response, request) {
3164
+ const quote = Array.isArray(response?.options) ? selectQuoteOption({
3165
+ ...response,
3166
+ fromChainId: request.inputChain,
3167
+ toChainId: request.outputChain,
3168
+ fromToken: request.inputToken,
3169
+ toToken: request.outputToken,
3170
+ fromAmount: request.inputAmount
3171
+ }) : response;
3172
+ if (quote?.gatewayOptions) quote.gatewayOptions = quote.gatewayOptions.map(numericExecutionChain);
3173
+ return numericExecutionChain(quote);
3174
+ }
3175
+ function numericExecutionChain(quote) {
3176
+ return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
3177
+ }
3178
+ function deliveredAmount(quote, solanaDestination) {
3179
+ return BigInt(quote.protocol === "zdheavy" || solanaDestination ? quote.finalAmount || quote.toAmount || "0" : quote.toAmount || "0");
3180
+ }
3181
+
3044
3182
  // src/core/solve.ts
3045
3183
  async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
3046
3184
  const destDecimals = assetDecimals(destinationToken);
@@ -3087,7 +3225,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3087
3225
  let bestGuess = guess;
3088
3226
  for (let i = 0; i < 3; i += 1) {
3089
3227
  const guessSent = guess;
3090
- const quote = await fetchQuote({
3228
+ const quote = selectQuoteOption(await fetchQuote({
3091
3229
  fromChainId: option.chainId,
3092
3230
  toChainId: Number(destination.chainId),
3093
3231
  fromToken: option.symbol,
@@ -3095,11 +3233,11 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3095
3233
  fromAmount: guessSent.toString(),
3096
3234
  owner: payer,
3097
3235
  destinationReceiver: destination.address
3098
- });
3236
+ }));
3099
3237
  if (BigInt(quote?.fromAmount || "0") !== guessSent) {
3100
3238
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3101
3239
  }
3102
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3240
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3103
3241
  const final = finalOf(quote);
3104
3242
  if (final > bestFinal) {
3105
3243
  bestFinal = final;
@@ -3136,7 +3274,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3136
3274
  directTransfer: false,
3137
3275
  quote: best,
3138
3276
  youPayRaw: bestGuess.toString(),
3139
- recipientReceivesRaw: (isSolanaChainId(destination.chainId) ? finalOf(best) : BigInt(best.toAmount || "0")).toString(),
3277
+ recipientReceivesRaw: deliveredAmount(best, isSolanaChainId(destination.chainId)).toString(),
3140
3278
  targetRaw: targetRaw.toString(),
3141
3279
  overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
3142
3280
  meetsTarget: bestFinal >= targetRaw,
@@ -3146,7 +3284,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
3146
3284
  async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
3147
3285
  const fromRaw = BigInt(amountInRaw || "0");
3148
3286
  if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
3149
- const quote = await fetchQuote({
3287
+ const quote = selectQuoteOption(await fetchQuote({
3150
3288
  fromChainId: option.chainId,
3151
3289
  toChainId: Number(destination.chainId),
3152
3290
  fromToken: option.symbol,
@@ -3154,11 +3292,11 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3154
3292
  fromAmount: fromRaw.toString(),
3155
3293
  owner: payer,
3156
3294
  destinationReceiver: destination.address
3157
- });
3295
+ }));
3158
3296
  if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
3159
3297
  throw new Error("ZeroDelta echoed a different input amount than requested.");
3160
3298
  }
3161
- const guaranteed = isSolanaChainId(destination.chainId) ? finalOf(quote) : BigInt(quote?.toAmount || "0");
3299
+ const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
3162
3300
  if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3163
3301
  return {
3164
3302
  directTransfer: false,
@@ -3171,6 +3309,24 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
3171
3309
  iterations: 1
3172
3310
  };
3173
3311
  }
3312
+ function resultForOption(result, option, mode, destinationChainId) {
3313
+ if (result.directTransfer) throw new Error("A direct transfer has no other option.");
3314
+ if (BigInt(option.fromAmount || "0") !== BigInt(result.youPayRaw)) throw new Error("ZeroDelta echoed a different input amount than requested.");
3315
+ const guaranteed = deliveredAmount(option, isSolanaChainId(destinationChainId));
3316
+ if (mode === "exact-in") {
3317
+ if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
3318
+ return { ...result, quote: option, recipientReceivesRaw: guaranteed.toString(), targetRaw: guaranteed.toString(), overageBps: 0, meetsTarget: true };
3319
+ }
3320
+ const targetRaw = BigInt(result.targetRaw);
3321
+ const final = finalOf(option);
3322
+ return {
3323
+ ...result,
3324
+ quote: option,
3325
+ recipientReceivesRaw: guaranteed.toString(),
3326
+ overageBps: targetRaw > 0n ? Number((final - targetRaw) * 10000n / targetRaw) : 0,
3327
+ meetsTarget: final >= targetRaw
3328
+ };
3329
+ }
3174
3330
 
3175
3331
  // src/core/order.ts
3176
3332
  var DEFAULT_DEADLINE_SECONDS = 1800;
@@ -3290,6 +3446,1011 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
3290
3446
  }
3291
3447
  }
3292
3448
 
3449
+ // src/core/checksum.ts
3450
+ var RC = [
3451
+ 0x0000000000000001n,
3452
+ 0x0000000000008082n,
3453
+ 0x800000000000808an,
3454
+ 0x8000000080008000n,
3455
+ 0x000000000000808bn,
3456
+ 0x0000000080000001n,
3457
+ 0x8000000080008081n,
3458
+ 0x8000000000008009n,
3459
+ 0x000000000000008an,
3460
+ 0x0000000000000088n,
3461
+ 0x0000000080008009n,
3462
+ 0x000000008000000an,
3463
+ 0x000000008000808bn,
3464
+ 0x800000000000008bn,
3465
+ 0x8000000000008089n,
3466
+ 0x8000000000008003n,
3467
+ 0x8000000000008002n,
3468
+ 0x8000000000000080n,
3469
+ 0x000000000000800an,
3470
+ 0x800000008000000an,
3471
+ 0x8000000080008081n,
3472
+ 0x8000000000008080n,
3473
+ 0x0000000080000001n,
3474
+ 0x8000000080008008n
3475
+ ];
3476
+ 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];
3477
+ var MASK = (1n << 64n) - 1n;
3478
+ var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
3479
+ function keccakF(s) {
3480
+ for (let round = 0; round < 24; round++) {
3481
+ const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
3482
+ for (let x = 0; x < 5; x++) {
3483
+ const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
3484
+ for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
3485
+ }
3486
+ const b = new Array(25);
3487
+ 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]);
3488
+ 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];
3489
+ s[0] = s[0] ^ RC[round];
3490
+ }
3491
+ }
3492
+ function keccak256Hex(bytes) {
3493
+ const rate = 136;
3494
+ const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
3495
+ padded.set(bytes);
3496
+ padded[bytes.length] = padded[bytes.length] ^ 1;
3497
+ padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
3498
+ const s = new Array(25).fill(0n);
3499
+ for (let off = 0; off < padded.length; off += rate) {
3500
+ for (let i = 0; i < rate / 8; i++) {
3501
+ let lane = 0n;
3502
+ for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
3503
+ s[i] = s[i] ^ lane;
3504
+ }
3505
+ keccakF(s);
3506
+ }
3507
+ let out = "";
3508
+ 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");
3509
+ return out;
3510
+ }
3511
+ function toChecksumAddress(address) {
3512
+ const lower3 = address.slice(2).toLowerCase();
3513
+ const hash2 = keccak256Hex(new TextEncoder().encode(lower3));
3514
+ let out = "0x";
3515
+ for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower3[i].toUpperCase() : lower3[i];
3516
+ return out;
3517
+ }
3518
+ function hasValidChecksum(address) {
3519
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
3520
+ const body = address.slice(2);
3521
+ if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
3522
+ return toChecksumAddress(address) === address;
3523
+ }
3524
+
3525
+ // src/core/zdheavy-codec.ts
3526
+ var concat = (parts) => "0x" + parts.map((p) => p.slice(2)).join("");
3527
+ var hexToBytes2 = (h2) => Uint8Array.from(h2.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
3528
+ var toBytes = (s) => new TextEncoder().encode(s);
3529
+ 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(""));
3530
+ var keccak256 = (h2) => "0x" + keccak256Hex(hexToBytes2(h2));
3531
+ var STEP_VERSION = 5;
3532
+ var MAX_STEPS2 = 8;
3533
+ var StepKind = {
3534
+ LOCAL_PAYOUT: 1,
3535
+ REMOTE_PAYOUT: 2,
3536
+ SEND: 3,
3537
+ SWAP: 4,
3538
+ EXECUTE: 5,
3539
+ NET: 6,
3540
+ SUBSIDY: 7
3541
+ };
3542
+ var ZdHeavyCodecError = class extends Error {
3543
+ constructor(message) {
3544
+ super(message);
3545
+ this.name = "ZdHeavyCodecError";
3546
+ }
3547
+ };
3548
+ function checkedHex(value, length) {
3549
+ if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value) || length !== void 0 && value.length !== 2 + length * 2) {
3550
+ throw new ZdHeavyCodecError(`Expected ${length === void 0 ? "byte-aligned" : length + "-byte"} hex`);
3551
+ }
3552
+ return value.toLowerCase();
3553
+ }
3554
+ function uint(value, bytes) {
3555
+ if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bytes * 8)) {
3556
+ throw new ZdHeavyCodecError(`Value outside uint${bytes * 8}`);
3557
+ }
3558
+ return toHex(value, { size: bytes });
3559
+ }
3560
+ var Reader2 = class {
3561
+ bytes;
3562
+ offset = 0;
3563
+ constructor(step) {
3564
+ this.bytes = hexToBytes2(checkedHex(step));
3565
+ }
3566
+ take(n) {
3567
+ if (this.offset + n > this.bytes.length) throw new ZdHeavyCodecError("Short step");
3568
+ const result = this.bytes.slice(this.offset, this.offset + n);
3569
+ this.offset += n;
3570
+ return result;
3571
+ }
3572
+ hex(n) {
3573
+ return toHex(this.take(n));
3574
+ }
3575
+ uint(n) {
3576
+ let result = 0n;
3577
+ for (const byte of this.take(n)) result = result << 8n | BigInt(byte);
3578
+ return result;
3579
+ }
3580
+ number(n) {
3581
+ return Number(this.uint(n));
3582
+ }
3583
+ address() {
3584
+ const n = this.number(1);
3585
+ if (n === 0 || n > 64) throw new ZdHeavyCodecError("Address length must be 1..64");
3586
+ return this.hex(n);
3587
+ }
3588
+ bytes16() {
3589
+ return this.hex(this.number(2));
3590
+ }
3591
+ adapters() {
3592
+ const count = this.number(1);
3593
+ if (count > 8) throw new ZdHeavyCodecError("Too many bridge adapters");
3594
+ return Array.from({ length: count }, () => this.number(2));
3595
+ }
3596
+ end() {
3597
+ if (this.offset !== this.bytes.length) throw new ZdHeavyCodecError("Trailing step bytes");
3598
+ }
3599
+ };
3600
+ function decodeStep(step) {
3601
+ const r = new Reader2(step);
3602
+ if (r.number(1) !== STEP_VERSION) throw new ZdHeavyCodecError("Unsupported step version");
3603
+ const kind = r.number(2);
3604
+ if (kind < 1 || kind > 7) throw new ZdHeavyCodecError("Unknown step kind");
3605
+ const chainId = r.uint(8);
3606
+ const count = r.number(1);
3607
+ if (kind !== StepKind.SWAP && count !== 0) throw new ZdHeavyCodecError("Unexpected allowances");
3608
+ const allowances = Array.from({ length: count }, () => ({
3609
+ pathwayId: r.number(1),
3610
+ maxShareBps: r.number(2),
3611
+ params: r.bytes16()
3612
+ }));
3613
+ const base = { chainId, allowances };
3614
+ let result;
3615
+ switch (kind) {
3616
+ case StepKind.LOCAL_PAYOUT:
3617
+ result = { ...base, kind: "LOCAL_PAYOUT", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16) };
3618
+ break;
3619
+ case StepKind.REMOTE_PAYOUT:
3620
+ result = {
3621
+ ...base,
3622
+ kind: "REMOTE_PAYOUT",
3623
+ token: r.address(),
3624
+ receiverChainId: r.uint(8),
3625
+ receiver: r.address(),
3626
+ bridgeAdapters: r.adapters(),
3627
+ maxFee: r.uint(16),
3628
+ minAmountOut: r.uint(16)
3629
+ };
3630
+ break;
3631
+ case StepKind.SEND:
3632
+ result = {
3633
+ ...base,
3634
+ kind: "SEND",
3635
+ token: r.address(),
3636
+ dstChainId: r.uint(8),
3637
+ bridgeAdapters: r.adapters(),
3638
+ maxFee: r.uint(16),
3639
+ inUnit: r.uint(16),
3640
+ outUnit: r.uint(16)
3641
+ };
3642
+ break;
3643
+ case StepKind.SWAP:
3644
+ result = { ...base, kind: "SWAP", tokenIn: r.address(), tokenOut: r.address(), expectedIn: r.uint(16), minOut: r.uint(16) };
3645
+ break;
3646
+ case StepKind.EXECUTE:
3647
+ result = { ...base, kind: "EXECUTE", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16), gasLimit: r.uint(8), data: r.bytes16() };
3648
+ break;
3649
+ case StepKind.NET: {
3650
+ const token = r.address(), pathwayId = r.number(1), arriveStep = r.number(1);
3651
+ const params = r.hex(78);
3652
+ const t = new Reader2(params);
3653
+ const terms = {
3654
+ nettingDeadline: t.uint(8),
3655
+ dstDomain: t.number(4),
3656
+ dstAsset: t.hex(32),
3657
+ inUnit: t.uint(16),
3658
+ outUnit: t.uint(16),
3659
+ complianceClass: t.number(2)
3660
+ };
3661
+ result = { chainId, allowances: [{ pathwayId, maxShareBps: 0, params }], kind: "NET", token, pathwayId, arriveStep, terms };
3662
+ break;
3663
+ }
3664
+ case StepKind.SUBSIDY:
3665
+ result = { ...base, kind: "SUBSIDY", token: r.address(), minIn: r.uint(16), amountOut: r.uint(16) };
3666
+ break;
3667
+ default:
3668
+ throw new ZdHeavyCodecError("Unknown step kind");
3669
+ }
3670
+ r.end();
3671
+ return result;
3672
+ }
3673
+ function routerWord(addr) {
3674
+ return concat([toHex(new Uint8Array(12)), checkedHex(addr, 20)]);
3675
+ }
3676
+ function ownerWord(addr) {
3677
+ return routerWord(addr);
3678
+ }
3679
+ function encodeOrderHeader(serial, router, ownerType, owner) {
3680
+ if (!Number.isInteger(ownerType) || ownerType < 0 || ownerType > 255) throw new ZdHeavyCodecError("Invalid ownerType");
3681
+ return concat(["0x050000", uint(serial, 8), routerWord(router), uint(BigInt(ownerType), 1), checkedHex(owner, 32)]);
3682
+ }
3683
+ function orderIdOf(expiryDate, header, steps) {
3684
+ if (steps.length < 1 || steps.length > MAX_STEPS2) throw new ZdHeavyCodecError("Step count must be 1..8");
3685
+ return keccak256(
3686
+ concat([toHex(toBytes("ZD/ORDER")), uint(expiryDate, 8), keccak256(checkedHex(header)), ...steps.map((step) => keccak256(checkedHex(step)))])
3687
+ );
3688
+ }
3689
+ var ZDHEAVY_SUBMIT_SELECTOR = "0x1a579a0c";
3690
+ var ZDHEAVY_PARTNER_SUBMIT_SELECTOR = "0xdd3d9749";
3691
+ var ZDHEAVY_QUOTE_SELECTOR = "0x3cfc3141";
3692
+ function decodeZdHeavySubmit(data) {
3693
+ const hex = checkedHex(data);
3694
+ const selector = hex.slice(0, 10);
3695
+ if (selector !== ZDHEAVY_SUBMIT_SELECTOR && selector !== ZDHEAVY_PARTNER_SUBMIT_SELECTOR) {
3696
+ throw new ZdHeavyCodecError("Expected submitOrder");
3697
+ }
3698
+ const body = hex.slice(10);
3699
+ const size = body.length / 2;
3700
+ const fail = () => {
3701
+ throw new ZdHeavyCodecError("Invalid submitOrder calldata");
3702
+ };
3703
+ const word2 = (at, bits = 256) => {
3704
+ if (!Number.isSafeInteger(at) || at < 0 || at + 32 > size) return fail();
3705
+ const n2 = BigInt(`0x${body.slice(at * 2, (at + 32) * 2)}`);
3706
+ if (n2 >= 1n << BigInt(bits)) return fail();
3707
+ return n2;
3708
+ };
3709
+ const fixed = (at) => {
3710
+ word2(at);
3711
+ return `0x${body.slice(at * 2, (at + 32) * 2)}`;
3712
+ };
3713
+ const offset = (at, expected) => {
3714
+ if (word2(at) !== BigInt(expected)) fail();
3715
+ };
3716
+ const bytes = (at) => {
3717
+ const n2 = word2(at);
3718
+ if (n2 > BigInt(size - at - 32)) return fail();
3719
+ const length = Number(n2);
3720
+ const end = at + 32 + Math.ceil(length / 32) * 32;
3721
+ if (end > size || /[^0]/.test(body.slice((at + 32 + length) * 2, end * 2))) return fail();
3722
+ return { value: `0x${body.slice((at + 32) * 2, (at + 32 + length) * 2)}`, end };
3723
+ };
3724
+ const base = selector === ZDHEAVY_SUBMIT_SELECTOR ? 32 : 64;
3725
+ offset(0, base);
3726
+ const partnerId = base === 64 ? fixed(32) : null;
3727
+ const serial = word2(base, 64);
3728
+ const ownerType = Number(word2(base + 32, 8));
3729
+ const owner = fixed(base + 64);
3730
+ const expiryDate = word2(base + 160, 64);
3731
+ offset(base + 96, 224);
3732
+ const ownerSignature = bytes(base + 224);
3733
+ offset(base + 128, ownerSignature.end - base);
3734
+ const array = ownerSignature.end;
3735
+ const count = word2(array);
3736
+ if (count > BigInt(Math.floor((size - array - 32) / 32))) return fail();
3737
+ const n = Number(count);
3738
+ const arrayBase = array + 32;
3739
+ let next = arrayBase + n * 32;
3740
+ const steps = [];
3741
+ for (let i = 0; i < n; i++) {
3742
+ offset(arrayBase + i * 32, next - arrayBase);
3743
+ const step = bytes(next);
3744
+ steps.push(step.value);
3745
+ next = step.end;
3746
+ }
3747
+ offset(base + 192, next - base);
3748
+ const q = next;
3749
+ const amountIn = word2(q, 128);
3750
+ const fee = { input: word2(q + 32, 128), native: word2(q + 64, 128) };
3751
+ const quoteId = fixed(q + 96);
3752
+ const requestId = fixed(q + 128);
3753
+ const expiresAt = word2(q + 160, 64);
3754
+ offset(q + 192, 224);
3755
+ const signature = bytes(q + 224);
3756
+ if (signature.end !== size) return fail();
3757
+ return {
3758
+ submission: {
3759
+ serial,
3760
+ ownerType,
3761
+ owner,
3762
+ ownerSignature: ownerSignature.value,
3763
+ steps,
3764
+ expiryDate,
3765
+ quote: { amountIn, fee, quoteId, requestId, expiresAt, signature: signature.value }
3766
+ },
3767
+ partnerId
3768
+ };
3769
+ }
3770
+ function quoteSubmitCalldata(data) {
3771
+ decodeZdHeavySubmit(data);
3772
+ const tuple = data.slice(data.slice(0, 10).toLowerCase() === ZDHEAVY_SUBMIT_SELECTOR ? 74 : 138);
3773
+ return `${ZDHEAVY_QUOTE_SELECTOR}${uintWord(32)}${tuple}`;
3774
+ }
3775
+
3776
+ // src/core/zdheavy-check.ts
3777
+ var isAddress2 = hasValidChecksum;
3778
+ var getAddress = (s) => toChecksumAddress(s);
3779
+ var refuse = (what) => ({
3780
+ ok: false,
3781
+ reason: `The ZD Heavy order the gateway built does not match the order shown (${what}) \u2014 refusing to sign.`
3782
+ });
3783
+ var lower = (v) => typeof v === "string" ? v.toLowerCase() : "";
3784
+ function big2(v) {
3785
+ if (v === void 0 || v === null || v === "") return null;
3786
+ try {
3787
+ return BigInt(v);
3788
+ } catch {
3789
+ return null;
3790
+ }
3791
+ }
3792
+ var sameBig = (a, b) => big2(b) === a;
3793
+ var sameAddr = (a, b) => !!b && lower(a) === lower(b);
3794
+ function checkZdHeavyRouter(chainId, router) {
3795
+ if (!router || !isAddress2(router)) return { ok: false, reason: "No valid ZD Heavy router address for this chain \u2014 refusing to sign." };
3796
+ const address = getAddress(router);
3797
+ const pinned = (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).map((a) => getAddress(a));
3798
+ if (!pinned.includes(address)) {
3799
+ return { ok: false, reason: `Router ${address} is not a trusted ZD Heavy router on this chain \u2014 refusing to sign.` };
3800
+ }
3801
+ return { ok: true, address };
3802
+ }
3803
+ function sameAllowances(d, j) {
3804
+ if (d.kind !== "SWAP") return true;
3805
+ const want = j.allowances ?? [];
3806
+ if (want.length !== d.allowances.length) return false;
3807
+ return d.allowances.every((a, i) => {
3808
+ const w = want[i];
3809
+ return a.pathwayId === w.pathwayId && a.maxShareBps === w.maxShareBps && lower(a.params) === lower(w.params && w.params !== "" ? w.params : "0x");
3810
+ });
3811
+ }
3812
+ function sameAdapters(a, b) {
3813
+ const w = b ?? [];
3814
+ return a.length === w.length && a.every((x, i) => x === w[i]);
3815
+ }
3816
+ function sameStep(d, j) {
3817
+ if (d.kind !== String(j.kind).toUpperCase()) return false;
3818
+ if (!sameBig(d.chainId, j.chainId)) return false;
3819
+ if (!sameAllowances(d, j)) return false;
3820
+ switch (d.kind) {
3821
+ case "SWAP":
3822
+ return sameAddr(d.tokenIn, j.tokenIn) && sameAddr(d.tokenOut, j.tokenOut) && sameBig(d.expectedIn, j.expectedIn) && sameBig(d.minOut, j.minOut);
3823
+ case "LOCAL_PAYOUT":
3824
+ return sameAddr(d.token, j.token) && sameAddr(d.receiver, j.receiver) && sameBig(d.minAmountOut, j.minAmountOut);
3825
+ case "REMOTE_PAYOUT":
3826
+ 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);
3827
+ case "SEND":
3828
+ 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);
3829
+ case "SUBSIDY":
3830
+ return sameAddr(d.token, j.token) && sameBig(d.minIn, j.minIn) && sameBig(d.amountOut, j.amountOut);
3831
+ case "NET": {
3832
+ const t = j.terms;
3833
+ if (!t) return false;
3834
+ const domainOfAsset = Number(BigInt(t.dstAsset) >> 224n);
3835
+ 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);
3836
+ }
3837
+ default:
3838
+ return false;
3839
+ }
3840
+ }
3841
+ function checkSubmit(tx, e) {
3842
+ if (tx.chainId !== String(e.chainId)) return refuse("chain");
3843
+ if (!sameAddr(e.router, tx.to)) return refuse("router");
3844
+ let decoded;
3845
+ try {
3846
+ decoded = decodeZdHeavySubmit(tx.data);
3847
+ } catch {
3848
+ return refuse("not a router submitOrder");
3849
+ }
3850
+ const { submission: s, partnerId } = decoded;
3851
+ const order = e.order;
3852
+ if (!order) return refuse("no order");
3853
+ const wantPartner = typeof e.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(e.partnerId) ? lower(e.partnerId) : null;
3854
+ if ((partnerId ? lower(partnerId) : null) !== wantPartner) return refuse("partner id");
3855
+ if (!isAddress2(e.owner)) return refuse("owner");
3856
+ if (s.ownerType !== 1 || lower(s.owner) !== lower(ownerWord(e.owner))) return refuse("owner");
3857
+ if (s.ownerSignature !== "0x") return refuse("owner signature");
3858
+ if (!s.quote.signature || s.quote.signature === "0x") return refuse("no API signature");
3859
+ if (order.chainNumber !== e.chainId || !sameAddr(e.router, order.router)) return refuse("router");
3860
+ if (s.steps.length < 1 || s.steps.length > MAX_STEPS2 || s.steps.length !== order.steps.length) return refuse("number of steps");
3861
+ const steps = [];
3862
+ for (let i = 0; i < s.steps.length; i++) {
3863
+ let d;
3864
+ try {
3865
+ d = decodeStep(s.steps[i]);
3866
+ } catch {
3867
+ return refuse(`step ${i} encoding`);
3868
+ }
3869
+ if (d.kind === "EXECUTE") return refuse(`step ${i} kind EXECUTE`);
3870
+ if (!sameStep(d, order.steps[i])) return refuse(`step ${i}`);
3871
+ steps.push(d);
3872
+ }
3873
+ const first = steps[0];
3874
+ if (first.chainId !== BigInt(e.chainId)) return refuse("source chain");
3875
+ const firstToken = first.kind === "SWAP" ? first.tokenIn : "token" in first ? first.token : "";
3876
+ if (!sameAddr(e.fromToken, firstToken) || !sameAddr(e.fromToken, order.tokenIn)) return refuse("source token");
3877
+ const last = steps[steps.length - 1];
3878
+ if (steps.slice(0, -1).some((d) => d.kind === "LOCAL_PAYOUT" || d.kind === "REMOTE_PAYOUT")) return refuse("payout before the last step");
3879
+ if (last.kind !== "LOCAL_PAYOUT" && last.kind !== "REMOTE_PAYOUT") return refuse("no payout");
3880
+ const deliveryChain = last.kind === "LOCAL_PAYOUT" ? last.chainId : last.receiverChainId;
3881
+ if (deliveryChain !== BigInt(e.toChainId)) return refuse("destination chain");
3882
+ if (last.kind === "LOCAL_PAYOUT") {
3883
+ if (!sameAddr(e.toToken, last.token)) return refuse("destination token");
3884
+ } else {
3885
+ if (!e.remotePayoutToken?.(last.token, Number(last.chainId))) return refuse("destination token of a cross-chain payout");
3886
+ }
3887
+ if (!sameAddr(e.receiver, last.receiver)) return refuse("receiver");
3888
+ const amountIn = big2(order.amountIn);
3889
+ const feeInput = big2(order.fee.input);
3890
+ const feeNative = big2(order.fee.native);
3891
+ if (amountIn === null || feeInput === null || feeNative === null) return refuse("amount");
3892
+ if (s.quote.amountIn !== amountIn || s.quote.fee.input !== feeInput || s.quote.fee.native !== feeNative) return refuse("amount");
3893
+ if (amountIn + feeInput !== e.amountRaw || big2(order.grossIn) !== e.amountRaw) return refuse("amount");
3894
+ if (s.expiryDate !== BigInt(order.expiryDate) || s.quote.expiresAt !== BigInt(order.expiresAt)) return refuse("expiry");
3895
+ if (s.expiryDate <= BigInt(e.nowSec) || s.quote.expiresAt <= BigInt(e.nowSec)) return refuse("expired");
3896
+ if (last.kind === "REMOTE_PAYOUT" && last.maxFee >= last.minAmountOut) return refuse("minimum out");
3897
+ const floor = last.kind === "REMOTE_PAYOUT" ? last.minAmountOut - last.maxFee : last.minAmountOut;
3898
+ if (floor <= 0n || floor !== e.finalAmount) return refuse("minimum out");
3899
+ let orderId;
3900
+ try {
3901
+ orderId = orderIdOf(s.expiryDate, encodeOrderHeader(s.serial, getAddress(e.router), 1, s.owner), s.steps);
3902
+ } catch {
3903
+ return refuse("order id");
3904
+ }
3905
+ if (!e.rootHash || lower(orderId) !== lower(e.rootHash)) return refuse("order id");
3906
+ return { ok: true, floor, orderId };
3907
+ }
3908
+ function checkZdHeavySubmit(tx, e) {
3909
+ try {
3910
+ return checkSubmit(tx, e);
3911
+ } catch {
3912
+ return refuse("malformed order");
3913
+ }
3914
+ }
3915
+
3916
+ // src/core/asset-identity.ts
3917
+ function key(chainId, address) {
3918
+ const id = Number(chainId);
3919
+ return Number.isSafeInteger(id) && id > 0 && typeof address === "string" && isChainAddress(id, address) ? tokenKey(id, address) : null;
3920
+ }
3921
+ function sameAssetDeployment(tokens, routes, a, b) {
3922
+ const ka = key(a.chainId, a.address);
3923
+ const kb = key(b.chainId, b.address);
3924
+ if (!ka || !kb) return false;
3925
+ const parent = /* @__PURE__ */ new Map();
3926
+ const find = (k) => {
3927
+ const p = parent.get(k);
3928
+ if (p === void 0) {
3929
+ parent.set(k, k);
3930
+ return k;
3931
+ }
3932
+ if (p === k) return k;
3933
+ const root = find(p);
3934
+ parent.set(k, root);
3935
+ return root;
3936
+ };
3937
+ const join = (x, y) => {
3938
+ if (x && y) parent.set(find(y), find(x));
3939
+ };
3940
+ for (const r of routes) {
3941
+ if (r.isEnabled === false) continue;
3942
+ const from = key(r.fromChainId, r.fromAddress);
3943
+ const to = key(r.toChainId, r.toAddress);
3944
+ join(from, to);
3945
+ const home = key(r.homeChainId, r.homeTokenAddress);
3946
+ join(from, home);
3947
+ join(to, home);
3948
+ }
3949
+ for (const t of tokens) join(key(t.chainId, t.address), key(t.homeChainId, t.homeTokenAddress));
3950
+ return parent.has(ka) && parent.has(kb) && find(ka) === find(kb);
3951
+ }
3952
+
3953
+ // src/core/validate-tx.ts
3954
+ var lower2 = (v) => String(v || "").toLowerCase();
3955
+ function isHexAddress(value) {
3956
+ return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
3957
+ }
3958
+ function isHexData(value) {
3959
+ return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value || "0x"));
3960
+ }
3961
+ function isHexQuantity(value) {
3962
+ return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
3963
+ }
3964
+ function dataWord(data, index) {
3965
+ const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
3966
+ return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
3967
+ }
3968
+ function dataAddress(data, index) {
3969
+ const word2 = dataWord(data, index);
3970
+ return word2 ? `0x${word2.slice(24)}` : "";
3971
+ }
3972
+ function dataUint(data, index) {
3973
+ const word2 = dataWord(data, index);
3974
+ return word2 ? BigInt(`0x${word2}`) : null;
3975
+ }
3976
+ function rawEquals(value, expected) {
3977
+ try {
3978
+ return value === BigInt(expected || "0");
3979
+ } catch {
3980
+ return false;
3981
+ }
3982
+ }
3983
+ function planMsgValueHex(route) {
3984
+ try {
3985
+ const raw2 = route?.quote?.msgValue;
3986
+ if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
3987
+ return "0x" + BigInt(raw2).toString(16);
3988
+ } catch {
3989
+ return null;
3990
+ }
3991
+ }
3992
+ function validatePlannedTransaction(tx, route, expectedRecipient, heavyExpected) {
3993
+ if (!tx || tx.mock) return true;
3994
+ if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
3995
+ const data = String(tx.data || "0x").toLowerCase();
3996
+ const selector = data.slice(0, 10);
3997
+ const value = lower2(tx.value || "0x0");
3998
+ if (tx.kind === "transfer") {
3999
+ if (value !== "0x0") return false;
4000
+ return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower2(tx.to) === lower2(tx.token) && lower2(dataAddress(data, 0)) === lower2(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4001
+ }
4002
+ if (tx.kind === "approve") {
4003
+ if (route.zdHeavy) {
4004
+ return !!heavyExpected && tx.chainId === heavyExpected.chainId && lower2(tx.to) === lower2(heavyExpected.fromToken) && lower2(data) === lower2(encodeApprove(heavyExpected.router, heavyExpected.amountRaw)) && BigInt(value) === 0n;
4005
+ }
4006
+ if (value !== "0x0") return false;
4007
+ 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);
4008
+ }
4009
+ if (tx.kind === "submitOrder") {
4010
+ if (route.zdHeavy) {
4011
+ const expectedValue = planMsgValueHex(route);
4012
+ return expectedValue !== null && value === lower2(expectedValue) && !!heavyExpected && checkZdHeavySubmit({ ...tx, chainId: String(tx.chainId) }, heavyExpected).ok;
4013
+ }
4014
+ const expected = planMsgValueHex(route);
4015
+ if (expected === null || value !== lower2(expected)) return false;
4016
+ if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower2(tx.to) !== lower2(tx.escrow)) return false;
4017
+ const decoded = decodeSubmitOrderCalldata(data);
4018
+ if (!decoded) return false;
4019
+ const first = decoded.orders[0];
4020
+ const last = decoded.orders[decoded.orders.length - 1];
4021
+ 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));
4022
+ }
4023
+ return false;
4024
+ }
4025
+ function solanaDeliveryMatches(encoded, recipient2, mint) {
4026
+ try {
4027
+ return lower2(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4028
+ } catch {
4029
+ return false;
4030
+ }
4031
+ }
4032
+ async function allowanceCovers(tx, account, ethCall) {
4033
+ if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4034
+ try {
4035
+ const raw2 = await ethCall(tx.token, encodeAllowance(account, tx.spender));
4036
+ return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4037
+ } catch {
4038
+ return false;
4039
+ }
4040
+ }
4041
+
4042
+ // src/core/zdheavy-route.ts
4043
+ function zdHeavyExpected(route, owner, receiver, tokens, routes) {
4044
+ const heavy = route.zdHeavy;
4045
+ if (!heavy) throw new Error("Missing ZD Heavy order.");
4046
+ const pin2 = checkZdHeavyRouter(route.source.chainId, heavy.order.router);
4047
+ if (!pin2.ok) throw new Error(pin2.reason);
4048
+ 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))
4049
+ throw new Error("ZD Heavy display amount mismatch.");
4050
+ return {
4051
+ chainId: route.source.chainId,
4052
+ router: pin2.address,
4053
+ owner,
4054
+ receiver,
4055
+ fromToken: route.source.tokenAddress,
4056
+ toToken: route.receive.tokenAddress,
4057
+ toChainId: route.receive.chainId,
4058
+ amountRaw: BigInt(heavy.amountRaw),
4059
+ finalAmount: BigInt(heavy.finalAmount),
4060
+ order: heavy.order,
4061
+ rootHash: heavy.rootHash,
4062
+ partnerId: route.quote.partnerId,
4063
+ nowSec: Math.floor(Date.now() / 1e3),
4064
+ remotePayoutToken: (token, chainId) => sameAssetDeployment(tokens, routes, { chainId, address: token }, { chainId: route.receive.chainId, address: route.receive.tokenAddress })
4065
+ };
4066
+ }
4067
+ function validateZdHeavyPlan(route, expected) {
4068
+ if (route.transactions.length !== 2 || route.transactions[0].kind !== "approve" || route.transactions[1].kind !== "submitOrder") {
4069
+ throw new Error("ZD Heavy requires exactly approve then submitOrder; refusing to sign.");
4070
+ }
4071
+ for (const tx of route.transactions) {
4072
+ if (tx.mock || tx.chainId !== expected.chainId || !validatePlannedTransaction(tx, route, expected.receiver, expected)) {
4073
+ throw new Error("ZD Heavy transaction does not match the reviewed plan; refusing to sign.");
4074
+ }
4075
+ }
4076
+ const submit = route.transactions[1];
4077
+ const checked = checkZdHeavySubmit({ ...submit, chainId: String(submit.chainId) }, expected);
4078
+ if (!checked.ok) throw new Error(checked.reason);
4079
+ return checked.floor;
4080
+ }
4081
+
4082
+ // src/core/zdheavy-build.ts
4083
+ function buildZdHeavyRoute(ctx) {
4084
+ const { option, destination, destinationToken, chains, result } = ctx;
4085
+ const q = result.quote;
4086
+ if (!zdHeavyExecutable(q)) throw new Error("ZD Heavy quote is not signed and executable.");
4087
+ const order = q.execution.order;
4088
+ const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
4089
+ const decimals = assetDecimals(destinationToken);
4090
+ const receiveAmount = formatUnits(result.recipientReceivesRaw, decimals);
4091
+ const partnerId = typeof q.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(q.partnerId) ? q.partnerId : void 0;
4092
+ const route = {
4093
+ id: `zdh-${option.chainId}-${option.symbolKey}-${destination.chainId}-${destinationToken.symbol}`,
4094
+ recommended: false,
4095
+ state: result.meetsTarget ? "ROUTE" : "SHORT",
4096
+ source: {
4097
+ asset: option.symbol,
4098
+ ticker: option.ticker || option.symbol,
4099
+ chainId: option.chainId,
4100
+ chainName: option.chainName,
4101
+ tokenAddress: option.address,
4102
+ decimals: option.decimals,
4103
+ amount: sourceAmount,
4104
+ payAmount: sourceAmount
4105
+ },
4106
+ receive: {
4107
+ asset: destinationToken.symbol,
4108
+ ticker: tokenTicker(destinationToken),
4109
+ chainId: Number(destination.chainId),
4110
+ chainName: chainNameOf(Number(destination.chainId), chains),
4111
+ tokenAddress: destinationToken.address,
4112
+ decimals,
4113
+ amount: receiveAmount
4114
+ },
4115
+ routeLabel: "Settle on ZeroDelta via ZD Heavy.",
4116
+ deltaLabel: result.meetsTarget ? "~0" : "Below requested amount",
4117
+ legs: [
4118
+ {
4119
+ index: 1,
4120
+ fromAsset: option.symbol,
4121
+ fromTicker: option.ticker || option.symbol,
4122
+ fromChainId: option.chainId,
4123
+ fromChainName: option.chainName,
4124
+ fromAmount: sourceAmount,
4125
+ toAsset: destinationToken.symbol,
4126
+ toTicker: tokenTicker(destinationToken),
4127
+ toChainId: Number(destination.chainId),
4128
+ toChainName: chainNameOf(Number(destination.chainId), chains),
4129
+ toAmount: receiveAmount,
4130
+ executionChainId: option.chainId,
4131
+ executionChainName: option.chainName
4132
+ }
4133
+ ],
4134
+ transactions: q.txData.map((tx, i) => {
4135
+ const submit = tx.actionType === "submit" || tx.actionType === "submitOrder";
4136
+ if (tx.actionType !== "approve" && !submit) throw new Error("Unexpected ZD Heavy transaction action.");
4137
+ if (typeof tx.value !== "string" || !/^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(tx.value)) throw new Error("Invalid ZD Heavy native value.");
4138
+ return {
4139
+ id: submit ? "submit-order" : `approve-${i}`,
4140
+ kind: submit ? "submitOrder" : "approve",
4141
+ label: submit ? "Submit ZeroDelta order" : `Approve ${option.ticker || option.symbol}`,
4142
+ chainId: Number(tx.chainId),
4143
+ to: tx.to,
4144
+ data: tx.data,
4145
+ // The gateway publishes decimal wei; EIP-1193 requires a hex quantity.
4146
+ // Calldata and targets remain the gateway's exact bytes.
4147
+ value: toHexQuantity(tx.value),
4148
+ token: option.address,
4149
+ spender: order.router,
4150
+ amountRaw: result.youPayRaw
4151
+ };
4152
+ }),
4153
+ quote: {
4154
+ bridge: q.bridge,
4155
+ feeBps: q.feeBps,
4156
+ estimatedDuration: q.estimatedDuration,
4157
+ gasCostSource: q.gasCostSource,
4158
+ iterations: result.iterations,
4159
+ compliance: q.compliance,
4160
+ partnerId,
4161
+ zeroDeltaFeeCentibips: q.zeroDeltaFeeCentibips,
4162
+ zeroDeltaFeeNative: q.zeroDeltaFeeNative
4163
+ },
4164
+ zdHeavy: { order, rootHash: q.rootHash, amountRaw: result.youPayRaw, finalAmount: result.recipientReceivesRaw, floor: "" }
4165
+ };
4166
+ if (route.transactions.length === 2) route.quote.msgValue = BigInt(route.transactions[1].value).toString();
4167
+ const expected = zdHeavyExpected(route, ctx.payer, destination.address, ctx.tokens, ctx.routes);
4168
+ route.zdHeavy.floor = validateZdHeavyPlan(route, expected).toString();
4169
+ return route;
4170
+ }
4171
+
4172
+ // src/core/quote-compare.ts
4173
+ var WAIT_MIN_SEC = 180;
4174
+ var WAIT_MAX_SEC = 7200;
4175
+ var WAIT_STEP_SEC = 60;
4176
+ function clampWait(sec) {
4177
+ if (!Number.isFinite(sec)) return WAIT_MIN_SEC;
4178
+ return Math.min(WAIT_MAX_SEC, Math.max(WAIT_MIN_SEC, sec));
4179
+ }
4180
+ var WAIT_POINTS = [
4181
+ [WAIT_MIN_SEC, 0],
4182
+ [1800, 0.295],
4183
+ [2700, 0.4725],
4184
+ [WAIT_MAX_SEC, 1]
4185
+ ];
4186
+ var FIGMA_TRAVEL_PX = 400;
4187
+ function waitScaleFor(travelPx) {
4188
+ if (!Number.isFinite(travelPx) || travelPx >= FIGMA_TRAVEL_PX || travelPx < 200) return WAIT_POINTS;
4189
+ return WAIT_POINTS.map(
4190
+ ([sec, fraction], i) => i === 0 || i === WAIT_POINTS.length - 1 ? [sec, fraction] : [sec, fraction * FIGMA_TRAVEL_PX / travelPx]
4191
+ );
4192
+ }
4193
+ var WAIT_POSITIONS = 1e3;
4194
+ function waitFraction(sec, points = WAIT_POINTS) {
4195
+ const s = clampWait(sec);
4196
+ for (let i = 1; i < points.length; i++) {
4197
+ const [s1, f1] = points[i];
4198
+ if (s <= s1) {
4199
+ const [s0, f0] = points[i - 1];
4200
+ return f0 + (s - s0) / (s1 - s0) * (f1 - f0);
4201
+ }
4202
+ }
4203
+ return 1;
4204
+ }
4205
+ function waitFromFraction(fraction, points = WAIT_POINTS) {
4206
+ const f = Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0;
4207
+ for (let i = 1; i < points.length; i++) {
4208
+ const [s1, f1] = points[i];
4209
+ if (f <= f1) {
4210
+ const [s0, f0] = points[i - 1];
4211
+ return s0 + (f - f0) / (f1 - f0) * (s1 - s0);
4212
+ }
4213
+ }
4214
+ return WAIT_MAX_SEC;
4215
+ }
4216
+ function snapWait(sec) {
4217
+ return clampWait(Math.round(sec / WAIT_STEP_SEC) * WAIT_STEP_SEC);
4218
+ }
4219
+ function waitLabel(sec) {
4220
+ const min = Math.round(clampWait(sec) / 60);
4221
+ if (min >= 60 && min % 60 === 0) return `Up to ${min / 60} ${min === 60 ? "hour" : "hours"}`;
4222
+ return `Up to ${min} min`;
4223
+ }
4224
+ var hasTime = (o) => Number.isFinite(o.estimatedDuration) && o.estimatedDuration > 0;
4225
+ function selectableOptions(options) {
4226
+ return options.filter((o) => !o.unavailable);
4227
+ }
4228
+ function bestOutputOption(options) {
4229
+ return selectableOptions(options).reduce((best, o) => !best || o.amount > best.amount ? o : best, void 0);
4230
+ }
4231
+ function fastestOption(options) {
4232
+ const selectable = selectableOptions(options);
4233
+ const labelled = selectable.find((o) => o.label?.toLowerCase() === "fastest");
4234
+ if (labelled) return labelled;
4235
+ return selectable.filter(hasTime).reduce((f, o) => !f || o.estimatedDuration < f.estimatedDuration ? o : f, void 0);
4236
+ }
4237
+ function proposedWait(options) {
4238
+ const best = bestOutputOption(options);
4239
+ return clampWait(best && hasTime(best) ? best.estimatedDuration : WAIT_MIN_SEC);
4240
+ }
4241
+ function pickForWait(options, waitSec) {
4242
+ const within = selectableOptions(options).filter((o) => hasTime(o) && o.estimatedDuration <= waitSec);
4243
+ return bestOutputOption(within) ?? fastestOption(options);
4244
+ }
4245
+ var MAX_QUOTE_CARDS = 3;
4246
+ function visibleOptions(options, waitSec, selectedId) {
4247
+ if (options.length <= MAX_QUOTE_CARDS) return nettingFirst(options);
4248
+ const selectable = selectableOptions(options);
4249
+ if (selectable.length === 0) return nettingFirst(options.slice(0, MAX_QUOTE_CARDS));
4250
+ const chosen = selectable.find((o) => o.id === selectedId) ?? pickForWait(options, waitSec);
4251
+ const gasless = bestOutputOption(selectable.filter((o) => o.gasSponsored));
4252
+ const netting = bestOutputOption(selectable.filter((o) => o.entersNetting));
4253
+ const ids = new Set([chosen?.id, fastestOption(options)?.id, gasless?.id, netting?.id].filter((id) => !!id));
4254
+ const keep = new Set([...ids].slice(0, MAX_QUOTE_CARDS));
4255
+ return nettingFirst(options.filter((o) => keep.has(o.id)));
4256
+ }
4257
+ function nettingFirst(options) {
4258
+ return [...options.filter((o) => o.entersNetting), ...options.filter((o) => !o.entersNetting)];
4259
+ }
4260
+ function compareDuration(seconds) {
4261
+ if (!Number.isFinite(seconds) || seconds <= 0) return "--";
4262
+ if (seconds < 60) return `~${Math.round(seconds)} s`;
4263
+ return `~${Math.round(seconds / 60)} min`;
4264
+ }
4265
+ function parity(options, inputUsd, toUnitUsd) {
4266
+ const priced = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
4267
+ if (!priced(inputUsd) || !priced(toUnitUsd)) return { kind: "unknown" };
4268
+ const reaching = selectableOptions(options).filter((o) => hasTime(o) && o.amount * toUnitUsd >= inputUsd);
4269
+ const earliest = reaching.reduce(
4270
+ (e, o) => !e || o.estimatedDuration < e.estimatedDuration || o.estimatedDuration === e.estimatedDuration && o.amount > e.amount ? o : e,
4271
+ void 0
4272
+ );
4273
+ return earliest ? { kind: "at", option: earliest, timeSec: earliest.estimatedDuration } : { kind: "unavailable" };
4274
+ }
4275
+ function extraVsFastest(options, selectedId) {
4276
+ const selected = selectableOptions(options).find((o) => o.id === selectedId);
4277
+ const fastest = fastestOption(options);
4278
+ if (!selected || !fastest) return null;
4279
+ const extra = selected.amount - fastest.amount;
4280
+ return extra > 1e-9 ? extra : null;
4281
+ }
4282
+ function routeBadges(options) {
4283
+ const field = options.filter((o) => !o.unavailable);
4284
+ const out = /* @__PURE__ */ new Map();
4285
+ if (field.length < 2) return out;
4286
+ const best = (pick, better) => field.reduce((acc, o) => {
4287
+ const value = pick(o);
4288
+ if (value === null) return acc;
4289
+ const accValue = acc ? pick(acc) : null;
4290
+ return accValue === null || better(value, accValue) ? o : acc;
4291
+ }, null);
4292
+ const bestReturn = best(
4293
+ (o) => o.amount,
4294
+ (a, b) => a > b
4295
+ );
4296
+ const fastest = best(
4297
+ (o) => o.estimatedDuration,
4298
+ (a, b) => a < b
4299
+ );
4300
+ const lowestFee = best(
4301
+ (o) => o.feeUsd,
4302
+ (a, b) => a < b
4303
+ );
4304
+ if (bestReturn) out.set(bestReturn.id, "Best return");
4305
+ if (fastest && !out.has(fastest.id)) out.set(fastest.id, "Fastest");
4306
+ if (lowestFee && !out.has(lowestFee.id)) out.set(lowestFee.id, "Lowest fee");
4307
+ return out;
4308
+ }
4309
+ function routeShapeLabel(option) {
4310
+ if (!option) return null;
4311
+ if (option.kind === "transfer") return "Transfer";
4312
+ const middle = option.hops.slice(1, -1);
4313
+ if (middle.length === 0) return "Direct";
4314
+ return `Via ${middle.map((h2) => h2.ticker).join(" \xB7 ")}`;
4315
+ }
4316
+ function cornerTags(options, option, parityState) {
4317
+ if (option.unavailable) return [];
4318
+ if (option.kind === "transfer") return [{ text: "Transfer", tone: "brand" }];
4319
+ if (option.entersNetting) return [{ text: "Best return", tone: "green" }];
4320
+ const tags = [];
4321
+ const labelledFastest = selectableOptions(options).some((o) => o.label?.toLowerCase() === "fastest");
4322
+ if (parityState.kind === "at" && parityState.option.id === option.id) tags.push({ text: "Target 1:1", tone: "brand" });
4323
+ else if (option.label?.toLowerCase() === "fastest") tags.push({ text: "Fastest", tone: "brand" });
4324
+ else if (option.gasSponsored) tags.push({ text: "Gasless", tone: "purple" });
4325
+ else {
4326
+ const badge = routeBadges(options).get(option.id);
4327
+ const text = badge === "Fastest" && labelledFastest ? void 0 : badge ?? routeShapeLabel(option) ?? void 0;
4328
+ if (text) tags.push({ text, tone: "brand" });
4329
+ }
4330
+ return tags;
4331
+ }
4332
+ function humanAmount(n, maxFrac = 6) {
4333
+ if (!Number.isFinite(n)) return String(n);
4334
+ if (n === 0) return "0";
4335
+ const digits = Math.min(Math.max(0, Math.trunc(maxFrac)), 8);
4336
+ const fixed = n.toFixed(digits);
4337
+ const out = fixed.includes(".") ? fixed.replace(/\.?0+$/, "") : fixed;
4338
+ if (Number(out) === 0) return `<${digits > 0 ? `0.${"0".repeat(digits - 1)}1` : "1"}`;
4339
+ const match = out.match(/^([+-]?)(\d+)(\.\d+)?$/);
4340
+ return match ? `${match[1]}${match[2].replace(/\B(?=(\d{3})+(?!\d))/g, ",")}${match[3] ?? ""}` : out;
4341
+ }
4342
+ function compareAmount(value) {
4343
+ const text = humanAmount(value, 6);
4344
+ if (text.startsWith("<")) return text;
4345
+ const [whole, fraction = ""] = text.split(".");
4346
+ return fraction.length >= 2 ? text : `${whole}.${fraction.padEnd(2, "0")}`;
4347
+ }
4348
+ function compareFeeUsd(option, fromUsd) {
4349
+ const centibips = option.feeCentibips;
4350
+ if (centibips === void 0 || option.feeNative) return null;
4351
+ if (centibips === 0) return 0;
4352
+ return typeof fromUsd === "number" && Number.isFinite(fromUsd) && fromUsd > 0 ? fromUsd * centibips / 1e6 : null;
4353
+ }
4354
+ function priceCompareOptions(options, fromUsd) {
4355
+ return options.map((o) => ({ ...o, feeUsd: compareFeeUsd(o, fromUsd) }));
4356
+ }
4357
+ var ZD_HEAVY_KEY_PREFIX = "zdheavy:";
4358
+ function zdHeavyOptionKey(q) {
4359
+ return q.label ? `${ZD_HEAVY_KEY_PREFIX}${q.label}:${String(q.escrowAddress ?? "").toLowerCase()}` : `${ZD_HEAVY_KEY_PREFIX}id:${q.optionId ?? ""}`;
4360
+ }
4361
+ function zdHeavyUnavailableStatus(q) {
4362
+ return zdHeavyExecutable(q) ? void 0 : typeof q.payloadStatus === "string" && q.payloadStatus ? q.payloadStatus : "unknown";
4363
+ }
4364
+ function tokenAt2(tokens, chainId, address) {
4365
+ const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
4366
+ const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
4367
+ if (!wanted || !tokens?.length) return void 0;
4368
+ return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
4369
+ }
4370
+ function hopFor(tokens, address, chainId, fallback) {
4371
+ const token = tokenAt2(tokens, chainId, address);
4372
+ return { address, chainId, ticker: token ? tokenTicker(token) : fallback ?? "Unknown" };
4373
+ }
4374
+ function compareHops(quote, ctx) {
4375
+ if (quote.protocol === "zdheavy") {
4376
+ const order = quote.execution?.order;
4377
+ if (!order || !Array.isArray(order.steps) || !order.steps.length) return [];
4378
+ const first = order.steps[0];
4379
+ const hops2 = [hopFor(ctx.tokens, String(first.tokenIn ?? first.token ?? order.tokenIn ?? ""), Number(order.chainNumber), ctx.from.ticker)];
4380
+ const push = (address, chainId, fallback) => {
4381
+ if (!address || chainId === void 0) return;
4382
+ const previous = hops2[hops2.length - 1];
4383
+ if (previous.address.toLowerCase() === address.toLowerCase() && previous.chainId === Number(chainId)) return;
4384
+ hops2.push(hopFor(ctx.tokens, address, Number(chainId), fallback));
4385
+ };
4386
+ order.steps.forEach((s, i) => {
4387
+ const n = order.steps[i + 1];
4388
+ const p = hops2[hops2.length - 1];
4389
+ if (s.kind === "SWAP") push(s.tokenOut, s.chainId);
4390
+ else if (s.kind === "SEND") push(n?.tokenIn ?? n?.token, s.dstChainId, p.ticker);
4391
+ else if (s.kind === "LOCAL_PAYOUT") push(s.token, s.chainId, ctx.to.ticker);
4392
+ else if (s.kind === "REMOTE_PAYOUT") push(ctx.to.address, s.receiverChainId, ctx.to.ticker);
4393
+ });
4394
+ return hops2;
4395
+ }
4396
+ const requests = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
4397
+ if (!requests.length) return [];
4398
+ const hops = [hopFor(ctx.tokens, String(requests[0].bidToken ?? ""), Number(quote.fromChainId), ctx.from.ticker)];
4399
+ requests.forEach((request, i) => {
4400
+ const last = i === requests.length - 1;
4401
+ hops.push(hopFor(ctx.tokens, String(request.askToken ?? ""), Number(request.destinationChainId || quote.toChainId), last ? ctx.to.ticker : void 0));
4402
+ });
4403
+ return hops;
4404
+ }
4405
+ var shortAddress2 = (address) => address.slice(0, 10).toLowerCase();
4406
+ function compareOptionOf(quote, ctx) {
4407
+ const heavy = quote.protocol === "zdheavy";
4408
+ if (!heavy && !liteExecutable(quote)) return null;
4409
+ const hops = compareHops(quote, ctx);
4410
+ if (hops.length < 2 && !heavy) return null;
4411
+ let amountRaw;
4412
+ let amount;
4413
+ try {
4414
+ amountRaw = BigInt(quote.finalAmount || quote.toAmount || "");
4415
+ amount = Number(formatUnits(amountRaw, ctx.to.decimals, ctx.to.decimals));
4416
+ } catch {
4417
+ return null;
4418
+ }
4419
+ const centibips = quote.zeroDeltaFeeCentibips;
4420
+ const native = quote.zeroDeltaFeeNative;
4421
+ const feeNative = typeof native === "string" && /^\d+$/.test(native) && BigInt(native) > 0n;
4422
+ const feeCentibips = typeof centibips === "number" && Number.isSafeInteger(centibips) && centibips >= 0 ? centibips : void 0;
4423
+ const unavailable = heavy ? zdHeavyUnavailableStatus(quote) : void 0;
4424
+ const option = {
4425
+ // The path, not the amount: the amount moves on every re-quote, and a key that changes would drop a pick.
4426
+ id: heavy ? zdHeavyOptionKey(quote) : hops.map((h2) => `${h2.chainId}:${shortAddress2(h2.address)}`).join(">"),
4427
+ ...typeof quote.label === "string" && quote.label ? { label: quote.label } : {},
4428
+ ...unavailable ? { unavailable } : {},
4429
+ amount,
4430
+ amountRaw: amountRaw.toString(),
4431
+ estimatedDuration: Number(quote.estimatedDuration) || 0,
4432
+ feeUsd: null,
4433
+ ...feeCentibips !== void 0 ? { feeCentibips } : {},
4434
+ ...feeNative ? { feeNative: true } : {},
4435
+ hops,
4436
+ ...quote.entersNetting === true ? { entersNetting: true } : {},
4437
+ ...quote.gasSponsored === true ? { gasSponsored: true } : {}
4438
+ };
4439
+ option.feeUsd = compareFeeUsd(option);
4440
+ return option;
4441
+ }
4442
+ function compareOptionsOf(quote, ctx) {
4443
+ const all = quote.gatewayOptions?.length ? quote.gatewayOptions : [quote];
4444
+ const seen = /* @__PURE__ */ new Set();
4445
+ const byIndex = all.map((q) => {
4446
+ const row = compareOptionOf(q, ctx);
4447
+ if (!row || seen.has(row.id)) return null;
4448
+ seen.add(row.id);
4449
+ return row;
4450
+ });
4451
+ return { options: byIndex.filter((o) => !!o), byIndex };
4452
+ }
4453
+
3293
4454
  // src/core/route.ts
3294
4455
  function routeDeltaLabel(result, quote) {
3295
4456
  if (result.directTransfer) return "~0";
@@ -3310,9 +4471,9 @@ function routeLabelFor(option, destinationToken, result) {
3310
4471
  const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
3311
4472
  return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
3312
4473
  }
3313
- function tokenAt2(tokens, chainId, address) {
3314
- const key = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
3315
- const wanted = isChainAddress(chainId, key) ? chainAddressKey(chainId, key) : null;
4474
+ function tokenAt3(tokens, chainId, address) {
4475
+ const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
4476
+ const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
3316
4477
  if (!wanted || !tokens?.length) return void 0;
3317
4478
  return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
3318
4479
  }
@@ -3334,7 +4495,7 @@ function buildLegs(orders, ctx) {
3334
4495
  const order = orders[index];
3335
4496
  const isLast = index === orders.length - 1;
3336
4497
  const toChainId = Number(order.destinationChainId);
3337
- const askToken = isLast ? ctx.destinationToken : tokenAt2(ctx.tokens, toChainId, order.askToken);
4498
+ const askToken = isLast ? ctx.destinationToken : tokenAt3(ctx.tokens, toChainId, order.askToken);
3338
4499
  const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
3339
4500
  const toTicker = askToken ? tokenTicker(askToken) : "";
3340
4501
  const toDecimals = askToken ? assetDecimals(askToken) : void 0;
@@ -3361,19 +4522,42 @@ function buildLegs(orders, ctx) {
3361
4522
  }
3362
4523
  return legs;
3363
4524
  }
3364
- async function buildRoute({
3365
- option,
3366
- destination,
3367
- destinationToken,
3368
- chains,
3369
- tokens,
3370
- payer,
3371
- fetchQuote,
3372
- solve = solveExactOut,
3373
- amountInRaw,
3374
- compliance
3375
- }) {
4525
+ async function buildRoute(args) {
4526
+ const { option, destination, destinationToken, payer, fetchQuote, amountInRaw } = args;
4527
+ const solve = args.solve ?? solveExactOut;
3376
4528
  const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
4529
+ const route = routeFromResult(args, result);
4530
+ return result.directTransfer ? route : withQuoteOptions(route, args, result, solve === solveExactIn ? "exact-in" : "exact-out");
4531
+ }
4532
+ function withQuoteOptions(route, args, result, mode) {
4533
+ const { option, destination, destinationToken } = args;
4534
+ const quote = result.quote;
4535
+ const { byIndex } = compareOptionsOf(quote, {
4536
+ tokens: args.tokens,
4537
+ from: { chainId: option.chainId, address: option.address, ticker: optionTicker(option) },
4538
+ to: { chainId: Number(destination.chainId), address: destinationToken.address, ticker: tokenTicker(destinationToken), decimals: assetDecimals(destinationToken) }
4539
+ });
4540
+ const selectedIndex = quote.gatewayOptions?.length ? quote.gatewayOptionIndex ?? -1 : 0;
4541
+ const built = [];
4542
+ const refused = /* @__PURE__ */ new Set();
4543
+ (quote.gatewayOptions ?? []).forEach((candidate, index) => {
4544
+ const row = byIndex[index];
4545
+ if (!row || row.unavailable || index === selectedIndex) return;
4546
+ try {
4547
+ built.push({ index, route: routeFromResult(args, resultForOption(result, candidate, mode, destination.chainId)) });
4548
+ } catch {
4549
+ refused.add(index);
4550
+ }
4551
+ });
4552
+ const options = [];
4553
+ byIndex.forEach((row, index) => {
4554
+ if (row) options.push(refused.has(index) ? { ...row, unavailable: "refused-by-widget" } : row);
4555
+ });
4556
+ const selectedOptionId = byIndex[selectedIndex]?.id;
4557
+ const alternatives = built.map(({ index, route: alt }) => ({ ...alt, id: route.id, options, selectedOptionId: byIndex[index].id }));
4558
+ return { ...route, options, ...selectedOptionId ? { selectedOptionId } : {}, ...alternatives.length ? { alternatives } : {} };
4559
+ }
4560
+ function routeFromResult({ option, destination, destinationToken, chains, tokens, routes, payer, compliance }, result) {
3377
4561
  const quote = result.quote;
3378
4562
  const destDecimals = assetDecimals(destinationToken);
3379
4563
  const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
@@ -3448,6 +4632,9 @@ async function buildRoute({
3448
4632
  }
3449
4633
  };
3450
4634
  }
4635
+ if (quote.protocol === "zdheavy") {
4636
+ return buildZdHeavyRoute({ option, destination, destinationToken, chains, tokens: tokens ?? [], routes: routes ?? [], payer, result });
4637
+ }
3451
4638
  const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
3452
4639
  if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
3453
4640
  const sourceChain = chainById(chains, option.chainId);
@@ -3549,12 +4736,201 @@ async function buildRoute({
3549
4736
  };
3550
4737
  }
3551
4738
 
4739
+ // src/core/promotions.ts
4740
+ var CENTIBIPS_PER_UNIT = 1e6;
4741
+ function toToken(raw2) {
4742
+ if (!raw2 || typeof raw2 !== "object") return void 0;
4743
+ const r = raw2;
4744
+ const chainId = Number(r.chainId);
4745
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) return void 0;
4746
+ if (typeof r.address !== "string" || !r.address) return void 0;
4747
+ if (typeof r.symbol !== "string" || !r.symbol) return void 0;
4748
+ return { chainId, address: r.address, symbol: r.symbol };
4749
+ }
4750
+ function parsePromotion(raw2, now = Date.now()) {
4751
+ if (!raw2 || typeof raw2 !== "object") return void 0;
4752
+ const r = raw2;
4753
+ if (typeof r.id !== "string" || !r.id) return void 0;
4754
+ if (r.kind !== "token" && r.kind !== "pair") return void 0;
4755
+ const destination = toToken(r.destination);
4756
+ if (!destination) return void 0;
4757
+ const source = r.kind === "pair" ? toToken(r.source) : void 0;
4758
+ if (r.kind === "pair" && !source) return void 0;
4759
+ const bonusCentibips = Number(r.bonusCentibips);
4760
+ if (!Number.isSafeInteger(bonusCentibips) || bonusCentibips <= 0) return void 0;
4761
+ if (r.fundedBy !== "issuer" && r.fundedBy !== "zerodelta") return void 0;
4762
+ if (typeof r.startsAt !== "string" || typeof r.endsAt !== "string") return void 0;
4763
+ const starts = Date.parse(r.startsAt);
4764
+ const ends = Date.parse(r.endsAt);
4765
+ if (!Number.isFinite(starts) || !Number.isFinite(ends) || !(starts <= now && now < ends)) return void 0;
4766
+ let maxBonusAmount;
4767
+ if (r.maxBonusAmount !== void 0) {
4768
+ if (typeof r.maxBonusAmount !== "string" || !/^[1-9]\d*$/.test(r.maxBonusAmount)) return void 0;
4769
+ maxBonusAmount = r.maxBonusAmount;
4770
+ }
4771
+ return {
4772
+ id: r.id,
4773
+ kind: r.kind,
4774
+ destination,
4775
+ ...source ? { source } : {},
4776
+ bonusCentibips,
4777
+ ...maxBonusAmount ? { maxBonusAmount } : {},
4778
+ fundedBy: r.fundedBy,
4779
+ ...typeof r.funderName === "string" && r.funderName ? { funderName: r.funderName } : {},
4780
+ startsAt: r.startsAt,
4781
+ endsAt: r.endsAt
4782
+ };
4783
+ }
4784
+ function parsePromotions(rows, now = Date.now()) {
4785
+ if (!Array.isArray(rows)) return [];
4786
+ return rows.map((row) => parsePromotion(row, now)).filter((p) => !!p);
4787
+ }
4788
+ function bonusPercentLabel(centibips) {
4789
+ const pct = centibips / 1e4;
4790
+ return `${Number(pct.toFixed(4)).toString()}%`;
4791
+ }
4792
+ function sameAddress(a, b) {
4793
+ return a.startsWith("0x") && b.startsWith("0x") ? a.toLowerCase() === b.toLowerCase() : a === b;
4794
+ }
4795
+ function sameToken(t, chainId, address) {
4796
+ return t.chainId === chainId && sameAddress(t.address, address);
4797
+ }
4798
+ function promotedAssets(promotions) {
4799
+ const bySymbol = /* @__PURE__ */ new Map();
4800
+ for (const p of promotions) {
4801
+ if (p.kind !== "token") continue;
4802
+ const key2 = p.destination.symbol.toUpperCase();
4803
+ const asset = bySymbol.get(key2) ?? { symbol: p.destination.symbol, maxCentibips: 0, networks: [], fundedBy: p.fundedBy };
4804
+ asset.networks.push({ promotion: p, chainId: p.destination.chainId, address: p.destination.address, bonusCentibips: p.bonusCentibips });
4805
+ if (p.bonusCentibips > asset.maxCentibips) {
4806
+ asset.maxCentibips = p.bonusCentibips;
4807
+ asset.fundedBy = p.fundedBy;
4808
+ }
4809
+ bySymbol.set(key2, asset);
4810
+ }
4811
+ const assets = [...bySymbol.values()];
4812
+ for (const a of assets) a.networks.sort((x, y) => y.bonusCentibips - x.bonusCentibips || x.chainId - y.chainId);
4813
+ return assets.sort((a, b) => b.maxCentibips - a.maxCentibips || a.symbol.localeCompare(b.symbol));
4814
+ }
4815
+ function promotionFor(promotions, ends) {
4816
+ let best;
4817
+ for (const p of promotions) {
4818
+ if (!sameToken(p.destination, ends.toChainId, ends.toAddress)) continue;
4819
+ if (p.kind === "pair") {
4820
+ if (!p.source || ends.fromChainId === void 0 || !ends.fromAddress) continue;
4821
+ if (!sameToken(p.source, ends.fromChainId, ends.fromAddress)) continue;
4822
+ }
4823
+ if (!best || p.bonusCentibips > best.bonusCentibips) best = p;
4824
+ }
4825
+ return best;
4826
+ }
4827
+ function pairPromotionsInto(promotions, chainId, address) {
4828
+ return promotions.filter((p) => p.kind === "pair" && sameToken(p.destination, chainId, address));
4829
+ }
4830
+ function estimateBonus(amount, promotion) {
4831
+ if (amount <= 0n) return 0n;
4832
+ const bonus = amount * BigInt(promotion.bonusCentibips) / BigInt(CENTIBIPS_PER_UNIT);
4833
+ if (promotion.maxBonusAmount) {
4834
+ const cap = BigInt(promotion.maxBonusAmount);
4835
+ return bonus > cap ? cap : bonus;
4836
+ }
4837
+ return bonus;
4838
+ }
4839
+ function fundedByLabel(p) {
4840
+ if (p.fundedBy === "zerodelta") return "Funded by ZeroDelta";
4841
+ return p.funderName ? `Funded by ${p.funderName}` : "Issuer-funded bonus";
4842
+ }
4843
+ function parseBonusUnits(value, decimals) {
4844
+ if (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value)) throw new Error("Invalid bonus amount");
4845
+ let [integer = "", fraction = "0"] = value.split(".");
4846
+ const negative = integer.startsWith("-");
4847
+ if (negative) integer = integer.slice(1);
4848
+ fraction = fraction.replace(/(0+)$/, "");
4849
+ if (decimals === 0) {
4850
+ if (Math.round(Number(`.${fraction}`)) === 1) integer = `${BigInt(integer) + 1n}`;
4851
+ fraction = "";
4852
+ } else if (fraction.length > decimals) {
4853
+ const left = fraction.slice(0, decimals - 1);
4854
+ const unit = fraction.slice(decimals - 1, decimals);
4855
+ const right = fraction.slice(decimals);
4856
+ const rounded = Math.round(Number(`${unit}.${right}`));
4857
+ if (rounded > 9) fraction = `${BigInt(left) + 1n}0`.padStart(left.length + 1, "0");
4858
+ else fraction = `${left}${rounded}`;
4859
+ if (fraction.length > decimals) {
4860
+ fraction = fraction.slice(1);
4861
+ integer = `${BigInt(integer) + 1n}`;
4862
+ }
4863
+ fraction = fraction.slice(0, decimals);
4864
+ } else {
4865
+ fraction = fraction.padEnd(decimals, "0");
4866
+ }
4867
+ return BigInt(`${negative ? "-" : ""}${integer}${fraction}`);
4868
+ }
4869
+ var PROMOTION_STABLES = /* @__PURE__ */ new Set([...STABLE_ASSETS, "GHO", "USD0", "USDF"]);
4870
+ function usdStablePair(a, b) {
4871
+ return !!a && !!b && PROMOTION_STABLES.has(a.toUpperCase()) && PROMOTION_STABLES.has(b.toUpperCase());
4872
+ }
4873
+ function decimalString(value, decimals) {
4874
+ const n = typeof value === "number" ? value : Number(value);
4875
+ if (!Number.isFinite(n) || n <= 0) return null;
4876
+ return typeof value === "string" && /^\d*\.?\d+$|^\d+\.?$/.test(value) ? value : n.toFixed(Math.min(decimals, 18));
4877
+ }
4878
+ function bonusFigure(promotion, inputs) {
4879
+ const { destination, quote, typed } = inputs;
4880
+ let base = null;
4881
+ if (quote) {
4882
+ const same2 = quote.chainId === destination.chainId && sameAddress(quote.address, destination.address);
4883
+ if (same2 || usdStablePair(quote.symbol, destination.symbol)) base = decimalString(quote.amount, destination.decimals);
4884
+ }
4885
+ if (base === null && typed && usdStablePair(typed.symbol, destination.symbol)) base = decimalString(typed.amount, destination.decimals);
4886
+ if (base === null) return null;
4887
+ try {
4888
+ const bonus = estimateBonus(parseBonusUnits(base, destination.decimals), promotion);
4889
+ return bonus > 0n ? bonus : null;
4890
+ } catch {
4891
+ return null;
4892
+ }
4893
+ }
4894
+ function insteadFigures(promotion, destination, typed, selectedAmount) {
4895
+ if (!typed) return null;
4896
+ const bonus = bonusFigure(promotion, { destination, typed });
4897
+ const sent = Number(typed.amount);
4898
+ if (bonus === null || !Number.isFinite(sent) || sent <= 0) return null;
4899
+ const total = sent + Number(formatUnits(bonus, destination.decimals, destination.decimals));
4900
+ const more = selectedAmount === null ? null : total - selectedAmount;
4901
+ return { bonus, total, more: more !== null && more > 5e-3 ? more : null };
4902
+ }
4903
+
4904
+ // src/core/quote-request.ts
4905
+ function nativeQuoteRequest(body) {
4906
+ const inputChain = Number(body.fromChainId);
4907
+ const owner = typeof body.owner === "string" && body.owner ? body.owner : void 0;
4908
+ const destinationWallet = typeof body.destinationReceiver === "string" && body.destinationReceiver ? body.destinationReceiver : void 0;
4909
+ const owners = owner ? isSolanaChainId(inputChain) && isSolanaAddress(owner) ? { svm: owner } : { evm: owner } : void 0;
4910
+ const sender = typeof body.sender === "string" ? body.sender : !isSolanaChainId(inputChain) ? owner : void 0;
4911
+ return {
4912
+ inputChain,
4913
+ outputChain: Number(body.toChainId),
4914
+ inputToken: String(body.fromToken ?? ""),
4915
+ outputToken: String(body.toToken ?? ""),
4916
+ inputAmount: String(body.fromAmount ?? ""),
4917
+ ...owners ? { owners } : {},
4918
+ ...destinationWallet ? { destinationWallet } : {},
4919
+ ...sender && owners && destinationWallet ? { sender } : {},
4920
+ // No new deadline, latency limit or subject is invented for EVM quoting. The
4921
+ // gateway derives the subject from owners when this caller has no explicit one.
4922
+ ...body.deadline !== void 0 ? { deadline: String(body.deadline) } : {},
4923
+ ...typeof body.maxTimeSec === "number" ? { maxTimeSec: body.maxTimeSec } : {},
4924
+ ...typeof body.subjectId === "string" ? { subjectId: body.subjectId } : {}
4925
+ };
4926
+ }
4927
+
3552
4928
  // src/core/channel.ts
3553
4929
  var CHANNEL_HEADER = "x-zd-channel";
3554
4930
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
3555
4931
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
3556
4932
  var WIDGET_CHANNEL = "widget";
3557
- var WIDGET_VERSION = "4.18.2" ;
4933
+ var WIDGET_VERSION = "4.20.0" ;
3558
4934
  var MAX_CHANNEL_VERSION_LEN = 32;
3559
4935
  function sanitizeVersion(raw2) {
3560
4936
  const v = String(raw2).trim();
@@ -3591,6 +4967,20 @@ function isReportableSubmission(report) {
3591
4967
  return typeof wallet === "string" && /^0x[0-9a-fA-F]{40}$/.test(wallet);
3592
4968
  }
3593
4969
 
4970
+ // src/core/quote-refusals.ts
4971
+ var GATE_REFUSALS = /* @__PURE__ */ new Set(["ROUTE_UNHEALTHY", "ROUTE_UNMEASURED", "GATE_UNAVAILABLE"]);
4972
+ function quoteRefusalCopy(code) {
4973
+ 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;
4974
+ }
4975
+ var DETERMINISTIC_REFUSALS = /* @__PURE__ */ new Set(["ROUTE_UNHEALTHY", "ROUTE_UNMEASURED", "ROUTE_BLOCKED", "PAIR_HALTED", "PROTOCOL_DISABLED"]);
4976
+ var TRANSIENT_REFUSALS = /* @__PURE__ */ new Set(["GATE_UNAVAILABLE", "MARKET_HALTED"]);
4977
+ function gateRefusalRetryable(code) {
4978
+ if (!code) return void 0;
4979
+ if (DETERMINISTIC_REFUSALS.has(code)) return false;
4980
+ if (TRANSIENT_REFUSALS.has(code)) return true;
4981
+ return void 0;
4982
+ }
4983
+
3594
4984
  // src/core/api.ts
3595
4985
  function apiError(message, props = {}) {
3596
4986
  const err2 = new Error(message);
@@ -3646,7 +5036,7 @@ function classifyQuoteError(error) {
3646
5036
  function amountFieldError(error) {
3647
5037
  const fieldErrors = error?.fieldErrors;
3648
5038
  if (!Array.isArray(fieldErrors)) return null;
3649
- const entry = fieldErrors.find((e) => e && typeof e === "object" && e.field === "fromAmount" && typeof e.message === "string");
5039
+ const entry = fieldErrors.find((e) => e && typeof e === "object" && (e.field === "fromAmount" || e.field === "inputAmount") && typeof e.message === "string");
3650
5040
  const message = entry ? sanitizeMessage(entry.message, "") : "";
3651
5041
  return message || null;
3652
5042
  }
@@ -3654,6 +5044,8 @@ function nowFresh(entry) {
3654
5044
  return !!entry && Date.now() - entry.at < API_CACHE_TTL_MS;
3655
5045
  }
3656
5046
  function isTransientQuoteError(error) {
5047
+ const gate = gateRefusalRetryable(error?.code);
5048
+ if (gate !== void 0) return gate;
3657
5049
  if (error?.code === "BRIDGE_RATE_LIMITED" || Array.isArray(error?.fieldErrors) && error.fieldErrors.length > 0) return false;
3658
5050
  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 || "");
3659
5051
  }
@@ -3662,7 +5054,7 @@ function wait(ms) {
3662
5054
  }
3663
5055
  var PAGE_LIMIT = 500;
3664
5056
  var MAX_PAGES = 10;
3665
- var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, inflight: /* @__PURE__ */ new Map() });
5057
+ var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, promotions: null, inflight: /* @__PURE__ */ new Map() });
3666
5058
  var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
3667
5059
  function registryCacheFor(scope) {
3668
5060
  if (!scope) return newRegistryCache();
@@ -3724,9 +5116,10 @@ function createApiClient(cfg) {
3724
5116
  }
3725
5117
  }
3726
5118
  if (!response.ok) {
3727
- throw apiError(apiMessage(json, `ZeroDelta request failed (${response.status}).`), {
5119
+ const code = json?.error?.code || json?.code || (response.status >= 502 ? "gateway_timeout" : "api_error");
5120
+ throw apiError(quoteRefusalCopy(code) ?? apiMessage(json, `ZeroDelta request failed (${response.status}).`), {
3728
5121
  status: response.status,
3729
- code: json?.error?.code || json?.code || (response.status >= 502 ? "gateway_timeout" : "api_error"),
5122
+ code,
3730
5123
  fieldErrors: json?.error?.fieldErrors || json?.fieldErrors,
3731
5124
  limits: json?.error?.limits || json?.limits,
3732
5125
  reasons: json?.error?.reasons || json?.reasons
@@ -3819,6 +5212,20 @@ function createApiClient(cfg) {
3819
5212
  return value;
3820
5213
  });
3821
5214
  }
5215
+ function fetchPromotions() {
5216
+ if (nowFresh(cache.promotions)) return Promise.resolve(parsePromotions(cache.promotions.value));
5217
+ return once("promotions", async () => {
5218
+ let value = [];
5219
+ try {
5220
+ const rows = await apiRequest("/promotions", { timeoutMs: 8e3 });
5221
+ value = Array.isArray(rows) ? rows : [];
5222
+ } catch {
5223
+ value = [];
5224
+ }
5225
+ cache.promotions = { at: Date.now(), value };
5226
+ return parsePromotions(value);
5227
+ });
5228
+ }
3822
5229
  const priceCache = /* @__PURE__ */ new Map();
3823
5230
  async function fetchPrices(symbols) {
3824
5231
  const wanted = [...new Set(symbols.map((s) => String(s || "").toUpperCase()).filter((s) => /^[A-Z0-9]{1,16}$/.test(s)))];
@@ -3849,11 +5256,12 @@ function createApiClient(cfg) {
3849
5256
  return out;
3850
5257
  }
3851
5258
  async function fetchQuote(body, retries = 1) {
5259
+ const request = nativeQuoteRequest(body);
3852
5260
  let lastError;
3853
5261
  for (let attempt = 0; attempt <= retries; attempt += 1) {
3854
5262
  try {
3855
- const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(body), timeoutMs: 18e3 });
3856
- return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
5263
+ const quote = await apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
5264
+ return normalizeQuoteResponse(quote, request);
3857
5265
  } catch (error) {
3858
5266
  lastError = error;
3859
5267
  if (attempt >= retries || !isTransientQuoteError(error)) throw error;
@@ -3867,10 +5275,10 @@ function createApiClient(cfg) {
3867
5275
  if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
3868
5276
  const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
3869
5277
  if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
3870
- const key = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
3871
- const hit = screenCache.get(key);
5278
+ const key2 = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
5279
+ const hit = screenCache.get(key2);
3872
5280
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
3873
- const inflight = screenInflight.get(key);
5281
+ const inflight = screenInflight.get(key2);
3874
5282
  if (inflight) return inflight;
3875
5283
  const request = apiRequest("/screen/wallet", {
3876
5284
  method: "POST",
@@ -3881,12 +5289,12 @@ function createApiClient(cfg) {
3881
5289
  throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
3882
5290
  }
3883
5291
  const value = { ...screen, address: screen.address || addr };
3884
- screenCache.set(key, { at: Date.now(), value });
5292
+ screenCache.set(key2, { at: Date.now(), value });
3885
5293
  return value;
3886
5294
  }).finally(() => {
3887
- screenInflight.delete(key);
5295
+ screenInflight.delete(key2);
3888
5296
  });
3889
- screenInflight.set(key, request);
5297
+ screenInflight.set(key2, request);
3890
5298
  return request;
3891
5299
  }
3892
5300
  async function reportSubmission(report) {
@@ -3909,7 +5317,7 @@ function createApiClient(cfg) {
3909
5317
  return false;
3910
5318
  }
3911
5319
  }
3912
- return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchQuote, screenWallet, reportSubmission, apiBase };
5320
+ return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchPromotions, fetchQuote, screenWallet, reportSubmission, apiBase };
3913
5321
  }
3914
5322
 
3915
5323
  // src/core/plan.ts
@@ -3972,9 +5380,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
3972
5380
  const balanceTargets = [];
3973
5381
  const seenTargets = /* @__PURE__ */ new Set();
3974
5382
  for (const option of options) {
3975
- const key = optionBalanceKey(option);
3976
- if (seenTargets.has(key)) continue;
3977
- seenTargets.add(key);
5383
+ const key2 = optionBalanceKey(option);
5384
+ if (seenTargets.has(key2)) continue;
5385
+ seenTargets.add(key2);
3978
5386
  balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
3979
5387
  }
3980
5388
  const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
@@ -3986,9 +5394,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
3986
5394
  for (const raw2 of [payer, destination.address]) {
3987
5395
  const addr = String(raw2 || "").trim();
3988
5396
  if (!addr) continue;
3989
- const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
3990
- if (seenParty.has(key)) continue;
3991
- seenParty.add(key);
5397
+ const key2 = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
5398
+ if (seenParty.has(key2)) continue;
5399
+ seenParty.add(key2);
3992
5400
  parties.push(addr);
3993
5401
  }
3994
5402
  try {
@@ -4035,6 +5443,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
4035
5443
  destinationToken,
4036
5444
  chains,
4037
5445
  tokens,
5446
+ routes,
4038
5447
  payer,
4039
5448
  fetchQuote: api.fetchQuote,
4040
5449
  compliance: option.direct ? directCompliance ?? void 0 : void 0
@@ -4095,7 +5504,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
4095
5504
  (o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
4096
5505
  );
4097
5506
  if (!option) throw new Error("That funding option is not available for this payment right now.");
4098
- return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
5507
+ return buildRoute({ option, destination, destinationToken, chains, tokens, routes, payer, fetchQuote: api.fetchQuote });
4099
5508
  }
4100
5509
 
4101
5510
  // src/core/swap.ts
@@ -4103,13 +5512,13 @@ function validateSwap(swap = {}) {
4103
5512
  const fromChainId = Number(swap.fromChainId);
4104
5513
  const toChainId = Number(swap.toChainId);
4105
5514
  const fromToken = symbolKey(swap.fromToken);
4106
- const toToken = symbolKey(swap.toToken);
5515
+ const toToken2 = symbolKey(swap.toToken);
4107
5516
  if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
4108
5517
  if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
4109
- if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken)) throw new Error("Unsupported swap asset.");
5518
+ if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken2)) throw new Error("Unsupported swap asset.");
4110
5519
  const amountIn = normalizeDecimalText(swap.amountIn);
4111
5520
  if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
4112
- return { fromChainId, toChainId, fromToken, toToken, amountIn };
5521
+ return { fromChainId, toChainId, fromToken, toToken: toToken2, amountIn };
4113
5522
  }
4114
5523
  function viaOf(quote, tokens) {
4115
5524
  const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
@@ -4159,7 +5568,7 @@ async function quoteSwapPreview(api, swap, owner) {
4159
5568
  async function buildSwapPlan(api, swap, payer, wallet = {}) {
4160
5569
  const v = validateSwap(swap);
4161
5570
  const account = assertAddress(payer, "Swap wallet");
4162
- const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
5571
+ const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
4163
5572
  const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
4164
5573
  const destToken = findToken(tokens, v.toChainId, v.toToken);
4165
5574
  if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
@@ -4182,7 +5591,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4182
5591
  direct: false
4183
5592
  };
4184
5593
  const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
4185
- const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
5594
+ const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, routes, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
4186
5595
  if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
4187
5596
  route.recommended = true;
4188
5597
  return {
@@ -4203,88 +5612,6 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
4203
5612
  };
4204
5613
  }
4205
5614
 
4206
- // src/core/validate-tx.ts
4207
- var lower = (v) => String(v || "").toLowerCase();
4208
- function isHexAddress(value) {
4209
- return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
4210
- }
4211
- function isHexData(value) {
4212
- return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value || "0x"));
4213
- }
4214
- function isHexQuantity(value) {
4215
- return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
4216
- }
4217
- function dataWord(data, index) {
4218
- const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
4219
- return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
4220
- }
4221
- function dataAddress(data, index) {
4222
- const word2 = dataWord(data, index);
4223
- return word2 ? `0x${word2.slice(24)}` : "";
4224
- }
4225
- function dataUint(data, index) {
4226
- const word2 = dataWord(data, index);
4227
- return word2 ? BigInt(`0x${word2}`) : null;
4228
- }
4229
- function rawEquals(value, expected) {
4230
- try {
4231
- return value === BigInt(expected || "0");
4232
- } catch {
4233
- return false;
4234
- }
4235
- }
4236
- function planMsgValueHex(route) {
4237
- try {
4238
- const raw2 = route?.quote?.msgValue;
4239
- if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
4240
- return "0x" + BigInt(raw2).toString(16);
4241
- } catch {
4242
- return null;
4243
- }
4244
- }
4245
- function validatePlannedTransaction(tx, route, expectedRecipient) {
4246
- if (!tx || tx.mock) return true;
4247
- if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
4248
- const data = String(tx.data || "0x").toLowerCase();
4249
- const selector = data.slice(0, 10);
4250
- const value = lower(tx.value || "0x0");
4251
- if (tx.kind === "transfer") {
4252
- if (value !== "0x0") return false;
4253
- return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
4254
- }
4255
- if (tx.kind === "approve") {
4256
- if (value !== "0x0") return false;
4257
- 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);
4258
- }
4259
- if (tx.kind === "submitOrder") {
4260
- const expected = planMsgValueHex(route);
4261
- if (expected === null || value !== lower(expected)) return false;
4262
- if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
4263
- const decoded = decodeSubmitOrderCalldata(data);
4264
- if (!decoded) return false;
4265
- const first = decoded.orders[0];
4266
- const last = decoded.orders[decoded.orders.length - 1];
4267
- 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));
4268
- }
4269
- return false;
4270
- }
4271
- function solanaDeliveryMatches(encoded, recipient2, mint) {
4272
- try {
4273
- return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
4274
- } catch {
4275
- return false;
4276
- }
4277
- }
4278
- async function allowanceCovers(tx, account, ethCall) {
4279
- if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
4280
- try {
4281
- const raw2 = await ethCall(tx.token, encodeAllowance(account, tx.spender));
4282
- return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
4283
- } catch {
4284
- return false;
4285
- }
4286
- }
4287
-
4288
5615
  // src/core/intent-schema.ts
4289
5616
  var STABLEGENIE_INTENT_VERSION = 1;
4290
5617
  var STABLEGENIE_INTENT_TTL_MS = 5 * 60 * 1e3;
@@ -4489,9 +5816,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4489
5816
  const seen = /* @__PURE__ */ new Set();
4490
5817
  for (const target of targets) {
4491
5818
  if (!target || !isAddress(target.tokenAddress)) continue;
4492
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4493
- if (seen.has(key)) continue;
4494
- seen.add(key);
5819
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5820
+ if (seen.has(key2)) continue;
5821
+ seen.add(key2);
4495
5822
  const chainId = Number(target.chainId);
4496
5823
  const group = groups.get(chainId) || [];
4497
5824
  group.push(target);
@@ -4500,8 +5827,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4500
5827
  function record(target, hex) {
4501
5828
  if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
4502
5829
  const raw2 = BigInt(hex || "0x0").toString();
4503
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
4504
- out[key] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
5830
+ const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
5831
+ out[key2] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
4505
5832
  return true;
4506
5833
  }
4507
5834
  async function readOne(rpcUrl, target) {
@@ -4547,7 +5874,18 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
4547
5874
  return null;
4548
5875
  }
4549
5876
  }
4550
- return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance };
5877
+ async function readZdHeavySubmitFee(chainId, to, data) {
5878
+ try {
5879
+ const override = rpcOverrides[Number(chainId)];
5880
+ const rpc = override && /^https?:\/\//i.test(override) ? override : BUNDLED_RPC[Number(chainId)];
5881
+ if (!rpc) return void 0;
5882
+ const result = await rpcCall(rpc, "eth_call", [{ to, data: quoteSubmitCalldata(data) }, "latest"]);
5883
+ return typeof result === "string" && /^0x[0-9a-fA-F]{64}$/.test(result) ? BigInt(result) : void 0;
5884
+ } catch {
5885
+ return void 0;
5886
+ }
5887
+ }
5888
+ return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance, readZdHeavySubmitFee };
4551
5889
  }
4552
5890
 
4553
5891
  // src/core/config.ts
@@ -4668,6 +6006,7 @@ function createEngine(config = {}) {
4668
6006
  fetchRouteHealth: api.fetchRouteHealth,
4669
6007
  fetchQuote: api.fetchQuote,
4670
6008
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
6009
+ fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
4671
6010
  fetchCatalogue: async (allowedAssets, product, options) => {
4672
6011
  const [chains, registryTokens, routes, health, vaults] = await Promise.all([
4673
6012
  api.fetchChains().catch(() => []),
@@ -4737,6 +6076,7 @@ exports.CANONICAL_DECIMALS = CANONICAL_DECIMALS;
4737
6076
  exports.CANONICAL_ESCROW = CANONICAL_ESCROW;
4738
6077
  exports.CANONICAL_INBOUND_BRIDGE = CANONICAL_INBOUND_BRIDGE;
4739
6078
  exports.CANONICAL_SOLANA_PROGRAM = CANONICAL_SOLANA_PROGRAM;
6079
+ exports.CENTIBIPS_PER_UNIT = CENTIBIPS_PER_UNIT;
4740
6080
  exports.CHAIN_DISPLAY_NAMES = CHAIN_DISPLAY_NAMES;
4741
6081
  exports.COMPLIANCE_CHECK_ORDER = COMPLIANCE_CHECK_ORDER;
4742
6082
  exports.COMPLIANCE_DENY_LABEL = COMPLIANCE_DENY_LABEL;
@@ -4753,6 +6093,7 @@ exports.LZ_FEE_BUFFER_BPS = LZ_FEE_BUFFER_BPS;
4753
6093
  exports.MAX_LZ_MSG_VALUE_WEI = MAX_LZ_MSG_VALUE_WEI;
4754
6094
  exports.MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = MAX_LZ_MSG_VALUE_WEI_BY_CHAIN;
4755
6095
  exports.MAX_QUOTE_CANDIDATES = MAX_QUOTE_CANDIDATES;
6096
+ exports.MAX_QUOTE_CARDS = MAX_QUOTE_CARDS;
4756
6097
  exports.MAX_SAME_CLASS_PAY_BPS = MAX_SAME_CLASS_PAY_BPS;
4757
6098
  exports.MAX_UINT64 = MAX_UINT64;
4758
6099
  exports.NO_PARTNER_ID = NO_PARTNER_ID;
@@ -4779,7 +6120,12 @@ exports.TOKEN_PROGRAM = TOKEN_PROGRAM;
4779
6120
  exports.TRACKING = TRACKING;
4780
6121
  exports.TRADEABLE_RWA_ASSETS = TRADEABLE_RWA_ASSETS;
4781
6122
  exports.TUNABLE_CATEGORIES = TUNABLE_CATEGORIES;
6123
+ exports.WAIT_MAX_SEC = WAIT_MAX_SEC;
6124
+ exports.WAIT_MIN_SEC = WAIT_MIN_SEC;
6125
+ exports.WAIT_POSITIONS = WAIT_POSITIONS;
6126
+ exports.WAIT_STEP_SEC = WAIT_STEP_SEC;
4782
6127
  exports.WALLET_HISTORY_LIMIT = WALLET_HISTORY_LIMIT;
6128
+ exports.ZD_HEAVY_KEY_PREFIX = ZD_HEAVY_KEY_PREFIX;
4783
6129
  exports.ZERO_ADDRESS = ZERO_ADDRESS;
4784
6130
  exports.addressWord = addressWord;
4785
6131
  exports.allowanceCovers = allowanceCovers;
@@ -4799,7 +6145,10 @@ exports.base58Decode = base58Decode;
4799
6145
  exports.base58Encode = base58Encode;
4800
6146
  exports.base64Decode = base64Decode;
4801
6147
  exports.base64Encode = base64Encode;
6148
+ exports.bestOutputOption = bestOutputOption;
4802
6149
  exports.blockLabelFor = blockLabelFor;
6150
+ exports.bonusFigure = bonusFigure;
6151
+ exports.bonusPercentLabel = bonusPercentLabel;
4803
6152
  exports.brokenLaneFor = brokenLaneFor;
4804
6153
  exports.brokenLaneReason = brokenLaneReason;
4805
6154
  exports.buildCatalogue = buildCatalogue;
@@ -4823,7 +6172,14 @@ exports.checkSolanaPlan = checkSolanaPlan;
4823
6172
  exports.checkSolanaProgram = checkSolanaProgram;
4824
6173
  exports.checkSolanaReceiver = checkSolanaReceiver;
4825
6174
  exports.checkSolanaRouteBuffer = checkSolanaRouteBuffer;
6175
+ exports.clampWait = clampWait;
4826
6176
  exports.classifyQuoteError = classifyQuoteError;
6177
+ exports.compareAmount = compareAmount;
6178
+ exports.compareDuration = compareDuration;
6179
+ exports.compareFeeUsd = compareFeeUsd;
6180
+ exports.compareHops = compareHops;
6181
+ exports.compareOptionOf = compareOptionOf;
6182
+ exports.compareOptionsOf = compareOptionsOf;
4827
6183
  exports.complianceChecks = complianceChecks;
4828
6184
  exports.complianceControlsEvaluated = complianceControlsEvaluated;
4829
6185
  exports.complianceControlsLine = complianceControlsLine;
@@ -4831,6 +6187,7 @@ exports.complianceReasonHead = complianceReasonHead;
4831
6187
  exports.complianceReasonTag = complianceReasonTag;
4832
6188
  exports.complianceTagOf = complianceTagOf;
4833
6189
  exports.complianceView = complianceView;
6190
+ exports.cornerTags = cornerTags;
4834
6191
  exports.cosignSolanaEvent = cosignSolanaEvent;
4835
6192
  exports.counterpartTokens = counterpartTokens;
4836
6193
  exports.createApiClient = createApiClient;
@@ -4851,12 +6208,15 @@ exports.encodeBalanceOf = encodeBalanceOf;
4851
6208
  exports.encodeNextSolanaOrders = encodeNextSolanaOrders;
4852
6209
  exports.encodeSubmitOrder = encodeSubmitOrder;
4853
6210
  exports.encodeTransfer = encodeTransfer;
6211
+ exports.estimateBonus = estimateBonus;
4854
6212
  exports.exceedsLaneLimit = exceedsLaneLimit;
4855
6213
  exports.executableRoutes = executableRoutes;
4856
6214
  exports.executeSolanaPlan = executeSolanaPlan;
4857
6215
  exports.executeSolanaPlanStaged = executeSolanaPlanStaged;
4858
6216
  exports.executionChainIds = executionChainIds;
4859
6217
  exports.expectedSolanaDelivery = expectedSolanaDelivery;
6218
+ exports.extraVsFastest = extraVsFastest;
6219
+ exports.fastestOption = fastestOption;
4860
6220
  exports.fetchDelivery = fetchDelivery;
4861
6221
  exports.fetchPaymentPlan = fetchPaymentPlan;
4862
6222
  exports.fetchWalletHistory = fetchWalletHistory;
@@ -4867,6 +6227,7 @@ exports.foldTicker = foldTicker;
4867
6227
  exports.formatJurisdiction = formatJurisdiction;
4868
6228
  exports.formatNative = formatNative;
4869
6229
  exports.formatUnits = formatUnits;
6230
+ exports.fundedByLabel = fundedByLabel;
4870
6231
  exports.hasReachableDestination = hasReachableDestination;
4871
6232
  exports.hexBytes = hexBytes;
4872
6233
  exports.hexToSolanaKey = hexToSolanaKey;
@@ -4874,6 +6235,7 @@ exports.historyEntryFromOrder = historyEntryFromOrder;
4874
6235
  exports.historyKey = historyKey;
4875
6236
  exports.hubDeliverableSymbols = hubDeliverableSymbols;
4876
6237
  exports.humanizeComplianceReason = humanizeComplianceReason;
6238
+ exports.insteadFigures = insteadFigures;
4877
6239
  exports.isAddress = isAddress;
4878
6240
  exports.isChainAddress = isChainAddress;
4879
6241
  exports.isDeliverable = isDeliverable;
@@ -4911,16 +6273,25 @@ exports.normalizeDelivery = normalizeDelivery;
4911
6273
  exports.normalizeOrderRequest = normalizeOrderRequest;
4912
6274
  exports.normalizeOrderRequests = normalizeOrderRequests;
4913
6275
  exports.overwriteBlockhash = overwriteBlockhash;
6276
+ exports.pairPromotionsInto = pairPromotionsInto;
6277
+ exports.parity = parity;
4914
6278
  exports.parseAddressLookupTable = parseAddressLookupTable;
4915
6279
  exports.parseAllowedApiBase = parseAllowedApiBase;
6280
+ exports.parsePromotion = parsePromotion;
6281
+ exports.parsePromotions = parsePromotions;
4916
6282
  exports.parseSolanaTransaction = parseSolanaTransaction;
4917
6283
  exports.parseUnitsDecimal = parseUnitsDecimal;
6284
+ exports.pickForWait = pickForWait;
4918
6285
  exports.placeSignature = placeSignature;
4919
6286
  exports.planErrorSummary = planErrorSummary;
4920
6287
  exports.planMsgValueHex = planMsgValueHex;
4921
6288
  exports.pollSolanaConfirmation = pollSolanaConfirmation;
4922
6289
  exports.previewSolanaSource = previewSolanaSource;
6290
+ exports.priceCompareOptions = priceCompareOptions;
4923
6291
  exports.productAssets = productAssets;
6292
+ exports.promotedAssets = promotedAssets;
6293
+ exports.promotionFor = promotionFor;
6294
+ exports.proposedWait = proposedWait;
4924
6295
  exports.quotePartnerId = quotePartnerId;
4925
6296
  exports.quotePayOption = quotePayOption;
4926
6297
  exports.quoteSolanaSource = quoteSolanaSource;
@@ -4934,13 +6305,19 @@ exports.resolveConfig = resolveConfig;
4934
6305
  exports.resolveSolanaKeys = resolveSolanaKeys;
4935
6306
  exports.resolveSwapReceiver = resolveSwapReceiver;
4936
6307
  exports.resolveVaultIcon = resolveVaultIcon;
6308
+ exports.resultForOption = resultForOption;
6309
+ exports.routeBadges = routeBadges;
4937
6310
  exports.routeNativeValue = routeNativeValue;
6311
+ exports.routeShapeLabel = routeShapeLabel;
4938
6312
  exports.safeTicker = safeTicker;
6313
+ exports.sameAddress = sameAddress;
4939
6314
  exports.scaleDecimals = scaleDecimals;
4940
6315
  exports.screeningOutcomeOf = screeningOutcomeOf;
6316
+ exports.selectableOptions = selectableOptions;
4941
6317
  exports.serializeSolanaTransaction = serializeSolanaTransaction;
4942
6318
  exports.sha256 = sha256;
4943
6319
  exports.simulateSolanaCost = simulateSolanaCost;
6320
+ exports.snapWait = snapWait;
4944
6321
  exports.solanaBridgeOf = solanaBridgeOf;
4945
6322
  exports.solanaDestinationAsset = solanaDestinationAsset;
4946
6323
  exports.solanaKeyBytes = solanaKeyBytes;
@@ -4964,6 +6341,7 @@ exports.txMatchesPlan = txMatchesPlan;
4964
6341
  exports.uint64Word = uint64Word;
4965
6342
  exports.uintWord = uintWord;
4966
6343
  exports.unattributedComplianceReasons = unattributedComplianceReasons;
6344
+ exports.usdStablePair = usdStablePair;
4967
6345
  exports.validateDestination = validateDestination;
4968
6346
  exports.validatePlannedTransaction = validatePlannedTransaction;
4969
6347
  exports.validateSwap = validateSwap;
@@ -4972,4 +6350,11 @@ exports.verifySolanaSubmit = verifySolanaSubmit;
4972
6350
  exports.verifySolanaTransaction = verifySolanaTransaction;
4973
6351
  exports.verifySubmit = verifySolanaSubmit;
4974
6352
  exports.verifyTransaction = verifySolanaTransaction;
6353
+ exports.visibleOptions = visibleOptions;
6354
+ exports.waitFraction = waitFraction;
6355
+ exports.waitFromFraction = waitFromFraction;
6356
+ exports.waitLabel = waitLabel;
6357
+ exports.waitScaleFor = waitScaleFor;
4975
6358
  exports.withVaultArtwork = withVaultArtwork;
6359
+ exports.zdHeavyOptionKey = zdHeavyOptionKey;
6360
+ exports.zdHeavyUnavailableStatus = zdHeavyUnavailableStatus;