@payai/x402-evm 2.4.0 → 2.4.2

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 (150) hide show
  1. package/dist/cjs/batch-settlement/client/file-storage.d.ts +47 -0
  2. package/dist/cjs/batch-settlement/client/file-storage.js +116 -0
  3. package/dist/cjs/batch-settlement/client/file-storage.js.map +1 -0
  4. package/dist/cjs/batch-settlement/client/index.d.ts +111 -0
  5. package/dist/cjs/batch-settlement/client/index.js +1565 -0
  6. package/dist/cjs/batch-settlement/client/index.js.map +1 -0
  7. package/dist/cjs/batch-settlement/facilitator/index.d.ts +71 -0
  8. package/dist/cjs/batch-settlement/facilitator/index.js +2032 -0
  9. package/dist/cjs/batch-settlement/facilitator/index.js.map +1 -0
  10. package/dist/cjs/batch-settlement/server/file-storage.d.ts +53 -0
  11. package/dist/cjs/batch-settlement/server/file-storage.js +181 -0
  12. package/dist/cjs/batch-settlement/server/file-storage.js.map +1 -0
  13. package/dist/cjs/batch-settlement/server/index.d.ts +491 -0
  14. package/dist/cjs/batch-settlement/server/index.js +1960 -0
  15. package/dist/cjs/batch-settlement/server/index.js.map +1 -0
  16. package/dist/cjs/batch-settlement/server/redis-storage.d.ts +87 -0
  17. package/dist/cjs/batch-settlement/server/redis-storage.js +181 -0
  18. package/dist/cjs/batch-settlement/server/redis-storage.js.map +1 -0
  19. package/dist/cjs/exact/client/index.d.ts +6 -4
  20. package/dist/cjs/exact/client/index.js +7 -5
  21. package/dist/cjs/exact/client/index.js.map +1 -1
  22. package/dist/cjs/exact/facilitator/index.d.ts +16 -9
  23. package/dist/cjs/exact/facilitator/index.js +56 -9
  24. package/dist/cjs/exact/facilitator/index.js.map +1 -1
  25. package/dist/cjs/exact/server/index.d.ts +0 -8
  26. package/dist/cjs/exact/server/index.js +53 -19
  27. package/dist/cjs/exact/server/index.js.map +1 -1
  28. package/dist/cjs/exact/v1/client/index.d.ts +2 -1
  29. package/dist/cjs/exact/v1/client/index.js.map +1 -1
  30. package/dist/cjs/exact/v1/facilitator/index.d.ts +11 -5
  31. package/dist/cjs/exact/v1/facilitator/index.js +16 -2
  32. package/dist/cjs/exact/v1/facilitator/index.js.map +1 -1
  33. package/dist/cjs/index.d.ts +113 -7
  34. package/dist/cjs/index.js +1353 -5
  35. package/dist/cjs/index.js.map +1 -1
  36. package/dist/{esm/permit2-CyZxwngN.d.mts → cjs/permit2-DhJRUcgY.d.ts} +1 -13
  37. package/dist/cjs/rpc-DULZzRne.d.ts +13 -0
  38. package/dist/cjs/scheme-CvkPJXBD.d.ts +307 -0
  39. package/dist/{esm/scheme-DCR7hsa3.d.mts → cjs/scheme-DTQFE9xp.d.ts} +2 -2
  40. package/dist/{esm/signer-D912R4mq.d.mts → cjs/signer-tYS6Y46X.d.ts} +3 -0
  41. package/dist/cjs/storage-6W5MO46W.d.ts +50 -0
  42. package/dist/cjs/storage-Bl6aD0Xg.d.ts +81 -0
  43. package/dist/cjs/types-CF8P2-NM.d.ts +180 -0
  44. package/dist/cjs/upto/client/index.d.ts +5 -3
  45. package/dist/cjs/upto/client/index.js +7 -5
  46. package/dist/cjs/upto/client/index.js.map +1 -1
  47. package/dist/cjs/upto/facilitator/index.d.ts +2 -1
  48. package/dist/cjs/upto/facilitator/index.js +2 -1
  49. package/dist/cjs/upto/facilitator/index.js.map +1 -1
  50. package/dist/cjs/upto/server/index.d.ts +0 -8
  51. package/dist/cjs/upto/server/index.js +51 -19
  52. package/dist/cjs/upto/server/index.js.map +1 -1
  53. package/dist/cjs/v1/index.d.ts +2 -1
  54. package/dist/cjs/v1/index.js.map +1 -1
  55. package/dist/esm/batch-settlement/client/file-storage.d.mts +47 -0
  56. package/dist/esm/batch-settlement/client/file-storage.mjs +63 -0
  57. package/dist/esm/batch-settlement/client/file-storage.mjs.map +1 -0
  58. package/dist/esm/batch-settlement/client/index.d.mts +111 -0
  59. package/dist/esm/batch-settlement/client/index.mjs +59 -0
  60. package/dist/esm/batch-settlement/client/index.mjs.map +1 -0
  61. package/dist/esm/batch-settlement/facilitator/index.d.mts +71 -0
  62. package/dist/esm/batch-settlement/facilitator/index.mjs +1235 -0
  63. package/dist/esm/batch-settlement/facilitator/index.mjs.map +1 -0
  64. package/dist/esm/batch-settlement/server/file-storage.d.mts +53 -0
  65. package/dist/esm/batch-settlement/server/file-storage.mjs +128 -0
  66. package/dist/esm/batch-settlement/server/file-storage.mjs.map +1 -0
  67. package/dist/esm/batch-settlement/server/index.d.mts +491 -0
  68. package/dist/esm/batch-settlement/server/index.mjs +1645 -0
  69. package/dist/esm/batch-settlement/server/index.mjs.map +1 -0
  70. package/dist/esm/batch-settlement/server/redis-storage.d.mts +87 -0
  71. package/dist/esm/batch-settlement/server/redis-storage.mjs +156 -0
  72. package/dist/esm/batch-settlement/server/redis-storage.mjs.map +1 -0
  73. package/dist/esm/chunk-2EUQTNJO.mjs +38 -0
  74. package/dist/esm/chunk-2EUQTNJO.mjs.map +1 -0
  75. package/dist/esm/chunk-53USC5VE.mjs +47 -0
  76. package/dist/esm/chunk-53USC5VE.mjs.map +1 -0
  77. package/dist/esm/{chunk-GJ57SZGI.mjs → chunk-6WQOGWBE.mjs} +7 -5
  78. package/dist/esm/{chunk-GJ57SZGI.mjs.map → chunk-6WQOGWBE.mjs.map} +1 -1
  79. package/dist/esm/{chunk-NSFLAANF.mjs → chunk-BTYNCDNS.mjs} +51 -2
  80. package/dist/esm/chunk-BTYNCDNS.mjs.map +1 -0
  81. package/dist/esm/{chunk-RYT6M3PA.mjs → chunk-CSQS7ZON.mjs} +47 -7
  82. package/dist/esm/chunk-CSQS7ZON.mjs.map +1 -0
  83. package/dist/esm/chunk-GD4MKCN7.mjs +57 -0
  84. package/dist/esm/chunk-GD4MKCN7.mjs.map +1 -0
  85. package/dist/esm/chunk-HYABYUBD.mjs +432 -0
  86. package/dist/esm/chunk-HYABYUBD.mjs.map +1 -0
  87. package/dist/esm/chunk-IN5YIT5C.mjs +159 -0
  88. package/dist/esm/chunk-IN5YIT5C.mjs.map +1 -0
  89. package/dist/esm/{chunk-JII456TS.mjs → chunk-JK7SLLF7.mjs} +1 -1
  90. package/dist/esm/chunk-JK7SLLF7.mjs.map +1 -0
  91. package/dist/esm/{chunk-C4ZQMS77.mjs → chunk-MACPBXCT.mjs} +2 -216
  92. package/dist/esm/chunk-MACPBXCT.mjs.map +1 -0
  93. package/dist/esm/chunk-NKYVYGRA.mjs +911 -0
  94. package/dist/esm/chunk-NKYVYGRA.mjs.map +1 -0
  95. package/dist/esm/{chunk-D6RXZXOS.mjs → chunk-R7I3RZFF.mjs} +10 -6
  96. package/dist/esm/{chunk-D6RXZXOS.mjs.map → chunk-R7I3RZFF.mjs.map} +1 -1
  97. package/dist/esm/{chunk-CRT6YNY5.mjs → chunk-RWLVVO3B.mjs} +21 -61
  98. package/dist/esm/chunk-RWLVVO3B.mjs.map +1 -0
  99. package/dist/esm/chunk-TGFAVNUD.mjs +111 -0
  100. package/dist/esm/chunk-TGFAVNUD.mjs.map +1 -0
  101. package/dist/esm/chunk-TW7Z65AO.mjs +34 -0
  102. package/dist/esm/chunk-TW7Z65AO.mjs.map +1 -0
  103. package/dist/esm/chunk-U4HCGTLU.mjs +35 -0
  104. package/dist/esm/chunk-U4HCGTLU.mjs.map +1 -0
  105. package/dist/esm/chunk-VS3RYAYE.mjs +80 -0
  106. package/dist/esm/chunk-VS3RYAYE.mjs.map +1 -0
  107. package/dist/esm/chunk-W6ON4LG2.mjs +39 -0
  108. package/dist/esm/chunk-W6ON4LG2.mjs.map +1 -0
  109. package/dist/esm/{chunk-WKBC5YMI.mjs → chunk-YMQCTKDU.mjs} +23 -55
  110. package/dist/esm/chunk-YMQCTKDU.mjs.map +1 -0
  111. package/dist/esm/exact/client/index.d.mts +6 -4
  112. package/dist/esm/exact/client/index.mjs +10 -5
  113. package/dist/esm/exact/facilitator/index.d.mts +16 -9
  114. package/dist/esm/exact/facilitator/index.mjs +39 -16
  115. package/dist/esm/exact/facilitator/index.mjs.map +1 -1
  116. package/dist/esm/exact/server/index.d.mts +0 -8
  117. package/dist/esm/exact/server/index.mjs +3 -19
  118. package/dist/esm/exact/server/index.mjs.map +1 -1
  119. package/dist/esm/exact/v1/client/index.d.mts +2 -1
  120. package/dist/esm/exact/v1/client/index.mjs +5 -2
  121. package/dist/esm/exact/v1/facilitator/index.d.mts +11 -5
  122. package/dist/esm/exact/v1/facilitator/index.mjs +5 -2
  123. package/dist/esm/index.d.mts +113 -7
  124. package/dist/esm/index.mjs +53 -7
  125. package/dist/esm/index.mjs.map +1 -1
  126. package/dist/esm/permit2-DhJRUcgY.d.mts +729 -0
  127. package/dist/esm/rpc-DULZzRne.d.mts +13 -0
  128. package/dist/esm/scheme-DtbSS4Fk.d.mts +307 -0
  129. package/dist/esm/scheme-gtqAIYPJ.d.mts +47 -0
  130. package/dist/esm/signer-tYS6Y46X.d.mts +170 -0
  131. package/dist/esm/storage-6W5MO46W.d.mts +50 -0
  132. package/dist/esm/storage-sZ1CDS4P.d.mts +81 -0
  133. package/dist/esm/types-CF8P2-NM.d.mts +180 -0
  134. package/dist/esm/upto/client/index.d.mts +5 -3
  135. package/dist/esm/upto/client/index.mjs +9 -4
  136. package/dist/esm/upto/facilitator/index.d.mts +2 -1
  137. package/dist/esm/upto/facilitator/index.mjs +17 -9
  138. package/dist/esm/upto/facilitator/index.mjs.map +1 -1
  139. package/dist/esm/upto/server/index.d.mts +0 -8
  140. package/dist/esm/upto/server/index.mjs +3 -19
  141. package/dist/esm/upto/server/index.mjs.map +1 -1
  142. package/dist/esm/v1/index.d.mts +2 -1
  143. package/dist/esm/v1/index.mjs +5 -2
  144. package/package.json +5 -5
  145. package/dist/esm/chunk-C4ZQMS77.mjs.map +0 -1
  146. package/dist/esm/chunk-CRT6YNY5.mjs.map +0 -1
  147. package/dist/esm/chunk-JII456TS.mjs.map +0 -1
  148. package/dist/esm/chunk-NSFLAANF.mjs.map +0 -1
  149. package/dist/esm/chunk-RYT6M3PA.mjs.map +0 -1
  150. package/dist/esm/chunk-WKBC5YMI.mjs.map +0 -1
