tenjin-cli 0.1.0-alpha.24 → 0.1.0-alpha.25

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 (114) hide show
  1. package/README.md +5 -1
  2. package/dist/{chunk-H5UR3GFJ.js → chunk-3ZYPVSIU.js} +56 -31
  3. package/dist/chunk-3ZYPVSIU.js.map +1 -0
  4. package/dist/chunk-7EKYXMUO.js +7536 -0
  5. package/dist/chunk-7EKYXMUO.js.map +1 -0
  6. package/dist/chunk-AKWGE6JQ.js +49 -0
  7. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  8. package/dist/{chunk-RCJ64OXH.js → chunk-CEMXMUIU.js} +3 -3
  9. package/dist/{chunk-XZUGRTSV.js → chunk-CKDD554V.js} +2 -2
  10. package/dist/{hook-command-GMIDXVFK.js → chunk-CP7O6M55.js} +190 -40
  11. package/dist/chunk-CP7O6M55.js.map +1 -0
  12. package/dist/{chunk-UBOFYC6J.js → chunk-DRXDTITB.js} +1821 -141
  13. package/dist/chunk-DRXDTITB.js.map +1 -0
  14. package/dist/{chunk-EP5P2STS.js → chunk-EACMJEF3.js} +201 -8
  15. package/dist/chunk-EACMJEF3.js.map +1 -0
  16. package/dist/{chunk-GPLSNGKX.js → chunk-EG7P4SM6.js} +4 -4
  17. package/dist/{chunk-RGVOODF4.js → chunk-EL56RW2J.js} +164 -7463
  18. package/dist/chunk-EL56RW2J.js.map +1 -0
  19. package/dist/{chunk-KC24CYGV.js → chunk-EOGJKIOG.js} +6 -8
  20. package/dist/{chunk-KC24CYGV.js.map → chunk-EOGJKIOG.js.map} +1 -1
  21. package/dist/{chunk-ZMFDMALH.js → chunk-GT6W3VJM.js} +2 -2
  22. package/dist/{chunk-TMLCEPCD.js → chunk-HII5HOQV.js} +3 -5
  23. package/dist/chunk-HII5HOQV.js.map +1 -0
  24. package/dist/{chunk-UXSF7IFD.js → chunk-IYLECN4D.js} +3 -3
  25. package/dist/{chunk-SQSKVKX6.js → chunk-KGTQRJGS.js} +17 -8
  26. package/dist/chunk-KGTQRJGS.js.map +1 -0
  27. package/dist/chunk-LFZJM56J.js +159 -0
  28. package/dist/chunk-LFZJM56J.js.map +1 -0
  29. package/dist/{chunk-YZTIYDWU.js → chunk-NTYQHAIM.js} +2 -2
  30. package/dist/{chunk-IIE65SJC.js → chunk-NYPFOHSJ.js} +4 -4
  31. package/dist/{chunk-ZNZGBUV6.js → chunk-ODH7UXIS.js} +8 -7
  32. package/dist/chunk-ODH7UXIS.js.map +1 -0
  33. package/dist/{chunk-NSDZESRS.js → chunk-OZ3LWLCI.js} +3 -3
  34. package/dist/{chunk-XRW4N23F.js → chunk-SCAE6PW6.js} +4 -4
  35. package/dist/{chunk-O2WN732M.js → chunk-UDWGT4FX.js} +2 -2
  36. package/dist/chunk-VYONGSMQ.js +119 -0
  37. package/dist/chunk-VYONGSMQ.js.map +1 -0
  38. package/dist/{chunk-P22ZWXFX.js → chunk-XICKN3CH.js} +49 -4
  39. package/dist/chunk-XICKN3CH.js.map +1 -0
  40. package/dist/chunk-YHKXNYTB.js +105 -0
  41. package/dist/chunk-YHKXNYTB.js.map +1 -0
  42. package/dist/{chunk-W2ARIOAZ.js → chunk-YSW57KUT.js} +8 -10
  43. package/dist/{chunk-W2ARIOAZ.js.map → chunk-YSW57KUT.js.map} +1 -1
  44. package/dist/{chunk-FFL5M5BC.js → chunk-YTM7OURD.js} +2 -2
  45. package/dist/{cli-GGNOQQEB.js → cli-4WMGZPBP.js} +27 -28
  46. package/dist/{cli-GGNOQQEB.js.map → cli-4WMGZPBP.js.map} +1 -1
  47. package/dist/{config-XUUFICXK.js → config-VU6U7QOU.js} +9 -8
  48. package/dist/{doctor-3LGF6CWI.js → doctor-26JS2SG3.js} +123 -31
  49. package/dist/doctor-26JS2SG3.js.map +1 -0
  50. package/dist/{fund-3URFMBMN.js → fund-JJN3FRRF.js} +13 -14
  51. package/dist/fund-JJN3FRRF.js.map +1 -0
  52. package/dist/hook-command-S2V4UNB3.js +28 -0
  53. package/dist/index.js +3 -3
  54. package/dist/{install-FRTG4KHF.js → install-GXQ33J4G.js} +19 -16
  55. package/dist/{install-identity-WNXSYP6N.js → install-identity-HFQUXPSI.js} +6 -7
  56. package/dist/{install-wallet-MXLJJP3N.js → install-wallet-27LTEHBI.js} +8 -9
  57. package/dist/{install-wallet-MXLJJP3N.js.map → install-wallet-27LTEHBI.js.map} +1 -1
  58. package/dist/{mcp-O2WJ3QBW.js → mcp-AHCZVD2U.js} +596 -75
  59. package/dist/mcp-AHCZVD2U.js.map +1 -0
  60. package/dist/{pay-43WUYTW5.js → pay-3TCOPGCX.js} +14 -13
  61. package/dist/{payments-7UTMMTIO.js → payments-H3LSBGSL.js} +6 -7
  62. package/dist/{payments-7UTMMTIO.js.map → payments-H3LSBGSL.js.map} +1 -1
  63. package/dist/{send-ALHG2RXT.js → send-LKCLN5GA.js} +9 -11
  64. package/dist/{send-ALHG2RXT.js.map → send-LKCLN5GA.js.map} +1 -1
  65. package/dist/{status-CFPNHB6R.js → status-2FDGI4LQ.js} +7 -9
  66. package/dist/{status-CFPNHB6R.js.map → status-2FDGI4LQ.js.map} +1 -1
  67. package/dist/{status-line-FJ6N7MKJ.js → status-line-QKDJYZGV.js} +4 -5
  68. package/dist/{status-line-FJ6N7MKJ.js.map → status-line-QKDJYZGV.js.map} +1 -1
  69. package/dist/{status-line-wiring-GXFNXHPE.js → status-line-wiring-ZDBYHNYR.js} +6 -4
  70. package/dist/{uninstall-5P2GFYBY.js → uninstall-ZXWABDHS.js} +33 -29
  71. package/dist/uninstall-ZXWABDHS.js.map +1 -0
  72. package/dist/{update-QJ5YHJ7I.js → update-HEIWVOP5.js} +17 -6
  73. package/dist/update-HEIWVOP5.js.map +1 -0
  74. package/dist/{wallet-6OJPGNEV.js → wallet-T7JYWI6O.js} +8 -9
  75. package/dist/wallet-T7JYWI6O.js.map +1 -0
  76. package/docs/agent-permissions.md +6 -3
  77. package/package.json +7 -6
  78. package/dist/chunk-EP5P2STS.js.map +0 -1
  79. package/dist/chunk-H5UR3GFJ.js.map +0 -1
  80. package/dist/chunk-O2JYBOUO.js +0 -47
  81. package/dist/chunk-O2JYBOUO.js.map +0 -1
  82. package/dist/chunk-P22ZWXFX.js.map +0 -1
  83. package/dist/chunk-RGVOODF4.js.map +0 -1
  84. package/dist/chunk-S2NRVRPF.js +0 -171
  85. package/dist/chunk-S2NRVRPF.js.map +0 -1
  86. package/dist/chunk-SQSKVKX6.js.map +0 -1
  87. package/dist/chunk-TMLCEPCD.js.map +0 -1
  88. package/dist/chunk-UBOFYC6J.js.map +0 -1
  89. package/dist/chunk-YXLG7Q6Q.js +0 -140
  90. package/dist/chunk-YXLG7Q6Q.js.map +0 -1
  91. package/dist/chunk-ZNZGBUV6.js.map +0 -1
  92. package/dist/doctor-3LGF6CWI.js.map +0 -1
  93. package/dist/fund-3URFMBMN.js.map +0 -1
  94. package/dist/hook-command-GMIDXVFK.js.map +0 -1
  95. package/dist/mcp-O2WJ3QBW.js.map +0 -1
  96. package/dist/uninstall-5P2GFYBY.js.map +0 -1
  97. package/dist/update-QJ5YHJ7I.js.map +0 -1
  98. /package/dist/{chunk-RCJ64OXH.js.map → chunk-CEMXMUIU.js.map} +0 -0
  99. /package/dist/{chunk-XZUGRTSV.js.map → chunk-CKDD554V.js.map} +0 -0
  100. /package/dist/{chunk-GPLSNGKX.js.map → chunk-EG7P4SM6.js.map} +0 -0
  101. /package/dist/{chunk-ZMFDMALH.js.map → chunk-GT6W3VJM.js.map} +0 -0
  102. /package/dist/{chunk-UXSF7IFD.js.map → chunk-IYLECN4D.js.map} +0 -0
  103. /package/dist/{chunk-YZTIYDWU.js.map → chunk-NTYQHAIM.js.map} +0 -0
  104. /package/dist/{chunk-IIE65SJC.js.map → chunk-NYPFOHSJ.js.map} +0 -0
  105. /package/dist/{chunk-NSDZESRS.js.map → chunk-OZ3LWLCI.js.map} +0 -0
  106. /package/dist/{chunk-XRW4N23F.js.map → chunk-SCAE6PW6.js.map} +0 -0
  107. /package/dist/{chunk-O2WN732M.js.map → chunk-UDWGT4FX.js.map} +0 -0
  108. /package/dist/{chunk-FFL5M5BC.js.map → chunk-YTM7OURD.js.map} +0 -0
  109. /package/dist/{config-XUUFICXK.js.map → config-VU6U7QOU.js.map} +0 -0
  110. /package/dist/{install-FRTG4KHF.js.map → hook-command-S2V4UNB3.js.map} +0 -0
  111. /package/dist/{install-identity-WNXSYP6N.js.map → install-GXQ33J4G.js.map} +0 -0
  112. /package/dist/{pay-43WUYTW5.js.map → install-identity-HFQUXPSI.js.map} +0 -0
  113. /package/dist/{status-line-wiring-GXFNXHPE.js.map → pay-3TCOPGCX.js.map} +0 -0
  114. /package/dist/{wallet-6OJPGNEV.js.map → status-line-wiring-ZDBYHNYR.js.map} +0 -0
@@ -3,64 +3,91 @@ import {
3
3
  assertPublicDestination
4
4
  } from "./chunk-LAIZ2AQA.js";
5
5
  import {
6
+ BATCH_SETTLEMENT_ADDRESS,
7
+ BATCH_SETTLEMENT_SCHEME,
8
+ ERC3009_DEPOSIT_COLLECTOR_ADDRESS,
9
+ ErrCumulativeAmountBelowClaimed,
10
+ ErrCumulativeAmountMismatch,
11
+ ErrRefundAmountInvalid,
12
+ ErrRefundNoBalance,
13
+ MIN_WITHDRAW_DELAY,
14
+ PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,
15
+ batchPermit2WitnessTypes,
16
+ computeChannelId,
17
+ createNonce,
18
+ createPermit2Nonce,
19
+ getBatchSettlementEip712Domain,
20
+ getEvmChainId,
21
+ normalizeChannelId,
22
+ receiveAuthorizationTypes,
23
+ voucherTypes
24
+ } from "./chunk-LFZJM56J.js";
25
+ import {
26
+ ADDITIVE_ARRAY_INFO_FIELDS,
6
27
  HTTPFacilitatorClient,
7
28
  PaymentRequirementsV2Schema,
8
29
  SIGN_IN_WITH_X,
9
30
  SIWX_HEADER,
10
31
  buildSiwxHeader,
11
- createPublicClient,
32
+ convertToTokenAmount,
12
33
  decodePaymentRequiredHeader,
13
34
  decodePaymentResponseHeader,
35
+ deepEqual,
14
36
  findByNetworkAndScheme,
15
37
  findSchemesByNetwork,
16
- http,
38
+ networkMatchesPattern,
39
+ parseMoney,
40
+ toComparableArray,
17
41
  x402HTTPClient,
18
42
  x402Version
19
- } from "./chunk-RGVOODF4.js";
43
+ } from "./chunk-7EKYXMUO.js";
44
+ import {
45
+ createPublicClient,
46
+ http,
47
+ recoverTypedDataAddress
48
+ } from "./chunk-EL56RW2J.js";
20
49
  import {
50
+ encodeAbiParameters,
21
51
  encodeFunctionData,
22
52
  getAddress as getAddress2,
23
53
  keccak256,
24
54
  maxUint256,
25
- toBytes,
26
- toHex
55
+ toBytes
27
56
  } from "./chunk-TTNESUPQ.js";
28
57
  import {
29
58
  promptYesNo
30
59
  } from "./chunk-LHHMV4GU.js";
31
60
  import {
32
61
  USDC_ADDRESS
33
- } from "./chunk-FFL5M5BC.js";
62
+ } from "./chunk-YTM7OURD.js";
34
63
  import {
35
64
  describeWallet,
36
65
  resolveSpendAuthorizer,
37
66
  resolveWalletProvider
38
- } from "./chunk-GPLSNGKX.js";
67
+ } from "./chunk-EG7P4SM6.js";
39
68
  import {
40
69
  getAddress
41
70
  } from "./chunk-EGELTSPU.js";
