@glacislabs/stablegenie-zerodelta 3.3.0 → 4.0.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.
@@ -1,8 +1,29 @@
1
1
  // src/core/constants.ts
2
2
  var DEFAULT_WIDGET_API_BASE = "/api/widget/v1";
3
3
  var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146, 98866]);
4
- var SUPPORTED_ASSETS = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE", "XAUT"]);
4
+ var EXECUTABLE_STABLE_ASSETS = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE", "USDTB", "AUSD", "PYUSD", "USDG"]);
5
+ var STABLE_ASSETS = /* @__PURE__ */ new Set([...EXECUTABLE_STABLE_ASSETS, "USD1", "WM", "USDS", "DAI", "RLUSD"]);
6
+ var TRADEABLE_RWA_ASSETS = /* @__PURE__ */ new Set([
7
+ "XAUT",
8
+ // Nest vault shares — chained delivery on Plume, sellable from their Ethereum deployment.
9
+ "NALPHA",
10
+ "NTBILL",
11
+ "NBASIS",
12
+ "NCREDIT",
13
+ "NOPAL",
14
+ "NWISDOM",
15
+ "NACRDX",
16
+ "NLCRD",
17
+ "NAXI",
18
+ "NCLOA",
19
+ "NFALCON",
20
+ // Centrifuge deRWA pair — chained asks on Base.
21
+ "DEJAAA",
22
+ "DESPXA"
23
+ ]);
24
+ var SUPPORTED_ASSETS = /* @__PURE__ */ new Set([...STABLE_ASSETS, ...TRADEABLE_RWA_ASSETS]);
5
25
  var API_CACHE_TTL_MS = 6e4;
26
+ var SCREEN_CACHE_TTL_MS = 5 * 6e4;
6
27
  var MAX_QUOTE_CANDIDATES = 8;
7
28
  var QUOTE_BUFFER_BPS = 50;
8
29
  var LZ_FEE_BUFFER_BPS = 1500n;
@@ -14,7 +35,41 @@ var ERC20_ALLOWANCE_SELECTOR = "0xdd62ed3e";
14
35
  var ERC20_BALANCEOF_SELECTOR = "0x70a08231";
15
36
  var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
16
37
  var PREVIEW_OWNER = "0x1111111111111111111111111111111111111111";
