@glacislabs/stablegenie-zerodelta 4.20.1 → 4.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -593,13 +593,22 @@ var MAX_STEPS = 8;
593
593
  function isZdHeavy(r, steps) {
594
594
  return r.protocol === "zdheavy" || steps.some((s) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP);
595
595
  }
596
+ var FILL_EVIDENCE = /* @__PURE__ */ new Set(["filled", "consumed", "step_executed", "paid_out", "delivered"]);
597
+ function ownerCancelServedAsDeliveryFailure(steps) {
598
+ const txHash = (s) => typeof s.txHash === "string" && /^0x[0-9a-fA-F]{64}$/.test(s.txHash);
599
+ const anyTx = (s) => typeof s.txHash === "string" && s.txHash.length > 0;
600
+ const cancelTx = steps.some((s) => s.stepName === "cancelled" && txHash(s));
601
+ const refunded = steps.some((s) => s.stepName === "refunded" && word(s.stepStatus) === "recovered" && txHash(s));
602
+ const filled = steps.some((s) => FILL_EVIDENCE.has(String(s.stepName)) && word(s.stepStatus) === "completed" && anyTx(s));
603
+ return cancelTx && refunded && !filled;
604
+ }
596
605
  function zdHeavyDelivery(own, rawSteps) {
597
606
  const named = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string");
598
607
  const lite = (name) => named.some((s) => Number(s.stepNumber ?? 0) < ZDH_FIRST_STEP && s.stepName === name && s.stepStatus === "completed");
599
608
  const events = named.map((s, i) => ({ s, i })).filter(({ s }) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP).sort((a, b) => (Date.parse(String(a.s.blockTimestamp ?? "")) || 0) - (Date.parse(String(b.s.blockTimestamp ?? "")) || 0) || a.i - b.i).map(({ s }) => s);
600
609
  const has = (name) => events.some((e) => e.stepName === name);
601
610
  const cancelled = has("cancelled");
602
- const status = PROGRESS.has(own) && has("paid_out") && !cancelled ? "delivered" : own;
611
+ const status = own === "delivery_failed" && ownerCancelServedAsDeliveryFailure(named) ? "cancelled" : PROGRESS.has(own) && has("paid_out") && !cancelled ? "delivered" : own;
603
612
  const steps = [];
604
613
  const push = (name, done) => {
605
614
  const last = steps[steps.length - 1];
@@ -690,7 +699,7 @@ function useDelivery(engine, hash2) {
690
699
  let unanswered = 0;
691
700
  const started2 = Date.now();
692
701
  setState({ hash: hash2, value: TRACKING });
693
- const schedule = () => {
702
+ const schedule2 = () => {
694
703
  if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) {
695
704
  if (waitsOnOwner) return;
696
705
  return setState({ hash: hash2, value: UNAVAILABLE });
@@ -699,18 +708,18 @@ function useDelivery(engine, hash2) {
699
708
  };
700
709
  const tick = async () => {
701
710
  timer2 = void 0;
702
- if (hidden()) return schedule();
711
+ if (hidden()) return schedule2();
703
712
  const next = await engine.trackDelivery(hash2);
704
713
  if (!alive) return;
705
714
  if (next.phase === "tracking") {
706
715
  if (!answered && ++unanswered >= UNANSWERED_LIMIT) return setState({ hash: hash2, value: UNAVAILABLE });
707
- return schedule();
716
+ return schedule2();
708
717
  }
709
718
  answered = true;
710
719
  waitsOnOwner = next.phase === "attention";
711
720
  setState({ hash: hash2, value: next });
712
721
  if (next.phase === "delivered" || next.phase === "failed") return;
713
- schedule();
722
+ schedule2();
714
723
  };
715
724
  const onVisible2 = () => {
716
725
  if (!alive || hidden() || !timer2) return;
@@ -749,8 +758,8 @@ function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
749
758
  case "delivered":
750
759
  return "Delivered";
751
760
  case "failed":
752
- if (delivery.status === "cancelled" && delivery.refunded) return "Cancelled \u2014 refunded to the owner";
753
- return delivery.status === "cancelled" ? "Cancelled \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
761
+ if (delivery.status === "cancelled" && delivery.refunded) return "Cancellation and refund reported by ZeroDelta";
762
+ return delivery.status === "cancelled" ? "Cancellation reported \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
754
763
  case "attention":
755
764
  return delivery.status === "cancel_pending" ? "Being cancelled \u2014 not delivered" : "Waiting to be claimed \u2014 open the transaction";
756
765
  case "in-progress": {
@@ -1839,6 +1848,7 @@ function hubDeliverableSymbols(tokens, execution) {
1839
1848
  function isSourceToken(token, ctx) {
1840
1849
  const chainId = Number(token.chainId);
1841
1850
  if (!ctx.sourceChains.has(chainId)) return false;
1851
+ if (ctx.zdHeavySources?.has(tokenKey(chainId, token.address))) return true;
1842
1852
  return ctx.execution.has(chainId) || !isKnownUnbridgeable(token.bridge) && ctx.source.has(tokenKey(chainId, token.address));
1843
1853
  }
1844
1854
  function directLaneOK(token, source2, lanes) {
@@ -1857,6 +1867,7 @@ function laneLimitFor(token, source2, limitedLanes2) {
1857
1867
  }
1858
1868
  function destinationAvailability(token, ctx, source2) {
1859
1869
  if (brokenLaneFor(token, source2 ?? void 0, ctx.brokenLanes)) return "unreachable";
1870
+ if (source2 && ctx.zdHeavyLanes?.has(laneKey(source2.chainId, source2.address, token.chainId, token.address))) return "available";
1860
1871
  if (directLaneOK(token, source2 ?? void 0, ctx.lanes)) {
1861
1872
  if (ctx.execution.has(Number(token.chainId))) return "available";
1862
1873
  if (token.isChainedDestination === true) return "available";
@@ -1875,6 +1886,7 @@ function hasReachableDestination(source2, catalogue, ctx) {
1875
1886
  }
1876
1887
  function buildCatalogue(input) {
1877
1888
  const { chains, tokens, routes, supportedChainIds, brokenLanes } = input;
1889
+ const zdHeavy = (input.zdHeavyRoutes ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r) && r.isEnabled !== false && r.isQuotable === true);
1878
1890
  const product = input.product ?? "stable";
1879
1891
  const universe = productAssets(product);
1880
1892
  const allowedAssets = input.allowedAssets ? new Set([...input.allowedAssets].filter((a) => universe.has(a))) : universe;
@@ -1882,7 +1894,10 @@ function buildCatalogue(input) {
1882
1894
  const registryChainIds = new Set(enabledChains.map((c) => Number(c.chainId)));
1883
1895
  const sourceChains = new Set([...registryChainIds].filter((id) => supportedChainIds.has(id)));
1884
1896
  const execution = executionChainIds(enabledChains);
1885
- const projected = product === "rwa" ? routes.filter((route) => route.isEnabled !== false) : executableRoutes(routes);
1897
+ const projected = [...product === "rwa" ? routes.filter((route) => route.isEnabled !== false) : executableRoutes(routes), ...zdHeavy];
1898
+ const zdHeavyLanes = laneKeys(zdHeavy);
1899
+ const zdHeavySources = sourceKeys(zdHeavy);
1900
+ const zdHeavyKeys = /* @__PURE__ */ new Set([...zdHeavySources, ...destinationKeys(zdHeavy)]);
1886
1901
  const source2 = sourceKeys(projected);
1887
1902
  const destination = destinationKeys(projected);
1888
1903
  const lanes = laneKeys(projected);
@@ -1897,14 +1912,15 @@ function buildCatalogue(input) {
1897
1912
  if (!chainIds.has(chainId)) return false;
1898
1913
  if (product === "rwa") return true;
1899
1914
  if (execution.has(chainId) || token.isChainedDestination === true) return true;
1900
- if (!isExecutableBridge(token)) return false;
1901
1915
  const key2 = tokenKey(token.chainId, token.address);
1916
+ if (zdHeavyKeys.has(key2)) return true;
1917
+ if (!isExecutableBridge(token)) return false;
1902
1918
  return source2.has(key2) || destination.has(key2);
1903
1919
  });
1904
1920
  const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
1905
1921
  const catalogue = ready ? projectedCatalogue : allowed;
1906
1922
  const hubSymbols = hubDeliverableSymbols(catalogue, execution);
1907
- const ctx = { source: source2, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
1923
+ const ctx = { source: source2, destination, lanes, execution, sourceChains, hubSymbols, ...zdHeavy.length ? { zdHeavyLanes, zdHeavySources } : {}, ...brokenLanes ? { brokenLanes } : {} };
1908
1924
  const sellable = (token) => product !== "rwa" || isSellableRwa(token);
1909
1925
  const sources2 = ready ? catalogue.filter((token) => sellable(token) && isSourceToken(token, ctx) && hasReachableDestination(token, catalogue, ctx)) : (
1910
1926
  // Unprojected: the only rule we can still apply with confidence is the escrow-chain bound,
@@ -2560,7 +2576,10 @@ function historyEntryFromOrder(raw2, tokens) {
2560
2576
  const toAsset = (to?.symbol ?? (str(r.finalToTokenSymbol) || str(r.toTokenSymbol))).slice(0, 10);
2561
2577
  const payAmount = amountOf(str(r.fromTokenRawAmount), from, r.fromTokenDecimals, str(r.fromTokenAmount));
2562
2578
  const receiveAmount = str(r.finalToTokenRawAmount) ? amountOf(str(r.finalToTokenRawAmount), to, r.finalToTokenDecimals, str(r.finalToTokenAmount)) : amountOf(str(r.toTokenRawAmount), to, r.toTokenDecimals, str(r.toTokenAmount));
2563
- const delivery = normalizeDelivery(r).phase;
2579
+ const tracked = normalizeDelivery(r);
2580
+ const delivery = tracked.phase;
2581
+ const protocol = str(r.protocol);
2582
+ const orderId = str(r.orderId);
2564
2583
  const wallet = str(r.wallet);
2565
2584
  const receiver = str(r.destinationReceiver);
2566
2585
  const at = str(r.createdAt) || str(r.submittedAt);
@@ -2582,6 +2601,11 @@ function historyEntryFromOrder(raw2, tokens) {
2582
2601
  status: "submitted",
2583
2602
  at: Number.isNaN(Date.parse(at)) ? (/* @__PURE__ */ new Date(0)).toISOString() : new Date(at).toISOString(),
2584
2603
  delivery: delivery === "tracking" || delivery === "unavailable" ? void 0 : delivery,
2604
+ ...tracked.status && delivery !== "tracking" && delivery !== "unavailable" ? { deliveryStatus: tracked.status.slice(0, 32) } : {},
2605
+ .../^[a-z]{1,16}$/.test(protocol) ? { protocol } : {},
2606
+ // Only a router order id (bytes32) is carried: it is the one thing a recovery call puts in a URL.
2607
+ .../^0x[0-9a-fA-F]{64}$/.test(orderId) ? { orderId } : {},
2608
+ ...r.claimable === true ? { claimable: true } : {},
2585
2609
  legs: [
2586
2610
  {
2587
2611
  index: 1,
@@ -2629,7 +2653,17 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
2629
2653
  if (seen.has(key2)) continue;
2630
2654
  seen.add(key2);
2631
2655
  const known = byHash.get(key2);
2632
- out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
2656
+ out.push(
2657
+ known ? {
2658
+ ...entry,
2659
+ delivery: known.delivery,
2660
+ legs: entry.legs ?? known.legs,
2661
+ deliveryStatus: known.deliveryStatus,
2662
+ protocol: known.protocol,
2663
+ orderId: known.orderId,
2664
+ claimable: known.claimable
2665
+ } : entry
2666
+ );
2633
2667
  }
2634
2668
  for (const [key2, entry] of byHash) if (!seen.has(key2)) out.push(entry);
2635
2669
  return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
@@ -2706,13 +2740,13 @@ function checkNativeFee(route, balance) {
2706
2740
  const shortfall = required > balance ? required - balance : 0n;
2707
2741
  return { required, balance, short: shortfall > 0n, shortfall };
2708
2742
  }
2709
- function nativeFeeShortLabel(check2, symbol) {
2710
- if (!check2.short) return null;
2711
- return `Need ${formatNative(check2.required)} ${symbol} for the bridge fee`;
2743
+ function nativeFeeShortLabel(check3, symbol) {
2744
+ if (!check3.short) return null;
2745
+ return `Need ${formatNative(check3.required)} ${symbol} for the bridge fee`;
2712
2746
  }
2713
- function nativeFeeShortMessage(check2, symbol, chainName3) {
2714
- const need = formatNative(check2.required);
2715
- const have = formatNative(check2.balance ?? 0n);
2747
+ function nativeFeeShortMessage(check3, symbol, chainName3) {
2748
+ const need = formatNative(check3.required);
2749
+ const have = formatNative(check3.balance ?? 0n);
2716
2750
  const where = chainName3 ? ` on ${chainName3}` : "";
2717
2751
  return `This route bridges via LayerZero, which charges a ${need} ${symbol} network fee paid as part of the transaction. Your wallet holds ${have} ${symbol}${where}. Add ${symbol}${where} and try again \u2014 gas is owed on top of this fee.`;
2718
2752
  }
@@ -3222,6 +3256,15 @@ function zdHeavyRouterPinned(chainId, router) {
3222
3256
  }
3223
3257
 
3224
3258
  // src/core/quote-option.ts
3259
+ function gateZdHeavyOptions(response, request, quotableRoutes) {
3260
+ if (!Array.isArray(response?.options)) return response;
3261
+ const matchesToken = (chainId, token, address, symbol) => typeof address === "string" && !!address && chainAddressKey(chainId, token) === chainAddressKey(chainId, address) || typeof symbol === "string" && !!symbolKey(symbol) && symbolKey(token) === symbolKey(symbol);
3262
+ const matchesLane = quotableRoutes.some(
3263
+ (r) => !!r && typeof r === "object" && !Array.isArray(r) && r.isEnabled !== false && r.isQuotable === true && Number(r.fromChainId) === Number(request.inputChain) && Number(r.toChainId) === Number(request.outputChain) && matchesToken(request.inputChain, request.inputToken, r.fromAddress, r.fromSymbol) && matchesToken(request.outputChain, request.outputToken, r.toAddress, r.toSymbol)
3264
+ );
3265
+ if (matchesLane) return response;
3266
+ return { ...response, options: response.options.filter((option) => option?.protocol !== "zdheavy") };
3267
+ }
3225
3268
  function zdHeavyExecutable(q) {
3226
3269
  const order = q.execution?.order;
3227
3270
  const chainId = typeof q.fromChainId === "number" ? q.fromChainId : Number(order?.chainNumber);
@@ -3478,16 +3521,16 @@ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionC
3478
3521
  );
3479
3522
  }
3480
3523
  function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result, tokens = [] }) {
3481
- const list = orders?.length ? orders : [order];
3482
- const sourceOrder = list[0];
3483
- const finalOrder = list[list.length - 1];
3524
+ const list2 = orders?.length ? orders : [order];
3525
+ const sourceOrder = list2[0];
3526
+ const finalOrder = list2[list2.length - 1];
3484
3527
  const now = Math.floor(Date.now() / 1e3);
3485
3528
  const deadline = Number(sourceOrder.deadline || 0);
3486
3529
  const solana = isSolanaChainId(destination.chainId);
3487
3530
  if (solana && solanaDestinationAsset(destinationToken.address)?.symbol !== symbolKey(destinationToken.symbol)) {
3488
3531
  throw new Error("This Solana token is not supported for delivery; refusing to sign.");
3489
3532
  }
3490
- for (const current of list) {
3533
+ for (const current of list2) {
3491
3534
  if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
3492
3535
  throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
3493
3536
  }
@@ -3538,9 +3581,9 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
3538
3581
  if (!Number.isFinite(deadline) || deadline <= now || deadline > now + maxDeadline + DEADLINE_CLOCK_SKEW_SECONDS) {
3539
3582
  throw new Error("ZeroDelta quote deadline is invalid or too far in the future.");
3540
3583
  }
3541
- for (let index = 1; index < list.length; index += 1) {
3542
- const previous = list[index - 1];
3543
- const current = list[index];
3584
+ for (let index = 1; index < list2.length; index += 1) {
3585
+ const previous = list2[index - 1];
3586
+ const current = list2[index];
3544
3587
  if (normalizeAddress(previous.askToken) !== normalizeAddress(current.bidToken)) {
3545
3588
  throw new Error("ZeroDelta chained quote returned disconnected order tokens.");
3546
3589
  }
@@ -3617,10 +3660,10 @@ function keccak256Hex(bytes) {
3617
3660
  return out;
3618
3661
  }
3619
3662
  function toChecksumAddress(address) {
3620
- const lower3 = address.slice(2).toLowerCase();
3621
- const hash2 = keccak256Hex(new TextEncoder().encode(lower3));
3663
+ const lower6 = address.slice(2).toLowerCase();
3664
+ const hash2 = keccak256Hex(new TextEncoder().encode(lower6));
3622
3665
  let out = "0x";
3623
- for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower3[i].toUpperCase() : lower3[i];
3666
+ for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower6[i].toUpperCase() : lower6[i];
3624
3667
  return out;
3625
3668
  }
3626
3669
  function hasValidChecksum(address) {
@@ -3638,6 +3681,7 @@ var toHex = (v, opts) => "0x" + (typeof v === "bigint" ? v.toString(16).padStart
3638
3681
  var keccak256 = (h2) => "0x" + keccak256Hex(hexToBytes2(h2));
3639
3682
  var STEP_VERSION = 5;
3640
3683
  var MAX_STEPS2 = 8;
3684
+ var ORDER_HEADER_LEN = 76;
3641
3685
  var StepKind = {
3642
3686
  LOCAL_PAYOUT: 1,
3643
3687
  REMOTE_PAYOUT: 2,
@@ -3778,11 +3822,11 @@ function decodeStep(step) {
3778
3822
  r.end();
3779
3823
  return result;
3780
3824
  }
3781
- function routerWord(addr) {
3782
- return concat([toHex(new Uint8Array(12)), checkedHex(addr, 20)]);
3825
+ function routerWord(addr2) {
3826
+ return concat([toHex(new Uint8Array(12)), checkedHex(addr2, 20)]);
3783
3827
  }
3784
- function ownerWord(addr) {
3785
- return routerWord(addr);
3828
+ function ownerWord(addr2) {
3829
+ return routerWord(addr2);
3786
3830
  }
3787
3831
  function encodeOrderHeader(serial, router, ownerType, owner) {
3788
3832
  if (!Number.isInteger(ownerType) || ownerType < 0 || ownerType > 255) throw new ZdHeavyCodecError("Invalid ownerType");
@@ -4153,6 +4197,16 @@ async function allowanceCovers(tx, account, ethCall2) {
4153
4197
  }
4154
4198
 
4155
4199
  // src/core/zdheavy-route.ts
4200
+ var ZdHeavyQuoteExpiredError = class extends Error {
4201
+ code = "zdheavy_quote_expired";
4202
+ constructor() {
4203
+ super("This ZD Heavy quote expired before it was signed. A fresh quote is loading \u2014 review it and press Exchange again.");
4204
+ this.name = "ZdHeavyQuoteExpiredError";
4205
+ }
4206
+ };
4207
+ function assertZdHeavyQuoteFresh(order, nowSec) {
4208
+ if (order && (order.expiresAt <= nowSec || order.expiryDate <= nowSec)) throw new ZdHeavyQuoteExpiredError();
4209
+ }
4156
4210
  function zdHeavyExpected(route, owner, receiver, tokens, routes) {
4157
4211
  const heavy = route.zdHeavy;
4158
4212
  if (!heavy) throw new Error("Missing ZD Heavy order.");
@@ -4178,6 +4232,7 @@ function zdHeavyExpected(route, owner, receiver, tokens, routes) {
4178
4232
  };
4179
4233
  }
4180
4234
  function validateZdHeavyPlan(route, expected) {
4235
+ assertZdHeavyQuoteFresh(expected.order, expected.nowSec);
4181
4236
  if (route.transactions.length !== 2 || route.transactions[0].kind !== "approve" || route.transactions[1].kind !== "submitOrder") {
4182
4237
  throw new Error("ZD Heavy requires exactly approve then submitOrder; refusing to sign.");
4183
4238
  }
@@ -4982,7 +5037,7 @@ var CHANNEL_HEADER = "x-zd-channel";
4982
5037
  var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
4983
5038
  var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
4984
5039
  var WIDGET_CHANNEL = "widget";
4985
- var WIDGET_VERSION = "4.20.1" ;
5040
+ var WIDGET_VERSION = "4.22.0" ;
4986
5041
  var MAX_CHANNEL_VERSION_LEN = 32;
4987
5042
  function sanitizeVersion(raw2) {
4988
5043
  const v = String(raw2).trim();
@@ -5106,7 +5161,7 @@ function wait(ms) {
5106
5161
  }
5107
5162
  var PAGE_LIMIT = 500;
5108
5163
  var MAX_PAGES = 10;
5109
- var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, promotions: null, inflight: /* @__PURE__ */ new Map() });
5164
+ var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, zdHeavy: null, health: null, vaults: null, promotions: null, inflight: /* @__PURE__ */ new Map() });
5110
5165
  var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
5111
5166
  function registryCacheFor(scope) {
5112
5167
  if (!scope) return newRegistryCache();
@@ -5183,13 +5238,14 @@ function createApiClient(cfg) {
5183
5238
  const json = await requestJson(path, init);
5184
5239
  return json?.data ?? json;
5185
5240
  }
5186
- async function requestAllPages(path) {
5241
+ async function requestAllPages(path, params = {}) {
5187
5242
  const rows = [];
5188
5243
  let firstRow = "";
5189
5244
  for (let page = 0; page < MAX_PAGES; page += 1) {
5190
- const json = await requestJson(`${path}${toQuery({ limit: PAGE_LIMIT, offset: rows.length || void 0 })}`);
5245
+ const json = await requestJson(`${path}${toQuery({ ...params, limit: PAGE_LIMIT, offset: rows.length || void 0 })}`);
5191
5246
  const envelope = json && !Array.isArray(json) ? json : {};
5192
5247
  const data = Array.isArray(json) ? json : envelope.data;
5248
+ if (params.protocol === "zdheavy" && !Array.isArray(data)) throw apiError(`ZeroDelta returned an unusable list (${path}).`, { code: "bad_response" });
5193
5249
  const pageRows = Array.isArray(data) ? data : [];
5194
5250
  const head = pageRows.length ? JSON.stringify(pageRows[0]) : "";
5195
5251
  if (page === 0) firstRow = head;
@@ -5235,6 +5291,20 @@ function createApiClient(cfg) {
5235
5291
  }
5236
5292
  });
5237
5293
  }
5294
+ function fetchZdHeavyRoutes() {
5295
+ if (nowFresh(cache.zdHeavy)) return Promise.resolve(cache.zdHeavy.value);
5296
+ return once("zdHeavy", async () => {
5297
+ let value = [];
5298
+ try {
5299
+ const rows = await requestAllPages("/routes", { protocol: "zdheavy", isEnabled: true });
5300
+ value = rows.filter((r) => !!r && typeof r === "object" && !Array.isArray(r) && r.isEnabled !== false && r.isQuotable === true);
5301
+ } catch {
5302
+ value = [];
5303
+ }
5304
+ cache.zdHeavy = { at: Date.now(), value };
5305
+ return value;
5306
+ });
5307
+ }
5238
5308
  function fetchRouteHealth() {
5239
5309
  if (nowFresh(cache.health)) return Promise.resolve(cache.health.value);
5240
5310
  return once("health", async () => {
@@ -5313,7 +5383,8 @@ function createApiClient(cfg) {
5313
5383
  for (let attempt = 0; attempt <= retries; attempt += 1) {
5314
5384
  try {
5315
5385
  const quote = await apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
5316
- return normalizeQuoteResponse(quote, request);
5386
+ const gated = Array.isArray(quote?.options) && quote.options.some((option) => option?.protocol === "zdheavy") ? gateZdHeavyOptions(quote, request, await fetchZdHeavyRoutes()) : quote;
5387
+ return normalizeQuoteResponse(gated, request);
5317
5388
  } catch (error) {
5318
5389
  lastError = error;
5319
5390
  if (attempt >= retries || !isTransientQuoteError(error)) throw error;
@@ -5323,24 +5394,24 @@ function createApiClient(cfg) {
5323
5394
  throw lastError;
5324
5395
  }
5325
5396
  async function screenWallet(address, chainId) {
5326
- const addr = String(address || "").trim();
5327
- if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
5328
- const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
5329
- if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
5330
- const key2 = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
5397
+ const addr2 = String(address || "").trim();
5398
+ if (!addr2) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
5399
+ const solana = isSolanaChainId(chainId) || isSolanaAddress(addr2);
5400
+ if (solana && !isSolanaAddress(addr2)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
5401
+ const key2 = solana ? "solana|" + addr2 : (/^0x[0-9a-fA-F]+$/.test(addr2) ? addr2.toLowerCase() : addr2) + "|" + (chainId ?? "");
5331
5402
  const hit = screenCache.get(key2);
5332
5403
  if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
5333
5404
  const inflight = screenInflight.get(key2);
5334
5405
  if (inflight) return inflight;
5335
5406
  const request = apiRequest("/screen/wallet", {
5336
5407
  method: "POST",
5337
- body: JSON.stringify(solana ? { address: addr, network: "solana" } : chainId == null ? { address: addr } : { address: addr, chainId }),
5408
+ body: JSON.stringify(solana ? { address: addr2, network: "solana" } : chainId == null ? { address: addr2 } : { address: addr2, chainId }),
5338
5409
  timeoutMs: 12e3
5339
5410
  }).then((screen) => {
5340
5411
  if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
5341
5412
  throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
5342
5413
  }
5343
- const value = { ...screen, address: screen.address || addr };
5414
+ const value = { ...screen, address: screen.address || addr2 };
5344
5415
  screenCache.set(key2, { at: Date.now(), value });
5345
5416
  return value;
5346
5417
  }).finally(() => {
@@ -5369,7 +5440,7 @@ function createApiClient(cfg) {
5369
5440
  return false;
5370
5441
  }
5371
5442
  }
5372
- return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchPromotions, fetchQuote, screenWallet, reportSubmission, apiBase };
5443
+ return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchZdHeavyRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchPromotions, fetchQuote, screenWallet, reportSubmission, apiBase };
5373
5444
  }
5374
5445
 
5375
5446
  // src/core/plan.ts
@@ -5444,12 +5515,12 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
5444
5515
  const parties = [];
5445
5516
  const seenParty = /* @__PURE__ */ new Set();
5446
5517
  for (const raw2 of [payer, destination.address]) {
5447
- const addr = String(raw2 || "").trim();
5448
- if (!addr) continue;
5449
- const key2 = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
5518
+ const addr2 = String(raw2 || "").trim();
5519
+ if (!addr2) continue;
5520
+ const key2 = /^0x[0-9a-fA-F]+$/.test(addr2) ? addr2.toLowerCase() : addr2;
5450
5521
  if (seenParty.has(key2)) continue;
5451
5522
  seenParty.add(key2);
5452
- parties.push(addr);
5523
+ parties.push(addr2);
5453
5524
  }
5454
5525
  try {
5455
5526
  const screens = await Promise.all(parties.map((address) => api.screenWallet(address, destination.chainId)));
@@ -5664,6 +5735,322 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
5664
5735
  };
5665
5736
  }
5666
5737
 
5738
+ // src/core/zdheavy-cancel.ts
5739
+ var lower3 = (s) => (typeof s === "string" ? s : "").toLowerCase();
5740
+ var ORDER_ID = /^0x[0-9a-fA-F]{64}$/;
5741
+ var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
5742
+ function isZdHeavyOrderId(v) {
5743
+ return typeof v === "string" && ORDER_ID.test(v);
5744
+ }
5745
+ function zdHeavyRecovery(plan, wallet) {
5746
+ const claims = wallet ? plan.places.flatMap(
5747
+ (p) => p.kind === "router" && p.chainId !== void 0 && p.contract ? p.claimable.filter((c) => lower3(c.payee) === lower3(wallet)).map((c) => ({ chainId: p.chainId, token: c.token, amount: c.amount })) : []
5748
+ ) : [];
5749
+ if (claims.length) return { kind: "claim", claims };
5750
+ if (plan.finished) return { kind: "delivered" };
5751
+ if (plan.state === "refund_complete" && plan.complete) {
5752
+ return { kind: "refunded", refunds: plan.places.flatMap((p) => p.refunds.map((r) => ({ ...r, chainId: p.chainId }))) };
5753
+ }
5754
+ if (plan.ownerType !== "evm") return { kind: "not-owner" };
5755
+ const holding = plan.places.filter(
5756
+ (p) => p.kind === "router" && p.chainId !== void 0 && !!p.contract && p.canCancelInPerson && !p.complete && p.lots.length > 0
5757
+ );
5758
+ if (holding.length) return { kind: "cancel", chains: holding.map((p) => p.chainId), requested: plan.state === "cancel_requested" };
5759
+ if (plan.state === "open" && !plan.complete) return { kind: "cancel", chains: [plan.originChainId], requested: false };
5760
+ return { kind: "waiting" };
5761
+ }
5762
+ var MAX_PLACES = 32;
5763
+ var MAX_ROWS = 64;
5764
+ var DIGITS = /^\d{1,78}$/;
5765
+ var LOT_KEY = /^(?:\d{1,78}|0x[0-9a-fA-F]{1,64})$/;
5766
+ var TX_HASH = /^0x[0-9a-fA-F]{64}$/;
5767
+ var posInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0 ? v : void 0;
5768
+ var nonNegInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
5769
+ var addr = (v) => typeof v === "string" && EVM_ADDRESS.test(v);
5770
+ var list = (v) => v === void 0 || v === null ? [] : Array.isArray(v) && v.length <= MAX_ROWS ? v : null;
5771
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : null;
5772
+ function normalizeCancellationPlan(raw2, orderId) {
5773
+ const r = obj(raw2);
5774
+ if (!r || !isZdHeavyOrderId(orderId) || lower3(r.orderId) !== lower3(orderId)) return null;
5775
+ const ownerType = r.ownerType === "evm" || r.ownerType === "solana" ? r.ownerType : null;
5776
+ const state = r.state === "open" || r.state === "cancel_requested" || r.state === "refund_complete" ? r.state : null;
5777
+ const originChainId = posInt(r.originChainId);
5778
+ if (!ownerType || !state || originChainId === void 0 || typeof r.complete !== "boolean" || typeof r.owner !== "string" || r.owner.length > 64) return null;
5779
+ if (r.finished !== void 0 && typeof r.finished !== "boolean") return null;
5780
+ if (!Array.isArray(r.places) || r.places.length > MAX_PLACES) return null;
5781
+ const places = [];
5782
+ for (const rawPlace of r.places) {
5783
+ const p = obj(rawPlace);
5784
+ if (!p || p.kind !== "router" && p.kind !== "hub" || typeof p.canCancelInPerson !== "boolean" || typeof p.complete !== "boolean") return null;
5785
+ const chainId = p.chainId === void 0 ? void 0 : posInt(p.chainId);
5786
+ if (p.chainId !== void 0 && chainId === void 0) return null;
5787
+ const contract = typeof p.contract === "string" ? p.contract : "";
5788
+ if (contract && !addr(contract)) return null;
5789
+ const lots = list(p.lots);
5790
+ const refunds = list(p.refunds);
5791
+ const claimable = list(p.claimable);
5792
+ if (!lots || !refunds || !claimable) return null;
5793
+ const place = {
5794
+ kind: p.kind,
5795
+ chainId,
5796
+ contract,
5797
+ canCancelInPerson: p.canCancelInPerson,
5798
+ complete: p.complete,
5799
+ lots: [],
5800
+ refunds: [],
5801
+ claimable: []
5802
+ };
5803
+ for (const rawLot of lots) {
5804
+ const l = obj(rawLot);
5805
+ if (!l || !nonNegInt(l.step) || !addr(l.token) || typeof l.amount !== "string" || !DIGITS.test(l.amount) || typeof l.key !== "string" || !LOT_KEY.test(l.key))
5806
+ return null;
5807
+ place.lots.push({ step: l.step, token: l.token, amount: l.amount, key: l.key });
5808
+ }
5809
+ for (const rawRefund of refunds) {
5810
+ const f = obj(rawRefund);
5811
+ if (!f || typeof f.txHash !== "string" || !TX_HASH.test(f.txHash) || !nonNegInt(f.step) || !addr(f.token) || typeof f.amount !== "string" || !DIGITS.test(f.amount) || !addr(f.to))
5812
+ return null;
5813
+ place.refunds.push({ txHash: f.txHash, step: f.step, token: f.token, amount: f.amount, to: f.to });
5814
+ }
5815
+ for (const rawClaim of claimable) {
5816
+ const c = obj(rawClaim);
5817
+ if (!c || !addr(c.payee) || !addr(c.token) || typeof c.amount !== "string" || !DIGITS.test(c.amount)) return null;
5818
+ place.claimable.push({ payee: c.payee, token: c.token, amount: c.amount });
5819
+ }
5820
+ places.push(place);
5821
+ }
5822
+ return {
5823
+ orderId: r.orderId,
5824
+ ownerType,
5825
+ owner: r.owner,
5826
+ originChainId,
5827
+ state,
5828
+ complete: r.complete,
5829
+ ...r.finished !== void 0 ? { finished: r.finished } : {},
5830
+ places
5831
+ };
5832
+ }
5833
+ function zdHeavyOrderPath(orderId, tail) {
5834
+ if (!isZdHeavyOrderId(orderId)) throw new ZdHeavyCodecError("Not a ZD Heavy order id.");
5835
+ return `/orders/${orderId.toLowerCase()}/${tail}`;
5836
+ }
5837
+ async function fetchZdHeavyCancellation(api, orderId) {
5838
+ if (!isZdHeavyOrderId(orderId)) return null;
5839
+ try {
5840
+ return normalizeCancellationPlan(await api.apiRequest(zdHeavyOrderPath(orderId, "cancellation"), { timeoutMs: 1e4 }), orderId);
5841
+ } catch {
5842
+ return null;
5843
+ }
5844
+ }
5845
+ function unsigned(raw2) {
5846
+ const r = obj(raw2);
5847
+ const s = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
5848
+ if (!r) return { purpose: "", chainId: "", from: "", to: "", data: "" };
5849
+ return {
5850
+ purpose: s(r.purpose),
5851
+ chainId: s(r.chainId),
5852
+ from: s(r.from),
5853
+ to: s(r.to),
5854
+ data: s(r.data),
5855
+ ...r.value !== void 0 ? { value: s(r.value) } : {}
5856
+ };
5857
+ }
5858
+ async function buildZdHeavyCancelTx(api, orderId, chainId) {
5859
+ return unsigned(
5860
+ await api.apiRequest(zdHeavyOrderPath(orderId, "cancel-tx"), {
5861
+ method: "POST",
5862
+ body: JSON.stringify(chainId === void 0 ? {} : { chainId }),
5863
+ timeoutMs: 15e3
5864
+ })
5865
+ );
5866
+ }
5867
+ async function buildZdHeavyClaimTx(api, orderId, chainId, token) {
5868
+ return unsigned(
5869
+ await api.apiRequest(zdHeavyOrderPath(orderId, "claim-tx"), {
5870
+ method: "POST",
5871
+ body: JSON.stringify({ chainId, token }),
5872
+ timeoutMs: 15e3
5873
+ })
5874
+ );
5875
+ }
5876
+ var ZDHEAVY_CANCEL_SELECTOR = "0xf26bce2c";
5877
+ var ZDHEAVY_CLAIM_SELECTOR = "0x1e83409a";
5878
+ var ZDHEAVY_CLAIM_TO_SELECTOR = "0x21c0b342";
5879
+ var MAX_CANCEL_KEYS = 32;
5880
+ function reader(data, selector) {
5881
+ if (typeof data !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data) || data.slice(0, 10).toLowerCase() !== selector) {
5882
+ throw new ZdHeavyCodecError("Unexpected call");
5883
+ }
5884
+ const body = data.slice(10).toLowerCase();
5885
+ const size = body.length / 2;
5886
+ const fail = () => {
5887
+ throw new ZdHeavyCodecError("Invalid calldata");
5888
+ };
5889
+ const word2 = (at, bits = 256) => {
5890
+ if (!Number.isSafeInteger(at) || at < 0 || at + 32 > size) return fail();
5891
+ const n = BigInt(`0x${body.slice(at * 2, (at + 32) * 2)}`);
5892
+ if (bits < 256 && n >= 1n << BigInt(bits)) return fail();
5893
+ return n;
5894
+ };
5895
+ const fixed = (at) => {
5896
+ word2(at);
5897
+ return `0x${body.slice(at * 2, (at + 32) * 2)}`;
5898
+ };
5899
+ const address = (at) => `0x${word2(at, 160).toString(16).padStart(40, "0")}`;
5900
+ const offset = (at, expected) => {
5901
+ if (word2(at) !== BigInt(expected)) fail();
5902
+ };
5903
+ const count = (at, each) => {
5904
+ const n = word2(at);
5905
+ if (n > BigInt(Math.floor((size - at - 32) / each))) return fail();
5906
+ return Number(n);
5907
+ };
5908
+ const bytes = (at) => {
5909
+ const n = word2(at);
5910
+ if (n > BigInt(size - at - 32)) return fail();
5911
+ const length = Number(n);
5912
+ const end = at + 32 + Math.ceil(length / 32) * 32;
5913
+ if (end > size || /[^0]/.test(body.slice((at + 32 + length) * 2, end * 2))) return fail();
5914
+ return { value: `0x${body.slice((at + 32) * 2, (at + 32 + length) * 2)}`, end };
5915
+ };
5916
+ return { size, fail, word: word2, fixed, address, offset, count, bytes };
5917
+ }
5918
+ function decodeZdHeavyCancel(data) {
5919
+ const r = reader(data, ZDHEAVY_CANCEL_SELECTOR);
5920
+ const orderId = r.fixed(0);
5921
+ const P3 = 96;
5922
+ r.offset(32, P3);
5923
+ const expiryDate = r.word(P3, 64);
5924
+ r.offset(P3 + 32, 96);
5925
+ const header = r.bytes(P3 + 96);
5926
+ r.offset(P3 + 64, header.end - P3);
5927
+ const hashesAt = header.end;
5928
+ const n = r.count(hashesAt, 32);
5929
+ const stepHashes = [];
5930
+ for (let i = 0; i < n; i++) stepHashes.push(r.fixed(hashesAt + 32 + i * 32));
5931
+ const keysAt = hashesAt + 32 + n * 32;
5932
+ r.offset(64, keysAt);
5933
+ const k = r.count(keysAt, 32);
5934
+ const keys = [];
5935
+ for (let i = 0; i < k; i++) keys.push(r.word(keysAt + 32 + i * 32));
5936
+ if (keysAt + 32 + k * 32 !== r.size) r.fail();
5937
+ return { orderId, proof: { expiryDate, orderHeader: header.value, stepHashes }, keys };
5938
+ }
5939
+ function decodeZdHeavyClaim(data) {
5940
+ const selector = typeof data === "string" ? data.slice(0, 10).toLowerCase() : "";
5941
+ if (selector === ZDHEAVY_CLAIM_SELECTOR) {
5942
+ const r2 = reader(data, ZDHEAVY_CLAIM_SELECTOR);
5943
+ if (r2.size !== 32) r2.fail();
5944
+ return { token: r2.address(0) };
5945
+ }
5946
+ const r = reader(data, ZDHEAVY_CLAIM_TO_SELECTOR);
5947
+ if (r.size !== 64) r.fail();
5948
+ return { token: r.address(0), to: r.address(32) };
5949
+ }
5950
+ var hexBytes2 = (h2) => Uint8Array.from(h2.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
5951
+ var keccak = (h2) => `0x${keccak256Hex(hexBytes2(h2))}`;
5952
+ function orderIdFromProof(expiryDate, header, stepHashes) {
5953
+ const tag = Array.from(new TextEncoder().encode("ZD/ORDER"), (b) => b.toString(16).padStart(2, "0")).join("");
5954
+ return keccak(`0x${tag}${expiryDate.toString(16).padStart(16, "0")}${keccak(header).slice(2)}${stepHashes.map((h2) => h2.slice(2)).join("")}`);
5955
+ }
5956
+ var TX = /^0x[0-9a-fA-F]{64}$/;
5957
+ var succeeded = (receipt) => {
5958
+ const status = obj(receipt)?.status;
5959
+ return typeof status === "string" && /^0x0*1$/.test(status);
5960
+ };
5961
+ async function verifyZdHeavySourceOrder(rpc, chainId, hash2, orderId) {
5962
+ const no = (reason) => ({ ok: false, reason });
5963
+ if (!SUPPORTED_CHAIN_IDS.has(chainId) || typeof hash2 !== "string" || !TX.test(hash2) || !isZdHeavyOrderId(orderId)) return no("not checkable");
5964
+ try {
5965
+ const [tx, receipt] = await Promise.all([rpc(chainId, "eth_getTransactionByHash", [hash2]), rpc(chainId, "eth_getTransactionReceipt", [hash2])]);
5966
+ const t = obj(tx);
5967
+ if (!t || lower3(t.hash) !== lower3(hash2)) return no("source transaction not found");
5968
+ if (!succeeded(receipt) || lower3(obj(receipt)?.transactionHash) !== lower3(hash2)) return no("source transaction not confirmed");
5969
+ const router = checkZdHeavyRouter(chainId, typeof t.to === "string" ? t.to : "");
5970
+ if (!router.ok) return no("source transaction is not to a pinned router");
5971
+ const input = typeof t.input === "string" ? t.input : typeof t.data === "string" ? t.data : "";
5972
+ const { submission } = decodeZdHeavySubmit(input);
5973
+ const id = orderIdOf(submission.expiryDate, encodeOrderHeader(submission.serial, router.address, submission.ownerType, submission.owner), submission.steps);
5974
+ return lower3(id) === lower3(orderId) ? { ok: true } : no("source transaction submitted another order");
5975
+ } catch {
5976
+ return no("source transaction could not be read");
5977
+ }
5978
+ }
5979
+ var refuse2 = (what) => ({ ok: false, reason: `The ${what} does not match this order. Refusing to sign.` });
5980
+ function commonChecks(tx, owner, purpose, chainId) {
5981
+ if (!tx || tx.purpose !== purpose) return refuse2("transaction kind");
5982
+ const chain2 = typeof tx.chainId === "string" && /^\d{1,12}$/.test(tx.chainId) ? Number(tx.chainId) : NaN;
5983
+ if (!Number.isSafeInteger(chain2) || chain2 <= 0) return refuse2("chain");
5984
+ if (chainId !== void 0 && chain2 !== chainId) return refuse2("chain");
5985
+ const router = checkZdHeavyRouter(chain2, tx.to);
5986
+ if (!router.ok) return { ok: false, reason: router.reason };
5987
+ if (!addr(owner) || !addr(tx.from) || lower3(tx.from) !== lower3(owner)) return refuse2("sender");
5988
+ try {
5989
+ if (tx.value !== void 0 && tx.value !== "" && BigInt(tx.value) !== 0n) return refuse2("value");
5990
+ } catch {
5991
+ return refuse2("value");
5992
+ }
5993
+ return { ok: true, chainId: chain2, router: router.address };
5994
+ }
5995
+ var accepted = (chainId, owner, router, data) => ({
5996
+ ok: true,
5997
+ chainId,
5998
+ tx: { from: owner, to: router, data: data.toLowerCase(), value: "0x0" }
5999
+ });
6000
+ function checkZdHeavyCancelTx(tx, e) {
6001
+ const base = commonChecks(tx, e.owner, "cancel", e.chainId);
6002
+ if (!base.ok) return base;
6003
+ let decoded;
6004
+ try {
6005
+ decoded = decodeZdHeavyCancel(tx.data);
6006
+ } catch {
6007
+ return refuse2("call");
6008
+ }
6009
+ const { orderId, proof, keys } = decoded;
6010
+ if (!isZdHeavyOrderId(e.orderId) || lower3(orderId) !== lower3(e.orderId)) return refuse2("order id");
6011
+ if (keys.length > MAX_CANCEL_KEYS) return refuse2("lot keys");
6012
+ const listed = e.lotKeys ? new Set(
6013
+ e.lotKeys.map((k) => {
6014
+ try {
6015
+ return BigInt(k).toString();
6016
+ } catch {
6017
+ return "";
6018
+ }
6019
+ })
6020
+ ) : void 0;
6021
+ const seen = /* @__PURE__ */ new Set();
6022
+ for (const k of keys) {
6023
+ if (listed && !listed.has(k.toString())) return refuse2("lot keys");
6024
+ const step = k >> 160n;
6025
+ const tokenBits = k & (1n << 160n) - 1n;
6026
+ if (step >= BigInt(proof.stepHashes.length) || tokenBits === 0n || seen.has(k.toString())) return refuse2("lot keys");
6027
+ seen.add(k.toString());
6028
+ }
6029
+ if (proof.stepHashes.length < 1 || proof.stepHashes.length > 8) return refuse2("order proof");
6030
+ if (lower3(orderIdFromProof(proof.expiryDate, proof.orderHeader, proof.stepHashes)) !== lower3(orderId)) return refuse2("order proof");
6031
+ const h2 = proof.orderHeader;
6032
+ if (h2.length !== 2 + ORDER_HEADER_LEN * 2) return refuse2("order proof");
6033
+ const routerWordHex = `0x${h2.slice(2 + 11 * 2, 2 + 43 * 2)}`;
6034
+ const ownerType = Number.parseInt(h2.slice(2 + 43 * 2, 2 + 44 * 2), 16);
6035
+ const ownerWordHex = `0x${h2.slice(2 + 44 * 2)}`;
6036
+ if (lower3(routerWordHex) !== lower3(ownerWord(base.router))) return refuse2("router");
6037
+ if (ownerType !== 1 || lower3(ownerWordHex) !== lower3(ownerWord(e.owner))) return refuse2("owner");
6038
+ return accepted(base.chainId, e.owner, base.router, tx.data);
6039
+ }
6040
+ function checkZdHeavyClaimTx(tx, e) {
6041
+ const base = commonChecks(tx, e.owner, "claim", e.chainId);
6042
+ if (!base.ok) return base;
6043
+ let decoded;
6044
+ try {
6045
+ decoded = decodeZdHeavyClaim(tx.data);
6046
+ } catch {
6047
+ return refuse2("call");
6048
+ }
6049
+ if (!addr(e.token) || lower3(decoded.token) !== lower3(e.token)) return refuse2("token");
6050
+ if (decoded.to !== void 0 && lower3(decoded.to) !== lower3(e.owner)) return refuse2("recipient");
6051
+ return accepted(base.chainId, e.owner, base.router, tx.data);
6052
+ }
6053
+
5667
6054
  // src/core/verify.ts
5668
6055
  var TX_VERIFY_ATTEMPTS = 5;
5669
6056
  var TX_VERIFY_INTERVAL_MS = 2500;
@@ -5877,7 +6264,13 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
5877
6264
  return void 0;
5878
6265
  }
5879
6266
  }
5880
- return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance, readZdHeavySubmitFee };
6267
+ async function bundledRpc(chainId, method, params) {
6268
+ const override = rpcOverrides[Number(chainId)];
6269
+ const rpc = override && /^https?:\/\//i.test(override) ? override : BUNDLED_RPC[Number(chainId)];
6270
+ if (!rpc) throw new Error("No bundled RPC for this chain");
6271
+ return rpcCall(rpc, method, params);
6272
+ }
6273
+ return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance, readZdHeavySubmitFee, bundledRpc };
5881
6274
  }
5882
6275
 
5883
6276
  // src/core/config.ts
@@ -6000,10 +6393,11 @@ function createEngine(config = {}) {
6000
6393
  fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
6001
6394
  fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
6002
6395
  fetchCatalogue: async (allowedAssets, product, options) => {
6003
- const [chains, registryTokens, routes, health, vaults] = await Promise.all([
6396
+ const [chains, registryTokens, routes, zdHeavyRoutes, health, vaults] = await Promise.all([
6004
6397
  api.fetchChains().catch(() => []),
6005
6398
  api.fetchTokens().catch(() => []),
6006
6399
  api.fetchRoutes().catch(() => []),
6400
+ api.fetchZdHeavyRoutes(),
6007
6401
  api.fetchRouteHealth(),
6008
6402
  api.fetchRwaVaults()
6009
6403
  ]);
@@ -6014,6 +6408,7 @@ function createEngine(config = {}) {
6014
6408
  chains,
6015
6409
  tokens,
6016
6410
  routes,
6411
+ zdHeavyRoutes,
6017
6412
  product,
6018
6413
  ...allowed ? { allowedAssets: allowed } : {},
6019
6414
  // Solana is a SOURCE only for a surface that can pay from it (the exchange card, through the
@@ -6035,6 +6430,10 @@ function createEngine(config = {}) {
6035
6430
  executeSolanaPlanStaged: (input) => executeSolanaPlanStaged({ ...input, rpc: input.rpc ?? solanaRpc }),
6036
6431
  previewSolanaSource: (input) => previewSolanaSource(api, input),
6037
6432
  trackDelivery: (hash2) => fetchDelivery(api, hash2),
6433
+ fetchZdHeavyCancellation: (orderId) => fetchZdHeavyCancellation(api, orderId),
6434
+ buildZdHeavyCancelTx: (orderId, chainId) => buildZdHeavyCancelTx(api, orderId, chainId),
6435
+ buildZdHeavyClaimTx: (orderId, chainId, tokenAddress) => buildZdHeavyClaimTx(api, orderId, chainId, tokenAddress),
6436
+ verifyZdHeavySourceOrder: (chainId, hash2, orderId) => verifyZdHeavySourceOrder(verifier.bundledRpc, chainId, hash2, orderId),
6038
6437
  fetchWalletHistory: (wallets) => fetchWalletHistory(api, wallets),
6039
6438
  readSolanaBalance: (owner, mint) => readSolanaBalance(solanaRpc, owner, mint),
6040
6439
  simulateSolanaCost: (plan) => simulateSolanaCost(solanaRpc, plan),
@@ -6182,7 +6581,9 @@ function normalizeWalletError(err2, fallback = "Transaction failed.") {
6182
6581
  async function sendTransaction(provider, tx) {
6183
6582
  const hash2 = await provider.request({
6184
6583
  method: "eth_sendTransaction",
6185
- params: [{ from: tx.from, to: tx.to, data: tx.data, value: tx.value || "0x0" }]
6584
+ // `chainId` only when the caller names one (ZD Heavy recovery writes): the wallet then refuses to
6585
+ // sign on any other chain. The order submit path names none, so its request is unchanged.
6586
+ params: [{ from: tx.from, to: tx.to, data: tx.data, value: tx.value || "0x0", ...tx.chainId ? { chainId: chainHex(tx.chainId) } : {} }]
6186
6587
  });
6187
6588
  return hash2;
6188
6589
  }
@@ -6413,6 +6814,8 @@ function useUserPresence() {
6413
6814
  }
6414
6815
 
6415
6816
  // src/react/hooks/useFlow.ts
6817
+ var REFRESH_LEAD_SECONDS = 20;
6818
+ var SIGN_MIN_SECONDS = 15;
6416
6819
  function reportQuietly(engine, report, stage) {
6417
6820
  try {
6418
6821
  void engine.reportSubmission?.({ ...report, stage })?.catch?.(() => {
@@ -6436,6 +6839,7 @@ function useFlow(args) {
6436
6839
  const [nonce, setNonce] = react.useState(0);
6437
6840
  const reqId = react.useRef(0);
6438
6841
  const busyRef = react.useRef(false);
6842
+ const keepExpiryError = react.useRef(false);
6439
6843
  const [planAt, setPlanAt] = react.useState(0);
6440
6844
  const planAtRef = react.useRef(0);
6441
6845
  const statusRef = react.useRef("idle");
@@ -6465,7 +6869,8 @@ function useFlow(args) {
6465
6869
  }
6466
6870
  const id = ++reqId.current;
6467
6871
  setStatus("loading");
6468
- setError(null);
6872
+ if (!keepExpiryError.current) setError(null);
6873
+ keepExpiryError.current = false;
6469
6874
  setVerdict(null);
6470
6875
  setTxHash(null);
6471
6876
  setLastTxEntry(null);
@@ -6531,8 +6936,8 @@ function useFlow(args) {
6531
6936
  engine.fetchChains().catch(() => [])
6532
6937
  ]);
6533
6938
  if (!alive) return;
6534
- const check2 = checkNativeFee(selected, balance);
6535
- setNativeShortfall(nativeFeeShortLabel(check2, nativeSymbol(Number(src.chainId), chains)));
6939
+ const check3 = checkNativeFee(selected, balance);
6940
+ setNativeShortfall(nativeFeeShortLabel(check3, nativeSymbol(Number(src.chainId), chains)));
6536
6941
  } catch {
6537
6942
  }
6538
6943
  })();
@@ -6558,6 +6963,10 @@ function useFlow(args) {
6558
6963
  setVerdict(null);
6559
6964
  const patch = (id, s, hash2) => setSteps((prev) => prev.map((st) => st.id === id ? { ...st, state: s, ...hash2 ? { hash: hash2 } : {} } : st));
6560
6965
  try {
6966
+ if (route.zdHeavy) {
6967
+ if (route.zdHeavy.order.expiresAt - Date.now() / 1e3 < SIGN_MIN_SECONDS) throw new ZdHeavyQuoteExpiredError();
6968
+ assertZdHeavyQuoteFresh(route.zdHeavy.order, Math.floor(Date.now() / 1e3));
6969
+ }
6561
6970
  const current = await getChainId(provider);
6562
6971
  if (current !== Number(sourceChainId)) {
6563
6972
  await switchChain(provider, Number(sourceChainId));
@@ -6565,10 +6974,10 @@ function useFlow(args) {
6565
6974
  if (after !== Number(sourceChainId)) throw new Error("Wallet did not switch to the source chain.");
6566
6975
  }
6567
6976
  if (routeNativeValue(route) > 0n) {
6568
- const check2 = checkNativeFee(route, await nativeBalance(provider, account));
6569
- if (check2.short) {
6977
+ const check3 = checkNativeFee(route, await nativeBalance(provider, account));
6978
+ if (check3.short) {
6570
6979
  const chains = await engine.fetchChains().catch(() => []);
6571
- throw new Error(nativeFeeShortMessage(check2, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
6980
+ throw new Error(nativeFeeShortMessage(check3, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
6572
6981
  }
6573
6982
  }
6574
6983
  const heavyExpected = route.zdHeavy ? zdHeavyExpected(route, account, recipient2, ...await Promise.all([engine.fetchTokens(), engine.fetchRoutes()])) : void 0;
@@ -6588,6 +6997,7 @@ function useFlow(args) {
6588
6997
  patch(tx.id, "done");
6589
6998
  continue;
6590
6999
  }
7000
+ if (route.zdHeavy && tx.kind === "submitOrder") assertZdHeavyQuoteFresh(route.zdHeavy.order, Math.floor(Date.now() / 1e3));
6591
7001
  if (!validatePlannedTransaction(tx, route, recipient2, heavyExpected ? { ...heavyExpected, nowSec: Math.floor(Date.now() / 1e3) } : void 0)) {
6592
7002
  throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
6593
7003
  }
@@ -6652,13 +7062,17 @@ function useFlow(args) {
6652
7062
  }
6653
7063
  } catch (e) {
6654
7064
  setStatus("error");
6655
- setError(normalizeWalletError(e));
7065
+ setError(e instanceof ZdHeavyQuoteExpiredError ? e.message : normalizeWalletError(e));
7066
+ if (e instanceof ZdHeavyQuoteExpiredError) {
7067
+ keepExpiryError.current = true;
7068
+ reload();
7069
+ }
6656
7070
  setSteps((prev) => prev.map((st) => st.state === "active" ? { ...st, state: "error" } : st));
6657
7071
  onError?.(e instanceof Error ? e : new Error(String(e)));
6658
7072
  } finally {
6659
7073
  busyRef.current = false;
6660
7074
  }
6661
- }, [selected, wallet.provider, wallet.account, engine, kind, recipientFor, onSuccess, onError]);
7075
+ }, [selected, wallet.provider, wallet.account, engine, kind, recipientFor, onSuccess, onError, reload]);
6662
7076
  const [prices, setPrices] = react.useState(null);
6663
7077
  const priceKey = baseSelected?.options?.length ? `${baseSelected.source.asset}|${baseSelected.receive.asset}` : "";
6664
7078
  react.useEffect(() => {
@@ -6715,8 +7129,8 @@ function useFlow(args) {
6715
7129
  try {
6716
7130
  if (typeof engine.fetchPromotions !== "function") return;
6717
7131
  const read = await engine.fetchPromotions();
6718
- const list = Array.isArray(read) ? read : [];
6719
- if (alive) setPromotionList((prev) => JSON.stringify(prev) === JSON.stringify(list) ? prev : list);
7132
+ const list2 = Array.isArray(read) ? read : [];
7133
+ if (alive) setPromotionList((prev) => JSON.stringify(prev) === JSON.stringify(list2) ? prev : list2);
6720
7134
  } catch {
6721
7135
  }
6722
7136
  })();
@@ -6754,6 +7168,24 @@ function useFlow(args) {
6754
7168
  const quoteReady = status === "ready" && !!plan;
6755
7169
  const quotePaused = quoteReady && idle2;
6756
7170
  const quoteStale = quoteReady && (idle2 || planAt < returnedAt2);
7171
+ react.useEffect(() => {
7172
+ if (!enabled || !selected?.zdHeavy || !quoteReady || quotePaused || busyRef.current) return;
7173
+ let timer2;
7174
+ const schedule2 = () => {
7175
+ clearTimeout(timer2);
7176
+ if (document.visibilityState !== "visible" || busyRef.current) return;
7177
+ const delay = Math.max(3e3, (selected.zdHeavy.order.expiresAt - REFRESH_LEAD_SECONDS) * 1e3 - Date.now());
7178
+ timer2 = setTimeout(() => {
7179
+ if (!busyRef.current && statusRef.current === "ready" && !isUserIdle() && document.visibilityState === "visible") reload();
7180
+ }, delay);
7181
+ };
7182
+ schedule2();
7183
+ document.addEventListener("visibilitychange", schedule2);
7184
+ return () => {
7185
+ clearTimeout(timer2);
7186
+ document.removeEventListener("visibilitychange", schedule2);
7187
+ };
7188
+ }, [enabled, selected, quoteReady, quotePaused, reload]);
6757
7189
  return {
6758
7190
  status,
6759
7191
  plan,
@@ -6781,7 +7213,7 @@ function useFlow(args) {
6781
7213
  var RETRY_DELAYS_MS = [800, 2400, 6e3];
6782
7214
  var CATALOGUE_REFRESH_MS = 6e4 + 250;
6783
7215
  function catalogueSignature(c) {
6784
- const ids = (list) => list.map((t) => `${Number(t.chainId)}:${String(t.address).toLowerCase()}`).join(",");
7216
+ const ids = (list2) => list2.map((t) => `${Number(t.chainId)}:${String(t.address).toLowerCase()}`).join(",");
6785
7217
  return [ids(c.tokens), ids(c.sources), [...c.source].sort().join(","), [...c.destination].sort().join(","), [...c.lanes ?? []].sort().join(","), [...c.brokenLanes?.keys() ?? []].sort().join(","), [...c.limitedLanes.keys()].sort().join(",")].join("|");
6786
7218
  }
6787
7219
  function useCatalogue(engine, options = {}) {
@@ -6846,16 +7278,16 @@ function useHoldings(engine, account, routes, initialBalances) {
6846
7278
  const reqId = react.useRef(0);
6847
7279
  const targets = react.useMemo(() => {
6848
7280
  const seen = /* @__PURE__ */ new Set();
6849
- const list = [];
7281
+ const list2 = [];
6850
7282
  for (const r of routes) {
6851
7283
  const s = r.source;
6852
7284
  if (!s?.tokenAddress || s.decimals == null) continue;
6853
7285
  const k = balanceKey(s.chainId, s.tokenAddress);
6854
7286
  if (seen.has(k)) continue;
6855
7287
  seen.add(k);
6856
- list.push({ chainId: s.chainId, tokenAddress: s.tokenAddress, decimals: s.decimals });
7288
+ list2.push({ chainId: s.chainId, tokenAddress: s.tokenAddress, decimals: s.decimals });
6857
7289
  }
6858
- return list;
7290
+ return list2;
6859
7291
  }, [routes]);
6860
7292
  const targetsKey = react.useMemo(() => targets.map((t) => balanceKey(t.chainId, t.tokenAddress)).join("|"), [targets]);
6861
7293
  react.useEffect(() => {
@@ -7334,6 +7766,13 @@ img.sg-tok-badge{width:16px;padding:0;object-fit:cover;background:var(--sg-bg)}
7334
7766
  /* transaction detail: copyable hash row (no external links \u2014 everything stays in-widget) */
7335
7767
  .sg-txd-hash{display:flex;align-items:center;gap:8px;margin-top:12px;font-size:13px}
7336
7768
  .sg-txd-hash .sg-mono{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
7769
+ .sg-zdh{margin-top:14px;padding:12px;border:1px solid var(--sg-border);border-radius:var(--sg-radius-control);background:var(--sg-surface)}
7770
+ .sg-zdh-title{font-size:14px;font-weight:600;line-height:1.25}
7771
+ .sg-zdh-body{margin:4px 0 10px;font-size:12px;line-height:1.45;color:var(--sg-text-muted)}
7772
+ .sg-zdh-actions{display:flex;flex-direction:column;gap:10px}
7773
+ .sg-zdh-action{display:flex;flex-direction:column;gap:6px}
7774
+ .sg-zdh-action .sg-txd-hash{margin-top:0}
7775
+ .sg-zdh-status{margin-top:14px}
7337
7776
  .sg-copy{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:26px;height:26px;border:1px solid var(--sg-border);border-radius:var(--sg-radius-control);background:transparent;color:var(--sg-text-muted);cursor:pointer;transition:color 120ms ease,border-color 120ms ease}
7338
7777
  .sg-copy:hover{color:var(--sg-accent);border-color:var(--sg-accent)}
7339
7778
 
@@ -8639,8 +9078,8 @@ function groupDeployments(deployments, prices) {
8639
9078
  const members = /* @__PURE__ */ new Map();
8640
9079
  for (const d of [...deployments].sort(byDeployment)) {
8641
9080
  const key2 = String(d.token.symbol).toUpperCase();
8642
- const list = members.get(key2);
8643
- if (list) list.push(d);
9081
+ const list2 = members.get(key2);
9082
+ if (list2) list2.push(d);
8644
9083
  else {
8645
9084
  members.set(key2, [d]);
8646
9085
  order.push(key2);
@@ -8654,10 +9093,10 @@ var CHAIN_ALIASES = {
8654
9093
  43114: ["avax"]
8655
9094
  };
8656
9095
  function labelForms(label2) {
8657
- const lower3 = label2.trim().toLowerCase();
8658
- if (!lower3) return [];
8659
- const compact = lower3.replace(/[^a-z0-9]/g, "");
8660
- return compact && compact !== lower3 ? [lower3, compact] : [lower3];
9096
+ const lower6 = label2.trim().toLowerCase();
9097
+ if (!lower6) return [];
9098
+ const compact = lower6.replace(/[^a-z0-9]/g, "");
9099
+ return compact && compact !== lower6 ? [lower6, compact] : [lower6];
8661
9100
  }
8662
9101
  function buildChainSearchTerms(chains) {
8663
9102
  const byId = /* @__PURE__ */ new Map();
@@ -9380,22 +9819,22 @@ function TriggerGlyph({ cv }) {
9380
9819
  if (cv.tone === "blocked" || cv.tone === "warn") return /* @__PURE__ */ jsxRuntime.jsx(CloseCircle, {});
9381
9820
  return /* @__PURE__ */ jsxRuntime.jsx(ShieldTick, {});
9382
9821
  }
9383
- function CheckRow({ check: check2, onViewPolicy }) {
9384
- const label2 = check2.id === "risk" ? check2.ok ? "Risk screening passed" : "Risk screening failed" : check2.label;
9385
- return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: "sg-cp-check", "data-ok": check2.ok, children: [
9822
+ function CheckRow({ check: check3, onViewPolicy }) {
9823
+ const label2 = check3.id === "risk" ? check3.ok ? "Risk screening passed" : "Risk screening failed" : check3.label;
9824
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: "sg-cp-check", "data-ok": check3.ok, children: [
9386
9825
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cp-check-head", children: [
9387
9826
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cp-check-label", children: [
9388
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-mark", "data-ok": check2.ok, children: check2.ok ? /* @__PURE__ */ jsxRuntime.jsx(Tick, {}) : /* @__PURE__ */ jsxRuntime.jsx(Cross, {}) }),
9827
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-mark", "data-ok": check3.ok, children: check3.ok ? /* @__PURE__ */ jsxRuntime.jsx(Tick, {}) : /* @__PURE__ */ jsxRuntime.jsx(Cross, {}) }),
9389
9828
  /* @__PURE__ */ jsxRuntime.jsx("span", { children: label2 }),
9390
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: check2.ok ? " \u2014 passed" : " \u2014 failed" })
9829
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: check3.ok ? " \u2014 passed" : " \u2014 failed" })
9391
9830
  ] }),
9392
- check2.id === "risk" ? /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-cp-link", onClick: onViewPolicy, children: [
9831
+ check3.id === "risk" ? /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "sg-cp-link", onClick: onViewPolicy, children: [
9393
9832
  "View policy",
9394
9833
  /* @__PURE__ */ jsxRuntime.jsx(CornerArrow, {})
9395
9834
  ] }) : null
9396
9835
  ] }),
9397
- check2.note ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-note", children: check2.note }) : null,
9398
- check2.reasons.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-reason", children: humanizeComplianceReason(reason) }, reason))
9836
+ check3.note ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-note", children: check3.note }) : null,
9837
+ check3.reasons.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cp-check-reason", children: humanizeComplianceReason(reason) }, reason))
9399
9838
  ] });
9400
9839
  }
9401
9840
  function QuoteChecks({
@@ -9429,7 +9868,7 @@ function QuoteChecks({
9429
9868
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-summary-sub", children: "The gateway returned no compliance decision for this quote, so there is nothing to show. It is not a failed check." })
9430
9869
  )
9431
9870
  ] }),
9432
- checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cp-checks", children: checks.map((check2) => /* @__PURE__ */ jsxRuntime.jsx(CheckRow, { check: check2, onViewPolicy }, check2.id)) }) : null,
9871
+ checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cp-checks", children: checks.map((check3) => /* @__PURE__ */ jsxRuntime.jsx(CheckRow, { check: check3, onViewPolicy }, check3.id)) }) : null,
9433
9872
  orphans.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cp-orphans", children: orphans.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: humanizeComplianceReason(reason) }, reason)) }) : null,
9434
9873
  direct2 && checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cp-scope", children: DIRECT_SCOPE_NOTE }) : null
9435
9874
  ] }),
@@ -9623,6 +10062,398 @@ function useWalletHistory(engine, wallets) {
9623
10062
  }, [engine, key2]);
9624
10063
  return entries;
9625
10064
  }
10065
+ var lower4 = (s) => (s ?? "").toLowerCase();
10066
+ var ZDH_RECHECK_MS = 15e3;
10067
+ var ZDH_RECHECK_FOR_MS = 30 * 6e4;
10068
+ var inFlight2 = /* @__PURE__ */ new Set();
10069
+ var writes = /* @__PURE__ */ new Map();
10070
+ var listeners = /* @__PURE__ */ new Set();
10071
+ var notify = () => {
10072
+ for (const listener of listeners) listener();
10073
+ };
10074
+ var hidden3 = () => typeof document !== "undefined" && document.visibilityState === "hidden";
10075
+ var unresolved = (w) => !!w && (w.status === "checking" || w.status === "stalled");
10076
+ var lockKey = (account, orderId, chainId, kind, asset) => `${lower4(account)}:${lower4(orderId)}:${chainId}:${kind}:${kind === "claim" ? lower4(asset) : ""}`;
10077
+ function cancelScope(keys) {
10078
+ const norm = keys.map((k) => {
10079
+ try {
10080
+ return BigInt(k).toString();
10081
+ } catch {
10082
+ return k;
10083
+ }
10084
+ });
10085
+ return `cancel:${[...new Set(norm)].sort().join(",")}`;
10086
+ }
10087
+ var claimScope = (asset, amount) => `claim:${lower4(asset)}:${amount ?? ""}`;
10088
+ async function check2(key2) {
10089
+ const w = writes.get(key2);
10090
+ if (!w || w.checking || !unresolved(w)) return;
10091
+ w.checking = true;
10092
+ let status;
10093
+ try {
10094
+ status = (await w.engine.verifySubmittedTx({ chainId: w.chainId, hash: w.hash, ...w.tx, minNonce: w.minNonce ?? 0 })).status;
10095
+ } catch {
10096
+ status = "unconfirmed";
10097
+ }
10098
+ w.checking = false;
10099
+ if (writes.get(key2) !== w) return;
10100
+ if (status === "confirmed" || status === "reverted") {
10101
+ if (w.timer) clearTimeout(w.timer);
10102
+ w.timer = void 0;
10103
+ w.status = status;
10104
+ notify();
10105
+ if (status === "confirmed") {
10106
+ try {
10107
+ window.dispatchEvent(new CustomEvent(TX_HISTORY_EVENT, { detail: { account: lower4(w.tx.from) } }));
10108
+ } catch {
10109
+ }
10110
+ }
10111
+ }
10112
+ }
10113
+ function schedule(key2) {
10114
+ const w = writes.get(key2);
10115
+ if (!w) return;
10116
+ if (w.timer) clearTimeout(w.timer);
10117
+ w.timer = void 0;
10118
+ if (w.status !== "checking") return;
10119
+ if (Date.now() - w.since >= ZDH_RECHECK_FOR_MS) {
10120
+ w.status = "stalled";
10121
+ notify();
10122
+ return;
10123
+ }
10124
+ w.timer = setTimeout(async () => {
10125
+ w.timer = void 0;
10126
+ if (!hidden3()) await check2(key2);
10127
+ schedule(key2);
10128
+ }, ZDH_RECHECK_MS);
10129
+ }
10130
+ function useZdHeavyAction(a) {
10131
+ const [phase, setPhase] = react.useState("idle");
10132
+ const [error, setError] = react.useState(null);
10133
+ const [switching, setSwitching] = react.useState(false);
10134
+ const alive = react.useRef(true);
10135
+ const [, rerender] = react.useReducer((n) => n + 1, 0);
10136
+ react.useEffect(() => {
10137
+ alive.current = true;
10138
+ listeners.add(rerender);
10139
+ return () => {
10140
+ alive.current = false;
10141
+ listeners.delete(rerender);
10142
+ };
10143
+ }, []);
10144
+ const walletEpoch = react.useRef(0);
10145
+ const walletKey = `${lower4(a.account)}:${a.walletChainId ?? ""}`;
10146
+ const lastWalletKey = react.useRef(walletKey);
10147
+ if (lastWalletKey.current !== walletKey) {
10148
+ lastWalletKey.current = walletKey;
10149
+ walletEpoch.current += 1;
10150
+ }
10151
+ const key2 = a.account ? lockKey(a.account, a.orderId, a.chainId, a.kind, a.asset) : "";
10152
+ const write = key2 ? writes.get(key2) : void 0;
10153
+ const scope = a.kind === "cancel" ? cancelScope(a.lotKeys ?? []) : claimScope(a.asset, a.amount);
10154
+ react.useEffect(() => {
10155
+ if (!key2 || !unresolved(writes.get(key2))) return;
10156
+ void check2(key2).then(() => schedule(key2));
10157
+ }, [key2]);
10158
+ const firedFor = react.useRef(null);
10159
+ const onConfirmed = a.onConfirmed;
10160
+ react.useEffect(() => {
10161
+ if (write?.status === "confirmed" && firedFor.current !== write.hash) {
10162
+ firedFor.current = write.hash;
10163
+ onConfirmed?.(write.hash);
10164
+ }
10165
+ });
10166
+ const supported = SUPPORTED_CHAIN_IDS.has(a.chainId);
10167
+ const connected2 = !!a.account && !!a.provider;
10168
+ const isOwner = !!a.account && lower4(a.account) === lower4(a.owner);
10169
+ const onChain = supported && a.walletChainId === a.chainId;
10170
+ const busy = phase === "preparing" || phase === "signing";
10171
+ const done = write?.status === "confirmed" && write.scope === scope;
10172
+ async function run() {
10173
+ const { engine, provider, account } = a;
10174
+ if (!engine || !provider || !account || !supported) return;
10175
+ const key3 = lockKey(account, a.orderId, a.chainId, a.kind, a.asset);
10176
+ const prior = writes.get(key3);
10177
+ if (unresolved(prior) || prior?.status === "confirmed" && prior.scope === scope) {
10178
+ setError(`This ${a.kind} was already sent. Wait for it to confirm.`);
10179
+ return;
10180
+ }
10181
+ if (inFlight2.has(key3)) {
10182
+ setError(`This ${a.kind} is already in progress. Wait for it to finish.`);
10183
+ return;
10184
+ }
10185
+ if (prior) writes.delete(key3);
10186
+ inFlight2.add(key3);
10187
+ const epoch = walletEpoch.current;
10188
+ const signer = account;
10189
+ const stale = () => !alive.current || walletEpoch.current !== epoch;
10190
+ setError(null);
10191
+ setPhase("preparing");
10192
+ try {
10193
+ const unsigned2 = a.kind === "cancel" ? await engine.buildZdHeavyCancelTx(a.orderId, a.chainId) : await engine.buildZdHeavyClaimTx(a.orderId, a.chainId, a.asset ?? "");
10194
+ const checked = a.kind === "cancel" ? checkZdHeavyCancelTx(unsigned2, { orderId: a.orderId, owner: signer, chainId: a.chainId, lotKeys: a.lotKeys }) : checkZdHeavyClaimTx(unsigned2, { owner: signer, chainId: a.chainId, token: a.asset ?? "" });
10195
+ if (!checked.ok) {
10196
+ if (alive.current) {
10197
+ setError(checked.reason);
10198
+ setPhase("idle");
10199
+ }
10200
+ return;
10201
+ }
10202
+ const minNonce = await engine.payerNonceBaseline(checked.chainId, signer);
10203
+ if (stale()) throw new Error(`The wallet changed while the ${a.kind} was prepared. Try again.`);
10204
+ const [walletChain, accounts] = await Promise.all([getChainId(provider), getAccounts(provider)]);
10205
+ if (stale()) throw new Error(`The wallet changed while the ${a.kind} was prepared. Try again.`);
10206
+ if (walletChain !== checked.chainId) throw new Error(`Switch your wallet to ${a.chainName} and try again.`);
10207
+ if (!accounts.some((x) => lower4(x) === lower4(signer))) throw new Error("The connected wallet changed. Try again.");
10208
+ setPhase("signing");
10209
+ const sentScope = a.kind === "cancel" ? cancelScope(decodeZdHeavyCancel(checked.tx.data).keys.map(String)) : claimScope(decodeZdHeavyClaim(checked.tx.data).token, a.amount);
10210
+ const hash2 = await sendTransaction(provider, { ...checked.tx, chainId: checked.chainId });
10211
+ writes.set(key3, {
10212
+ hash: hash2,
10213
+ chainId: checked.chainId,
10214
+ tx: checked.tx,
10215
+ minNonce,
10216
+ engine,
10217
+ scope: sentScope,
10218
+ since: Date.now(),
10219
+ status: "checking",
10220
+ checking: false
10221
+ });
10222
+ notify();
10223
+ if (alive.current) setPhase("idle");
10224
+ await check2(key3);
10225
+ schedule(key3);
10226
+ } catch (e) {
10227
+ if (!alive.current) return;
10228
+ const msg = normalizeWalletError(e, "");
10229
+ setError(msg ? `Could not ${a.kind === "claim" ? "claim" : "cancel"}: ${msg}` : `Could not prepare the ${a.kind}.`);
10230
+ setPhase("idle");
10231
+ } finally {
10232
+ inFlight2.delete(key3);
10233
+ }
10234
+ }
10235
+ function retryCheck() {
10236
+ const w = key2 ? writes.get(key2) : void 0;
10237
+ if (!w || !unresolved(w)) return;
10238
+ w.since = Date.now();
10239
+ w.status = "checking";
10240
+ notify();
10241
+ void check2(key2).then(() => schedule(key2));
10242
+ }
10243
+ const text = !connected2 ? "Connect wallet" : !supported ? `Unsupported network ${a.chainId}` : !isOwner ? a.kind === "claim" ? "Connected wallet is not the refund address" : "Connected wallet is not the order owner" : !onChain ? switching ? "Switching\u2026" : `Switch to ${a.chainName}` : done ? a.kind === "claim" ? "Claimed" : `Cancelled on ${a.chainName}` : phase === "preparing" ? "Preparing\u2026" : phase === "signing" ? "Signing\u2026" : a.label;
10244
+ const disabled = !connected2 ? !a.onConnect : !supported || !isOwner || (!onChain ? switching : busy || done || unresolved(write));
10245
+ function onClick() {
10246
+ if (busy || switching) return;
10247
+ if (!connected2) return a.onConnect?.();
10248
+ if (!onChain && supported && a.provider) {
10249
+ setSwitching(true);
10250
+ setError(null);
10251
+ switchChain(a.provider, a.chainId).catch((e) => alive.current && setError(normalizeWalletError(e, `Could not switch to ${a.chainName}.`))).finally(() => alive.current && setSwitching(false));
10252
+ return;
10253
+ }
10254
+ void run();
10255
+ }
10256
+ const reverted = write?.status === "reverted" ? `The ${a.kind} reverted on-chain. Nothing changed.` : null;
10257
+ return {
10258
+ text,
10259
+ disabled,
10260
+ onClick,
10261
+ retryCheck,
10262
+ sentHash: write?.hash ?? null,
10263
+ done,
10264
+ busy,
10265
+ error: error ?? reverted,
10266
+ pending: write?.status === "checking",
10267
+ stalled: write?.status === "stalled"
10268
+ };
10269
+ }
10270
+ var ZDH_PLAN_REFRESH_MS = 1e4;
10271
+ var hidden4 = () => typeof document !== "undefined" && document.visibilityState === "hidden";
10272
+ var settled = (plan) => plan.complete && (plan.finished === true || plan.state === "refund_complete");
10273
+ function useZdHeavyRecovery(engine, orderId) {
10274
+ const [state, setState] = react.useState({ orderId, value: { status: "loading" } });
10275
+ const readRef = react.useRef(() => {
10276
+ });
10277
+ react.useEffect(() => {
10278
+ setState({ orderId, value: { status: "loading" } });
10279
+ if (!engine || !isZdHeavyOrderId(orderId)) return;
10280
+ let alive = true;
10281
+ let timer2;
10282
+ let shown = false;
10283
+ let started2 = Date.now();
10284
+ const read = async () => {
10285
+ if (timer2) clearTimeout(timer2);
10286
+ timer2 = void 0;
10287
+ if (!hidden4()) {
10288
+ const plan = await engine.fetchZdHeavyCancellation(orderId);
10289
+ if (!alive) return;
10290
+ if (plan) {
10291
+ shown = true;
10292
+ setState({ orderId, value: { status: "ready", plan } });
10293
+ if (settled(plan)) return;
10294
+ } else if (!shown) {
10295
+ setState({ orderId, value: { status: "unavailable" } });
10296
+ }
10297
+ }
10298
+ if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) return;
10299
+ timer2 = setTimeout(read, ZDH_PLAN_REFRESH_MS);
10300
+ };
10301
+ readRef.current = () => {
10302
+ started2 = Date.now();
10303
+ void read();
10304
+ };
10305
+ void read();
10306
+ return () => {
10307
+ alive = false;
10308
+ readRef.current = () => {
10309
+ };
10310
+ if (timer2) clearTimeout(timer2);
10311
+ };
10312
+ }, [engine, orderId]);
10313
+ const refresh = react.useCallback(() => readRef.current(), []);
10314
+ return { state: state.orderId === orderId ? state.value : { status: "loading" }, refresh };
10315
+ }
10316
+ function useZdHeavySourceBinding(engine, chainId, hash2, orderId) {
10317
+ const key2 = `${chainId ?? ""}:${hash2}:${orderId ?? ""}`;
10318
+ const [state, setState] = react.useState({ key: key2, value: "checking" });
10319
+ react.useEffect(() => {
10320
+ setState({ key: key2, value: "checking" });
10321
+ if (!engine || typeof chainId !== "number" || !isZdHeavyOrderId(orderId)) {
10322
+ setState({ key: key2, value: "unbound" });
10323
+ return;
10324
+ }
10325
+ let alive = true;
10326
+ engine.verifyZdHeavySourceOrder(chainId, hash2, orderId).then((r) => alive && setState({ key: key2, value: r.ok ? "bound" : "unbound" })).catch(() => alive && setState({ key: key2, value: "unbound" }));
10327
+ return () => {
10328
+ alive = false;
10329
+ };
10330
+ }, [engine, chainId, hash2, orderId, key2]);
10331
+ return state.key === key2 ? state.value : "checking";
10332
+ }
10333
+ var lower5 = (s) => (s ?? "").toLowerCase();
10334
+ var shortHash = (h2) => `${h2.slice(0, 10)}\u2026${h2.slice(-8)}`;
10335
+ function showsZdHeavyRecovery(entry) {
10336
+ if (entry.protocol !== "zdheavy" || !isZdHeavyOrderId(entry.orderId)) return false;
10337
+ return !(entry.delivery === "delivered" && !entry.claimable);
10338
+ }
10339
+ function ZdHeavyRecovery(props) {
10340
+ const orderId = isZdHeavyOrderId(props.entry.orderId) ? props.entry.orderId : void 0;
10341
+ const binding = useZdHeavySourceBinding(props.engine, props.entry.chainId, props.entry.hash, orderId);
10342
+ const { state, refresh } = useZdHeavyRecovery(props.engine, binding === "bound" ? orderId : void 0);
10343
+ const view = state.status === "ready" ? zdHeavyRecovery(state.plan, props.account) : null;
10344
+ if (!orderId) return null;
10345
+ if (binding === "unbound") {
10346
+ return /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-note sg-zdh-status", role: "status", "data-testid": "zdh-recovery-unbound", children: "This order could not be matched to its transaction on-chain, so it cannot be cancelled or claimed from here." });
10347
+ }
10348
+ if (state.status === "unavailable") {
10349
+ return /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-note sg-zdh-status", role: "status", "aria-live": "polite", "data-testid": "zdh-recovery-unavailable", children: "Cancellation status is unavailable right now. It is checked again in a moment." });
10350
+ }
10351
+ if (binding === "checking" || state.status === "loading" || !view) {
10352
+ return /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-note sg-zdh-status", role: "status", "aria-live": "polite", children: "Checking whether this order can be cancelled\u2026" });
10353
+ }
10354
+ const plan = state.plan;
10355
+ if (view.kind === "delivered" || view.kind === "not-owner") return null;
10356
+ const chainName3 = (id) => CHAIN_LABELS[id] || `Chain ${id}`;
10357
+ const listNames = (ids) => {
10358
+ const names = ids.map(chainName3);
10359
+ return names.length <= 1 ? names[0] ?? "" : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
10360
+ };
10361
+ const amountLabel = (chainId, asset, amount) => {
10362
+ const t = (props.tokens ?? []).find((x) => Number(x.chainId) === chainId && lower5(String(x.address)) === lower5(asset));
10363
+ if (!t) return "your funds";
10364
+ try {
10365
+ return `${formatUnits(amount, Number(t.decimals))} ${t.symbol}`;
10366
+ } catch {
10367
+ return t.symbol;
10368
+ }
10369
+ };
10370
+ const bid = props.entry.fromTicker || props.entry.fromAsset || "funds";
10371
+ let headline;
10372
+ let body;
10373
+ let actions = [];
10374
+ let refunds = [];
10375
+ if (view.kind === "claim") {
10376
+ headline = "Ready to claim";
10377
+ body = `The refund could not be sent to your wallet automatically, so it is waiting for you on ${listNames([...new Set(view.claims.map((c) => c.chainId))])}. Confirm the claim in your wallet to receive it.`;
10378
+ actions = view.claims.map((c) => ({
10379
+ // The signer is part of the key: another wallet's claim is another button, not this one's state.
10380
+ key: `claim:${c.chainId}:${c.token}:${props.account ?? ""}`,
10381
+ kind: "claim",
10382
+ chainId: c.chainId,
10383
+ asset: c.token,
10384
+ amount: c.amount,
10385
+ label: `Claim ${amountLabel(c.chainId, c.token, c.amount)}`,
10386
+ // The payee: the claim reads claimable[msg.sender], so only it can send this.
10387
+ owner: props.account ?? ""
10388
+ }));
10389
+ } else if (view.kind === "cancel") {
10390
+ const holding = plan.places.some((p) => p.lots.length > 0);
10391
+ headline = view.requested ? "Finish the cancellation" : "You can cancel this order and reclaim your funds";
10392
+ body = view.requested ? `Part of your ${bid} is still held by the order router on ${listNames(view.chains)}. Cancel there too to have it refunded.` : holding ? view.chains.length > 1 ? `Your ${bid} is held by the order router on ${listNames(view.chains)}. Cancel on each network to have it refunded, one signature per network.` : `Your ${bid} is held by the order router on ${listNames(view.chains)}. Cancel it and the router refunds what it holds in the same transaction.` : `Your ${bid} is on its way between networks. If you cancel, the order stops and the funds are refunded when they land; you may be asked to cancel once more on the network they reach.`;
10393
+ actions = view.chains.map((chainId) => {
10394
+ const lots = plan.places.find((p) => p.kind === "router" && p.chainId === chainId)?.lots ?? [];
10395
+ return {
10396
+ key: `cancel:${chainId}:${props.account ?? ""}`,
10397
+ kind: "cancel",
10398
+ chainId,
10399
+ label: view.chains.length > 1 || view.requested ? `Cancel on ${chainName3(chainId)}` : "Cancel order",
10400
+ owner: plan.owner,
10401
+ lotKeys: lots.length ? lots.map((l) => l.key) : void 0
10402
+ };
10403
+ });
10404
+ } else if (view.kind === "refunded") {
10405
+ headline = "Cancellation reported by ZeroDelta";
10406
+ body = `ZeroDelta reports your ${bid} as refunded. This widget has not checked the refund on-chain.`;
10407
+ refunds = view.refunds.map((r) => r.txHash);
10408
+ } else {
10409
+ headline = "What happens next";
10410
+ body = "Your cancellation is in. Funds still travelling between networks are refunded when they land; this page updates by itself.";
10411
+ }
10412
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-zdh", "data-testid": "zdh-recovery", "data-zdh-recovery": view.kind, children: [
10413
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-zdh-title", children: headline }),
10414
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-zdh-body", children: body }),
10415
+ actions.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-zdh-actions", children: actions.map(({ key: key2, ...a }) => /* @__PURE__ */ jsxRuntime.jsx(
10416
+ ZdHeavyActionButton,
10417
+ {
10418
+ ...a,
10419
+ engine: props.engine,
10420
+ provider: props.provider,
10421
+ account: props.account,
10422
+ walletChainId: props.walletChainId,
10423
+ onConnect: props.onConnect,
10424
+ orderId,
10425
+ chainName: chainName3(a.chainId),
10426
+ onConfirmed: refresh
10427
+ },
10428
+ key2
10429
+ )) }) : null,
10430
+ refunds.map((hash2) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-txd-hash", children: [
10431
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Reported refund tx" }),
10432
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-mono", children: shortHash(hash2) })
10433
+ ] }, hash2))
10434
+ ] });
10435
+ }
10436
+ function ZdHeavyActionButton(args) {
10437
+ const a = useZdHeavyAction(args);
10438
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-zdh-action", children: [
10439
+ a.pending ? (
10440
+ // A write of this wallet for this order is broadcast and its receipt has not decided: no button,
10441
+ // on this mount or any later one, until it does (re-review 2026-12-01, finding 4).
10442
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-note", role: "status", "aria-live": "polite", "data-testid": "zdh-action-pending", children: "Sent \u2014 confirming" })
10443
+ ) : a.stalled ? (
10444
+ // Still undecided after the bounded recheck: say so, and offer another CHECK — never a new send.
10445
+ /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
10446
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-note", role: "status", "data-testid": "zdh-action-stalled", children: "Not confirmed yet \u2014 check the transaction" }),
10447
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-btn sg-btn-ghost", onClick: a.retryCheck, children: "Retry check" })
10448
+ ] })
10449
+ ) : /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-btn sg-btn-ghost", onClick: a.onClick, disabled: a.disabled, "data-zdh-action": args.kind, children: a.text }),
10450
+ a.error ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-ws-error", role: "alert", "data-testid": "zdh-action-error", children: a.error }) : null,
10451
+ a.sentHash ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-txd-hash", children: [
10452
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: args.kind === "claim" ? "Claim tx" : "Cancel tx" }),
10453
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-mono", children: shortHash(a.sentHash) })
10454
+ ] }) : null
10455
+ ] });
10456
+ }
9626
10457
  function BackGlyph() {
9627
10458
  return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "17", height: "17", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
9628
10459
  /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M19 12H5" }),
@@ -9709,6 +10540,7 @@ function TxLegs(props) {
9709
10540
  function statusBadge(entry) {
9710
10541
  if (entry.delivery === "delivered")
9711
10542
  return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Delivered" });
10543
+ if (entry.delivery === "failed" && entry.deliveryStatus === "cancelled") return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", children: "Cancellation reported" });
9712
10544
  if (entry.delivery === "failed")
9713
10545
  return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Not delivered" });
9714
10546
  if (entry.delivery === "attention")
@@ -9853,7 +10685,20 @@ function TxDetail(props) {
9853
10685
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Tx hash" }),
9854
10686
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-mono", children: `${e.hash.slice(0, 10)}\u2026${e.hash.slice(-8)}` }),
9855
10687
  /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-copy", onClick: copyHash, "aria-label": copied ? "Copied" : "Copy transaction hash", "aria-live": "polite", title: "Copy transaction hash", children: copied ? /* @__PURE__ */ jsxRuntime.jsx(CheckGlyph, {}) : /* @__PURE__ */ jsxRuntime.jsx(CopyGlyph, {}) })
9856
- ] })
10688
+ ] }),
10689
+ props.recovery?.engine && showsZdHeavyRecovery(e) ? /* @__PURE__ */ jsxRuntime.jsx(
10690
+ ZdHeavyRecovery,
10691
+ {
10692
+ entry: e,
10693
+ engine: props.recovery.engine,
10694
+ provider: props.recovery.provider,
10695
+ account: props.recovery.account,
10696
+ walletChainId: props.recovery.walletChainId,
10697
+ onConnect: props.recovery.onConnect,
10698
+ tokens: props.tokens
10699
+ },
10700
+ e.orderId
10701
+ ) : null
9857
10702
  ] });
9858
10703
  }
9859
10704
  function displayableHistory(entries, account) {
@@ -9882,7 +10727,15 @@ function TxHistoryPanel(props) {
9882
10727
  account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress3(account) }) : null
9883
10728
  ] })