42
71
  import {
43
72
  sanitizeForTerminal
44
- } from "./chunk-O2WN732M.js";
73
+ } from "./chunk-UDWGT4FX.js";
45
74
  import {
46
75
  mask
47
76
  } from "./chunk-7QKHZQKW.js";
48
77
  import {
49
78
  fetchFailureToCliError,
50
79
  httpRequest
51
- } from "./chunk-RCJ64OXH.js";
80
+ } from "./chunk-CEMXMUIU.js";
52
81
  import {
53
82
  resolveContextSettings
54
- } from "./chunk-TMLCEPCD.js";
55
- import {
56
- parseUsdToAtomic,
57
- toMoney
58
- } from "./chunk-O2JYBOUO.js";
83
+ } from "./chunk-HII5HOQV.js";
59
84
  import {
60
85
  external_exports,
61
86
  isSameDeployment,
62
- readUsdcBalanceWithFallback
63
- } from "./chunk-P22ZWXFX.js";
87
+ parseUsdToAtomic,
88
+ readUsdcBalanceWithFallback,
89
+ toMoney
90
+ } from "./chunk-XICKN3CH.js";
64
91
  import {
65
92
  CliError
66
93
  } from "./chunk-JLEF5WHM.js";
@@ -8066,7 +8093,7 @@ import { setTimeout as delay } from "node:timers/promises";
8066
8093
  import { readFile } from "node:fs/promises";
8067
8094
  import { join } from "node:path";
8068
8095
 
8069
- // node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/dist/esm/chunk-KKZBRP7D.mjs
8096
+ // node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/dist/esm/chunk-SV2YHMOC.mjs
8070
8097
  var BAZAAR = { key: "bazaar" };
8071
8098
  var BRACKET_PARAM_REGEX = /\[([^\]]+)\]/;
8072
8099
  var BRACKET_PARAM_REGEX_ALL = /\[([^\]]+)\]/g;
@@ -8087,6 +8114,10 @@ function normalizeWildcardPattern(pattern) {
8087
8114
  return seg;
8088
8115
  }).join("/");
8089
8116
  }
8117
+ function isWildcardOnlyPattern(pattern) {
8118
+ const segments = pattern.split("/").filter((segment) => segment.length > 0);
8119
+ return segments.length > 0 && segments.every((segment) => segment === "*");
8120
+ }
8090
8121
  function extractDynamicRouteInfo(routePattern, urlPath) {
8091
8122
  const hasBracket = BRACKET_PARAM_REGEX.test(routePattern);
8092
8123
  const hasColon = COLON_PARAM_REGEX.test(routePattern);
@@ -8163,6 +8194,9 @@ var bazaarResourceServerExtension = {
8163
8194
  }
8164
8195
  };
8165
8196
  const rawRoutePattern = transportContext.routePattern;
8197
+ if (rawRoutePattern && isWildcardOnlyPattern(rawRoutePattern)) {
8198
+ return enrichedResult;
8199
+ }
8166
8200
  const routePattern = rawRoutePattern ? normalizeWildcardPattern(rawRoutePattern) : void 0;
8167
8201
  const dynamicRoute = routePattern ? extractDynamicRouteInfo(routePattern, transportContext.adapter.getPath()) : null;
