@anywalletkit/protocol-swap2-cctp 0.5.4 → 0.5.5

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,6 +1,6 @@
1
1
  import {
2
2
  cctpProvider
3
- } from "./chunk-H4W3JMYC.js";
3
+ } from "./chunk-UPA4KJKX.js";
4
4
  import {
5
5
  cctp
6
6
  } from "./chunk-ZR5XR5RO.js";
@@ -24,4 +24,4 @@ var CctpSwap2Protocol = class extends SingleProviderSwap2 {
24
24
  export {
25
25
  CctpSwap2Protocol
26
26
  };
27
- //# sourceMappingURL=chunk-LK64TDTT.js.map
27
+ //# sourceMappingURL=chunk-3UR3G3XL.js.map
@@ -11,6 +11,7 @@ import {
11
11
  } from "./chunk-ZR5XR5RO.js";
12
12
 
13
13
  // src/provider.ts
14
+ import { httpRefusal, refusal, refusalNotes, withReason } from "@anywalletkit/protocol-swap2-core/errors";
14
15
  import { createPublicClient, decodeFunctionData, encodeFunctionData, getAddress, http, isAddress, pad, parseAbi, zeroHash } from "viem";
15
16
  import { ccAsset } from "@anywalletkit/swap2-assets";
16
17
  import { timeoutSignal } from "@anywalletkit/protocol-swap2-core/util";
@@ -29,6 +30,18 @@ var DEFAULT_QUOTE_TTL_MS = 6e4;
29
30
  var GAS_DEPOSIT = "200000";
30
31
  var GAS_CLAIM = "260000";
31
32
  var isHexData = (v) => typeof v === "string" && /^0x(?:[0-9a-fA-F]{2})+$/.test(v);
33
+ function unreachable(error, signal) {
34
+ if (!signal?.aborted && error instanceof Error) withReason(error, "upstream_unavailable");
35
+ return error;
36
+ }
37
+ function rpcFailure(error) {
38
+ if (!(error instanceof Error)) return error;
39
+ let reverted = false;
40
+ for (let e = error, i = 0; e instanceof Error && i < 8; e = e.cause, i++) {
41
+ if (e.name === "ContractFunctionRevertedError" || e.name === "ContractFunctionZeroDataError" || e.name === "ExecutionRevertedError") reverted = true;
42
+ }
43
+ return withReason(error, reverted ? "simulation_failed" : "upstream_unavailable");
44
+ }
32
45
  var same = (a, b) => !!a && a.toLowerCase() === b.toLowerCase();
33
46
  function feeFor(amount, bps, bufferPct) {
34
47
  const hundredths = BigInt(Math.round(bps * 100));
@@ -57,10 +70,24 @@ function cctpProvider(config = {}) {
57
70
  return url ? createPublicClient({ transport: http(url, { fetchOptions: {}, ...config.fetchImpl ? { fetchFn: config.fetchImpl } : {} }), ccipRead: false }) : null;
58
71
  };
59
72
  async function getJson(path, signal) {
60
- const res = await doFetch(`${api}${path}`, { headers: { accept: "application/json" }, signal: signal ?? timeoutSignal(12e3) });
73
+ let res;
74
+ try {
75
+ res = await doFetch(`${api}${path}`, { headers: { accept: "application/json" }, signal: signal ?? timeoutSignal(12e3) });
76
+ } catch (e) {
77
+ throw unreachable(e, signal);
78
+ }
61
79
  if (res.status === 404) return null;
62
- if (!res.ok) throw new Error(`cctp: ${path} \u2192 ${res.status}`);
63
- return await res.json();
80
+ if (!res.ok) {
81
+ const byStatus = httpRefusal(res.status, res.headers?.get?.("retry-after"));
82
+ const info = byStatus?.reason === "key_rejected" ? { reason: "upstream_unavailable", httpStatus: res.status } : byStatus;
83
+ const error = new Error(`cctp: ${path} \u2192 ${res.status}`);
84
+ throw info ? withReason(error, info) : error;
85
+ }
86
+ try {
87
+ return await res.json();
88
+ } catch (e) {
89
+ throw unreachable(e, signal);
90
+ }
64
91
  }
65
92
  const feeRows = (src, dst, signal) => getJson(`/v2/burn/USDC/fees/${src.domain}/${dst.domain}`, signal);
66
93
  function usdcOf(dom) {
@@ -115,7 +142,7 @@ function cctpProvider(config = {}) {
115
142
  if (!(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === "USDC")) return null;
116
143
  const usdc = usdcOf(src);
117
144
  if (!usdc) {
118
- params.onRefusal?.("catalog USDC on the source chain is not Circle's native USDC");
145
+ params.onRefusal?.("catalog USDC on the source chain is not Circle's native USDC", { reason: "unsupported_pair" });
119
146
  return null;
120
147
  }
121
148
  if (!/^\d+$/.test(params.amountIn)) return null;
@@ -123,7 +150,7 @@ function cctpProvider(config = {}) {
123
150
  if (amount <= 0n) return null;
124
151
  const recipient = params.destAddress || (params.dry !== false ? EVM_PLACEHOLDER : "");
125
152
  if (!recipient) {
126
- params.onRefusal?.("a live quote needs a recipient");
153
+ params.onRefusal?.("a live quote needs a recipient", { reason: "policy_refused" });
127
154
  return null;
128
155
  }
129
156
  if (!isAddress(recipient)) {
@@ -133,7 +160,7 @@ function cctpProvider(config = {}) {
133
160
  try {
134
161
  const fees = await feeRows(src, dst, signal);
135
162
  if (!fees || !Array.isArray(fees) || fees.length === 0) {
136
- params.onRefusal?.("Circle publishes no fee for this pair");
163
+ params.onRefusal?.("Circle publishes no fee for this pair", { reason: !fees || Array.isArray(fees) ? "unsupported_pair" : "upstream_unavailable" });
137
164
  return null;
138
165
  }
139
166
  const fast = fees.find((f) => f.finalityThreshold === FINALITY_FAST);
@@ -142,7 +169,7 @@ function cctpProvider(config = {}) {
142
169
  let bps;
143
170
  if (mode === "standard") {
144
171
  if (!standard) {
145
- params.onRefusal?.("Standard Transfer is not offered for this pair");
172
+ params.onRefusal?.("Standard Transfer is not offered for this pair", { reason: "unsupported_pair" });
146
173
  return null;
147
174
  }
148
175
  threshold = FINALITY_STANDARD;
@@ -157,20 +184,20 @@ function cctpProvider(config = {}) {
157
184
  threshold = FINALITY_FAST;
158
185
  bps = fast.minimumFee;
159
186
  } else if (mode === "fast") {
160
- params.onRefusal?.(fast ? "Fast Transfer allowance is exhausted" : "Fast Transfer is not offered for this pair");
187
+ params.onRefusal?.(fast ? "Fast Transfer allowance is exhausted" : "Fast Transfer is not offered for this pair", { reason: fast ? "insufficient_liquidity" : "unsupported_pair" });
161
188
  return null;
162
189
  } else if (standard) {
163
190
  threshold = FINALITY_STANDARD;
164
191
  bps = standard.minimumFee;
165
192
  } else {
166
- params.onRefusal?.("neither Fast nor Standard is offered");
193
+ params.onRefusal?.("neither Fast nor Standard is offered", { reason: "unsupported_pair" });
167
194
  return null;
168
195
  }
169
196
  }
170
197
  if (!Number.isFinite(bps) || bps < 0) return null;
171
198
  const maxFee = feeFor(amount, bps, bufferPct);
172
199
  if (maxFee >= amount) {
173
- params.onRefusal?.("amount is below the Fast Transfer fee");
200
+ params.onRefusal?.("amount is below the Fast Transfer fee", { reason: "amount_too_small" });
174
201
  return null;
175
202
  }
176
203
  const out = amount - maxFee;
@@ -212,7 +239,7 @@ function cctpProvider(config = {}) {
212
239
  async buildDeposit(quote) {
213
240
  const tx = quote.txRequest;
214
241
  const parsed = parseIntent(quote.intentId);
215
- if (!tx || !parsed) throw new Error("swap2: CCTP quote has no transaction request");
242
+ if (!tx || !parsed) throw refusal("policy_refused", "swap2: CCTP quote has no transaction request");
216
243
  return {
217
244
  chain: parsed.src.caip2,
218
245
  to: tx.to ?? "",
@@ -231,21 +258,25 @@ function cctpProvider(config = {}) {
231
258
  */
232
259
  async preflightDeposit(quote, tx) {
233
260
  const parsed = parseIntent(quote.intentId);
234
- if (!parsed) throw new Error("cctp: malformed intent id");
235
- if (!same(tx.to, parsed.src.tokenMessenger)) throw new Error("cctp: deposit target is not the TokenMessengerV2 of the source domain");
261
+ if (!parsed) throw refusal("policy_refused", "cctp: malformed intent id");
262
+ if (!same(tx.to, parsed.src.tokenMessenger)) throw refusal("vault_mismatch", "cctp: deposit target is not the TokenMessengerV2 of the source domain");
236
263
  if (parsed.threshold === FINALITY_FAST) {
237
264
  const fast = (await feeRows(parsed.src, parsed.dst))?.find((f) => f.finalityThreshold === FINALITY_FAST);
238
- if (!fast || !Number.isFinite(fast.minimumFee) || fast.minimumFee < 0) throw new Error("cctp: Circle no longer publishes a Fast Transfer fee for this pair \u2014 re-quote");
265
+ if (!fast || !Number.isFinite(fast.minimumFee) || fast.minimumFee < 0) throw refusal("quote_expired", "cctp: Circle no longer publishes a Fast Transfer fee for this pair \u2014 re-quote");
239
266
  const minFee = feeFor(BigInt(quote.sourceAmount), fast.minimumFee, 0);
240
267
  const maxFee = BigInt(quote.providerData?.maxFee ?? "0");
241
- if (minFee > maxFee) throw new Error(`cctp: Circle's Fast Transfer fee ${minFee} (${fast.minimumFee} bps) exceeds the quoted maxFee ${maxFee} \u2014 re-quote`);
268
+ if (minFee > maxFee) throw refusal("quote_expired", `cctp: Circle's Fast Transfer fee ${minFee} (${fast.minimumFee} bps) exceeds the quoted maxFee ${maxFee} \u2014 re-quote`);
242
269
  }
243
270
  const c = client(parsed.src.caip2);
244
271
  if (!c) return;
245
- const transmitter = await c.readContract({ address: getAddress(parsed.src.tokenMessenger), abi: TOKEN_MESSENGER_ABI, functionName: "localMessageTransmitter" });
246
- if (!same(transmitter, parsed.src.messageTransmitter)) throw new Error("cctp: TokenMessengerV2 does not point at the expected MessageTransmitterV2");
247
- const domain = await c.readContract({ address: getAddress(parsed.src.messageTransmitter), abi: MESSAGE_TRANSMITTER_ABI, functionName: "localDomain" });
248
- if (Number(domain) !== parsed.src.domain) throw new Error(`cctp: MessageTransmitterV2 reports domain ${domain}, expected ${parsed.src.domain}`);
272
+ const transmitter = await c.readContract({ address: getAddress(parsed.src.tokenMessenger), abi: TOKEN_MESSENGER_ABI, functionName: "localMessageTransmitter" }).catch((e) => {
273
+ throw rpcFailure(e);
274
+ });
275
+ if (!same(transmitter, parsed.src.messageTransmitter)) throw refusal("vault_mismatch", "cctp: TokenMessengerV2 does not point at the expected MessageTransmitterV2");
276
+ const domain = await c.readContract({ address: getAddress(parsed.src.messageTransmitter), abi: MESSAGE_TRANSMITTER_ABI, functionName: "localDomain" }).catch((e) => {
277
+ throw rpcFailure(e);
278
+ });
279
+ if (Number(domain) !== parsed.src.domain) throw refusal("vault_mismatch", `cctp: MessageTransmitterV2 reports domain ${domain}, expected ${parsed.src.domain}`);
249
280
  },
250
281
  async trackIntent(ref) {
251
282
  const parsed = parseIntent(ref.intentId);
@@ -279,10 +310,10 @@ function cctpProvider(config = {}) {
279
310
  const m = await fetchMessage(parsed.src, ref.sourceTxHash);
280
311
  if (!m || m.status !== "complete" || !isHexData(m.attestation) || !isHexData(m.message)) return null;
281
312
  if (m.decodedMessage?.destinationDomain !== void 0 && Number(m.decodedMessage.destinationDomain) !== parsed.dst.domain) {
282
- throw new Error("cctp: attested message is for another destination domain");
313
+ throw refusal("recipient_mismatch", "cctp: attested message is for another destination domain");
283
314
  }
284
315
  if (m.decodedMessage?.sourceDomain !== void 0 && Number(m.decodedMessage.sourceDomain) !== parsed.src.domain) {
285
- throw new Error("cctp: attested message is for another source domain");
316
+ throw refusal("policy_refused", "cctp: attested message is for another source domain");
286
317
  }
287
318
  const exp = m.decodedMessage?.decodedMessageBody?.expirationBlock;
288
319
  const c = client(parsed.dst.caip2);
@@ -309,24 +340,26 @@ function cctpProvider(config = {}) {
309
340
  }
310
341
  };
311
342
  }
343
+ var notes = refusalNotes();
344
+ var why = (text, reason) => notes.note(text, reason);
312
345
  function cctpVerifyQuote(params, quote) {
313
346
  const src = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, params.sourceChain) ? CCTP_DOMAINS[params.sourceChain] : void 0;
314
347
  const dst = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, params.destChain) ? CCTP_DOMAINS[params.destChain] : void 0;
315
- if (!src || !dst || src === dst) return "not a CCTP route between two domains";
316
- if (params.sourceToken.toUpperCase() !== "USDC" || !(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === "USDC")) return "not USDC to USDC";
348
+ if (!src || !dst || src === dst) return why("not a CCTP route between two domains", "unsupported_pair");
349
+ if (params.sourceToken.toUpperCase() !== "USDC" || !(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === "USDC")) return why("not USDC to USDC", "unsupported_pair");
317
350
  const tx = quote.txRequest;
318
- if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return "the quote carries no TokenMessenger call";
319
- if (!same(tx.to, src.tokenMessenger)) return `the call targets ${tx.to}, not the TokenMessengerV2`;
320
- if (BigInt(tx.value ?? "0") !== 0n) return "a burn attaches no value";
321
- if (!tx.approvalAddress || !same(tx.approvalAddress, src.tokenMessenger)) return "the burn approves another spender than the TokenMessengerV2";
322
- if (tx.chainId !== void 0 && tx.chainId !== src.chainId) return `the call is for chain ${tx.chainId}, not ${src.chainId}`;
351
+ if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return why("the quote carries no TokenMessenger call", "policy_refused");
352
+ if (!same(tx.to, src.tokenMessenger)) return why(`the call targets ${tx.to}, not the TokenMessengerV2`, "vault_mismatch");
353
+ if (BigInt(tx.value ?? "0") !== 0n) return why("a burn attaches no value", "policy_refused");
354
+ if (!tx.approvalAddress || !same(tx.approvalAddress, src.tokenMessenger)) return why("the burn approves another spender than the TokenMessengerV2", "vault_mismatch");
355
+ if (tx.chainId !== void 0 && tx.chainId !== src.chainId) return why(`the call is for chain ${tx.chainId}, not ${src.chainId}`, "policy_refused");
323
356
  let args;
324
357
  try {
325
358
  const d = decodeFunctionData({ abi: TOKEN_MESSENGER_ABI, data: tx.data });
326
- if (d.functionName !== "depositForBurn") return `${d.functionName} is not depositForBurn`;
359
+ if (d.functionName !== "depositForBurn") return why(`${d.functionName} is not depositForBurn`, "policy_refused");
327
360
  args = d.args;
328
361
  } catch {
329
- return "the call is not depositForBurn";
362
+ return why("the call is not depositForBurn", "policy_refused");
330
363
  }
331
364
  const [amount, domain, mintRecipient, burnToken, caller, maxFee, threshold] = args;
332
365
  let amountIn, floor;
@@ -335,27 +368,28 @@ function cctpVerifyQuote(params, quote) {
335
368
  floor = BigInt(quote.minDestAmount);
336
369
  if (params.minAmountOut !== void 0 && BigInt(params.minAmountOut) > floor) floor = BigInt(params.minAmountOut);
337
370
  } catch {
338
- return "the request does not name amounts";
371
+ return why("the request does not name amounts", "upstream_unavailable");
339
372
  }
340
- if (amount !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return `the burn moves ${amount}, not the ${amountIn} input`;
341
- if (domain !== dst.domain) return `the burn mints on domain ${domain}, not ${dst.name} (${dst.domain})`;
373
+ if (amount !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return why(`the burn moves ${amount}, not the ${amountIn} input`, "policy_refused");
374
+ if (domain !== dst.domain) return why(`the burn mints on domain ${domain}, not ${dst.name} (${dst.domain})`, "recipient_mismatch");
342
375
  if (params.destAddress || params.dry === false) {
343
376
  if (!isAddress(params.destAddress)) return "the recipient is not an EVM address";
344
- if (mintRecipient.toLowerCase() !== pad(getAddress(params.destAddress), { size: 32 }).toLowerCase()) return `the burn mints to ${mintRecipient}, not the recipient`;
377
+ if (mintRecipient.toLowerCase() !== pad(getAddress(params.destAddress), { size: 32 }).toLowerCase()) return why(`the burn mints to ${mintRecipient}, not the recipient`, "recipient_mismatch");
345
378
  }
346
- if (!same(burnToken, src.usdc)) return `the burn spends ${burnToken}, not the source domain's USDC`;
347
- if (caller !== zeroHash) return "the burn names a destination caller";
348
- if (threshold !== FINALITY_FAST && threshold !== FINALITY_STANDARD) return `finality threshold ${threshold} is neither Fast nor Standard`;
349
- if (maxFee >= amount || amount - maxFee < floor) return `the burn's maxFee ${maxFee} leaves less than the ${floor} minimum`;
350
- if ((/^([\s\S]+)~[0-9a-f]{32}$/.exec(quote.intentId)?.[1] ?? quote.intentId) !== `cctp:${src.domain}:${dst.domain}:${threshold}`) return "the intent id does not name this burn";
351
- if (quote.providerData?.maxFee !== void 0 && quote.providerData.maxFee !== maxFee.toString()) return "the quoted maxFee is not the burn's";
379
+ if (!same(burnToken, src.usdc)) return why(`the burn spends ${burnToken}, not the source domain's USDC`, "policy_refused");
380
+ if (caller !== zeroHash) return why("the burn names a destination caller", "policy_refused");
381
+ if (threshold !== FINALITY_FAST && threshold !== FINALITY_STANDARD) return why(`finality threshold ${threshold} is neither Fast nor Standard`, "policy_refused");
382
+ if (maxFee >= amount || amount - maxFee < floor) return why(`the burn's maxFee ${maxFee} leaves less than the ${floor} minimum`, "price_check_failed");
383
+ if ((/^([\s\S]+)~[0-9a-f]{32}$/.exec(quote.intentId)?.[1] ?? quote.intentId) !== `cctp:${src.domain}:${dst.domain}:${threshold}`) return why("the intent id does not name this burn", "policy_refused");
384
+ if (quote.providerData?.maxFee !== void 0 && quote.providerData.maxFee !== maxFee.toString()) return why("the quoted maxFee is not the burn's", "policy_refused");
352
385
  return null;
353
386
  }
354
387
  var cctpPins = Object.freeze({
355
388
  callTargets: (chain) => cctpMessengerFor(chain),
356
389
  spenders: (chain) => cctpMessengerFor(chain),
357
390
  claimTargets: cctpClaimTargets,
358
- verifyQuote: cctpVerifyQuote
391
+ verifyQuote: cctpVerifyQuote,
392
+ reasonOf: notes.reasonOf
359
393
  });
360
394
  function cctpMessengerFor(chain) {
361
395
  const d = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, chain) ? CCTP_DOMAINS[chain] : void 0;
@@ -368,4 +402,4 @@ export {
368
402
  cctpVerifyQuote,
369
403
  cctpPins
370
404
  };
371
- //# sourceMappingURL=chunk-H4W3JMYC.js.map
405
+ //# sourceMappingURL=chunk-UPA4KJKX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provider.ts"],"sourcesContent":["import type {RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {httpRefusal, refusal, refusalNotes, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {createPublicClient, decodeFunctionData, encodeFunctionData, getAddress, http, isAddress, pad, parseAbi, zeroHash, type Hex} from \"viem\";\nimport {describeCctpActivity} from \"./activity.js\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\nimport {timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {CCTP_API, CCTP_BY_DOMAIN, CCTP_DOMAINS, FINALITY_FAST, FINALITY_STANDARD, cctp as cctpCfg, type CctpDomain} from \"./config.js\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\n\n/**\n * Circle CCTP V2 — native USDC between chains by burn-and-mint, no spread, no\n * aggregator fee. TWO-PHASE: `depositForBurn` on the source burns the USDC and\n * emits the message; Circle's attestation service (Iris) signs it once the\n * source reached the requested finality; `receiveMessage(message, attestation)`\n * on the destination mints. That second transaction is the user's: the engine\n * exposes it through `buildClaim` / `claimSwap2` (status \"action-required\").\n *\n * - Fast Transfer (finality 1000, confirmed, ~seconds–minutes) costs a fee in\n * bps that Circle publishes per pair; Standard (2000, finalized, ~15 min)\n * is free. `mode: \"auto\"` takes Fast when the pair offers it and the Fast\n * allowance covers the amount, else Standard.\n * - `maxFee` sent on-chain is the published fee (plus a small buffer) and is\n * the only thing that can be deducted: the guaranteed output is\n * amount − maxFee. `preflightDeposit` re-reads Circle's published fee right\n * before the burn (the deployed TokenMessengerV2 has no on-chain\n * `getMinFeeAmount`/`minFee` — both revert on Ethereum, Base, Arbitrum,\n * 2026-10-12) and, with an RPC for the source chain, the transmitter's\n * `localDomain()` on the very contract the calldata targets.\n * - Everything is bound to Circle's documented contract addresses and the\n * native USDC of each domain; a catalog USDC that is not the native one\n * refuses the route (USDC.e cannot be burnt).\n */\n\nconst TOKEN_MESSENGER_ABI = parseAbi([\n \"function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold)\",\n \"function localMessageTransmitter() view returns (address)\",\n]);\nconst MESSAGE_TRANSMITTER_ABI = parseAbi([\n \"function receiveMessage(bytes message, bytes attestation) returns (bool)\",\n \"function localDomain() view returns (uint32)\",\n \"function usedNonces(bytes32 nonce) view returns (uint256)\",\n]);\n\nconst EVM_PLACEHOLDER = \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\";\nconst DEFAULT_QUOTE_TTL_MS = 60_000;\n/** Fallback gas limit: a depositForBurn runs ~110–150k, receiveMessage ~150–200k. */\nconst GAS_DEPOSIT = \"200000\";\nconst GAS_CLAIM = \"260000\";\n\nexport type CctpMode = \"auto\" | \"fast\" | \"standard\";\n\nexport interface CctpProviderConfig {\n enabled?: boolean;\n /** Circle attestation API base (default https://iris-api.circle.com). */\n apiUrl?: string;\n /** Fast when offered and within the allowance (default), or force one path. */\n mode?: CctpMode;\n /** Extra headroom on the published Fast fee, in percent of the fee (default 10). The excess is never charged. */\n feeBufferPct?: number;\n /**\n * JSON-RPC URLs per CAIP-2 chain. Optional, but with them the provider\n * verifies the contracts before the burn and detects the mint on the\n * destination (`usedNonces`). Without the destination chain's URL the status\n * reaches \"completed\" only through the id `claimSwap2` returns for a claim the\n * account saw succeed; a bare claim hash stays \"pending\" (hash kept).\n */\n rpcUrls?: Readonly<Record<string, string>>;\n /** Local lifetime of a quote (fees are stable; default 60 s). */\n quoteTtlMs?: number;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n}\n\ninterface FeeRow { finalityThreshold: number; minimumFee: number }\ninterface ApiMessage {\n message?: string;\n eventNonce?: string;\n attestation?: string | null;\n status?: string;\n delayReason?: string | null;\n cctpVersion?: number;\n decodedMessage?: {\n sourceDomain?: string; destinationDomain?: string; nonce?: string; mintRecipient?: string;\n decodedMessageBody?: {amount?: string; maxFee?: string; feeExecuted?: string; expirationBlock?: string; mintRecipient?: string; burnToken?: string};\n };\n}\n\nconst isHexData = (v: unknown): v is Hex => typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2})+$/.test(v);\n\n/**\n * Tags a failed read with what it means and hands back the same error: a network failure, our own timeout or an\n * answer that is not JSON is `upstream_unavailable`; the caller's own abort stays unclassified.\n */\nfunction unreachable<E>(error: E, signal?: AbortSignal): E {\n if (!signal?.aborted && error instanceof Error) withReason(error, \"upstream_unavailable\");\n return error;\n}\n\n/** A contract read on the caller's RPC that failed: an `eth_call` that reverted or found no code, else the node's failure. */\nfunction rpcFailure<E>(error: E): E {\n if (!(error instanceof Error)) return error;\n let reverted = false;\n for (let e: unknown = error, i = 0; e instanceof Error && i < 8; e = e.cause, i++) {\n if (e.name === \"ContractFunctionRevertedError\" || e.name === \"ContractFunctionZeroDataError\" || e.name === \"ExecutionRevertedError\") reverted = true;\n }\n return withReason(error, reverted ? \"simulation_failed\" : \"upstream_unavailable\");\n}\nconst same = (a: string | undefined, b: string) => !!a && a.toLowerCase() === b.toLowerCase();\n\n/** `amount × bps` rounded up; `bps` may be fractional (Circle publishes 1.3). */\nfunction feeFor(amount: bigint, bps: number, bufferPct: number): bigint {\n const hundredths = BigInt(Math.round(bps * 100)); // 1.3 bps → 130\n const fee = (amount * hundredths + 999_999n) / 1_000_000n;\n if (fee === 0n) return 0n;\n return fee + (fee * BigInt(Math.round(bufferPct * 100)) + 9_999n) / 10_000n;\n}\n\n/**\n * The contracts a CCTP claim may call on `chain`: its MessageTransmitter (`receiveMessage`). Pass it\n * as `claimTargets` to a remote provider stub so the app, not the server, decides (round 3, M24).\n */\nexport function cctpClaimTargets(chain: string): readonly string[] {\n const d = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, chain) ? CCTP_DOMAINS[chain] : undefined;\n return d ? [d.messageTransmitter] : [];\n}\n\nexport function cctpProvider(config: CctpProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const api = (config.apiUrl ?? CCTP_API).replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(api)) throw new Error(\"cctp: apiUrl must use http or https\");\n const mode: CctpMode = config.mode ?? \"auto\";\n if (![\"auto\", \"fast\", \"standard\"].includes(mode)) throw new Error(\"cctp: mode must be auto | fast | standard\");\n const bufferPct = config.feeBufferPct ?? 10;\n if (!Number.isFinite(bufferPct) || bufferPct < 0 || bufferPct > 100) throw new Error(\"cctp: feeBufferPct must be between 0 and 100\");\n const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;\n if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 300_000) throw new Error(\"cctp: quoteTtlMs must be an integer between 1 and 300000\");\n const doFetch = config.fetchImpl ?? fetch;\n const rpcUrls = Object.freeze({...(config.rpcUrls ?? {})});\n\n const client = (caip2: string) => {\n const url = rpcUrls[caip2];\n return url ? createPublicClient({transport: http(url, {fetchOptions: {}, ...(config.fetchImpl ? {fetchFn: config.fetchImpl} : {})} as never), ccipRead: false}) : null;\n };\n\n async function getJson<T>(path: string, signal?: AbortSignal): Promise<T | null> {\n let res: Response;\n try {\n res = await doFetch(`${api}${path}`, {headers: {accept: \"application/json\"}, signal: signal ?? timeoutSignal(12_000)});\n } catch (e) {\n throw unreachable(e, signal);\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n // 429 (with Retry-After), 408 / 425 / 5xx; any other status stays unclassified. Circle's API takes no key, so a\n // 401 / 403 (a block in front of it) is upstream_unavailable with its status, never key_rejected.\n const byStatus = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n const info = byStatus?.reason === \"key_rejected\" ? {reason: \"upstream_unavailable\" as const, httpStatus: res.status} : byStatus;\n const error = new Error(`cctp: ${path} → ${res.status}`);\n throw info ? withReason(error, info) : error;\n }\n try {\n return (await res.json()) as T;\n } catch (e) {\n throw unreachable(e, signal);\n }\n }\n\n /** Circle's published fee per finality threshold, in bps of the burnt amount. */\n const feeRows = (src: CctpDomain, dst: CctpDomain, signal?: AbortSignal) =>\n getJson<FeeRow[]>(`/v2/burn/USDC/fees/${src.domain}/${dst.domain}`, signal);\n\n /** The native USDC of a domain, cross-checked against the asset catalog when it knows the chain. */\n function usdcOf(dom: CctpDomain): string | null {\n const known = ccAsset(dom.caip2, \"USDC\");\n if (known && (!known.contract || !same(known.contract, dom.usdc))) return null; // catalog has a USDC that is not Circle's → refuse\n return dom.usdc;\n }\n\n function parseIntent(intentId: string): {src: CctpDomain; dst: CctpDomain; threshold: number} | null {\n const [tag, s, dd, t] = intentId.split(\":\");\n if (tag !== \"cctp\") return null;\n const src = CCTP_BY_DOMAIN[Number(s)];\n const dst = CCTP_BY_DOMAIN[Number(dd)];\n const threshold = Number(t);\n if (!src || !dst || !(threshold === FINALITY_FAST || threshold === FINALITY_STANDARD)) return null;\n return {src, dst, threshold};\n }\n\n async function fetchMessage(src: CctpDomain, sourceTxHash: string): Promise<ApiMessage | null> {\n const out = await getJson<{messages?: ApiMessage[]}>(`/v2/messages/${src.domain}?transactionHash=${encodeURIComponent(sourceTxHash)}`);\n const m = out?.messages?.find((x) => x.cctpVersion === undefined || x.cctpVersion === 2);\n return m ?? null;\n }\n\n /** The nonce's state on the destination: null without an RPC there, \"unknown\" when the configured RPC fails to answer. */\n async function minted(dst: CctpDomain, nonce: Hex): Promise<boolean | null | \"unknown\"> {\n const c = client(dst.caip2);\n if (!c) return null;\n try {\n const used = await c.readContract({address: getAddress(dst.messageTransmitter), abi: MESSAGE_TRANSMITTER_ABI, functionName: \"usedNonces\", args: [nonce]});\n return used !== 0n;\n } catch {\n return \"unknown\";\n }\n }\n\n return {\n name: \"cctp\",\n claimTargets: cctpClaimTargets,\n describeActivity: describeCctpActivity,\n enabled: () => config.enabled ?? true,\n supportsChain: (chain: string) => cctpCfg.supportsChain(chain),\n supportsChainPair: (from: string, to: string) => cctpCfg.supports(from, to),\n supportsRoute(from: Asset, to: Asset): boolean {\n const src = CCTP_DOMAINS[from.chain];\n const dst = CCTP_DOMAINS[to.chain];\n if (!src || !dst || from.chain === to.chain) return false;\n if (from.token.toUpperCase() !== \"USDC\") return false;\n // Destination is given as an address (zero = native): only the native USDC of the destination domain.\n return same(to.token, dst.usdc) || to.token.toUpperCase() === \"USDC\";\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n if (params.flex) return null; // the amount is baked into the calldata\n const src = CCTP_DOMAINS[params.sourceChain];\n const dst = CCTP_DOMAINS[params.destChain];\n if (!src || !dst || src === dst) return null;\n if (params.sourceToken.toUpperCase() !== \"USDC\") return null;\n if (!(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === \"USDC\")) return null;\n const usdc = usdcOf(src);\n if (!usdc) { params.onRefusal?.(\"catalog USDC on the source chain is not Circle's native USDC\", {reason: \"unsupported_pair\"}); return null; }\n if (!/^\\d+$/.test(params.amountIn)) return null;\n const amount = BigInt(params.amountIn);\n if (amount <= 0n) return null;\n // The placeholder prices a dry quote; a live one without a recipient would mint to it (round 3, H8).\n const recipient = params.destAddress || (params.dry !== false ? EVM_PLACEHOLDER : \"\");\n if (!recipient) { params.onRefusal?.(\"a live quote needs a recipient\", {reason: \"policy_refused\"}); return null; }\n if (!isAddress(recipient)) { params.onRefusal?.(\"destination must be an EVM address\"); return null; }\n\n try {\n const fees = await feeRows(src, dst, signal);\n if (!fees || !Array.isArray(fees) || fees.length === 0) {\n // No fee list (404) or an empty one: Circle does not serve the pair; a list of another shape is a broken answer.\n params.onRefusal?.(\"Circle publishes no fee for this pair\", {reason: !fees || Array.isArray(fees) ? \"unsupported_pair\" : \"upstream_unavailable\"});\n return null;\n }\n const fast = fees.find((f) => f.finalityThreshold === FINALITY_FAST);\n const standard = fees.find((f) => f.finalityThreshold === FINALITY_STANDARD);\n let threshold: number;\n let bps: number;\n if (mode === \"standard\") {\n if (!standard) { params.onRefusal?.(\"Standard Transfer is not offered for this pair\", {reason: \"unsupported_pair\"}); return null; }\n threshold = FINALITY_STANDARD; bps = standard.minimumFee;\n } else {\n let fastOk = !!fast;\n if (fastOk) {\n const allowance = await getJson<{allowance?: number}>(\"/v2/fastBurn/USDC/allowance\", signal).catch(() => null);\n // The allowance is in whole USDC; refuse Fast when it cannot cover the burn.\n if (typeof allowance?.allowance === \"number\" && allowance.allowance * 1e6 < bigintToNumber(amount)) fastOk = false;\n }\n if (fastOk) { threshold = FINALITY_FAST; bps = fast!.minimumFee; }\n else if (mode === \"fast\") {\n params.onRefusal?.(fast ? \"Fast Transfer allowance is exhausted\" : \"Fast Transfer is not offered for this pair\", {reason: fast ? \"insufficient_liquidity\" : \"unsupported_pair\"});\n return null;\n }\n else if (standard) { threshold = FINALITY_STANDARD; bps = standard.minimumFee; }\n else { params.onRefusal?.(\"neither Fast nor Standard is offered\", {reason: \"unsupported_pair\"}); return null; }\n }\n if (!Number.isFinite(bps) || bps < 0) return null;\n const maxFee = feeFor(amount, bps, bufferPct);\n if (maxFee >= amount) { params.onRefusal?.(\"amount is below the Fast Transfer fee\", {reason: \"amount_too_small\"}); return null; }\n const out = amount - maxFee;\n if (params.minAmountOut !== undefined && out < BigInt(params.minAmountOut)) return null;\n\n const data = encodeFunctionData({\n abi: TOKEN_MESSENGER_ABI,\n functionName: \"depositForBurn\",\n args: [amount, dst.domain, pad(getAddress(recipient), {size: 32}), getAddress(usdc), zeroHash, maxFee, threshold],\n });\n const eta = threshold === FINALITY_FAST ? (src.domain === 0 ? 180 : 45) : (src.domain === 0 ? 1200 : 1000);\n return {\n provider: \"cctp\",\n intentId: `cctp:${src.domain}:${dst.domain}:${threshold}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {to: src.tokenMessenger, data, value: \"0\", chainId: src.chainId, gasLimit: GAS_DEPOSIT, approvalAddress: src.tokenMessenger},\n sourceAmount: amount.toString(),\n destAmount: out.toString(),\n minDestAmount: out.toString(),\n feeUsd: bigintToNumber(maxFee) / 1e6,\n fees: maxFee > 0n ? [{type: \"protocol\", amount: maxFee.toString(), token: usdc, included: true, description: `Circle Fast Transfer fee (${bps} bps + ${bufferPct}% buffer, unused part is not charged)`}] : [],\n etaSeconds: eta,\n reliability: 0.99,\n validUntilMs: Date.now() + quoteTtlMs,\n providerData: {\n sourceDomain: String(src.domain), destinationDomain: String(dst.domain), finalityThreshold: String(threshold),\n maxFee: maxFee.toString(), mintRecipient: getAddress(recipient), claimChain: dst.caip2, claimRequired: \"1\",\n },\n };\n } catch {\n return null;\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n const parsed = parseIntent(quote.intentId);\n if (!tx || !parsed) throw refusal(\"policy_refused\", \"swap2: CCTP quote has no transaction request\");\n return {\n chain: parsed.src.caip2,\n to: tx.to ?? \"\",\n value: tx.value ?? \"0\",\n ...(tx.data ? {data: tx.data} : {}),\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n };\n },\n\n /**\n * Fast: Circle's CURRENT fee (same source and rounding as the quote, without\n * the buffer) still fits `maxFee` — Iris would otherwise hold the burn\n * until it times out to Standard. With a source RPC: the target really is\n * CCTP for this domain.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const parsed = parseIntent(quote.intentId);\n if (!parsed) throw refusal(\"policy_refused\", \"cctp: malformed intent id\");\n if (!same(tx.to, parsed.src.tokenMessenger)) throw refusal(\"vault_mismatch\", \"cctp: deposit target is not the TokenMessengerV2 of the source domain\");\n if (parsed.threshold === FINALITY_FAST) {\n const fast = (await feeRows(parsed.src, parsed.dst))?.find((f) => f.finalityThreshold === FINALITY_FAST);\n if (!fast || !Number.isFinite(fast.minimumFee) || fast.minimumFee < 0) throw refusal(\"quote_expired\", \"cctp: Circle no longer publishes a Fast Transfer fee for this pair — re-quote\");\n const minFee = feeFor(BigInt(quote.sourceAmount), fast.minimumFee, 0);\n const maxFee = BigInt(quote.providerData?.maxFee ?? \"0\");\n if (minFee > maxFee) throw refusal(\"quote_expired\", `cctp: Circle's Fast Transfer fee ${minFee} (${fast.minimumFee} bps) exceeds the quoted maxFee ${maxFee} — re-quote`);\n }\n const c = client(parsed.src.caip2);\n if (!c) return;\n const transmitter = await c.readContract({address: getAddress(parsed.src.tokenMessenger), abi: TOKEN_MESSENGER_ABI, functionName: \"localMessageTransmitter\"})\n .catch((e: unknown) => { throw rpcFailure(e); });\n if (!same(transmitter, parsed.src.messageTransmitter)) throw refusal(\"vault_mismatch\", \"cctp: TokenMessengerV2 does not point at the expected MessageTransmitterV2\");\n const domain = await c.readContract({address: getAddress(parsed.src.messageTransmitter), abi: MESSAGE_TRANSMITTER_ABI, functionName: \"localDomain\"})\n .catch((e: unknown) => { throw rpcFailure(e); });\n if (Number(domain) !== parsed.src.domain) throw refusal(\"vault_mismatch\", `cctp: MessageTransmitterV2 reports domain ${domain}, expected ${parsed.src.domain}`);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const parsed = parseIntent(ref.intentId);\n if (!parsed) return {state: \"failed\"};\n const claim = {chain: parsed.dst.caip2, ready: false};\n if (!ref.sourceTxHash) return {state: \"pending\", claim};\n try {\n const m = await fetchMessage(parsed.src, ref.sourceTxHash);\n if (!m) return {state: \"pending\", depositReceived: false, claim};\n const nonce = m.decodedMessage?.nonce;\n if (m.status === \"complete\" && isHexData(m.attestation) && isHexData(m.message)) {\n // A message without a readable nonce cannot be checked on the destination even with an RPC there.\n const done = isHexData(nonce) && nonce.length === 66 ? await minted(parsed.dst, nonce) : client(parsed.dst.caip2) ? \"unknown\" : null;\n if (done === true) return {state: \"completed\", claim: {...claim, ready: false}, ...(ref.destTxHash ? {destTxHash: ref.destTxHash} : {})};\n if (ref.destTxHash) {\n // A claim the sending account saw included and succeed is the mint: receiveMessage reverts once the\n // nonce is used, so a successful one minted this message. Without a destination read that is completed;\n // a destination read that does not show it yet is a node behind the claim, not a claim to send again.\n if (ref.destTxConfirmed === true) {\n return done === false\n ? {state: \"pending\", depositReceived: true, destTxHash: ref.destTxHash, claim: {...claim, ready: false}}\n : {state: \"completed\", destTxHash: ref.destTxHash, claim: {...claim, ready: false}};\n }\n // A claim was sent, but nothing here can read whether it minted (no destination RPC, or one that did\n // not answer): the hash is kept and the swap stays pending — a hash alone is not a mint.\n if (done !== false) return {state: \"pending\", depositReceived: true, destTxHash: ref.destTxHash, claim: {...claim, ready: false}};\n }\n return {state: \"action-required\", depositReceived: true, claim: {...claim, ready: true}};\n }\n return {state: \"pending\", depositReceived: true, claim};\n } catch {\n return {state: \"pending\", claim};\n }\n },\n\n /** `receiveMessage(message, attestation)` on the destination once Circle attested; null while pending. */\n async buildClaim(ref: IntentRef): Promise<UnsignedTx | null> {\n const parsed = parseIntent(ref.intentId);\n if (!parsed || !ref.sourceTxHash) return null;\n const m = await fetchMessage(parsed.src, ref.sourceTxHash);\n if (!m || m.status !== \"complete\" || !isHexData(m.attestation) || !isHexData(m.message)) return null;\n // Bind the attested message to the route it claims to complete.\n if (m.decodedMessage?.destinationDomain !== undefined && Number(m.decodedMessage.destinationDomain) !== parsed.dst.domain) {\n throw refusal(\"recipient_mismatch\", \"cctp: attested message is for another destination domain\");\n }\n if (m.decodedMessage?.sourceDomain !== undefined && Number(m.decodedMessage.sourceDomain) !== parsed.src.domain) {\n throw refusal(\"policy_refused\", \"cctp: attested message is for another source domain\");\n }\n // Fast messages expire at `expirationBlock` on the destination; an expired\n // one needs Circle's re-attestation before it can be received. The\n // transmitter compares it with `block.number`, which on Arbitrum-stack\n // chains is the L1 (Ethereum) height, not the L2 height eth_blockNumber\n // returns — the RPC block carries it as `l1BlockNumber` (live\n // 2026-10-16: a Base→Arbitrum claim was held as \"expired\" by L2 height).\n const exp = m.decodedMessage?.decodedMessageBody?.expirationBlock;\n const c = client(parsed.dst.caip2);\n if (c && exp && /^\\d+$/.test(exp) && BigInt(exp) > 0n) {\n const head = await c.request({method: \"eth_getBlockByNumber\", params: [\"latest\", false]})\n .then((b) => {\n const block = b as {number?: string; l1BlockNumber?: string} | null;\n const raw = block?.l1BlockNumber ?? block?.number;\n return raw ? BigInt(raw) : null;\n })\n .catch(() => null);\n if (head !== null && head >= BigInt(exp)) {\n const nonce = m.decodedMessage?.nonce ?? m.eventNonce;\n if (nonce) await doFetch(`${api}/v2/reattest/${nonce}`, {method: \"POST\", signal: timeoutSignal(12_000)}).catch(() => undefined);\n return null;\n }\n }\n return {\n chain: parsed.dst.caip2,\n to: parsed.dst.messageTransmitter,\n value: \"0\",\n data: encodeFunctionData({abi: MESSAGE_TRANSMITTER_ABI, functionName: \"receiveMessage\", args: [m.message, m.attestation]}),\n chainId: parsed.dst.chainId,\n gasLimit: GAS_CLAIM,\n };\n },\n };\n}\n\n/** The reason behind each text {@link cctpVerifyQuote} returns (`cctpPins.reasonOf`). */\nconst notes = refusalNotes();\nconst why = (text: string, reason: Swap2RefusalReason): string => notes.note(text, reason);\n\n/**\n * A remote CCTP quote's burn, decoded on the device against the app's own request (scan 2026-10-30, F3): exactly\n * `depositForBurn` on the source TokenMessengerV2 with no value, approving it; the input amount; the destination\n * chain's domain; the recipient as `mintRecipient`; the source domain's native USDC; no destination caller; a Fast\n * or Standard threshold; and a `maxFee` that leaves at least the quoted minimum and the caller's floor. The reason\n * it fails, or null. The engine then requires the build to repeat this quote's call.\n */\nexport function cctpVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n const src = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, params.sourceChain) ? CCTP_DOMAINS[params.sourceChain] : undefined;\n const dst = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, params.destChain) ? CCTP_DOMAINS[params.destChain] : undefined;\n if (!src || !dst || src === dst) return why(\"not a CCTP route between two domains\", \"unsupported_pair\");\n if (params.sourceToken.toUpperCase() !== \"USDC\" || !(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === \"USDC\")) return why(\"not USDC to USDC\", \"unsupported_pair\");\n const tx = quote.txRequest;\n if (!tx?.data || !tx.to || tx.serializedTx !== undefined) return why(\"the quote carries no TokenMessenger call\", \"policy_refused\");\n if (!same(tx.to, src.tokenMessenger)) return why(`the call targets ${tx.to}, not the TokenMessengerV2`, \"vault_mismatch\");\n if (BigInt(tx.value ?? \"0\") !== 0n) return why(\"a burn attaches no value\", \"policy_refused\");\n if (!tx.approvalAddress || !same(tx.approvalAddress, src.tokenMessenger)) return why(\"the burn approves another spender than the TokenMessengerV2\", \"vault_mismatch\");\n if (tx.chainId !== undefined && tx.chainId !== src.chainId) return why(`the call is for chain ${tx.chainId}, not ${src.chainId}`, \"policy_refused\");\n let args: readonly unknown[];\n try {\n const d = decodeFunctionData({abi: TOKEN_MESSENGER_ABI, data: tx.data as Hex});\n if (d.functionName !== \"depositForBurn\") return why(`${d.functionName} is not depositForBurn`, \"policy_refused\");\n args = d.args;\n } catch {\n return why(\"the call is not depositForBurn\", \"policy_refused\");\n }\n const [amount, domain, mintRecipient, burnToken, caller, maxFee, threshold] = args as [bigint, number, Hex, string, Hex, bigint, number];\n let amountIn: bigint, floor: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n floor = BigInt(quote.minDestAmount);\n if (params.minAmountOut !== undefined && BigInt(params.minAmountOut) > floor) floor = BigInt(params.minAmountOut);\n } catch {\n return why(\"the request does not name amounts\", \"upstream_unavailable\");\n }\n if (amount !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return why(`the burn moves ${amount}, not the ${amountIn} input`, \"policy_refused\");\n if (domain !== dst.domain) return why(`the burn mints on domain ${domain}, not ${dst.name} (${dst.domain})`, \"recipient_mismatch\");\n // A dry quote without a recipient prices the placeholder the provider uses; it is never built (the engine re-quotes live).\n if (params.destAddress || params.dry === false) {\n if (!isAddress(params.destAddress)) return \"the recipient is not an EVM address\";\n if (mintRecipient.toLowerCase() !== pad(getAddress(params.destAddress), {size: 32}).toLowerCase()) return why(`the burn mints to ${mintRecipient}, not the recipient`, \"recipient_mismatch\");\n }\n if (!same(burnToken, src.usdc)) return why(`the burn spends ${burnToken}, not the source domain's USDC`, \"policy_refused\");\n if (caller !== zeroHash) return why(\"the burn names a destination caller\", \"policy_refused\");\n if (threshold !== FINALITY_FAST && threshold !== FINALITY_STANDARD) return why(`finality threshold ${threshold} is neither Fast nor Standard`, \"policy_refused\");\n if (maxFee >= amount || amount - maxFee < floor) return why(`the burn's maxFee ${maxFee} leaves less than the ${floor} minimum`, \"price_check_failed\");\n // The server appends its intent token (`<id>~<tag>`); the id before it is what the server's provider tracks and claims.\n if ((/^([\\s\\S]+)~[0-9a-f]{32}$/.exec(quote.intentId)?.[1] ?? quote.intentId) !== `cctp:${src.domain}:${dst.domain}:${threshold}`) return why(\"the intent id does not name this burn\", \"policy_refused\");\n if (quote.providerData?.maxFee !== undefined && quote.providerData.maxFee !== maxFee.toString()) return why(\"the quoted maxFee is not the burn's\", \"policy_refused\");\n return null;\n}\n\n/**\n * The TokenMessenger a CCTP burn calls and approves, and the MessageTransmitter its claim calls, per\n * chain, and {@link cctpVerifyQuote} — the app's pins for `remoteProvider({name: \"cctp\", baseUrl, ...cctpPins})`\n * (scan 2026-10-27 modules, F8/F16; claims since round 3, M24; the burn's arguments since scan 2026-10-30, F3).\n * `reasonOf` classifies each text the verifier returns (`Swap2RefusalReason`), so a remote stub's refusal carries it.\n */\nexport const cctpPins: RemotePins & {claimTargets(chain: string): readonly string[]} = Object.freeze({\n callTargets: (chain: string): readonly string[] => cctpMessengerFor(chain),\n spenders: (chain: string): readonly string[] => cctpMessengerFor(chain),\n claimTargets: cctpClaimTargets,\n verifyQuote: cctpVerifyQuote,\n reasonOf: notes.reasonOf,\n});\nfunction cctpMessengerFor(chain: string): readonly string[] {\n const d = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, chain) ? CCTP_DOMAINS[chain] : undefined;\n return d ? [d.tokenMessenger] : [];\n}\n"],"mappings":";;;;;;;;;;;;;AACA,SAAQ,aAAa,SAAS,cAAc,kBAA0C;AACtF,SAAQ,oBAAoB,oBAAoB,oBAAoB,YAAY,MAAM,WAAW,KAAK,UAAU,gBAAyB;AAEzI,SAAQ,eAAc;AACtB,SAAQ,qBAAoB;AAG5B,SAAQ,sBAAqB;AA0B7B,IAAM,sBAAsB,SAAS;AAAA,EACnC;AAAA,EACA;AACF,CAAC;AACD,IAAM,0BAA0B,SAAS;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,kBAAkB;AACxB,IAAM,uBAAuB;AAE7B,IAAM,cAAc;AACpB,IAAM,YAAY;AAwClB,IAAM,YAAY,CAAC,MAAyB,OAAO,MAAM,YAAY,0BAA0B,KAAK,CAAC;AAMrG,SAAS,YAAe,OAAU,QAAyB;AACzD,MAAI,CAAC,QAAQ,WAAW,iBAAiB,MAAO,YAAW,OAAO,sBAAsB;AACxF,SAAO;AACT;AAGA,SAAS,WAAc,OAAa;AAClC,MAAI,EAAE,iBAAiB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,MAAI,cAAc,iBAAiB,cAAc,kBAAmB,QAAO,IAAI,sBAAsB,SAAS,iCAAiC,gBAAgB;AAC/J,MAAI,UAAU,UAAU,SAAS,SAAS,MAAO,QAAO,IAAI,qBAAqB,MAAM,yBAAyB,KAAK,YAAY,oBAAoB;AAErJ,OAAK,2BAA2B,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,MAAM,cAAc,QAAQ,IAAI,MAAM,IAAI,IAAI,MAAM,IAAI,SAAS,GAAI,QAAO,IAAI,yCAAyC,gBAAgB;AACtM,MAAI,MAAM,cAAc,WAAW,UAAa,MAAM,aAAa,WAAW,OAAO,SAAS,EAAG,QAAO,IAAI,uCAAuC,gBAAgB;AACnK,SAAO;AACT;AAQO,IAAM,WAA0E,OAAO,OAAO;AAAA,EACnG,aAAa,CAAC,UAAqC,iBAAiB,KAAK;AAAA,EACzE,UAAU,CAAC,UAAqC,iBAAiB,KAAK;AAAA,EACtE,cAAc;AAAA,EACd,aAAa;AAAA,EACb,UAAU,MAAM;AAClB,CAAC;AACD,SAAS,iBAAiB,OAAkC;AAC1D,QAAM,IAAI,OAAO,UAAU,eAAe,KAAK,cAAc,KAAK,IAAI,aAAa,KAAK,IAAI;AAC5F,SAAO,IAAI,CAAC,EAAE,cAAc,IAAI,CAAC;AACnC;","names":[]}
package/dist/index.cjs CHANGED
@@ -97,6 +97,7 @@ var cctp = {
97
97
  };
98
98
 
99
99
  // src/provider.ts
100
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
100
101
  var import_viem = require("viem");
101
102
 
102
103
  // src/activity.ts
@@ -135,6 +136,18 @@ var DEFAULT_QUOTE_TTL_MS = 6e4;
135
136
  var GAS_DEPOSIT = "200000";
136
137
  var GAS_CLAIM = "260000";
137
138
  var isHexData = (v) => typeof v === "string" && /^0x(?:[0-9a-fA-F]{2})+$/.test(v);
139
+ function unreachable(error, signal) {
140
+ if (!signal?.aborted && error instanceof Error) (0, import_errors.withReason)(error, "upstream_unavailable");
141
+ return error;
142
+ }
143
+ function rpcFailure(error) {
144
+ if (!(error instanceof Error)) return error;
145
+ let reverted = false;
146
+ for (let e = error, i = 0; e instanceof Error && i < 8; e = e.cause, i++) {
147
+ if (e.name === "ContractFunctionRevertedError" || e.name === "ContractFunctionZeroDataError" || e.name === "ExecutionRevertedError") reverted = true;
148
+ }
149
+ return (0, import_errors.withReason)(error, reverted ? "simulation_failed" : "upstream_unavailable");
150
+ }
138
151
  var same = (a, b) => !!a && a.toLowerCase() === b.toLowerCase();
139
152
  function feeFor(amount, bps, bufferPct) {
140
153
  const hundredths = BigInt(Math.round(bps * 100));
@@ -163,10 +176,24 @@ function cctpProvider(config = {}) {
163
176
  return url ? (0, import_viem.createPublicClient)({ transport: (0, import_viem.http)(url, { fetchOptions: {}, ...config.fetchImpl ? { fetchFn: config.fetchImpl } : {} }), ccipRead: false }) : null;
164
177
  };
165
178
  async function getJson(path, signal) {
166
- const res = await doFetch(`${api}${path}`, { headers: { accept: "application/json" }, signal: signal ?? (0, import_util2.timeoutSignal)(12e3) });
179
+ let res;
180
+ try {
181
+ res = await doFetch(`${api}${path}`, { headers: { accept: "application/json" }, signal: signal ?? (0, import_util2.timeoutSignal)(12e3) });
182
+ } catch (e) {
183
+ throw unreachable(e, signal);
184
+ }
167
185
  if (res.status === 404) return null;
168
- if (!res.ok) throw new Error(`cctp: ${path} \u2192 ${res.status}`);
169
- return await res.json();
186
+ if (!res.ok) {
187
+ const byStatus = (0, import_errors.httpRefusal)(res.status, res.headers?.get?.("retry-after"));
188
+ const info = byStatus?.reason === "key_rejected" ? { reason: "upstream_unavailable", httpStatus: res.status } : byStatus;
189
+ const error = new Error(`cctp: ${path} \u2192 ${res.status}`);
190
+ throw info ? (0, import_errors.withReason)(error, info) : error;
191
+ }
192
+ try {
193
+ return await res.json();
194
+ } catch (e) {
195
+ throw unreachable(e, signal);
196
+ }
170
197
  }
171
198
  const feeRows = (src, dst, signal) => getJson(`/v2/burn/USDC/fees/${src.domain}/${dst.domain}`, signal);
172
199
  function usdcOf(dom) {
@@ -221,7 +248,7 @@ function cctpProvider(config = {}) {
221
248
  if (!(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === "USDC")) return null;
222
249
  const usdc = usdcOf(src);
223
250
  if (!usdc) {
224
- params.onRefusal?.("catalog USDC on the source chain is not Circle's native USDC");
251
+ params.onRefusal?.("catalog USDC on the source chain is not Circle's native USDC", { reason: "unsupported_pair" });
225
252
  return null;
226
253
  }
227
254
  if (!/^\d+$/.test(params.amountIn)) return null;
@@ -229,7 +256,7 @@ function cctpProvider(config = {}) {
229
256
  if (amount <= 0n) return null;
230
257
  const recipient = params.destAddress || (params.dry !== false ? EVM_PLACEHOLDER : "");
231
258
  if (!recipient) {
232
- params.onRefusal?.("a live quote needs a recipient");
259
+ params.onRefusal?.("a live quote needs a recipient", { reason: "policy_refused" });
233
260
  return null;
234
261
  }
235
262
  if (!(0, import_viem.isAddress)(recipient)) {
@@ -239,7 +266,7 @@ function cctpProvider(config = {}) {
239
266
  try {
240
267
  const fees = await feeRows(src, dst, signal);
241
268
  if (!fees || !Array.isArray(fees) || fees.length === 0) {
242
- params.onRefusal?.("Circle publishes no fee for this pair");
269
+ params.onRefusal?.("Circle publishes no fee for this pair", { reason: !fees || Array.isArray(fees) ? "unsupported_pair" : "upstream_unavailable" });
243
270
  return null;
244
271
  }
245
272
  const fast = fees.find((f) => f.finalityThreshold === FINALITY_FAST);
@@ -248,7 +275,7 @@ function cctpProvider(config = {}) {
248
275
  let bps;
249
276
  if (mode === "standard") {
250
277
  if (!standard) {
251
- params.onRefusal?.("Standard Transfer is not offered for this pair");
278
+ params.onRefusal?.("Standard Transfer is not offered for this pair", { reason: "unsupported_pair" });
252
279
  return null;
253
280
  }
254
281
  threshold = FINALITY_STANDARD;
@@ -263,20 +290,20 @@ function cctpProvider(config = {}) {
263
290
  threshold = FINALITY_FAST;
264
291
  bps = fast.minimumFee;
265
292
  } else if (mode === "fast") {
266
- params.onRefusal?.(fast ? "Fast Transfer allowance is exhausted" : "Fast Transfer is not offered for this pair");
293
+ params.onRefusal?.(fast ? "Fast Transfer allowance is exhausted" : "Fast Transfer is not offered for this pair", { reason: fast ? "insufficient_liquidity" : "unsupported_pair" });
267
294
  return null;
268
295
  } else if (standard) {
269
296
  threshold = FINALITY_STANDARD;
270
297
  bps = standard.minimumFee;
271
298
  } else {
272
- params.onRefusal?.("neither Fast nor Standard is offered");
299
+ params.onRefusal?.("neither Fast nor Standard is offered", { reason: "unsupported_pair" });
273
300
  return null;
274
301
  }
275
302
  }
276
303
  if (!Number.isFinite(bps) || bps < 0) return null;
277
304
  const maxFee = feeFor(amount, bps, bufferPct);
278
305
  if (maxFee >= amount) {
279
- params.onRefusal?.("amount is below the Fast Transfer fee");
306
+ params.onRefusal?.("amount is below the Fast Transfer fee", { reason: "amount_too_small" });
280
307
  return null;
281
308
  }
282
309
  const out = amount - maxFee;
@@ -318,7 +345,7 @@ function cctpProvider(config = {}) {
318
345
  async buildDeposit(quote) {
319
346
  const tx = quote.txRequest;
320
347
  const parsed = parseIntent(quote.intentId);
321
- if (!tx || !parsed) throw new Error("swap2: CCTP quote has no transaction request");
348
+ if (!tx || !parsed) throw (0, import_errors.refusal)("policy_refused", "swap2: CCTP quote has no transaction request");
322
349
  return {
323
350
  chain: parsed.src.caip2,
324
351
  to: tx.to ?? "",
@@ -337,21 +364,25 @@ function cctpProvider(config = {}) {
337
364
  */
338
365
  async preflightDeposit(quote, tx) {
339
366
  const parsed = parseIntent(quote.intentId);
340
- if (!parsed) throw new Error("cctp: malformed intent id");
341
- if (!same(tx.to, parsed.src.tokenMessenger)) throw new Error("cctp: deposit target is not the TokenMessengerV2 of the source domain");
367
+ if (!parsed) throw (0, import_errors.refusal)("policy_refused", "cctp: malformed intent id");
368
+ if (!same(tx.to, parsed.src.tokenMessenger)) throw (0, import_errors.refusal)("vault_mismatch", "cctp: deposit target is not the TokenMessengerV2 of the source domain");
342
369
  if (parsed.threshold === FINALITY_FAST) {
343
370
  const fast = (await feeRows(parsed.src, parsed.dst))?.find((f) => f.finalityThreshold === FINALITY_FAST);
344
- if (!fast || !Number.isFinite(fast.minimumFee) || fast.minimumFee < 0) throw new Error("cctp: Circle no longer publishes a Fast Transfer fee for this pair \u2014 re-quote");
371
+ if (!fast || !Number.isFinite(fast.minimumFee) || fast.minimumFee < 0) throw (0, import_errors.refusal)("quote_expired", "cctp: Circle no longer publishes a Fast Transfer fee for this pair \u2014 re-quote");
345
372
  const minFee = feeFor(BigInt(quote.sourceAmount), fast.minimumFee, 0);
346
373
  const maxFee = BigInt(quote.providerData?.maxFee ?? "0");
347
- if (minFee > maxFee) throw new Error(`cctp: Circle's Fast Transfer fee ${minFee} (${fast.minimumFee} bps) exceeds the quoted maxFee ${maxFee} \u2014 re-quote`);
374
+ if (minFee > maxFee) throw (0, import_errors.refusal)("quote_expired", `cctp: Circle's Fast Transfer fee ${minFee} (${fast.minimumFee} bps) exceeds the quoted maxFee ${maxFee} \u2014 re-quote`);
348
375
  }
349
376
  const c = client(parsed.src.caip2);
350
377
  if (!c) return;
351
- const transmitter = await c.readContract({ address: (0, import_viem.getAddress)(parsed.src.tokenMessenger), abi: TOKEN_MESSENGER_ABI, functionName: "localMessageTransmitter" });
352
- if (!same(transmitter, parsed.src.messageTransmitter)) throw new Error("cctp: TokenMessengerV2 does not point at the expected MessageTransmitterV2");
353
- const domain = await c.readContract({ address: (0, import_viem.getAddress)(parsed.src.messageTransmitter), abi: MESSAGE_TRANSMITTER_ABI, functionName: "localDomain" });
354
- if (Number(domain) !== parsed.src.domain) throw new Error(`cctp: MessageTransmitterV2 reports domain ${domain}, expected ${parsed.src.domain}`);
378
+ const transmitter = await c.readContract({ address: (0, import_viem.getAddress)(parsed.src.tokenMessenger), abi: TOKEN_MESSENGER_ABI, functionName: "localMessageTransmitter" }).catch((e) => {
379
+ throw rpcFailure(e);
380
+ });
381
+ if (!same(transmitter, parsed.src.messageTransmitter)) throw (0, import_errors.refusal)("vault_mismatch", "cctp: TokenMessengerV2 does not point at the expected MessageTransmitterV2");
382
+ const domain = await c.readContract({ address: (0, import_viem.getAddress)(parsed.src.messageTransmitter), abi: MESSAGE_TRANSMITTER_ABI, functionName: "localDomain" }).catch((e) => {
383
+ throw rpcFailure(e);
384
+ });
385
+ if (Number(domain) !== parsed.src.domain) throw (0, import_errors.refusal)("vault_mismatch", `cctp: MessageTransmitterV2 reports domain ${domain}, expected ${parsed.src.domain}`);
355
386
  },
356
387
  async trackIntent(ref) {
357
388
  const parsed = parseIntent(ref.intentId);
@@ -385,10 +416,10 @@ function cctpProvider(config = {}) {
385
416
  const m = await fetchMessage(parsed.src, ref.sourceTxHash);
386
417
  if (!m || m.status !== "complete" || !isHexData(m.attestation) || !isHexData(m.message)) return null;
387
418
  if (m.decodedMessage?.destinationDomain !== void 0 && Number(m.decodedMessage.destinationDomain) !== parsed.dst.domain) {
388
- throw new Error("cctp: attested message is for another destination domain");
419
+ throw (0, import_errors.refusal)("recipient_mismatch", "cctp: attested message is for another destination domain");
389
420
  }
390
421
  if (m.decodedMessage?.sourceDomain !== void 0 && Number(m.decodedMessage.sourceDomain) !== parsed.src.domain) {
391
- throw new Error("cctp: attested message is for another source domain");
422
+ throw (0, import_errors.refusal)("policy_refused", "cctp: attested message is for another source domain");
392
423
  }
393
424
  const exp = m.decodedMessage?.decodedMessageBody?.expirationBlock;
394
425
  const c = client(parsed.dst.caip2);
@@ -415,24 +446,26 @@ function cctpProvider(config = {}) {
415
446
  }
416
447
  };
417
448
  }
449
+ var notes = (0, import_errors.refusalNotes)();
450
+ var why = (text, reason) => notes.note(text, reason);
418
451
  function cctpVerifyQuote(params, quote) {
419
452
  const src = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, params.sourceChain) ? CCTP_DOMAINS[params.sourceChain] : void 0;
420
453
  const dst = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, params.destChain) ? CCTP_DOMAINS[params.destChain] : void 0;
421
- if (!src || !dst || src === dst) return "not a CCTP route between two domains";
422
- if (params.sourceToken.toUpperCase() !== "USDC" || !(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === "USDC")) return "not USDC to USDC";
454
+ if (!src || !dst || src === dst) return why("not a CCTP route between two domains", "unsupported_pair");
455
+ if (params.sourceToken.toUpperCase() !== "USDC" || !(same(params.destToken, dst.usdc) || params.destToken.toUpperCase() === "USDC")) return why("not USDC to USDC", "unsupported_pair");
423
456
  const tx = quote.txRequest;
424
- if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return "the quote carries no TokenMessenger call";
425
- if (!same(tx.to, src.tokenMessenger)) return `the call targets ${tx.to}, not the TokenMessengerV2`;
426
- if (BigInt(tx.value ?? "0") !== 0n) return "a burn attaches no value";
427
- if (!tx.approvalAddress || !same(tx.approvalAddress, src.tokenMessenger)) return "the burn approves another spender than the TokenMessengerV2";
428
- if (tx.chainId !== void 0 && tx.chainId !== src.chainId) return `the call is for chain ${tx.chainId}, not ${src.chainId}`;
457
+ if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return why("the quote carries no TokenMessenger call", "policy_refused");
458
+ if (!same(tx.to, src.tokenMessenger)) return why(`the call targets ${tx.to}, not the TokenMessengerV2`, "vault_mismatch");
459
+ if (BigInt(tx.value ?? "0") !== 0n) return why("a burn attaches no value", "policy_refused");
460
+ if (!tx.approvalAddress || !same(tx.approvalAddress, src.tokenMessenger)) return why("the burn approves another spender than the TokenMessengerV2", "vault_mismatch");
461
+ if (tx.chainId !== void 0 && tx.chainId !== src.chainId) return why(`the call is for chain ${tx.chainId}, not ${src.chainId}`, "policy_refused");
429
462
  let args;
430
463
  try {
431
464
  const d2 = (0, import_viem.decodeFunctionData)({ abi: TOKEN_MESSENGER_ABI, data: tx.data });
432
- if (d2.functionName !== "depositForBurn") return `${d2.functionName} is not depositForBurn`;
465
+ if (d2.functionName !== "depositForBurn") return why(`${d2.functionName} is not depositForBurn`, "policy_refused");
433
466
  args = d2.args;
434
467
  } catch {
435
- return "the call is not depositForBurn";
468
+ return why("the call is not depositForBurn", "policy_refused");
436
469
  }
437
470
  const [amount, domain, mintRecipient, burnToken, caller, maxFee, threshold] = args;
438
471
  let amountIn, floor;
@@ -441,27 +474,28 @@ function cctpVerifyQuote(params, quote) {
441
474
  floor = BigInt(quote.minDestAmount);
442
475
  if (params.minAmountOut !== void 0 && BigInt(params.minAmountOut) > floor) floor = BigInt(params.minAmountOut);
443
476
  } catch {
444
- return "the request does not name amounts";
477
+ return why("the request does not name amounts", "upstream_unavailable");
445
478
  }
446
- if (amount !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return `the burn moves ${amount}, not the ${amountIn} input`;
447
- if (domain !== dst.domain) return `the burn mints on domain ${domain}, not ${dst.name} (${dst.domain})`;
479
+ if (amount !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return why(`the burn moves ${amount}, not the ${amountIn} input`, "policy_refused");
480
+ if (domain !== dst.domain) return why(`the burn mints on domain ${domain}, not ${dst.name} (${dst.domain})`, "recipient_mismatch");
448
481
  if (params.destAddress || params.dry === false) {
449
482
  if (!(0, import_viem.isAddress)(params.destAddress)) return "the recipient is not an EVM address";
450
- if (mintRecipient.toLowerCase() !== (0, import_viem.pad)((0, import_viem.getAddress)(params.destAddress), { size: 32 }).toLowerCase()) return `the burn mints to ${mintRecipient}, not the recipient`;
483
+ if (mintRecipient.toLowerCase() !== (0, import_viem.pad)((0, import_viem.getAddress)(params.destAddress), { size: 32 }).toLowerCase()) return why(`the burn mints to ${mintRecipient}, not the recipient`, "recipient_mismatch");
451
484
  }
452
- if (!same(burnToken, src.usdc)) return `the burn spends ${burnToken}, not the source domain's USDC`;
453
- if (caller !== import_viem.zeroHash) return "the burn names a destination caller";
454
- if (threshold !== FINALITY_FAST && threshold !== FINALITY_STANDARD) return `finality threshold ${threshold} is neither Fast nor Standard`;
455
- if (maxFee >= amount || amount - maxFee < floor) return `the burn's maxFee ${maxFee} leaves less than the ${floor} minimum`;
456
- if ((/^([\s\S]+)~[0-9a-f]{32}$/.exec(quote.intentId)?.[1] ?? quote.intentId) !== `cctp:${src.domain}:${dst.domain}:${threshold}`) return "the intent id does not name this burn";
457
- if (quote.providerData?.maxFee !== void 0 && quote.providerData.maxFee !== maxFee.toString()) return "the quoted maxFee is not the burn's";
485
+ if (!same(burnToken, src.usdc)) return why(`the burn spends ${burnToken}, not the source domain's USDC`, "policy_refused");
486
+ if (caller !== import_viem.zeroHash) return why("the burn names a destination caller", "policy_refused");
487
+ if (threshold !== FINALITY_FAST && threshold !== FINALITY_STANDARD) return why(`finality threshold ${threshold} is neither Fast nor Standard`, "policy_refused");
488
+ if (maxFee >= amount || amount - maxFee < floor) return why(`the burn's maxFee ${maxFee} leaves less than the ${floor} minimum`, "price_check_failed");
489
+ if ((/^([\s\S]+)~[0-9a-f]{32}$/.exec(quote.intentId)?.[1] ?? quote.intentId) !== `cctp:${src.domain}:${dst.domain}:${threshold}`) return why("the intent id does not name this burn", "policy_refused");
490
+ if (quote.providerData?.maxFee !== void 0 && quote.providerData.maxFee !== maxFee.toString()) return why("the quoted maxFee is not the burn's", "policy_refused");
458
491
  return null;
459
492
  }
460
493
  var cctpPins = Object.freeze({
461
494
  callTargets: (chain) => cctpMessengerFor(chain),
462
495
  spenders: (chain) => cctpMessengerFor(chain),
463
496
  claimTargets: cctpClaimTargets,
464
- verifyQuote: cctpVerifyQuote
497
+ verifyQuote: cctpVerifyQuote,
498
+ reasonOf: notes.reasonOf
465
499
  });
466
500
  function cctpMessengerFor(chain) {
467
501
  const d2 = Object.prototype.hasOwnProperty.call(CCTP_DOMAINS, chain) ? CCTP_DOMAINS[chain] : void 0;