9884
10729
  ] }),
9885
- selected ? /* @__PURE__ */ jsxRuntime.jsx(TxDetail, { entry: selected, tokens: props.tokens, vaultIcons: props.vaultIcons }) : /* @__PURE__ */ jsxRuntime.jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
10730
+ selected ? /* @__PURE__ */ jsxRuntime.jsx(
10731
+ TxDetail,
10732
+ {
10733
+ entry: selected,
10734
+ tokens: props.tokens,
10735
+ vaultIcons: props.vaultIcons,
10736
+ recovery: { engine: props.engine, provider: props.provider, account, walletChainId: props.walletChainId, onConnect: props.onConnect }
10737
+ }
10738
+ ) : /* @__PURE__ */ jsxRuntime.jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
9886
10739
  ] });
9887
10740
  }
9888
10741
 
@@ -9914,7 +10767,7 @@ function registry(win) {
9914
10767
  const existing = registries.get(win);
9915
10768
  if (existing) return existing;
9916
10769
  const standard = /* @__PURE__ */ new Set();
9917
- const listeners = /* @__PURE__ */ new Set();
10770
+ const listeners2 = /* @__PURE__ */ new Set();
9918
10771
  let snapshot = EMPTY2;
9919
10772
  const read = () => {
9920
10773
  const candidates = [...standard].map(solanaWalletInfo);
@@ -9945,7 +10798,7 @@ function registry(win) {
9945
10798
  const refresh = () => {
9946
10799
  const previous = snapshot;
9947
10800
  read();
9948
- if (previous !== snapshot) for (const cb of listeners) cb();
10801
+ if (previous !== snapshot) for (const cb of listeners2) cb();
9949
10802
  };
9950
10803
  const api = {
9951
10804
  register(...wallets) {
@@ -9959,9 +10812,9 @@ function registry(win) {
9959
10812
  }
9960
10813
  };
9961
10814
  const result = { read, watch: (cb) => {
9962
- listeners.add(cb);
10815
+ listeners2.add(cb);
9963
10816
  return () => {
9964
- listeners.delete(cb);
10817
+ listeners2.delete(cb);
9965
10818
  };
9966
10819
  } };
9967
10820
  registries.set(win, result);
@@ -11167,13 +12020,13 @@ function PaymentIsland(props) {
11167
12020
  const exFromBal = exFrom && exFromToken ? exBalances[balanceKey(exFrom.chainId, exFromToken.address)] : void 0;
11168
12021
  const fundingTokens = react.useMemo(() => {
11169
12022
  const seen = /* @__PURE__ */ new Set();
11170
- const list = [];
12023
+ const list2 = [];
11171
12024
  for (const r of visibleRoutes) {
11172
12025
  const key2 = balanceKey(r.source.chainId, r.source.tokenAddress);
11173
12026
  if (seen.has(key2)) continue;
11174
12027
  seen.add(key2);
11175
12028
  const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
11176
- list.push(
12029
+ list2.push(
11177
12030
  reg ?? {
11178
12031
  symbol: r.source.asset,
11179
12032
  displaySymbol: r.source.ticker,
@@ -11184,7 +12037,7 @@ function PaymentIsland(props) {
11184
12037
  }
11185
12038
  );
11186
12039
  }
11187
- return list;
12040
+ return list2;
11188
12041
  }, [visibleRoutes, registryTokens]);
11189
12042
  const fundingChains = react.useMemo(() => {
11190
12043
  const ids = new Set(fundingTokens.map((t) => Number(t.chainId)));
@@ -11192,15 +12045,15 @@ function PaymentIsland(props) {
11192
12045
  }, [chains, fundingTokens]);
11193
12046
  const payableAssets = react.useMemo(() => {
11194
12047
  const seen = /* @__PURE__ */ new Set();
11195
- const list = [];
12048
+ const list2 = [];
11196
12049
  for (const { route } of held) {
11197
12050
  const symbol = symbolKey(route.source.asset);
11198
12051
  if (seen.has(symbol)) continue;
11199
12052
  seen.add(symbol);
11200
12053
  const token = registryTokens.find((t) => Number(t.chainId) === route.source.chainId && addrEq(t.address, route.source.tokenAddress));
11201
- list.push({ symbol: route.source.asset, logoUrl: token?.logoUrl });
12054
+ list2.push({ symbol: route.source.asset, logoUrl: token?.logoUrl });
11202
12055
  }
11203
- return list;
12056
+ return list2;
11204
12057
  }, [held, registryTokens]);
11205
12058
  const userPicked = react.useRef(false);
11206
12059
  const selectRoute = react.useCallback(
@@ -11418,7 +12271,7 @@ function PaymentIsland(props) {
11418
12271
  ] });
11419
12272
  let body;
11420
12273
  if (hist && wallet.account) {
11421
- body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
12274
+ body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, provider: wallet.provider, walletChainId: wallet.chainId, onConnect: wallet.connect, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
11422
12275
  } else if (isPay && view === "select" && wallet.account) {
11423
12276
  body = /* @__PURE__ */ jsxRuntime.jsx(
11424
12277
  TokenSelect,
@@ -11702,22 +12555,22 @@ function PillLauncher(props) {
11702
12555
  if (e.key !== "Tab") return;
11703
12556
  const root = dialogRef.current;
11704
12557
  if (!root) return;
11705
- const list = Array.from(root.querySelectorAll("a[href],button,input,select,textarea,[tabindex]")).filter(
12558
+ const list2 = Array.from(root.querySelectorAll("a[href],button,input,select,textarea,[tabindex]")).filter(
11706
12559
  (el) => el.tabIndex >= 0 && !el.hasAttribute("disabled") && el.getClientRects().length > 0
11707
12560
  );
11708
- if (list.length === 0) {
12561
+ if (list2.length === 0) {
11709
12562
  e.preventDefault();
11710
12563
  return;
11711
12564
  }
11712
- const first = list[0];
11713
- const last = list[list.length - 1];
11714
- const idx = list.indexOf(document.activeElement);
12565
+ const first = list2[0];
12566
+ const last = list2[list2.length - 1];
12567
+ const idx = list2.indexOf(document.activeElement);
11715
12568
  if (e.shiftKey) {
11716
12569
  if (idx <= 0) {
11717
12570
  e.preventDefault();
11718
12571
  last.focus();
11719
12572
  }
11720
- } else if (idx === -1 || idx === list.length - 1) {
12573
+ } else if (idx === -1 || idx === list2.length - 1) {
11721
12574
  e.preventDefault();
11722
12575
  first.focus();
11723
12576
  }
@@ -11890,12 +12743,12 @@ function PayCard(props) {
11890
12743
  const registryTokens = react.useMemo(() => catalogue?.tokens ?? [], [catalogue]);
11891
12744
  const fundingTokens = react.useMemo(() => {
11892
12745
  const seen = /* @__PURE__ */ new Set();
11893
- const list = [];
12746
+ const list2 = [];
11894
12747
  const push = (chainId, address, fallback) => {
11895
12748
  const key2 = balanceKey(chainId, address);
11896
12749
  if (seen.has(key2)) return;
11897
12750
  seen.add(key2);
11898
- list.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
12751
+ list2.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
11899
12752
  };
11900
12753
  for (const r of visibleRoutes) {
11901
12754
  push(r.source.chainId, r.source.tokenAddress, {
@@ -11910,7 +12763,7 @@ function PayCard(props) {
11910
12763
  for (const o of unquoted) {
11911
12764
  push(o.chainId, o.address, { symbol: o.symbol, displaySymbol: o.ticker, name: o.name, chainId: o.chainId, address: o.address, decimals: o.decimals, logoUrl: o.logoUrl });
11912
12765
  }
11913
- return list;
12766
+ return list2;
11914
12767
  }, [visibleRoutes, unquoted, registryTokens]);
11915
12768
  const fundingChains = react.useMemo(() => {
11916
12769
  const ids = new Set(fundingTokens.map((t) => Number(t.chainId)));
@@ -12016,7 +12869,7 @@ function PayCard(props) {
12016
12869
  ...durationLabel(sel.quote.estimatedDuration) ? [{ label: "Estimated time", value: durationLabel(sel.quote.estimatedDuration) }] : []
12017
12870
  ] : [];
12018
12871
  const loadingPlan = flow.status === "loading" || holdings.loading && !sel || pricing !== null;
12019
- return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Complete payment", theme: config.theme, heightPx: props.heightPx, walletSlot, onClose: props.onClose, children: hist && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) : view === "select" && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(
12872
+ return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Complete payment", theme: config.theme, heightPx: props.heightPx, walletSlot, onClose: props.onClose, children: hist && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, provider: wallet.provider, walletChainId: wallet.chainId, onConnect: wallet.connect, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) : view === "select" && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(
12020
12873
  TokenSelect,
12021
12874
  {
12022
12875
  title: "Pay with",
@@ -12201,7 +13054,7 @@ function StableGenieSwap(props) {
12201
13054
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-brand", children: "ZeroDelta" })
12202
13055
  ] }) : void 0;
12203
13056
  if (hist && wallet.account) {
12204
- return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) });
13057
+ return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, provider: wallet.provider, walletChainId: wallet.chainId, onConnect: wallet.connect, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) });
12205
13058
  }
12206
13059
  if (recipientState.open) return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsxRuntime.jsx(RecipientSheet, { state: recipientState, symbol: toAsset }) });
12207
13060
  if (flow.status === "success" || flow.status === "pending") {
@@ -12491,16 +13344,16 @@ function Hint({ id, label: label2, text, hint }) {
12491
13344
  open ? /* @__PURE__ */ jsxRuntime.jsx("span", { role: "tooltip", id: tipId, className: "sg-cd-tip", children: text }) : null
12492
13345
  ] });
12493
13346
  }
12494
- function CheckRow2({ check: check2, hideNote }) {
12495
- const label2 = check2.id === "risk" ? check2.ok ? "Risk screening passed" : "Risk screening failed" : check2.label;
12496
- return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: "sg-cd-check", "data-ok": check2.ok, children: [
13347
+ function CheckRow2({ check: check3, hideNote }) {
13348
+ const label2 = check3.id === "risk" ? check3.ok ? "Risk screening passed" : "Risk screening failed" : check3.label;
13349
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: "sg-cd-check", "data-ok": check3.ok, children: [
12497
13350
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cd-check-line", children: [
12498
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-mark", "data-ok": check2.ok, children: check2.ok ? /* @__PURE__ */ jsxRuntime.jsx(Tick, { size: 12 }) : /* @__PURE__ */ jsxRuntime.jsx(Cross, { size: 12 }) }),
13351
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-mark", "data-ok": check3.ok, children: check3.ok ? /* @__PURE__ */ jsxRuntime.jsx(Tick, { size: 12 }) : /* @__PURE__ */ jsxRuntime.jsx(Cross, { size: 12 }) }),
12499
13352
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-label", children: label2 }),
12500
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: check2.ok ? " \u2014 passed" : " \u2014 failed" })
13353
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", children: check3.ok ? " \u2014 passed" : " \u2014 failed" })
12501
13354
  ] }),
12502
- check2.note && !hideNote ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-note", children: check2.note }) : null,
12503
- check2.reasons.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-reason", children: humanizeComplianceReason(reason) }, reason))
13355
+ check3.note && !hideNote ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-note", children: check3.note }) : null,
13356
+ check3.reasons.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cd-check-reason", children: humanizeComplianceReason(reason) }, reason))
12504
13357
  ] });
12505
13358
  }
12506
13359
  function Fact2({ label: label2, value, title, mono = false }) {
@@ -12535,10 +13388,10 @@ function QuoteChecks2(props) {
12535
13388
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-summary-sub", children: "The gateway returned no compliance decision for this quote, so there is nothing to show. It is not a failed check." })
12536
13389
  )
12537
13390
  ] }),
12538
- checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cd-checks", children: checks.map((check2) => (
13391
+ checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cd-checks", children: checks.map((check3) => (
12539
13392
  // The Figma row carries no sub-line: with ONE screened wallet the note would repeat the
12540
13393
  // address Quote details names two cards down. Any other note (a count of wallets) stays.
12541
- /* @__PURE__ */ jsxRuntime.jsx(CheckRow2, { check: check2, hideNote: check2.id === "screening" && wallets.length === 1 && hasDetails }, check2.id)
13394
+ /* @__PURE__ */ jsxRuntime.jsx(CheckRow2, { check: check3, hideNote: check3.id === "screening" && wallets.length === 1 && hasDetails }, check3.id)
12542
13395
  )) }) : null,
