@piprail/sdk 2.13.1 → 2.14.1

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.
Files changed (30) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/{algorand-AQK5EAUF.cjs → algorand-ICJNXO5V.cjs} +43 -42
  3. package/dist/{algorand-TQCYK2XT.js → algorand-RM7MP4PK.js} +12 -11
  4. package/dist/{aptos-RYQOSFBQ.js → aptos-2FIRTMQX.js} +11 -10
  5. package/dist/{aptos-65UX7GKA.cjs → aptos-MVEG5ZPS.cjs} +41 -40
  6. package/dist/{chunk-DCOUJZPL.cjs → chunk-57V5DNJT.cjs} +45 -19
  7. package/dist/{chunk-O32N6MFN.js → chunk-NUPCFNC5.js} +27 -1
  8. package/dist/index.cjs +503 -239
  9. package/dist/index.d.cts +279 -7
  10. package/dist/index.d.ts +279 -7
  11. package/dist/index.js +299 -35
  12. package/dist/{ledger-mF_SoiDB.d.ts → ledger-uFtXlIHY.d.cts} +31 -1
  13. package/dist/{ledger-mF_SoiDB.d.cts → ledger-uFtXlIHY.d.ts} +31 -1
  14. package/dist/{near-UDPFA6SV.cjs → near-C2IS4RCH.cjs} +39 -30
  15. package/dist/{near-VDATC5AV.js → near-L2OWD7M6.js} +14 -5
  16. package/dist/node.d.cts +2 -2
  17. package/dist/node.d.ts +2 -2
  18. package/dist/{solana-RQNXFCZO.cjs → solana-B424IQ5I.cjs} +54 -39
  19. package/dist/{solana-VYLWFNAH.js → solana-V2TGLHJ4.js} +22 -7
  20. package/dist/{stellar-OK2HW5PZ.cjs → stellar-4YR4UZQX.cjs} +23 -23
  21. package/dist/{stellar-KBR4V77T.js → stellar-J7VE7QP7.js} +4 -4
  22. package/dist/{sui-SVFBJFW5.cjs → sui-F7UW6JXJ.cjs} +35 -27
  23. package/dist/{sui-BXHB6D3W.js → sui-GMRQAAJH.js} +20 -12
  24. package/dist/{ton-D7YN6BGR.cjs → ton-3SHFVDLP.cjs} +33 -22
  25. package/dist/{ton-NNKQFQ6U.js → ton-PEBYBNWJ.js} +18 -7
  26. package/dist/{tron-WZFU57NX.cjs → tron-BS5EID2U.cjs} +39 -39
  27. package/dist/{tron-W2D5PQXV.js → tron-ZYJHHROT.js} +10 -10
  28. package/dist/{xrpl-37E23W53.js → xrpl-P2D6TS6I.js} +13 -13
  29. package/dist/{xrpl-5NHY3NEL.cjs → xrpl-SUEFOOKW.cjs} +31 -31
  30. package/package.json +3 -2
package/dist/index.cjs CHANGED
@@ -31,7 +31,8 @@ var _chunkCQQI5IJXcjs = require('./chunk-CQQI5IJX.cjs');
31
31
 
32
32
 
33
33
 
34
- var _chunkDCOUJZPLcjs = require('./chunk-DCOUJZPL.cjs');
34
+
35
+ var _chunk57V5DNJTcjs = require('./chunk-57V5DNJT.cjs');
35
36
 
36
37
  // src/drivers/registry.ts
37
38
  var byFamily = /* @__PURE__ */ new Map();
@@ -60,13 +61,13 @@ function resolveNetwork(opts) {
60
61
  const family = familyForChain(opts.chain);
61
62
  const driver = byFamily.get(family);
62
63
  if (!driver) {
63
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedNetworkError)(
64
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedNetworkError)(
64
65
  `No driver registered for the "${family}" family \u2014 it may not be mounted yet (use the async resolveNetwork()).`
65
66
  );
66
67
  }
67
68
  const net = driver.resolve(opts);
68
69
  if (!net) {
69
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedNetworkError)(
70
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedNetworkError)(
70
71
  `The ${family} driver didn't recognise this chain input.`
71
72
  );
72
73
  }
@@ -331,12 +332,12 @@ function resolveChain(input, rpcUrlOverride) {
331
332
 
332
333
  var _accounts = require('viem/accounts');
333
334
  function createWalletAdapter(config, resolved) {
334
- _chunkDCOUJZPLcjs.assertNoLegacyWalletKey.call(void 0, config, "EVM");
335
+ _chunk57V5DNJTcjs.assertNoLegacyWalletKey.call(void 0, config, "EVM");
335
336
  if ("key" in config) {
336
337
  const key = config.key;
337
338
  if (typeof key !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(key)) {
338
339
  const hint = typeof key === "string" && !key.startsWith("0x") ? " (got a non-0x string \u2014 a base58/seed key belongs to another family; pass { key } as the EVM chain's 0x\u2026 hex secret)." : " (expected 0x followed by 64 hex characters).";
339
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
340
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
340
341
  `chain is EVM; the wallet { key } is not a valid 0x\u2026 32-byte hex private key${hint}`
341
342
  );
342
343
  }
@@ -344,7 +345,7 @@ function createWalletAdapter(config, resolved) {
344
345
  try {
345
346
  account = _accounts.privateKeyToAccount.call(void 0, key);
346
347
  } catch (err) {
347
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
348
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
348
349
  `chain is EVM; the wallet { key } is not a valid 0x\u2026 32-byte hex private key: ${err instanceof Error ? err.message : String(err)}.`
349
350
  );
350
351
  }
@@ -354,12 +355,12 @@ function createWalletAdapter(config, resolved) {
354
355
  }
355
356
  const wc = config.walletClient;
356
357
  if (!wc.account) {
357
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
358
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
358
359
  "chain is EVM; the provided walletClient has no attached account. Use `createWalletClient({ account, chain, transport })`, or pass { key }."
359
360
  );
360
361
  }
361
362
  if (wc.chain && wc.chain.id !== resolved.chainId) {
362
- throw new (0, _chunkDCOUJZPLcjs.WrongChainError)(
363
+ throw new (0, _chunk57V5DNJTcjs.WrongChainError)(
363
364
  `PipRailClient: walletClient is on chain ${wc.chain.id} but the SDK was configured with chain ${resolved.chainId}. They must match.`
364
365
  );
365
366
  }
@@ -689,7 +690,7 @@ async function payExactEvm(input) {
689
690
  code = void 0;
690
691
  }
691
692
  if (code && code !== "0x") {
692
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
693
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
693
694
  `exact buyer rail requires an EOA signer; ${account.address} is a contract / EIP-1271 / EIP-7702-delegated account (no recoverable ECDSA signature). Pay via onchain-proof.`
694
695
  );
695
696
  }
@@ -699,13 +700,13 @@ async function payExactEvm(input) {
699
700
  domain = await readExactDomain(publicClient, accept.asset);
700
701
  }
701
702
  if (!domain) {
702
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
703
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
703
704
  `exact: couldn't derive the EIP-712 domain for ${accept.asset} on ${accept.network}. Either it isn't an EIP-3009 token (USDT needs Permit2; native/plain ERC-20 aren't exact-payable) \u2014 pay via onchain-proof \u2014 OR your RPC couldn't read it (transient): if the gate advertised eip3009, pass a reliable rpcUrl and retry.`
704
705
  );
705
706
  }
706
707
  const g = globalThis.crypto;
707
708
  if (!_optionalChain([g, 'optionalAccess', _5 => _5.getRandomValues])) {
708
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
709
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
709
710
  "this runtime lacks Web Crypto (globalThis.crypto.getRandomValues); the exact rail needs a CSPRNG nonce."
710
711
  );
711
712
  }
@@ -962,7 +963,7 @@ async function verifyAndSettleExactEvm(input) {
962
963
  args: writeArgs
963
964
  });
964
965
  } catch (err) {
965
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
966
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
966
967
  `exact settle: the merchant relayer failed to broadcast transferWithAuthorization (${shorten(err instanceof Error ? err.message : String(err))}). The payer's authorization is still valid and unused \u2014 fund/fix the relayer and the payer can retry.`,
967
968
  { cause: err }
968
969
  );
@@ -974,7 +975,7 @@ async function verifyAndSettleExactEvm(input) {
974
975
  return { ok: false, error: "tx_reverted", detail: `Settlement tx ${txHash} reverted on-chain.` };
975
976
  }
976
977
  } catch (err) {
977
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
978
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
978
979
  `exact settle: broadcast ${txHash} but couldn't confirm it (${shorten(err instanceof Error ? err.message : String(err))}).`,
979
980
  { cause: err }
980
981
  );
@@ -1105,7 +1106,7 @@ function shorten2(msg) {
1105
1106
  function randomPermit2Nonce() {
1106
1107
  const g = globalThis.crypto;
1107
1108
  if (!_optionalChain([g, 'optionalAccess', _8 => _8.getRandomValues])) {
1108
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
1109
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
1109
1110
  "this runtime lacks Web Crypto (globalThis.crypto.getRandomValues); the permit2 rail needs a CSPRNG nonce."
1110
1111
  );
1111
1112
  }
@@ -1124,7 +1125,7 @@ async function ensurePermit2Allowance(input) {
1124
1125
  args: [account.address, PERMIT2_ADDRESS]
1125
1126
  });
1126
1127
  } catch (err) {
1127
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
1128
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
1128
1129
  `permit2: couldn't read the Permit2 allowance for ${token} (${shorten2(err instanceof Error ? err.message : String(err))}).`
1129
1130
  );
1130
1131
  }
@@ -1141,7 +1142,7 @@ async function ensurePermit2Allowance(input) {
1141
1142
  await publicClient.waitForTransactionReceipt({ hash, confirmations: 1 });
1142
1143
  return hash;
1143
1144
  } catch (err) {
1144
- throw _nullishCoalesce(_chunkDCOUJZPLcjs.toInsufficientFundsError.call(void 0, err), () => ( new (0, _chunkDCOUJZPLcjs.SettlementError)(
1145
+ throw _nullishCoalesce(_chunk57V5DNJTcjs.toInsufficientFundsError.call(void 0, err), () => ( new (0, _chunk57V5DNJTcjs.SettlementError)(
1145
1146
  `permit2: the one-time Permit2 approval for ${token} failed to broadcast (${shorten2(err instanceof Error ? err.message : String(err))}).`,
1146
1147
  { cause: err }
1147
1148
  )));
@@ -1156,7 +1157,7 @@ async function payPermit2Evm(input) {
1156
1157
  code = void 0;
1157
1158
  }
1158
1159
  if (code && code !== "0x") {
1159
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
1160
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
1160
1161
  `permit2 buyer rail requires an EOA signer; ${account.address} is a contract / EIP-1271 / EIP-7702-delegated account. Pay via onchain-proof.`
1161
1162
  );
1162
1163
  }
@@ -1331,7 +1332,7 @@ async function verifyAndSettlePermit2Evm(input) {
1331
1332
  args: settleArgs
1332
1333
  });
1333
1334
  } catch (err) {
1334
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
1335
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
1335
1336
  `permit2 settle: the merchant relayer failed to broadcast the proxy settle (${shorten2(err instanceof Error ? err.message : String(err))}). The payer's signature is still valid and its nonce unused \u2014 fund/fix the relayer and the payer can retry.`,
1336
1337
  { cause: err }
1337
1338
  );
@@ -1343,7 +1344,7 @@ async function verifyAndSettlePermit2Evm(input) {
1343
1344
  return { ok: false, error: "tx_reverted", detail: `Settlement tx ${txHash} reverted on-chain.` };
1344
1345
  }
1345
1346
  } catch (err) {
1346
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
1347
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
1347
1348
  `permit2 settle: broadcast ${txHash} but couldn't confirm it (${shorten2(err instanceof Error ? err.message : String(err))}).`,
1348
1349
  { cause: err }
1349
1350
  );
@@ -1441,7 +1442,7 @@ function shorten3(msg) {
1441
1442
  function randomPermit2Nonce2() {
1442
1443
  const g = globalThis.crypto;
1443
1444
  if (!_optionalChain([g, 'optionalAccess', _9 => _9.getRandomValues])) {
1444
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
1445
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
1445
1446
  "this runtime lacks Web Crypto (globalThis.crypto.getRandomValues); the upto rail needs a CSPRNG nonce."
1446
1447
  );
1447
1448
  }
@@ -1458,13 +1459,13 @@ async function payUptoEvm(input) {
1458
1459
  code = void 0;
1459
1460
  }
1460
1461
  if (code && code !== "0x") {
1461
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
1462
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
1462
1463
  `upto buyer rail requires an EOA signer; ${account.address} is a contract / EIP-1271 / EIP-7702-delegated account. Pay via onchain-proof.`
1463
1464
  );
1464
1465
  }
1465
1466
  const facilitatorAddress = _optionalChain([accept, 'access', _10 => _10.extra, 'optionalAccess', _11 => _11.facilitatorAddress]);
1466
1467
  if (typeof facilitatorAddress !== "string" || facilitatorAddress.length === 0) {
1467
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
1468
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
1468
1469
  `upto: the rail carries no extra.facilitatorAddress to bind into witness.facilitator \u2014 refusing to sign.`
1469
1470
  );
1470
1471
  }
@@ -1685,7 +1686,7 @@ async function verifyAndSettleUptoEvm(input) {
1685
1686
  args: settleArgs
1686
1687
  });
1687
1688
  } catch (err) {
1688
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
1689
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
1689
1690
  `upto settle: the merchant relayer failed to broadcast the proxy settle (${shorten3(err instanceof Error ? err.message : String(err))}). The payer's signature is still valid and its nonce unused \u2014 fund/fix the relayer and the payer can retry.`,
1690
1691
  { cause: err }
1691
1692
  );
@@ -1697,7 +1698,7 @@ async function verifyAndSettleUptoEvm(input) {
1697
1698
  return { ok: false, error: "tx_reverted", detail: `Settlement tx ${txHash} reverted on-chain.` };
1698
1699
  }
1699
1700
  } catch (err) {
1700
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
1701
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
1701
1702
  `upto settle: broadcast ${txHash} but couldn't confirm it (${shorten3(err instanceof Error ? err.message : String(err))}).`,
1702
1703
  { cause: err }
1703
1704
  );
@@ -1780,6 +1781,37 @@ function buildReceiptExtension(bundle) {
1780
1781
  if (bundle.attestation) info.receipt = bundle.attestation;
1781
1782
  return { [EXT_OFFER_RECEIPT]: { info } };
1782
1783
  }
1784
+ var EXT_PAYMENT_IDENTIFIER = "payment-identifier";
1785
+ var PAYMENT_ID_MIN = 16;
1786
+ var PAYMENT_ID_MAX = 128;
1787
+ var PAYMENT_ID_RE = /^[A-Za-z0-9_-]+$/;
1788
+ function buildPaymentIdentifierAdvertisement() {
1789
+ return {
1790
+ [EXT_PAYMENT_IDENTIFIER]: {
1791
+ info: { required: false },
1792
+ schema: { properties: { id: { type: "string", minLength: PAYMENT_ID_MIN, maxLength: PAYMENT_ID_MAX } } }
1793
+ }
1794
+ };
1795
+ }
1796
+ function readPaymentIdentifier(payload) {
1797
+ if (typeof payload !== "object" || payload === null) return null;
1798
+ const ext = payload.extensions;
1799
+ if (typeof ext !== "object" || ext === null) return null;
1800
+ const block = ext[EXT_PAYMENT_IDENTIFIER];
1801
+ if (typeof block !== "object" || block === null) return null;
1802
+ const info = block.info;
1803
+ if (typeof info !== "object" || info === null) return null;
1804
+ const id = info.id;
1805
+ if (id === void 0) return null;
1806
+ if (typeof id !== "string") return { invalid: "payment-identifier id must be a string" };
1807
+ if (id.length < PAYMENT_ID_MIN || id.length > PAYMENT_ID_MAX) {
1808
+ return { invalid: `payment-identifier id must be ${PAYMENT_ID_MIN}\u2013${PAYMENT_ID_MAX} chars (got ${id.length})` };
1809
+ }
1810
+ if (!PAYMENT_ID_RE.test(id)) {
1811
+ return { invalid: "payment-identifier id must match [A-Za-z0-9_-]" };
1812
+ }
1813
+ return id;
1814
+ }
1783
1815
  function buildSignatureHeader(signature) {
1784
1816
  return toBase64Json(signature);
1785
1817
  }
@@ -1806,7 +1838,10 @@ function parseReceipt(response) {
1806
1838
  const headerValue = _nullishCoalesce(response.headers.get(HEADER_RESPONSE), () => ( response.headers.get(HEADER_RESPONSE_V1)));
1807
1839
  if (!headerValue) return null;
1808
1840
  const parsed = fromBase64Json(headerValue);
1809
- return isValidReceipt(parsed) ? parsed : null;
1841
+ if (!isValidReceipt(parsed)) return null;
1842
+ const r = parsed;
1843
+ if (typeof r.transaction !== "string" && typeof r.txHash === "string") r.transaction = r.txHash;
1844
+ return r;
1810
1845
  }