8168
8202
  if (dynamicRoute) {
@@ -8839,7 +8873,44 @@ async function confirmSpend(input) {
8839
8873
  return promptYesNo(prompt);
8840
8874
  }
8841
8875
 
8842
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/client/index.mjs
8876
+ // node_modules/.pnpm/@x402+core@2.28.0/node_modules/@x402/core/dist/esm/client/index.mjs
8877
+ var DEFAULT_MAX_AMOUNT_PER_PAYMENT = "$1";
8878
+ function isAtomicAmount(amount) {
8879
+ return /^\d+$/.test(amount);
8880
+ }
8881
+ function findSpendControlAssetEntry(controls, requirement, defaultAsset) {
8882
+ if (controls.allowedAssets === true) {
8883
+ return void 0;
8884
+ }
8885
+ return controls.allowedAssets?.find((entry) => {
8886
+ if (!networkMatchesPattern(entry.network, requirement.network)) {
8887
+ return false;
8888
+ }
8889
+ if (entry.asset.toLowerCase() === requirement.asset.toLowerCase()) {
8890
+ return true;
8891
+ }
8892
+ return defaultAsset != null && defaultAsset.symbol.toLowerCase() === entry.asset.toLowerCase();
8893
+ });
8894
+ }
8895
+ function resolveAtomicSpendCap(controls, requirement, defaultAsset) {
8896
+ if (controls === false) {
8897
+ return void 0;
8898
+ }
8899
+ const assetEntry = findSpendControlAssetEntry(controls, requirement, defaultAsset);
8900
+ if (assetEntry?.maxAmountPerPayment != null) {
8901
+ if (!isAtomicAmount(assetEntry.maxAmountPerPayment)) {
8902
+ throw new Error(
8903
+ `spendControls.allowedAssets[].maxAmountPerPayment must be an integer atomic amount, not a dollar value; got ${JSON.stringify(assetEntry.maxAmountPerPayment)}`
8904
+ );
8905
+ }
8906
+ return assetEntry.maxAmountPerPayment;
8907
+ }
8908
+ if (!defaultAsset || controls.maxAmountPerPayment === false) {
8909
+ return void 0;
8910
+ }
8911
+ const usdLimit = controls.maxAmountPerPayment ?? DEFAULT_MAX_AMOUNT_PER_PAYMENT;
8912
+ return convertToTokenAmount(parseMoney(usdLimit).amount, defaultAsset.decimals);
8913
+ }
8843
8914
  var x402Client = class _x402Client {
8844
8915
  /**
8845
8916
  * Creates a new x402Client instance.
@@ -8851,6 +8922,7 @@ var x402Client = class _x402Client {
8851
8922
  this.schemeClientHookAdapters = /* @__PURE__ */ new Map();
8852
8923
  this.policies = [];
8853
8924
  this.registeredExtensions = /* @__PURE__ */ new Map();
8925
+ this.spendControls = {};
8854
8926
  this.beforePaymentCreationHooks = [];
8855
8927
  this.afterPaymentCreationHooks = [];
8856
8928
  this.onPaymentCreationFailureHooks = [];
@@ -8875,6 +8947,9 @@ var x402Client = class _x402Client {
8875
8947
  config.policies?.forEach((policy) => {
8876
8948
  client2.registerPolicy(policy);
8877
8949
  });
8950
+ if (config.spendControls !== void 0) {
8951
+ client2.setSpendControls(config.spendControls);
8952
+ }
8878
8953
  return client2;
8879
8954
  }
8880
8955
  /**
@@ -8923,13 +8998,25 @@ var x402Client = class _x402Client {
8923
8998
  this.policies.push(policy);
8924
8999
  return this;
8925
9000
  }
9001
+ /**
9002
+ * Replace spend controls. Pass `false` to disable all spend controls.
9003
+ * When an object is passed, omitted `maxAmountPerPayment` still defaults to
9004
+ * {@link DEFAULT_MAX_AMOUNT_PER_PAYMENT}.
9005
+ *
9006
+ * @param controls - Spend control configuration, or `false` to disable
9007
+ * @returns This client for chaining
9008
+ */
9009
+ setSpendControls(controls) {
9010
+ this.spendControls = controls;
9011
+ return this;
9012
+ }
8926
9013
  /**
8927
9014
  * Registers a client extension that can enrich payment payloads.
8928
9015
  *
8929
9016
  * Extensions are invoked after the scheme creates the base payload and the
8930
- * payload is wrapped with extensions/resource/accepted data. If the extension's
8931
- * key is present in `paymentRequired.extensions`, the extension's
8932
- * `enrichPaymentPayload` hook is called to modify the payload.
9017
+ * payload is wrapped with extensions/resource/accepted data. Every registered
9018
+ * extension's `enrichPaymentPayload` hook is called to modify the payload.
9019
+ * Server-declared fields are preserved via merge after enrichment.
8933
9020
  *
8934
9021
  * @param extension - The client extension to register
8935
9022
  * @returns The x402Client instance for chaining
@@ -9048,7 +9135,14 @@ var x402Client = class _x402Client {
9048
9135
  const partialPayload = await schemeNetworkClient.createPaymentPayload(
9049
9136
  paymentRequired.x402Version,
9050
9137
  requirements,
9051
- { extensions: paymentRequired.extensions }
9138
+ {
9139
+ extensions: paymentRequired.extensions,
9140
+ maxAmountPerPayment: resolveAtomicSpendCap(
9141
+ this.spendControls,
9142
+ requirements,
9143
+ schemeNetworkClient.findDefaultAsset?.(requirements.asset, requirements.network)
9144
+ )
9145
+ }
9052
9146
  );
9053
9147
  let paymentPayload;
9054
9148
  if (partialPayload.x402Version == 1) {
@@ -9102,6 +9196,11 @@ var x402Client = class _x402Client {
9102
9196
  /**
9103
9197
  * Merges server-declared extensions with client extension echoes.
9104
9198
  * Client extension data may add fields, but server-declared fields remain intact.
9199
+ * For fields listed in `ADDITIVE_ARRAY_INFO_FIELDS` (e.g. builder-code `s`), a
9200
+ * conflicting array is concatenated with client entries first (so a downstream
9201
+ * length cap trims server entries rather than the client's) and duplicates
9202
+ * removed; a scalar on either side is treated as a single-element array. Every
9203
+ * other conflicting array keeps the server's value, same as any other scalar.
9105
9204
  *
9106
9205
  * @param serverExtensions - Extensions declared by the server in the 402 response
9107
9206
  * @param clientExtensions - Extensions provided by the client or scheme
@@ -9119,6 +9218,7 @@ var x402Client = class _x402Client {
9119
9218
  }
9120
9219
  const serverRecord = serverValue;
9121
9220
  const clientRecord = clientValue;
9221
+ const additiveFields = ADDITIVE_ARRAY_INFO_FIELDS[key];
9122
9222
  const extensionValue = { ...serverRecord };
9123
9223
  const pending = [{ target: extensionValue, source: clientRecord }];
9124
9224
  for (const item of pending) {
@@ -9133,6 +9233,14 @@ var x402Client = class _x402Client {
9133
9233
  });
9134
9234
  continue;
9135
9235
  }
9236
+ if (additiveFields?.has(fieldKey) && (Array.isArray(serverFieldValue) || Array.isArray(clientFieldValue))) {
9237
+ const serverArray = toComparableArray(serverFieldValue);
9238
+ const clientArray = toComparableArray(clientFieldValue);
9239
+ if (serverArray && clientArray) {
9240
+ item.target[fieldKey] = mergeArraysUnique(clientArray, serverArray);
9241
+ continue;
9242
+ }
9243
+ }
9136
9244
  if (!Object.prototype.hasOwnProperty.call(item.target, fieldKey)) {
9137
9245
  item.target[fieldKey] = clientFieldValue;
9138
9246
  }
@@ -9144,20 +9252,20 @@ var x402Client = class _x402Client {
9144
9252
  }
9145
9253
  /**
9146
9254
  * Enriches a payment payload by calling registered extension hooks.
9147
- * For each extension key present in the PaymentRequired response,
9148
- * invokes the corresponding extension's enrichPaymentPayload callback.
9255
+ * Invokes enrichPaymentPayload for every registered extension, then merges
9256
+ * server-declared extension fields back into the result.
9149
9257
  *
9150
9258
  * @param paymentPayload - The payment payload to enrich with extension data
9151
9259
  * @param paymentRequired - The PaymentRequired response containing extension declarations
9152
9260
  * @returns The enriched payment payload with extension data applied
9153
9261
  */
9154
9262
  async enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired) {
9155
- if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {
9263
+ if (this.registeredExtensions.size === 0) {
9156
9264
  return paymentPayload;
9157
9265
  }
9158
9266
  let enriched = paymentPayload;
9159
- for (const [key, extension] of this.registeredExtensions) {
9160
- if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {
9267
+ for (const [, extension] of this.registeredExtensions) {
9268
+ if (extension.enrichPaymentPayload) {
9161
9269
  enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);
9162
9270
  }
9163
9271
  }
@@ -9171,8 +9279,11 @@ var x402Client = class _x402Client {
9171
9279
  *
9172
9280
  * Selection process:
9173
9281
  * 1. Filter by registered schemes (network + scheme support)
9174
- * 2. Apply all registered policies in order
9175
- * 3. Use selector to choose final requirement
9282
+ * 2. Drop accepts with unrecognized `extra.paymentFlow`
9283
+ * 3. Enforce spend controls (allowlist, per-asset caps, USD cap on default assets)
9284
+ * 4. Apply all registered policies in order
9285
+ * 5. Prefer authorization (omit or explicit) over upfront/escrow when both remain
9286
+ * 6. Use selector to choose final requirement
9176
9287
  *
9177
9288
  * @param x402Version - The x402 protocol version
9178
9289
  * @param paymentRequirements - Array of available payment requirements
@@ -9199,15 +9310,119 @@ var x402Client = class _x402Client {
9199
9310
  schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
9200
9311
  })}`);
9201
9312
  }
9202
- let filteredRequirements = supportedPaymentRequirements;
9313
+ const recognizedFlowRequirements = supportedPaymentRequirements.filter((requirement) => {
9314
+ const flow = requirement.extra?.paymentFlow;
9315
+ return flow == null || flow === "authorization" || flow === "upfront" || flow === "escrow";
9316
+ });
9317
+ if (recognizedFlowRequirements.length === 0) {
9318
+ throw new Error(
9319
+ `No payment requirements with a recognized paymentFlow for x402 version: ${x402Version2}`
9320
+ );
9321
+ }
9322
+ let filteredRequirements = this.applySpendControls(
9323
+ x402Version2,
9324
+ recognizedFlowRequirements,
9325
+ clientSchemesByNetwork
9326
+ );
9203
9327
  for (const policy of this.policies) {
9204
9328
  filteredRequirements = policy(x402Version2, filteredRequirements);
9205
9329
  if (filteredRequirements.length === 0) {
9206
9330
  throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
9207
9331
  }
9208
9332
  }
9333
+ const authorizationAccepts = filteredRequirements.filter(
9334
+ (requirement) => requirement.extra?.paymentFlow == null || requirement.extra?.paymentFlow === "authorization"
9335
+ );
9336
+ if (authorizationAccepts.length > 0) {
9337
+ filteredRequirements = authorizationAccepts;
9338
+ }
9209
9339
  return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
9210
9340
  }
9341
+ /**
9342
+ * Filter by spend controls (default-asset allowlist → opt-in assets → caps).
9343
+ * Keeps any accept that fits so a mixed offer can still pay the affordable option.
9344
+ *
9345
+ * @param x402Version - Protocol version (v1 uses `maxAmountRequired`)
9346
+ * @param requirements - Post scheme/flow filter
9347
+ * @param clientSchemesByNetwork - Registered clients for this version
9348
+ * @returns Requirements that pass spend controls
9349
+ */
9350
+ applySpendControls(x402Version2, requirements, clientSchemesByNetwork) {
9351
+ const controls = this.spendControls;
9352
+ if (controls === false) {
9353
+ return requirements;
9354
+ }
9355
+ const rawAmountOf = (requirement) => x402Version2 === 1 ? requirement.maxAmountRequired : requirement.amount;
9356
+ const schemeFor = (requirement) => findByNetworkAndScheme(
9357
+ clientSchemesByNetwork,
9358
+ requirement.scheme,
9359
+ requirement.network
9360
+ );
9361
+ const defaultAssetFor = (requirement) => schemeFor(requirement)?.findDefaultAsset?.(requirement.asset, requirement.network);
9362
+ const findAssetEntry = (requirement) => findSpendControlAssetEntry(controls, requirement, defaultAssetFor(requirement));
9363
+ const allowAnyAsset = controls.allowedAssets === true;
9364
+ let filtered = allowAnyAsset ? requirements : requirements.filter((requirement) => {
9365
+ if (defaultAssetFor(requirement) != null) {
9366
+ return true;
9367
+ }
9368
+ return findAssetEntry(requirement) != null;
9369
+ });
9370
+ if (filtered.length === 0) {
9371
+ throw new Error(
9372
+ `All payment requirements were rejected by spendControls: only default assets or entries in spendControls.allowedAssets are allowed. Add an allowedAssets entry for non-default tokens, set allowedAssets: true, or set spendControls: false.`
9373
+ );
9374
+ }
9375
+ const usdLimit = controls.maxAmountPerPayment === false ? false : controls.maxAmountPerPayment ?? DEFAULT_MAX_AMOUNT_PER_PAYMENT;
9376
+ const beforeAmountCaps = filtered;
9377
+ let rejectedByAssetCap = false;
9378
+ let rejectedUsdSymbol;
9379
+ filtered = filtered.filter((requirement) => {
9380
+ const defaultAsset = defaultAssetFor(requirement);
9381
+ const assetEntry = findSpendControlAssetEntry(controls, requirement, defaultAsset);
9382
+ const cap = resolveAtomicSpendCap(controls, requirement, defaultAsset);
9383
+ if (cap === void 0) {
9384
+ return true;
9385
+ }
9386
+ const rawAmount = rawAmountOf(requirement);
9387
+ if (!isAtomicAmount(rawAmount)) {
9388
+ if (assetEntry?.maxAmountPerPayment != null) {
9389
+ rejectedByAssetCap = true;
9390
+ return false;
9391
+ }
9392
+ if (usdLimit === false) {
9393
+ return true;
9394
+ }
9395
+ const valueScaled = BigInt(convertToTokenAmount(rawAmount, 18));
9396
+ const capScaled = BigInt(convertToTokenAmount(parseMoney(usdLimit).amount, 18));
9397
+ const ok2 = valueScaled <= capScaled;
9398
+ if (!ok2) rejectedUsdSymbol = defaultAsset?.symbol;
9399
+ return ok2;
9400
+ }
9401
+ const ok = BigInt(rawAmount) <= BigInt(cap);
9402
+ if (!ok) {
9403
+ if (assetEntry?.maxAmountPerPayment != null) {
9404
+ rejectedByAssetCap = true;
9405
+ } else {
9406
+ rejectedUsdSymbol = defaultAsset?.symbol;
9407
+ }
9408
+ }
9409
+ return ok;
9410
+ });
9411
+ if (filtered.length === 0) {
9412
+ if (rejectedByAssetCap && beforeAmountCaps.every((requirement) => {
9413
+ const entry = findAssetEntry(requirement);
9414
+ return entry?.maxAmountPerPayment != null;
9415
+ })) {
9416
+ throw new Error(
9417
+ `All payment requirements were rejected by spendControls.allowedAssets maxAmountPerPayment. Raise the per-asset cap, or omit maxAmountPerPayment to allow uncapped (default assets then fall back to the top-level USD cap).`
9418
+ );
9419
+ }
9420
+ throw new Error(
9421
+ `All payment requirements were rejected by spendControls.maxAmountPerPayment (${String(usdLimit)}${rejectedUsdSymbol ? `, including ${rejectedUsdSymbol}` : ""}). Raise maxAmountPerPayment, set it to false to disable, set allowedAssets[].maxAmountPerPayment for a per-asset atomic cap, or set spendControls: false to disable all spend controls.`
9422
+ );
9423
+ }
9424
+ return filtered;
9425
+ }
9211
9426
  /**
9212
9427
  * Internal method to register a scheme client.
9213
9428
  *
@@ -9324,8 +9539,44 @@ var x402Client = class _x402Client {
9324
9539
  }
9325
9540
  }
9326
9541
  };
9542
+ function mergeArraysUnique(client2, server) {
9543
+ const merged = [];
9544
+ for (const item of [...client2, ...server]) {
9545
+ if (!merged.some((existing) => deepEqual(existing, item))) {
9546
+ merged.push(item);
9547
+ }
9548
+ }
9549
+ return merged;
9550
+ }
9327
9551
 
9328
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-MACPBXCT.mjs
9552
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-GPMYUGHX.mjs
9553
+ var EVM_NETWORK_CHAIN_ID_MAP = {
9554
+ ethereum: 1,
9555
+ sepolia: 11155111,
9556
+ abstract: 2741,
9557
+ "abstract-testnet": 11124,
9558
+ "base-sepolia": 84532,
9559
+ base: 8453,
9560
+ "avalanche-fuji": 43113,
9561
+ avalanche: 43114,
9562
+ iotex: 4689,
9563
+ sei: 1329,
9564
+ "sei-testnet": 1328,
9565
+ polygon: 137,
9566
+ "polygon-amoy": 80002,
9567
+ peaq: 3338,
9568
+ story: 1514,
9569
+ educhain: 41923,
9570
+ "skale-base-sepolia": 324705682,
9571
+ megaeth: 4326,
9572
+ monad: 143,
9573
+ "monad-testnet": 10143,
9574
+ stable: 988,
9575
+ "stable-testnet": 2201,
9576
+ celo: 42220,
9577
+ flare: 14
9578
+ };
9579
+ var NETWORKS = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);
9329
9580
  var authorizationTypes = {
9330
9581
  TransferWithAuthorization: [
9331
9582
  { name: "from", type: "address" },
@@ -9401,97 +9652,634 @@ var DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100000000n;
9401
9652
  var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
9402
9653
  var x402ExactPermit2ProxyAddress = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001";
9403
9654
 
9404
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-7KTOBWB2.mjs
9405
- var PAYMENT_INFO_TYPEHASH = keccak256(
9406
- new TextEncoder().encode(
9407
- "PaymentInfo(address operator,address payer,address receiver,address token,uint120 maxAmount,uint48 preApprovalExpiry,uint48 authorizationExpiry,uint48 refundExpiry,uint16 minFeeBps,uint16 maxFeeBps,address feeReceiver,uint256 salt)"
9408
- )
9409
- );
9410
-
9411
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-TW7Z65AO.mjs
9412
- function getEvmChainId(network) {
9413
- if (network.startsWith("eip155:")) {
9414
- const idStr = network.split(":")[1];
9415
- const chainId = parseInt(idStr, 10);
9416
- if (isNaN(chainId)) {
9417
- throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
9655
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-LQQ3M4DU.mjs
9656
+ var DEFAULT_ASSETS = {
9657
+ "eip155:8453": [
9658
+ {
9659
+ asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
9660
+ name: "USD Coin",
9661
+ version: "2",
9662
+ decimals: 6,
9663
+ symbol: "USDC"
9664
+ }
9665
+ ],
9666
+ // Base mainnet USDC
9667
+ "eip155:84532": [
9668
+ {
9669
+ asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
9670
+ name: "USDC",
9671
+ version: "2",
9672
+ decimals: 6,
9673
+ symbol: "USDC"
9674
+ }
9675
+ ],
9676
+ // Base Sepolia USDC
9677
+ "eip155:1": [
9678
+ {
9679
+ asset: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
9680
+ name: "USD Coin",
9681
+ version: "2",
9682
+ decimals: 6,
9683
+ symbol: "USDC"
9684
+ }
9685
+ ],
9686
+ // Ethereum mainnet USDC
9687
+ "eip155:43114": [
9688
+ {
9689
+ asset: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
9690
+ name: "USD Coin",
9691
+ version: "2",
9692
+ decimals: 6,
9693
+ symbol: "USDC"
9694
+ }
9695
+ ],
9696
+ // Avalanche C-Chain USDC
9697
+ "eip155:4326": [
9698
+ {
9699
+ asset: "0xFAfDdbb3FC7688494971a79cc65DCa3EF82079E7",
9700
+ name: "MegaUSD",
9701
+ version: "1",
9702
+ decimals: 18,
9703
+ symbol: "MegaUSD",
9704
+ assetTransferMethod: "permit2",
9705
+ supportsEip2612: true
9706
+ }
9707
+ ],
9708
+ // MegaETH mainnet MegaUSD (no EIP-3009, supports EIP-2612)
9709
+ "eip155:143": [
9710
+ {
9711
+ asset: "0x754704Bc059F8C67012fEd69BC8A327a5aafb603",
9712
+ name: "USDC",
9713
+ version: "2",
9714
+ decimals: 6,
9715
+ symbol: "USDC"
9716
+ }
9717
+ ],
9718
+ // Monad mainnet USDC
9719
+ "eip155:10143": [
9720
+ {
9721
+ asset: "0x534b2f3A21130d7a60830c2Df862319e593943A3",
9722
+ name: "USDC",
9723
+ version: "2",
9724
+ decimals: 6,
9725
+ symbol: "USDC"
9726
+ }
9727
+ ],
9728
+ // Monad testnet USDC
9729
+ "eip155:988": [
9730
+ {
9731
+ asset: "0x779Ded0c9e1022225f8E0630b35a9b54bE713736",
9732
+ name: "USDT0",
9733
+ version: "1",
9734
+ decimals: 6,
9735
+ symbol: "USDT0"
9736
+ }
9737
+ ],
9738
+ // Stable mainnet USDT0
9739
+ "eip155:2201": [
9740
+ {
9741
+ asset: "0x78Cf24370174180738C5B8E352B6D14c83a6c9A9",
9742
+ name: "USDT0",
9743
+ version: "1",
9744
+ decimals: 6,
9745
+ symbol: "USDT0"
9746
+ }
9747
+ ],
9748
+ // Stable testnet USDT0
9749
+ "eip155:137": [
9750
+ {
9751
+ asset: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
9752
+ name: "USD Coin",
9753
+ version: "2",
9754
+ decimals: 6,
9755
+ symbol: "USDC"
9756
+ }
9757
+ ],
9758
+ // Polygon mainnet USDC
9759
+ "eip155:42161": [
9760
+ {
9761
+ asset: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
9762
+ name: "USD Coin",
9763
+ version: "2",
9764
+ decimals: 6,
9765
+ symbol: "USDC"
9766
+ }
9767
+ ],
9768
+ // Arbitrum One USDC
9769
+ "eip155:421614": [
9770
+ {
9771
+ asset: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
9772
+ name: "USD Coin",
9773
+ version: "2",
9774
+ decimals: 6,
9775
+ symbol: "USDC"
9776
+ }
9777
+ ],
9778
+ // Arbitrum Sepolia USDC
9779
+ "eip155:31612": [
9780
+ {
9781
+ asset: "0xdD468A1DDc392dcdbEf6db6e34E89AA338F9F186",
9782
+ name: "Mezo USD",
9783
+ version: "1",
9784
+ decimals: 18,
9785
+ symbol: "mUSD",
9786
+ assetTransferMethod: "permit2",
9787
+ supportsEip2612: true
9788
+ }
9789
+ ],
9790
+ // Mezo mainnet mUSD (no EIP-3009, supports EIP-2612)
9791
+ "eip155:31611": [
9792
+ {
9793
+ asset: "0x118917a40FAF1CD7a13dB0Ef56C86De7973Ac503",
9794
+ name: "Mezo USD",
9795
+ version: "1",
9796
+ decimals: 18,
9797
+ symbol: "mUSD",
9798
+ assetTransferMethod: "permit2",
9799
+ supportsEip2612: true
9800
+ }
9801
+ ],
9802
+ // Mezo Testnet mUSD (no EIP-3009, supports EIP-2612)
9803
+ "eip155:723487": [
9804
+ {
9805
+ asset: "0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb",
9806
+ name: "Stable Coin",
9807
+ version: "1",
9808
+ decimals: 6,
9809
+ symbol: "SBC",
9810
+ assetTransferMethod: "permit2",
9811
+ supportsEip2612: true
9812
+ }
9813
+ ],
9814
+ // Radius Network SBC (no EIP-3009, supports EIP-2612)
9815
+ "eip155:72344": [
9816
+ {
9817
+ asset: "0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb",
9818
+ name: "Stable Coin",
9819
+ version: "1",
9820
+ decimals: 6,
9821
+ symbol: "SBC",
9822
+ assetTransferMethod: "permit2",
9823
+ supportsEip2612: true
9824
+ }
9825
+ ],
9826
+ // Radius Testnet SBC (no EIP-3009, supports EIP-2612)
9827
+ "eip155:36900": [
9828
+ {
9829
+ asset: "0x9cb8142aEBBcdc60AF7c97Af897A67A8f3CA71C2",
9830
+ name: "USDC.e",
9831
+ version: "2",
9832
+ decimals: 6,
9833
+ symbol: "USDC.e"
9834
+ }
9835
+ ],
9836
+ // ADI Chain USDC.e (EIP-3009 supported)
9837
+ "eip155:190415": [
9838
+ {
9839
+ asset: "0x401eCb1D350407f13ba348573E5630B83638E30D",
9840
+ name: "Bridged USDC",
9841
+ version: "2",
9842
+ decimals: 6,
9843
+ symbol: "USDC.e"
9844
+ }
9845
+ ],
9846
+ // HPP mainnet USDC.e
9847
+ "eip155:181228": [
9848
+ {
9849
+ asset: "0x401eCb1D350407f13ba348573E5630B83638E30D",
9850
+ name: "Bridged USDC",
9851
+ version: "2",
9852
+ decimals: 6,
9853
+ symbol: "USDC.e"
9854
+ }
9855
+ ],
9856
+ // HPP Sepolia USDC.e
9857
+ "eip155:50": [
9858
+ {
9859
+ asset: "0xfA2958CB79b0491CC627c1557F441eF849Ca8eb1",
9860
+ name: "USDC",
9861
+ version: "2",
9862
+ decimals: 6,
9863
+ symbol: "USDC"
9864
+ }
9865
+ ],
9866
+ // XDC Network mainnet USDC (Bridged USDC Standard, EIP-3009 supported)
9867
+ "eip155:51": [
9868
+ {
9869
+ asset: "0xb5AB69F7bBada22B28e79C8FFAECe55eF1c771D4",
9870
+ name: "USDC",
9871
+ version: "2",
9872
+ decimals: 6,
9873
+ symbol: "USDC"
9874
+ }
9875
+ ],
9876
+ // XDC Apothem testnet USDC (Bridged USDC Standard, EIP-3009 supported)
9877
+ "eip155:38833": [
9878
+ {
9879
+ asset: "0xA5b8BF902b2844dA17d4506cc827F7F1681735E7",
9880
+ name: "USDC",
9881
+ version: "1",
9882
+ decimals: 6,
9883
+ symbol: "USDC",
9884
+ assetTransferMethod: "permit2"
9885
+ }
9886
+ ],
9887
+ // Igra mainnet USDC (no EIP-3009, no EIP-2612)
9888
+ "eip155:14": [
9889
+ {
9890
+ asset: "0xe7cd86e13AC4309349F30B3435a9d337750fC82D",
9891
+ name: "USD\u20AE0",
9892
+ version: "1",
9893
+ decimals: 6,
9894
+ symbol: "USDT0"
9895
+ }
9896
+ ],
9897
+ // Flare mainnet USD₮0 (EIP-3009 supported)
9898
+ "eip155:42220": [
9899
+ {
9900
+ asset: "0xcebA9300f2b948710d2653dD7B07f33A8B32118C",
9901
+ name: "USDC",
9902
+ version: "2",
9903
+ decimals: 6,
9904
+ symbol: "USDC"
9905
+ },
9906
+ {
9907
+ asset: "0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",
9908
+ name: "Tether USD",
9909
+ version: "1",
9910
+ decimals: 6,
9911
+ symbol: "USDT"
9912
+ },
9913
+ {
9914
+ asset: "0xD2ab3C9A02DBBAB236BfEC45D1d755DF4267F771",
9915
+ name: "Tether America USD",
9916
+ version: "1",
9917
+ decimals: 6,
9918
+ symbol: "USAT"
9919
+ }
9920
+ ],
9921
+ // Celo mainnet USDC, USDT, USAT (EIP-3009 supported)
9922
+ "eip155:11142220": [
9923
+ {
9924
+ asset: "0x01C5C0122039549AD1493B8220cABEdD739BC44E",
9925
+ name: "USDC",
9926
+ version: "2",
9927
+ decimals: 6,
9928
+ symbol: "USDC"
9929
+ }
9930
+ ],
9931
+ // Celo Sepolia testnet USDC (EIP-3009 supported)
9932
+ "eip155:1329": [
9933
+ {
9934
+ asset: "0xe15fC38F6D8c56aF07bbCBe3BAf5708A2Bf42392",
9935
+ name: "USDC",
9936
+ version: "2",
9937
+ decimals: 6,
9938
+ symbol: "USDC"
9939
+ }
9940
+ ],
9941
+ // Sei mainnet USDC (EIP-3009 supported)
9942
+ "eip155:1328": [
9943
+ {
9944
+ asset: "0x4fCF1784B31630811181f670Aea7A7bEF803eaED",
9945
+ name: "USDC",
9946
+ version: "2",
9947
+ decimals: 6,
9948
+ symbol: "USDC"
9949
+ }
9950
+ ],
9951
+ // Sei testnet USDC (EIP-3009 supported)
9952
+ "eip155:5042": [
9953
+ {
9954
+ asset: "0x3600000000000000000000000000000000000000",
9955
+ name: "USDC",
9956
+ version: "2",
9957
+ decimals: 6,
9958
+ symbol: "USDC"
9959
+ }
9960
+ ],
9961
+ // Arc mainnet USDC (EIP-3009 supported)
9962
+ "eip155:5042002": [
9963
+ {
9964
+ asset: "0x3600000000000000000000000000000000000000",
9965
+ name: "USDC",
9966
+ version: "2",
9967
+ decimals: 6,
9968
+ symbol: "USDC"
9418
9969
  }
9419
- return chainId;
9970
+ ]
9971
+ // Arc Testnet USDC (EIP-3009 supported)
9972
+ };
9973
+ function resolveNetworkKey(network) {
9974
+ if (network in DEFAULT_ASSETS) {
9975
+ return network;
9420
9976
  }
9421
- throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
9422
- }
9423
- function getCrypto() {
9424
- const cryptoObj = globalThis.crypto;
9425
- if (!cryptoObj) {
9426
- throw new Error("Crypto API not available");
9977
+ const chainId = EVM_NETWORK_CHAIN_ID_MAP[network];
9978
+ if (chainId !== void 0) {
9979
+ return `eip155:${chainId}`;
9427
9980
  }
9428
- return cryptoObj;
9429
- }
9430
- function createNonce() {
9431
- return toHex(getCrypto().getRandomValues(new Uint8Array(32)));
9432
- }
9433
- function createPermit2Nonce() {
9434
- const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));
9435
- return BigInt(toHex(randomBytes)).toString();
9981
+ return network;
9436
9982
  }
9983
+ var findDefaultAsset = (asset, network) => {
9984
+ const key = resolveNetworkKey(network);
9985
+ const assets = DEFAULT_ASSETS[key];
9986
+ if (!assets) {
9987
+ return void 0;
9988
+ }
9989
+ const normalized = asset.toLowerCase();
9990
+ return assets.find((entry) => entry.asset.toLowerCase() === normalized);
9991
+ };
9437
9992
 
9438
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-BQS2RW2S.mjs
9439
- var CHANNEL_CONFIG_TYPEHASH = keccak256(
9993
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-KPBDMMIU.mjs
9994
+ var SALT_BINDING_TYPEHASH = keccak256(
9440
9995
  toBytes(
9441
- "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
9996
+ "x402AuthCaptureSaltBinding(address receiverAuthorizer,address policy,uint256 saltNonce)"
9997
+ )
9998
+ );
9999
+ var PAYMENT_INFO_TYPEHASH = keccak256(
10000
+ new TextEncoder().encode(
10001
+ "PaymentInfo(address operator,address payer,address receiver,address token,uint120 maxAmount,uint48 preApprovalExpiry,uint48 authorizationExpiry,uint48 refundExpiry,uint16 minFeeBps,uint16 maxFeeBps,address feeReceiver,uint256 salt)"
9442
10002
  )
9443
10003
  );
9444
10004
 
9445
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-27MWX225.mjs
9446
- var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
9447
- var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
9448
- var ERC20_APPROVAL_GAS_SPONSORING_VERSION = "1";
9449
- async function signEip2612Permit(signer, tokenAddress, tokenName, tokenVersion, chainId, deadline, permittedAmount) {
9450
- const owner = signer.address;
9451
- const spender = getAddress2(PERMIT2_ADDRESS);
9452
- const nonce = await signer.readContract({
9453
- address: tokenAddress,
9454
- abi: eip2612NoncesAbi,
9455
- functionName: "nonces",
9456
- args: [owner]
9457
- });
9458
- const domain = {
9459
- name: tokenName,
9460
- version: tokenVersion,
9461
- chainId,
9462
- verifyingContract: tokenAddress
9463
- };
9464
- const approvalAmount = BigInt(permittedAmount);
9465
- const message = {
9466
- owner,
9467
- spender,
9468
- value: approvalAmount,
9469
- nonce,
9470
- deadline: BigInt(deadline)
9471
- };
9472
- const signature = await signer.signTypedData({
9473
- domain,
9474
- types: eip2612PermitTypes,
9475
- primaryType: "Permit",
9476
- message
9477
- });
9478
- return {
9479
- from: owner,
9480
- asset: tokenAddress,
9481
- spender,
9482
- amount: approvalAmount.toString(),
9483
- nonce: nonce.toString(),
9484
- deadline,
9485
- signature,
9486
- version: "1"
9487
- };
10005
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-W6ON4LG2.mjs
10006
+ function buildErc3009DepositNonce(channelId, salt) {
10007
+ return keccak256(
10008
+ encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [channelId, BigInt(salt)])
10009
+ );
9488
10010
  }
9489
- async function signErc20ApprovalTransaction(signer, tokenAddress, chainId) {
9490
- const from = signer.address;
9491
- const spender = getAddress2(PERMIT2_ADDRESS);
9492
- const data = encodeFunctionData({
9493
- abi: erc20ApproveAbi,
9494
- functionName: "approve",
10011
+
10012
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-H25OEB2U.mjs
10013
+ var channelConfigComponents = [
10014
+ { name: "payer", type: "address" },
10015
+ { name: "payerAuthorizer", type: "address" },
10016
+ { name: "receiver", type: "address" },
10017
+ { name: "receiverAuthorizer", type: "address" },
10018
+ { name: "token", type: "address" },
10019
+ { name: "withdrawDelay", type: "uint40" },
10020
+ { name: "salt", type: "bytes32" }
10021
+ ];
10022
+ var voucherClaimComponents = [
10023
+ {
10024
+ name: "voucher",
10025
+ type: "tuple",
10026
+ components: [
10027
+ {
10028
+ name: "channel",
10029
+ type: "tuple",
10030
+ components: channelConfigComponents
10031
+ },
10032
+ { name: "maxClaimableAmount", type: "uint128" }
10033
+ ]
10034
+ },
10035
+ { name: "signature", type: "bytes" },
10036
+ { name: "totalClaimed", type: "uint128" }
10037
+ ];
10038
+ var batchSettlementABI = [
10039
+ {
10040
+ type: "function",
10041
+ name: "multicall",
10042
+ inputs: [{ name: "data", type: "bytes[]" }],
10043
+ outputs: [{ name: "results", type: "bytes[]" }],
10044
+ stateMutability: "nonpayable"
10045
+ },
10046
+ {
10047
+ type: "function",
10048
+ name: "deposit",
10049
+ inputs: [
10050
+ { name: "config", type: "tuple", components: channelConfigComponents },
10051
+ { name: "amount", type: "uint128" },
10052
+ { name: "collector", type: "address" },
10053
+ { name: "collectorData", type: "bytes" }
10054
+ ],
10055
+ outputs: [],
10056
+ stateMutability: "nonpayable"
10057
+ },
10058
+ {
10059
+ type: "function",
10060
+ name: "claim",
10061
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
10062
+ outputs: [],
10063
+ stateMutability: "nonpayable"
10064
+ },
10065
+ {
10066
+ type: "function",
10067
+ name: "claimWithSignature",
10068
+ inputs: [
10069
+ { name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents },
10070
+ { name: "authorizerSignature", type: "bytes" }
10071
+ ],
10072
+ outputs: [],
10073
+ stateMutability: "nonpayable"
10074
+ },
10075
+ {
10076
+ type: "function",
10077
+ name: "settle",
10078
+ inputs: [
10079
+ { name: "receiver", type: "address" },
10080
+ { name: "token", type: "address" }
10081
+ ],
10082
+ outputs: [],
10083
+ stateMutability: "nonpayable"
10084
+ },
10085
+ {
10086
+ type: "function",
10087
+ name: "initiateWithdraw",
10088
+ inputs: [
10089
+ { name: "config", type: "tuple", components: channelConfigComponents },
10090
+ { name: "amount", type: "uint128" }
10091
+ ],
10092
+ outputs: [],
10093
+ stateMutability: "nonpayable"
10094
+ },
10095
+ {
10096
+ type: "function",
10097
+ name: "finalizeWithdraw",
10098
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
10099
+ outputs: [],
10100
+ stateMutability: "nonpayable"
10101
+ },
10102
+ {
10103
+ type: "function",
10104
+ name: "refund",
10105
+ inputs: [
10106
+ { name: "config", type: "tuple", components: channelConfigComponents },
10107
+ { name: "amount", type: "uint128" }
10108
+ ],
10109
+ outputs: [],
10110
+ stateMutability: "nonpayable"
10111
+ },
10112
+ {
10113
+ type: "function",
10114
+ name: "refundWithSignature",
10115
+ inputs: [
10116
+ { name: "config", type: "tuple", components: channelConfigComponents },
10117
+ { name: "amount", type: "uint128" },
10118
+ { name: "nonce", type: "uint256" },
10119
+ { name: "receiverAuthorizerSignature", type: "bytes" }
10120
+ ],
10121
+ outputs: [],
10122
+ stateMutability: "nonpayable"
10123
+ },
10124
+ {
10125
+ type: "function",
10126
+ name: "getChannelId",
10127
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
10128
+ outputs: [{ name: "", type: "bytes32" }],
10129
+ stateMutability: "view"
10130
+ },
10131
+ {
10132
+ type: "function",
10133
+ name: "CHANNEL_CONFIG_TYPEHASH",
10134
+ inputs: [],
10135
+ outputs: [{ name: "", type: "bytes32" }],
10136
+ stateMutability: "view"
10137
+ },
10138
+ {
10139
+ type: "function",
10140
+ name: "channels",
10141
+ inputs: [{ name: "channelId", type: "bytes32" }],
10142
+ outputs: [
10143
+ { name: "balance", type: "uint128" },
10144
+ { name: "totalClaimed", type: "uint128" }
10145
+ ],
10146
+ stateMutability: "view"
10147
+ },
10148
+ {
10149
+ type: "function",
10150
+ name: "pendingWithdrawals",
10151
+ inputs: [{ name: "channelId", type: "bytes32" }],
10152
+ outputs: [
10153
+ { name: "amount", type: "uint128" },
10154
+ { name: "initiatedAt", type: "uint40" }
10155
+ ],
10156
+ stateMutability: "view"
10157
+ },
10158
+ {
10159
+ type: "function",
10160
+ name: "receivers",
10161
+ inputs: [
10162
+ { name: "receiver", type: "address" },
10163
+ { name: "token", type: "address" }
10164
+ ],
10165
+ outputs: [
10166
+ { name: "totalClaimed", type: "uint128" },
10167
+ { name: "totalSettled", type: "uint128" }
10168
+ ],
10169
+ stateMutability: "view"
10170
+ },
10171
+ {
10172
+ type: "function",
10173
+ name: "getVoucherDigest",
10174
+ inputs: [
10175
+ { name: "channelId", type: "bytes32" },
10176
+ { name: "maxClaimableAmount", type: "uint128" }
10177
+ ],
10178
+ outputs: [{ name: "", type: "bytes32" }],
10179
+ stateMutability: "view"
10180
+ },
10181
+ {
10182
+ type: "function",
10183
+ name: "getRefundDigest",
10184
+ inputs: [
10185
+ { name: "channelId", type: "bytes32" },
10186
+ { name: "nonce", type: "uint256" },
10187
+ { name: "amount", type: "uint128" }
10188
+ ],
10189
+ outputs: [{ name: "", type: "bytes32" }],
10190
+ stateMutability: "view"
10191
+ },
10192
+ {
10193
+ type: "function",
10194
+ name: "refundNonce",
10195
+ inputs: [{ name: "channelId", type: "bytes32" }],
10196
+ outputs: [{ name: "", type: "uint256" }],
10197
+ stateMutability: "view"
10198
+ },
10199
+ {
10200
+ type: "function",
10201
+ name: "getClaimBatchDigest",
10202
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
10203
+ outputs: [{ name: "", type: "bytes32" }],
10204
+ stateMutability: "view"
10205
+ },
10206
+ {
10207
+ type: "event",
10208
+ name: "Settled",
10209
+ inputs: [
10210
+ { name: "receiver", type: "address", indexed: true },
10211
+ { name: "token", type: "address", indexed: true },
10212
+ { name: "sender", type: "address", indexed: true },
10213
+ { name: "amount", type: "uint128", indexed: false }
10214
+ ],
10215
+ anonymous: false
10216
+ }
10217
+ ];
10218
+
10219
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-U4HCGTLU.mjs
10220
+ function isObject(payload) {
10221
+ return typeof payload === "object" && payload !== null;
10222
+ }
10223
+ function isVoucherFields(payload) {
10224
+ return isObject(payload) && "channelId" in payload && "maxClaimableAmount" in payload && "signature" in payload;
10225
+ }
10226
+ function isBatchSettlementDepositPayload(payload) {
10227
+ return isObject(payload) && payload.type === "deposit" && "channelConfig" in payload && isVoucherFields(payload.voucher) && isObject(payload.deposit) && typeof payload.deposit.amount === "string" && isObject(payload.deposit.authorization);
10228
+ }
10229
+ function isBatchSettlementRefundPayload(payload) {
10230
+ return isObject(payload) && payload.type === "refund" && "channelConfig" in payload && isVoucherFields(payload.voucher);
10231
+ }
10232
+
10233
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-X4BYNI7R.mjs
10234
+ var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
10235
+ var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
10236
+ var ERC20_APPROVAL_GAS_SPONSORING_VERSION = "1";
10237
+ async function signEip2612Permit(signer, tokenAddress, tokenName, tokenVersion, chainId, deadline, permittedAmount) {
10238
+ const owner = signer.address;
10239
+ const spender = getAddress2(PERMIT2_ADDRESS);
10240
+ const nonce = await signer.readContract({
10241
+ address: tokenAddress,
10242
+ abi: eip2612NoncesAbi,
10243
+ functionName: "nonces",
10244
+ args: [owner]
10245
+ });
10246
+ const domain = {
10247
+ name: tokenName,
10248
+ version: tokenVersion,
10249
+ chainId,
10250
+ verifyingContract: tokenAddress
10251
+ };
10252
+ const approvalAmount = BigInt(permittedAmount);
10253
+ const message = {
10254
+ owner,
10255
+ spender,
10256
+ value: approvalAmount,
10257
+ nonce,
10258
+ deadline: BigInt(deadline)
10259
+ };
10260
+ const signature = await signer.signTypedData({
10261
+ domain,
10262
+ types: eip2612PermitTypes,
10263
+ primaryType: "Permit",
10264
+ message
10265
+ });
10266
+ return {
10267
+ from: owner,
10268
+ asset: tokenAddress,
10269
+ spender,
10270
+ amount: approvalAmount.toString(),
10271
+ nonce: nonce.toString(),
10272
+ deadline,
10273
+ signature,
10274
+ version: "1"
10275
+ };
10276
+ }
10277
+ async function signErc20ApprovalTransaction(signer, tokenAddress, chainId) {
10278
+ const from = signer.address;
10279
+ const spender = getAddress2(PERMIT2_ADDRESS);
10280
+ const data = encodeFunctionData({
10281
+ abi: erc20ApproveAbi,
10282
+ functionName: "approve",
9495
10283
  args: [spender, maxUint256]
9496
10284
  });
9497
10285
  const nonce = await signer.getTransactionCount({ address: from });
@@ -9668,33 +10456,873 @@ async function trySignErc20ApprovalExtension(signer, options, requirements, cont
9668
10456
  };
9669
10457
  }
9670
10458
 
9671
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-2GHXG5WB.mjs
9672
- var EVM_NETWORK_CHAIN_ID_MAP = {
9673
- ethereum: 1,
9674
- sepolia: 11155111,
9675
- abstract: 2741,
9676
- "abstract-testnet": 11124,
9677
- "base-sepolia": 84532,
9678
- base: 8453,
9679
- "avalanche-fuji": 43113,
9680
- avalanche: 43114,
9681
- iotex: 4689,
9682
- sei: 1329,
9683
- "sei-testnet": 1328,
9684
- polygon: 137,
9685
- "polygon-amoy": 80002,
9686
- peaq: 3338,
9687
- story: 1514,
9688
- educhain: 41923,
9689
- "skale-base-sepolia": 324705682,
9690
- megaeth: 4326,
9691
- monad: 143,
9692
- stable: 988,
9693
- "stable-testnet": 2201
10459
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-QJHO4KEV.mjs
10460
+ async function signVoucher(signer, channelId, maxClaimableAmount, network) {
10461
+ const chainId = getEvmChainId(network);
10462
+ const signature = await signer.signTypedData({
10463
+ domain: getBatchSettlementEip712Domain(chainId),
10464
+ types: voucherTypes,
10465
+ primaryType: "Voucher",
10466
+ message: {
10467
+ channelId,
10468
+ maxClaimableAmount: BigInt(maxClaimableAmount)
10469
+ }
10470
+ });
10471
+ return {
10472
+ channelId,
10473
+ maxClaimableAmount,
10474
+ signature
10475
+ };
10476
+ }
10477
+ async function createBatchSettlementEIP3009DepositPayload(signer, x402Version2, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
10478
+ const salt = createNonce();
10479
+ const now = Math.floor(Date.now() / 1e3);
10480
+ const chainId = getEvmChainId(paymentRequirements.network);
10481
+ if (!paymentRequirements.extra?.name || !paymentRequirements.extra?.version) {
10482
+ throw new Error(
10483
+ `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`
10484
+ );
10485
+ }
10486
+ const { name, version } = paymentRequirements.extra;
10487
+ const channelId = computeChannelId(channelConfig, paymentRequirements.network);
10488
+ const erc3009Nonce = buildErc3009DepositNonce(channelId, salt);
10489
+ const signature = await signer.signTypedData({
10490
+ domain: {
10491
+ name,
10492
+ version,
10493
+ chainId,
10494
+ verifyingContract: getAddress2(paymentRequirements.asset)
10495
+ },
10496
+ types: receiveAuthorizationTypes,
10497
+ primaryType: "ReceiveWithAuthorization",
10498
+ message: {
10499
+ from: getAddress2(signer.address),
10500
+ to: getAddress2(ERC3009_DEPOSIT_COLLECTOR_ADDRESS),
10501
+ value: BigInt(depositAmount),
10502
+ validAfter: BigInt(0),
10503
+ validBefore: BigInt(now + paymentRequirements.maxTimeoutSeconds),
10504
+ nonce: erc3009Nonce
10505
+ }
10506
+ });
10507
+ const vSigner = voucherSigner ?? signer;
10508
+ const voucher = await signVoucher(
10509
+ vSigner,
10510
+ channelId,
10511
+ maxClaimableAmount,
10512
+ paymentRequirements.network
10513
+ );
10514
+ const payload = {
10515
+ type: "deposit",
10516
+ channelConfig,
10517
+ voucher,
10518
+ deposit: {
10519
+ amount: depositAmount,
10520
+ authorization: {
10521
+ erc3009Authorization: {
10522
+ validAfter: "0",
10523
+ validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
10524
+ salt,
10525
+ signature
10526
+ }
10527
+ }
10528
+ }
10529
+ };
10530
+ return {
10531
+ x402Version: x402Version2,
10532
+ payload
10533
+ };
10534
+ }
10535
+ var InMemoryClientChannelStorage = class {
10536
+ constructor() {
10537
+ this.channels = /* @__PURE__ */ new Map();
10538
+ }
10539
+ /**
10540
+ * Returns the channel record for `key` if present.
10541
+ *
10542
+ * @param key - Channel storage key (a canonical `bytes32` channel id).
10543
+ * @returns Persisted context or undefined.
10544
+ */
10545
+ async get(key) {
10546
+ return this.channels.get(normalizeChannelId(key));
10547
+ }
10548
+ /**
10549
+ * Stores or replaces the channel record for `key`.
10550
+ *
10551
+ * @param key - Channel storage key (a canonical `bytes32` channel id).
10552
+ * @param context - Channel fields to persist.
10553
+ * @returns Resolves when stored.
10554
+ */
10555
+ async set(key, context) {
10556
+ this.channels.set(normalizeChannelId(key), context);
10557
+ }
10558
+ /**
10559
+ * Removes the channel record for `key` if it exists.
10560
+ *
10561
+ * @param key - Channel storage key (a canonical `bytes32` channel id).
10562
+ * @returns Resolves when removed.
10563
+ */
10564
+ async delete(key) {
10565
+ this.channels.delete(normalizeChannelId(key));
10566
+ }
10567
+ };
10568
+ var DEFAULT_SALT = "0x0000000000000000000000000000000000000000000000000000000000000000";
10569
+ function isBatchSettlementEvmSchemeOptions(o) {
10570
+ return o !== void 0 && typeof o === "object" && ("storage" in o || "depositPolicy" in o || "depositStrategy" in o || "salt" in o || "payerAuthorizer" in o || "rpcUrl" in o || "voucherSigner" in o);
10571
+ }
10572
+ function resolveClientOptions(second) {
10573
+ if (second === void 0) {
10574
+ return { storage: new InMemoryClientChannelStorage(), salt: DEFAULT_SALT };
10575
+ }
10576
+ if (isBatchSettlementEvmSchemeOptions(second)) {
10577
+ return {
10578
+ storage: second.storage ?? new InMemoryClientChannelStorage(),
10579
+ depositPolicy: second.depositPolicy,
10580
+ depositStrategy: second.depositStrategy,
10581
+ salt: second.salt ?? DEFAULT_SALT,
10582
+ payerAuthorizer: second.payerAuthorizer,
10583
+ voucherSigner: second.voucherSigner,
10584
+ extensionRpcOptions: second.rpcUrl ? { rpcUrl: second.rpcUrl } : void 0
10585
+ };
10586
+ }
10587
+ return {
10588
+ storage: new InMemoryClientChannelStorage(),
10589
+ depositPolicy: second,
10590
+ salt: DEFAULT_SALT
10591
+ };
10592
+ }
10593
+ function validateDepositPolicy(policy) {
10594
+ if (!policy) return;
10595
+ const m = policy.depositMultiplier;
10596
+ if (m !== void 0 && (!Number.isInteger(m) || m < 3)) {
10597
+ throw new Error("depositMultiplier must be an integer >= 3");
10598
+ }
10599
+ }
10600
+ function parseAnnouncedMinDeposit(value, requestAmount) {
10601
+ if (typeof value !== "string" || !/^\d+$/.test(value)) {
10602
+ return void 0;
10603
+ }
10604
+ const parsed = BigInt(value);
10605
+ if (parsed <= 0n || parsed < requestAmount) {
10606
+ return void 0;
10607
+ }
10608
+ return parsed;
10609
+ }
10610
+ function maxDepositFromSpendCap(maxAmountPerPayment, depositMultiplier = 5) {
10611
+ if (typeof maxAmountPerPayment !== "string" || !/^\d+$/.test(maxAmountPerPayment) || BigInt(maxAmountPerPayment) <= 0n) {
10612
+ return void 0;
10613
+ }
10614
+ return BigInt(maxAmountPerPayment) * BigInt(depositMultiplier);
10615
+ }
10616
+ function applyMaxDeposit(deposit, needed, maxDeposit) {
10617
+ if (maxDeposit === void 0) {
10618
+ return deposit.toString();
10619
+ }
10620
+ if (needed > maxDeposit) {
10621
+ throw new Error(
10622
+ `Required deposit ${needed.toString()} exceeds depositMultiplier \xD7 spendControls.maxAmountPerPayment (${maxDeposit.toString()}). Raise maxAmountPerPayment or depositMultiplier.`
10623
+ );
10624
+ }
10625
+ return (deposit > maxDeposit ? maxDeposit : deposit).toString();
10626
+ }
10627
+ function depositAmountForRequest(policy, requestAmount, needed, extra, maxDeposit) {
10628
+ const announced = parseAnnouncedMinDeposit(extra?.minDeposit, requestAmount);
10629
+ const multiplier = BigInt(policy?.depositMultiplier ?? 5);
10630
+ const target = announced ?? multiplier * requestAmount;
10631
+ const deposit = needed > target ? needed : target;
10632
+ return applyMaxDeposit(deposit, needed, maxDeposit);
10633
+ }
10634
+ function buildChannelConfig(deps, paymentRequirements) {
10635
+ const extra = paymentRequirements.extra;
10636
+ const receiverAuthorizer = extra?.receiverAuthorizer;
10637
+ if (!receiverAuthorizer || getAddress2(receiverAuthorizer) === "0x0000000000000000000000000000000000000000") {
10638
+ throw new Error("Payment requirements must include a non-zero extra.receiverAuthorizer");
10639
+ }
10640
+ return {
10641
+ payer: deps.signer.address,
10642
+ payerAuthorizer: getAddress2(
10643
+ deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
10644
+ ),
10645
+ receiver: paymentRequirements.payTo,
10646
+ receiverAuthorizer: getAddress2(receiverAuthorizer),
10647
+ token: paymentRequirements.asset,
10648
+ withdrawDelay: typeof extra?.withdrawDelay === "number" ? extra.withdrawDelay : MIN_WITHDRAW_DELAY,
10649
+ salt: deps.salt
10650
+ };
10651
+ }
10652
+ async function updateChannelFromSettle(storage, input) {
10653
+ const { server, local } = input;
10654
+ let chargedAmount = 0n;
10655
+ if (server.chargedAmount !== void 0) {
10656
+ if (!/^\d+$/.test(server.chargedAmount)) {
10657
+ throw new Error("invalid chargedAmount: not a non-negative integer");
10658
+ }
10659
+ chargedAmount = BigInt(server.chargedAmount);
10660
+ }
10661
+ const requestAmount = BigInt(local.requestAmount);
10662
+ if (chargedAmount > requestAmount) {
10663
+ throw new Error("settle response chargedAmount exceeds PaymentRequirements.amount");
10664
+ }
10665
+ const key = local.channelId.toLowerCase();
10666
+ const previous = await storage.get(key);
10667
+ const depositAmount = local.depositAmount === void 0 ? void 0 : BigInt(local.depositAmount);
10668
+ if (!previous && chargedAmount === 0n && depositAmount === void 0) {
10669
+ return;
10670
+ }
10671
+ const nextChargedCumulative = BigInt(previous?.chargedCumulativeAmount ?? "0") + chargedAmount;
10672
+ if (server.chargedCumulativeAmount !== void 0) {
10673
+ if (!/^\d+$/.test(server.chargedCumulativeAmount) || BigInt(server.chargedCumulativeAmount) !== nextChargedCumulative) {
10674
+ return;
10675
+ }
10676
+ }
10677
+ const next = { ...previous ?? {} };
10678
+ next.chargedCumulativeAmount = nextChargedCumulative.toString();
10679
+ if (depositAmount !== void 0) {
10680
+ next.balance = (BigInt(previous?.balance ?? "0") + depositAmount).toString();
10681
+ }
10682
+ await storage.set(key, next);
10683
+ }
10684
+ async function updateChannelAfterRefund(storage, channelKey, refundAmount) {
10685
+ if (refundAmount === void 0) {
10686
+ await storage.delete(channelKey);
10687
+ return;
10688
+ }
10689
+ const amount = BigInt(refundAmount);
10690
+ const previous = await storage.get(channelKey);
10691
+ const previousBalance = BigInt(previous?.balance ?? "0");
10692
+ const chargedCumulativeAmount = BigInt(previous?.chargedCumulativeAmount ?? "0");
10693
+ const refundableBalance = previousBalance > chargedCumulativeAmount ? previousBalance - chargedCumulativeAmount : 0n;
10694
+ if (amount >= refundableBalance) {
10695
+ await storage.delete(channelKey);
10696
+ return;
10697
+ }
10698
+ const next = { ...previous ?? {} };
10699
+ next.balance = (previousBalance - amount).toString();
10700
+ await storage.set(channelKey, next);
10701
+ }
10702
+ async function recoverChannel(deps, paymentRequirements) {
10703
+ if (!deps.signer.readContract) {
10704
+ throw new Error("recoverChannel requires ClientEvmSigner.readContract");
10705
+ }
10706
+ const config = buildChannelConfig(deps, paymentRequirements);
10707
+ const channelId = computeChannelId(config, paymentRequirements.network);
10708
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
10709
+ deps.signer,
10710
+ channelId
10711
+ );
10712
+ const ctx = {
10713
+ chargedCumulativeAmount: chTotalClaimed.toString(),
10714
+ balance: chBalance.toString(),
10715
+ totalClaimed: chTotalClaimed.toString()
10716
+ };
10717
+ await deps.storage.set(channelId.toLowerCase(), ctx);
10718
+ return ctx;
10719
+ }
10720
+ async function readChannelBalanceAndTotalClaimed(signer, channelId) {
10721
+ if (!signer.readContract) {
10722
+ throw new Error("readChannelBalanceAndTotalClaimed requires ClientEvmSigner.readContract");
10723
+ }
10724
+ return await signer.readContract({
10725
+ address: BATCH_SETTLEMENT_ADDRESS,
10726
+ abi: batchSettlementABI,
10727
+ functionName: "channels",
10728
+ args: [channelId]
10729
+ });
10730
+ }
10731
+ async function processCorrectivePaymentRequired(deps, paymentRequired) {
10732
+ if (paymentRequired.error !== ErrCumulativeAmountMismatch && paymentRequired.error !== ErrCumulativeAmountBelowClaimed) {
10733
+ return false;
10734
+ }
10735
+ const accept = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
10736
+ if (!accept) {
10737
+ return false;
10738
+ }
10739
+ const channelState = accept.extra.channelState;
10740
+ const voucherState = accept.extra.voucherState;
10741
+ const hasSig = channelState?.chargedCumulativeAmount !== void 0 && voucherState?.signedMaxClaimable !== void 0 && voucherState.signature !== void 0;
10742
+ if (!hasSig) {
10743
+ return recoverFromOnChainState(deps, accept);
10744
+ }
10745
+ return recoverFromSignature(deps, accept, channelState, voucherState);
10746
+ }
10747
+ async function recoverFromSignature(deps, accept, channelState, voucherState) {
10748
+ const chargedRaw = channelState.chargedCumulativeAmount;
10749
+ const signedRaw = voucherState.signedMaxClaimable;
10750
+ const sig = voucherState.signature;
10751
+ const charged = BigInt(String(chargedRaw));
10752
+ const signed = BigInt(String(signedRaw));
10753
+ if (charged > signed) {
10754
+ return false;
10755
+ }
10756
+ const config = buildChannelConfig(deps, accept);
10757
+ const channelId = computeChannelId(config, accept.network);
10758
+ if (!deps.signer.readContract) {
10759
+ return false;
10760
+ }
10761
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
10762
+ deps.signer,
10763
+ channelId
10764
+ );
10765
+ if (charged < chTotalClaimed) {
10766
+ return false;
10767
+ }
10768
+ const chainId = getEvmChainId(accept.network);
10769
+ const recovered = await recoverTypedDataAddress({
10770
+ domain: getBatchSettlementEip712Domain(chainId),
10771
+ types: voucherTypes,
10772
+ primaryType: "Voucher",
10773
+ message: {
10774
+ channelId,
10775
+ maxClaimableAmount: signed
10776
+ },
10777
+ signature: sig
10778
+ });
10779
+ const expectedSigner = getAddress2(
10780
+ deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
10781
+ );
10782
+ if (recovered.toLowerCase() !== expectedSigner.toLowerCase()) {
10783
+ return false;
10784
+ }
10785
+ const ctx = {
10786
+ chargedCumulativeAmount: charged.toString(),
10787
+ signedMaxClaimable: signed.toString(),
10788
+ signature: sig,
10789
+ balance: chBalance.toString(),
10790
+ totalClaimed: chTotalClaimed.toString()
10791
+ };
10792
+ await deps.storage.set(channelId.toLowerCase(), ctx);
10793
+ return true;
10794
+ }
10795
+ async function recoverFromOnChainState(deps, accept) {
10796
+ if (!deps.signer.readContract) {
10797
+ return false;
10798
+ }
10799
+ const config = buildChannelConfig(deps, accept);
10800
+ const channelId = computeChannelId(config, accept.network);
10801
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
10802
+ deps.signer,
10803
+ channelId
10804
+ );
10805
+ const ctx = {
10806
+ chargedCumulativeAmount: chTotalClaimed.toString(),
10807
+ balance: chBalance.toString(),
10808
+ totalClaimed: chTotalClaimed.toString()
10809
+ };
10810
+ await deps.storage.set(channelId.toLowerCase(), ctx);
10811
+ return true;
10812
+ }
10813
+ function createBatchSettlementClientHooks(deps) {
10814
+ return {
10815
+ onPaymentResponse: async (ctx) => {
10816
+ const settleResponse = ctx.settleResponse;
10817
+ if (settleResponse) {
10818
+ if (!settleResponse.success) {
10819
+ return;
10820
+ }
10821
+ const payload = ctx.paymentPayload.payload;
10822
+ const channelId = computeChannelId(
10823
+ buildChannelConfig(deps, ctx.requirements),
10824
+ ctx.requirements.network
10825
+ );
10826
+ if (isBatchSettlementRefundPayload(payload)) {
10827
+ await updateChannelAfterRefund(deps.storage, channelId.toLowerCase(), payload.amount);
10828
+ return;
10829
+ }
10830
+ const chargedAmount = settleResponse.extra?.chargedAmount;
10831
+ if (chargedAmount !== void 0 && typeof chargedAmount !== "string") {
10832
+ throw new Error("invalid chargedAmount: not a non-negative integer");
10833
+ }
10834
+ const channelState = settleResponse.extra?.channelState;
10835
+ await updateChannelFromSettle(deps.storage, {
10836
+ server: {
10837
+ chargedAmount,
10838
+ chargedCumulativeAmount: channelState?.chargedCumulativeAmount
10839
+ },
10840
+ local: {
10841
+ channelId,
10842
+ requestAmount: ctx.requirements.amount,
10843
+ depositAmount: isBatchSettlementDepositPayload(payload) ? payload.deposit.amount : void 0
10844
+ }
10845
+ });
10846
+ return;
10847
+ }
10848
+ if (ctx.paymentRequired) {
10849
+ const recovered = await processCorrectivePaymentRequired(deps, ctx.paymentRequired);
10850
+ return recovered ? { recovered: true } : void 0;
10851
+ }
10852
+ }
10853
+ };
10854
+ }
10855
+ var NON_RECOVERABLE_REFUND_ERRORS = /* @__PURE__ */ new Set([
10856
+ ErrRefundNoBalance,
10857
+ ErrRefundAmountInvalid
10858
+ ]);
10859
+ async function refundChannel(ctx, url, options) {
10860
+ const fetchImpl = options?.fetch ?? globalThis.fetch;
10861
+ if (!fetchImpl) {
10862
+ throw new Error("refund requires a fetch implementation (globalThis.fetch unavailable)");
10863
+ }
10864
+ const refundAmount = normalizeRefundAmount(options?.amount);
10865
+ const probe = await probeRefundRequirements(url, fetchImpl);
10866
+ return executeRefund(ctx, url, probe, refundAmount, fetchImpl);
10867
+ }
10868
+ async function probeRefundRequirements(url, fetchImpl) {
10869
+ const probe = await fetchImpl(url, { method: "GET" });
10870
+ if (probe.status !== 402) {
10871
+ throw new Error(`Refund probe expected 402, got ${probe.status}`);
10872
+ }
10873
+ const header = probe.headers.get("PAYMENT-REQUIRED");
10874
+ if (!header) {
10875
+ throw new Error("Refund probe response missing PAYMENT-REQUIRED header");
10876
+ }
10877
+ const paymentRequired = decodePaymentRequiredHeader(header);
10878
+ const requirements = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
10879
+ if (!requirements) {
10880
+ throw new Error(`No ${BATCH_SETTLEMENT_SCHEME} payment option at ${url}`);
10881
+ }
10882
+ const extra = requirements.extra;
10883
+ if (!extra?.receiverAuthorizer) {
10884
+ throw new Error("Refund requires a configured receiverAuthorizer on the receiver");
10885
+ }
10886
+ return { paymentRequired, requirements };
10887
+ }
10888
+ async function executeRefund(ctx, url, probe, refundAmount, fetchImpl) {
10889
+ const maxAttempts = 2;
10890
+ const { paymentRequired, requirements } = probe;
10891
+ const httpClient = createRefundHttpClient(ctx, requirements);
10892
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
10893
+ const paymentPayload = await buildRefundPaymentPayload(
10894
+ ctx,
10895
+ paymentRequired,
10896
+ requirements,
10897
+ refundAmount
10898
+ );
10899
+ const headers = httpClient.encodePaymentSignatureHeader(paymentPayload);
10900
+ const response = await fetchImpl(url, { method: "GET", headers });
10901
+ if (response.status === 402) {
10902
+ const nonRecoverable = getNonRecoverableRefundFailure(response);
10903
+ if (nonRecoverable) {
10904
+ throw new Error(nonRecoverable);
10905
+ }
10906
+ }
10907
+ const result = await httpClient.processPaymentResult(
10908
+ paymentPayload,
10909
+ (name) => response.headers.get(name),
10910
+ response.status
10911
+ );
10912
+ if (response.status === 402) {
10913
+ if (result.recovered && attempt < maxAttempts) {
10914
+ continue;
10915
+ }
10916
+ if (result.recovered) {
10917
+ throw new Error(`Refund failed: server returned 402 after ${attempt} attempt(s)`);
10918
+ }
10919
+ const corrective = getRefundPaymentRequired(response);
10920
+ throw new Error(`Refund failed: ${corrective.error ?? "unknown"}`);
10921
+ }
10922
+ if (!result.settleResponse) {
10923
+ throw new Error(
10924
+ `Refund response missing PAYMENT-RESPONSE header (status ${response.status})`
10925
+ );
10926
+ }
10927
+ return result.settleResponse;
10928
+ }
10929
+ throw new Error("Refund failed: retry budget exhausted");
10930
+ }
10931
+ async function buildRefundPaymentPayload(ctx, paymentRequired, requirements, refundAmount) {
10932
+ const config = buildChannelConfig(ctx, requirements);
10933
+ const channelId = computeChannelId(config, requirements.network);
10934
+ const key = channelId.toLowerCase();
10935
+ let channel = await ctx.storage.get(key);
10936
+ if (channel === void 0 && ctx.signer.readContract) {
10937
+ channel = await recoverChannel(ctx, requirements);
10938
+ }
10939
+ if (channel === void 0) {
10940
+ throw new Error(
10941
+ "Refund requires an existing channel record; deposit first or call from a context with an EVM RPC"
10942
+ );
10943
+ }
10944
+ const charged = channel.chargedCumulativeAmount ?? "0";
10945
+ if (channel.balance !== void 0 && BigInt(channel.balance) <= BigInt(charged)) {
10946
+ throw new Error(
10947
+ `Refund failed: channel has no remaining balance (balance=${channel.balance}, chargedCumulativeAmount=${charged})`
10948
+ );
10949
+ }
10950
+ const voucherSigner = ctx.voucherSigner ?? ctx.signer;
10951
+ const voucher = await signVoucher(voucherSigner, channelId, charged, requirements.network);
10952
+ const payload = {
10953
+ type: "refund",
10954
+ channelConfig: config,
10955
+ voucher,
10956
+ ...refundAmount !== void 0 ? { amount: refundAmount } : {}
10957
+ };
10958
+ return {
10959
+ x402Version: 2,
10960
+ accepted: requirements,
10961
+ payload,
10962
+ ...paymentRequired.resource ? { resource: paymentRequired.resource } : {},
10963
+ ...paymentRequired.extensions ? { extensions: paymentRequired.extensions } : {}
10964
+ };
10965
+ }
10966
+ function createRefundHttpClient(ctx, requirements) {
10967
+ const client2 = new x402Client().register(requirements.network, {
10968
+ scheme: BATCH_SETTLEMENT_SCHEME,
10969
+ schemeHooks: createBatchSettlementClientHooks(ctx),
10970
+ createPaymentPayload: async () => {
10971
+ throw new Error("Refund payloads are built by refundChannel");
10972
+ }
10973
+ });
10974
+ return new x402HTTPClient(client2);
10975
+ }
10976
+ function getNonRecoverableRefundFailure(response) {
10977
+ const settleHeader = response.headers.get("PAYMENT-RESPONSE");
10978
+ if (settleHeader) {
10979
+ return formatRefundFailure(decodePaymentResponseHeader(settleHeader));
10980
+ }
10981
+ const paymentRequired = getRefundPaymentRequired(response);
10982
+ const errorCode = paymentRequired.error;
10983
+ if (errorCode && NON_RECOVERABLE_REFUND_ERRORS.has(errorCode)) {
10984
+ return `Refund failed: ${errorCode}`;
10985
+ }
10986
+ }
10987
+ function getRefundPaymentRequired(response) {
10988
+ const requiredHeader = response.headers.get("PAYMENT-REQUIRED");
10989
+ if (!requiredHeader) {
10990
+ throw new Error("Refund 402 missing PAYMENT-REQUIRED header");
10991
+ }
10992
+ return decodePaymentRequiredHeader(requiredHeader);
10993
+ }
10994
+ function formatRefundFailure(settle) {
10995
+ const reason = settle.errorReason ?? "unknown_settlement_error";
10996
+ const message = settle.errorMessage;
10997
+ if (message && message !== reason) {
10998
+ return `Refund failed: ${reason}: ${message}`;
10999
+ }
11000
+ return `Refund failed: ${reason}`;
11001
+ }
11002
+ function normalizeRefundAmount(amount) {
11003
+ if (amount === void 0) return void 0;
11004
+ if (!/^\d+$/.test(amount) || amount === "0") {
11005
+ throw new Error(`Invalid refund amount "${amount}": must be a positive integer string`);
11006
+ }
11007
+ return amount;
11008
+ }
11009
+ async function createBatchSettlementPermit2DepositPayload(signer, x402Version2, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
11010
+ const chainId = getEvmChainId(paymentRequirements.network);
11011
+ const nonce = createPermit2Nonce();
11012
+ const deadline = Math.floor(Date.now() / 1e3 + paymentRequirements.maxTimeoutSeconds).toString();
11013
+ const channelId = computeChannelId(channelConfig, paymentRequirements.network);
11014
+ const permit2Authorization = {
11015
+ from: signer.address,
11016
+ permitted: {
11017
+ token: getAddress2(paymentRequirements.asset),
11018
+ amount: depositAmount
11019
+ },
11020
+ spender: getAddress2(PERMIT2_DEPOSIT_COLLECTOR_ADDRESS),
11021
+ nonce,
11022
+ deadline,
11023
+ witness: {
11024
+ channelId
11025
+ }
11026
+ };
11027
+ const signature = await signer.signTypedData({
11028
+ domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
11029
+ types: batchPermit2WitnessTypes,
11030
+ primaryType: "PermitWitnessTransferFrom",
11031
+ message: {
11032
+ permitted: {
11033
+ token: permit2Authorization.permitted.token,
11034
+ amount: BigInt(permit2Authorization.permitted.amount)
11035
+ },
11036
+ spender: permit2Authorization.spender,
11037
+ nonce: BigInt(permit2Authorization.nonce),
11038
+ deadline: BigInt(permit2Authorization.deadline),
11039
+ witness: {
11040
+ channelId
11041
+ }
11042
+ }
11043
+ });
11044
+ const voucher = await signVoucher(
11045
+ voucherSigner ?? signer,
11046
+ channelId,
11047
+ maxClaimableAmount,
11048
+ paymentRequirements.network
11049
+ );
11050
+ const payload = {
11051
+ type: "deposit",
11052
+ channelConfig,
11053
+ voucher,
11054
+ deposit: {
11055
+ amount: depositAmount,
11056
+ authorization: {
11057
+ permit2Authorization: {
11058
+ ...permit2Authorization,
11059
+ signature
11060
+ }
11061
+ }
11062
+ }
11063
+ };
11064
+ return { x402Version: x402Version2, payload };
11065
+ }
11066
+ var BatchSettlementEvmScheme = class {
11067
+ /**
11068
+ * Constructs a batched client scheme.
11069
+ *
11070
+ * @param signer - Client EVM wallet used for signing vouchers and ERC-3009 authorizations.
11071
+ * @param optionsOrPolicy - Either a full options object or a bare deposit-policy.
11072
+ */
11073
+ constructor(signer, optionsOrPolicy) {
11074
+ this.signer = signer;
11075
+ this.scheme = BATCH_SETTLEMENT_SCHEME;
11076
+ this.findDefaultAsset = findDefaultAsset;
11077
+ const {
11078
+ storage,
11079
+ depositPolicy,
11080
+ depositStrategy,
11081
+ salt,
11082
+ payerAuthorizer,
11083
+ voucherSigner,
11084
+ extensionRpcOptions
11085
+ } = resolveClientOptions(optionsOrPolicy);
11086
+ this.storage = storage;
11087
+ this.depositPolicy = depositPolicy;
11088
+ this.depositStrategy = depositStrategy;
11089
+ this.salt = salt;
11090
+ this.payerAuthorizer = payerAuthorizer;
11091
+ this.voucherSigner = voucherSigner;
11092
+ this.extensionRpcOptions = extensionRpcOptions;
11093
+ if (payerAuthorizer !== void 0 && voucherSigner !== void 0 && getAddress2(payerAuthorizer) !== getAddress2(voucherSigner.address)) {
11094
+ throw new Error("payerAuthorizer address must match voucherSigner.address");
11095
+ }
11096
+ validateDepositPolicy(depositPolicy);
11097
+ this.schemeHooks = createBatchSettlementClientHooks(this.deps());
11098
+ }
11099
+ /**
11100
+ * Creates the payment payload for a batched request.
11101
+ *
11102
+ * If the channel has no onchain deposit (or needs a top-up), builds an
11103
+ * ERC-3009 deposit payload bundled with a voucher. Otherwise, signs and
11104
+ * returns a voucher-only payload.
11105
+ *
11106
+ * @param x402Version - Protocol version for the payload envelope.
11107
+ * @param paymentRequirements - Server payment requirements (scheme, network, asset, amount).
11108
+ * @param context - Optional extensions and the resolved atomic spend cap.
11109
+ * @returns A {@link PaymentPayloadResult} ready to be sent as the `X-PAYMENT` header.
11110
+ */
11111
+ async createPaymentPayload(x402Version2, paymentRequirements, context) {
11112
+ const deps = this.deps();
11113
+ const config = buildChannelConfig(deps, paymentRequirements);
11114
+ const channelId = computeChannelId(config, paymentRequirements.network);
11115
+ const key = channelId.toLowerCase();
11116
+ let batchedCtx = await this.storage.get(key);
11117
+ if (batchedCtx === void 0 && this.signer.readContract) {
11118
+ batchedCtx = await recoverChannel(deps, paymentRequirements);
11119
+ }
11120
+ batchedCtx = batchedCtx ?? {};
11121
+ const needsInitialDeposit = !batchedCtx.balance || batchedCtx.balance === "0";
11122
+ const baseCumulative = BigInt(batchedCtx.chargedCumulativeAmount ?? "0");
11123
+ const requestAmount = BigInt(paymentRequirements.amount);
11124
+ const maxClaimableAmount = (baseCumulative + requestAmount).toString();
11125
+ const currentBalance = BigInt(batchedCtx.balance ?? "0");
11126
+ const needsTopUp = !needsInitialDeposit && BigInt(maxClaimableAmount) > currentBalance;
11127
+ if (needsInitialDeposit || needsTopUp) {
11128
+ const minimumDepositAmount = BigInt(maxClaimableAmount) - currentBalance;
11129
+ const maxDeposit = maxDepositFromSpendCap(
11130
+ context?.maxAmountPerPayment,
11131
+ this.depositPolicy?.depositMultiplier ?? 5
11132
+ );
11133
+ const computedDeposit = depositAmountForRequest(
11134
+ this.depositPolicy,
11135
+ requestAmount,
11136
+ minimumDepositAmount,
11137
+ paymentRequirements.extra,
11138
+ maxDeposit
11139
+ );
11140
+ const depositAmount = await this.resolveDepositAmount({
11141
+ paymentRequirements,
11142
+ channelConfig: config,
11143
+ channelId,
11144
+ clientContext: batchedCtx,
11145
+ requestAmount: requestAmount.toString(),
11146
+ maxClaimableAmount,
11147
+ currentBalance: currentBalance.toString(),
11148
+ minimumDepositAmount: minimumDepositAmount.toString(),
11149
+ depositAmount: computedDeposit,
11150
+ ...maxDeposit !== void 0 ? { maxDeposit: maxDeposit.toString() } : {}
11151
+ });
11152
+ if (depositAmount === false) {
11153
+ return this.createVoucherPayload(
11154
+ x402Version2,
11155
+ channelId,
11156
+ maxClaimableAmount,
11157
+ paymentRequirements.network,
11158
+ config
11159
+ );
11160
+ }
11161
+ const assetTransferMethod = paymentRequirements.extra?.assetTransferMethod ?? "eip3009";
11162
+ if (assetTransferMethod === "eip3009") {
11163
+ return createBatchSettlementEIP3009DepositPayload(
11164
+ this.signer,
11165
+ x402Version2,
11166
+ paymentRequirements,
11167
+ config,
11168
+ depositAmount,
11169
+ maxClaimableAmount,
11170
+ this.voucherSigner
11171
+ );
11172
+ }
11173
+ if (assetTransferMethod !== "permit2") {
11174
+ throw new Error(`unsupported batch-settlement assetTransferMethod: ${assetTransferMethod}`);
11175
+ }
11176
+ const result = await createBatchSettlementPermit2DepositPayload(
11177
+ this.signer,
11178
+ x402Version2,
11179
+ paymentRequirements,
11180
+ config,
11181
+ depositAmount,
11182
+ maxClaimableAmount,
11183
+ this.voucherSigner
11184
+ );
11185
+ const eip2612Extensions = await trySignEip2612PermitExtension(
11186
+ this.signer,
11187
+ this.extensionRpcOptions,
11188
+ paymentRequirements,
11189
+ result,
11190
+ context,
11191
+ depositAmount
11192
+ );
11193
+ if (eip2612Extensions) {
11194
+ return { ...result, extensions: eip2612Extensions };
11195
+ }
11196
+ const erc20Extensions = await trySignErc20ApprovalExtension(
11197
+ this.signer,
11198
+ this.extensionRpcOptions,
11199
+ paymentRequirements,
11200
+ context,
11201
+ depositAmount
11202
+ );
11203
+ if (erc20Extensions) {
11204
+ return { ...result, extensions: erc20Extensions };
11205
+ }
11206
+ return result;
11207
+ }
11208
+ return this.createVoucherPayload(
11209
+ x402Version2,
11210
+ channelId,
11211
+ maxClaimableAmount,
11212
+ paymentRequirements.network,
11213
+ config
11214
+ );
11215
+ }
11216
+ /**
11217
+ * Sends a cooperative refund request.
11218
+ *
11219
+ * @param url - The route URL backing the channel to refund.
11220
+ * @param options - Optional `amount` (partial refund) and `fetch` override.
11221
+ * @returns The settle response describing the refund outcome.
11222
+ */
11223
+ async refund(url, options) {
11224
+ return refundChannel(this.deps(), url, options);
11225
+ }
11226
+ /**
11227
+ * Resyncs local channel state from a corrective 402 response.
11228
+ *
11229
+ * @param paymentRequired - The decoded 402 response body.
11230
+ * @returns `true` if local state was successfully resynced and a retry is warranted.
11231
+ */
11232
+ async processCorrectivePaymentRequired(paymentRequired) {
11233
+ return processCorrectivePaymentRequired(this.deps(), paymentRequired);
11234
+ }
11235
+ /**
11236
+ * Builds the immutable {@link ChannelConfig} for a given set of payment
11237
+ * requirements, using the scheme's own signer and salt.
11238
+ *
11239
+ * @param paymentRequirements - Server payment requirements for the channel.
11240
+ * @returns The channel config that uniquely identifies the payment channel.
11241
+ */
11242
+ buildChannelConfig(paymentRequirements) {
11243
+ return buildChannelConfig(this.deps(), paymentRequirements);
11244
+ }
11245
+ /**
11246
+ * Resolves the deposit amount after applying the optional custom strategy.
11247
+ *
11248
+ * @param context - Deposit attempt context exposed to the strategy.
11249
+ * @returns The deposit amount to sign, or `false` to skip this deposit attempt.
11250
+ */
11251
+ async resolveDepositAmount(context) {
11252
+ const strategyResult = await this.depositStrategy?.(context);
11253
+ if (strategyResult === false) return false;
11254
+ if (strategyResult === void 0) return context.depositAmount;
11255
+ const depositAmount = this.normalizeStrategyDepositAmount(strategyResult);
11256
+ if (BigInt(depositAmount) < BigInt(context.minimumDepositAmount)) {
11257
+ throw new Error(
11258
+ `depositStrategy returned ${depositAmount}, below required top-up ${context.minimumDepositAmount}`
11259
+ );
11260
+ }
11261
+ return applyMaxDeposit(
11262
+ BigInt(depositAmount),
11263
+ BigInt(context.minimumDepositAmount),
11264
+ context.maxDeposit === void 0 ? void 0 : BigInt(context.maxDeposit)
11265
+ );
11266
+ }
11267
+ /**
11268
+ * Normalizes and validates a strategy-provided base-unit deposit amount.
11269
+ *
11270
+ * @param value - Strategy-provided string or bigint amount.
11271
+ * @returns Normalized decimal string.
11272
+ */
11273
+ normalizeStrategyDepositAmount(value) {
11274
+ if (typeof value === "bigint") {
11275
+ if (value <= 0n) {
11276
+ throw new Error("depositStrategy must return a positive integer deposit amount");
11277
+ }
11278
+ return value.toString();
11279
+ }
11280
+ if (/^\d+$/.test(value) && BigInt(value) > 0n) {
11281
+ return BigInt(value).toString();
11282
+ }
11283
+ throw new Error("depositStrategy must return a positive integer deposit amount");
11284
+ }
11285
+ /**
11286
+ * Signs a voucher-only payment payload for the current channel.
11287
+ *
11288
+ * @param x402Version - Protocol version for the payload envelope.
11289
+ * @param channelId - Channel identifier for the voucher.
11290
+ * @param maxClaimableAmount - Cumulative ceiling for the voucher.
11291
+ * @param network - CAIP-2 network identifier.
11292
+ * @param config - Immutable channel configuration.
11293
+ * @returns Voucher-only payment payload.
11294
+ */
11295
+ async createVoucherPayload(x402Version2, channelId, maxClaimableAmount, network, config) {
11296
+ const voucherSigner = this.voucherSigner ?? this.signer;
11297
+ const voucher = await signVoucher(voucherSigner, channelId, maxClaimableAmount, network);
11298
+ const payload = {
11299
+ type: "voucher",
11300
+ channelConfig: config,
11301
+ voucher
11302
+ };
11303
+ return {
11304
+ x402Version: x402Version2,
11305
+ payload
11306
+ };
11307
+ }
11308
+ /**
11309
+ * Bundles the class state into the {@link BatchSettlementClientDeps} shape
11310
+ * consumed by the `channel`, `recovery`, and `refund` modules.
11311
+ *
11312
+ * @returns Client deps wrapping the scheme's own signer and storage.
11313
+ */
11314
+ deps() {
11315
+ return {
11316
+ signer: this.signer,
11317
+ storage: this.storage,
11318
+ salt: this.salt,
11319
+ payerAuthorizer: this.payerAuthorizer,
11320
+ voucherSigner: this.voucherSigner
11321
+ };
11322
+ }
9694
11323
  };
9695
- var NETWORKS = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);
9696
11324
 
9697
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-4NBQRJBB.mjs
11325
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-XP6HEYCL.mjs
9698
11326
  async function createPermit2PayloadForProxy(proxyAddress, signer, x402Version2, paymentRequirements) {
9699
11327
  const now = Math.floor(Date.now() / 1e3);
9700
11328
  const nonce = createPermit2Nonce();
@@ -9746,7 +11374,7 @@ async function signPermit2Authorization(signer, permit2Authorization, requiremen
9746
11374
  });
9747
11375
  }
9748
11376
 
9749
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-UUEZJ3RH.mjs
11377
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-OR6TZGCV.mjs
9750
11378
  var MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
9751
11379
  async function createPermit2Payload(signer, x402Version2, paymentRequirements) {
9752
11380
  return createPermit2PayloadForProxy(
@@ -9757,7 +11385,7 @@ async function createPermit2Payload(signer, x402Version2, paymentRequirements) {
9757
11385
  );
9758
11386
  }
9759
11387
 
9760
- // node_modules/.pnpm/@x402+evm@2.17.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-VFVBY5MG.mjs
11388
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-DLPUE5VK.mjs
9761
11389
  async function createEIP3009Payload(signer, x402Version2, paymentRequirements) {
9762
11390
  const nonce = createNonce();
9763
11391
  const now = Math.floor(Date.now() / 1e3);
@@ -9822,6 +11450,7 @@ var ExactEvmScheme = class {
9822
11450
  this.signer = signer;
9823
11451
  this.options = options;
9824
11452
  this.scheme = "exact";
11453
+ this.findDefaultAsset = findDefaultAsset;
9825
11454
  }
9826
11455
  /**
9827
11456
  * Creates a payment payload for the Exact scheme.
@@ -9871,9 +11500,41 @@ var ExactEvmScheme = class {
9871
11500
  }
9872
11501
  };
9873
11502
 
9874
- // node_modules/.pnpm/@x402+extensions@2.17.0_typescript@6.0.3/node_modules/@x402/extensions/dist/esm/chunk-26YBCURG.mjs
11503
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-BPTXPSEK.mjs
11504
+ var DEFAULT_ASSET_CONTRACT_CACHE_TTL_MS = 15 * 60 * 1e3;
11505
+
11506
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/index.mjs
11507
+ function toClientEvmSigner(signer, publicClient) {
11508
+ const readContract = signer.readContract ?? publicClient?.readContract.bind(publicClient);
11509
+ const result = {
11510
+ address: signer.address,
11511
+ signTypedData: (msg) => signer.signTypedData(msg)
11512
+ };
11513
+ if (readContract) {
11514
+ result.readContract = readContract;
11515
+ }
11516
+ const signTransaction = signer.signTransaction;
11517
+ if (signTransaction) {
11518
+ result.signTransaction = (args) => signTransaction(args);
11519
+ }
11520
+ const getTransactionCount = signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);
11521
+ if (getTransactionCount) {
11522
+ result.getTransactionCount = (args) => getTransactionCount(args);
11523
+ }
11524
+ const estimateFeesPerGas = signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);
11525
+ if (estimateFeesPerGas) {
11526
+ result.estimateFeesPerGas = () => estimateFeesPerGas();
11527
+ }
11528
+ return result;
11529
+ }
11530
+
11531
+ // node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/dist/esm/chunk-DGKLKGT2.mjs
9875
11532
  var BUILDER_CODE = "builder-code";
9876
11533
  var BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
11534
+ var MAX_CLIENT_SERVICE_CODES = 5;
11535
+ var MAX_SERVER_SERVICE_CODES = 5;
11536
+ var MAX_FACILITATOR_SERVICE_CODES = 1;
11537
+ var MAX_SERVICE_CODES = MAX_CLIENT_SERVICE_CODES + MAX_SERVER_SERVICE_CODES + MAX_FACILITATOR_SERVICE_CODES;
9877
11538
  var BuilderCodeClientExtension = class {
9878
11539
  /**
9879
11540
  * Creates a client extension that attaches the given service code(s) to payments.
@@ -9887,6 +11548,11 @@ var BuilderCodeClientExtension = class {
9887
11548
  constructor(serviceCodes) {
9888
11549
  this.key = BUILDER_CODE;
9889
11550
  const codes = Array.isArray(serviceCodes) ? serviceCodes : [serviceCodes];
11551
+ if (codes.length > MAX_CLIENT_SERVICE_CODES) {
11552
+ throw new Error(
11553
+ `Too many service codes: ${codes.length} exceeds the maximum of ${MAX_CLIENT_SERVICE_CODES}.`
11554
+ );
11555
+ }
9890
11556
  for (const code of codes) {
9891
11557
  if (!BUILDER_CODE_PATTERN.test(code)) {
9892
11558
  throw new Error(
@@ -9913,6 +11579,7 @@ var BuilderCodeClientExtension = class {
9913
11579
  };
9914
11580
  }
9915
11581
  };
11582
+ var MAX_ECHOED_SERVICE_CODES = MAX_CLIENT_SERVICE_CODES + MAX_SERVER_SERVICE_CODES;
9916
11583
 
9917
11584
  // src/lib/x402-pay.ts
9918
11585
  function authorizationOf(payload) {
@@ -10009,6 +11676,15 @@ async function buildExactPayment(paymentRequired, signer, only) {
10009
11676
  const { core, http: http2, builderCodeKey } = createPayerClient(() => signer);
10010
11677
  const requirement = only ?? selectPayableRequirement(core, paymentRequired);
10011
11678
  if (requirement === void 0) throw noPayableRequirement(paymentRequired.accepts);
11679
+ core.setSpendControls({
11680
+ allowedAssets: [
11681
+ {
11682
+ network: requirement.network,
11683
+ asset: requirement.asset,
11684
+ maxAmountPerPayment: requirement.amount
11685
+ }
11686
+ ]
11687
+ });
10012
11688
  const bound = {
10013
11689
  ...paymentRequired,
10014
11690
  accepts: [requirement],
@@ -10619,9 +12295,13 @@ export {
10619
12295
  inputProblems,
10620
12296
  assertResultSchema,
10621
12297
  projectBody,
12298
+ x402Client,
12299
+ BatchSettlementEvmScheme,
12300
+ toClientEvmSigner,
12301
+ canonicalUsdcOnly,
10622
12302
  runPay,
10623
12303
  MAX_PAID_LEG_TIMEOUT_MS,
10624
12304
  paidLegTimeoutMs,
10625
12305
  settlementTx
10626
12306
  };
10627
- //# sourceMappingURL=chunk-UBOFYC6J.js.map
12307
+ //# sourceMappingURL=chunk-DRXDTITB.js.map