12543
13396
  orphans.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "sg-cd-orphans", children: orphans.map((reason) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: humanizeComplianceReason(reason) }, reason)) }) : null,
12544
13397
  props.direct && checks.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "sg-cd-scope", children: DIRECT_SCOPE_NOTE }) : null
@@ -12993,10 +13846,10 @@ function QuoteCard(props) {
12993
13846
  const hops = option.hops;
12994
13847
  const collapsed = side && hops.length > 3;
12995
13848
  const inline = collapsed ? [hops[0], hops[1], "gap", hops[hops.length - 1]] : hops;
12996
- const hidden3 = collapsed ? hops.slice(2, -1) : [];
13849
+ const hidden5 = collapsed ? hops.slice(2, -1) : [];
12997
13850
  const routeIcons = /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-cq-route-icons", "data-testid": "compare-route-inline", children: inline.map((hop, i) => /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-hop-inline", children: [
12998
13851
  i > 0 ? /* @__PURE__ */ jsxRuntime.jsx(ArrowGlyph2, {}) : null,
12999
- hop === "gap" ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cq-gap", title: hidden3.map((h2) => `${h2.ticker} on ${props.chainName(h2.chainId)}`).join(" \u2192 "), "aria-label": `Also via ${hidden3.map((h2) => `${h2.ticker} on ${props.chainName(h2.chainId)}`).join(", ")}`, children: "\u2026" }) : /* @__PURE__ */ jsxRuntime.jsx("span", { title: `${hop.ticker} on ${props.chainName(hop.chainId)}`, children: /* @__PURE__ */ jsxRuntime.jsx(HopMark, { hop, tokens: props.tokens, size: "xxs" }) })
13852
+ hop === "gap" ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "sg-cq-gap", title: hidden5.map((h2) => `${h2.ticker} on ${props.chainName(h2.chainId)}`).join(" \u2192 "), "aria-label": `Also via ${hidden5.map((h2) => `${h2.ticker} on ${props.chainName(h2.chainId)}`).join(", ")}`, children: "\u2026" }) : /* @__PURE__ */ jsxRuntime.jsx("span", { title: `${hop.ticker} on ${props.chainName(hop.chainId)}`, children: /* @__PURE__ */ jsxRuntime.jsx(HopMark, { hop, tokens: props.tokens, size: "xxs" }) })
13000
13853
  ] }, hop === "gap" ? "gap" : `${hop.chainId}-${hop.address}-${i}`)) });
13001
13854
  const fee = compareFeeLabel(option.feeUsd);
13002
13855
  const tagEl = tags.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("span", { ref: tagRef, className: "sg-cq-tag", "data-kind": nettingTag ? "netting" : purple ? "purple" : "brand", children: tags.map((tag, i) => /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-cq-tag-item", children: [
@@ -13719,7 +14572,7 @@ function ExchangeCard(props) {
13719
14572
  let body;
13720
14573
  let takeover = false;
13721
14574
  if (hist && connected2) {
13722
- body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, solanaAccount: solanaWallet.address, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
14575
+ body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, engine, provider: wallet.provider, walletChainId: wallet.chainId, onConnect: wallet.connect, solanaAccount: solanaWallet.address, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
13723
14576
  } else if (view === "from" || view === "to") {
13724
14577
  const isFrom = view === "from";
13725
14578
  body = /* @__PURE__ */ jsxRuntime.jsx(