@@ -0,0 +1,1565 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/batch-settlement/client/index.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ BatchSettlementEvmScheme: () => BatchSettlementEvmScheme,
24
+ InMemoryClientChannelStorage: () => InMemoryClientChannelStorage,
25
+ buildChannelConfig: () => buildChannelConfig,
26
+ computeChannelId: () => computeChannelId,
27
+ createBatchSettlementClientHooks: () => createBatchSettlementClientHooks,
28
+ createBatchSettlementEIP3009DepositPayload: () => createBatchSettlementEIP3009DepositPayload,
29
+ depositAmountForRequest: () => depositAmountForRequest,
30
+ getChannel: () => getChannel,
31
+ handleBatchSettlementPaymentResponse: () => handleBatchSettlementPaymentResponse,
32
+ hasChannel: () => hasChannel,
33
+ isBatchSettlementEvmSchemeOptions: () => isBatchSettlementEvmSchemeOptions,
34
+ processCorrectivePaymentRequired: () => processCorrectivePaymentRequired,
35
+ processPaymentResponse: () => processPaymentResponse,
36
+ processSettleResponse: () => processSettleResponse,
37
+ readChannelBalanceAndTotalClaimed: () => readChannelBalanceAndTotalClaimed,
38
+ recoverChannel: () => recoverChannel,
39
+ recoverFromOnChainState: () => recoverFromOnChainState,
40
+ recoverFromSignature: () => recoverFromSignature,
41
+ refundChannel: () => refundChannel,
42
+ resolveClientOptions: () => resolveClientOptions,
43
+ signVoucher: () => signVoucher,
44
+ updateChannelAfterRefund: () => updateChannelAfterRefund,
45
+ validateDepositPolicy: () => validateDepositPolicy
46
+ });
47
+ module.exports = __toCommonJS(client_exports);
48
+
49
+ // src/batch-settlement/client/scheme.ts
50
+ var import_viem13 = require("viem");
51
+
52
+ // src/batch-settlement/constants.ts
53
+ var import_viem = require("viem");
54
+ var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
55
+ var BATCH_SETTLEMENT_ADDRESS = "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003";
56
+ var ERC3009_DEPOSIT_COLLECTOR_ADDRESS = "0x4020806089470a89826cB9fB1f4059150b550004";
57
+ var PERMIT2_DEPOSIT_COLLECTOR_ADDRESS = "0x4020425FAf3B746C082C2f942b4E5159887B0005";
58
+ var MIN_WITHDRAW_DELAY = 900;
59
+ var BATCH_SETTLEMENT_DOMAIN = {
60
+ name: "x402 Batch Settlement",
61
+ version: "1"
62
+ };
63
+ var CHANNEL_CONFIG_TYPEHASH = (0, import_viem.keccak256)(
64
+ (0, import_viem.toBytes)(
65
+ "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
66
+ )
67
+ );
68
+ var channelConfigTypes = {
69
+ ChannelConfig: [
70
+ { name: "payer", type: "address" },
71
+ { name: "payerAuthorizer", type: "address" },
72
+ { name: "receiver", type: "address" },
73
+ { name: "receiverAuthorizer", type: "address" },
74
+ { name: "token", type: "address" },
75
+ { name: "withdrawDelay", type: "uint40" },
76
+ { name: "salt", type: "bytes32" }
77
+ ]
78
+ };
79
+ var voucherTypes = {
80
+ Voucher: [
81
+ { name: "channelId", type: "bytes32" },
82
+ { name: "maxClaimableAmount", type: "uint128" }
83
+ ]
84
+ };
85
+ var receiveAuthorizationTypes = {
86
+ ReceiveWithAuthorization: [
87
+ { name: "from", type: "address" },
88
+ { name: "to", type: "address" },
89
+ { name: "value", type: "uint256" },
90
+ { name: "validAfter", type: "uint256" },
91
+ { name: "validBefore", type: "uint256" },
92
+ { name: "nonce", type: "bytes32" }
93
+ ]
94
+ };
95
+ var batchPermit2WitnessTypes = {
96
+ PermitWitnessTransferFrom: [
97
+ { name: "permitted", type: "TokenPermissions" },
98
+ { name: "spender", type: "address" },
99
+ { name: "nonce", type: "uint256" },
100
+ { name: "deadline", type: "uint256" },
101
+ { name: "witness", type: "DepositWitness" }
102
+ ],
103
+ TokenPermissions: [
104
+ { name: "token", type: "address" },
105
+ { name: "amount", type: "uint256" }
106
+ ],
107
+ DepositWitness: [{ name: "channelId", type: "bytes32" }]
108
+ };
109
+
110
+ // src/batch-settlement/utils.ts
111
+ var import_viem3 = require("viem");
112
+
113
+ // src/utils.ts
114
+ var import_viem2 = require("viem");
115
+ function getEvmChainId(network) {
116
+ if (network.startsWith("eip155:")) {
117
+ const idStr = network.split(":")[1];
118
+ const chainId = parseInt(idStr, 10);
119
+ if (isNaN(chainId)) {
120
+ throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
121
+ }
122
+ return chainId;
123
+ }
124
+ throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
125
+ }
126
+ function getCrypto() {
127
+ const cryptoObj = globalThis.crypto;
128
+ if (!cryptoObj) {
129
+ throw new Error("Crypto API not available");
130
+ }
131
+ return cryptoObj;
132
+ }
133
+ function createNonce() {
134
+ return (0, import_viem2.toHex)(getCrypto().getRandomValues(new Uint8Array(32)));
135
+ }
136
+ function createPermit2Nonce() {
137
+ const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));
138
+ return BigInt((0, import_viem2.toHex)(randomBytes)).toString();
139
+ }
140
+
141
+ // src/batch-settlement/utils.ts
142
+ function computeChannelId(config, networkOrChainId) {
143
+ const chainId = typeof networkOrChainId === "number" ? networkOrChainId : getEvmChainId(networkOrChainId);
144
+ return (0, import_viem3.hashTypedData)({
145
+ domain: getBatchSettlementEip712Domain(chainId),
146
+ types: channelConfigTypes,
147
+ primaryType: "ChannelConfig",
148
+ message: {
149
+ payer: config.payer,
150
+ payerAuthorizer: config.payerAuthorizer,
151
+ receiver: config.receiver,
152
+ receiverAuthorizer: config.receiverAuthorizer,
153
+ token: config.token,
154
+ withdrawDelay: config.withdrawDelay,
155
+ salt: config.salt
156
+ }
157
+ });
158
+ }
159
+ function getBatchSettlementEip712Domain(chainId) {
160
+ return {
161
+ ...BATCH_SETTLEMENT_DOMAIN,
162
+ chainId,
163
+ verifyingContract: (0, import_viem3.getAddress)(BATCH_SETTLEMENT_ADDRESS)
164
+ };
165
+ }
166
+
167
+ // src/exact/extensions.ts
168
+ var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
169
+ var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
170
+ var ERC20_APPROVAL_GAS_SPONSORING_VERSION = "1";
171
+
172
+ // src/shared/extensions.ts
173
+ var import_viem7 = require("viem");
174
+
175
+ // src/constants.ts
176
+ var eip2612PermitTypes = {
177
+ Permit: [
178
+ { name: "owner", type: "address" },
179
+ { name: "spender", type: "address" },
180
+ { name: "value", type: "uint256" },
181
+ { name: "nonce", type: "uint256" },
182
+ { name: "deadline", type: "uint256" }
183
+ ]
184
+ };
185
+ var eip2612NoncesAbi = [
186
+ {
187
+ type: "function",
188
+ name: "nonces",
189
+ inputs: [{ name: "owner", type: "address" }],
190
+ outputs: [{ type: "uint256" }],
191
+ stateMutability: "view"
192
+ }
193
+ ];
194
+ var erc20ApproveAbi = [
195
+ {
196
+ type: "function",
197
+ name: "approve",
198
+ inputs: [
199
+ { name: "spender", type: "address" },
200
+ { name: "amount", type: "uint256" }
201
+ ],
202
+ outputs: [{ type: "bool" }],
203
+ stateMutability: "nonpayable"
204
+ }
205
+ ];
206
+ var erc20AllowanceAbi = [
207
+ {
208
+ type: "function",
209
+ name: "allowance",
210
+ inputs: [
211
+ { name: "owner", type: "address" },
212
+ { name: "spender", type: "address" }
213
+ ],
214
+ outputs: [{ type: "uint256" }],
215
+ stateMutability: "view"
216
+ }
217
+ ];
218
+ var ERC20_APPROVE_GAS_LIMIT = 70000n;
219
+ var DEFAULT_MAX_FEE_PER_GAS = 1000000000n;
220
+ var DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100000000n;
221
+ var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
222
+
223
+ // src/exact/client/eip2612.ts
224
+ var import_viem4 = require("viem");
225
+ async function signEip2612Permit(signer, tokenAddress, tokenName, tokenVersion, chainId, deadline, permittedAmount) {
226
+ const owner = signer.address;
227
+ const spender = (0, import_viem4.getAddress)(PERMIT2_ADDRESS);
228
+ const nonce = await signer.readContract({
229
+ address: tokenAddress,
230
+ abi: eip2612NoncesAbi,
231
+ functionName: "nonces",
232
+ args: [owner]
233
+ });
234
+ const domain = {
235
+ name: tokenName,
236
+ version: tokenVersion,
237
+ chainId,
238
+ verifyingContract: tokenAddress
239
+ };
240
+ const approvalAmount = BigInt(permittedAmount);
241
+ const message = {
242
+ owner,
243
+ spender,
244
+ value: approvalAmount,
245
+ nonce,
246
+ deadline: BigInt(deadline)
247
+ };
248
+ const signature = await signer.signTypedData({
249
+ domain,
250
+ types: eip2612PermitTypes,
251
+ primaryType: "Permit",
252
+ message
253
+ });
254
+ return {
255
+ from: owner,
256
+ asset: tokenAddress,
257
+ spender,
258
+ amount: approvalAmount.toString(),
259
+ nonce: nonce.toString(),
260
+ deadline,
261
+ signature,
262
+ version: "1"
263
+ };
264
+ }
265
+
266
+ // src/exact/client/erc20approval.ts
267
+ var import_viem5 = require("viem");
268
+ async function signErc20ApprovalTransaction(signer, tokenAddress, chainId) {
269
+ const from = signer.address;
270
+ const spender = (0, import_viem5.getAddress)(PERMIT2_ADDRESS);
271
+ const data = (0, import_viem5.encodeFunctionData)({
272
+ abi: erc20ApproveAbi,
273
+ functionName: "approve",
274
+ args: [spender, import_viem5.maxUint256]
275
+ });
276
+ const nonce = await signer.getTransactionCount({ address: from });
277
+ let maxFeePerGas;
278
+ let maxPriorityFeePerGas;
279
+ try {
280
+ const fees = await signer.estimateFeesPerGas?.();
281
+ if (!fees) {
282
+ throw new Error("no fee estimates available");
283
+ }
284
+ maxFeePerGas = fees.maxFeePerGas;
285
+ maxPriorityFeePerGas = fees.maxPriorityFeePerGas;
286
+ } catch {
287
+ maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;
288
+ maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;
289
+ }
290
+ const signedTransaction = await signer.signTransaction({
291
+ to: tokenAddress,
292
+ data,
293
+ nonce,
294
+ gas: ERC20_APPROVE_GAS_LIMIT,
295
+ maxFeePerGas,
296
+ maxPriorityFeePerGas,
297
+ chainId
298
+ });
299
+ return {
300
+ from,
301
+ asset: tokenAddress,
302
+ spender,
303
+ amount: import_viem5.maxUint256.toString(),
304
+ signedTransaction,
305
+ version: ERC20_APPROVAL_GAS_SPONSORING_VERSION
306
+ };
307
+ }
308
+
309
+ // src/shared/rpc.ts
310
+ var import_viem6 = require("viem");
311
+ var rpcClientCache = /* @__PURE__ */ new Map();
312
+ function isConfigByChainId(options) {
313
+ const keys = Object.keys(options);
314
+ return keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
315
+ }
316
+ function getRpcClient(rpcUrl) {
317
+ const existing = rpcClientCache.get(rpcUrl);
318
+ if (existing) {
319
+ return existing;
320
+ }
321
+ const client = (0, import_viem6.createPublicClient)({
322
+ transport: (0, import_viem6.http)(rpcUrl)
323
+ });
324
+ rpcClientCache.set(rpcUrl, client);
325
+ return client;
326
+ }
327
+ function resolveRpcUrl(network, options) {
328
+ if (!options) {
329
+ return void 0;
330
+ }
331
+ if (isConfigByChainId(options)) {
332
+ const chainId = getEvmChainId(network);
333
+ const optionsByChainId = options;
334
+ return optionsByChainId[chainId]?.rpcUrl;
335
+ }
336
+ return options.rpcUrl;
337
+ }
338
+ function resolveExtensionRpcCapabilities(network, signer, options) {
339
+ const capabilities = {
340
+ signTransaction: signer.signTransaction,
341
+ readContract: signer.readContract,
342
+ getTransactionCount: signer.getTransactionCount,
343
+ estimateFeesPerGas: signer.estimateFeesPerGas
344
+ };
345
+ const needsRpcBackfill = !capabilities.readContract || !capabilities.getTransactionCount || !capabilities.estimateFeesPerGas;
346
+ if (!needsRpcBackfill) {
347
+ return capabilities;
348
+ }
349
+ const rpcUrl = resolveRpcUrl(network, options);
350
+ if (!rpcUrl) {
351
+ return capabilities;
352
+ }
353
+ const rpcClient = getRpcClient(rpcUrl);
354
+ if (!capabilities.readContract) {
355
+ capabilities.readContract = (args) => rpcClient.readContract(args);
356
+ }
357
+ if (!capabilities.getTransactionCount) {
358
+ capabilities.getTransactionCount = async (args) => rpcClient.getTransactionCount({ address: args.address });
359
+ }
360
+ if (!capabilities.estimateFeesPerGas) {
361
+ capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();
362
+ }
363
+ return capabilities;
364
+ }
365
+
366
+ // src/shared/extensions.ts
367
+ async function trySignEip2612PermitExtension(signer, options, requirements, result, context, approvalAmount) {
368
+ const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
369
+ if (!capabilities.readContract) {
370
+ return void 0;
371
+ }
372
+ if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {
373
+ return void 0;
374
+ }
375
+ const tokenName = requirements.extra?.name;
376
+ const tokenVersion = requirements.extra?.version;
377
+ if (!tokenName || !tokenVersion) {
378
+ return void 0;
379
+ }
380
+ const chainId = getEvmChainId(requirements.network);
381
+ const tokenAddress = (0, import_viem7.getAddress)(requirements.asset);
382
+ const requiredAllowance = approvalAmount ?? requirements.amount;
383
+ try {
384
+ const allowance = await capabilities.readContract({
385
+ address: tokenAddress,
386
+ abi: erc20AllowanceAbi,
387
+ functionName: "allowance",
388
+ args: [signer.address, PERMIT2_ADDRESS]
389
+ });
390
+ if (allowance >= BigInt(requiredAllowance)) {
391
+ return void 0;
392
+ }
393
+ } catch {
394
+ }
395
+ const permit2Auth = result.payload?.permit2Authorization;
396
+ const deadline = permit2Auth?.deadline ?? Math.floor(Date.now() / 1e3 + requirements.maxTimeoutSeconds).toString();
397
+ const info = await signEip2612Permit(
398
+ {
399
+ address: signer.address,
400
+ signTypedData: (msg) => signer.signTypedData(msg),
401
+ readContract: capabilities.readContract
402
+ },
403
+ tokenAddress,
404
+ tokenName,
405
+ tokenVersion,
406
+ chainId,
407
+ deadline,
408
+ requiredAllowance
409
+ );
410
+ return {
411
+ [EIP2612_GAS_SPONSORING_KEY]: { info }
412
+ };
413
+ }
414
+ async function trySignErc20ApprovalExtension(signer, options, requirements, context, approvalAmount) {
415
+ const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
416
+ if (!capabilities.readContract) {
417
+ return void 0;
418
+ }
419
+ if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {
420
+ return void 0;
421
+ }
422
+ if (!capabilities.signTransaction || !capabilities.getTransactionCount) {
423
+ return void 0;
424
+ }
425
+ const chainId = getEvmChainId(requirements.network);
426
+ const tokenAddress = (0, import_viem7.getAddress)(requirements.asset);
427
+ const requiredAllowance = approvalAmount ?? requirements.amount;
428
+ try {
429
+ const allowance = await capabilities.readContract({
430
+ address: tokenAddress,
431
+ abi: erc20AllowanceAbi,
432
+ functionName: "allowance",
433
+ args: [signer.address, PERMIT2_ADDRESS]
434
+ });
435
+ if (allowance >= BigInt(requiredAllowance)) {
436
+ return void 0;
437
+ }
438
+ } catch {
439
+ }
440
+ const info = await signErc20ApprovalTransaction(
441
+ {
442
+ address: signer.address,
443
+ signTransaction: capabilities.signTransaction,
444
+ getTransactionCount: capabilities.getTransactionCount,
445
+ estimateFeesPerGas: capabilities.estimateFeesPerGas
446
+ },
447
+ tokenAddress,
448
+ chainId
449
+ );
450
+ return {
451
+ [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info }
452
+ };
453
+ }
454
+
455
+ // src/batch-settlement/client/eip3009.ts
456
+ var import_viem9 = require("viem");
457
+
458
+ // src/batch-settlement/client/voucher.ts
459
+ async function signVoucher(signer, channelId, maxClaimableAmount, network) {
460
+ const chainId = getEvmChainId(network);
461
+ const signature = await signer.signTypedData({
462
+ domain: getBatchSettlementEip712Domain(chainId),
463
+ types: voucherTypes,
464
+ primaryType: "Voucher",
465
+ message: {
466
+ channelId,
467
+ maxClaimableAmount: BigInt(maxClaimableAmount)
468
+ }
469
+ });
470
+ return {
471
+ channelId,
472
+ maxClaimableAmount,
473
+ signature
474
+ };
475
+ }
476
+
477
+ // src/batch-settlement/encoding.ts
478
+ var import_viem8 = require("viem");
479
+ function buildErc3009DepositNonce(channelId, salt) {
480
+ return (0, import_viem8.keccak256)(
481
+ (0, import_viem8.encodeAbiParameters)([{ type: "bytes32" }, { type: "uint256" }], [channelId, BigInt(salt)])
482
+ );
483
+ }
484
+
485
+ // src/batch-settlement/client/eip3009.ts
486
+ async function createBatchSettlementEIP3009DepositPayload(signer, x402Version, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
487
+ const salt = createNonce();
488
+ const now = Math.floor(Date.now() / 1e3);
489
+ const chainId = getEvmChainId(paymentRequirements.network);
490
+ if (!paymentRequirements.extra?.name || !paymentRequirements.extra?.version) {
491
+ throw new Error(
492
+ `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`
493
+ );
494
+ }
495
+ const { name, version } = paymentRequirements.extra;
496
+ const channelId = computeChannelId(channelConfig, paymentRequirements.network);
497
+ const erc3009Nonce = buildErc3009DepositNonce(channelId, salt);
498
+ const signature = await signer.signTypedData({
499
+ domain: {
500
+ name,
501
+ version,
502
+ chainId,
503
+ verifyingContract: (0, import_viem9.getAddress)(paymentRequirements.asset)
504
+ },
505
+ types: receiveAuthorizationTypes,
506
+ primaryType: "ReceiveWithAuthorization",
507
+ message: {
508
+ from: (0, import_viem9.getAddress)(signer.address),
509
+ to: (0, import_viem9.getAddress)(ERC3009_DEPOSIT_COLLECTOR_ADDRESS),
510
+ value: BigInt(depositAmount),
511
+ validAfter: BigInt(now - 600),
512
+ validBefore: BigInt(now + paymentRequirements.maxTimeoutSeconds),
513
+ nonce: erc3009Nonce
514
+ }
515
+ });
516
+ const vSigner = voucherSigner ?? signer;
517
+ const voucher = await signVoucher(
518
+ vSigner,
519
+ channelId,
520
+ maxClaimableAmount,
521
+ paymentRequirements.network
522
+ );
523
+ const payload = {
524
+ type: "deposit",
525
+ channelConfig,
526
+ voucher,
527
+ deposit: {
528
+ amount: depositAmount,
529
+ authorization: {
530
+ erc3009Authorization: {
531
+ validAfter: (now - 600).toString(),
532
+ validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
533
+ salt,
534
+ signature
535
+ }
536
+ }
537
+ }
538
+ };
539
+ return {
540
+ x402Version,
541
+ payload
542
+ };
543
+ }
544
+
545
+ // src/batch-settlement/client/permit2.ts
546
+ var import_viem10 = require("viem");
547
+ async function createBatchSettlementPermit2DepositPayload(signer, x402Version, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
548
+ const chainId = getEvmChainId(paymentRequirements.network);
549
+ const nonce = createPermit2Nonce();
550
+ const deadline = Math.floor(Date.now() / 1e3 + paymentRequirements.maxTimeoutSeconds).toString();
551
+ const channelId = computeChannelId(channelConfig, paymentRequirements.network);
552
+ const permit2Authorization = {
553
+ from: signer.address,
554
+ permitted: {
555
+ token: (0, import_viem10.getAddress)(paymentRequirements.asset),
556
+ amount: depositAmount
557
+ },
558
+ spender: (0, import_viem10.getAddress)(PERMIT2_DEPOSIT_COLLECTOR_ADDRESS),
559
+ nonce,
560
+ deadline,
561
+ witness: {
562
+ channelId
563
+ }
564
+ };
565
+ const signature = await signer.signTypedData({
566
+ domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
567
+ types: batchPermit2WitnessTypes,
568
+ primaryType: "PermitWitnessTransferFrom",
569
+ message: {
570
+ permitted: {
571
+ token: permit2Authorization.permitted.token,
572
+ amount: BigInt(permit2Authorization.permitted.amount)
573
+ },
574
+ spender: permit2Authorization.spender,
575
+ nonce: BigInt(permit2Authorization.nonce),
576
+ deadline: BigInt(permit2Authorization.deadline),
577
+ witness: {
578
+ channelId
579
+ }
580
+ }
581
+ });
582
+ const voucher = await signVoucher(
583
+ voucherSigner ?? signer,
584
+ channelId,
585
+ maxClaimableAmount,
586
+ paymentRequirements.network
587
+ );
588
+ const payload = {
589
+ type: "deposit",
590
+ channelConfig,
591
+ voucher,
592
+ deposit: {
593
+ amount: depositAmount,
594
+ authorization: {
595
+ permit2Authorization: {
596
+ ...permit2Authorization,
597
+ signature
598
+ }
599
+ }
600
+ }
601
+ };
602
+ return { x402Version, payload };
603
+ }
604
+
605
+ // src/batch-settlement/client/storage.ts
606
+ var InMemoryClientChannelStorage = class {
607
+ constructor() {
608
+ this.channels = /* @__PURE__ */ new Map();
609
+ }
610
+ /**
611
+ * Returns the channel record for `key` if present.
612
+ *
613
+ * @param key - Channel storage key (channelId).
614
+ * @returns Persisted context or undefined.
615
+ */
616
+ async get(key) {
617
+ return this.channels.get(key);
618
+ }
619
+ /**
620
+ * Stores or replaces the channel record for `key`.
621
+ *
622
+ * @param key - Channel storage key.
623
+ * @param context - Channel fields to persist.
624
+ * @returns Resolves when stored.
625
+ */
626
+ async set(key, context) {
627
+ this.channels.set(key, context);
628
+ }
629
+ /**
630
+ * Removes the channel record for `key` if it exists.
631
+ *
632
+ * @param key - Channel storage key.
633
+ * @returns Resolves when removed.
634
+ */
635
+ async delete(key) {
636
+ this.channels.delete(key);
637
+ }
638
+ };
639
+
640
+ // src/batch-settlement/client/config.ts
641
+ var DEFAULT_SALT = "0x0000000000000000000000000000000000000000000000000000000000000000";
642
+ function isBatchSettlementEvmSchemeOptions(o) {
643
+ 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);
644
+ }
645
+ function resolveClientOptions(second) {
646
+ if (second === void 0) {
647
+ return { storage: new InMemoryClientChannelStorage(), salt: DEFAULT_SALT };
648
+ }
649
+ if (isBatchSettlementEvmSchemeOptions(second)) {
650
+ return {
651
+ storage: second.storage ?? new InMemoryClientChannelStorage(),
652
+ depositPolicy: second.depositPolicy,
653
+ depositStrategy: second.depositStrategy,
654
+ salt: second.salt ?? DEFAULT_SALT,
655
+ payerAuthorizer: second.payerAuthorizer,
656
+ voucherSigner: second.voucherSigner,
657
+ extensionRpcOptions: second.rpcUrl ? { rpcUrl: second.rpcUrl } : void 0
658
+ };
659
+ }
660
+ return {
661
+ storage: new InMemoryClientChannelStorage(),
662
+ depositPolicy: second,
663
+ salt: DEFAULT_SALT
664
+ };
665
+ }
666
+ function validateDepositPolicy(policy) {
667
+ if (!policy) return;
668
+ const m = policy.depositMultiplier;
669
+ if (m !== void 0 && (!Number.isInteger(m) || m < 3)) {
670
+ throw new Error("depositMultiplier must be an integer >= 3");
671
+ }
672
+ }
673
+ function depositAmountForRequest(policy, requestAmount) {
674
+ const mult = BigInt(policy?.depositMultiplier ?? 5);
675
+ return (mult * requestAmount).toString();
676
+ }
677
+
678
+ // src/batch-settlement/client/refund.ts
679
+ var import_http2 = require("@payai/x402/http");
680
+ var import_client = require("@payai/x402/client");
681
+
682
+ // src/batch-settlement/errors.ts
683
+ var ErrCumulativeAmountBelowClaimed = "invalid_batch_settlement_evm_cumulative_below_claimed";
684
+ var ErrCumulativeAmountMismatch = "invalid_batch_settlement_evm_cumulative_amount_mismatch";
685
+ var ErrRefundNoBalance = "invalid_batch_settlement_evm_refund_no_balance";
686
+ var ErrRefundAmountInvalid = "invalid_batch_settlement_evm_refund_amount_invalid";
687
+
688
+ // src/batch-settlement/client/channel.ts
689
+ var import_http = require("@payai/x402/http");
690
+ var import_viem11 = require("viem");
691
+
692
+ // src/batch-settlement/abi.ts
693
+ var channelConfigComponents = [
694
+ { name: "payer", type: "address" },
695
+ { name: "payerAuthorizer", type: "address" },
696
+ { name: "receiver", type: "address" },
697
+ { name: "receiverAuthorizer", type: "address" },
698
+ { name: "token", type: "address" },
699
+ { name: "withdrawDelay", type: "uint40" },
700
+ { name: "salt", type: "bytes32" }
701
+ ];
702
+ var voucherClaimComponents = [
703
+ {
704
+ name: "voucher",
705
+ type: "tuple",
706
+ components: [
707
+ {
708
+ name: "channel",
709
+ type: "tuple",
710
+ components: channelConfigComponents
711
+ },
712
+ { name: "maxClaimableAmount", type: "uint128" }
713
+ ]
714
+ },
715
+ { name: "signature", type: "bytes" },
716
+ { name: "totalClaimed", type: "uint128" }
717
+ ];
718
+ var batchSettlementABI = [
719
+ {
720
+ type: "function",
721
+ name: "multicall",
722
+ inputs: [{ name: "data", type: "bytes[]" }],
723
+ outputs: [{ name: "results", type: "bytes[]" }],
724
+ stateMutability: "nonpayable"
725
+ },
726
+ {
727
+ type: "function",
728
+ name: "deposit",
729
+ inputs: [
730
+ { name: "config", type: "tuple", components: channelConfigComponents },
731
+ { name: "amount", type: "uint128" },
732
+ { name: "collector", type: "address" },
733
+ { name: "collectorData", type: "bytes" }
734
+ ],
735
+ outputs: [],
736
+ stateMutability: "nonpayable"
737
+ },
738
+ {
739
+ type: "function",
740
+ name: "claim",
741
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
742
+ outputs: [],
743
+ stateMutability: "nonpayable"
744
+ },
745
+ {
746
+ type: "function",
747
+ name: "claimWithSignature",
748
+ inputs: [
749
+ { name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents },
750
+ { name: "authorizerSignature", type: "bytes" }
751
+ ],
752
+ outputs: [],
753
+ stateMutability: "nonpayable"
754
+ },
755
+ {
756
+ type: "function",
757
+ name: "settle",
758
+ inputs: [
759
+ { name: "receiver", type: "address" },
760
+ { name: "token", type: "address" }
761
+ ],
762
+ outputs: [],
763
+ stateMutability: "nonpayable"
764
+ },
765
+ {
766
+ type: "function",
767
+ name: "initiateWithdraw",
768
+ inputs: [
769
+ { name: "config", type: "tuple", components: channelConfigComponents },
770
+ { name: "amount", type: "uint128" }
771
+ ],
772
+ outputs: [],
773
+ stateMutability: "nonpayable"
774
+ },
775
+ {
776
+ type: "function",
777
+ name: "finalizeWithdraw",
778
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
779
+ outputs: [],
780
+ stateMutability: "nonpayable"
781
+ },
782
+ {
783
+ type: "function",
784
+ name: "refund",
785
+ inputs: [
786
+ { name: "config", type: "tuple", components: channelConfigComponents },
787
+ { name: "amount", type: "uint128" }
788
+ ],
789
+ outputs: [],
790
+ stateMutability: "nonpayable"
791
+ },
792
+ {
793
+ type: "function",
794
+ name: "refundWithSignature",
795
+ inputs: [
796
+ { name: "config", type: "tuple", components: channelConfigComponents },
797
+ { name: "amount", type: "uint128" },
798
+ { name: "nonce", type: "uint256" },
799
+ { name: "receiverAuthorizerSignature", type: "bytes" }
800
+ ],
801
+ outputs: [],
802
+ stateMutability: "nonpayable"
803
+ },
804
+ {
805
+ type: "function",
806
+ name: "getChannelId",
807
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
808
+ outputs: [{ name: "", type: "bytes32" }],
809
+ stateMutability: "view"
810
+ },
811
+ {
812
+ type: "function",
813
+ name: "CHANNEL_CONFIG_TYPEHASH",
814
+ inputs: [],
815
+ outputs: [{ name: "", type: "bytes32" }],
816
+ stateMutability: "view"
817
+ },
818
+ {
819
+ type: "function",
820
+ name: "channels",
821
+ inputs: [{ name: "channelId", type: "bytes32" }],
822
+ outputs: [
823
+ { name: "balance", type: "uint128" },
824
+ { name: "totalClaimed", type: "uint128" }
825
+ ],
826
+ stateMutability: "view"
827
+ },
828
+ {
829
+ type: "function",
830
+ name: "pendingWithdrawals",
831
+ inputs: [{ name: "channelId", type: "bytes32" }],
832
+ outputs: [
833
+ { name: "amount", type: "uint128" },
834
+ { name: "initiatedAt", type: "uint40" }
835
+ ],
836
+ stateMutability: "view"
837
+ },
838
+ {
839
+ type: "function",
840
+ name: "receivers",
841
+ inputs: [
842
+ { name: "receiver", type: "address" },
843
+ { name: "token", type: "address" }
844
+ ],
845
+ outputs: [
846
+ { name: "totalClaimed", type: "uint128" },
847
+ { name: "totalSettled", type: "uint128" }
848
+ ],
849
+ stateMutability: "view"
850
+ },
851
+ {
852
+ type: "function",
853
+ name: "getVoucherDigest",
854
+ inputs: [
855
+ { name: "channelId", type: "bytes32" },
856
+ { name: "maxClaimableAmount", type: "uint128" }
857
+ ],
858
+ outputs: [{ name: "", type: "bytes32" }],
859
+ stateMutability: "view"
860
+ },
861
+ {
862
+ type: "function",
863
+ name: "getRefundDigest",
864
+ inputs: [
865
+ { name: "channelId", type: "bytes32" },
866
+ { name: "nonce", type: "uint256" },
867
+ { name: "amount", type: "uint128" }
868
+ ],
869
+ outputs: [{ name: "", type: "bytes32" }],
870
+ stateMutability: "view"
871
+ },
872
+ {
873
+ type: "function",
874
+ name: "refundNonce",
875
+ inputs: [{ name: "channelId", type: "bytes32" }],
876
+ outputs: [{ name: "", type: "uint256" }],
877
+ stateMutability: "view"
878
+ },
879
+ {
880
+ type: "function",
881
+ name: "getClaimBatchDigest",
882
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
883
+ outputs: [{ name: "", type: "bytes32" }],
884
+ stateMutability: "view"
885
+ },
886
+ {
887
+ type: "event",
888
+ name: "Settled",
889
+ inputs: [
890
+ { name: "receiver", type: "address", indexed: true },
891
+ { name: "token", type: "address", indexed: true },
892
+ { name: "sender", type: "address", indexed: true },
893
+ { name: "amount", type: "uint128", indexed: false }
894
+ ],
895
+ anonymous: false
896
+ }
897
+ ];
898
+
899
+ // src/batch-settlement/client/channel.ts
900
+ function readResponseChannelState(extra) {
901
+ const channelState = extra.channelState;
902
+ if (typeof channelState !== "object" || channelState === null) {
903
+ return void 0;
904
+ }
905
+ return channelState;
906
+ }
907
+ function buildChannelConfig(deps, paymentRequirements) {
908
+ const extra = paymentRequirements.extra;
909
+ const receiverAuthorizer = extra?.receiverAuthorizer;
910
+ if (!receiverAuthorizer || (0, import_viem11.getAddress)(receiverAuthorizer) === "0x0000000000000000000000000000000000000000") {
911
+ throw new Error("Payment requirements must include a non-zero extra.receiverAuthorizer");
912
+ }
913
+ return {
914
+ payer: deps.signer.address,
915
+ payerAuthorizer: (0, import_viem11.getAddress)(
916
+ deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
917
+ ),
918
+ receiver: paymentRequirements.payTo,
919
+ receiverAuthorizer: (0, import_viem11.getAddress)(receiverAuthorizer),
920
+ token: paymentRequirements.asset,
921
+ withdrawDelay: typeof extra?.withdrawDelay === "number" ? extra.withdrawDelay : MIN_WITHDRAW_DELAY,
922
+ salt: deps.salt
923
+ };
924
+ }
925
+ async function processSettleResponse(storage, settle) {
926
+ const extra = settle.extra ?? {};
927
+ const channelState = readResponseChannelState(extra);
928
+ if (!channelState) return;
929
+ const channelId = channelState.channelId;
930
+ const key = channelId.toLowerCase();
931
+ const prev = await storage.get(key);
932
+ const next = { ...prev ?? {} };
933
+ if (channelState.chargedCumulativeAmount !== void 0) {
934
+ next.chargedCumulativeAmount = String(channelState.chargedCumulativeAmount);
935
+ }
936
+ if (channelState.balance !== void 0) {
937
+ next.balance = String(channelState.balance);
938
+ }
939
+ if (channelState.totalClaimed !== void 0) {
940
+ next.totalClaimed = String(channelState.totalClaimed);
941
+ }
942
+ await storage.set(key, next);
943
+ }
944
+ async function updateChannelAfterRefund(storage, channelKey, settleExtra) {
945
+ const channelState = readResponseChannelState(settleExtra);
946
+ if (!channelState) {
947
+ await storage.delete(channelKey);
948
+ return;
949
+ }
950
+ const balanceAfter = channelState.balance !== void 0 ? BigInt(String(channelState.balance)) : void 0;
951
+ if (balanceAfter === void 0 || balanceAfter <= 0n) {
952
+ await storage.delete(channelKey);
953
+ return;
954
+ }
955
+ const prev = await storage.get(channelKey);
956
+ const next = { ...prev ?? {} };
957
+ next.balance = balanceAfter.toString();
958
+ if (channelState.chargedCumulativeAmount !== void 0) {
959
+ next.chargedCumulativeAmount = String(channelState.chargedCumulativeAmount);
960
+ }
961
+ if (channelState.totalClaimed !== void 0) {
962
+ next.totalClaimed = String(channelState.totalClaimed);
963
+ }
964
+ await storage.set(channelKey, next);
965
+ }
966
+ async function processPaymentResponse(storage, getHeader) {
967
+ const raw = getHeader("PAYMENT-RESPONSE");
968
+ if (!raw) return;
969
+ const settle = (0, import_http.decodePaymentResponseHeader)(raw);
970
+ await processSettleResponse(storage, settle);
971
+ }
972
+ async function recoverChannel(deps, paymentRequirements) {
973
+ if (!deps.signer.readContract) {
974
+ throw new Error("recoverChannel requires ClientEvmSigner.readContract");
975
+ }
976
+ const config = buildChannelConfig(deps, paymentRequirements);
977
+ const channelId = computeChannelId(config, paymentRequirements.network);
978
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
979
+ deps.signer,
980
+ channelId
981
+ );
982
+ const ctx = {
983
+ chargedCumulativeAmount: chTotalClaimed.toString(),
984
+ balance: chBalance.toString(),
985
+ totalClaimed: chTotalClaimed.toString()
986
+ };
987
+ await deps.storage.set(channelId.toLowerCase(), ctx);
988
+ return ctx;
989
+ }
990
+ async function readChannelBalanceAndTotalClaimed(signer, channelId) {
991
+ if (!signer.readContract) {
992
+ throw new Error("readChannelBalanceAndTotalClaimed requires ClientEvmSigner.readContract");
993
+ }
994
+ return await signer.readContract({
995
+ address: BATCH_SETTLEMENT_ADDRESS,
996
+ abi: batchSettlementABI,
997
+ functionName: "channels",
998
+ args: [channelId]
999
+ });
1000
+ }
1001
+ async function hasChannel(storage, channelId) {
1002
+ const channel = await storage.get(channelId.toLowerCase());
1003
+ return channel !== void 0;
1004
+ }
1005
+ async function getChannel(storage, channelId) {
1006
+ return storage.get(channelId.toLowerCase());
1007
+ }
1008
+
1009
+ // src/batch-settlement/types.ts
1010
+ function isObject(payload) {
1011
+ return typeof payload === "object" && payload !== null;
1012
+ }
1013
+ function isVoucherFields(payload) {
1014
+ return isObject(payload) && "channelId" in payload && "maxClaimableAmount" in payload && "signature" in payload;
1015
+ }
1016
+ function isBatchSettlementRefundPayload(payload) {
1017
+ return isObject(payload) && payload.type === "refund" && "channelConfig" in payload && isVoucherFields(payload.voucher);
1018
+ }
1019
+
1020
+ // src/batch-settlement/client/recovery.ts
1021
+ var import_viem12 = require("viem");
1022
+ async function processCorrectivePaymentRequired(deps, paymentRequired) {
1023
+ if (paymentRequired.error !== ErrCumulativeAmountMismatch && paymentRequired.error !== ErrCumulativeAmountBelowClaimed) {
1024
+ return false;
1025
+ }
1026
+ const accept = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
1027
+ if (!accept) {
1028
+ return false;
1029
+ }
1030
+ const channelState = accept.extra.channelState;
1031
+ const voucherState = accept.extra.voucherState;
1032
+ const hasSig = channelState?.chargedCumulativeAmount !== void 0 && voucherState?.signedMaxClaimable !== void 0 && voucherState.signature !== void 0;
1033
+ if (!hasSig) {
1034
+ return recoverFromOnChainState(deps, accept);
1035
+ }
1036
+ return recoverFromSignature(deps, accept, channelState, voucherState);
1037
+ }
1038
+ async function recoverFromSignature(deps, accept, channelState, voucherState) {
1039
+ const chargedRaw = channelState.chargedCumulativeAmount;
1040
+ const signedRaw = voucherState.signedMaxClaimable;
1041
+ const sig = voucherState.signature;
1042
+ const charged = BigInt(String(chargedRaw));
1043
+ const signed = BigInt(String(signedRaw));
1044
+ if (charged > signed) {
1045
+ return false;
1046
+ }
1047
+ const config = buildChannelConfig(deps, accept);
1048
+ const channelId = computeChannelId(config, accept.network);
1049
+ if (!deps.signer.readContract) {
1050
+ return false;
1051
+ }
1052
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1053
+ deps.signer,
1054
+ channelId
1055
+ );
1056
+ if (charged < chTotalClaimed) {
1057
+ return false;
1058
+ }
1059
+ const chainId = getEvmChainId(accept.network);
1060
+ const recovered = await (0, import_viem12.recoverTypedDataAddress)({
1061
+ domain: getBatchSettlementEip712Domain(chainId),
1062
+ types: voucherTypes,
1063
+ primaryType: "Voucher",
1064
+ message: {
1065
+ channelId,
1066
+ maxClaimableAmount: signed
1067
+ },
1068
+ signature: sig
1069
+ });
1070
+ const expectedSigner = (0, import_viem12.getAddress)(
1071
+ deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
1072
+ );
1073
+ if (recovered.toLowerCase() !== expectedSigner.toLowerCase()) {
1074
+ return false;
1075
+ }
1076
+ const ctx = {
1077
+ chargedCumulativeAmount: charged.toString(),
1078
+ signedMaxClaimable: signed.toString(),
1079
+ signature: sig,
1080
+ balance: chBalance.toString(),
1081
+ totalClaimed: chTotalClaimed.toString()
1082
+ };
1083
+ await deps.storage.set(channelId.toLowerCase(), ctx);
1084
+ return true;
1085
+ }
1086
+ async function recoverFromOnChainState(deps, accept) {
1087
+ if (!deps.signer.readContract) {
1088
+ return false;
1089
+ }
1090
+ const config = buildChannelConfig(deps, accept);
1091
+ const channelId = computeChannelId(config, accept.network);
1092
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1093
+ deps.signer,
1094
+ channelId
1095
+ );
1096
+ const ctx = {
1097
+ chargedCumulativeAmount: chTotalClaimed.toString(),
1098
+ balance: chBalance.toString(),
1099
+ totalClaimed: chTotalClaimed.toString()
1100
+ };
1101
+ await deps.storage.set(channelId.toLowerCase(), ctx);
1102
+ return true;
1103
+ }
1104
+
1105
+ // src/batch-settlement/client/hooks.ts
1106
+ function createBatchSettlementClientHooks(deps) {
1107
+ return {
1108
+ onPaymentResponse: (ctx) => handleBatchSettlementPaymentResponse(deps, ctx)
1109
+ };
1110
+ }
1111
+ async function handleBatchSettlementPaymentResponse(deps, ctx) {
1112
+ if (ctx.settleResponse) {
1113
+ if (isBatchSettlementRefundPayload(ctx.paymentPayload.payload)) {
1114
+ const extra = ctx.settleResponse.extra ?? {};
1115
+ const channelState = extra.channelState;
1116
+ const channelId = typeof channelState === "object" && channelState !== null && "channelId" in channelState ? channelState.channelId : void 0;
1117
+ if (typeof channelId === "string" && channelId) {
1118
+ await updateChannelAfterRefund(deps.storage, channelId.toLowerCase(), extra);
1119
+ }
1120
+ return;
1121
+ }
1122
+ await processSettleResponse(deps.storage, ctx.settleResponse);
1123
+ return;
1124
+ }
1125
+ if (ctx.paymentRequired) {
1126
+ const recovered = await processCorrectivePaymentRequired(deps, ctx.paymentRequired);
1127
+ return recovered ? { recovered: true } : void 0;
1128
+ }
1129
+ }
1130
+
1131
+ // src/batch-settlement/client/refund.ts
1132
+ var NON_RECOVERABLE_REFUND_ERRORS = /* @__PURE__ */ new Set([
1133
+ ErrRefundNoBalance,
1134
+ ErrRefundAmountInvalid
1135
+ ]);
1136
+ async function refundChannel(ctx, url, options) {
1137
+ const fetchImpl = options?.fetch ?? globalThis.fetch;
1138
+ if (!fetchImpl) {
1139
+ throw new Error("refund requires a fetch implementation (globalThis.fetch unavailable)");
1140
+ }
1141
+ const refundAmount = normalizeRefundAmount(options?.amount);
1142
+ const probe = await probeRefundRequirements(url, fetchImpl);
1143
+ return executeRefund(ctx, url, probe, refundAmount, fetchImpl);
1144
+ }
1145
+ async function probeRefundRequirements(url, fetchImpl) {
1146
+ const probe = await fetchImpl(url, { method: "GET" });
1147
+ if (probe.status !== 402) {
1148
+ throw new Error(`Refund probe expected 402, got ${probe.status}`);
1149
+ }
1150
+ const header = probe.headers.get("PAYMENT-REQUIRED");
1151
+ if (!header) {
1152
+ throw new Error("Refund probe response missing PAYMENT-REQUIRED header");
1153
+ }
1154
+ const paymentRequired = (0, import_http2.decodePaymentRequiredHeader)(header);
1155
+ const requirements = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
1156
+ if (!requirements) {
1157
+ throw new Error(`No ${BATCH_SETTLEMENT_SCHEME} payment option at ${url}`);
1158
+ }
1159
+ const extra = requirements.extra;
1160
+ if (!extra?.receiverAuthorizer) {
1161
+ throw new Error("Refund requires a configured receiverAuthorizer on the receiver");
1162
+ }
1163
+ return { paymentRequired, requirements };
1164
+ }
1165
+ async function executeRefund(ctx, url, probe, refundAmount, fetchImpl) {
1166
+ const maxAttempts = 2;
1167
+ const { paymentRequired, requirements } = probe;
1168
+ const httpClient = createRefundHttpClient(ctx, requirements);
1169
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
1170
+ const paymentPayload = await buildRefundPaymentPayload(
1171
+ ctx,
1172
+ paymentRequired,
1173
+ requirements,
1174
+ refundAmount
1175
+ );
1176
+ const headers = httpClient.encodePaymentSignatureHeader(paymentPayload);
1177
+ const response = await fetchImpl(url, { method: "GET", headers });
1178
+ if (response.status === 402) {
1179
+ const nonRecoverable = getNonRecoverableRefundFailure(response);
1180
+ if (nonRecoverable) {
1181
+ throw new Error(nonRecoverable);
1182
+ }
1183
+ }
1184
+ const result = await httpClient.processPaymentResult(
1185
+ paymentPayload,
1186
+ (name) => response.headers.get(name),
1187
+ response.status
1188
+ );
1189
+ if (response.status === 402) {
1190
+ if (result.recovered && attempt < maxAttempts) {
1191
+ continue;
1192
+ }
1193
+ if (result.recovered) {
1194
+ throw new Error(`Refund failed: server returned 402 after ${attempt} attempt(s)`);
1195
+ }
1196
+ const corrective = getRefundPaymentRequired(response);
1197
+ throw new Error(`Refund failed: ${corrective.error ?? "unknown"}`);
1198
+ }
1199
+ if (!result.settleResponse) {
1200
+ throw new Error(
1201
+ `Refund response missing PAYMENT-RESPONSE header (status ${response.status})`
1202
+ );
1203
+ }
1204
+ return result.settleResponse;
1205
+ }
1206
+ throw new Error("Refund failed: retry budget exhausted");
1207
+ }
1208
+ async function buildRefundPaymentPayload(ctx, paymentRequired, requirements, refundAmount) {
1209
+ const config = buildChannelConfig(ctx, requirements);
1210
+ const channelId = computeChannelId(config, requirements.network);
1211
+ const key = channelId.toLowerCase();
1212
+ let channel = await ctx.storage.get(key);
1213
+ if (channel === void 0 && ctx.signer.readContract) {
1214
+ channel = await recoverChannel(ctx, requirements);
1215
+ }
1216
+ if (channel === void 0) {
1217
+ throw new Error(
1218
+ "Refund requires an existing channel record; deposit first or call from a context with an EVM RPC"
1219
+ );
1220
+ }
1221
+ const charged = channel.chargedCumulativeAmount ?? "0";
1222
+ if (channel.balance !== void 0 && BigInt(channel.balance) <= BigInt(charged)) {
1223
+ throw new Error(
1224
+ `Refund failed: channel has no remaining balance (balance=${channel.balance}, chargedCumulativeAmount=${charged})`
1225
+ );
1226
+ }
1227
+ const voucherSigner = ctx.voucherSigner ?? ctx.signer;
1228
+ const voucher = await signVoucher(voucherSigner, channelId, charged, requirements.network);
1229
+ const payload = {
1230
+ type: "refund",
1231
+ channelConfig: config,
1232
+ voucher,
1233
+ ...refundAmount !== void 0 ? { amount: refundAmount } : {}
1234
+ };
1235
+ return {
1236
+ x402Version: 2,
1237
+ accepted: requirements,
1238
+ payload,
1239
+ ...paymentRequired.resource ? { resource: paymentRequired.resource } : {},
1240
+ ...paymentRequired.extensions ? { extensions: paymentRequired.extensions } : {}
1241
+ };
1242
+ }
1243
+ function createRefundHttpClient(ctx, requirements) {
1244
+ const client = new import_client.x402Client().register(requirements.network, {
1245
+ scheme: BATCH_SETTLEMENT_SCHEME,
1246
+ schemeHooks: createBatchSettlementClientHooks(ctx),
1247
+ createPaymentPayload: async () => {
1248
+ throw new Error("Refund payloads are built by refundChannel");
1249
+ }
1250
+ });
1251
+ return new import_client.x402HTTPClient(client);
1252
+ }
1253
+ function getNonRecoverableRefundFailure(response) {
1254
+ const settleHeader = response.headers.get("PAYMENT-RESPONSE");
1255
+ if (settleHeader) {
1256
+ return formatRefundFailure((0, import_http2.decodePaymentResponseHeader)(settleHeader));
1257
+ }
1258
+ const paymentRequired = getRefundPaymentRequired(response);
1259
+ const errorCode = paymentRequired.error;
1260
+ if (errorCode && NON_RECOVERABLE_REFUND_ERRORS.has(errorCode)) {
1261
+ return `Refund failed: ${errorCode}`;
1262
+ }
1263
+ }
1264
+ function getRefundPaymentRequired(response) {
1265
+ const requiredHeader = response.headers.get("PAYMENT-REQUIRED");
1266
+ if (!requiredHeader) {
1267
+ throw new Error("Refund 402 missing PAYMENT-REQUIRED header");
1268
+ }
1269
+ return (0, import_http2.decodePaymentRequiredHeader)(requiredHeader);
1270
+ }
1271
+ function formatRefundFailure(settle) {
1272
+ const reason = settle.errorReason ?? "unknown_settlement_error";
1273
+ const message = settle.errorMessage;
1274
+ if (message && message !== reason) {
1275
+ return `Refund failed: ${reason}: ${message}`;
1276
+ }
1277
+ return `Refund failed: ${reason}`;
1278
+ }
1279
+ function normalizeRefundAmount(amount) {
1280
+ if (amount === void 0) return void 0;
1281
+ if (!/^\d+$/.test(amount) || amount === "0") {
1282
+ throw new Error(`Invalid refund amount "${amount}": must be a positive integer string`);
1283
+ }
1284
+ return amount;
1285
+ }
1286
+
1287
+ // src/batch-settlement/client/scheme.ts
1288
+ var BatchSettlementEvmScheme = class {
1289
+ /**
1290
+ * Constructs a batched client scheme.
1291
+ *
1292
+ * @param signer - Client EVM wallet used for signing vouchers and ERC-3009 authorizations.
1293
+ * @param optionsOrPolicy - Either a full options object or a bare deposit-policy.
1294
+ */
1295
+ constructor(signer, optionsOrPolicy) {
1296
+ this.signer = signer;
1297
+ this.scheme = BATCH_SETTLEMENT_SCHEME;
1298
+ const {
1299
+ storage,
1300
+ depositPolicy,
1301
+ depositStrategy,
1302
+ salt,
1303
+ payerAuthorizer,
1304
+ voucherSigner,
1305
+ extensionRpcOptions
1306
+ } = resolveClientOptions(optionsOrPolicy);
1307
+ this.storage = storage;
1308
+ this.depositPolicy = depositPolicy;
1309
+ this.depositStrategy = depositStrategy;
1310
+ this.salt = salt;
1311
+ this.payerAuthorizer = payerAuthorizer;
1312
+ this.voucherSigner = voucherSigner;
1313
+ this.extensionRpcOptions = extensionRpcOptions;
1314
+ if (payerAuthorizer !== void 0 && voucherSigner !== void 0 && (0, import_viem13.getAddress)(payerAuthorizer) !== (0, import_viem13.getAddress)(voucherSigner.address)) {
1315
+ throw new Error("payerAuthorizer address must match voucherSigner.address");
1316
+ }
1317
+ validateDepositPolicy(depositPolicy);
1318
+ this.schemeHooks = createBatchSettlementClientHooks(this.deps());
1319
+ }
1320
+ /**
1321
+ * Creates the payment payload for a batched request.
1322
+ *
1323
+ * If the channel has no onchain deposit (or needs a top-up), builds an
1324
+ * ERC-3009 deposit payload bundled with a voucher. Otherwise, signs and
1325
+ * returns a voucher-only payload.
1326
+ *
1327
+ * @param x402Version - Protocol version for the payload envelope.
1328
+ * @param paymentRequirements - Server payment requirements (scheme, network, asset, amount).
1329
+ * @param context - Optional payment payload context with extension hints.
1330
+ * @returns A {@link PaymentPayloadResult} ready to be sent as the `X-PAYMENT` header.
1331
+ */
1332
+ async createPaymentPayload(x402Version, paymentRequirements, context) {
1333
+ const deps = this.deps();
1334
+ const config = buildChannelConfig(deps, paymentRequirements);
1335
+ const channelId = computeChannelId(config, paymentRequirements.network);
1336
+ const key = channelId.toLowerCase();
1337
+ let batchedCtx = await this.storage.get(key);
1338
+ if (batchedCtx === void 0 && this.signer.readContract) {
1339
+ batchedCtx = await recoverChannel(deps, paymentRequirements);
1340
+ }
1341
+ batchedCtx = batchedCtx ?? {};
1342
+ const needsInitialDeposit = !batchedCtx.balance || batchedCtx.balance === "0";
1343
+ const baseCumulative = BigInt(batchedCtx.chargedCumulativeAmount ?? "0");
1344
+ const requestAmount = BigInt(paymentRequirements.amount);
1345
+ const maxClaimableAmount = (baseCumulative + requestAmount).toString();
1346
+ const currentBalance = BigInt(batchedCtx.balance ?? "0");
1347
+ const needsTopUp = !needsInitialDeposit && BigInt(maxClaimableAmount) > currentBalance;
1348
+ if (needsInitialDeposit || needsTopUp) {
1349
+ const computedDeposit = depositAmountForRequest(this.depositPolicy, requestAmount);
1350
+ const minimumDepositAmount = BigInt(maxClaimableAmount) - currentBalance;
1351
+ const depositAmount = await this.resolveDepositAmount({
1352
+ paymentRequirements,
1353
+ channelConfig: config,
1354
+ channelId,
1355
+ clientContext: batchedCtx,
1356
+ requestAmount: requestAmount.toString(),
1357
+ maxClaimableAmount,
1358
+ currentBalance: currentBalance.toString(),
1359
+ minimumDepositAmount: minimumDepositAmount.toString(),
1360
+ depositAmount: computedDeposit
1361
+ });
1362
+ if (depositAmount === false) {
1363
+ return this.createVoucherPayload(
1364
+ x402Version,
1365
+ channelId,
1366
+ maxClaimableAmount,
1367
+ paymentRequirements.network,
1368
+ config
1369
+ );
1370
+ }
1371
+ const assetTransferMethod = paymentRequirements.extra?.assetTransferMethod ?? "eip3009";
1372
+ if (assetTransferMethod === "eip3009") {
1373
+ return createBatchSettlementEIP3009DepositPayload(
1374
+ this.signer,
1375
+ x402Version,
1376
+ paymentRequirements,
1377
+ config,
1378
+ depositAmount,
1379
+ maxClaimableAmount,
1380
+ this.voucherSigner
1381
+ );
1382
+ }
1383
+ if (assetTransferMethod !== "permit2") {
1384
+ throw new Error(`unsupported batch-settlement assetTransferMethod: ${assetTransferMethod}`);
1385
+ }
1386
+ const result = await createBatchSettlementPermit2DepositPayload(
1387
+ this.signer,
1388
+ x402Version,
1389
+ paymentRequirements,
1390
+ config,
1391
+ depositAmount,
1392
+ maxClaimableAmount,
1393
+ this.voucherSigner
1394
+ );
1395
+ const eip2612Extensions = await trySignEip2612PermitExtension(
1396
+ this.signer,
1397
+ this.extensionRpcOptions,
1398
+ paymentRequirements,
1399
+ result,
1400
+ context,
1401
+ depositAmount
1402
+ );
1403
+ if (eip2612Extensions) {
1404
+ return { ...result, extensions: eip2612Extensions };
1405
+ }
1406
+ const erc20Extensions = await trySignErc20ApprovalExtension(
1407
+ this.signer,
1408
+ this.extensionRpcOptions,
1409
+ paymentRequirements,
1410
+ context,
1411
+ depositAmount
1412
+ );
1413
+ if (erc20Extensions) {
1414
+ return { ...result, extensions: erc20Extensions };
1415
+ }
1416
+ return result;
1417
+ }
1418
+ return this.createVoucherPayload(
1419
+ x402Version,
1420
+ channelId,
1421
+ maxClaimableAmount,
1422
+ paymentRequirements.network,
1423
+ config
1424
+ );
1425
+ }
1426
+ /**
1427
+ * Sends a cooperative refund request.
1428
+ *
1429
+ * @param url - The route URL backing the channel to refund.
1430
+ * @param options - Optional `amount` (partial refund) and `fetch` override.
1431
+ * @returns The settle response describing the refund outcome.
1432
+ */
1433
+ async refund(url, options) {
1434
+ return refundChannel(this.deps(), url, options);
1435
+ }
1436
+ /**
1437
+ * Updates local channel state from a settle response.
1438
+ *
1439
+ * @param settle - The parsed settle response from the server.
1440
+ * @returns Resolves when local channel state has been updated.
1441
+ */
1442
+ async processSettleResponse(settle) {
1443
+ return processSettleResponse(this.storage, settle);
1444
+ }
1445
+ /**
1446
+ * Resyncs local channel state from a corrective 402 response.
1447
+ *
1448
+ * @param paymentRequired - The decoded 402 response body.
1449
+ * @returns `true` if local state was successfully resynced and a retry is warranted.
1450
+ */
1451
+ async processCorrectivePaymentRequired(paymentRequired) {
1452
+ return processCorrectivePaymentRequired(this.deps(), paymentRequired);
1453
+ }
1454
+ /**
1455
+ * Builds the immutable {@link ChannelConfig} for a given set of payment
1456
+ * requirements, using the scheme's own signer and salt.
1457
+ *
1458
+ * @param paymentRequirements - Server payment requirements for the channel.
1459
+ * @returns The channel config that uniquely identifies the payment channel.
1460
+ */
1461
+ buildChannelConfig(paymentRequirements) {
1462
+ return buildChannelConfig(this.deps(), paymentRequirements);
1463
+ }
1464
+ /**
1465
+ * Resolves the deposit amount after applying the optional custom strategy.
1466
+ *
1467
+ * @param context - Deposit attempt context exposed to the strategy.
1468
+ * @returns The deposit amount to sign, or `false` to skip this deposit attempt.
1469
+ */
1470
+ async resolveDepositAmount(context) {
1471
+ const strategyResult = await this.depositStrategy?.(context);
1472
+ if (strategyResult === false) return false;
1473
+ if (strategyResult === void 0) return context.depositAmount;
1474
+ const depositAmount = this.normalizeStrategyDepositAmount(strategyResult);
1475
+ if (BigInt(depositAmount) < BigInt(context.minimumDepositAmount)) {
1476
+ throw new Error(
1477
+ `depositStrategy returned ${depositAmount}, below required top-up ${context.minimumDepositAmount}`
1478
+ );
1479
+ }
1480
+ return depositAmount;
1481
+ }
1482
+ /**
1483
+ * Normalizes and validates a strategy-provided base-unit deposit amount.
1484
+ *
1485
+ * @param value - Strategy-provided string or bigint amount.
1486
+ * @returns Normalized decimal string.
1487
+ */
1488
+ normalizeStrategyDepositAmount(value) {
1489
+ if (typeof value === "bigint") {
1490
+ if (value <= 0n) {
1491
+ throw new Error("depositStrategy must return a positive integer deposit amount");
1492
+ }
1493
+ return value.toString();
1494
+ }
1495
+ if (/^\d+$/.test(value) && BigInt(value) > 0n) {
1496
+ return BigInt(value).toString();
1497
+ }
1498
+ throw new Error("depositStrategy must return a positive integer deposit amount");
1499
+ }
1500
+ /**
1501
+ * Signs a voucher-only payment payload for the current channel.
1502
+ *
1503
+ * @param x402Version - Protocol version for the payload envelope.
1504
+ * @param channelId - Channel identifier for the voucher.
1505
+ * @param maxClaimableAmount - Cumulative ceiling for the voucher.
1506
+ * @param network - CAIP-2 network identifier.
1507
+ * @param config - Immutable channel configuration.
1508
+ * @returns Voucher-only payment payload.
1509
+ */
1510
+ async createVoucherPayload(x402Version, channelId, maxClaimableAmount, network, config) {
1511
+ const voucherSigner = this.voucherSigner ?? this.signer;
1512
+ const voucher = await signVoucher(voucherSigner, channelId, maxClaimableAmount, network);
1513
+ const payload = {
1514
+ type: "voucher",
1515
+ channelConfig: config,
1516
+ voucher
1517
+ };
1518
+ return {
1519
+ x402Version,
1520
+ payload
1521
+ };
1522
+ }
1523
+ /**
1524
+ * Bundles the class state into the {@link BatchSettlementClientDeps} shape
1525
+ * consumed by the `channel`, `recovery`, and `refund` modules.
1526
+ *
1527
+ * @returns Client deps wrapping the scheme's own signer and storage.
1528
+ */
1529
+ deps() {
1530
+ return {
1531
+ signer: this.signer,
1532
+ storage: this.storage,
1533
+ salt: this.salt,
1534
+ payerAuthorizer: this.payerAuthorizer,
1535
+ voucherSigner: this.voucherSigner
1536
+ };
1537
+ }
1538
+ };
1539
+ // Annotate the CommonJS export names for ESM import in node:
1540
+ 0 && (module.exports = {
1541
+ BatchSettlementEvmScheme,
1542
+ InMemoryClientChannelStorage,
1543
+ buildChannelConfig,
1544
+ computeChannelId,
1545
+ createBatchSettlementClientHooks,
1546
+ createBatchSettlementEIP3009DepositPayload,
1547
+ depositAmountForRequest,
1548
+ getChannel,
1549
+ handleBatchSettlementPaymentResponse,
1550
+ hasChannel,
1551
+ isBatchSettlementEvmSchemeOptions,
1552
+ processCorrectivePaymentRequired,
1553
+ processPaymentResponse,
1554
+ processSettleResponse,
1555
+ readChannelBalanceAndTotalClaimed,
1556
+ recoverChannel,
1557
+ recoverFromOnChainState,
1558
+ recoverFromSignature,
1559
+ refundChannel,
1560
+ resolveClientOptions,
1561
+ signVoucher,
1562
+ updateChannelAfterRefund,
1563
+ validateDepositPolicy
1564
+ });
1565
+ //# sourceMappingURL=index.js.map