1811
1846
  function parseReceiptExtension(response) {
1812
1847
  const headerValue = _nullishCoalesce(response.headers.get(HEADER_RESPONSE), () => ( response.headers.get(HEADER_RESPONSE_V1)));
@@ -1836,7 +1871,8 @@ function parseSettleResponse(response) {
1836
1871
  if (!parsed || typeof parsed !== "object" || typeof parsed.success !== "boolean") return null;
1837
1872
  return {
1838
1873
  success: parsed.success,
1839
- ...typeof parsed.transaction === "string" ? { transaction: parsed.transaction } : {},
1874
+ // Tolerate the legacy v1 `txHash` alias for `transaction` (mirrors isValidReceipt/parseReceipt).
1875
+ ...typeof parsed.transaction === "string" ? { transaction: parsed.transaction } : typeof parsed.txHash === "string" ? { transaction: parsed.txHash } : {},
1840
1876
  ...typeof parsed.network === "string" ? { network: parsed.network } : {},
1841
1877
  ...typeof parsed.payer === "string" ? { payer: parsed.payer } : {},
1842
1878
  ...typeof parsed.errorReason === "string" ? { errorReason: parsed.errorReason } : {},
@@ -1855,6 +1891,14 @@ function parseSignatureObject(parsed) {
1855
1891
  if (!payload || typeof payload.txHash !== "string" || typeof payload.nonce !== "string") {
1856
1892
  return null;
1857
1893
  }
1894
+ if (!accepted) {
1895
+ const synthesized = {
1896
+ scheme: "onchain-proof",
1897
+ ...typeof v.network === "string" ? { network: v.network } : {},
1898
+ ...typeof v.asset === "string" ? { asset: v.asset } : {}
1899
+ };
1900
+ return { ...v, accepted: synthesized, payload };
1901
+ }
1858
1902
  return parsed;
1859
1903
  }
1860
1904
  function parseSignatureHeader(value) {
@@ -1994,7 +2038,11 @@ var evmDriver = {
1994
2038
  resolve(opts) {
1995
2039
  if (typeof opts.chain === "string" && /^(solana|ton|stellar)/.test(opts.chain)) return null;
1996
2040
  if (typeof opts.chain === "string") {
1997
- return makeEvmNetwork(resolveChain(opts.chain, opts.rpcUrl));
2041
+ try {
2042
+ return makeEvmNetwork(resolveChain(opts.chain, opts.rpcUrl));
2043
+ } catch (err) {
2044
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedNetworkError)(err instanceof Error ? err.message : String(err), { cause: err });
2045
+ }
1998
2046
  }
1999
2047
  let resolved;
2000
2048
  try {
@@ -2027,20 +2075,25 @@ function makeEvmNetwork(resolved) {
2027
2075
  const info = resolved.tokens[token.toUpperCase()];
2028
2076
  if (!info) {
2029
2077
  const known = Object.keys(resolved.tokens).join(", ") || "(none built in)";
2030
- throw new (0, _chunkDCOUJZPLcjs.UnknownTokenError)(
2078
+ throw new (0, _chunk57V5DNJTcjs.UnknownTokenError)(
2031
2079
  `token "${token}" isn't built in for ${resolved.chain.name} (known: ${known}). Pass { address, decimals } instead, or use 'native'.`
2032
2080
  );
2033
2081
  }
2034
2082
  return { asset: info.address, decimals: info.decimals, symbol: info.symbol };
2035
2083
  }
2036
- _chunkDCOUJZPLcjs.rejectForeignToken.call(void 0, token, "evm", network);
2084
+ _chunk57V5DNJTcjs.rejectForeignToken.call(void 0, token, "evm", network);
2037
2085
  if (!("address" in token)) {
2038
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
2086
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
2039
2087
  `chain ${network} is EVM; a custom token must be { address, decimals }.`
2040
2088
  );
2041
2089
  }
2090
+ if (!_viem.isAddress.call(void 0, token.address)) {
2091
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
2092
+ `chain ${network} is EVM, but token address "${token.address}" is not a valid 0x address.`
2093
+ );
2094
+ }
2042
2095
  return {
2043
- asset: token.address,
2096
+ asset: _viem.getAddress.call(void 0, token.address),
2044
2097
  decimals: token.decimals,
2045
2098
  ...token.symbol ? { symbol: token.symbol } : {}
2046
2099
  };
@@ -2067,20 +2120,20 @@ function makeEvmNetwork(resolved) {
2067
2120
  },
2068
2121
  assertValidPayTo(payTo) {
2069
2122
  if (!_viem.isAddress.call(void 0, payTo)) {
2070
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
2123
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
2071
2124
  `chain ${network} is EVM, but payTo "${payTo}" is not a valid 0x address.`
2072
2125
  );
2073
2126
  }
2074
2127
  },
2075
2128
  bindWallet(wallet) {
2076
2129
  if (typeof wallet !== "object" || wallet === null) {
2077
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
2130
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
2078
2131
  `chain ${network} is EVM; wallet must be { key } (0x\u2026 hex) or { walletClient }.`
2079
2132
  );
2080
2133
  }
2081
- _chunkDCOUJZPLcjs.assertNoLegacyWalletKey.call(void 0, wallet, "EVM");
2134
+ _chunk57V5DNJTcjs.assertNoLegacyWalletKey.call(void 0, wallet, "EVM");
2082
2135
  if (!("key" in wallet) && !("walletClient" in wallet)) {
2083
- throw new (0, _chunkDCOUJZPLcjs.WrongFamilyError)(
2136
+ throw new (0, _chunk57V5DNJTcjs.WrongFamilyError)(
2084
2137
  `chain ${network} is EVM; wallet must be { key } (0x\u2026 hex) or { walletClient }.`
2085
2138
  );
2086
2139
  }
@@ -2097,12 +2150,12 @@ function makeEvmNetwork(resolved) {
2097
2150
  });
2098
2151
  } catch (err) {
2099
2152
  if (isViemInsufficientFunds(err)) {
2100
- throw new (0, _chunkDCOUJZPLcjs.InsufficientFundsError)(
2153
+ throw new (0, _chunk57V5DNJTcjs.InsufficientFundsError)(
2101
2154
  err instanceof Error ? err.message : "Insufficient funds for payment.",
2102
2155
  { cause: err }
2103
2156
  );
2104
2157
  }
2105
- throw _nullishCoalesce(_chunkDCOUJZPLcjs.toInsufficientFundsError.call(void 0, err), () => ( err));
2158
+ throw _nullishCoalesce(_chunk57V5DNJTcjs.toInsufficientFundsError.call(void 0, err), () => ( err));
2106
2159
  }
2107
2160
  },
2108
2161
  async confirm(ref, minConfirmations) {
@@ -2113,7 +2166,7 @@ function makeEvmNetwork(resolved) {
2113
2166
  });
2114
2167
  return { height: receipt.blockNumber.toString() };
2115
2168
  } catch (err) {
2116
- throw new (0, _chunkDCOUJZPLcjs.ConfirmationTimeoutError)(
2169
+ throw new (0, _chunk57V5DNJTcjs.ConfirmationTimeoutError)(
2117
2170
  `EVM tx ${ref} did not reach ${minConfirmations} confirmation(s) in time.`,
2118
2171
  { cause: err }
2119
2172
  );
@@ -2121,10 +2174,10 @@ function makeEvmNetwork(resolved) {
2121
2174
  },
2122
2175
  async estimateCost(accept) {
2123
2176
  const { decimals, symbol } = resolved.chain.nativeCurrency;
2124
- if (accept.scheme === "exact") {
2125
- const m = accept.extra.assetTransferMethod;
2126
- const permit2 = m === "permit2" || m === "permit2-exact";
2127
- return _chunkDCOUJZPLcjs.nativeCost.call(void 0, {
2177
+ if (accept.scheme === "exact" || accept.scheme === "upto") {
2178
+ const m = _optionalChain([accept, 'access', _19 => _19.extra, 'optionalAccess', _20 => _20.assetTransferMethod]);
2179
+ const permit2 = m === "permit2" || m === "permit2-exact" || m === "permit2-upto";
2180
+ return _chunk57V5DNJTcjs.nativeCost.call(void 0, {
2128
2181
  symbol,
2129
2182
  decimals,
2130
2183
  fee: 0n,
@@ -2135,7 +2188,7 @@ function makeEvmNetwork(resolved) {
2135
2188
  const gasLimit = accept.asset === "native" ? 21000n : 65000n;
2136
2189
  try {
2137
2190
  const gasPrice = await publicClient.getGasPrice();
2138
- return _chunkDCOUJZPLcjs.nativeCost.call(void 0, {
2191
+ return _chunk57V5DNJTcjs.nativeCost.call(void 0, {
2139
2192
  symbol,
2140
2193
  decimals,
2141
2194
  fee: gasPrice * gasLimit,
@@ -2144,7 +2197,7 @@ function makeEvmNetwork(resolved) {
2144
2197
  });
2145
2198
  } catch (e23) {
2146
2199
  const gasPrice = 5000000000n;
2147
- return _chunkDCOUJZPLcjs.nativeCost.call(void 0, {
2200
+ return _chunk57V5DNJTcjs.nativeCost.call(void 0, {
2148
2201
  symbol,
2149
2202
  decimals,
2150
2203
  fee: gasPrice * gasLimit,
@@ -2329,9 +2382,9 @@ var loaders = {
2329
2382
  solana: async () => {
2330
2383
  let mod;
2331
2384
  try {
2332
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./solana-RQNXFCZO.cjs")));
2385
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./solana-B424IQ5I.cjs")));
2333
2386
  } catch (cause) {
2334
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2387
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2335
2388
  `Solana selected, but its packages aren't installed. Run: npm install @solana/web3.js @solana/spl-token bs58`,
2336
2389
  { cause }
2337
2390
  );
@@ -2341,9 +2394,9 @@ var loaders = {
2341
2394
  ton: async () => {
2342
2395
  let mod;
2343
2396
  try {
2344
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./ton-D7YN6BGR.cjs")));
2397
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./ton-3SHFVDLP.cjs")));
2345
2398
  } catch (cause) {
2346
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2399
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2347
2400
  `TON selected, but its packages aren't installed. Run: npm install @ton/ton @ton/core @ton/crypto`,
2348
2401
  { cause }
2349
2402
  );
@@ -2353,9 +2406,9 @@ var loaders = {
2353
2406
  stellar: async () => {
2354
2407
  let mod;
2355
2408
  try {
2356
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./stellar-OK2HW5PZ.cjs")));
2409
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./stellar-4YR4UZQX.cjs")));
2357
2410
  } catch (cause) {
2358
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2411
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2359
2412
  `Stellar selected, but its package isn't installed. Run: npm install @stellar/stellar-sdk`,
2360
2413
  { cause }
2361
2414
  );
@@ -2365,9 +2418,9 @@ var loaders = {
2365
2418
  xrpl: async () => {
2366
2419
  let mod;
2367
2420
  try {
2368
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./xrpl-5NHY3NEL.cjs")));
2421
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./xrpl-SUEFOOKW.cjs")));
2369
2422
  } catch (cause) {
2370
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2423
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2371
2424
  `XRPL selected, but its package isn't installed. Run: npm install xrpl`,
2372
2425
  { cause }
2373
2426
  );
@@ -2377,9 +2430,9 @@ var loaders = {
2377
2430
  tron: async () => {
2378
2431
  let mod;
2379
2432
  try {
2380
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./tron-WZFU57NX.cjs")));
2433
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./tron-BS5EID2U.cjs")));
2381
2434
  } catch (cause) {
2382
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2435
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2383
2436
  `Tron selected, but its package isn't installed. Run: npm install tronweb`,
2384
2437
  { cause }
2385
2438
  );
@@ -2389,9 +2442,9 @@ var loaders = {
2389
2442
  sui: async () => {
2390
2443
  let mod;
2391
2444
  try {
2392
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./sui-SVFBJFW5.cjs")));
2445
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./sui-F7UW6JXJ.cjs")));
2393
2446
  } catch (cause) {
2394
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2447
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2395
2448
  `Sui selected, but its package isn't installed. Run: npm install @mysten/sui`,
2396
2449
  { cause }
2397
2450
  );
@@ -2401,9 +2454,9 @@ var loaders = {
2401
2454
  near: async () => {
2402
2455
  let mod;
2403
2456
  try {
2404
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./near-UDPFA6SV.cjs")));
2457
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./near-C2IS4RCH.cjs")));
2405
2458
  } catch (cause) {
2406
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2459
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2407
2460
  `NEAR selected, but its package isn't installed. Run: npm install near-api-js`,
2408
2461
  { cause }
2409
2462
  );
@@ -2413,9 +2466,9 @@ var loaders = {
2413
2466
  aptos: async () => {
2414
2467
  let mod;
2415
2468
  try {
2416
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./aptos-65UX7GKA.cjs")));
2469
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./aptos-MVEG5ZPS.cjs")));
2417
2470
  } catch (cause) {
2418
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2471
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2419
2472
  `Aptos selected, but its package isn't installed. Run: npm install @aptos-labs/ts-sdk`,
2420
2473
  { cause }
2421
2474
  );
@@ -2425,9 +2478,9 @@ var loaders = {
2425
2478
  algorand: async () => {
2426
2479
  let mod;
2427
2480
  try {
2428
- mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./algorand-AQK5EAUF.cjs")));
2481
+ mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./algorand-ICJNXO5V.cjs")));
2429
2482
  } catch (cause) {
2430
- throw new (0, _chunkDCOUJZPLcjs.MissingDriverError)(
2483
+ throw new (0, _chunk57V5DNJTcjs.MissingDriverError)(
2431
2484
  `Algorand selected, but its package isn't installed. Run: npm install algosdk`,
2432
2485
  { cause }
2433
2486
  );
@@ -2458,7 +2511,7 @@ async function resolveNetwork2(opts) {
2458
2511
  }
2459
2512
 
2460
2513
  // src/indexes.ts
2461
- var DIRECTORY_INFO = {
2514
+ var DIRECTORY_INFO = Object.freeze({
2462
2515
  "402index": {
2463
2516
  source: "402index",
2464
2517
  review: "probe-sync",
@@ -2486,7 +2539,7 @@ var DIRECTORY_INFO = {
2486
2539
  readByDiscover: true,
2487
2540
  caveat: "CDP Bazaar has no register endpoint \u2014 it catalogs a resource only when its own facilitator settles a payment. PipRail verifies locally with no facilitator, so a PipRail resource cannot be listed here (you can still READ Bazaar to find others). List on 402 Index or x402scan instead."
2488
2541
  }
2489
- };
2542
+ });
2490
2543
  function getDirectoryInfo(source) {
2491
2544
  return DIRECTORY_INFO[source];
2492
2545
  }
@@ -2788,7 +2841,7 @@ async function register402Index(input) {
2788
2841
  if (res.ok) {
2789
2842
  const body = await res.json().catch(() => ({}));
2790
2843
  const msg = typeof body.message === "string" && body.message.length > 0 ? body.message : void 0;
2791
- const live = _optionalChain([body, 'access', _19 => _19.service, 'optionalAccess', _20 => _20.status]) === "active";
2844
+ const live = _optionalChain([body, 'access', _21 => _21.service, 'optionalAccess', _22 => _22.status]) === "active";
2792
2845
  return {
2793
2846
  source: "402index",
2794
2847
  ok: true,
@@ -2925,11 +2978,11 @@ async function readSiwxInfo(res) {
2925
2978
  try {
2926
2979
  const body = await res.json();
2927
2980
  const ext = body.extensions;
2928
- const siwx = _optionalChain([ext, 'optionalAccess', _21 => _21["sign-in-with-x"]]);
2929
- const info = _nullishCoalesce(_optionalChain([siwx, 'optionalAccess', _22 => _22.info]), () => ( siwx));
2930
- if (info && info.chainId == null && Array.isArray(_optionalChain([siwx, 'optionalAccess', _23 => _23.supportedChains]))) {
2981
+ const siwx = _optionalChain([ext, 'optionalAccess', _23 => _23["sign-in-with-x"]]);
2982
+ const info = _nullishCoalesce(_optionalChain([siwx, 'optionalAccess', _24 => _24.info]), () => ( siwx));
2983
+ if (info && info.chainId == null && Array.isArray(_optionalChain([siwx, 'optionalAccess', _25 => _25.supportedChains]))) {
2931
2984
  const evm = siwx.supportedChains.find(
2932
- (c) => typeof _optionalChain([c, 'optionalAccess', _24 => _24.chainId]) === "string" && c.chainId.startsWith("eip155:")
2985
+ (c) => typeof _optionalChain([c, 'optionalAccess', _26 => _26.chainId]) === "string" && c.chainId.startsWith("eip155:")
2933
2986
  );
2934
2987
  if (evm && typeof evm.chainId === "string") info.chainId = evm.chainId;
2935
2988
  }
@@ -3071,7 +3124,7 @@ function encodeBase642(str) {
3071
3124
  }
3072
3125
 
3073
3126
  // src/policy.ts
3074
- var DENOM_PRECISION = _chunkDCOUJZPLcjs.MAX_DECIMALS;
3127
+ var DENOM_PRECISION = _chunk57V5DNJTcjs.MAX_DECIMALS;
3075
3128
  var BUILTIN_DENOMS = {
3076
3129
  USDC: "USD",
3077
3130
  USDT: "USD",
@@ -3085,7 +3138,7 @@ var BUILTIN_DENOMS = {
3085
3138
  function denomOf(symbol, asset, policy) {
3086
3139
  if (asset === "native") return void 0;
3087
3140
  const norm = (v) => typeof v === "string" && v.trim() !== "" ? v.trim().toUpperCase() : void 0;
3088
- const override = _optionalChain([policy, 'optionalAccess', _25 => _25.denomFor]);
3141
+ const override = _optionalChain([policy, 'optionalAccess', _27 => _27.denomFor]);
3089
3142
  if (override && typeof override === "object") {
3090
3143
  if (asset && asset in override) {
3091
3144
  const d = norm(override[asset]);
@@ -3186,7 +3239,7 @@ function evaluatePolicy(intent, policy, spentForAssetBase, ctx) {
3186
3239
  }
3187
3240
  }
3188
3241
  if (policy.maxAmount !== void 0) {
3189
- const cap = _chunkDCOUJZPLcjs.floorUnits.call(void 0, policy.maxAmount, intent.decimals);
3242
+ const cap = _chunk57V5DNJTcjs.floorUnits.call(void 0, policy.maxAmount, intent.decimals);
3190
3243
  if (intent.amountBase > cap) {
3191
3244
  return deny(
3192
3245
  "MAX_AMOUNT",
@@ -3195,7 +3248,7 @@ function evaluatePolicy(intent, policy, spentForAssetBase, ctx) {
3195
3248
  }
3196
3249
  }
3197
3250
  if (policy.maxTotal !== void 0) {
3198
- const cap = _chunkDCOUJZPLcjs.floorUnits.call(void 0, policy.maxTotal, intent.decimals);
3251
+ const cap = _chunk57V5DNJTcjs.floorUnits.call(void 0, policy.maxTotal, intent.decimals);
3199
3252
  if (spentForAssetBase + intent.amountBase > cap) {
3200
3253
  return deny(
3201
3254
  "MAX_TOTAL",
@@ -3214,7 +3267,7 @@ function evaluatePolicy(intent, policy, spentForAssetBase, ctx) {
3214
3267
  `token for ${denom} has more than ${DENOM_PRECISION} decimals \u2014 refusing to count it toward policy.maxTotalPerDenom.${denom} on trust (it can't be summed safely).`
3215
3268
  );
3216
3269
  }
3217
- const capScaled = _chunkDCOUJZPLcjs.floorUnits.call(void 0, capStr, DENOM_PRECISION);
3270
+ const capScaled = _chunk57V5DNJTcjs.floorUnits.call(void 0, capStr, DENOM_PRECISION);
3218
3271
  if ((_nullishCoalesce(ctx.spentInDenomScaled, () => ( 0n))) + thisScaled > capScaled) {
3219
3272
  return deny(
3220
3273
  "MAX_TOTAL_DENOM",
@@ -3232,7 +3285,7 @@ function evaluatePolicy(intent, policy, spentForAssetBase, ctx) {
3232
3285
  }
3233
3286
  }
3234
3287
  if (ctx && policy.windowTotal !== void 0 && policy.windowSeconds !== void 0) {
3235
- const cap = _chunkDCOUJZPLcjs.floorUnits.call(void 0, policy.windowTotal, intent.decimals);
3288
+ const cap = _chunk57V5DNJTcjs.floorUnits.call(void 0, policy.windowTotal, intent.decimals);
3236
3289
  if (ctx.spentInWindowBase + intent.amountBase > cap) {
3237
3290
  return deny(
3238
3291
  "WINDOW_TOTAL",
@@ -3286,7 +3339,7 @@ var SpendLedger = (_class = class {
3286
3339
  } catch (e30) {
3287
3340
  seed = [];
3288
3341
  }
3289
- for (const r of seed) this.ingest(r, _nullishCoalesce(_optionalChain([r, 'optionalAccess', _26 => _26.decimals]), () => ( 0)), _optionalChain([r, 'optionalAccess', _27 => _27.denom]));
3342
+ for (const r of seed) this.ingest(r, _nullishCoalesce(_optionalChain([r, 'optionalAccess', _28 => _28.decimals]), () => ( 0)), _optionalChain([r, 'optionalAccess', _29 => _29.denom]));
3290
3343
  }
3291
3344
  }
3292
3345
  /**
@@ -3298,7 +3351,7 @@ var SpendLedger = (_class = class {
3298
3351
  * read or the constructor.
3299
3352
  */
3300
3353
  isTallyable(r, decimals) {
3301
- return !!r && typeof r.amountBase === "string" && /^\d+$/.test(r.amountBase) && Number.isInteger(decimals) && decimals >= 0 && decimals <= _chunkDCOUJZPLcjs.MAX_DECIMALS;
3354
+ return !!r && typeof r.amountBase === "string" && /^\d+$/.test(r.amountBase) && Number.isInteger(decimals) && decimals >= 0 && decimals <= _chunk57V5DNJTcjs.MAX_DECIMALS;
3302
3355
  }
3303
3356
  /** Apply a record to the in-memory tallies (records + per-asset bucket + denom total).
3304
3357
  * Shared by {@link record} and constructor hydration; does NOT persist. Returns the
@@ -3348,7 +3401,7 @@ var SpendLedger = (_class = class {
3348
3401
  }
3349
3402
  /** Running total (base units) already spent on this (network, asset). */
3350
3403
  totalFor(network, asset) {
3351
- return _nullishCoalesce(_optionalChain([this, 'access', _28 => _28.buckets, 'access', _29 => _29.get, 'call', _30 => _30(keyFor(network, asset)), 'optionalAccess', _31 => _31.total]), () => ( 0n));
3404
+ return _nullishCoalesce(_optionalChain([this, 'access', _30 => _30.buckets, 'access', _31 => _31.get, 'call', _32 => _32(keyFor(network, asset)), 'optionalAccess', _33 => _33.total]), () => ( 0n));
3352
3405
  }
3353
3406
  /**
3354
3407
  * Running grand total for a DENOMINATION, scaled to {@link DENOM_PRECISION} (so
@@ -3435,14 +3488,14 @@ var SpendLedger = (_class = class {
3435
3488
  symbol: b.symbol,
3436
3489
  decimals: b.decimals,
3437
3490
  totalBase: b.total.toString(),
3438
- totalFormatted: _chunkDCOUJZPLcjs.formatUnits.call(void 0, b.total, b.decimals),
3491
+ totalFormatted: _chunk57V5DNJTcjs.formatUnits.call(void 0, b.total, b.decimals),
3439
3492
  count: b.count
3440
3493
  })),
3441
3494
  byDenom: [...this.denomTotals.entries()].map(([denom, scaled]) => ({
3442
3495
  denom,
3443
3496
  totalScaled: scaled.toString(),
3444
- totalFormatted: _chunkDCOUJZPLcjs.formatUnits.call(void 0, scaled, DENOM_PRECISION),
3445
- count: this.records.filter((r) => _optionalChain([r, 'access', _32 => _32.denom, 'optionalAccess', _33 => _33.toUpperCase, 'call', _34 => _34()]) === denom).length
3497
+ totalFormatted: _chunk57V5DNJTcjs.formatUnits.call(void 0, scaled, DENOM_PRECISION),
3498
+ count: this.records.filter((r) => _optionalChain([r, 'access', _34 => _34.denom, 'optionalAccess', _35 => _35.toUpperCase, 'call', _36 => _36()]) === denom).length
3446
3499
  })),
3447
3500
  records: [...this.records]
3448
3501
  };
@@ -3678,17 +3731,17 @@ var PipRailClient = (_class2 = class {
3678
3731
  * {@link ReceiptVerification}).
3679
3732
  */
3680
3733
  static async verifyReceipt(receipt, opts) {
3681
- const r = _optionalChain([receipt, 'optionalAccess', _35 => _35.receipt]);
3734
+ const r = _optionalChain([receipt, 'optionalAccess', _37 => _37.receipt]);
3682
3735
  if (!r || typeof r !== "object") {
3683
3736
  return { ok: false, onChain: { payTo: "", asset: "", amount: "", payer: "" }, matchesClaims: false, ageSeconds: 0, error: "tx_not_found" };
3684
3737
  }
3685
3738
  const claimed = { payTo: _nullishCoalesce(r.payTo, () => ( "")), asset: _nullishCoalesce(r.asset, () => ( "")), amount: _nullishCoalesce(r.amount, () => ( "")), payer: _nullishCoalesce(r.payer, () => ( "")) };
3686
3739
  const ageSeconds = receiptAgeSeconds(r.verifiedAt);
3687
3740
  try {
3688
- const chain = chainSelectorForNetwork(r.network, _optionalChain([opts, 'optionalAccess', _36 => _36.rpcUrl]));
3741
+ const chain = chainSelectorForNetwork(r.network, _optionalChain([opts, 'optionalAccess', _38 => _38.rpcUrl]));
3689
3742
  const net = await resolveNetwork2({
3690
3743
  chain,
3691
- ..._optionalChain([opts, 'optionalAccess', _37 => _37.rpcUrl]) ? { rpcUrl: opts.rpcUrl } : {}
3744
+ ..._optionalChain([opts, 'optionalAccess', _39 => _39.rpcUrl]) ? { rpcUrl: opts.rpcUrl } : {}
3692
3745
  });
3693
3746
  const accept = {
3694
3747
  scheme: "onchain-proof",
@@ -3735,7 +3788,7 @@ var PipRailClient = (_class2 = class {
3735
3788
  * no chain libs. The JWS format defers to R3 (`{ ok:false, reason:'jws-not-loaded' }`).
3736
3789
  */
3737
3790
  static async verifyAttestation(receipt) {
3738
- const att = _optionalChain([receipt, 'optionalAccess', _38 => _38.attestation]);
3791
+ const att = _optionalChain([receipt, 'optionalAccess', _40 => _40.attestation]);
3739
3792
  if (!att || typeof att !== "object" || typeof att.signature !== "string") {
3740
3793
  return { ok: false, reason: "no-attestation" };
3741
3794
  }
@@ -3746,7 +3799,7 @@ var PipRailClient = (_class2 = class {
3746
3799
  if (!r || typeof r !== "object") return { ok: false, reason: "no-receipt" };
3747
3800
  const payload = _nullishCoalesce(att.payload, () => ( {}));
3748
3801
  const network = typeof payload.network === "string" ? payload.network : r.network;
3749
- const resourceUrl = typeof payload.resourceUrl === "string" ? payload.resourceUrl : _nullishCoalesce(_optionalChain([receipt, 'access', _39 => _39.resource, 'optionalAccess', _40 => _40.url]), () => ( ""));
3802
+ const resourceUrl = typeof payload.resourceUrl === "string" ? payload.resourceUrl : _nullishCoalesce(_optionalChain([receipt, 'access', _41 => _41.resource, 'optionalAccess', _42 => _42.url]), () => ( ""));
3750
3803
  const payer = typeof payload.payer === "string" ? payload.payer : r.payer;
3751
3804
  const issuedAt = typeof payload.issuedAt === "number" ? payload.issuedAt : receiptIssuedAtSeconds(r.verifiedAt);
3752
3805
  const transaction = typeof payload.transaction === "string" ? payload.transaction : _nullishCoalesce(r.transaction, () => ( ""));
@@ -3792,7 +3845,7 @@ var PipRailClient = (_class2 = class {
3792
3845
  * as-is) or a plain object (serialised as JSON).
3793
3846
  */
3794
3847
  post(url, body, init) {
3795
- const headers = new Headers(_optionalChain([init, 'optionalAccess', _41 => _41.headers]));
3848
+ const headers = new Headers(_optionalChain([init, 'optionalAccess', _43 => _43.headers]));
3796
3849
  let payload;
3797
3850
  if (body === void 0 || body === null) {
3798
3851
  payload = void 0;
@@ -3823,7 +3876,7 @@ var PipRailClient = (_class2 = class {
3823
3876
  * "0.05 USDC on Base, within budget → pay it." No funds move.
3824
3877
  */
3825
3878
  async quote(url, init) {
3826
- const res = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), method: _nullishCoalesce(_optionalChain([init, 'optionalAccess', _42 => _42.method]), () => ( "GET")) });
3879
+ const res = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), method: _nullishCoalesce(_optionalChain([init, 'optionalAccess', _44 => _44.method]), () => ( "GET")) });
3827
3880
  if (res.status !== 402) return null;
3828
3881
  const { quote } = await this.resolveChallenge(url, res, this.resolveSchemes());
3829
3882
  return quote;
@@ -3842,14 +3895,14 @@ var PipRailClient = (_class2 = class {
3842
3895
  * on Tron, where a USD₮ transfer can cost real TRX.
3843
3896
  */
3844
3897
  async estimateCost(url, init) {
3845
- const res = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), method: _nullishCoalesce(_optionalChain([init, 'optionalAccess', _43 => _43.method]), () => ( "GET")) });
3898
+ const res = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), method: _nullishCoalesce(_optionalChain([init, 'optionalAccess', _45 => _45.method]), () => ( "GET")) });
3846
3899
  if (res.status !== 402) return null;
3847
3900
  try {
3848
3901
  const { net, accept, quote } = await this.resolveChallenge(url, res, this.resolveSchemes());
3849
3902
  const cost = await net.estimateCost(accept);
3850
3903
  return { quote, cost };
3851
3904
  } catch (err) {
3852
- if (err instanceof _chunkDCOUJZPLcjs.InvalidEnvelopeError) return null;
3905
+ if (err instanceof _chunk57V5DNJTcjs.InvalidEnvelopeError) return null;
3853
3906
  throw err;
3854
3907
  }
3855
3908
  }
@@ -3880,8 +3933,8 @@ var PipRailClient = (_class2 = class {
3880
3933
  return {
3881
3934
  session: {
3882
3935
  start,
3883
- expiresAt: _optionalChain([view, 'optionalAccess', _44 => _44.expiresAt]) != null ? new Date(view.expiresAt).toISOString() : null,
3884
- secondsRemaining: _nullishCoalesce(_optionalChain([view, 'optionalAccess', _45 => _45.secondsRemaining]), () => ( null))
3936
+ expiresAt: _optionalChain([view, 'optionalAccess', _46 => _46.expiresAt]) != null ? new Date(view.expiresAt).toISOString() : null,
3937
+ secondsRemaining: _nullishCoalesce(_optionalChain([view, 'optionalAccess', _47 => _47.secondsRemaining]), () => ( null))
3885
3938
  },
3886
3939
  byAsset: this.remaining(),
3887
3940
  byDenom: this.denomRemaining(),
@@ -3896,19 +3949,19 @@ var PipRailClient = (_class2 = class {
3896
3949
  * price-converted figure (tokens grouped as one unit, each 1:1).
3897
3950
  */
3898
3951
  denomRemaining() {
3899
- const caps = _optionalChain([this, 'access', _46 => _46.opts, 'access', _47 => _47.policy, 'optionalAccess', _48 => _48.maxTotalPerDenom]);
3952
+ const caps = _optionalChain([this, 'access', _48 => _48.opts, 'access', _49 => _49.policy, 'optionalAccess', _50 => _50.maxTotalPerDenom]);
3900
3953
  if (!caps) return [];
3901
3954
  return Object.entries(caps).map(([rawDenom, capStr]) => {
3902
3955
  const denom = rawDenom.toUpperCase();
3903
3956
  const spentScaled = this.ledger.totalForDenom(denom);
3904
- const capScaled = _chunkDCOUJZPLcjs.floorUnits.call(void 0, capStr, DENOM_PRECISION);
3957
+ const capScaled = _chunk57V5DNJTcjs.floorUnits.call(void 0, capStr, DENOM_PRECISION);
3905
3958
  const remainingScaled = capScaled > spentScaled ? capScaled - spentScaled : 0n;
3906
3959
  const fraction = capScaled === 0n ? spentScaled > 0n ? 1 : 0 : Number(spentScaled * 1000000n / capScaled) / 1e6;
3907
3960
  return {
3908
3961
  denom,
3909
- spentFormatted: _chunkDCOUJZPLcjs.formatUnits.call(void 0, spentScaled, DENOM_PRECISION),
3910
- capFormatted: _chunkDCOUJZPLcjs.formatUnits.call(void 0, capScaled, DENOM_PRECISION),
3911
- remainingFormatted: _chunkDCOUJZPLcjs.formatUnits.call(void 0, remainingScaled, DENOM_PRECISION),
3962
+ spentFormatted: _chunk57V5DNJTcjs.formatUnits.call(void 0, spentScaled, DENOM_PRECISION),
3963
+ capFormatted: _chunk57V5DNJTcjs.formatUnits.call(void 0, capScaled, DENOM_PRECISION),
3964
+ remainingFormatted: _chunk57V5DNJTcjs.formatUnits.call(void 0, remainingScaled, DENOM_PRECISION),
3912
3965
  fraction
3913
3966
  };
3914
3967
  });
@@ -3919,11 +3972,11 @@ var PipRailClient = (_class2 = class {
3919
3972
  const policy = this.opts.policy;
3920
3973
  const settled = this.ledger.count();
3921
3974
  const out = { settled };
3922
- if (_optionalChain([policy, 'optionalAccess', _49 => _49.maxPayments]) !== void 0) {
3975
+ if (_optionalChain([policy, 'optionalAccess', _51 => _51.maxPayments]) !== void 0) {
3923
3976
  out.lifetimeCap = policy.maxPayments;
3924
3977
  out.lifetimeRemaining = Math.max(0, policy.maxPayments - settled);
3925
3978
  }
3926
- if (_optionalChain([policy, 'optionalAccess', _50 => _50.maxPaymentsPerWindow]) !== void 0 && policy.windowSeconds !== void 0) {
3979
+ if (_optionalChain([policy, 'optionalAccess', _52 => _52.maxPaymentsPerWindow]) !== void 0 && policy.windowSeconds !== void 0) {
3927
3980
  const windowSettled = this.ledger.countSince(Date.now() - policy.windowSeconds * 1e3);
3928
3981
  out.windowCap = policy.maxPaymentsPerWindow;
3929
3982
  out.windowSettled = windowSettled;
@@ -3939,7 +3992,7 @@ var PipRailClient = (_class2 = class {
3939
3992
  * never throws, never sums across tokens (no price oracle). PROCESS-SCOPED.
3940
3993
  */
3941
3994
  remaining() {
3942
- const maxTotal = _optionalChain([this, 'access', _51 => _51.opts, 'access', _52 => _52.policy, 'optionalAccess', _53 => _53.maxTotal]);
3995
+ const maxTotal = _optionalChain([this, 'access', _53 => _53.opts, 'access', _54 => _54.policy, 'optionalAccess', _55 => _55.maxTotal]);
3943
3996
  return this.ledger.assetBuckets().map((b) => {
3944
3997
  const base2 = {
3945
3998
  network: b.network,
@@ -3949,13 +4002,13 @@ var PipRailClient = (_class2 = class {
3949
4002
  spentBase: b.totalBase.toString()
3950
4003
  };
3951
4004
  if (maxTotal === void 0) return base2;
3952
- const capBase = _chunkDCOUJZPLcjs.floorUnits.call(void 0, maxTotal, b.decimals);
4005
+ const capBase = _chunk57V5DNJTcjs.floorUnits.call(void 0, maxTotal, b.decimals);
3953
4006
  const remainingBase = capBase > b.totalBase ? capBase - b.totalBase : 0n;
3954
4007
  return {
3955
4008
  ...base2,
3956
4009
  capBase: capBase.toString(),
3957
4010
  remainingBase: remainingBase.toString(),
3958
- remainingFormatted: _chunkDCOUJZPLcjs.formatUnits.call(void 0, remainingBase, b.decimals)
4011
+ remainingFormatted: _chunk57V5DNJTcjs.formatUnits.call(void 0, remainingBase, b.decimals)
3959
4012
  };
3960
4013
  });
3961
4014
  }
@@ -3991,15 +4044,15 @@ var PipRailClient = (_class2 = class {
3991
4044
  * the plan yourself. No funds move.
3992
4045
  */
3993
4046
  async planPayment(url, init) {
3994
- const res = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), method: _nullishCoalesce(_optionalChain([init, 'optionalAccess', _54 => _54.method]), () => ( "GET")) });
4047
+ const res = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), method: _nullishCoalesce(_optionalChain([init, 'optionalAccess', _56 => _56.method]), () => ( "GET")) });
3995
4048
  if (res.status !== 402) return null;
3996
4049
  const challenge = await parseChallenge(res);
3997
4050
  if (!challenge) {
3998
- throw new (0, _chunkDCOUJZPLcjs.InvalidEnvelopeError)("402 response did not include a parseable x402 challenge.");
4051
+ throw new (0, _chunk57V5DNJTcjs.InvalidEnvelopeError)("402 response did not include a parseable x402 challenge.");
3999
4052
  }
4000
4053
  const { net, wallet } = await this.ensure();
4001
4054
  if (!wallet) {
4002
- throw new (0, _chunkDCOUJZPLcjs.WalletRequiredError)(
4055
+ throw new (0, _chunk57V5DNJTcjs.WalletRequiredError)(
4003
4056
  "planPayment needs a wallet (it checks YOUR balance, gas, and recipient-readiness). This client is read-only \u2014 construct it with a `wallet` to plan or pay."
4004
4057
  );
4005
4058
  }
@@ -4032,7 +4085,8 @@ var PipRailClient = (_class2 = class {
4032
4085
  * before publishing, so retry with a brief backoff if a fresh listing is missing.
4033
4086
  * - Results are cross-scheme (mostly the mainstream `exact` scheme); `fetch()` pays
4034
4087
  * `onchain-proof` rails by default, and standard `exact` rails too once you opt in
4035
- * with `schemes: ['onchain-proof', 'exact']` (EVM EIP-3009/Permit2 + Solana SVM + Algorand).
4088
+ * with `schemes: ['onchain-proof', 'exact']` (EVM EIP-3009/Permit2 + Solana SVM + Algorand
4089
+ * + Aptos + NEAR).
4036
4090
  */
4037
4091
  async discover(opts = {}) {
4038
4092
  const found = await searchOpenIndexes({
@@ -4172,31 +4226,31 @@ var PipRailClient = (_class2 = class {
4172
4226
  * streams throw `NonReplayableBodyError`.
4173
4227
  */
4174
4228
  async fetch(url, init) {
4175
- const body = _optionalChain([init, 'optionalAccess', _55 => _55.body]);
4229
+ const body = _optionalChain([init, 'optionalAccess', _57 => _57.body]);
4176
4230
  if (body !== void 0 && body !== null && !isReplayableBodyInit(body)) {
4177
- throw new (0, _chunkDCOUJZPLcjs.NonReplayableBodyError)(
4231
+ throw new (0, _chunk57V5DNJTcjs.NonReplayableBodyError)(
4178
4232
  "fetch(): init.body is not replayable. Pass a string, FormData, URLSearchParams, ArrayBuffer, or Blob \u2014 not a ReadableStream."
4179
4233
  );
4180
4234
  }
4181
4235
  const firstResponse = await fetch(url, init);
4182
4236
  if (firstResponse.status !== 402) return firstResponse;
4183
- const schemes = this.resolveSchemes(_optionalChain([init, 'optionalAccess', _56 => _56.schemes]));
4237
+ const schemes = this.resolveSchemes(_optionalChain([init, 'optionalAccess', _58 => _58.schemes]));
4184
4238
  const resolved = await this.resolveChallenge(url, firstResponse, schemes);
4185
4239
  const { net, wallet, challenge } = resolved;
4186
4240
  if (!wallet) {
4187
- throw new (0, _chunkDCOUJZPLcjs.WalletRequiredError)(
4241
+ throw new (0, _chunk57V5DNJTcjs.WalletRequiredError)(
4188
4242
  "Paying a 402 needs a wallet to sign + settle. This client is read-only \u2014 construct it with a `wallet` to pay (quote/discover/register still work without one)."
4189
4243
  );
4190
4244
  }
4191
4245
  let accept = resolved.accept;
4192
4246
  let quote = resolved.quote;
4193
- const autoRoute = _nullishCoalesce(_nullishCoalesce(_optionalChain([init, 'optionalAccess', _57 => _57.autoRoute]), () => ( this.opts.autoRoute)), () => ( false));
4247
+ const autoRoute = _nullishCoalesce(_nullishCoalesce(_optionalChain([init, 'optionalAccess', _59 => _59.autoRoute]), () => ( this.opts.autoRoute)), () => ( false));
4194
4248
  if (autoRoute) {
4195
4249
  const plan = await this.planFromChallenge(net, wallet, challenge, url, schemes);
4196
4250
  if (!plan.best) {
4197
4251
  const reason = _nullishCoalesce(plan.fundingHint, () => ( "No rail is settleable for this payment."));
4198
4252
  this.safeEmit({ kind: "payment-failed", reason });
4199
- throw new (0, _chunkDCOUJZPLcjs.PaymentDeclinedError)(reason);
4253
+ throw new (0, _chunk57V5DNJTcjs.PaymentDeclinedError)(reason);
4200
4254
  }
4201
4255
  accept = plan.best.accept;
4202
4256
  quote = plan.best.quote;
@@ -4210,7 +4264,7 @@ var PipRailClient = (_class2 = class {
4210
4264
  return this.payExactRail(net, wallet, accept, url, init, quote);
4211
4265
  }
4212
4266
  if (accept.scheme !== "onchain-proof") {
4213
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
4267
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
4214
4268
  `internal: unrouted accept scheme '${accept.scheme}' reached the onchain-proof pay path.`
4215
4269
  );
4216
4270
  }
@@ -4228,7 +4282,7 @@ var PipRailClient = (_class2 = class {
4228
4282
  async resolveChallenge(url, response, schemes) {
4229
4283
  const challenge = await parseChallenge(response);
4230
4284
  if (!challenge) {
4231
- throw new (0, _chunkDCOUJZPLcjs.InvalidEnvelopeError)(
4285
+ throw new (0, _chunk57V5DNJTcjs.InvalidEnvelopeError)(
4232
4286
  "402 response did not include a parseable x402 challenge."
4233
4287
  );
4234
4288
  }
@@ -4239,8 +4293,8 @@ var PipRailClient = (_class2 = class {
4239
4293
  (a) => a.scheme === "exact" && this.supportsNetwork(net, a.network)
4240
4294
  );
4241
4295
  if (schemes.includes("exact") && exactOnNet && typeof net.payExact !== "function") {
4242
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
4243
- `This 402 offers a standard 'exact' rail on ${net.network}, but the ${net.family} family can't pay 'exact' (supported on EVM, Solana, Algorand + NEAR today), and no 'onchain-proof' rail was offered.`
4296
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
4297
+ `This 402 offers a standard 'exact' rail on ${net.network}, but the ${net.family} family can't pay 'exact' (supported on EVM, Solana, Algorand, Aptos + NEAR today), and no 'onchain-proof' rail was offered.`
4244
4298
  );
4245
4299
  }
4246
4300
  if (!schemes.includes("exact") && exactOnNet && typeof net.payExact === "function") {
@@ -4248,13 +4302,13 @@ var PipRailClient = (_class2 = class {
4248
4302
  (a) => a.scheme === "exact" && this.supportsNetwork(net, a.network) && net.describeAsset(a.asset) != null
4249
4303
  );
4250
4304
  if (payable) {
4251
- throw new (0, _chunkDCOUJZPLcjs.NoCompatibleAcceptError)(
4305
+ throw new (0, _chunk57V5DNJTcjs.NoCompatibleAcceptError)(
4252
4306
  `This 402 is payable only via the standard 'exact' rail on ${net.network}, which is OFF by default. Enable it: new PipRailClient({ \u2026, schemes: ['onchain-proof', 'exact'] }) or per call fetch(url, { schemes: ['exact'] }) (MCP: PIPRAIL_SCHEMES=onchain-proof,exact).`
4253
4307
  );
4254
4308
  }
4255
4309
  }
4256
4310
  const networks = [...new Set(challenge.accepts.map((a) => a.network))].join(", ");
4257
- throw new (0, _chunkDCOUJZPLcjs.NoCompatibleAcceptError)(
4311
+ throw new (0, _chunk57V5DNJTcjs.NoCompatibleAcceptError)(
4258
4312
  `No accepts[] entry payable by this client on ${net.network} (schemes: ${schemes.join(", ")}; challenge offered: ${networks || "none"}).`
4259
4313
  );
4260
4314
  }
@@ -4293,7 +4347,15 @@ var PipRailClient = (_class2 = class {
4293
4347
  if (schemes.includes("exact")) {
4294
4348
  out.push(
4295
4349
  ...challenge.accepts.filter(
4296
- (a) => a.scheme === "exact" && this.supportsNetwork(net, a.network) && typeof net.payExact === "function" && net.describeAsset(a.asset) != null && // a foreign rail's maxTimeoutSeconds must be a usable positive integer, or
4350
+ (a) => a.scheme === "exact" && this.supportsNetwork(net, a.network) && typeof net.payExact === "function" && // `native` is never `exact`-payable on ANY family (exact = an EIP-3009/Permit2-style
4351
+ // signed-authorization scheme a native coin can't support; every driver's payExact
4352
+ // throws/returns-null for it). describeAsset('native') IS non-null (onchain-proof needs
4353
+ // it), so without this guard a malformed 402 advertising a native `exact` rail would be
4354
+ // gathered, planned `payable`, even chosen by autoRoute — then throw at pay time.
4355
+ a.asset !== "native" && // the exact pay path (payExact → driver) reads `extra.assetTransferMethod`; a malformed
4356
+ // 402 offering an exact rail for a RECOGNISED token but omitting `extra` would otherwise
4357
+ // be planned payable then throw a raw TypeError mid-pay. Require it at gather time.
4358
+ typeof _optionalChain([a, 'access', _60 => _60.extra, 'optionalAccess', _61 => _61.assetTransferMethod]) === "string" && net.describeAsset(a.asset) != null && // a foreign rail's maxTimeoutSeconds must be a usable positive integer, or
4297
4359
  // signing it would build a NaN/garbage validBefore — drop it silently
4298
4360
  // (symmetric with an unrecognised token) rather than leak a raw SyntaxError.
4299
4361
  Number.isInteger(a.maxTimeoutSeconds) && a.maxTimeoutSeconds > 0
@@ -4303,7 +4365,8 @@ var PipRailClient = (_class2 = class {
4303
4365
  if (schemes.includes("upto")) {
4304
4366
  out.push(
4305
4367
  ...challenge.accepts.filter(
4306
- (a) => a.scheme === "upto" && this.supportsNetwork(net, a.network) && typeof net.payUpto === "function" && net.describeAsset(a.asset) != null && typeof _optionalChain([a, 'access', _58 => _58.extra, 'optionalAccess', _59 => _59.facilitatorAddress]) === "string" && a.extra.facilitatorAddress.length > 0 && Number.isInteger(a.maxTimeoutSeconds) && a.maxTimeoutSeconds > 0
4368
+ (a) => a.scheme === "upto" && this.supportsNetwork(net, a.network) && typeof net.payUpto === "function" && a.asset !== "native" && // native is not upto-payable either (same reason as exact)
4369
+ net.describeAsset(a.asset) != null && typeof _optionalChain([a, 'access', _62 => _62.extra, 'optionalAccess', _63 => _63.facilitatorAddress]) === "string" && a.extra.facilitatorAddress.length > 0 && Number.isInteger(a.maxTimeoutSeconds) && a.maxTimeoutSeconds > 0
4307
4370
  )
4308
4371
  );
4309
4372
  }
@@ -4374,21 +4437,21 @@ var PipRailClient = (_class2 = class {
4374
4437
  if (isExact) {
4375
4438
  if (tokenKnown && bal.token < amount) {
4376
4439
  blockers.push("INSUFFICIENT_TOKEN");
4377
- shortfall.token = _chunkDCOUJZPLcjs.formatUnits.call(void 0, amount - bal.token, quote.decimals);
4440
+ shortfall.token = _chunk57V5DNJTcjs.formatUnits.call(void 0, amount - bal.token, quote.decimals);
4378
4441
  }
4379
4442
  } else if (isNative) {
4380
4443
  if (nativeKnown && bal.native < amount + fee) {
4381
4444
  blockers.push("INSUFFICIENT_TOKEN");
4382
- shortfall.token = _chunkDCOUJZPLcjs.formatUnits.call(void 0, amount + fee - bal.native, quote.decimals);
4445
+ shortfall.token = _chunk57V5DNJTcjs.formatUnits.call(void 0, amount + fee - bal.native, quote.decimals);
4383
4446
  }
4384
4447
  } else {
4385
4448
  if (tokenKnown && bal.token < amount) {
4386
4449
  blockers.push("INSUFFICIENT_TOKEN");
4387
- shortfall.token = _chunkDCOUJZPLcjs.formatUnits.call(void 0, amount - bal.token, quote.decimals);
4450
+ shortfall.token = _chunk57V5DNJTcjs.formatUnits.call(void 0, amount - bal.token, quote.decimals);
4388
4451
  }
4389
4452
  if (nativeKnown && bal.native < fee) {
4390
4453
  blockers.push("INSUFFICIENT_GAS");
4391
- shortfall.native = _chunkDCOUJZPLcjs.formatUnits.call(void 0, fee - bal.native, cost.feeDecimals);
4454
+ shortfall.native = _chunk57V5DNJTcjs.formatUnits.call(void 0, fee - bal.native, cost.feeDecimals);
4392
4455
  } else if (nativeKnown && fee > 0n && bal.native < fee * 3n / 2n) {
4393
4456
  warnings.push("THIN_GAS_MARGIN");
4394
4457
  }
@@ -4413,8 +4476,8 @@ var PipRailClient = (_class2 = class {
4413
4476
  blockers,
4414
4477
  warnings,
4415
4478
  balance: {
4416
- token: bal.token != null ? _chunkDCOUJZPLcjs.formatUnits.call(void 0, bal.token, quote.decimals) : null,
4417
- native: bal.native != null ? _chunkDCOUJZPLcjs.formatUnits.call(void 0, bal.native, cost.feeDecimals) : null
4479
+ token: bal.token != null ? _chunk57V5DNJTcjs.formatUnits.call(void 0, bal.token, quote.decimals) : null,
4480
+ native: bal.native != null ? _chunk57V5DNJTcjs.formatUnits.call(void 0, bal.native, cost.feeDecimals) : null
4418
4481
  },
4419
4482
  need: { token: quote.amountFormatted, native: cost.feeFormatted },
4420
4483
  ...shortfall.token || shortfall.native ? { shortfall } : {},
@@ -4425,30 +4488,30 @@ var PipRailClient = (_class2 = class {
4425
4488
  * driver's describeAsset) + the policy verdict + a symbol-mismatch flag. */
4426
4489
  buildQuote(net, accept, url, description) {
4427
4490
  if (typeof accept.amount !== "string" || !/^\d+$/.test(accept.amount)) {
4428
- throw new (0, _chunkDCOUJZPLcjs.InvalidEnvelopeError)(
4491
+ throw new (0, _chunk57V5DNJTcjs.InvalidEnvelopeError)(
4429
4492
  `challenge amount "${String(accept.amount)}" is not a base-unit integer string.`
4430
4493
  );
4431
4494
  }
4432
4495
  if (typeof accept.asset !== "string" || accept.asset.length === 0) {
4433
- throw new (0, _chunkDCOUJZPLcjs.InvalidEnvelopeError)(
4496
+ throw new (0, _chunk57V5DNJTcjs.InvalidEnvelopeError)(
4434
4497
  `challenge on ${accept.network} states no (string) asset \u2014 refusing to price it.`
4435
4498
  );
4436
4499
  }
4437
4500
  const amountBase = BigInt(accept.amount);
4438
4501
  const described = net.describeAsset(accept.asset);
4439
- const decimals = _nullishCoalesce(_optionalChain([described, 'optionalAccess', _60 => _60.decimals]), () => ( _optionalChain([accept, 'access', _61 => _61.extra, 'optionalAccess', _62 => _62.decimals])));
4502
+ const decimals = _nullishCoalesce(_optionalChain([described, 'optionalAccess', _64 => _64.decimals]), () => ( _optionalChain([accept, 'access', _65 => _65.extra, 'optionalAccess', _66 => _66.decimals])));
4440
4503
  if (typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0) {
4441
- throw new (0, _chunkDCOUJZPLcjs.InvalidEnvelopeError)(
4504
+ throw new (0, _chunk57V5DNJTcjs.InvalidEnvelopeError)(
4442
4505
  `challenge for ${accept.asset} on ${accept.network} states no valid decimals and the SDK doesn't recognise the token \u2014 refusing to price it.`
4443
4506
  );
4444
4507
  }
4445
- if (decimals > _chunkDCOUJZPLcjs.MAX_DECIMALS) {
4446
- throw new (0, _chunkDCOUJZPLcjs.InvalidEnvelopeError)(
4447
- `challenge for ${accept.asset} on ${accept.network} states ${decimals} decimals (> ${_chunkDCOUJZPLcjs.MAX_DECIMALS}) \u2014 refusing to price it (no real token is that deep).`
4508
+ if (decimals > _chunk57V5DNJTcjs.MAX_DECIMALS) {
4509
+ throw new (0, _chunk57V5DNJTcjs.InvalidEnvelopeError)(
4510
+ `challenge for ${accept.asset} on ${accept.network} states ${decimals} decimals (> ${_chunk57V5DNJTcjs.MAX_DECIMALS}) \u2014 refusing to price it (no real token is that deep).`
4448
4511
  );
4449
4512
  }
4450
- const symbol = _nullishCoalesce(_optionalChain([described, 'optionalAccess', _63 => _63.symbol]), () => ( _optionalChain([accept, 'access', _64 => _64.extra, 'optionalAccess', _65 => _65.symbol])));
4451
- const amountFormatted = _chunkDCOUJZPLcjs.formatUnits.call(void 0, amountBase, decimals);
4513
+ const symbol = _nullishCoalesce(_optionalChain([described, 'optionalAccess', _67 => _67.symbol]), () => ( _optionalChain([accept, 'access', _68 => _68.extra, 'optionalAccess', _69 => _69.symbol])));
4514
+ const amountFormatted = _chunk57V5DNJTcjs.formatUnits.call(void 0, amountBase, decimals);
4452
4515
  const intent = {
4453
4516
  host: hostOf2(url),
4454
4517
  chain: this.opts.chain,
@@ -4489,7 +4552,7 @@ var PipRailClient = (_class2 = class {
4489
4552
  this.ledger.totalFor(accept.network, accept.asset),
4490
4553
  ctx
4491
4554
  );
4492
- const serverSymbol = _optionalChain([accept, 'access', _66 => _66.extra, 'optionalAccess', _67 => _67.symbol]);
4555
+ const serverSymbol = _optionalChain([accept, 'access', _70 => _70.extra, 'optionalAccess', _71 => _71.symbol]);
4493
4556
  const symbolMismatch = intent.recognized && !!serverSymbol && !!symbol && serverSymbol.toUpperCase() !== symbol.toUpperCase();
4494
4557
  return {
4495
4558
  url,
@@ -4553,7 +4616,7 @@ var PipRailClient = (_class2 = class {
4553
4616
  ...opts.quote ? { quote: opts.quote } : {},
4554
4617
  budget: this.budget()
4555
4618
  });
4556
- throw new (0, _chunkDCOUJZPLcjs.PaymentDeclinedError)(reason, {
4619
+ throw new (0, _chunk57V5DNJTcjs.PaymentDeclinedError)(reason, {
4557
4620
  ...opts.reasonCode ? { reasonCode: opts.reasonCode } : {},
4558
4621
  ...opts.cause !== void 0 ? { cause: opts.cause } : {}
4559
4622
  });
@@ -4585,7 +4648,7 @@ var PipRailClient = (_class2 = class {
4585
4648
  const max = BigInt(quote.amount);
4586
4649
  const shown = claimed < max ? claimed : max;
4587
4650
  settledBase = shown.toString();
4588
- settledFormatted = _chunkDCOUJZPLcjs.formatUnits.call(void 0, shown, quote.decimals);
4651
+ settledFormatted = _chunk57V5DNJTcjs.formatUnits.call(void 0, shown, quote.decimals);
4589
4652
  } catch (e36) {
4590
4653
  }
4591
4654
  }
@@ -4621,7 +4684,7 @@ var PipRailClient = (_class2 = class {
4621
4684
  * `warnAtFraction` is set. Reads the just-computed {@link SessionBudget}; isolated (safeEmit).
4622
4685
  */
4623
4686
  emitThresholds(budget) {
4624
- const frac = _optionalChain([this, 'access', _68 => _68.opts, 'access', _69 => _69.policy, 'optionalAccess', _70 => _70.warnAtFraction]);
4687
+ const frac = _optionalChain([this, 'access', _72 => _72.opts, 'access', _73 => _73.policy, 'optionalAccess', _74 => _74.warnAtFraction]);
4625
4688
  if (frac === void 0) return;
4626
4689
  const fire = (scope, label, spentFormatted, capFormatted, fraction) => {
4627
4690
  if (fraction < frac) return;
@@ -4636,8 +4699,8 @@ var PipRailClient = (_class2 = class {
4636
4699
  fire(
4637
4700
  "asset",
4638
4701
  `${_nullishCoalesce(r.symbol, () => ( r.asset))} on ${r.network}`,
4639
- _chunkDCOUJZPLcjs.formatUnits.call(void 0, spent, r.decimals),
4640
- _chunkDCOUJZPLcjs.formatUnits.call(void 0, cap, r.decimals),
4702
+ _chunk57V5DNJTcjs.formatUnits.call(void 0, spent, r.decimals),
4703
+ _chunk57V5DNJTcjs.formatUnits.call(void 0, cap, r.decimals),
4641
4704
  fraction
4642
4705
  );
4643
4706
  }
@@ -4645,17 +4708,17 @@ var PipRailClient = (_class2 = class {
4645
4708
  fire("denom", d.denom, d.spentFormatted, d.capFormatted, d.fraction);
4646
4709
  }
4647
4710
  const policy = this.opts.policy;
4648
- if (_optionalChain([policy, 'optionalAccess', _71 => _71.windowTotal]) !== void 0 && policy.windowSeconds !== void 0) {
4711
+ if (_optionalChain([policy, 'optionalAccess', _75 => _75.windowTotal]) !== void 0 && policy.windowSeconds !== void 0) {
4649
4712
  const since = Date.now() - policy.windowSeconds * 1e3;
4650
4713
  for (const r of budget.byAsset) {
4651
- const cap = _chunkDCOUJZPLcjs.floorUnits.call(void 0, policy.windowTotal, r.decimals);
4714
+ const cap = _chunk57V5DNJTcjs.floorUnits.call(void 0, policy.windowTotal, r.decimals);
4652
4715
  const spent = this.ledger.totalSince(r.network, r.asset, since);
4653
4716
  const fraction = cap === 0n ? spent > 0n ? 1 : 0 : Number(spent * 1000000n / cap) / 1e6;
4654
4717
  fire(
4655
4718
  "window",
4656
4719
  `${_nullishCoalesce(r.symbol, () => ( r.asset))} on ${r.network}`,
4657
- _chunkDCOUJZPLcjs.formatUnits.call(void 0, spent, r.decimals),
4658
- _chunkDCOUJZPLcjs.formatUnits.call(void 0, cap, r.decimals),
4720
+ _chunk57V5DNJTcjs.formatUnits.call(void 0, spent, r.decimals),
4721
+ _chunk57V5DNJTcjs.formatUnits.call(void 0, cap, r.decimals),
4659
4722
  fraction
4660
4723
  );
4661
4724
  }
@@ -4676,14 +4739,14 @@ var PipRailClient = (_class2 = class {
4676
4739
  }
4677
4740
  async payAndConfirm(net, wallet, accept) {
4678
4741
  if (!this.supportsNetwork(net, accept.network)) {
4679
- throw new (0, _chunkDCOUJZPLcjs.WrongChainError)(
4742
+ throw new (0, _chunk57V5DNJTcjs.WrongChainError)(
4680
4743
  `Challenge expects ${accept.network} but client is on ${net.network}.`
4681
4744
  );
4682
4745
  }
4683
4746
  const ref = await net.send(wallet, accept);
4684
4747
  this.safeEmit({ kind: "payment-broadcast", ref });
4685
4748
  try {
4686
- const { height } = await net.confirm(ref, _nullishCoalesce(_optionalChain([accept, 'access', _72 => _72.extra, 'optionalAccess', _73 => _73.minConfirmations]), () => ( 1)));
4749
+ const { height } = await net.confirm(ref, _nullishCoalesce(_optionalChain([accept, 'access', _76 => _76.extra, 'optionalAccess', _77 => _77.minConfirmations]), () => ( 1)));
4687
4750
  this.safeEmit({
4688
4751
  kind: "payment-confirmed",
4689
4752
  ref,
@@ -4703,9 +4766,9 @@ var PipRailClient = (_class2 = class {
4703
4766
  const signature = {
4704
4767
  x402Version: 2,
4705
4768
  accepted: accept,
4706
- payload: { nonce: _optionalChain([accept, 'access', _74 => _74.extra, 'optionalAccess', _75 => _75.nonce]), txHash: ref }
4769
+ payload: { nonce: _optionalChain([accept, 'access', _78 => _78.extra, 'optionalAccess', _79 => _79.nonce]), txHash: ref }
4707
4770
  };
4708
- const headers = new Headers(_optionalChain([originalInit, 'optionalAccess', _76 => _76.headers]));
4771
+ const headers = new Headers(_optionalChain([originalInit, 'optionalAccess', _80 => _80.headers]));
4709
4772
  headers.set(HEADER_SIGNATURE, buildSignatureHeader(signature));
4710
4773
  let lastResponse = null;
4711
4774
  let lastReason = null;
@@ -4720,7 +4783,7 @@ var PipRailClient = (_class2 = class {
4720
4783
  () => timeoutController.abort(),
4721
4784
  this.retryTimeoutMs
4722
4785
  );
4723
- const signal = _optionalChain([originalInit, 'optionalAccess', _77 => _77.signal]) && typeof AbortSignal.any === "function" ? AbortSignal.any([timeoutController.signal, originalInit.signal]) : timeoutController.signal;
4786
+ const signal = _optionalChain([originalInit, 'optionalAccess', _81 => _81.signal]) && typeof AbortSignal.any === "function" ? AbortSignal.any([timeoutController.signal, originalInit.signal]) : timeoutController.signal;
4724
4787
  try {
4725
4788
  lastResponse = await fetch(url, {
4726
4789
  ..._nullishCoalesce(originalInit, () => ( {})),
@@ -4729,7 +4792,7 @@ var PipRailClient = (_class2 = class {
4729
4792
  });
4730
4793
  } catch (err) {
4731
4794
  if (timeoutController.signal.aborted) {
4732
- throw new (0, _chunkDCOUJZPLcjs.PaymentTimeoutError)(
4795
+ throw new (0, _chunk57V5DNJTcjs.PaymentTimeoutError)(
4733
4796
  `Server did not respond within ${this.retryTimeoutMs}ms after broadcasting payment ${ref}. Re-verify or re-submit ref=${ref} \u2014 do NOT re-pay.`,
4734
4797
  { cause: err, ref }
4735
4798
  );
@@ -4753,7 +4816,7 @@ var PipRailClient = (_class2 = class {
4753
4816
  reason: `server returned 402 after broadcasting payment ${ref}${unconfirmedNote} (${why})`,
4754
4817
  ...lastReason ? { code: lastReason.error, detail: lastReason.detail } : {}
4755
4818
  });
4756
- throw new (0, _chunkDCOUJZPLcjs.MaxRetriesExceededError)(
4819
+ throw new (0, _chunk57V5DNJTcjs.MaxRetriesExceededError)(
4757
4820
  `Server still returned 402 after ${attempts} attempt(s) with on-chain proof ref=${ref}${unconfirmedNote}. Last server rejection: ${why}. Re-verify or re-submit ref=${ref} before retrying \u2014 never re-pay (it would double-spend).`,
4758
4821
  { ref }
4759
4822
  );
@@ -4777,17 +4840,17 @@ var PipRailClient = (_class2 = class {
4777
4840
  */
4778
4841
  async payExactRail(net, wallet, accept, url, init, quote) {
4779
4842
  if (!net.payExact) {
4780
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
4843
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
4781
4844
  `the ${net.family} family can't pay a standard 'exact' rail (supported on EVM, Solana, Algorand, Aptos + NEAR today).`
4782
4845
  );
4783
4846
  }
4784
- throwIfAborted(_optionalChain([init, 'optionalAccess', _78 => _78.signal]));
4847
+ throwIfAborted(_optionalChain([init, 'optionalAccess', _82 => _82.signal]));
4785
4848
  const { payload, accepted, payerFrom, nonce } = await net.payExact(wallet, accept);
4786
- const headers = new Headers(_optionalChain([init, 'optionalAccess', _79 => _79.headers]));
4849
+ const headers = new Headers(_optionalChain([init, 'optionalAccess', _83 => _83.headers]));
4787
4850
  headers.set(HEADER_SIGNATURE, buildExactSignatureHeader({ accepted, payload }));
4788
4851
  const rejectDefinitive = (why2) => {
4789
4852
  this.safeEmit({ kind: "payment-failed", reason: `exact: facilitator rejected nonce=${nonce} (${why2})`, code: why2 });
4790
- throw new (0, _chunkDCOUJZPLcjs.MaxRetriesExceededError)(
4853
+ throw new (0, _chunk57V5DNJTcjs.MaxRetriesExceededError)(
4791
4854
  `exact: the facilitator rejected the payment (${why2}). Fix the cause, then re-present the SAME signed authorization (nonce=${nonce}) \u2014 do NOT re-sign a fresh nonce. ref=${nonce}.`,
4792
4855
  { ref: nonce }
4793
4856
  );
@@ -4800,17 +4863,17 @@ var PipRailClient = (_class2 = class {
4800
4863
  if (Date.now() >= deadline) break;
4801
4864
  await new Promise((r) => setTimeout(r, Math.min(2e3, 400 * 2 ** (attempt - 1))));
4802
4865
  }
4803
- throwIfAborted(_optionalChain([init, 'optionalAccess', _80 => _80.signal]));
4866
+ throwIfAborted(_optionalChain([init, 'optionalAccess', _84 => _84.signal]));
4804
4867
  const budget = Math.min(this.retryTimeoutMs, deadline - Date.now());
4805
4868
  if (budget <= 0) break;
4806
4869
  const timeoutController = new AbortController();
4807
4870
  const timeoutId = setTimeout(() => timeoutController.abort(), budget);
4808
- const signal = _optionalChain([init, 'optionalAccess', _81 => _81.signal]) && typeof AbortSignal.any === "function" ? AbortSignal.any([timeoutController.signal, init.signal]) : timeoutController.signal;
4871
+ const signal = _optionalChain([init, 'optionalAccess', _85 => _85.signal]) && typeof AbortSignal.any === "function" ? AbortSignal.any([timeoutController.signal, init.signal]) : timeoutController.signal;
4809
4872
  let response;
4810
4873
  try {
4811
4874
  response = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), headers, signal });
4812
4875
  } catch (err) {
4813
- throw new (0, _chunkDCOUJZPLcjs.PaymentTimeoutError)(
4876
+ throw new (0, _chunk57V5DNJTcjs.PaymentTimeoutError)(
4814
4877
  `exact: no response after submitting the authorization (nonce=${nonce}) to ${hostOf2(url)}. The facilitator may have already settled it \u2014 verify on-chain via ${exactSettleCheckHint(net.family, payerFrom, nonce)} before re-presenting the SAME signed authorization; do NOT re-pay.`,
4815
4878
  { cause: err, ref: nonce }
4816
4879
  );
@@ -4827,7 +4890,7 @@ var PipRailClient = (_class2 = class {
4827
4890
  const receipt = parseReceipt(response);
4828
4891
  this.captureReceipt(response, url);
4829
4892
  this.safeEmit({ kind: "payment-settled", receipt, ...settle ? { settle } : {} });
4830
- const ref = _optionalChain([settle, 'optionalAccess', _82 => _82.transaction]) || _optionalChain([receipt, 'optionalAccess', _83 => _83.transaction]) || `${net.family === "evm" ? "eip3009" : net.family}-nonce:${nonce}`;
4893
+ const ref = _optionalChain([settle, 'optionalAccess', _86 => _86.transaction]) || _optionalChain([receipt, 'optionalAccess', _87 => _87.transaction]) || `${net.family === "evm" ? "eip3009" : net.family}-nonce:${nonce}`;
4831
4894
  this.recordSpend(quote, ref);
4832
4895
  return response;
4833
4896
  }
@@ -4845,7 +4908,7 @@ var PipRailClient = (_class2 = class {
4845
4908
  reason: `exact: 402 after submitting authorization nonce=${nonce} (${why})`,
4846
4909
  ...lastReason ? { code: lastReason.error, detail: lastReason.detail } : {}
4847
4910
  });
4848
- throw new (0, _chunkDCOUJZPLcjs.MaxRetriesExceededError)(
4911
+ throw new (0, _chunk57V5DNJTcjs.MaxRetriesExceededError)(
4849
4912
  `exact: server still returned 402 after submitting the signed authorization (nonce=${nonce}). Last rejection: ${why}. Re-present the SAME authorization \u2014 do NOT re-sign a fresh nonce; verify on-chain via ${exactSettleCheckHint(net.family, payerFrom, nonce)} first. ref=${nonce}.`,
4850
4913
  { ref: nonce }
4851
4914
  );
@@ -4861,17 +4924,17 @@ var PipRailClient = (_class2 = class {
4861
4924
  */
4862
4925
  async payUptoRail(net, wallet, accept, url, init, quote) {
4863
4926
  if (!net.payUpto) {
4864
- throw new (0, _chunkDCOUJZPLcjs.UnsupportedSchemeError)(
4927
+ throw new (0, _chunk57V5DNJTcjs.UnsupportedSchemeError)(
4865
4928
  `the ${net.family} family can't pay a standard 'upto' rail (EVM-Permit2 only today).`
4866
4929
  );
4867
4930
  }
4868
- throwIfAborted(_optionalChain([init, 'optionalAccess', _84 => _84.signal]));
4931
+ throwIfAborted(_optionalChain([init, 'optionalAccess', _88 => _88.signal]));
4869
4932
  const { payload, accepted, payerFrom, nonce } = await net.payUpto(wallet, accept);
4870
- const headers = new Headers(_optionalChain([init, 'optionalAccess', _85 => _85.headers]));
4933
+ const headers = new Headers(_optionalChain([init, 'optionalAccess', _89 => _89.headers]));
4871
4934
  headers.set(HEADER_SIGNATURE, buildUptoSignatureHeader({ accepted, payload }));
4872
4935
  const rejectDefinitive = (why2) => {
4873
4936
  this.safeEmit({ kind: "payment-failed", reason: `upto: facilitator rejected nonce=${nonce} (${why2})`, code: why2 });
4874
- throw new (0, _chunkDCOUJZPLcjs.MaxRetriesExceededError)(
4937
+ throw new (0, _chunk57V5DNJTcjs.MaxRetriesExceededError)(
4875
4938
  `upto: the server rejected the payment (${why2}). Fix the cause, then re-present the SAME signed authorization (nonce=${nonce}) \u2014 do NOT re-sign a fresh nonce. ref=${nonce}.`,
4876
4939
  { ref: nonce }
4877
4940
  );
@@ -4884,17 +4947,17 @@ var PipRailClient = (_class2 = class {
4884
4947
  if (Date.now() >= deadline) break;
4885
4948
  await new Promise((r) => setTimeout(r, Math.min(2e3, 400 * 2 ** (attempt - 1))));
4886
4949
  }
4887
- throwIfAborted(_optionalChain([init, 'optionalAccess', _86 => _86.signal]));
4950
+ throwIfAborted(_optionalChain([init, 'optionalAccess', _90 => _90.signal]));
4888
4951
  const budget = Math.min(this.retryTimeoutMs, deadline - Date.now());
4889
4952
  if (budget <= 0) break;
4890
4953
  const timeoutController = new AbortController();
4891
4954
  const timeoutId = setTimeout(() => timeoutController.abort(), budget);
4892
- const signal = _optionalChain([init, 'optionalAccess', _87 => _87.signal]) && typeof AbortSignal.any === "function" ? AbortSignal.any([timeoutController.signal, init.signal]) : timeoutController.signal;
4955
+ const signal = _optionalChain([init, 'optionalAccess', _91 => _91.signal]) && typeof AbortSignal.any === "function" ? AbortSignal.any([timeoutController.signal, init.signal]) : timeoutController.signal;
4893
4956
  let response;
4894
4957
  try {
4895
4958
  response = await fetch(url, { ..._nullishCoalesce(init, () => ( {})), headers, signal });
4896
4959
  } catch (err) {
4897
- throw new (0, _chunkDCOUJZPLcjs.PaymentTimeoutError)(
4960
+ throw new (0, _chunk57V5DNJTcjs.PaymentTimeoutError)(
4898
4961
  `upto: no response after submitting the authorization (nonce=${nonce}) to ${hostOf2(url)}. The merchant may have already settled it \u2014 verify on-chain before re-presenting; do NOT re-pay.`,
4899
4962
  { cause: err, ref: nonce }
4900
4963
  );
@@ -4911,8 +4974,8 @@ var PipRailClient = (_class2 = class {
4911
4974
  const receipt = parseReceipt(response);
4912
4975
  this.captureReceipt(response, url);
4913
4976
  this.safeEmit({ kind: "payment-settled", receipt, ...settle ? { settle } : {} });
4914
- const ref = _optionalChain([settle, 'optionalAccess', _88 => _88.transaction]) || _optionalChain([receipt, 'optionalAccess', _89 => _89.transaction]) || `upto-nonce:${nonce}`;
4915
- const settledAmount = _nullishCoalesce(_optionalChain([settle, 'optionalAccess', _90 => _90.amount]), () => ( _optionalChain([receipt, 'optionalAccess', _91 => _91.amount])));
4977
+ const ref = _optionalChain([settle, 'optionalAccess', _92 => _92.transaction]) || _optionalChain([receipt, 'optionalAccess', _93 => _93.transaction]) || `upto-nonce:${nonce}`;
4978
+ const settledAmount = _nullishCoalesce(_optionalChain([settle, 'optionalAccess', _94 => _94.amount]), () => ( _optionalChain([receipt, 'optionalAccess', _95 => _95.amount])));
4916
4979
  this.recordSpend(quote, ref, settledAmount);
4917
4980
  return response;
4918
4981
  }
@@ -4930,14 +4993,14 @@ var PipRailClient = (_class2 = class {
4930
4993
  reason: `upto: 402 after submitting authorization nonce=${nonce} (${why})`,
4931
4994
  ...lastReason ? { code: lastReason.error, detail: lastReason.detail } : {}
4932
4995
  });
4933
- throw new (0, _chunkDCOUJZPLcjs.MaxRetriesExceededError)(
4996
+ throw new (0, _chunk57V5DNJTcjs.MaxRetriesExceededError)(
4934
4997
  `upto: server still returned 402 after submitting the signed authorization (nonce=${nonce}). Last rejection: ${why}. Re-present the SAME authorization \u2014 do NOT re-sign a fresh nonce. ref=${nonce}.`,
4935
4998
  { ref: nonce }
4936
4999
  );
4937
5000
  }
4938
5001
  }, _class2);
4939
5002
  function throwIfAborted(signal) {
4940
- if (_optionalChain([signal, 'optionalAccess', _92 => _92.aborted])) {
5003
+ if (_optionalChain([signal, 'optionalAccess', _96 => _96.aborted])) {
4941
5004
  throw _nullishCoalesce(signal.reason, () => ( new DOMException("This operation was aborted.", "AbortError")));
4942
5005
  }
4943
5006
  }
@@ -5007,10 +5070,10 @@ function buildFundingHint(options, chainLabel) {
5007
5070
  return `Couldn't fully read your wallet on ${chainLabel} (RPC throttled) \u2014 retry; you may already be able to pay ${target.quote.amountFormatted} ${sym}.`;
5008
5071
  }
5009
5072
  const parts = [];
5010
- if (target.blockers.includes("INSUFFICIENT_TOKEN") && _optionalChain([target, 'access', _93 => _93.shortfall, 'optionalAccess', _94 => _94.token])) {
5073
+ if (target.blockers.includes("INSUFFICIENT_TOKEN") && _optionalChain([target, 'access', _97 => _97.shortfall, 'optionalAccess', _98 => _98.token])) {
5011
5074
  parts.push(`top up ${target.shortfall.token} ${sym}`);
5012
5075
  }
5013
- if (target.blockers.includes("INSUFFICIENT_GAS") && _optionalChain([target, 'access', _95 => _95.shortfall, 'optionalAccess', _96 => _96.native])) {
5076
+ if (target.blockers.includes("INSUFFICIENT_GAS") && _optionalChain([target, 'access', _99 => _99.shortfall, 'optionalAccess', _100 => _100.native])) {
5014
5077
  parts.push(`add ~${target.shortfall.native} ${target.cost.feeSymbol} for gas`);
5015
5078
  }
5016
5079
  return parts.length ? `Can't settle on ${chainLabel}: ${parts.join(" and ")} (to pay ${target.quote.amountFormatted} ${sym}).` : `Can't settle on ${chainLabel} for ${target.quote.amountFormatted} ${sym}.`;
@@ -5024,7 +5087,7 @@ async function planAcross(clients, url, init) {
5024
5087
  const status = best ? "ready" : options.some((o) => o.state === "unknown") ? "unknown" : "blocked";
5025
5088
  return {
5026
5089
  url,
5027
- network: _nullishCoalesce(_optionalChain([best, 'optionalAccess', _97 => _97.accept, 'access', _98 => _98.network]), () => ( live[0].network)),
5090
+ network: _nullishCoalesce(_optionalChain([best, 'optionalAccess', _101 => _101.accept, 'access', _102 => _102.network]), () => ( live[0].network)),
5028
5091
  status,
5029
5092
  payable: best !== null,
5030
5093
  best,
@@ -5043,7 +5106,7 @@ async function fetchAcross(clients, url, init) {
5043
5106
  const best = rankAcross(live.map((p) => p.plan)).find((o) => o.state === "payable");
5044
5107
  if (!best) {
5045
5108
  const hint = mergeDeclineHint(live.map((p) => p.plan));
5046
- throw new (0, _chunkDCOUJZPLcjs.PaymentDeclinedError)(hint || "No funded chain can settle this payment right now.");
5109
+ throw new (0, _chunk57V5DNJTcjs.PaymentDeclinedError)(hint || "No funded chain can settle this payment right now.");
5047
5110
  }
5048
5111
  const owner = live.find((p) => p.plan.options.includes(best)).client;
5049
5112
  return owner.fetch(url, { ..._nullishCoalesce(init, () => ( {})), autoRoute: true });
@@ -5089,8 +5152,8 @@ function isReplayableBodyInit(value) {
5089
5152
  async function readInvalidReason(response) {
5090
5153
  try {
5091
5154
  const body = await response.clone().json();
5092
- const ext = _optionalChain([body, 'optionalAccess', _99 => _99.extensions]);
5093
- const piprail = _optionalChain([ext, 'optionalAccess', _100 => _100.piprail]);
5155
+ const ext = _optionalChain([body, 'optionalAccess', _103 => _103.extensions]);
5156
+ const piprail = _optionalChain([ext, 'optionalAccess', _104 => _104.piprail]);
5094
5157
  if (piprail && typeof piprail.code === "string") {
5095
5158
  return {
5096
5159
  error: piprail.code,
@@ -5112,7 +5175,7 @@ async function readInvalidReason(response) {
5112
5175
  } catch (e40) {
5113
5176
  }
5114
5177
  const settle = parseSettleResponse(response);
5115
- if (_optionalChain([settle, 'optionalAccess', _101 => _101.errorReason])) return { error: settle.errorReason, detail: "" };
5178
+ if (_optionalChain([settle, 'optionalAccess', _105 => _105.errorReason])) return { error: settle.errorReason, detail: "" };
5116
5179
  return null;
5117
5180
  }
5118
5181
  var EVM_PRESET_FOR_CHAINID = {
@@ -5210,7 +5273,7 @@ var MultiChainPayer = class _MultiChainPayer {
5210
5273
  ledger,
5211
5274
  ...opts.policy ? { policy: opts.policy } : {},
5212
5275
  ...opts.schemes ? { schemes: opts.schemes } : {},
5213
- ..._optionalChain([opts, 'access', _102 => _102.rpcUrls, 'optionalAccess', _103 => _103[chain]]) ? { rpcUrl: opts.rpcUrls[chain] } : {},
5276
+ ..._optionalChain([opts, 'access', _106 => _106.rpcUrls, 'optionalAccess', _107 => _107[chain]]) ? { rpcUrl: opts.rpcUrls[chain] } : {},
5214
5277
  ...opts.onBeforePay ? { onBeforePay: opts.onBeforePay } : {},
5215
5278
  ...opts.onEvent ? { onEvent: opts.onEvent } : {},
5216
5279
  ...opts.maxPaymentRetries != null ? { maxPaymentRetries: opts.maxPaymentRetries } : {},
@@ -5268,7 +5331,7 @@ var MultiChainPayer = class _MultiChainPayer {
5268
5331
  * {@link PipRailClient.post}.
5269
5332
  */
5270
5333
  post(url, body, init) {
5271
- const headers = new Headers(_optionalChain([init, 'optionalAccess', _104 => _104.headers]));
5334
+ const headers = new Headers(_optionalChain([init, 'optionalAccess', _108 => _108.headers]));
5272
5335
  let payload;
5273
5336
  if (body === void 0 || body === null) {
5274
5337
  payload = void 0;
@@ -5418,14 +5481,14 @@ function buildSelfDescription(input) {
5418
5481
  }
5419
5482
  function buildEndpointInfo(input) {
5420
5483
  const d = input.descriptor;
5421
- const summary = _nullishCoalesce(_optionalChain([d, 'optionalAccess', _105 => _105.summary]), () => ( input.description));
5422
- const hasInput = _optionalChain([d, 'optionalAccess', _106 => _106.queryParams]) && Object.keys(d.queryParams).length > 0;
5484
+ const summary = _nullishCoalesce(_optionalChain([d, 'optionalAccess', _109 => _109.summary]), () => ( input.description));
5485
+ const hasInput = _optionalChain([d, 'optionalAccess', _110 => _110.queryParams]) && Object.keys(d.queryParams).length > 0;
5423
5486
  const endpoint = {
5424
5487
  ...summary ? { summary } : {},
5425
- ..._optionalChain([d, 'optionalAccess', _107 => _107.method]) ? { method: d.method.toUpperCase() } : {},
5488
+ ..._optionalChain([d, 'optionalAccess', _111 => _111.method]) ? { method: d.method.toUpperCase() } : {},
5426
5489
  ...input.mimeType ? { mimeType: input.mimeType } : {},
5427
5490
  ...hasInput ? { input: d.queryParams } : {},
5428
- ..._optionalChain([d, 'optionalAccess', _108 => _108.output]) ? { output: d.output } : {}
5491
+ ..._optionalChain([d, 'optionalAccess', _112 => _112.output]) ? { output: d.output } : {}
5429
5492
  };
5430
5493
  return Object.keys(endpoint).length > 0 ? endpoint : void 0;
5431
5494
  }
@@ -5443,7 +5506,7 @@ function summarizePlan(plan) {
5443
5506
  return `NOT payable: ${_nullishCoalesce(plan.fundingHint, () => ( `no settleable rail on ${plan.network}`))}`;
5444
5507
  }
5445
5508
  function explainDecline(err) {
5446
- if (!(err instanceof _chunkDCOUJZPLcjs.PipRailError)) {
5509
+ if (!(err instanceof _chunk57V5DNJTcjs.PipRailError)) {
5447
5510
  return `Payment failed: ${err instanceof Error ? err.message : String(err)}`;
5448
5511
  }
5449
5512
  switch (err.code) {
@@ -5474,14 +5537,15 @@ function formatSpendReport(summary) {
5474
5537
  return `${perAsset} \u2014 grand total: ${grand}`;
5475
5538
  }
5476
5539
  function describeChallenge(challenge) {
5477
- const first = challenge.accepts[0];
5540
+ const accepts = Array.isArray(_optionalChain([challenge, 'optionalAccess', _113 => _113.accepts])) ? challenge.accepts : [];
5541
+ const first = accepts[0];
5478
5542
  if (!first) {
5479
5543
  return `${BRAND.name} x402 payment endpoint. Pay with @piprail/sdk (${BRAND.sdkInstall}). Docs: ${BRAND.home}.`;
5480
5544
  }
5481
5545
  const extra = _nullishCoalesce(first.extra, () => ( {}));
5482
5546
  const amount = _nullishCoalesce(extra.amountFormatted, () => ( first.amount));
5483
5547
  const token = _nullishCoalesce(extra.symbol, () => ( first.asset));
5484
- const hasExact = challenge.accepts.some((a) => a.scheme === "exact");
5548
+ const hasExact = accepts.some((a) => a.scheme === "exact");
5485
5549
  const standard = hasExact ? "; or any standard x402 client (an exact rail is offered)" : "";
5486
5550
  return `${BRAND.name} x402 payment endpoint \u2014 pay ${amount} ${token} on ${first.network} to ${first.payTo}. Programmatic: ${BRAND.sdkInstall} then client.fetch(url)${standard}. Docs: ${BRAND.home}.`;
5487
5551
  }
@@ -5517,8 +5581,8 @@ A 402 may offer up to three rails; you don't choose per payment \u2014 the clien
5517
5581
  (the native coin \u2014 ETH/SOL/\u2026). Works on every chain.
5518
5582
  - exact (the ratified x402 rail, opt-in): you only SIGN; the server \u2014 or a facilitator it chose
5519
5583
  (e.g. PayAI) \u2014 broadcasts it, so you pay ZERO gas (you need only the token, no native coin). It
5520
- works on EVM, Solana + Algorand, and the on-chain method (EIP-3009 / Permit2 / SVM / Algorand
5521
- fee-pooled group) is picked automatically.
5584
+ works on EVM, Solana, Algorand, Aptos + NEAR, and the on-chain method (EIP-3009 / Permit2 / SVM /
5585
+ Algorand fee-pooled group / Aptos fee-payer / NEAR SignedDelegateAction) is picked automatically.
5522
5586
  - upto (the metered/variable x402 rail, opt-in, EVM): the amount you see is a MAXIMUM \u2014 you sign
5523
5587
  a ceiling, the server meters real usage and settles the ACTUAL (<= the max). BUDGET AGAINST THE MAX:
5524
5588
  the plan/policy treat the ceiling as the spend (a server may charge up to it), so a payable plan
@@ -5595,14 +5659,14 @@ async function readBody(res) {
5595
5659
  }
5596
5660
  }
5597
5661
  function toToolError(err) {
5598
- if (!(err instanceof _chunkDCOUJZPLcjs.PipRailError)) throw err;
5662
+ if (!(err instanceof _chunk57V5DNJTcjs.PipRailError)) throw err;
5599
5663
  const out = {
5600
5664
  ok: false,
5601
5665
  code: err.code,
5602
5666
  reason: err.message,
5603
5667
  explain: explainDecline(err)
5604
5668
  };
5605
- if (err instanceof _chunkDCOUJZPLcjs.PaymentDeclinedError) {
5669
+ if (err instanceof _chunk57V5DNJTcjs.PaymentDeclinedError) {
5606
5670
  out.declined = true;
5607
5671
  if (err.reasonCode) out.reasonCode = err.reasonCode;
5608
5672
  }
@@ -5818,14 +5882,14 @@ function paymentTools(client) {
5818
5882
  ...verifiable ? { verifiableReceipt: { ...verifiable, resource: { url } } } : {}
5819
5883
  };
5820
5884
  } catch (err) {
5821
- if (err instanceof _chunkDCOUJZPLcjs.PipRailError) {
5885
+ if (err instanceof _chunk57V5DNJTcjs.PipRailError) {
5822
5886
  const out = {
5823
5887
  ok: false,
5824
5888
  code: err.code,
5825
5889
  reason: err.message,
5826
5890
  explain: explainDecline(err)
5827
5891
  };
5828
- if (err instanceof _chunkDCOUJZPLcjs.PaymentDeclinedError) {
5892
+ if (err instanceof _chunk57V5DNJTcjs.PaymentDeclinedError) {
5829
5893
  out.declined = true;
5830
5894
  if (err.reasonCode) out.reasonCode = err.reasonCode;
5831
5895
  }
@@ -5973,12 +6037,14 @@ function paymentTools(client) {
5973
6037
 
5974
6038
  // src/classify.ts
5975
6039
  function classifyChallenge(challenge, opts) {
5976
- const accepts = _nullishCoalesce(challenge.accepts, () => ( []));
6040
+ const accepts = Array.isArray(_optionalChain([challenge, 'optionalAccess', _114 => _114.accepts])) ? challenge.accepts : [];
6041
+ const network = _optionalChain([opts, 'optionalAccess', _115 => _115.network]);
6042
+ const schemes = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _116 => _116.schemes]), () => ( []));
5977
6043
  const offeredSchemes = [...new Set(accepts.map((a) => a.scheme))];
5978
6044
  const offeredNetworks = [...new Set(accepts.map((a) => a.network))];
5979
- const onClientChain = accepts.some((a) => a.network === opts.network);
6045
+ const onClientChain = accepts.some((a) => a.network === network);
5980
6046
  const payableScheme = accepts.some(
5981
- (a) => a.network === opts.network && opts.schemes.includes(a.scheme)
6047
+ (a) => a.network === network && schemes.includes(a.scheme)
5982
6048
  );
5983
6049
  const verdict = accepts.length === 0 ? "NO_RAIL" : payableScheme ? "PAYABLE_RAIL" : onClientChain ? "UNPAYABLE_SCHEME" : "WRONG_CHAIN";
5984
6050
  return { onClientChain, payableScheme, offeredSchemes, offeredNetworks, verdict };
@@ -6063,6 +6129,29 @@ function buildWellKnownX402(input) {
6063
6129
  ...input.ownershipProofs && input.ownershipProofs.length > 0 ? { ownershipProofs: input.ownershipProofs } : {}
6064
6130
  };
6065
6131
  }
6132
+ function buildWellKnownX402Manifest(input) {
6133
+ if (!Array.isArray(_optionalChain([input, 'optionalAccess', _117 => _117.resources]))) {
6134
+ throw new (0, _chunk57V5DNJTcjs.InvalidConfigError)(
6135
+ "buildWellKnownX402Manifest: `resources` must be an array of ResourceDescription."
6136
+ );
6137
+ }
6138
+ const lastUpdated = typeof input.lastUpdated === "number" && Number.isFinite(input.lastUpdated) ? input.lastUpdated : Math.floor(Date.now() / 1e3);
6139
+ return {
6140
+ x402Version: 2,
6141
+ lastUpdated,
6142
+ items: input.resources.map((r) => ({
6143
+ resource: {
6144
+ url: r.url,
6145
+ ...r.description ? { description: r.description } : {},
6146
+ ...r.mimeType ? { mimeType: r.mimeType } : {}
6147
+ },
6148
+ type: "http",
6149
+ accepts: r.accepts,
6150
+ input: { method: (_nullishCoalesce(r.method, () => ( "GET"))).toUpperCase() },
6151
+ ...r.mimeType ? { output: { mimeType: r.mimeType } } : {}
6152
+ }))
6153
+ };
6154
+ }
6066
6155
  function buildX402DnsTxt(input) {
6067
6156
  const descriptor = input.descriptor ? `descriptor=${input.descriptor};` : "";
6068
6157
  return {
@@ -6132,10 +6221,10 @@ async function fetchFacilitatorFeePayer(url, network, timeoutMs = 8e3) {
6132
6221
  const res = await fetch(`${base2}/supported`, { signal: ctrl.signal });
6133
6222
  if (!res.ok) return void 0;
6134
6223
  const body = await res.json();
6135
- const kinds = Array.isArray(_optionalChain([body, 'optionalAccess', _109 => _109.kinds])) ? body.kinds : [];
6224
+ const kinds = Array.isArray(_optionalChain([body, 'optionalAccess', _118 => _118.kinds])) ? body.kinds : [];
6136
6225
  const want = normalizeNetwork(network);
6137
- const kind = kinds.find((k) => _optionalChain([k, 'optionalAccess', _110 => _110.scheme]) === "exact" && normalizeNetwork(String(_nullishCoalesce(_optionalChain([k, 'optionalAccess', _111 => _111.network]), () => ( "")))) === want);
6138
- const fp = _optionalChain([kind, 'optionalAccess', _112 => _112.extra, 'optionalAccess', _113 => _113.feePayer]);
6226
+ const kind = kinds.find((k) => _optionalChain([k, 'optionalAccess', _119 => _119.scheme]) === "exact" && normalizeNetwork(String(_nullishCoalesce(_optionalChain([k, 'optionalAccess', _120 => _120.network]), () => ( "")))) === want);
6227
+ const fp = _optionalChain([kind, 'optionalAccess', _121 => _121.extra, 'optionalAccess', _122 => _122.feePayer]);
6139
6228
  return typeof fp === "string" ? fp : void 0;
6140
6229
  } catch (e43) {
6141
6230
  return void 0;
@@ -6144,16 +6233,16 @@ async function fetchFacilitatorFeePayer(url, network, timeoutMs = 8e3) {
6144
6233
  }
6145
6234
  }
6146
6235
  function parseFacilitatorSupported(body) {
6147
- const kinds = _optionalChain([body, 'optionalAccess', _114 => _114.kinds]);
6236
+ const kinds = _optionalChain([body, 'optionalAccess', _123 => _123.kinds]);
6148
6237
  if (!Array.isArray(kinds)) return [];
6149
6238
  const out = [];
6150
6239
  for (const k of kinds) {
6151
6240
  if (!k || typeof k !== "object") continue;
6152
6241
  const o = k;
6153
6242
  if (typeof o.scheme !== "string" || typeof o.network !== "string") continue;
6154
- const fp = _optionalChain([o, 'access', _115 => _115.extra, 'optionalAccess', _116 => _116.feePayer]);
6243
+ const fp = _optionalChain([o, 'access', _124 => _124.extra, 'optionalAccess', _125 => _125.feePayer]);
6155
6244
  const ver = o.x402Version;
6156
- const method = _optionalChain([o, 'access', _117 => _117.extra, 'optionalAccess', _118 => _118.assetTransferMethod]);
6245
+ const method = _optionalChain([o, 'access', _126 => _126.extra, 'optionalAccess', _127 => _127.assetTransferMethod]);
6157
6246
  out.push({
6158
6247
  scheme: o.scheme,
6159
6248
  network: o.network,
@@ -6217,13 +6306,13 @@ async function settleViaFacilitator(input) {
6217
6306
  try {
6218
6307
  verify = await post(`${base2}/verify`, body, auth);
6219
6308
  } catch (err) {
6220
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
6309
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
6221
6310
  `exact settle (facilitator ${base2}): /verify request failed (${err instanceof Error ? err.message : String(err)}).`,
6222
6311
  { cause: err }
6223
6312
  );
6224
6313
  }
6225
6314
  if (verify.status !== 200) {
6226
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
6315
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
6227
6316
  `exact settle (facilitator ${base2}): /verify returned HTTP ${verify.status} (transport/auth error).`
6228
6317
  );
6229
6318
  }
@@ -6239,13 +6328,13 @@ async function settleViaFacilitator(input) {
6239
6328
  try {
6240
6329
  settle = await post(`${base2}/settle`, body, auth);
6241
6330
  } catch (err) {
6242
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
6331
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
6243
6332
  `exact settle (facilitator ${base2}): /settle request failed (${err instanceof Error ? err.message : String(err)}).`,
6244
6333
  { cause: err }
6245
6334
  );
6246
6335
  }
6247
6336
  if (settle.status !== 200) {
6248
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
6337
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
6249
6338
  `exact settle (facilitator ${base2}): /settle returned HTTP ${settle.status} (transport/auth error).`
6250
6339
  );
6251
6340
  }
@@ -6655,13 +6744,13 @@ function createPaymentGate(options) {
6655
6744
  const net = await resolveNetwork2({ chain: a.chain, rpcUrl: _nullishCoalesce(a.rpcUrl, () => ( options.rpcUrl)) });
6656
6745
  const payTo = _nullishCoalesce(a.payTo, () => ( options.payTo));
6657
6746
  if (!payTo) {
6658
- throw new Error(
6747
+ throw new (0, _chunk57V5DNJTcjs.InvalidConfigError)(
6659
6748
  `requirePayment: no payTo for chain ${net.network}. Set it on the accept entry or pass a top-level payTo.`
6660
6749
  );
6661
6750
  }
6662
6751
  net.assertValidPayTo(payTo);
6663
6752
  const { asset, decimals, symbol } = net.resolveToken(a.token);
6664
- const amountBase = _chunkDCOUJZPLcjs.parseUnits.call(void 0, a.amount, decimals);
6753
+ const amountBase = _chunk57V5DNJTcjs.parseUnits.call(void 0, a.amount, decimals);
6665
6754
  const spec = { net, asset, decimals, symbol, amountBase, amountFormatted: a.amount, payTo };
6666
6755
  if (exactOption) {
6667
6756
  const outcome = await resolveExactRail(net, asset);
@@ -6684,7 +6773,7 @@ function createPaymentGate(options) {
6684
6773
  if (exactOption && !specs.some((s) => s.exact)) {
6685
6774
  const why = exactSkips.length > 0 ? exactSkips.join(" ") : "The standard `exact` rail is EVM ERC-20 (EIP-3009 \u2014 USDC / EURC \u2014 or Permit2, e.g. Binance-Peg USDC on BNB) or a Solana SPL token (SVM) \u2014 NOT native coins, NOT families without a standard `exact` scheme.";
6686
6775
  if (exactOption.settle === "keyless") {
6687
- if (typeof process === "undefined" || !_optionalChain([process, 'optionalAccess', _119 => _119.env, 'optionalAccess', _120 => _120.PIPRAIL_NO_HINTS])) {
6776
+ if (typeof process === "undefined" || !_optionalChain([process, 'optionalAccess', _128 => _128.env, 'optionalAccess', _129 => _129.PIPRAIL_NO_HINTS])) {
6688
6777
  console.warn(
6689
6778
  `[piprail] exact: true \u2014 no offered chain has a gasless \`exact\` rail available, so this gate serves ONCHAIN-PROOF ONLY (buyers PAY GAS \u2014 the fallback when no facilitator can sponsor). ${why} To be gasless: pin \`exact: { settle: { facilitator } }\` or self-settle \`exact: { settle: 'self', relayer }\`. (Suppress with PIPRAIL_NO_HINTS=1.)`
6690
6779
  );
@@ -6712,7 +6801,7 @@ function createPaymentGate(options) {
6712
6801
  skipReason: `${net.network}: \`exact: true\` found no known keyless facilitator for this network. Pass \`exact: { settle: { facilitator } }\`, \`exact: { settle: 'self', relayer }\`, or see the coverage map (KNOWN_FACILITATORS / docs.piprail.com).`
6713
6802
  };
6714
6803
  }
6715
- if (typeof process === "undefined" || _optionalChain([process, 'optionalAccess', _121 => _121.env, 'optionalAccess', _122 => _122.NODE_ENV]) !== "production" && !_optionalChain([process, 'optionalAccess', _123 => _123.env, 'optionalAccess', _124 => _124.PIPRAIL_NO_HINTS])) {
6804
+ if (typeof process === "undefined" || _optionalChain([process, 'optionalAccess', _130 => _130.env, 'optionalAccess', _131 => _131.NODE_ENV]) !== "production" && !_optionalChain([process, 'optionalAccess', _132 => _132.env, 'optionalAccess', _133 => _133.PIPRAIL_NO_HINTS])) {
6716
6805
  console.warn(
6717
6806
  `[piprail] exact: keyless rail on ${net.network} auto-settles via ${picked.url} (zero-config; pin \`exact.settle.facilitator\` in production).`
6718
6807
  );
@@ -6793,7 +6882,7 @@ function createPaymentGate(options) {
6793
6882
  if (hasCustomStore) {
6794
6883
  return options.isUsed ? Boolean(await options.isUsed(ref)) : false;
6795
6884
  }
6796
- const key = ref.toLowerCase();
6885
+ const key = ref.startsWith("pid:") ? ref : ref.toLowerCase();
6797
6886
  const now = Date.now();
6798
6887
  pruneUsed(now);
6799
6888
  if (localUsed.has(key)) return true;
@@ -6805,7 +6894,7 @@ function createPaymentGate(options) {
6805
6894
  if (ok && options.markUsed) await options.markUsed(ref);
6806
6895
  return;
6807
6896
  }
6808
- if (!ok) localUsed.delete(ref.toLowerCase());
6897
+ if (!ok) localUsed.delete(ref.startsWith("pid:") ? ref : ref.toLowerCase());
6809
6898
  }
6810
6899
  function buildAccept(s, nonce) {
6811
6900
  return {
@@ -6856,7 +6945,7 @@ function createPaymentGate(options) {
6856
6945
  extra: {
6857
6946
  assetTransferMethod: "permit2-upto",
6858
6947
  // facilitatorAddress comes from rail.extra; the spread below carries it (+ name/version).
6859
- facilitatorAddress: _nullishCoalesce(_optionalChain([rail, 'access', _125 => _125.extra, 'optionalAccess', _126 => _126.facilitatorAddress]), () => ( "")),
6948
+ facilitatorAddress: _nullishCoalesce(_optionalChain([rail, 'access', _134 => _134.extra, 'optionalAccess', _135 => _135.facilitatorAddress]), () => ( "")),
6860
6949
  minConfirmations,
6861
6950
  decimals: s.decimals,
6862
6951
  amountFormatted: s.amountFormatted,
@@ -6878,6 +6967,7 @@ function createPaymentGate(options) {
6878
6967
  const specs = await ready();
6879
6968
  const nonce = genNonce();
6880
6969
  const bazaar = options.discovery ? { bazaar: buildBazaarExtension(options.discovery === true ? {} : options.discovery) } : void 0;
6970
+ const paymentIdAd = options.paymentIdentifier ? buildPaymentIdentifierAdvertisement() : void 0;
6881
6971
  const accepts = buildAccepts(specs, nonce);
6882
6972
  const endpointInfo = buildEndpointInfo({
6883
6973
  ...options.description ? { description: options.description } : {},
@@ -6890,16 +6980,18 @@ function createPaymentGate(options) {
6890
6980
  ...endpointInfo ? { endpoint: endpointInfo } : {},
6891
6981
  ...receiptsOn ? { verifiableReceipts: true } : {}
6892
6982
  });
6893
- const rejectionExt = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _127 => _127.extensions]), () => ( {}));
6983
+ const rejectionExt = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _136 => _136.extensions]), () => ( {}));
6894
6984
  const rejectionPiprail = _nullishCoalesce(rejectionExt.piprail, () => ( {}));
6895
6985
  const bodyPiprail = { ..._nullishCoalesce(selfDescribe, () => ( {})), ...rejectionPiprail };
6896
6986
  const bodyExtensions = {
6897
6987
  ...bazaar,
6988
+ ...paymentIdAd,
6898
6989
  ...rejectionExt,
6899
6990
  ...Object.keys(bodyPiprail).length > 0 ? { piprail: bodyPiprail } : {}
6900
6991
  };
6901
6992
  const headerExtensions = {
6902
6993
  ...bazaar,
6994
+ ...paymentIdAd,
6903
6995
  ...Object.keys(rejectionPiprail).length > 0 ? { piprail: rejectionPiprail } : {}
6904
6996
  };
6905
6997
  const challenge2 = {
@@ -6910,7 +7002,7 @@ function createPaymentGate(options) {
6910
7002
  ...options.mimeType ? { mimeType: options.mimeType } : {}
6911
7003
  },
6912
7004
  accepts,
6913
- ..._optionalChain([opts, 'optionalAccess', _128 => _128.error]) ? { error: opts.error } : {},
7005
+ ..._optionalChain([opts, 'optionalAccess', _137 => _137.error]) ? { error: opts.error } : {},
6914
7006
  ...Object.keys(bodyExtensions).length > 0 ? { extensions: bodyExtensions } : {}
6915
7007
  };
6916
7008
  const headerChallenge = {
@@ -6941,7 +7033,7 @@ function createPaymentGate(options) {
6941
7033
  function enrichReceipt(spec, receipt) {
6942
7034
  let amountFormatted = receipt.amount;
6943
7035
  try {
6944
- amountFormatted = _chunkDCOUJZPLcjs.formatUnits.call(void 0, BigInt(receipt.amount), spec.decimals);
7036
+ amountFormatted = _chunk57V5DNJTcjs.formatUnits.call(void 0, BigInt(receipt.amount), spec.decimals);
6945
7037
  } catch (e47) {
6946
7038
  }
6947
7039
  return {
@@ -7109,7 +7201,17 @@ function createPaymentGate(options) {
7109
7201
  await settleTx(ref, false);
7110
7202
  return rejection(result.error, result.detail);
7111
7203
  }
7112
- await settleTx(ref, true);
7204
+ const verified = result.receipt.transaction;
7205
+ if (verified && verified !== ref) {
7206
+ if (await claimTx(verified)) {
7207
+ await settleTx(ref, false);
7208
+ return rejection("tx_already_used", `Payment ${verified} was already redeemed.`);
7209
+ }
7210
+ await settleTx(ref, false);
7211
+ await settleTx(verified, true);
7212
+ } else {
7213
+ await settleTx(ref, true);
7214
+ }
7113
7215
  await deliverOnPaid(spec, result.receipt);
7114
7216
  return await buildPaidResult(spec, result.receipt, sig.payload.nonce);
7115
7217
  }
@@ -7183,7 +7285,7 @@ function createPaymentGate(options) {
7183
7285
  const ftMethod = accept.extra.assetTransferMethod;
7184
7286
  const needsFeePayer = ftMethod === "svm" || ftMethod === "algorand" || ftMethod === "aptos" || ftMethod === "near";
7185
7287
  if (needsFeePayer && !accept.extra.feePayer) {
7186
- throw new (0, _chunkDCOUJZPLcjs.SettlementError)(
7288
+ throw new (0, _chunk57V5DNJTcjs.SettlementError)(
7187
7289
  `exact settle: the ${ftMethod} facilitator rail is missing extra.feePayer (the gas sponsor) \u2014 cannot settle.`
7188
7290
  );
7189
7291
  }
@@ -7231,15 +7333,15 @@ function createPaymentGate(options) {
7231
7333
  if (s.endsWith("%")) {
7232
7334
  const pct = s.slice(0, -1).trim();
7233
7335
  if (!/^\d+(\.\d+)?$/.test(pct)) return null;
7234
- const pctScaled = _chunkDCOUJZPLcjs.floorUnits.call(void 0, pct, 4);
7336
+ const pctScaled = _chunk57V5DNJTcjs.floorUnits.call(void 0, pct, 4);
7235
7337
  return maxAmount * pctScaled / (100n * 10n ** 4n);
7236
7338
  }
7237
7339
  if (s.startsWith("$")) {
7238
7340
  const amt = s.slice(1).trim();
7239
- return _chunkDCOUJZPLcjs.floorUnits.call(void 0, amt, decimals);
7341
+ return _chunk57V5DNJTcjs.floorUnits.call(void 0, amt, decimals);
7240
7342
  }
7241
7343
  if (/^\d+$/.test(s)) return BigInt(s);
7242
- return _chunkDCOUJZPLcjs.floorUnits.call(void 0, s, decimals);
7344
+ return _chunk57V5DNJTcjs.floorUnits.call(void 0, s, decimals);
7243
7345
  } catch (e56) {
7244
7346
  return null;
7245
7347
  }
@@ -7290,7 +7392,7 @@ function createPaymentGate(options) {
7290
7392
  result = await spec.net.settleUptoSelf({ relayer, payload: upto.payload, accept, settleAmount });
7291
7393
  } catch (err) {
7292
7394
  await settleTx(nonce, false);
7293
- if (err instanceof _chunkDCOUJZPLcjs.SettlementError) throw err;
7395
+ if (err instanceof _chunk57V5DNJTcjs.SettlementError) throw err;
7294
7396
  return rejection(
7295
7397
  "tx_reverted",
7296
7398
  `upto: metering/settle failed (${err instanceof Error ? err.message : String(err)}).`
@@ -7315,7 +7417,7 @@ function createPaymentGate(options) {
7315
7417
  if (result.kind === "invalid") await deliverOnFailed(result);
7316
7418
  return result;
7317
7419
  }
7318
- async function resolveVerdictObject(obj) {
7420
+ async function routeVerdictObject(obj) {
7319
7421
  if (obj === void 0 || obj === null) return asChallenge();
7320
7422
  const sig = parseSignatureObject(obj);
7321
7423
  if (sig && sig.accepted && typeof sig.accepted.network === "string" && typeof sig.accepted.asset === "string") {
@@ -7327,11 +7429,49 @@ function createPaymentGate(options) {
7327
7429
  if (exact) return verifyExact(exact);
7328
7430
  return asChallenge();
7329
7431
  }
7432
+ function echoPaymentIdentifier(result, id) {
7433
+ try {
7434
+ const decoded = decodeBase64Json(result.receiptHeader);
7435
+ if (!decoded) return result;
7436
+ const { extensions: existing, ...receiptOnly } = decoded;
7437
+ const merged = {
7438
+ ..._nullishCoalesce(existing, () => ( {})),
7439
+ [EXT_PAYMENT_IDENTIFIER]: { info: { required: false, id } }
7440
+ };
7441
+ return { ...result, receiptHeader: buildReceiptHeader(receiptOnly, merged) };
7442
+ } catch (e57) {
7443
+ return result;
7444
+ }
7445
+ }
7446
+ async function resolveVerdictObject(obj) {
7447
+ if (!options.paymentIdentifier) return routeVerdictObject(obj);
7448
+ const id = readPaymentIdentifier(obj);
7449
+ if (id !== null && typeof id === "object") {
7450
+ return rejection("signature_invalid", `payment-identifier: ${id.invalid}.`);
7451
+ }
7452
+ if (id === null) return routeVerdictObject(obj);
7453
+ const idKey = "pid:" + id;
7454
+ if (await claimTx(idKey)) {
7455
+ return rejection(
7456
+ "tx_already_used",
7457
+ `Idempotency id "${id}" is already bound to a settled payment; use a fresh id for a new payment.`
7458
+ );
7459
+ }
7460
+ let result;
7461
+ try {
7462
+ result = await routeVerdictObject(obj);
7463
+ } catch (err) {
7464
+ await settleTx(idKey, false);
7465
+ throw err;
7466
+ }
7467
+ await settleTx(idKey, result.kind === "paid");
7468
+ return result.kind === "paid" ? echoPaymentIdentifier(result, id) : result;
7469
+ }
7330
7470
  return { challenge, verify, verifyObject, describe, landingPage };
7331
7471
  }
7332
7472
  function requirePayment(options) {
7333
7473
  if (options.upto) {
7334
- throw new (_class3 = class extends _chunkDCOUJZPLcjs.PipRailError {constructor(...args2) { super(...args2); _class3.prototype.__init7.call(this); }
7474
+ throw new (_class3 = class extends _chunk57V5DNJTcjs.PipRailError {constructor(...args2) { super(...args2); _class3.prototype.__init7.call(this); }
7335
7475
  __init7() {this.code = "UNSUPPORTED_SCHEME"}
7336
7476
  }, _class3)(
7337
7477
  "requirePayment: the 'upto' (metered) rail is unsupported through the Express middleware \u2014 it settles before the route handler serves, so metered usage is unknown at settle time. Call gate.verify() directly (createPaymentGate) and meter inside settleAmount; see docs/accepting-payments/upto-rail-seller.md."
@@ -7343,7 +7483,7 @@ function requirePayment(options) {
7343
7483
  try {
7344
7484
  result = await gate.verify(_nullishCoalesce(req.headers[HEADER_SIGNATURE], () => ( req.headers[HEADER_SIGNATURE_V1])));
7345
7485
  } catch (err) {
7346
- if (err instanceof _chunkDCOUJZPLcjs.SettlementError) {
7486
+ if (err instanceof _chunk57V5DNJTcjs.SettlementError) {
7347
7487
  res.status(502);
7348
7488
  res.json({
7349
7489
  x402Version: 2,
@@ -7391,7 +7531,7 @@ function isRetryableStatus(status) {
7391
7531
  }
7392
7532
  var sleep = (ms) => ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
7393
7533
  async function signBody(secret, body) {
7394
- const subtle = _optionalChain([globalThis, 'access', _129 => _129.crypto, 'optionalAccess', _130 => _130.subtle]);
7534
+ const subtle = _optionalChain([globalThis, 'access', _138 => _138.crypto, 'optionalAccess', _139 => _139.subtle]);
7395
7535
  if (!subtle) return null;
7396
7536
  try {
7397
7537
  const enc = new TextEncoder();
@@ -7401,7 +7541,7 @@ async function signBody(secret, body) {
7401
7541
  const sig = await subtle.sign("HMAC", key, enc.encode(body));
7402
7542
  const hex = Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
7403
7543
  return `sha256=${hex}`;
7404
- } catch (e57) {
7544
+ } catch (e58) {
7405
7545
  return null;
7406
7546
  }
7407
7547
  }
@@ -7461,8 +7601,8 @@ async function deliverReceipt(receipt, options) {
7461
7601
  const retryable = status === void 0 ? true : isRetryableStatus(status);
7462
7602
  const willRetry = !ok && retryable && attempt < maxAttempts;
7463
7603
  try {
7464
- _optionalChain([onAttempt, 'optionalCall', _131 => _131({ attempt, ok, ...status !== void 0 ? { status } : {}, ...error ? { error } : {}, willRetry })]);
7465
- } catch (e58) {
7604
+ _optionalChain([onAttempt, 'optionalCall', _140 => _140({ attempt, ok, ...status !== void 0 ? { status } : {}, ...error ? { error } : {}, willRetry })]);
7605
+ } catch (e59) {
7466
7606
  }
7467
7607
  if (ok) return { delivered: true, attempts: attempt, status };
7468
7608
  if (!willRetry) {
@@ -7550,13 +7690,13 @@ function toA2APaymentFailed(code, detail, receipts = [], network) {
7550
7690
  };
7551
7691
  }
7552
7692
  function fromA2APaymentRequired(task) {
7553
- const meta = _optionalChain([task, 'access', _132 => _132.status, 'optionalAccess', _133 => _133.message, 'optionalAccess', _134 => _134.metadata]);
7554
- const required = _optionalChain([meta, 'optionalAccess', _135 => _135[A2A_REQUIRED_KEY]]);
7693
+ const meta = _optionalChain([task, 'access', _141 => _141.status, 'optionalAccess', _142 => _142.message, 'optionalAccess', _143 => _143.metadata]);
7694
+ const required = _optionalChain([meta, 'optionalAccess', _144 => _144[A2A_REQUIRED_KEY]]);
7555
7695
  if (!required || typeof required !== "object") return null;
7556
7696
  return required;
7557
7697
  }
7558
7698
  function fromA2APaymentPayload(message) {
7559
- const raw = _optionalChain([message, 'access', _136 => _136.metadata, 'optionalAccess', _137 => _137[A2A_PAYLOAD_KEY]]);
7699
+ const raw = _optionalChain([message, 'access', _145 => _145.metadata, 'optionalAccess', _146 => _146[A2A_PAYLOAD_KEY]]);
7560
7700
  if (raw === void 0 || raw === null) return null;
7561
7701
  return { raw, taskId: _nullishCoalesce(message.taskId, () => ( "")) };
7562
7702
  }
@@ -7589,7 +7729,7 @@ function createA2APaymentHandler(options) {
7589
7729
  const ttlMs = _nullishCoalesce(options.taskTtlMs, () => ( maxTimeoutSeconds * 1e3));
7590
7730
  const store = _nullishCoalesce(options.taskStore, () => ( defaultTaskStore()));
7591
7731
  function appendReceipt(taskId, entry) {
7592
- const prior = _nullishCoalesce(_optionalChain([store, 'access', _138 => _138.get, 'call', _139 => _139(taskId), 'optionalAccess', _140 => _140.receipts]), () => ( []));
7732
+ const prior = _nullishCoalesce(_optionalChain([store, 'access', _147 => _147.get, 'call', _148 => _148(taskId), 'optionalAccess', _149 => _149.receipts]), () => ( []));
7593
7733
  const isDup = "success" in entry && entry.success === true && entry.transaction !== "" && prior.some((r) => "transaction" in r && r.transaction === entry.transaction);
7594
7734
  const next = isDup ? prior : [...prior, entry];
7595
7735
  const receipts = next.length > MAX_TASK_RECEIPTS ? next.slice(-MAX_TASK_RECEIPTS) : next;
@@ -7665,7 +7805,7 @@ function createA2APaymentHandler(options) {
7665
7805
  try {
7666
7806
  result = await gate.verifyObject(inbound.raw);
7667
7807
  } catch (err) {
7668
- if (err instanceof _chunkDCOUJZPLcjs.SettlementError) {
7808
+ if (err instanceof _chunk57V5DNJTcjs.SettlementError) {
7669
7809
  return failedTask(id, "settlement_failed", err.message, attempted);
7670
7810
  }
7671
7811
  const detail = err instanceof Error ? err.message : String(err);
@@ -7697,11 +7837,11 @@ function createA2APaymentHandler(options) {
7697
7837
  }
7698
7838
  }
7699
7839
  function agentCardExtension(opts) {
7700
- const uri = _optionalChain([opts, 'optionalAccess', _141 => _141.version]) === "v0.2" ? A2A_X402_EXTENSION_URI_V02 : A2A_X402_EXTENSION_URI_V01;
7840
+ const uri = _optionalChain([opts, 'optionalAccess', _150 => _150.version]) === "v0.2" ? A2A_X402_EXTENSION_URI_V02 : A2A_X402_EXTENSION_URI_V01;
7701
7841
  return {
7702
7842
  uri,
7703
7843
  description: "Supports payments using the x402 protocol for on-chain settlement.",
7704
- ..._optionalChain([opts, 'optionalAccess', _142 => _142.required]) ? { required: true } : {}
7844
+ ..._optionalChain([opts, 'optionalAccess', _151 => _151.required]) ? { required: true } : {}
7705
7845
  };
7706
7846
  }
7707
7847
  return { handleMessage, agentCardExtension, gate };
@@ -7712,7 +7852,7 @@ function singleNetworkOf(challenge) {
7712
7852
  }
7713
7853
  function networkFromPayload(raw) {
7714
7854
  const v = raw;
7715
- if (v && typeof _optionalChain([v, 'access', _143 => _143.accepted, 'optionalAccess', _144 => _144.network]) === "string") return v.accepted.network;
7855
+ if (v && typeof _optionalChain([v, 'access', _152 => _152.accepted, 'optionalAccess', _153 => _153.network]) === "string") return v.accepted.network;
7716
7856
  if (v && typeof v.network === "string") return v.network;
7717
7857
  return void 0;
7718
7858
  }
@@ -7727,6 +7867,130 @@ function resourceUrlFromMessage(message) {
7727
7867
  return "";
7728
7868
  }
7729
7869
 
7870
+ // src/transports/mcp-types.ts
7871
+ var MCP_PAYMENT_META_KEY = "x402/payment";
7872
+ var MCP_PAYMENT_RESPONSE_META_KEY = "x402/payment-response";
7873
+
7874
+ // src/transports/mcp.ts
7875
+ function toMcpPaymentRequired(challenge) {
7876
+ const text = JSON.stringify(challenge);
7877
+ return {
7878
+ isError: true,
7879
+ structuredContent: challenge,
7880
+ content: [{ type: "text", text }]
7881
+ };
7882
+ }
7883
+ function toMcpPaymentResponse(content, receipt) {
7884
+ return {
7885
+ content,
7886
+ _meta: {
7887
+ [MCP_PAYMENT_RESPONSE_META_KEY]: {
7888
+ success: true,
7889
+ transaction: receipt.transaction,
7890
+ network: receipt.network,
7891
+ payer: receipt.payer
7892
+ }
7893
+ }
7894
+ };
7895
+ }
7896
+ function fromMcpPayment(params) {
7897
+ const meta = _optionalChain([params, 'optionalAccess', _154 => _154._meta, 'optionalAccess', _155 => _155[MCP_PAYMENT_META_KEY]]);
7898
+ return meta == null ? null : meta;
7899
+ }
7900
+ function fromMcpPaymentRequired(result) {
7901
+ if (!result || result.isError !== true) return null;
7902
+ const sc = result.structuredContent;
7903
+ if (sc && typeof sc === "object" && typeof sc.x402Version === "number") {
7904
+ return sc;
7905
+ }
7906
+ const text = _optionalChain([result, 'access', _156 => _156.content, 'optionalAccess', _157 => _157[0], 'optionalAccess', _158 => _158.text]);
7907
+ if (typeof text === "string") {
7908
+ try {
7909
+ const parsed = JSON.parse(text);
7910
+ if (parsed && typeof parsed === "object" && typeof parsed.x402Version === "number") {
7911
+ return parsed;
7912
+ }
7913
+ } catch (e60) {
7914
+ }
7915
+ }
7916
+ return null;
7917
+ }
7918
+ function isMcpPaymentRequired(result) {
7919
+ return fromMcpPaymentRequired(result) != null;
7920
+ }
7921
+ function fromMcpPaymentResponse(result) {
7922
+ const meta = _optionalChain([result, 'optionalAccess', _159 => _159._meta, 'optionalAccess', _160 => _160[MCP_PAYMENT_RESPONSE_META_KEY]]);
7923
+ if (!meta || typeof meta !== "object") return null;
7924
+ return meta;
7925
+ }
7926
+ function buildMcpPaymentMeta(input) {
7927
+ return {
7928
+ [MCP_PAYMENT_META_KEY]: {
7929
+ x402Version: _nullishCoalesce(input.x402Version, () => ( 2)),
7930
+ ...input.resource ? { resource: input.resource } : {},
7931
+ accepted: input.accepted,
7932
+ payload: input.payload
7933
+ }
7934
+ };
7935
+ }
7936
+ function createMcpPaymentTool(options) {
7937
+ const gate = _nullishCoalesce(options.gate, () => ( createPaymentGate(options)));
7938
+ function settlementFailed(code, detail) {
7939
+ return {
7940
+ isError: true,
7941
+ content: [
7942
+ {
7943
+ type: "text",
7944
+ text: `x402 settlement failed (${toA2AErrorCode(code)}): ${detail}. The buyer can retry, or pay the onchain-proof rail directly.`
7945
+ }
7946
+ ]
7947
+ };
7948
+ }
7949
+ async function handleToolCall(params) {
7950
+ const raw = fromMcpPayment(params);
7951
+ if (raw == null) {
7952
+ const { challenge } = await gate.challenge(_nullishCoalesce(options.resourceUrl, () => ( "")));
7953
+ return toMcpPaymentRequired(challenge);
7954
+ }
7955
+ let result;
7956
+ try {
7957
+ result = await gate.verifyObject(raw);
7958
+ } catch (err) {
7959
+ if (err instanceof _chunk57V5DNJTcjs.SettlementError) return settlementFailed("settlement_failed", err.message);
7960
+ throw err;
7961
+ }
7962
+ if (result.kind === "paid") {
7963
+ try {
7964
+ const content = await options.fulfill({ receipt: result.receipt, params });
7965
+ return toMcpPaymentResponse(content, result.receipt);
7966
+ } catch (err) {
7967
+ const detail = err instanceof Error ? err.message : String(err);
7968
+ return toMcpPaymentResponse(
7969
+ [{ type: "text", text: `Payment settled (tx ${result.receipt.transaction}), but serving the result failed: ${detail}` }],
7970
+ result.receipt
7971
+ );
7972
+ }
7973
+ }
7974
+ return toMcpPaymentRequired(result.challenge);
7975
+ }
7976
+ return { handleToolCall, gate };
7977
+ }
7978
+
7979
+
7980
+
7981
+
7982
+
7983
+
7984
+
7985
+
7986
+
7987
+
7988
+
7989
+
7990
+
7991
+
7992
+
7993
+
7730
7994
 
7731
7995
 
7732
7996
 
@@ -7859,4 +8123,4 @@ function resourceUrlFromMessage(message) {
7859
8123
 
7860
8124
 
7861
8125
 
7862
- exports.A2A_ERROR_KEY = A2A_ERROR_KEY; exports.A2A_EXTENSIONS_HEADER = A2A_EXTENSIONS_HEADER; exports.A2A_PAYLOAD_KEY = A2A_PAYLOAD_KEY; exports.A2A_RECEIPTS_KEY = A2A_RECEIPTS_KEY; exports.A2A_REQUIRED_KEY = A2A_REQUIRED_KEY; exports.A2A_STATUS_KEY = A2A_STATUS_KEY; exports.A2A_X402_EXTENSION_URI_V01 = A2A_X402_EXTENSION_URI_V01; exports.A2A_X402_EXTENSION_URI_V02 = A2A_X402_EXTENSION_URI_V02; exports.BRAND = BRAND; exports.BUILTIN_DENOMS = BUILTIN_DENOMS; exports.CHAINS = CHAINS; exports.ConfirmationTimeoutError = _chunkDCOUJZPLcjs.ConfirmationTimeoutError; exports.DENOM_PRECISION = DENOM_PRECISION; exports.DIRECTORY_INFO = DIRECTORY_INFO; exports.EIP3009_TYPES = EIP3009_TYPES; exports.EXACT_NETWORK_SLUGS = EXACT_NETWORK_SLUGS; exports.EXT_OFFER_RECEIPT = EXT_OFFER_RECEIPT; exports.GENERATOR = GENERATOR; exports.HEADER_REQUIRED = HEADER_REQUIRED; exports.HEADER_RESPONSE = HEADER_RESPONSE; exports.HEADER_RESPONSE_V1 = HEADER_RESPONSE_V1; exports.HEADER_SIGNATURE = HEADER_SIGNATURE; exports.HEADER_SIGNATURE_V1 = HEADER_SIGNATURE_V1; exports.InsufficientFundsError = _chunkDCOUJZPLcjs.InsufficientFundsError; exports.InvalidEnvelopeError = _chunkDCOUJZPLcjs.InvalidEnvelopeError; exports.KNOWN_FACILITATORS = KNOWN_FACILITATORS; exports.MaxRetriesExceededError = _chunkDCOUJZPLcjs.MaxRetriesExceededError; exports.MissingDriverError = _chunkDCOUJZPLcjs.MissingDriverError; exports.MultiChainPayer = MultiChainPayer; exports.NoCompatibleAcceptError = _chunkDCOUJZPLcjs.NoCompatibleAcceptError; exports.NonReplayableBodyError = _chunkDCOUJZPLcjs.NonReplayableBodyError; exports.PERMIT2_ADDRESS = PERMIT2_ADDRESS; exports.PERMIT2_PROXY_CHAIN_IDS = PERMIT2_PROXY_CHAIN_IDS; exports.PERMIT2_UPTO_WITNESS_TYPES = PERMIT2_UPTO_WITNESS_TYPES; exports.PERMIT2_WITNESS_TYPES = PERMIT2_WITNESS_TYPES; exports.PIPRAIL_AGENT_GUIDE = PIPRAIL_AGENT_GUIDE; exports.POWERED_BY = POWERED_BY; exports.PaymentDeclinedError = _chunkDCOUJZPLcjs.PaymentDeclinedError; exports.PaymentTimeoutError = _chunkDCOUJZPLcjs.PaymentTimeoutError; exports.PipRailClient = PipRailClient; exports.PipRailError = _chunkDCOUJZPLcjs.PipRailError; exports.REGISTER_ATTRIBUTION = REGISTER_ATTRIBUTION; exports.RecipientNotReadyError = _chunkDCOUJZPLcjs.RecipientNotReadyError; exports.SettlementError = _chunkDCOUJZPLcjs.SettlementError; exports.SpendLedger = SpendLedger; exports.UPTO_PROXY_CHAIN_IDS = UPTO_PROXY_CHAIN_IDS; exports.UnknownTokenError = _chunkDCOUJZPLcjs.UnknownTokenError; exports.UnsupportedNetworkError = _chunkDCOUJZPLcjs.UnsupportedNetworkError; exports.UnsupportedSchemeError = _chunkDCOUJZPLcjs.UnsupportedSchemeError; exports.VERIFY_CODE_TO_A2A_ERROR = VERIFY_CODE_TO_A2A_ERROR; exports.WalletRequiredError = _chunkDCOUJZPLcjs.WalletRequiredError; exports.WrongChainError = _chunkDCOUJZPLcjs.WrongChainError; exports.WrongFamilyError = _chunkDCOUJZPLcjs.WrongFamilyError; exports.X402_EXACT_PERMIT2_PROXY = X402_EXACT_PERMIT2_PROXY; exports.X402_UPTO_PERMIT2_PROXY = X402_UPTO_PERMIT2_PROXY; exports.agentGuide = agentGuide; exports.appendAttribution = appendAttribution; exports.appendKeywords = appendKeywords; exports.buildBazaarExtension = buildBazaarExtension; exports.buildChallengeHeader = buildChallengeHeader; exports.buildEndpointInfo = buildEndpointInfo; exports.buildExactAuthorization = buildExactAuthorization; exports.buildExactSignatureHeader = buildExactSignatureHeader; exports.buildOpenApi = buildOpenApi; exports.buildReceiptExtension = buildReceiptExtension; exports.buildReceiptHeader = buildReceiptHeader; exports.buildSelfDescription = buildSelfDescription; exports.buildSignatureHeader = buildSignatureHeader; exports.buildUptoSignatureHeader = buildUptoSignatureHeader; exports.buildWellKnownX402 = buildWellKnownX402; exports.buildX402DnsTxt = buildX402DnsTxt; exports.chainIdForExactNetwork = chainIdForExactNetwork; exports.claim402IndexDomain = claim402IndexDomain; exports.classifyChallenge = classifyChallenge; exports.createA2APaymentHandler = createA2APaymentHandler; exports.createPaymentGate = createPaymentGate; exports.decodeBase64Json = decodeBase64Json; exports.decorateOutcome = decorateOutcome; exports.deliverReceipt = deliverReceipt; exports.denomOf = denomOf; exports.describeChallenge = describeChallenge; exports.discoveryHeaders = discoveryHeaders; exports.eip3009Abi = eip3009Abi; exports.encodeXPaymentHeader = encodeXPaymentHeader; exports.evaluatePolicy = evaluatePolicy; exports.explainDecline = explainDecline; exports.facilitatorCoverage = facilitatorCoverage; exports.fetchAcross = fetchAcross; exports.firstKeylessFacilitator = firstKeylessFacilitator; exports.formatSpendReport = formatSpendReport; exports.fromA2APaymentPayload = fromA2APaymentPayload; exports.fromA2APaymentRequired = fromA2APaymentRequired; exports.getDirectoryInfo = getDirectoryInfo; exports.isPermit2ProxyChain = isPermit2ProxyChain; exports.isUptoProxyChain = isUptoProxyChain; exports.knownFacilitatorsFor = knownFacilitatorsFor; exports.memorySpendStore = _chunkO4UQOZ4Zcjs.memorySpendStore; exports.normalizeNetwork = normalizeNetwork; exports.parseChallenge = parseChallenge; exports.parseExactObject = parseExactObject; exports.parseExactPaymentHeader = parseExactPaymentHeader; exports.parseExactRequirements = parseExactRequirements; exports.parseFacilitatorSupported = parseFacilitatorSupported; exports.parseReceipt = parseReceipt; exports.parseReceiptExtension = parseReceiptExtension; exports.parseSettleResponse = parseSettleResponse; exports.parseSignatureHeader = parseSignatureHeader; exports.parseSignatureObject = parseSignatureObject; exports.parseUptoObject = parseUptoObject; exports.parseUptoPaymentHeader = parseUptoPaymentHeader; exports.paymentTools = paymentTools; exports.pickAccept = pickAccept; exports.planAcross = planAcross; exports.rankResources = rankResources; exports.readExactDomain = readExactDomain; exports.register402Index = register402Index; exports.registerDriver = registerDriver; exports.registerX402Scan = registerX402Scan; exports.renderLandingPage = renderLandingPage; exports.requirePayment = requirePayment; exports.resolveChain = resolveChain; exports.scoreResource = scoreResource; exports.searchOpenIndexes = searchOpenIndexes; exports.settleViaFacilitator = settleViaFacilitator; exports.summarizePlan = summarizePlan; exports.toA2AErrorCode = toA2AErrorCode; exports.toA2APaymentFailed = toA2APaymentFailed; exports.toA2APaymentReceipts = toA2APaymentReceipts; exports.toA2APaymentRequired = toA2APaymentRequired; exports.toInsufficientFundsError = _chunkDCOUJZPLcjs.toInsufficientFundsError; exports.toInvalidBody = toInvalidBody; exports.verify402IndexDomain = verify402IndexDomain;
8126
+ exports.A2A_ERROR_KEY = A2A_ERROR_KEY; exports.A2A_EXTENSIONS_HEADER = A2A_EXTENSIONS_HEADER; exports.A2A_PAYLOAD_KEY = A2A_PAYLOAD_KEY; exports.A2A_RECEIPTS_KEY = A2A_RECEIPTS_KEY; exports.A2A_REQUIRED_KEY = A2A_REQUIRED_KEY; exports.A2A_STATUS_KEY = A2A_STATUS_KEY; exports.A2A_X402_EXTENSION_URI_V01 = A2A_X402_EXTENSION_URI_V01; exports.A2A_X402_EXTENSION_URI_V02 = A2A_X402_EXTENSION_URI_V02; exports.BRAND = BRAND; exports.BUILTIN_DENOMS = BUILTIN_DENOMS; exports.CHAINS = CHAINS; exports.ConfirmationTimeoutError = _chunk57V5DNJTcjs.ConfirmationTimeoutError; exports.DENOM_PRECISION = DENOM_PRECISION; exports.DIRECTORY_INFO = DIRECTORY_INFO; exports.EIP3009_TYPES = EIP3009_TYPES; exports.EXACT_NETWORK_SLUGS = EXACT_NETWORK_SLUGS; exports.EXT_OFFER_RECEIPT = EXT_OFFER_RECEIPT; exports.EXT_PAYMENT_IDENTIFIER = EXT_PAYMENT_IDENTIFIER; exports.GENERATOR = GENERATOR; exports.HEADER_REQUIRED = HEADER_REQUIRED; exports.HEADER_RESPONSE = HEADER_RESPONSE; exports.HEADER_RESPONSE_V1 = HEADER_RESPONSE_V1; exports.HEADER_SIGNATURE = HEADER_SIGNATURE; exports.HEADER_SIGNATURE_V1 = HEADER_SIGNATURE_V1; exports.InsufficientFundsError = _chunk57V5DNJTcjs.InsufficientFundsError; exports.InvalidConfigError = _chunk57V5DNJTcjs.InvalidConfigError; exports.InvalidEnvelopeError = _chunk57V5DNJTcjs.InvalidEnvelopeError; exports.KNOWN_FACILITATORS = KNOWN_FACILITATORS; exports.MCP_PAYMENT_META_KEY = MCP_PAYMENT_META_KEY; exports.MCP_PAYMENT_RESPONSE_META_KEY = MCP_PAYMENT_RESPONSE_META_KEY; exports.MaxRetriesExceededError = _chunk57V5DNJTcjs.MaxRetriesExceededError; exports.MissingDriverError = _chunk57V5DNJTcjs.MissingDriverError; exports.MultiChainPayer = MultiChainPayer; exports.NoCompatibleAcceptError = _chunk57V5DNJTcjs.NoCompatibleAcceptError; exports.NonReplayableBodyError = _chunk57V5DNJTcjs.NonReplayableBodyError; exports.PERMIT2_ADDRESS = PERMIT2_ADDRESS; exports.PERMIT2_PROXY_CHAIN_IDS = PERMIT2_PROXY_CHAIN_IDS; exports.PERMIT2_UPTO_WITNESS_TYPES = PERMIT2_UPTO_WITNESS_TYPES; exports.PERMIT2_WITNESS_TYPES = PERMIT2_WITNESS_TYPES; exports.PIPRAIL_AGENT_GUIDE = PIPRAIL_AGENT_GUIDE; exports.POWERED_BY = POWERED_BY; exports.PaymentDeclinedError = _chunk57V5DNJTcjs.PaymentDeclinedError; exports.PaymentTimeoutError = _chunk57V5DNJTcjs.PaymentTimeoutError; exports.PipRailClient = PipRailClient; exports.PipRailError = _chunk57V5DNJTcjs.PipRailError; exports.REGISTER_ATTRIBUTION = REGISTER_ATTRIBUTION; exports.RecipientNotReadyError = _chunk57V5DNJTcjs.RecipientNotReadyError; exports.SettlementError = _chunk57V5DNJTcjs.SettlementError; exports.SpendLedger = SpendLedger; exports.UPTO_PROXY_CHAIN_IDS = UPTO_PROXY_CHAIN_IDS; exports.UnknownTokenError = _chunk57V5DNJTcjs.UnknownTokenError; exports.UnsupportedNetworkError = _chunk57V5DNJTcjs.UnsupportedNetworkError; exports.UnsupportedSchemeError = _chunk57V5DNJTcjs.UnsupportedSchemeError; exports.VERIFY_CODE_TO_A2A_ERROR = VERIFY_CODE_TO_A2A_ERROR; exports.WalletRequiredError = _chunk57V5DNJTcjs.WalletRequiredError; exports.WrongChainError = _chunk57V5DNJTcjs.WrongChainError; exports.WrongFamilyError = _chunk57V5DNJTcjs.WrongFamilyError; exports.X402_EXACT_PERMIT2_PROXY = X402_EXACT_PERMIT2_PROXY; exports.X402_UPTO_PERMIT2_PROXY = X402_UPTO_PERMIT2_PROXY; exports.agentGuide = agentGuide; exports.appendAttribution = appendAttribution; exports.appendKeywords = appendKeywords; exports.buildBazaarExtension = buildBazaarExtension; exports.buildChallengeHeader = buildChallengeHeader; exports.buildEndpointInfo = buildEndpointInfo; exports.buildExactAuthorization = buildExactAuthorization; exports.buildExactSignatureHeader = buildExactSignatureHeader; exports.buildMcpPaymentMeta = buildMcpPaymentMeta; exports.buildOpenApi = buildOpenApi; exports.buildPaymentIdentifierAdvertisement = buildPaymentIdentifierAdvertisement; exports.buildReceiptExtension = buildReceiptExtension; exports.buildReceiptHeader = buildReceiptHeader; exports.buildSelfDescription = buildSelfDescription; exports.buildSignatureHeader = buildSignatureHeader; exports.buildUptoSignatureHeader = buildUptoSignatureHeader; exports.buildWellKnownX402 = buildWellKnownX402; exports.buildWellKnownX402Manifest = buildWellKnownX402Manifest; exports.buildX402DnsTxt = buildX402DnsTxt; exports.chainIdForExactNetwork = chainIdForExactNetwork; exports.claim402IndexDomain = claim402IndexDomain; exports.classifyChallenge = classifyChallenge; exports.createA2APaymentHandler = createA2APaymentHandler; exports.createMcpPaymentTool = createMcpPaymentTool; exports.createPaymentGate = createPaymentGate; exports.decodeBase64Json = decodeBase64Json; exports.decorateOutcome = decorateOutcome; exports.deliverReceipt = deliverReceipt; exports.denomOf = denomOf; exports.describeChallenge = describeChallenge; exports.discoveryHeaders = discoveryHeaders; exports.eip3009Abi = eip3009Abi; exports.encodeXPaymentHeader = encodeXPaymentHeader; exports.evaluatePolicy = evaluatePolicy; exports.explainDecline = explainDecline; exports.facilitatorCoverage = facilitatorCoverage; exports.fetchAcross = fetchAcross; exports.firstKeylessFacilitator = firstKeylessFacilitator; exports.formatSpendReport = formatSpendReport; exports.fromA2APaymentPayload = fromA2APaymentPayload; exports.fromA2APaymentRequired = fromA2APaymentRequired; exports.fromMcpPayment = fromMcpPayment; exports.fromMcpPaymentRequired = fromMcpPaymentRequired; exports.fromMcpPaymentResponse = fromMcpPaymentResponse; exports.getDirectoryInfo = getDirectoryInfo; exports.isMcpPaymentRequired = isMcpPaymentRequired; exports.isPermit2ProxyChain = isPermit2ProxyChain; exports.isUptoProxyChain = isUptoProxyChain; exports.knownFacilitatorsFor = knownFacilitatorsFor; exports.memorySpendStore = _chunkO4UQOZ4Zcjs.memorySpendStore; exports.normalizeNetwork = normalizeNetwork; exports.parseChallenge = parseChallenge; exports.parseExactObject = parseExactObject; exports.parseExactPaymentHeader = parseExactPaymentHeader; exports.parseExactRequirements = parseExactRequirements; exports.parseFacilitatorSupported = parseFacilitatorSupported; exports.parseReceipt = parseReceipt; exports.parseReceiptExtension = parseReceiptExtension; exports.parseSettleResponse = parseSettleResponse; exports.parseSignatureHeader = parseSignatureHeader; exports.parseSignatureObject = parseSignatureObject; exports.parseUptoObject = parseUptoObject; exports.parseUptoPaymentHeader = parseUptoPaymentHeader; exports.paymentTools = paymentTools; exports.pickAccept = pickAccept; exports.planAcross = planAcross; exports.rankResources = rankResources; exports.readExactDomain = readExactDomain; exports.readPaymentIdentifier = readPaymentIdentifier; exports.register402Index = register402Index; exports.registerDriver = registerDriver; exports.registerX402Scan = registerX402Scan; exports.renderLandingPage = renderLandingPage; exports.requirePayment = requirePayment; exports.resolveChain = resolveChain; exports.scoreResource = scoreResource; exports.searchOpenIndexes = searchOpenIndexes; exports.settleViaFacilitator = settleViaFacilitator; exports.summarizePlan = summarizePlan; exports.toA2AErrorCode = toA2AErrorCode; exports.toA2APaymentFailed = toA2APaymentFailed; exports.toA2APaymentReceipts = toA2APaymentReceipts; exports.toA2APaymentRequired = toA2APaymentRequired; exports.toInsufficientFundsError = _chunk57V5DNJTcjs.toInsufficientFundsError; exports.toInvalidBody = toInvalidBody; exports.toMcpPaymentRequired = toMcpPaymentRequired; exports.toMcpPaymentResponse = toMcpPaymentResponse; exports.verify402IndexDomain = verify402IndexDomain;