17
- var CANONICAL_DECIMALS = { USDC: 6, USDT: 6, USDE: 18, XAUT: 6 };
38
+ var CANONICAL_DECIMALS = {
39
+ USDC: 6,
40
+ USDT: 6,
41
+ USDE: 18,
42
+ XAUT: 6,
43
+ // Added 2026-09-08 with the dapp-parity asset expansion. Every value below was read from the
44
+ // token contract itself — `eth_call decimals()` against each deployment the registry lists on the
45
+ // nine escrow chains — and each symbol answered the SAME number on every chain it is deployed on.
46
+ // The set is a deliberate mix of 6 and 18, and a copy-pasted row is wrong by a factor of 1e12
47
+ // while still looking entirely plausible in review; that is the bug this pin exists to prevent.
48
+ USDTB: 18,
49
+ AUSD: 6,
50
+ PYUSD: 6,
51
+ USDG: 6,
52
+ // The wider stable list — the bid side of an RWA trade.
53
+ DAI: 18,
54
+ RLUSD: 18,
55
+ USD1: 18,
56
+ USDS: 18,
57
+ WM: 6,
58
+ // Real-world assets. Every Nest vault share is 6; the Centrifuge pair is 18.
59
+ NALPHA: 6,
60
+ NTBILL: 6,
61
+ NBASIS: 6,
62
+ NCREDIT: 6,
63
+ NOPAL: 6,
64
+ NWISDOM: 6,
65
+ NACRDX: 6,
66
+ NLCRD: 6,
67
+ NAXI: 6,
68
+ NCLOA: 6,
69
+ NFALCON: 6,
70
+ DEJAAA: 18,
71
+ DESPXA: 18
72
+ };
18
73
  var CANONICAL_ESCROW = Object.freeze({
19
74
  1: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
20
75
  // Ethereum
@@ -44,9 +99,40 @@ var CANONICAL_INBOUND_BRIDGE = {
44
99
  USDC: "cctp",
45
100
  USDT: "layerzero",
46
101
  USDE: "layerzero",
47
- XAUT: "layerzero"
102
+ XAUT: "layerzero",
103
+ // 2026-09-08: the four assets added for dapp parity are all LayerZero V2 OFTs on every chain the
104
+ // registry lists them on (`standard: "LayerZeroV2OFT"`, verified against dev and prod /tokens).
105
+ // USDC remains the only CCTP asset.
106
+ USDTB: "layerzero",
107
+ AUSD: "layerzero",
108
+ PYUSD: "layerzero",
109
+ USDG: "layerzero",
110
+ // `"none"` is a POSITIVE statement, not a gap: these assets have no inbound bridge adapter at all
111
+ // (the registry says `bridge: "None"`, or ships no bridge field at all), so they can only ever be
112
+ // bid on the chain the order already executes on and can never legitimately owe a native
113
+ // LayerZero fee. Pinning them matters because the fallback for an UNpinned asset is the label
114
+ // sniff, and a hostile quote controls the label — `bridge: "layerzero"` on one of these would
115
+ // otherwise let it attach msg.value to an order that forwards none, stranding it in the escrow.
116
+ DAI: "none",
117
+ RLUSD: "none",
118
+ USD1: "none",
119
+ USDS: "none",
120
+ WM: "none",
121
+ NALPHA: "none",
122
+ NTBILL: "none",
123
+ NBASIS: "none",
124
+ NCREDIT: "none",
125
+ NOPAL: "none",
126
+ NWISDOM: "none",
127
+ NACRDX: "none",
128
+ NLCRD: "none",
129
+ NAXI: "none",
130
+ NCLOA: "none",
131
+ NFALCON: "none",
132
+ DEJAAA: "none",
133
+ DESPXA: "none"
48
134
  };
49
- var SAME_CLASS_STABLE = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE"]);
135
+ var SAME_CLASS_STABLE = new Set(STABLE_ASSETS);
50
136
  var MAX_SAME_CLASS_PAY_BPS = 30000n;
51
137
  var BUNDLED_NATIVE_SYMBOL = {
52
138
  1: "ETH",
@@ -69,6 +155,55 @@ var BUNDLED_RPC = {
69
155
  42161: "https://arb1.arbitrum.io/rpc",
70
156
  98866: "https://rpc.plume.org"
71
157
  };
158
+ var CHAIN_DISPLAY_NAMES = Object.freeze({
159
+ 1: "Ethereum",
160
+ 10: "Optimism",
161
+ 14: "Flare",
162
+ 30: "Rootstock",
163
+ 50: "XDC Network",
164
+ 56: "BNB Chain",
165
+ 88: "Viction",
166
+ 130: "Unichain",
167
+ 137: "Polygon",
168
+ 143: "Monad",
169
+ 146: "Sonic",
170
+ 151: "Redbelly Network",
171
+ 169: "Manta Pacific",
172
+ 196: "X Layer",
173
+ 252: "Fraxtal",
174
+ 324: "zkSync Era",
175
+ 480: "World Chain",
176
+ 988: "Stable",
177
+ 999: "HyperEVM",
178
+ 1030: "Conflux eSpace",
179
+ 1088: "Metis",
180
+ 1135: "Lisk",
181
+ 1329: "Sei",
182
+ 1776: "Injective EVM",
183
+ 1868: "Soneium",
184
+ 1923: "Swellchain",
185
+ 2222: "Kava",
186
+ 2818: "Morph",
187
+ 3343: "EDGE",
188
+ 4326: "MegaETH",
189
+ 5e3: "Mantle",
190
+ 8453: "Base",
191
+ 9745: "Plasma",
192
+ 34443: "Mode",
193
+ 42161: "Arbitrum One",
194
+ 43114: "Avalanche C-Chain",
195
+ 48900: "Zircuit",
196
+ 57073: "Ink",
197
+ 59144: "Linea",
198
+ 80094: "Berachain",
199
+ 81224: "Codex",
200
+ 81457: "Blast",
201
+ 98866: "Plume",
202
+ 534352: "Scroll",
203
+ 747474: "Katana",
204
+ 7777777: "Zora",
205
+ 21e6: "Corn"
206
+ });
72
207
 
73
208
  // src/core/address.ts
74
209
  function symbolKey(value) {
@@ -333,10 +468,129 @@ function applyLayerZeroBuffer(quote, option = {}) {
333
468
  return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
334
469
  }
335
470
 
471
+ // src/core/availability.ts
472
+ function assetClassOf(symbol) {
473
+ const key = symbolKey(symbol);
474
+ if (TRADEABLE_RWA_ASSETS.has(key)) return "rwa";
475
+ if (STABLE_ASSETS.has(key)) return "stable";
476
+ return null;
477
+ }
478
+ function productAssets(product) {
479
+ return product === "rwa" ? /* @__PURE__ */ new Set([...STABLE_ASSETS, ...TRADEABLE_RWA_ASSETS]) : EXECUTABLE_STABLE_ASSETS;
480
+ }
481
+ function counterpartTokens(tokens, selected) {
482
+ const want = assetClassOf(selected?.symbol) === "rwa" ? "stable" : "rwa";
483
+ return tokens.filter((token) => assetClassOf(token.symbol) === want);
484
+ }
485
+ function tokenKey(chainId, address) {
486
+ return `${Number(chainId)}:${String(address || "").toLowerCase()}`;
487
+ }
488
+ function laneKey(fromChainId, fromAddress, toChainId, toAddress) {
489
+ return `${tokenKey(fromChainId, fromAddress)}>${tokenKey(toChainId, toAddress)}`;
490
+ }
491
+ function isExecutableBridge(descriptor) {
492
+ const bridge = descriptor?.bridge?.trim().toLowerCase();
493
+ const standard = descriptor?.standard?.replace(/[\s_-]/g, "").toLowerCase();
494
+ return (bridge === "circle" || bridge === "cctp") && standard === "cctpv2" || bridge === "layerzero" && standard === "layerzerov2oft";
495
+ }
496
+ function isKnownUnbridgeable(bridge) {
497
+ return typeof bridge === "string" && bridge.trim().toLowerCase() === "none";
498
+ }
499
+ function executableRoutes(routes) {
500
+ return routes.filter((route) => route.isEnabled !== false && isExecutableBridge(route));
501
+ }
502
+ function sourceKeys(routes) {
503
+ return new Set(routes.filter((r) => r.isEnabled !== false).map((r) => tokenKey(r.fromChainId, r.fromAddress ?? "")));
504
+ }
505
+ function destinationKeys(routes) {
506
+ return new Set(routes.filter((r) => r.isEnabled !== false).map((r) => tokenKey(r.toChainId, r.toAddress ?? "")));
507
+ }
508
+ function laneKeys(routes) {
509
+ return new Set(routes.filter((r) => r.isEnabled !== false).map((r) => laneKey(r.fromChainId, r.fromAddress ?? "", r.toChainId, r.toAddress ?? "")));
510
+ }
511
+ function executionChainIds(chains) {
512
+ return new Set(chains.filter((c) => c.isEnabled !== false && c.isExecutionChain === true).map((c) => Number(c.chainId)));
513
+ }
514
+ function hubDeliverableSymbols(tokens, execution) {
515
+ return new Set(tokens.filter((t) => execution.has(Number(t.chainId))).map((t) => symbolKey(t.symbol)));
516
+ }
517
+ function isSourceToken(token, ctx) {
518
+ const chainId = Number(token.chainId);
519
+ if (!ctx.sourceChains.has(chainId)) return false;
520
+ return ctx.execution.has(chainId) || !isKnownUnbridgeable(token.bridge) && ctx.source.has(tokenKey(chainId, token.address));
521
+ }
522
+ function directLaneOK(token, source, lanes) {
523
+ if (!source || !lanes) return true;
524
+ if (symbolKey(source.symbol) !== symbolKey(token.symbol)) return true;
525
+ if (Number(source.chainId) === Number(token.chainId)) return true;
526
+ return lanes.has(laneKey(source.chainId, source.address, token.chainId, token.address));
527
+ }
528
+ function brokenLaneFor(token, source, brokenLanes) {
529
+ if (!source || !brokenLanes) return void 0;
530
+ return brokenLanes.get(laneKey(source.chainId, source.address, token.chainId, token.address));
531
+ }
532
+ function destinationAvailability(token, ctx, source) {
533
+ if (brokenLaneFor(token, source ?? void 0, ctx.brokenLanes)) return "unreachable";
534
+ if (ctx.execution.has(Number(token.chainId))) return "available";
535
+ if (token.isChainedDestination === true) return "available";
536
+ if (!isKnownUnbridgeable(token.bridge) && ctx.destination.has(tokenKey(token.chainId, token.address)) && directLaneOK(token, source ?? void 0, ctx.lanes)) {
537
+ return "available";
538
+ }
539
+ return ctx.hubSymbols.has(symbolKey(token.symbol)) ? "hub-only" : "unreachable";
540
+ }
541
+ function hasReachableDestination(source, catalogue, ctx) {
542
+ if (catalogue.length === 0) return true;
543
+ const from = tokenKey(source.chainId, source.address);
544
+ for (const candidate of catalogue) {
545
+ if (tokenKey(candidate.chainId, candidate.address) === from) continue;
546
+ if (destinationAvailability(candidate, ctx, source) === "available") return true;
547
+ }
548
+ return false;
549
+ }
550
+ function buildCatalogue(input) {
551
+ const { chains, tokens, routes, supportedChainIds, brokenLanes } = input;
552
+ const product = input.product ?? "stable";
553
+ const universe = productAssets(product);
554
+ const allowedAssets = input.allowedAssets ? new Set([...input.allowedAssets].filter((a) => universe.has(a))) : universe;
555
+ const enabledChains = chains.filter((c) => c.isEnabled !== false);
556
+ const registryChainIds = new Set(enabledChains.map((c) => Number(c.chainId)));
557
+ const sourceChains = new Set([...registryChainIds].filter((id) => supportedChainIds.has(id)));
558
+ const execution = executionChainIds(enabledChains);
559
+ const projected = product === "rwa" ? routes.filter((route) => route.isEnabled !== false) : executableRoutes(routes);
560
+ const source = sourceKeys(projected);
561
+ const destination = destinationKeys(projected);
562
+ const lanes = laneKeys(projected);
563
+ const chainIds = new Set(sourceChains);
564
+ for (const route of projected) {
565
+ const id = Number(route.toChainId);
566
+ if (Number.isSafeInteger(id) && id > 0) chainIds.add(id);
567
+ }
568
+ const allowed = tokens.filter((token) => token.isEnabled !== false && allowedAssets.has(symbolKey(token.symbol)));
569
+ const projectedCatalogue = allowed.filter((token) => {
570
+ if (!chainIds.has(Number(token.chainId))) return false;
571
+ if (product === "rwa") return true;
572
+ if (!isExecutableBridge(token)) return false;
573
+ const key = tokenKey(token.chainId, token.address);
574
+ return source.has(key) || destination.has(key) || execution.has(Number(token.chainId));
575
+ });
576
+ const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
577
+ const catalogue = ready ? projectedCatalogue : allowed;
578
+ const hubSymbols = hubDeliverableSymbols(catalogue, execution);
579
+ const ctx = { source, destination, lanes, execution, sourceChains, hubSymbols, ...brokenLanes ? { brokenLanes } : {} };
580
+ const sources = ready ? catalogue.filter((token) => isSourceToken(token, ctx) && hasReachableDestination(token, catalogue, ctx)) : (
581
+ // Unprojected: the only rule we can still apply with confidence is the escrow-chain bound,
582
+ // which comes from this build's own pins rather than from the registry.
583
+ catalogue.filter((token) => sourceChains.has(Number(token.chainId)))
584
+ );
585
+ const byId = new Map(enabledChains.map((c) => [Number(c.chainId), c]));
586
+ for (const id of chainIds) if (!byId.has(id)) byId.set(id, { chainId: id, isEnabled: true });
587
+ return { ...ctx, product, tokens: catalogue, sources, chainIds, chains: [...byId.values()], ready };
588
+ }
589
+
336
590
  // src/core/options.ts
337
591
  function chainNameOf(chainId, chains) {
338
592
  const chain = chains.find((item) => Number(item.chainId) === Number(chainId));
339
- return chain?.displayName || chain?.name || `Chain ${chainId}`;
593
+ return chain?.displayName || chain?.name || CHAIN_DISPLAY_NAMES[Number(chainId)] || `Chain ${chainId}`;
340
594
  }
341
595
  function chainById(chains, chainId) {
342
596
  return chains.find((chain) => Number(chain.chainId) === Number(chainId)) || null;
@@ -357,45 +611,57 @@ function findToken(tokens, chainId, symbol) {
357
611
  const key = symbolKey(symbol);
358
612
  return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key) || null;
359
613
  }
360
- function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId }) {
614
+ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
361
615
  const invoiceKey = symbolKey(invoiceAsset);
362
- const tokenBySymbolAndChain = /* @__PURE__ */ new Map();
363
- for (const token of tokens) {
364
- if (!tokenEnabled(token)) continue;
365
- const key = symbolKey(token.symbol);
366
- if (!tokenBySymbolAndChain.has(key)) tokenBySymbolAndChain.set(key, /* @__PURE__ */ new Map());
367
- tokenBySymbolAndChain.get(key).set(Number(token.chainId), token);
368
- }
616
+ const invoiceChain = Number(invoiceChainId);
617
+ const live = catalogue?.ready ? catalogue : null;
618
+ const destinationToken = findToken(tokens, invoiceChain, invoiceKey);
369
619
  const routeBridge = /* @__PURE__ */ new Map();
370
620
  for (const route of routes || []) {
371
- if (route.isEnabled === false || Number(route.toChainId) !== Number(invoiceChainId)) continue;
621
+ if (route.isEnabled === false || Number(route.toChainId) !== invoiceChain) continue;
372
622
  routeBridge.set(`${symbolKey(route.tokenName || route.tokenId)}:${Number(route.fromChainId)}`, route.bridge);
373
623
  routeBridge.set(`${symbolKey(route.tokenId)}:${Number(route.fromChainId)}`, route.bridge);
374
624
  }
375
- const receiveDeliverable = isDeliverable(invoiceKey, invoiceChainId);
376
- const options = [];
377
- for (const [payKey, byChain] of tokenBySymbolAndChain.entries()) {
378
- if (!byChain.has(Number(invoiceChainId))) continue;
379
- for (const [chainId, token] of byChain.entries()) {
380
- const chain = chainById(chains, chainId);
381
- if (!chainSelectable(chain, chainId)) continue;
382
- const direct = chainId === Number(invoiceChainId) && payKey === invoiceKey;
383
- if (!direct && payKey === invoiceKey) continue;
384
- if (!direct && (!receiveDeliverable || !isDeliverable(payKey, chainId))) continue;
385
- options.push({
386
- symbol: token.symbol,
387
- symbolKey: payKey,
388
- name: token.name || token.symbol,
389
- chainId,
390
- chainName: chainNameOf(chainId, chains),
391
- address: token.address,
392
- decimals: assetDecimals(token),
393
- logoUrl: token.logoUrl,
394
- bridge: routeBridge.get(`${payKey}:${chainId}`) || token.bridge,
395
- sameChain: chainId === Number(invoiceChainId),
396
- direct
397
- });
625
+ const knownLanes = live?.lanes && live.lanes.size > 0 ? live.lanes : null;
626
+ function refusal(token) {
627
+ const sameSymbol = symbolKey(token.symbol) === invoiceKey;
628
+ const sameChain = Number(token.chainId) === invoiceChain;
629
+ if (sameSymbol && sameChain) return null;
630
+ if (live && destinationToken && brokenLaneFor(destinationToken, token, live.brokenLanes)) return "measured";
631
+ if (live && !isSourceToken(token, live)) return "not-a-source";
632
+ if (sameSymbol && knownLanes && !knownLanes.has(laneKey(token.chainId, token.address, invoiceChain, destinationToken?.address ?? ""))) {
633
+ return "no-direct-lane";
398
634
  }
635
+ if (live && destinationToken && destinationAvailability(destinationToken, live, token) !== "available") return "undeliverable";
636
+ return null;
637
+ }
638
+ const options = [];
639
+ const seen = /* @__PURE__ */ new Set();
640
+ const universe = live ? live.tokens : tokens;
641
+ for (const token of universe) {
642
+ if (!tokenEnabled(token)) continue;
643
+ const chainId = Number(token.chainId);
644
+ const chain = chainById(chains, chainId);
645
+ if (!chainSelectable(chain, chainId)) continue;
646
+ const key = tokenKey(chainId, token.address);
647
+ if (seen.has(key)) continue;
648
+ if (refusal(token)) continue;
649
+ seen.add(key);
650
+ const payKey = symbolKey(token.symbol);
651
+ const direct = chainId === invoiceChain && payKey === invoiceKey;
652
+ options.push({
653
+ symbol: token.symbol,
654
+ symbolKey: payKey,
655
+ name: token.name || token.symbol,
656
+ chainId,
657
+ chainName: chainNameOf(chainId, chains),
658
+ address: token.address,
659
+ decimals: assetDecimals(token),
660
+ logoUrl: token.logoUrl,
661
+ bridge: routeBridge.get(`${payKey}:${chainId}`) || token.bridge,
662
+ sameChain: chainId === invoiceChain,
663
+ direct
664
+ });
399
665
  }
400
666
  options.sort((a, b) => {
401
667
  const walletChain = Number(walletChainId || 0);
@@ -454,6 +720,368 @@ function nativeFeeShortMessage(check, symbol, chainName) {
454
720
  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.`;
455
721
  }
456
722
 
723
+ // src/core/route-health.ts
724
+ var EMPTY = /* @__PURE__ */ new Map();
725
+ function suppressedLanes(health) {
726
+ if (health?.mode !== "enforce" || !Array.isArray(health.lanes)) return EMPTY;
727
+ const out = /* @__PURE__ */ new Map();
728
+ for (const lane of health.lanes) {
729
+ if (lane?.status !== "broken") continue;
730
+ const key = typeof lane.laneKey === "string" ? lane.laneKey.toLowerCase() : "";
731
+ if (!key) continue;
732
+ out.set(key, {
733
+ route: typeof lane.route === "string" ? lane.route : "",
734
+ code: typeof lane.code === "string" ? lane.code : "",
735
+ message: typeof lane.message === "string" ? lane.message : "",
736
+ ...typeof lane.kind === "string" ? { kind: lane.kind } : {}
737
+ });
738
+ }
739
+ return out;
740
+ }
741
+ function brokenLaneReason(lane) {
742
+ if (!lane) return "";
743
+ switch (lane.kind) {
744
+ case "bridge-throttled":
745
+ return "The issuer's bridge for this pair is closed right now.";
746
+ case "vault-closed":
747
+ return "This vault is not accepting deposits right now.";
748
+ default:
749
+ return "ZeroDelta could not price this pair in its latest check.";
750
+ }
751
+ }
752
+
753
+ // src/core/compliance.ts
754
+ var COMPLIANCE_DENY_LABEL = "Compliance check failed";
755
+ function complianceView(compliance, hasQuote = true) {
756
+ if (!hasQuote) {
757
+ return {
758
+ tone: "neutral",
759
+ label: "Compliance checks run with your quote",
760
+ headline: "No compliance decision for this payment yet",
761
+ blocked: false,
762
+ needsAction: false,
763
+ screened: false
764
+ };
765
+ }
766
+ const decision = compliance?.decision;
767
+ const screened = compliance?.status === "SCREENED";
768
+ if (decision === "DENY") {
769
+ return {
770
+ tone: "blocked",
771
+ label: COMPLIANCE_DENY_LABEL,
772
+ headline: "Blocked by compliance policy",
773
+ blocked: true,
774
+ needsAction: false,
775
+ screened
776
+ };
777
+ }
778
+ if (decision === "REVIEW" || decision === "REMEDIATE") {
779
+ const word = decision.toLowerCase();
780
+ return {
781
+ tone: "warn",
782
+ label: `Compliance: ${word} required`,
783
+ headline: `Manual ${word} required`,
784
+ blocked: false,
785
+ needsAction: true,
786
+ screened
787
+ };
788
+ }
789
+ if (decision === "ALLOW") {
790
+ return {
791
+ tone: "ok",
792
+ label: screened ? "Compliance checks passed" : "Allowed \u2014 wallets not screened",
793
+ headline: screened ? "Wallets screened and allowed" : "Allowed \u2014 wallets not screened",
794
+ blocked: false,
795
+ needsAction: false,
796
+ screened
797
+ };
798
+ }
799
+ return {
800
+ tone: "neutral",
801
+ label: screened ? "Screened \u2014 no policy decision returned" : "No compliance decision returned",
802
+ headline: screened ? "Screened \u2014 no policy decision returned" : "No compliance decision returned",
803
+ blocked: false,
804
+ needsAction: false,
805
+ screened
806
+ };
807
+ }
808
+ var CATEGORY_PHRASES = {
809
+ SANCTIONS: "sanctions",
810
+ TERRORISM_FINANCING: "terrorism financing",
811
+ STOLEN_FUNDS: "stolen funds",
812
+ RANSOMWARE: "ransomware",
813
+ SCAM: "scam activity",
814
+ DARKNET: "darknet activity",
815
+ MIXER: "mixer usage",
816
+ HIGH_RISK_ENTITY: "a high-risk entity",
817
+ PEP: "a politically-exposed person",
818
+ INDIRECT_EXPOSURE: "indirect exposure",
819
+ UNCLASSIFIED: "an unrecognized risk",
820
+ UNKNOWN: "an unrecognized risk"
821
+ };
822
+ function categoryLabel(code) {
823
+ const key = code.trim().toUpperCase();
824
+ const LABELS = {
825
+ SANCTIONS: "Sanctions",
826
+ TERRORISM_FINANCING: "Terrorist financing",
827
+ STOLEN_FUNDS: "Stolen funds",
828
+ RANSOMWARE: "Ransomware",
829
+ SCAM: "Scam",
830
+ DARKNET: "Darknet services",
831
+ MIXER: "Mixer",
832
+ HIGH_RISK_ENTITY: "High-risk entity",
833
+ PEP: "Politically exposed person (PEP)",
834
+ INDIRECT_EXPOSURE: "Indirect exposure",
835
+ UNCLASSIFIED: "Unclassified risk",
836
+ UNKNOWN: "Unclassified risk"
837
+ };
838
+ return LABELS[key] ?? key.toLowerCase().replace(/_/g, " ");
839
+ }
840
+ function cleanJurisdiction(code) {
841
+ return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
842
+ }
843
+ function stripBundlePrefix(head) {
844
+ if (head.startsWith("policy_")) return { head: head.slice("policy_".length), source: "policy" };
845
+ if (head.startsWith("legislation_")) return { head: head.slice("legislation_".length), source: "legislation" };
846
+ return { head, source: null };
847
+ }
848
+ function complianceReasonHead(raw) {
849
+ return stripBundlePrefix((raw.split(":")[0] ?? "").trim()).head;
850
+ }
851
+ function usd(raw) {
852
+ const n = Number(raw);
853
+ if (!Number.isFinite(n)) return `$${raw}`;
854
+ return `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
855
+ }
856
+ function capFromDetail(detail) {
857
+ const m = detail.match(/>([\d.]+)/);
858
+ return m ? ` (${usd(m[1])})` : "";
859
+ }
860
+ function categoryPhrase(detail) {
861
+ const cat = detail.replace(/\s*\(.*\)$/, "").toUpperCase();
862
+ return CATEGORY_PHRASES[cat] ?? cat.toLowerCase().replace(/_/g, " ");
863
+ }
864
+ function humanizeComplianceReason(raw) {
865
+ const [headRaw, ...restParts] = raw.split(":");
866
+ const detail = restParts.join(":").trim();
867
+ const { head, source } = stripBundlePrefix((headRaw ?? "").trim());
868
+ const scope = source === "legislation" ? "applicable regulations" : "the applicable policy";
869
+ switch (head) {
870
+ case "asset_pair_not_allowed": {
871
+ const m = detail.match(/^(\S+)->(\S+)\s+in\s+(\S+)/);
872
+ if (m) return `${m[1]} \u2192 ${m[2]} isn't available in your region (${cleanJurisdiction(m[3])}).`;
873
+ return "This asset pair isn't available in your region.";
874
+ }
875
+ case "asset_not_allowed": {
876
+ const m = detail.match(/^(\S+?)->(\S+?)(?::|$)/);
877
+ if (m) return `${m[1]} \u2192 ${m[2]} isn't permitted under ${scope}.`;
878
+ return `This asset pair isn't permitted under ${scope}.`;
879
+ }
880
+ case "blocked_jurisdiction":
881
+ return `Your region (${cleanJurisdiction(detail)}) isn't supported.`;
882
+ case "blocked_destination_jurisdiction":
883
+ return `The destination region (${cleanJurisdiction(detail)}) isn't supported.`;
884
+ case "jurisdiction_out_of_scope":
885
+ return `Not covered by ${scope}.`;
886
+ case "ui_block":
887
+ return `Payments aren't available in your region (${cleanJurisdiction(detail)}).`;
888
+ case "blocked_corridor_mode":
889
+ return "This route isn't currently open for payments.";
890
+ case "blocked_category":
891
+ return `Flagged for ${categoryPhrase(detail)}.`;
892
+ case "amount_exceeds_max_order_usd":
893
+ case "amount_exceeds_max":
894
+ return `Amount exceeds the maximum order size${capFromDetail(detail)}.`;
895
+ case "amount_exceeds_actor_cap":
896
+ return `Amount exceeds the limit for your account type${capFromDetail(detail)}.`;
897
+ case "amount_exceeds_jurisdiction_max":
898
+ return `Amount exceeds the limit for your region${capFromDetail(detail)}.`;
899
+ case "source_chain_not_allowed":
900
+ return `The source chain isn't permitted under ${scope}.`;
901
+ case "dest_chain_not_allowed":
902
+ return `The destination chain isn't permitted under ${scope}.`;
903
+ default:
904
+ return detail ? `${head.replace(/_/g, " ")} \u2014 ${detail}` : head.replace(/_/g, " ");
905
+ }
906
+ }
907
+ var COMPLIANCE_CHECK_ORDER = [
908
+ "location",
909
+ "screening",
910
+ "risk",
911
+ "asset",
912
+ "limits"
913
+ ];
914
+ var CHECK_LABELS = {
915
+ location: "Location and corridor permitted",
916
+ screening: "Both wallets screened",
917
+ risk: "Risk policy passed",
918
+ asset: "Asset and amount allowed",
919
+ limits: "Transaction limits verified"
920
+ };
921
+ var CHECK_HEADS = {
922
+ location: [
923
+ "blocked_jurisdiction",
924
+ "blocked_destination_jurisdiction",
925
+ "ui_block",
926
+ "blocked_corridor_mode",
927
+ "jurisdiction_out_of_scope"
928
+ ],
929
+ screening: [],
930
+ risk: ["blocked_category"],
931
+ asset: ["asset_pair_not_allowed", "asset_not_allowed", "source_chain_not_allowed", "dest_chain_not_allowed"],
932
+ limits: [
933
+ "amount_exceeds_max_order_usd",
934
+ "amount_exceeds_max",
935
+ "amount_exceeds_actor_cap",
936
+ "amount_exceeds_jurisdiction_max"
937
+ ]
938
+ };
939
+ function distinctScreenedWallets(compliance) {
940
+ const seen = /* @__PURE__ */ new Set();
941
+ const wallets = [];
942
+ for (const raw of compliance?.screenedWallets ?? []) {
943
+ const address = raw?.trim();
944
+ if (!address) continue;
945
+ const key = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
946
+ if (seen.has(key)) continue;
947
+ seen.add(key);
948
+ wallets.push(address);
949
+ }
950
+ return wallets;
951
+ }
952
+ function shortAddress(a) {
953
+ return a.length > 12 ? `${a.slice(0, 6)}\u2026${a.slice(-4)}` : a;
954
+ }
955
+ function screeningLabel(wallets) {
956
+ if (wallets === 1) return "Wallet screened";
957
+ if (wallets === 2) return CHECK_LABELS.screening;
958
+ return "Wallets screened";
959
+ }
960
+ function complianceChecks(compliance, cv = complianceView(compliance)) {
961
+ if (cv.tone === "neutral") return [];
962
+ const byControl = /* @__PURE__ */ new Map();
963
+ for (const raw of compliance?.reasons ?? []) {
964
+ const head = complianceReasonHead(raw);
965
+ const id = COMPLIANCE_CHECK_ORDER.find((c) => CHECK_HEADS[c].includes(head));
966
+ if (!id) continue;
967
+ byControl.set(id, [...byControl.get(id) ?? [], raw]);
968
+ }
969
+ const screenedWallets = distinctScreenedWallets(compliance);
970
+ const wallets = screenedWallets.length;
971
+ const blocking = compliance?.blockingCategories?.length ?? 0;
972
+ return COMPLIANCE_CHECK_ORDER.map((id) => {
973
+ if (id === "screening") {
974
+ const ok2 = cv.screened || wallets > 0;
975
+ const note = wallets === 1 ? shortAddress(screenedWallets[0]) : wallets > 1 ? `${wallets} wallets screened` : void 0;
976
+ return { id, label: ok2 ? screeningLabel(wallets) : "Wallets not screened", ok: ok2, reasons: [], note };
977
+ }
978
+ const reasons = byControl.get(id) ?? [];
979
+ const ok = reasons.length === 0 && !(id === "risk" && blocking > 0);
980
+ return { id, label: CHECK_LABELS[id], ok, reasons };
981
+ });
982
+ }
983
+ function unattributedComplianceReasons(compliance, cv = complianceView(compliance)) {
984
+ const claimed = new Set(complianceChecks(compliance, cv).flatMap((c) => c.reasons));
985
+ return (compliance?.reasons ?? []).filter((r) => !claimed.has(r));
986
+ }
987
+ function complianceControlsEvaluated(compliance, cv = complianceView(compliance)) {
988
+ const checks = complianceChecks(compliance, cv);
989
+ if (checks.length === 0) return 0;
990
+ const named = /* @__PURE__ */ new Set();
991
+ for (const raw of [...compliance?.appliedPolicyNames ?? [], ...compliance?.appliedLegislation ?? []]) {
992
+ const name = raw?.trim();
993
+ if (name) named.add(name.toLowerCase());
994
+ }
995
+ return checks.length + named.size;
996
+ }
997
+ function complianceControlsLine(compliance, cv = complianceView(compliance)) {
998
+ if (cv.blocked || cv.needsAction) return cv.headline;
999
+ const n = complianceControlsEvaluated(compliance, cv);
1000
+ if (n === 0) return cv.headline;
1001
+ return `${n} compliance control${n === 1 ? "" : "s"} evaluated for this payment`;
1002
+ }
1003
+ function directComplianceFromScreens(screens) {
1004
+ const blockedAny = screens.some((s) => s.blocked);
1005
+ const cats = (pick) => [
1006
+ ...new Set(screens.flatMap((s) => pick(s) ?? []))
1007
+ ];
1008
+ return {
1009
+ status: "SCREENED",
1010
+ decision: blockedAny ? "DENY" : "ALLOW",
1011
+ screenedWallets: screens.map((s) => s.address),
1012
+ riskCategories: cats((s) => s.riskCategories),
1013
+ flaggedCategories: cats((s) => s.flaggedCategories),
1014
+ blockingCategories: cats((s) => s.blockingCategories),
1015
+ reasons: blockedAny ? cats((s) => s.blockingCategories).map((c) => `blocked_category:${c}`) : []
1016
+ };
1017
+ }
1018
+ var DIRECT_CHECK_IDS = ["screening", "risk"];
1019
+ var DIRECT_SCOPE_NOTE = "Direct settlement moves your funds straight to the recipient, so wallet screening applies. Jurisdiction, corridor and amount policy are evaluated on routed payments.";
1020
+ var BLOCK_CATEGORY_LABELS = {
1021
+ STOLEN_FUNDS: "flagged as associated with stolen funds",
1022
+ SANCTIONS: "on a sanctions list",
1023
+ SANCTIONED: "on a sanctions list",
1024
+ OFAC: "on a sanctions list",
1025
+ TERRORIST_FINANCING: "flagged for terrorist financing",
1026
+ TERRORISM_FINANCING: "flagged for terrorist financing",
1027
+ FRAUD: "flagged for fraud",
1028
+ SCAM: "flagged as a scam address"
1029
+ };
1030
+ var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
1031
+ function blockLabelFor(categories) {
1032
+ for (const raw of categories) {
1033
+ const label = BLOCK_CATEGORY_LABELS[String(raw || "").trim().toUpperCase()];
1034
+ if (label) return label;
1035
+ }
1036
+ return BLOCK_LABEL_DEFAULT;
1037
+ }
1038
+ var REASON_TAGS = {
1039
+ blocked_jurisdiction: "Restricted country",
1040
+ ui_block: "Restricted country",
1041
+ blocked_destination_jurisdiction: "Restricted destination",
1042
+ blocked_corridor_mode: "Corridor closed",
1043
+ blocked_category: "Risk flag",
1044
+ amount_exceeds_max_order_usd: "Limit exceeded",
1045
+ amount_exceeds_max: "Limit exceeded",
1046
+ amount_exceeds_actor_cap: "Limit exceeded",
1047
+ amount_exceeds_jurisdiction_max: "Limit exceeded",
1048
+ asset_pair_not_allowed: "Asset not allowed",
1049
+ asset_not_allowed: "Asset not allowed",
1050
+ source_chain_not_allowed: "Chain not allowed",
1051
+ dest_chain_not_allowed: "Chain not allowed",
1052
+ jurisdiction_out_of_scope: "Out of scope"
1053
+ };
1054
+ function complianceReasonTag(raw) {
1055
+ const head = complianceReasonHead(raw);
1056
+ return REASON_TAGS[head] ?? head.replace(/_/g, " ");
1057
+ }
1058
+ function complianceTagOf(compliance) {
1059
+ const first = (compliance?.reasons ?? [])[0];
1060
+ return first ? complianceReasonTag(first) : "";
1061
+ }
1062
+ var FLOOR_CATEGORIES = ["SANCTIONS", "TERRORISM_FINANCING", "STOLEN_FUNDS", "RANSOMWARE"];
1063
+ var TUNABLE_CATEGORIES = ["SCAM", "DARKNET", "MIXER", "HIGH_RISK_ENTITY", "PEP", "INDIRECT_EXPOSURE", "UNCLASSIFIED"];
1064
+ var TUNED_OUTCOMES = {
1065
+ SCAM: "blocked",
1066
+ DARKNET: "blocked",
1067
+ MIXER: "flagged",
1068
+ HIGH_RISK_ENTITY: "flagged",
1069
+ PEP: "flagged",
1070
+ INDIRECT_EXPOSURE: "flagged",
1071
+ UNCLASSIFIED: "flagged"
1072
+ };
1073
+ function screeningOutcomeOf(category) {
1074
+ const key = category.trim().toUpperCase();
1075
+ if (FLOOR_CATEGORIES.includes(key)) return "always-blocked";
1076
+ return TUNED_OUTCOMES[key] ?? null;
1077
+ }
1078
+ var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
1079
+ var SCREENING_BUCKETS = [
1080
+ { outcome: "always-blocked", title: "Always blocked", detail: "Cannot be changed or disabled.", categories: labelsFor("always-blocked") },
1081
+ { outcome: "blocked", title: "Blocked under this policy", detail: "The current policy stops the order.", categories: labelsFor("blocked") },
1082
+ { outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
1083
+ ];
1084
+
457
1085
  // src/core/solve.ts
458
1086
  async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
459
1087
  const destDecimals = assetDecimals(destinationToken);
@@ -690,7 +1318,7 @@ function routeLabelFor(option, destinationToken, result) {
690
1318
  const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
691
1319
  return `Swap ${option.symbol} to ${destinationToken.symbol} and settle on ZeroDelta${bridge}.`;
692
1320
  }
693
- async function buildRoute({ option, destination, destinationToken, chains, payer, fetchQuote, solve = solveExactOut, amountInRaw }) {
1321
+ async function buildRoute({ option, destination, destinationToken, chains, payer, fetchQuote, solve = solveExactOut, amountInRaw, compliance }) {
694
1322
  const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
695
1323
  const quote = result.quote;
696
1324
  const destDecimals = assetDecimals(destinationToken);
@@ -737,7 +1365,11 @@ async function buildRoute({ option, destination, destinationToken, chains, payer
737
1365
  bridge: quote.bridge,
738
1366
  feeBps: quote.feeBps,
739
1367
  estimatedDuration: quote.estimatedDuration,
740
- iterations: result.iterations
1368
+ iterations: result.iterations,
1369
+ // A direct transfer never reaches /quote (solve.ts short-circuits it), so there is no
1370
+ // gateway decision to carry. The caller screens both parties itself and passes the
1371
+ // synthesized verdict in — see plan.ts and compliance.ts::directComplianceFromScreens.
1372
+ compliance
741
1373
  }
742
1374
  };
743
1375
  }
@@ -821,7 +1453,11 @@ async function buildRoute({ option, destination, destinationToken, chains, payer
821
1453
  gasCostSource: quote.gasCostSource,
822
1454
  msgValue: valueRaw.toString(),
823
1455
  deadline: order.deadline,
824
- iterations: result.iterations
1456
+ iterations: result.iterations,
1457
+ // Carried verbatim from the gateway's decision on THIS wallet pair. The projection used to
1458
+ // drop it, which is why the widget could show a price with no evidence of the control that
1459
+ // produced it.
1460
+ compliance: quote.compliance
825
1461
  }
826
1462
  };
827
1463
  }
@@ -857,25 +1493,20 @@ function apiMessage(json, fallback) {
857
1493
  }
858
1494
  return sanitizeMessage(err?.message, fallback);
859
1495
  }
860
- var BLOCK_CATEGORY_LABELS = {
861
- STOLEN_FUNDS: "flagged as associated with stolen funds",
862
- SANCTIONS: "on a sanctions list",
863
- SANCTIONED: "on a sanctions list",
864
- OFAC: "on a sanctions list",
865
- TERRORIST_FINANCING: "flagged for terrorist financing",
866
- FRAUD: "flagged for fraud",
867
- SCAM: "flagged as a scam address"
868
- };
869
- var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
1496
+ function isStructuredComplianceBlock(error) {
1497
+ const code = String(error?.code || "").toUpperCase();
1498
+ if (code === "COMPLIANCE_BLOCKED" || code === "COMPLIANCE_BLOCK") return true;
1499
+ return error?.status === 422 && Array.isArray(error?.reasons) && error.reasons.length > 0;
1500
+ }
870
1501
  function classifyQuoteError(error) {
871
1502
  if (!error) return null;
872
1503
  const reasons = Array.isArray(error.reasons) ? error.reasons : [];
873
1504
  const haystack = `${error.message || ""} ${reasons.join(" ")}`;
874
1505
  const catMatch = /blocked_category:\s*([A-Za-z_]+)/i.exec(haystack);
875
- const isBlock = !!catMatch || error.code === "blocked" || error.code === "compliance_block" || /\b(stolen|sanction(?:s|ed|ing)?|block(?:ed|list)|screen(?:ed|ing)?|compliance|ofac|denylist|blacklist)\b/i.test(haystack);
1506
+ const isBlock = isStructuredComplianceBlock(error) || !!catMatch || error.code === "blocked" || error.code === "compliance_block" || /\b(stolen|sanction(?:s|ed|ing)?|block(?:ed|list)|screen(?:ed|ing)?|compliance|ofac|denylist|blacklist)\b/i.test(haystack);
876
1507
  if (!isBlock) return null;
877
1508
  const category = (catMatch?.[1] || "").toUpperCase() || "COMPLIANCE";
878
- const label = BLOCK_CATEGORY_LABELS[category] || BLOCK_LABEL_DEFAULT;
1509
+ const label = blockLabelFor([category]);
879
1510
  return {
880
1511
  blocked: true,
881
1512
  category,
@@ -896,8 +1527,11 @@ function createApiClient(cfg) {
896
1527
  const cache = {
897
1528
  chains: null,
898
1529
  tokens: null,
899
- routes: null
1530
+ routes: null,
1531
+ health: null
900
1532
  };
1533
+ const screenCache = /* @__PURE__ */ new Map();
1534
+ const screenInflight = /* @__PURE__ */ new Map();
901
1535
  const apiBase = cfg.apiBase.replace(/\/$/, "");
902
1536
  async function apiRequest(path, init = {}) {
903
1537
  const apiKey = await cfg.getApiKey();
@@ -966,6 +1600,18 @@ function createApiClient(cfg) {
966
1600
  return [];
967
1601
  }
968
1602
  }
1603
+ async function fetchRouteHealth() {
1604
+ if (nowFresh(cache.health)) return cache.health.value;
1605
+ let value = null;
1606
+ try {
1607
+ const health = await apiRequest("/route-health", { timeoutMs: 8e3 });
1608
+ value = health && typeof health === "object" && !Array.isArray(health) ? health : null;
1609
+ } catch {
1610
+ value = null;
1611
+ }
1612
+ cache.health = { at: Date.now(), value };
1613
+ return value;
1614
+ }
969
1615
  async function fetchQuote(body, retries = 1) {
970
1616
  let lastError;
971
1617
  for (let attempt = 0; attempt <= retries; attempt += 1) {
@@ -980,7 +1626,32 @@ function createApiClient(cfg) {
980
1626
  }
981
1627
  throw lastError;
982
1628
  }
983
- return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchQuote, apiBase };
1629
+ async function screenWallet(address, chainId) {
1630
+ const addr = String(address || "").trim();
1631
+ if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
1632
+ const key = `${/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr}|${chainId ?? ""}`;
1633
+ const hit = screenCache.get(key);
1634
+ if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
1635
+ const inflight = screenInflight.get(key);
1636
+ if (inflight) return inflight;
1637
+ const request = apiRequest("/screen/wallet", {
1638
+ method: "POST",
1639
+ body: JSON.stringify(chainId == null ? { address: addr } : { address: addr, chainId }),
1640
+ timeoutMs: 12e3
1641
+ }).then((screen) => {
1642
+ if (!screen || typeof screen !== "object" || typeof screen.blocked !== "boolean") {
1643
+ throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
1644
+ }
1645
+ const value = { ...screen, address: screen.address || addr };
1646
+ screenCache.set(key, { at: Date.now(), value });
1647
+ return value;
1648
+ }).finally(() => {
1649
+ screenInflight.delete(key);
1650
+ });
1651
+ screenInflight.set(key, request);
1652
+ return request;
1653
+ }
1654
+ return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchQuote, screenWallet, apiBase };
984
1655
  }
985
1656
 
986
1657
  // src/core/plan.ts
@@ -998,7 +1669,7 @@ function validateDestination(destination) {
998
1669
  assertAddress(destination.address, "Destination address");
999
1670
  const chainId = Number(destination.chainId);
1000
1671
  const asset = symbolKey(destination.asset);
1001
- if (!SUPPORTED_CHAIN_IDS.has(chainId)) throw new Error("Unsupported destination chain.");
1672
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error("Unsupported destination chain.");
1002
1673
  if (!SUPPORTED_ASSETS.has(asset)) throw new Error("Unsupported destination asset.");
1003
1674
  const normalizedAmount = normalizeDecimalText(destination.amount);
1004
1675
  if (!/^\d+(\.\d+)?$/.test(normalizedAmount)) throw new Error("Could not detect a valid payment amount.");
@@ -1012,7 +1683,15 @@ function planErrorSummary(errors) {
1012
1683
  async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances) {
1013
1684
  validateDestination(request);
1014
1685
  assertAddress(payer, "Payer wallet");
1015
- const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
1686
+ const [chains, tokens, routes, health] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes(), api.fetchRouteHealth()]);
1687
+ const catalogue = buildCatalogue({
1688
+ chains,
1689
+ tokens,
1690
+ routes,
1691
+ product: "stable",
1692
+ supportedChainIds: SUPPORTED_CHAIN_IDS,
1693
+ brokenLanes: suppressedLanes(health)
1694
+ });
1016
1695
  const destination = {
1017
1696
  ...request,
1018
1697
  chainId: Number(request.chainId),
@@ -1027,7 +1706,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
1027
1706
  tokens,
1028
1707
  routes,
1029
1708
  chains,
1030
- walletChainId: wallet?.chainId
1709
+ walletChainId: wallet?.chainId,
1710
+ catalogue
1031
1711
  }).filter((option) => option.direct || !allowedFunding || allowedFunding.has(option.symbolKey));
1032
1712
  if (!options.length) throw new Error(`No enabled ZeroDelta funding assets can settle ${destination.asset} on ${chainNameOf(destination.chainId, chains)}.`);
1033
1713
  const balanceTargets = [];
@@ -1039,7 +1719,36 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
1039
1719
  balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
1040
1720
  }
1041
1721
  const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
1042
- const candidates = options.filter((option) => option.direct);
1722
+ const directOptions = options.filter((option) => option.direct);
1723
+ let directCompliance = null;
1724
+ if (directOptions.length) {
1725
+ const parties = [];
1726
+ const seenParty = /* @__PURE__ */ new Set();
1727
+ for (const raw of [payer, destination.address]) {
1728
+ const addr = String(raw || "").trim();
1729
+ if (!addr) continue;
1730
+ const key = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
1731
+ if (seenParty.has(key)) continue;
1732
+ seenParty.add(key);
1733
+ parties.push(addr);
1734
+ }
1735
+ try {
1736
+ const screens = await Promise.all(parties.map((address) => api.screenWallet(address, destination.chainId)));
1737
+ const blocked = screens.filter((screen) => screen.blocked);
1738
+ if (blocked.length) {
1739
+ const who = blocked.some((s) => s.address.toLowerCase() === payer.toLowerCase()) ? "your wallet" : "the recipient";
1740
+ const categories = [...new Set(blocked.flatMap((s) => s.blockingCategories ?? []))];
1741
+ throw apiError(
1742
+ `This payment was blocked by compliance screening \u2014 ${who} is ${blockLabelFor(categories)}. Choose a different recipient or connect a different wallet.`,
1743
+ { blocked: true, blockedCategory: categories[0] || "COMPLIANCE", blockedReason: categories.join(", ") }
1744
+ );
1745
+ }
1746
+ directCompliance = directComplianceFromScreens(screens);
1747
+ } catch (error) {
1748
+ if (error?.blocked) throw error;
1749
+ }
1750
+ }
1751
+ const candidates = directCompliance ? directOptions : [];
1043
1752
  const heldOptions = options.filter((option) => !option.direct && hasPositiveBalance(option, walletBalances));
1044
1753
  const heldKeys = new Set(heldOptions.map(optionBalanceKey));
1045
1754
  const seenChains = /* @__PURE__ */ new Set();
@@ -1059,7 +1768,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
1059
1768
  }
1060
1769
  const routeErrors = [];
1061
1770
  const routePromises = candidates.map(
1062
- (option) => buildRoute({ option, destination, destinationToken, chains, payer, fetchQuote: api.fetchQuote }).catch((error) => {
1771
+ (option) => buildRoute({ option, destination, destinationToken, chains, payer, fetchQuote: api.fetchQuote, compliance: option.direct ? directCompliance ?? void 0 : void 0 }).catch((error) => {
1063
1772
  routeErrors.push(error);
1064
1773
  return null;
1065
1774
  })
@@ -1109,7 +1818,8 @@ function validateSwap(swap = {}) {
1109
1818
  const toChainId = Number(swap.toChainId);
1110
1819
  const fromToken = symbolKey(swap.fromToken);
1111
1820
  const toToken = symbolKey(swap.toToken);
1112
- if (!SUPPORTED_CHAIN_IDS.has(fromChainId) || !SUPPORTED_CHAIN_IDS.has(toChainId)) throw new Error("Unsupported swap chain.");
1821
+ if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
1822
+ if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
1113
1823
  if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken)) throw new Error("Unsupported swap asset.");
1114
1824
  const amountIn = normalizeDecimalText(swap.amountIn);
1115
1825
  if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
@@ -1271,7 +1981,7 @@ async function allowanceCovers(tx, account, ethCall) {
1271
1981
  var STABLEGENIE_INTENT_VERSION = 1;
1272
1982
  var STABLEGENIE_INTENT_TTL_MS = 5 * 60 * 1e3;
1273
1983
  var STABLEGENIE_SUPPORTED_CHAIN_IDS = Object.freeze([1, 10, 130, 146, 8453, 9745, 57073, 42161, 98866]);
1274
- var STABLEGENIE_SUPPORTED_ASSETS = Object.freeze(["USDC", "USDE", "USDT", "XAUT"]);
1984
+ var STABLEGENIE_SUPPORTED_ASSETS = Object.freeze(["USDC", "USDT", "USDE", "USDTB", "AUSD", "PYUSD", "USDG", "USD1", "WM", "USDS", "DAI", "RLUSD", "XAUT", "NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON", "DEJAAA", "DESPXA"]);
1275
1985
  var stableGenieIntentSchema = {
1276
1986
  type: "object",
1277
1987
  additionalProperties: false,
@@ -1301,7 +2011,10 @@ var stableGenieIntentSchema = {
1301
2011
  required: ["address", "chainId", "asset", "amount"],
1302
2012
  properties: {
1303
2013
  address: { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" },
1304
- chainId: { type: "integer", enum: STABLEGENIE_SUPPORTED_CHAIN_IDS },
2014
+ // A DESTINATION chain, so it is bounded by shape, not by the escrow-chain list: a payment may
2015
+ // be delivered on any chain the gateway publishes a route to (~31 of them), while only the
2016
+ // nine escrow chains can SEND one. See validateDestination in plan.ts.
2017
+ chainId: { type: "integer", minimum: 1 },
1305
2018
  chainName: { type: "string", maxLength: 64 },
1306
2019
  asset: { type: "string", enum: STABLEGENIE_SUPPORTED_ASSETS },
1307
2020
  amount: { type: "string", pattern: "^(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" }
@@ -1607,7 +2320,26 @@ function createEngine(config = {}) {
1607
2320
  fetchChains: api.fetchChains,
1608
2321
  fetchTokens: api.fetchTokens,
1609
2322
  fetchRoutes: api.fetchRoutes,
2323
+ fetchRouteHealth: api.fetchRouteHealth,
1610
2324
  fetchQuote: api.fetchQuote,
2325
+ fetchCatalogue: async (allowedAssets, product) => {
2326
+ const [chains, tokens, routes, health] = await Promise.all([
2327
+ api.fetchChains().catch(() => []),
2328
+ api.fetchTokens().catch(() => []),
2329
+ api.fetchRoutes().catch(() => []),
2330
+ api.fetchRouteHealth()
2331
+ ]);
2332
+ const allowed = allowedAssets?.length ? new Set([...allowedAssets].map(symbolKey).filter((a) => SUPPORTED_ASSETS.has(a))) : void 0;
2333
+ return buildCatalogue({
2334
+ chains,
2335
+ tokens,
2336
+ routes,
2337
+ product,
2338
+ ...allowed ? { allowedAssets: allowed } : {},
2339
+ supportedChainIds: SUPPORTED_CHAIN_IDS,
2340
+ brokenLanes: suppressedLanes(health)
2341
+ });
2342
+ },
1611
2343
  fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet, verifier.readBalances),
1612
2344
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
1613
2345
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
@@ -1626,4 +2358,4 @@ function createEngine(config = {}) {
1626
2358
  };
1627
2359
  }
1628
2360
 
1629
- export { API_CACHE_TTL_MS, BUNDLED_NATIVE_SYMBOL, BUNDLED_RPC, CANONICAL_DECIMALS, CANONICAL_ESCROW, CANONICAL_INBOUND_BRIDGE, DEFAULT_WIDGET_API_BASE, ERC20_ALLOWANCE_SELECTOR, ERC20_APPROVE_SELECTOR, ERC20_BALANCEOF_SELECTOR, ERC20_TRANSFER_SELECTOR, LZ_FEE_BUFFER_BPS, MAX_LZ_MSG_VALUE_WEI, MAX_LZ_MSG_VALUE_WEI_BY_CHAIN, MAX_QUOTE_CANDIDATES, MAX_SAME_CLASS_PAY_BPS, MAX_UINT64, NO_PARTNER_ID, PREVIEW_OWNER, QUOTE_BUFFER_BPS, SAME_CLASS_STABLE, STABLEGENIE_INTENT_TTL_MS, STABLEGENIE_INTENT_VERSION, STABLEGENIE_SUPPORTED_ASSETS, STABLEGENIE_SUPPORTED_CHAIN_IDS, SUBMIT_ORDER_SELECTOR, SUPPORTED_ASSETS, SUPPORTED_CHAIN_IDS, ZERO_ADDRESS, addressWord, allowanceCovers, apiError, applyLayerZeroBuffer, assertAddress, assertQuoteMatchesSelection, assetDecimals, buildPayOptions, buildRoute, buildSwapPlan, bytes32Word, bytesPayload, canAttachApiKey, chainById, chainNameOf, chainSelectable, checkEscrow, checkNativeFee, classifyQuoteError, createApiClient, createEngine, createVerifier, decodeSubmitOrderCalldata, encodeAllowance, encodeApprove, encodeBalanceOf, encodeSubmitOrder, encodeTransfer, fetchPaymentPlan, finalOf, findToken, formatNative, formatUnits, isAddress, isDeliverable, isHexAddress, isHexData, isHexQuantity, isLayerZeroRoute, maxNativeFeeWei, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, normalizeOrderRequest, normalizeOrderRequests, parseAllowedApiBase, parseUnitsDecimal, planErrorSummary, planMsgValueHex, quoteSwapPreview, registryRpc, requiresNativeBridgeFee, resolveApiBase, resolveConfig, resolveSwapReceiver, routeNativeValue, scaleDecimals, solveExactIn, solveExactOut, stableGenieIntentSchema, strip0x, symbolKey, toHexQuantity, tokenEnabled, txMatchesPlan, uint64Word, uintWord, validateDestination, validatePlannedTransaction, validateSwap };
2361
+ export { API_CACHE_TTL_MS, BLOCK_LABEL_DEFAULT, BUNDLED_NATIVE_SYMBOL, BUNDLED_RPC, CANONICAL_DECIMALS, CANONICAL_ESCROW, CANONICAL_INBOUND_BRIDGE, CHAIN_DISPLAY_NAMES, COMPLIANCE_CHECK_ORDER, COMPLIANCE_DENY_LABEL, DEFAULT_WIDGET_API_BASE, DIRECT_CHECK_IDS, DIRECT_SCOPE_NOTE, ERC20_ALLOWANCE_SELECTOR, ERC20_APPROVE_SELECTOR, ERC20_BALANCEOF_SELECTOR, ERC20_TRANSFER_SELECTOR, EXECUTABLE_STABLE_ASSETS, FLOOR_CATEGORIES, LZ_FEE_BUFFER_BPS, MAX_LZ_MSG_VALUE_WEI, MAX_LZ_MSG_VALUE_WEI_BY_CHAIN, MAX_QUOTE_CANDIDATES, MAX_SAME_CLASS_PAY_BPS, MAX_UINT64, NO_PARTNER_ID, PREVIEW_OWNER, QUOTE_BUFFER_BPS, SAME_CLASS_STABLE, SCREENING_BUCKETS, SCREEN_CACHE_TTL_MS, STABLEGENIE_INTENT_TTL_MS, STABLEGENIE_INTENT_VERSION, STABLEGENIE_SUPPORTED_ASSETS, STABLEGENIE_SUPPORTED_CHAIN_IDS, STABLE_ASSETS, SUBMIT_ORDER_SELECTOR, SUPPORTED_ASSETS, SUPPORTED_CHAIN_IDS, TRADEABLE_RWA_ASSETS, TUNABLE_CATEGORIES, ZERO_ADDRESS, addressWord, allowanceCovers, apiError, applyLayerZeroBuffer, assertAddress, assertQuoteMatchesSelection, assetClassOf, assetDecimals, blockLabelFor, brokenLaneFor, brokenLaneReason, buildCatalogue, buildPayOptions, buildRoute, buildSwapPlan, bytes32Word, bytesPayload, canAttachApiKey, categoryLabel, chainById, chainNameOf, chainSelectable, checkEscrow, checkNativeFee, classifyQuoteError, complianceChecks, complianceControlsEvaluated, complianceControlsLine, complianceReasonHead, complianceReasonTag, complianceTagOf, complianceView, counterpartTokens, createApiClient, createEngine, createVerifier, decodeSubmitOrderCalldata, destinationAvailability, destinationKeys, directComplianceFromScreens, distinctScreenedWallets, encodeAllowance, encodeApprove, encodeBalanceOf, encodeSubmitOrder, encodeTransfer, executableRoutes, executionChainIds, fetchPaymentPlan, finalOf, findToken, formatNative, formatUnits, hasReachableDestination, hubDeliverableSymbols, humanizeComplianceReason, isAddress, isDeliverable, isExecutableBridge, isHexAddress, isHexData, isHexQuantity, isKnownUnbridgeable, isLayerZeroRoute, isSourceToken, laneKey, laneKeys, maxNativeFeeWei, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, normalizeOrderRequest, normalizeOrderRequests, parseAllowedApiBase, parseUnitsDecimal, planErrorSummary, planMsgValueHex, productAssets, quoteSwapPreview, registryRpc, requiresNativeBridgeFee, resolveApiBase, resolveConfig, resolveSwapReceiver, routeNativeValue, scaleDecimals, screeningOutcomeOf, solveExactIn, solveExactOut, sourceKeys, stableGenieIntentSchema, strip0x, suppressedLanes, symbolKey, toHexQuantity, tokenEnabled, tokenKey, txMatchesPlan, uint64Word, uintWord, unattributedComplianceReasons, validateDestination, validatePlannedTransaction, validateSwap };