@dvmkit/dvm-cli 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/{_esm-M2HUAA3B.js → _esm-MN4BUYV6.js} +56 -54
  2. package/dist/{accounts-S747UW3A.js → accounts-2WZE4N5F.js} +5 -5
  3. package/dist/actions-LR65XILR.js +244 -0
  4. package/dist/{ccip-XZ5F5J6R.js → ccip-JXYJSXTW.js} +3 -3
  5. package/dist/{chains-PINFXYUE.js → chains-LJ7XK6H3.js} +8 -8
  6. package/dist/{chunk-YZUBKHHA.js → chunk-2VVVWBQA.js} +471 -471
  7. package/dist/chunk-3SWX5BQP.js +66 -0
  8. package/dist/chunk-3W2M46WM.js +61142 -0
  9. package/dist/chunk-4JXFXP4Y.js +757 -0
  10. package/dist/{chunk-GIDSTROG.js → chunk-4NWEJTAW.js} +160 -158
  11. package/dist/{chunk-UXQCP26E.js → chunk-65EY7CT4.js} +2 -2
  12. package/dist/{chunk-6UGZAFIR.js → chunk-6CC6JGEU.js} +348 -18
  13. package/dist/{chunk-PHZHPRQE.js → chunk-6O27TEXD.js} +173 -173
  14. package/dist/{chunk-HPRIQEJS.js → chunk-7OK7MBT6.js} +19 -19
  15. package/dist/{chunk-7UPZZGC5.js → chunk-BECPI5H5.js} +193 -193
  16. package/dist/chunk-CJTE5TS3.js +1298 -0
  17. package/dist/{chunk-RWBYCM47.js → chunk-ECEM3ZAS.js} +10 -10
  18. package/dist/{chunk-ACNNU5RY.js → chunk-ECK465AY.js} +694 -565
  19. package/dist/{chunk-XGABM4H5.js → chunk-EGY4KDBW.js} +3822 -2012
  20. package/dist/{chunk-SLDVIXCS.js → chunk-EVQERRCP.js} +12 -12
  21. package/dist/{chunk-4AQ4G7L5.js → chunk-EZHT2RLJ.js} +383 -383
  22. package/dist/{chunk-IC6OXFYW.js → chunk-F55NNH2F.js} +63 -63
  23. package/dist/chunk-G5C6E6PJ.js +9063 -0
  24. package/dist/{chunk-6AJ7H2VX.js → chunk-GZWKCIYN.js} +213 -1281
  25. package/dist/{chunk-ZGXCK43G.js → chunk-LH3QPVN6.js} +8499 -8498
  26. package/dist/{chunk-MMJR6N3J.js → chunk-MLDUKBU3.js} +1368 -1368
  27. package/dist/chunk-N3UJT2NJ.js +3 -0
  28. package/dist/{chunk-BZNZWRBB.js → chunk-OWJZYYMG.js} +11 -15
  29. package/dist/chunk-ZJYO7OLO.js +514 -0
  30. package/dist/{client-D3XFLWOK.js → client-OWIOFBKS.js} +18 -16
  31. package/dist/{dist-7MMV3EZA.js → dist-2G3QBGID.js} +11 -10
  32. package/dist/dvm.js +26781 -4423
  33. package/dist/esm-RQLHAH2K.js +5183 -0
  34. package/dist/internal-QFQ7MJ5V.js +1228 -0
  35. package/dist/payout-reporter-3UB5WRCV-XTVZFIAO.js +17 -0
  36. package/dist/{pocket-refill-GDYSTECR.js → pocket-refill-PQ5ZVSBY.js} +26 -30
  37. package/dist/revenue-reporter-JIKUPXOK-TYUBTF4P.js +11 -0
  38. package/dist/{secp256k1-4YWQEMGF.js → secp256k1-JLZEQ2H7.js} +2 -2
  39. package/dist/tempo-lifecycle-SQL3KLEZ-AATA2SKI.js +28 -0
  40. package/dist/{tempo-wallet-5FEOI4CF.js → tempo-wallet-QOLEIPCV-SWCXRBDS.js} +2 -4
  41. package/dist/{x402-VNFA3DBY.js → x402-FTG2GRAQ-UGAUMUL6.js} +13 -24
  42. package/package.json +2 -10
  43. package/dist/channel-store-GOV7TEDN.js +0 -62
  44. package/dist/chunk-3PPOU55E.js +0 -312
  45. package/dist/chunk-3TBULV3F.js +0 -551
  46. package/dist/chunk-5BUV73FO.js +0 -2351
  47. package/dist/chunk-EY5K4BM3.js +0 -1780
  48. package/dist/chunk-G3RLVJF5.js +0 -19
  49. package/dist/chunk-KC4UPK44.js +0 -113
  50. package/dist/chunk-MTBCEXJ6.js +0 -4602
  51. package/dist/chunk-ONQMRWY3.js +0 -83
  52. package/dist/chunk-TO47XRK7.js +0 -24890
  53. package/dist/chunk-U5TNSUYW.js +0 -1757
  54. package/dist/chunk-UU6QMSTQ.js +0 -171
  55. package/dist/chunk-ZELLQI7F.js +0 -248
  56. package/dist/lifecycle-5RLM5JMN.js +0 -29
  57. package/dist/tempo-lifecycle-DHZPQTSB.js +0 -31
  58. package/dist/wallet-G3VOUCL4.js +0 -30
@@ -1,2351 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __dvmCreateRequire } from "node:module";
3
- const require = __dvmCreateRequire(import.meta.url);
4
- import {
5
- formatUsdcMicrounits
6
- } from "./chunk-ZELLQI7F.js";
7
- import {
8
- ADDITIVE_ARRAY_INFO_FIELDS,
9
- decodePaymentRequiredHeader,
10
- decodePaymentResponseHeader,
11
- deepEqual,
12
- findByNetworkAndScheme,
13
- findSchemesByNetwork,
14
- toComparableArray,
15
- x402HTTPClient,
16
- x402NetworkByCaip2,
17
- x402SupportedNetworksHint,
18
- x402Version
19
- } from "./chunk-MTBCEXJ6.js";
20
- import {
21
- redactUrl,
22
- redactUrlsInText,
23
- resolveRpcHttpTransportOptions,
24
- resolveRpcOverride
25
- } from "./chunk-ONQMRWY3.js";
26
- import {
27
- DvmX402ChannelStorage,
28
- listX402Channels,
29
- x402ChannelBalanceUnreconciledAt
30
- } from "./chunk-3TBULV3F.js";
31
- import {
32
- DvmError
33
- } from "./chunk-U5TNSUYW.js";
34
- import {
35
- createPublicClient,
36
- http
37
- } from "./chunk-6AJ7H2VX.js";
38
- import {
39
- recoverTypedDataAddress
40
- } from "./chunk-ZGXCK43G.js";
41
- import {
42
- encodeFunctionData
43
- } from "./chunk-IC6OXFYW.js";
44
- import {
45
- hashTypedData
46
- } from "./chunk-PHZHPRQE.js";
47
- import {
48
- encodeAbiParameters,
49
- getAddress,
50
- keccak256,
51
- maxUint256,
52
- toBytes,
53
- toHex
54
- } from "./chunk-MMJR6N3J.js";
55
-
56
- // node_modules/@x402/evm/dist/esm/chunk-MACPBXCT.mjs
57
- var eip2612PermitTypes = {
58
- Permit: [
59
- { name: "owner", type: "address" },
60
- { name: "spender", type: "address" },
61
- { name: "value", type: "uint256" },
62
- { name: "nonce", type: "uint256" },
63
- { name: "deadline", type: "uint256" }
64
- ]
65
- };
66
- var eip2612NoncesAbi = [
67
- {
68
- type: "function",
69
- name: "nonces",
70
- inputs: [{ name: "owner", type: "address" }],
71
- outputs: [{ type: "uint256" }],
72
- stateMutability: "view"
73
- }
74
- ];
75
- var erc20ApproveAbi = [
76
- {
77
- type: "function",
78
- name: "approve",
79
- inputs: [
80
- { name: "spender", type: "address" },
81
- { name: "amount", type: "uint256" }
82
- ],
83
- outputs: [{ type: "bool" }],
84
- stateMutability: "nonpayable"
85
- }
86
- ];
87
- var erc20AllowanceAbi = [
88
- {
89
- type: "function",
90
- name: "allowance",
91
- inputs: [
92
- { name: "owner", type: "address" },
93
- { name: "spender", type: "address" }
94
- ],
95
- outputs: [{ type: "uint256" }],
96
- stateMutability: "view"
97
- }
98
- ];
99
- var ERC20_APPROVE_GAS_LIMIT = 70000n;
100
- var DEFAULT_MAX_FEE_PER_GAS = 1000000000n;
101
- var DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100000000n;
102
- var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
103
-
104
- // node_modules/@x402/evm/dist/esm/chunk-7KTOBWB2.mjs
105
- var PAYMENT_INFO_TYPEHASH = keccak256(
106
- new TextEncoder().encode(
107
- "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)"
108
- )
109
- );
110
-
111
- // node_modules/@x402/evm/dist/esm/chunk-W6ON4LG2.mjs
112
- function buildErc3009DepositNonce(channelId, salt) {
113
- return keccak256(
114
- encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [channelId, BigInt(salt)])
115
- );
116
- }
117
-
118
- // node_modules/@x402/evm/dist/esm/chunk-H25OEB2U.mjs
119
- var channelConfigComponents = [
120
- { name: "payer", type: "address" },
121
- { name: "payerAuthorizer", type: "address" },
122
- { name: "receiver", type: "address" },
123
- { name: "receiverAuthorizer", type: "address" },
124
- { name: "token", type: "address" },
125
- { name: "withdrawDelay", type: "uint40" },
126
- { name: "salt", type: "bytes32" }
127
- ];
128
- var voucherClaimComponents = [
129
- {
130
- name: "voucher",
131
- type: "tuple",
132
- components: [
133
- {
134
- name: "channel",
135
- type: "tuple",
136
- components: channelConfigComponents
137
- },
138
- { name: "maxClaimableAmount", type: "uint128" }
139
- ]
140
- },
141
- { name: "signature", type: "bytes" },
142
- { name: "totalClaimed", type: "uint128" }
143
- ];
144
- var batchSettlementABI = [
145
- {
146
- type: "function",
147
- name: "multicall",
148
- inputs: [{ name: "data", type: "bytes[]" }],
149
- outputs: [{ name: "results", type: "bytes[]" }],
150
- stateMutability: "nonpayable"
151
- },
152
- {
153
- type: "function",
154
- name: "deposit",
155
- inputs: [
156
- { name: "config", type: "tuple", components: channelConfigComponents },
157
- { name: "amount", type: "uint128" },
158
- { name: "collector", type: "address" },
159
- { name: "collectorData", type: "bytes" }
160
- ],
161
- outputs: [],
162
- stateMutability: "nonpayable"
163
- },
164
- {
165
- type: "function",
166
- name: "claim",
167
- inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
168
- outputs: [],
169
- stateMutability: "nonpayable"
170
- },
171
- {
172
- type: "function",
173
- name: "claimWithSignature",
174
- inputs: [
175
- { name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents },
176
- { name: "authorizerSignature", type: "bytes" }
177
- ],
178
- outputs: [],
179
- stateMutability: "nonpayable"
180
- },
181
- {
182
- type: "function",
183
- name: "settle",
184
- inputs: [
185
- { name: "receiver", type: "address" },
186
- { name: "token", type: "address" }
187
- ],
188
- outputs: [],
189
- stateMutability: "nonpayable"
190
- },
191
- {
192
- type: "function",
193
- name: "initiateWithdraw",
194
- inputs: [
195
- { name: "config", type: "tuple", components: channelConfigComponents },
196
- { name: "amount", type: "uint128" }
197
- ],
198
- outputs: [],
199
- stateMutability: "nonpayable"
200
- },
201
- {
202
- type: "function",
203
- name: "finalizeWithdraw",
204
- inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
205
- outputs: [],
206
- stateMutability: "nonpayable"
207
- },
208
- {
209
- type: "function",
210
- name: "refund",
211
- inputs: [
212
- { name: "config", type: "tuple", components: channelConfigComponents },
213
- { name: "amount", type: "uint128" }
214
- ],
215
- outputs: [],
216
- stateMutability: "nonpayable"
217
- },
218
- {
219
- type: "function",
220
- name: "refundWithSignature",
221
- inputs: [
222
- { name: "config", type: "tuple", components: channelConfigComponents },
223
- { name: "amount", type: "uint128" },
224
- { name: "nonce", type: "uint256" },
225
- { name: "receiverAuthorizerSignature", type: "bytes" }
226
- ],
227
- outputs: [],
228
- stateMutability: "nonpayable"
229
- },
230
- {
231
- type: "function",
232
- name: "getChannelId",
233
- inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
234
- outputs: [{ name: "", type: "bytes32" }],
235
- stateMutability: "view"
236
- },
237
- {
238
- type: "function",
239
- name: "CHANNEL_CONFIG_TYPEHASH",
240
- inputs: [],
241
- outputs: [{ name: "", type: "bytes32" }],
242
- stateMutability: "view"
243
- },
244
- {
245
- type: "function",
246
- name: "channels",
247
- inputs: [{ name: "channelId", type: "bytes32" }],
248
- outputs: [
249
- { name: "balance", type: "uint128" },
250
- { name: "totalClaimed", type: "uint128" }
251
- ],
252
- stateMutability: "view"
253
- },
254
- {
255
- type: "function",
256
- name: "pendingWithdrawals",
257
- inputs: [{ name: "channelId", type: "bytes32" }],
258
- outputs: [
259
- { name: "amount", type: "uint128" },
260
- { name: "initiatedAt", type: "uint40" }
261
- ],
262
- stateMutability: "view"
263
- },
264
- {
265
- type: "function",
266
- name: "receivers",
267
- inputs: [
268
- { name: "receiver", type: "address" },
269
- { name: "token", type: "address" }
270
- ],
271
- outputs: [
272
- { name: "totalClaimed", type: "uint128" },
273
- { name: "totalSettled", type: "uint128" }
274
- ],
275
- stateMutability: "view"
276
- },
277
- {
278
- type: "function",
279
- name: "getVoucherDigest",
280
- inputs: [
281
- { name: "channelId", type: "bytes32" },
282
- { name: "maxClaimableAmount", type: "uint128" }
283
- ],
284
- outputs: [{ name: "", type: "bytes32" }],
285
- stateMutability: "view"
286
- },
287
- {
288
- type: "function",
289
- name: "getRefundDigest",
290
- inputs: [
291
- { name: "channelId", type: "bytes32" },
292
- { name: "nonce", type: "uint256" },
293
- { name: "amount", type: "uint128" }
294
- ],
295
- outputs: [{ name: "", type: "bytes32" }],
296
- stateMutability: "view"
297
- },
298
- {
299
- type: "function",
300
- name: "refundNonce",
301
- inputs: [{ name: "channelId", type: "bytes32" }],
302
- outputs: [{ name: "", type: "uint256" }],
303
- stateMutability: "view"
304
- },
305
- {
306
- type: "function",
307
- name: "getClaimBatchDigest",
308
- inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
309
- outputs: [{ name: "", type: "bytes32" }],
310
- stateMutability: "view"
311
- },
312
- {
313
- type: "event",
314
- name: "Settled",
315
- inputs: [
316
- { name: "receiver", type: "address", indexed: true },
317
- { name: "token", type: "address", indexed: true },
318
- { name: "sender", type: "address", indexed: true },
319
- { name: "amount", type: "uint128", indexed: false }
320
- ],
321
- anonymous: false
322
- }
323
- ];
324
-
325
- // node_modules/@x402/evm/dist/esm/chunk-TW7Z65AO.mjs
326
- function getEvmChainId(network) {
327
- if (network.startsWith("eip155:")) {
328
- const idStr = network.split(":")[1];
329
- const chainId = parseInt(idStr, 10);
330
- if (isNaN(chainId)) {
331
- throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
332
- }
333
- return chainId;
334
- }
335
- throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
336
- }
337
- function getCrypto() {
338
- const cryptoObj = globalThis.crypto;
339
- if (!cryptoObj) {
340
- throw new Error("Crypto API not available");
341
- }
342
- return cryptoObj;
343
- }
344
- function createNonce() {
345
- return toHex(getCrypto().getRandomValues(new Uint8Array(32)));
346
- }
347
- function createPermit2Nonce() {
348
- const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));
349
- return BigInt(toHex(randomBytes)).toString();
350
- }
351
-
352
- // node_modules/@x402/evm/dist/esm/chunk-76GJG6LX.mjs
353
- var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
354
- var BATCH_SETTLEMENT_ADDRESS = "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003";
355
- var ERC3009_DEPOSIT_COLLECTOR_ADDRESS = "0x4020806089470a89826cB9fB1f4059150b550004";
356
- var PERMIT2_DEPOSIT_COLLECTOR_ADDRESS = "0x4020425FAf3B746C082C2f942b4E5159887B0005";
357
- var MIN_WITHDRAW_DELAY = 900;
358
- var BATCH_SETTLEMENT_DOMAIN = {
359
- name: "x402 Batch Settlement",
360
- version: "1"
361
- };
362
- var CHANNEL_CONFIG_TYPEHASH = keccak256(
363
- toBytes(
364
- "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
365
- )
366
- );
367
- var channelConfigTypes = {
368
- ChannelConfig: [
369
- { name: "payer", type: "address" },
370
- { name: "payerAuthorizer", type: "address" },
371
- { name: "receiver", type: "address" },
372
- { name: "receiverAuthorizer", type: "address" },
373
- { name: "token", type: "address" },
374
- { name: "withdrawDelay", type: "uint40" },
375
- { name: "salt", type: "bytes32" }
376
- ]
377
- };
378
- var voucherTypes = {
379
- Voucher: [
380
- { name: "channelId", type: "bytes32" },
381
- { name: "maxClaimableAmount", type: "uint128" }
382
- ]
383
- };
384
- var receiveAuthorizationTypes = {
385
- ReceiveWithAuthorization: [
386
- { name: "from", type: "address" },
387
- { name: "to", type: "address" },
388
- { name: "value", type: "uint256" },
389
- { name: "validAfter", type: "uint256" },
390
- { name: "validBefore", type: "uint256" },
391
- { name: "nonce", type: "bytes32" }
392
- ]
393
- };
394
- var batchPermit2WitnessTypes = {
395
- PermitWitnessTransferFrom: [
396
- { name: "permitted", type: "TokenPermissions" },
397
- { name: "spender", type: "address" },
398
- { name: "nonce", type: "uint256" },
399
- { name: "deadline", type: "uint256" },
400
- { name: "witness", type: "DepositWitness" }
401
- ],
402
- TokenPermissions: [
403
- { name: "token", type: "address" },
404
- { name: "amount", type: "uint256" }
405
- ],
406
- DepositWitness: [{ name: "channelId", type: "bytes32" }]
407
- };
408
- var ErrCumulativeAmountBelowClaimed = "invalid_batch_settlement_evm_cumulative_below_claimed";
409
- var ErrInvalidChannelId = "invalid_batch_settlement_evm_channel_id_invalid";
410
- var ErrCumulativeAmountMismatch = "invalid_batch_settlement_evm_cumulative_amount_mismatch";
411
- var ErrRefundNoBalance = "invalid_batch_settlement_evm_refund_no_balance";
412
- var ErrRefundAmountInvalid = "invalid_batch_settlement_evm_refund_amount_invalid";
413
- var CHANNEL_ID_RE = /^0x[0-9a-fA-F]{64}$/;
414
- function isCanonicalChannelId(value) {
415
- return typeof value === "string" && CHANNEL_ID_RE.test(value);
416
- }
417
- function normalizeChannelId(channelId) {
418
- if (!isCanonicalChannelId(channelId)) {
419
- throw new Error(ErrInvalidChannelId);
420
- }
421
- return channelId.toLowerCase();
422
- }
423
- function computeChannelId(config, networkOrChainId) {
424
- const chainId = typeof networkOrChainId === "number" ? networkOrChainId : getEvmChainId(networkOrChainId);
425
- return hashTypedData({
426
- domain: getBatchSettlementEip712Domain(chainId),
427
- types: channelConfigTypes,
428
- primaryType: "ChannelConfig",
429
- message: {
430
- payer: config.payer,
431
- payerAuthorizer: config.payerAuthorizer,
432
- receiver: config.receiver,
433
- receiverAuthorizer: config.receiverAuthorizer,
434
- token: config.token,
435
- withdrawDelay: config.withdrawDelay,
436
- salt: config.salt
437
- }
438
- });
439
- }
440
- function getBatchSettlementEip712Domain(chainId) {
441
- return {
442
- ...BATCH_SETTLEMENT_DOMAIN,
443
- chainId,
444
- verifyingContract: getAddress(BATCH_SETTLEMENT_ADDRESS)
445
- };
446
- }
447
-
448
- // node_modules/@x402/evm/dist/esm/chunk-U4HCGTLU.mjs
449
- function isObject(payload) {
450
- return typeof payload === "object" && payload !== null;
451
- }
452
- function isVoucherFields(payload) {
453
- return isObject(payload) && "channelId" in payload && "maxClaimableAmount" in payload && "signature" in payload;
454
- }
455
- function isBatchSettlementRefundPayload(payload) {
456
- return isObject(payload) && payload.type === "refund" && "channelConfig" in payload && isVoucherFields(payload.voucher);
457
- }
458
-
459
- // node_modules/@x402/evm/dist/esm/chunk-27MWX225.mjs
460
- var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
461
- var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
462
- var ERC20_APPROVAL_GAS_SPONSORING_VERSION = "1";
463
- async function signEip2612Permit(signer, tokenAddress, tokenName, tokenVersion, chainId, deadline, permittedAmount) {
464
- const owner = signer.address;
465
- const spender = getAddress(PERMIT2_ADDRESS);
466
- const nonce = await signer.readContract({
467
- address: tokenAddress,
468
- abi: eip2612NoncesAbi,
469
- functionName: "nonces",
470
- args: [owner]
471
- });
472
- const domain = {
473
- name: tokenName,
474
- version: tokenVersion,
475
- chainId,
476
- verifyingContract: tokenAddress
477
- };
478
- const approvalAmount = BigInt(permittedAmount);
479
- const message = {
480
- owner,
481
- spender,
482
- value: approvalAmount,
483
- nonce,
484
- deadline: BigInt(deadline)
485
- };
486
- const signature = await signer.signTypedData({
487
- domain,
488
- types: eip2612PermitTypes,
489
- primaryType: "Permit",
490
- message
491
- });
492
- return {
493
- from: owner,
494
- asset: tokenAddress,
495
- spender,
496
- amount: approvalAmount.toString(),
497
- nonce: nonce.toString(),
498
- deadline,
499
- signature,
500
- version: "1"
501
- };
502
- }
503
- async function signErc20ApprovalTransaction(signer, tokenAddress, chainId) {
504
- const from = signer.address;
505
- const spender = getAddress(PERMIT2_ADDRESS);
506
- const data = encodeFunctionData({
507
- abi: erc20ApproveAbi,
508
- functionName: "approve",
509
- args: [spender, maxUint256]
510
- });
511
- const nonce = await signer.getTransactionCount({ address: from });
512
- let maxFeePerGas;
513
- let maxPriorityFeePerGas;
514
- try {
515
- const fees = await signer.estimateFeesPerGas?.();
516
- if (!fees) {
517
- throw new Error("no fee estimates available");
518
- }
519
- maxFeePerGas = fees.maxFeePerGas;
520
- maxPriorityFeePerGas = fees.maxPriorityFeePerGas;
521
- } catch {
522
- maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;
523
- maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;
524
- }
525
- const signedTransaction = await signer.signTransaction({
526
- to: tokenAddress,
527
- data,
528
- nonce,
529
- gas: ERC20_APPROVE_GAS_LIMIT,
530
- maxFeePerGas,
531
- maxPriorityFeePerGas,
532
- chainId
533
- });
534
- return {
535
- from,
536
- asset: tokenAddress,
537
- spender,
538
- amount: maxUint256.toString(),
539
- signedTransaction,
540
- version: ERC20_APPROVAL_GAS_SPONSORING_VERSION
541
- };
542
- }
543
- var rpcClientCache = /* @__PURE__ */ new Map();
544
- function isConfigByChainId(options) {
545
- const keys = Object.keys(options);
546
- return keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
547
- }
548
- function getRpcClient(rpcUrl) {
549
- const existing = rpcClientCache.get(rpcUrl);
550
- if (existing) {
551
- return existing;
552
- }
553
- const client = createPublicClient({
554
- transport: http(rpcUrl)
555
- });
556
- rpcClientCache.set(rpcUrl, client);
557
- return client;
558
- }
559
- function resolveRpcUrl(network, options) {
560
- if (!options) {
561
- return void 0;
562
- }
563
- if (isConfigByChainId(options)) {
564
- const chainId = getEvmChainId(network);
565
- const optionsByChainId = options;
566
- return optionsByChainId[chainId]?.rpcUrl;
567
- }
568
- return options.rpcUrl;
569
- }
570
- function resolveExtensionRpcCapabilities(network, signer, options) {
571
- const capabilities = {
572
- signTransaction: signer.signTransaction,
573
- readContract: signer.readContract,
574
- getTransactionCount: signer.getTransactionCount,
575
- estimateFeesPerGas: signer.estimateFeesPerGas
576
- };
577
- const needsRpcBackfill = !capabilities.readContract || !capabilities.getTransactionCount || !capabilities.estimateFeesPerGas;
578
- if (!needsRpcBackfill) {
579
- return capabilities;
580
- }
581
- const rpcUrl = resolveRpcUrl(network, options);
582
- if (!rpcUrl) {
583
- return capabilities;
584
- }
585
- const rpcClient = getRpcClient(rpcUrl);
586
- if (!capabilities.readContract) {
587
- capabilities.readContract = (args) => rpcClient.readContract(args);
588
- }
589
- if (!capabilities.getTransactionCount) {
590
- capabilities.getTransactionCount = async (args) => rpcClient.getTransactionCount({ address: args.address });
591
- }
592
- if (!capabilities.estimateFeesPerGas) {
593
- capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();
594
- }
595
- return capabilities;
596
- }
597
- async function trySignEip2612PermitExtension(signer, options, requirements, result, context, approvalAmount) {
598
- const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
599
- if (!capabilities.readContract) {
600
- return void 0;
601
- }
602
- if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {
603
- return void 0;
604
- }
605
- const tokenName = requirements.extra?.name;
606
- const tokenVersion = requirements.extra?.version;
607
- if (!tokenName || !tokenVersion) {
608
- return void 0;
609
- }
610
- const chainId = getEvmChainId(requirements.network);
611
- const tokenAddress = getAddress(requirements.asset);
612
- const requiredAllowance = approvalAmount ?? requirements.amount;
613
- try {
614
- const allowance = await capabilities.readContract({
615
- address: tokenAddress,
616
- abi: erc20AllowanceAbi,
617
- functionName: "allowance",
618
- args: [signer.address, PERMIT2_ADDRESS]
619
- });
620
- if (allowance >= BigInt(requiredAllowance)) {
621
- return void 0;
622
- }
623
- } catch {
624
- }
625
- const permit2Auth = result.payload?.permit2Authorization;
626
- const deadline = permit2Auth?.deadline ?? Math.floor(Date.now() / 1e3 + requirements.maxTimeoutSeconds).toString();
627
- const info = await signEip2612Permit(
628
- {
629
- address: signer.address,
630
- signTypedData: (msg) => signer.signTypedData(msg),
631
- readContract: capabilities.readContract
632
- },
633
- tokenAddress,
634
- tokenName,
635
- tokenVersion,
636
- chainId,
637
- deadline,
638
- requiredAllowance
639
- );
640
- return {
641
- [EIP2612_GAS_SPONSORING_KEY]: { info }
642
- };
643
- }
644
- async function trySignErc20ApprovalExtension(signer, options, requirements, context, approvalAmount) {
645
- const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
646
- if (!capabilities.readContract) {
647
- return void 0;
648
- }
649
- if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {
650
- return void 0;
651
- }
652
- if (!capabilities.signTransaction || !capabilities.getTransactionCount) {
653
- return void 0;
654
- }
655
- const chainId = getEvmChainId(requirements.network);
656
- const tokenAddress = getAddress(requirements.asset);
657
- const requiredAllowance = approvalAmount ?? requirements.amount;
658
- try {
659
- const allowance = await capabilities.readContract({
660
- address: tokenAddress,
661
- abi: erc20AllowanceAbi,
662
- functionName: "allowance",
663
- args: [signer.address, PERMIT2_ADDRESS]
664
- });
665
- if (allowance >= BigInt(requiredAllowance)) {
666
- return void 0;
667
- }
668
- } catch {
669
- }
670
- const info = await signErc20ApprovalTransaction(
671
- {
672
- address: signer.address,
673
- signTransaction: capabilities.signTransaction,
674
- getTransactionCount: capabilities.getTransactionCount,
675
- estimateFeesPerGas: capabilities.estimateFeesPerGas
676
- },
677
- tokenAddress,
678
- chainId
679
- );
680
- return {
681
- [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info }
682
- };
683
- }
684
-
685
- // node_modules/@x402/core/dist/esm/client/index.mjs
686
- var x402Client = class _x402Client {
687
- /**
688
- * Creates a new x402Client instance.
689
- *
690
- * @param paymentRequirementsSelector - Function to select payment requirements from available options
691
- */
692
- constructor(paymentRequirementsSelector) {
693
- this.registeredClientSchemes = /* @__PURE__ */ new Map();
694
- this.schemeClientHookAdapters = /* @__PURE__ */ new Map();
695
- this.policies = [];
696
- this.registeredExtensions = /* @__PURE__ */ new Map();
697
- this.beforePaymentCreationHooks = [];
698
- this.afterPaymentCreationHooks = [];
699
- this.onPaymentCreationFailureHooks = [];
700
- this.paymentResponseHooks = [];
701
- this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version2, accepts) => accepts[0]);
702
- }
703
- /**
704
- * Creates a new x402Client instance from a configuration object.
705
- *
706
- * @param config - The client configuration including schemes, policies, and payment requirements selector
707
- * @returns A configured x402Client instance
708
- */
709
- static fromConfig(config) {
710
- const client = new _x402Client(config.paymentRequirementsSelector);
711
- config.schemes.forEach((scheme) => {
712
- if (scheme.x402Version === 1) {
713
- client.registerV1(scheme.network, scheme.client);
714
- } else {
715
- client.register(scheme.network, scheme.client);
716
- }
717
- });
718
- config.policies?.forEach((policy) => {
719
- client.registerPolicy(policy);
720
- });
721
- return client;
722
- }
723
- /**
724
- * Registers a scheme client for the current x402 version.
725
- *
726
- * @param network - The network to register the client for
727
- * @param client - The scheme network client to register
728
- * @returns The x402Client instance for chaining
729
- */
730
- register(network, client) {
731
- return this._registerScheme(x402Version, network, client);
732
- }
733
- /**
734
- * Registers a scheme client for x402 version 1.
735
- *
736
- * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
737
- * @param client - The scheme network client to register
738
- * @returns The x402Client instance for chaining
739
- */
740
- registerV1(network, client) {
741
- return this._registerScheme(1, network, client);
742
- }
743
- /**
744
- * Registers a policy to filter or transform payment requirements.
745
- *
746
- * Policies are applied in order after filtering by registered schemes
747
- * and before the selector chooses the final payment requirement.
748
- *
749
- * @param policy - Function to filter/transform payment requirements
750
- * @returns The x402Client instance for chaining
751
- *
752
- * @example
753
- * ```typescript
754
- * // Prefer cheaper options
755
- * client.registerPolicy((version, reqs) =>
756
- * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
757
- * );
758
- *
759
- * // Prefer specific networks
760
- * client.registerPolicy((version, reqs) =>
761
- * reqs.filter(r => r.network.startsWith('eip155:'))
762
- * );
763
- * ```
764
- */
765
- registerPolicy(policy) {
766
- this.policies.push(policy);
767
- return this;
768
- }
769
- /**
770
- * Registers a client extension that can enrich payment payloads.
771
- *
772
- * Extensions are invoked after the scheme creates the base payload and the
773
- * payload is wrapped with extensions/resource/accepted data. Every registered
774
- * extension's `enrichPaymentPayload` hook is called to modify the payload.
775
- * Server-declared fields are preserved via merge after enrichment.
776
- *
777
- * @param extension - The client extension to register
778
- * @returns The x402Client instance for chaining
779
- */
780
- registerExtension(extension) {
781
- this.registeredExtensions.set(extension.key, extension);
782
- return this;
783
- }
784
- /**
785
- * Get all registered client extensions.
786
- *
787
- * @returns Array of registered extensions
788
- */
789
- getExtensions() {
790
- return Array.from(this.registeredExtensions.values());
791
- }
792
- /**
793
- * Register a hook to execute before payment payload creation.
794
- * Can abort creation by returning { abort: true, reason: string }
795
- *
796
- * @param hook - The hook function to register
797
- * @returns The x402Client instance for chaining
798
- */
799
- onBeforePaymentCreation(hook) {
800
- this.beforePaymentCreationHooks.push(hook);
801
- return this;
802
- }
803
- /**
804
- * Register a hook to execute after successful payment payload creation.
805
- *
806
- * @param hook - The hook function to register
807
- * @returns The x402Client instance for chaining
808
- */
809
- onAfterPaymentCreation(hook) {
810
- this.afterPaymentCreationHooks.push(hook);
811
- return this;
812
- }
813
- /**
814
- * Register a hook to execute when payment payload creation fails.
815
- * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
816
- *
817
- * @param hook - The hook function to register
818
- * @returns The x402Client instance for chaining
819
- */
820
- onPaymentCreationFailure(hook) {
821
- this.onPaymentCreationFailureHooks.push(hook);
822
- return this;
823
- }
824
- /**
825
- * Register a hook to execute after a paid request completes.
826
- * Can signal recovery by returning { recovered: true }, causing the transport to retry.
827
- *
828
- * @param hook - The hook function to register
829
- * @returns The x402Client instance for chaining
830
- */
831
- onPaymentResponse(hook) {
832
- this.paymentResponseHooks.push(hook);
833
- return this;
834
- }
835
- /**
836
- * Fires all registered payment response hooks in order.
837
- * Returns `{ recovered: true }` if any hook signals recovery (first wins).
838
- *
839
- * @param ctx - The payment response context
840
- * @returns Recovery signal or undefined
841
- */
842
- async handlePaymentResponse(ctx) {
843
- for (const hook of this.getLabeledHooks(
844
- "onPaymentResponse",
845
- ctx.paymentPayload.x402Version,
846
- ctx.requirements,
847
- ctx.paymentRequired?.extensions ?? ctx.paymentPayload.extensions
848
- )) {
849
- const result = await hook(ctx);
850
- if (result && "recovered" in result && result.recovered) {
851
- return { recovered: true };
852
- }
853
- }
854
- return void 0;
855
- }
856
- /**
857
- * Creates a payment payload based on a PaymentRequired response.
858
- *
859
- * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
860
- * response and constructs a complete PaymentPayload with the accepted requirements.
861
- *
862
- * @param paymentRequired - The PaymentRequired response from the server
863
- * @returns Promise resolving to the complete payment payload
864
- */
865
- async createPaymentPayload(paymentRequired) {
866
- const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);
867
- if (!clientSchemesByNetwork) {
868
- throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);
869
- }
870
- const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);
871
- const context = {
872
- paymentRequired,
873
- selectedRequirements: requirements
874
- };
875
- for (const hook of this.getLabeledHooks(
876
- "beforePaymentCreation",
877
- paymentRequired.x402Version,
878
- requirements,
879
- paymentRequired.extensions
880
- )) {
881
- const result = await hook(context);
882
- if (result && "abort" in result && result.abort) {
883
- throw new Error(`Payment creation aborted: ${result.reason}`);
884
- }
885
- }
886
- try {
887
- const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);
888
- if (!schemeNetworkClient) {
889
- throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);
890
- }
891
- const partialPayload = await schemeNetworkClient.createPaymentPayload(
892
- paymentRequired.x402Version,
893
- requirements,
894
- { extensions: paymentRequired.extensions }
895
- );
896
- let paymentPayload;
897
- if (partialPayload.x402Version == 1) {
898
- paymentPayload = partialPayload;
899
- } else {
900
- const mergedExtensions = this.mergeExtensions(
901
- paymentRequired.extensions,
902
- partialPayload.extensions
903
- );
904
- paymentPayload = {
905
- x402Version: partialPayload.x402Version,
906
- payload: partialPayload.payload,
907
- extensions: mergedExtensions,
908
- resource: paymentRequired.resource,
909
- accepted: requirements
910
- };
911
- }
912
- paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);
913
- const createdContext = {
914
- ...context,
915
- paymentPayload
916
- };
917
- for (const hook of this.getLabeledHooks(
918
- "afterPaymentCreation",
919
- paymentRequired.x402Version,
920
- requirements,
921
- paymentRequired.extensions
922
- )) {
923
- await hook(createdContext);
924
- }
925
- return paymentPayload;
926
- } catch (error) {
927
- const failureContext = {
928
- ...context,
929
- error
930
- };
931
- for (const hook of this.getLabeledHooks(
932
- "onPaymentCreationFailure",
933
- paymentRequired.x402Version,
934
- requirements,
935
- paymentRequired.extensions
936
- )) {
937
- const result = await hook(failureContext);
938
- if (result && "recovered" in result && result.recovered) {
939
- return result.payload;
940
- }
941
- }
942
- throw error;
943
- }
944
- }
945
- /**
946
- * Merges server-declared extensions with client extension echoes.
947
- * Client extension data may add fields, but server-declared fields remain intact.
948
- * For fields listed in `ADDITIVE_ARRAY_INFO_FIELDS` (e.g. builder-code `s`), a
949
- * conflicting array is concatenated with client entries first (so a downstream
950
- * length cap trims server entries rather than the client's) and duplicates
951
- * removed; a scalar on either side is treated as a single-element array. Every
952
- * other conflicting array keeps the server's value, same as any other scalar.
953
- *
954
- * @param serverExtensions - Extensions declared by the server in the 402 response
955
- * @param clientExtensions - Extensions provided by the client or scheme
956
- * @returns The merged extensions object, or undefined if both inputs are undefined
957
- */
958
- mergeExtensions(serverExtensions, clientExtensions) {
959
- if (!clientExtensions) return serverExtensions;
960
- if (!serverExtensions) return clientExtensions;
961
- const merged = { ...serverExtensions };
962
- for (const [key, clientValue] of Object.entries(clientExtensions)) {
963
- const serverValue = merged[key];
964
- if (serverValue === null || typeof serverValue !== "object" || Array.isArray(serverValue) || clientValue === null || typeof clientValue !== "object" || Array.isArray(clientValue)) {
965
- merged[key] = clientValue;
966
- continue;
967
- }
968
- const serverRecord = serverValue;
969
- const clientRecord = clientValue;
970
- const additiveFields = ADDITIVE_ARRAY_INFO_FIELDS[key];
971
- const extensionValue = { ...serverRecord };
972
- const pending = [{ target: extensionValue, source: clientRecord }];
973
- for (const item of pending) {
974
- for (const [fieldKey, clientFieldValue] of Object.entries(item.source)) {
975
- const serverFieldValue = item.target[fieldKey];
976
- if (serverFieldValue !== null && typeof serverFieldValue === "object" && !Array.isArray(serverFieldValue) && clientFieldValue !== null && typeof clientFieldValue === "object" && !Array.isArray(clientFieldValue)) {
977
- const nestedValue = { ...serverFieldValue };
978
- item.target[fieldKey] = nestedValue;
979
- pending.push({
980
- target: nestedValue,
981
- source: clientFieldValue
982
- });
983
- continue;
984
- }
985
- if (additiveFields?.has(fieldKey) && (Array.isArray(serverFieldValue) || Array.isArray(clientFieldValue))) {
986
- const serverArray = toComparableArray(serverFieldValue);
987
- const clientArray = toComparableArray(clientFieldValue);
988
- if (serverArray && clientArray) {
989
- item.target[fieldKey] = mergeArraysUnique(clientArray, serverArray);
990
- continue;
991
- }
992
- }
993
- if (!Object.prototype.hasOwnProperty.call(item.target, fieldKey)) {
994
- item.target[fieldKey] = clientFieldValue;
995
- }
996
- }
997
- }
998
- merged[key] = extensionValue;
999
- }
1000
- return merged;
1001
- }
1002
- /**
1003
- * Enriches a payment payload by calling registered extension hooks.
1004
- * Invokes enrichPaymentPayload for every registered extension, then merges
1005
- * server-declared extension fields back into the result.
1006
- *
1007
- * @param paymentPayload - The payment payload to enrich with extension data
1008
- * @param paymentRequired - The PaymentRequired response containing extension declarations
1009
- * @returns The enriched payment payload with extension data applied
1010
- */
1011
- async enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired) {
1012
- if (this.registeredExtensions.size === 0) {
1013
- return paymentPayload;
1014
- }
1015
- let enriched = paymentPayload;
1016
- for (const [, extension] of this.registeredExtensions) {
1017
- if (extension.enrichPaymentPayload) {
1018
- enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);
1019
- }
1020
- }
1021
- return {
1022
- ...enriched,
1023
- extensions: this.mergeExtensions(paymentRequired.extensions, enriched.extensions)
1024
- };
1025
- }
1026
- /**
1027
- * Selects appropriate payment requirements based on registered clients and policies.
1028
- *
1029
- * Selection process:
1030
- * 1. Filter by registered schemes (network + scheme support)
1031
- * 2. Apply all registered policies in order
1032
- * 3. Use selector to choose final requirement
1033
- *
1034
- * @param x402Version - The x402 protocol version
1035
- * @param paymentRequirements - Array of available payment requirements
1036
- * @returns The selected payment requirements
1037
- */
1038
- selectPaymentRequirements(x402Version2, paymentRequirements) {
1039
- const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
1040
- if (!clientSchemesByNetwork) {
1041
- throw new Error(`No client registered for x402 version: ${x402Version2}`);
1042
- }
1043
- const supportedPaymentRequirements = paymentRequirements.filter((requirement) => {
1044
- let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);
1045
- if (!clientSchemes) {
1046
- return false;
1047
- }
1048
- return clientSchemes.has(requirement.scheme);
1049
- });
1050
- if (supportedPaymentRequirements.length === 0) {
1051
- throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({
1052
- x402Version: x402Version2,
1053
- paymentRequirements,
1054
- x402Versions: Array.from(this.registeredClientSchemes.keys()),
1055
- networks: Array.from(clientSchemesByNetwork.keys()),
1056
- schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
1057
- })}`);
1058
- }
1059
- let filteredRequirements = supportedPaymentRequirements;
1060
- for (const policy of this.policies) {
1061
- filteredRequirements = policy(x402Version2, filteredRequirements);
1062
- if (filteredRequirements.length === 0) {
1063
- throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
1064
- }
1065
- }
1066
- return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
1067
- }
1068
- /**
1069
- * Internal method to register a scheme client.
1070
- *
1071
- * @param x402Version - The x402 protocol version
1072
- * @param network - The network to register the client for
1073
- * @param client - The scheme network client to register
1074
- * @returns The x402Client instance for chaining
1075
- */
1076
- _registerScheme(x402Version2, network, client) {
1077
- if (!this.registeredClientSchemes.has(x402Version2)) {
1078
- this.registeredClientSchemes.set(x402Version2, /* @__PURE__ */ new Map());
1079
- }
1080
- const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
1081
- if (!clientSchemesByNetwork.has(network)) {
1082
- clientSchemesByNetwork.set(network, /* @__PURE__ */ new Map());
1083
- }
1084
- const clientByScheme = clientSchemesByNetwork.get(network);
1085
- clientByScheme.set(client.scheme, client);
1086
- if (!this.schemeClientHookAdapters.has(x402Version2)) {
1087
- this.schemeClientHookAdapters.set(x402Version2, /* @__PURE__ */ new Map());
1088
- }
1089
- const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version2);
1090
- if (!adaptersByNetwork.has(network)) {
1091
- adaptersByNetwork.set(network, /* @__PURE__ */ new Map());
1092
- }
1093
- const adaptersByScheme = adaptersByNetwork.get(network);
1094
- const hooks = client.schemeHooks;
1095
- if (!hooks) {
1096
- adaptersByScheme.delete(client.scheme);
1097
- return this;
1098
- }
1099
- const handles = {};
1100
- if (hooks.onBeforePaymentCreation) {
1101
- handles.beforePaymentCreation = hooks.onBeforePaymentCreation;
1102
- }
1103
- if (hooks.onAfterPaymentCreation) {
1104
- handles.afterPaymentCreation = hooks.onAfterPaymentCreation;
1105
- }
1106
- if (hooks.onPaymentCreationFailure) {
1107
- handles.onPaymentCreationFailure = hooks.onPaymentCreationFailure;
1108
- }
1109
- if (hooks.onPaymentResponse) {
1110
- handles.onPaymentResponse = hooks.onPaymentResponse;
1111
- }
1112
- if (Object.keys(handles).length > 0) {
1113
- adaptersByScheme.set(client.scheme, handles);
1114
- } else {
1115
- adaptersByScheme.delete(client.scheme);
1116
- }
1117
- return this;
1118
- }
1119
- /**
1120
- * Returns manual hooks followed by the selected scheme hook and declared extension hooks.
1121
- *
1122
- * @param phase - Hook slot to collect
1123
- * @param x402Version - Protocol version for the selected requirement
1124
- * @param requirements - Selected payment requirement
1125
- * @param declaredExtensions - Extension declarations that scope extension hooks
1126
- * @returns Hooks in invocation order
1127
- */
1128
- getLabeledHooks(phase, x402Version2, requirements, declaredExtensions) {
1129
- let manual;
1130
- switch (phase) {
1131
- case "beforePaymentCreation":
1132
- manual = this.beforePaymentCreationHooks;
1133
- break;
1134
- case "afterPaymentCreation":
1135
- manual = this.afterPaymentCreationHooks;
1136
- break;
1137
- case "onPaymentCreationFailure":
1138
- manual = this.onPaymentCreationFailureHooks;
1139
- break;
1140
- case "onPaymentResponse":
1141
- manual = this.paymentResponseHooks;
1142
- break;
1143
- }
1144
- const out = [...manual];
1145
- const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version2);
1146
- const schemeAdapter = adaptersByNetwork ? findByNetworkAndScheme(adaptersByNetwork, requirements.scheme, requirements.network) : void 0;
1147
- const hook = schemeAdapter?.[phase];
1148
- if (hook !== void 0) {
1149
- out.push(hook);
1150
- }
1151
- if (!declaredExtensions) {
1152
- return out;
1153
- }
1154
- const extensionHookKey = this.getClientExtensionHookKey(phase);
1155
- for (const [extensionKey, extension] of this.registeredExtensions) {
1156
- if (!(extensionKey in declaredExtensions)) continue;
1157
- const extensionHook = extension.hooks?.[extensionHookKey];
1158
- if (!extensionHook) continue;
1159
- out.push((async (ctx) => {
1160
- return extensionHook(declaredExtensions[extensionKey], ctx);
1161
- }));
1162
- }
1163
- return out;
1164
- }
1165
- /**
1166
- * Maps internal hook phases to extension hook names.
1167
- *
1168
- * @param phase - Internal hook phase
1169
- * @returns Extension hook key for the phase
1170
- */
1171
- getClientExtensionHookKey(phase) {
1172
- switch (phase) {
1173
- case "beforePaymentCreation":
1174
- return "onBeforePaymentCreation";
1175
- case "afterPaymentCreation":
1176
- return "onAfterPaymentCreation";
1177
- case "onPaymentCreationFailure":
1178
- return "onPaymentCreationFailure";
1179
- case "onPaymentResponse":
1180
- return "onPaymentResponse";
1181
- }
1182
- }
1183
- };
1184
- function mergeArraysUnique(client, server) {
1185
- const merged = [];
1186
- for (const item of [...client, ...server]) {
1187
- if (!merged.some((existing) => deepEqual(existing, item))) {
1188
- merged.push(item);
1189
- }
1190
- }
1191
- return merged;
1192
- }
1193
-
1194
- // node_modules/@x402/evm/dist/esm/chunk-K3FJDFD6.mjs
1195
- async function signVoucher(signer, channelId, maxClaimableAmount, network) {
1196
- const chainId = getEvmChainId(network);
1197
- const signature = await signer.signTypedData({
1198
- domain: getBatchSettlementEip712Domain(chainId),
1199
- types: voucherTypes,
1200
- primaryType: "Voucher",
1201
- message: {
1202
- channelId,
1203
- maxClaimableAmount: BigInt(maxClaimableAmount)
1204
- }
1205
- });
1206
- return {
1207
- channelId,
1208
- maxClaimableAmount,
1209
- signature
1210
- };
1211
- }
1212
- async function createBatchSettlementEIP3009DepositPayload(signer, x402Version2, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
1213
- const salt = createNonce();
1214
- const now = Math.floor(Date.now() / 1e3);
1215
- const chainId = getEvmChainId(paymentRequirements.network);
1216
- if (!paymentRequirements.extra?.name || !paymentRequirements.extra?.version) {
1217
- throw new Error(
1218
- `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`
1219
- );
1220
- }
1221
- const { name, version } = paymentRequirements.extra;
1222
- const channelId = computeChannelId(channelConfig, paymentRequirements.network);
1223
- const erc3009Nonce = buildErc3009DepositNonce(channelId, salt);
1224
- const signature = await signer.signTypedData({
1225
- domain: {
1226
- name,
1227
- version,
1228
- chainId,
1229
- verifyingContract: getAddress(paymentRequirements.asset)
1230
- },
1231
- types: receiveAuthorizationTypes,
1232
- primaryType: "ReceiveWithAuthorization",
1233
- message: {
1234
- from: getAddress(signer.address),
1235
- to: getAddress(ERC3009_DEPOSIT_COLLECTOR_ADDRESS),
1236
- value: BigInt(depositAmount),
1237
- validAfter: BigInt(0),
1238
- validBefore: BigInt(now + paymentRequirements.maxTimeoutSeconds),
1239
- nonce: erc3009Nonce
1240
- }
1241
- });
1242
- const vSigner = voucherSigner ?? signer;
1243
- const voucher = await signVoucher(
1244
- vSigner,
1245
- channelId,
1246
- maxClaimableAmount,
1247
- paymentRequirements.network
1248
- );
1249
- const payload = {
1250
- type: "deposit",
1251
- channelConfig,
1252
- voucher,
1253
- deposit: {
1254
- amount: depositAmount,
1255
- authorization: {
1256
- erc3009Authorization: {
1257
- validAfter: "0",
1258
- validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
1259
- salt,
1260
- signature
1261
- }
1262
- }
1263
- }
1264
- };
1265
- return {
1266
- x402Version: x402Version2,
1267
- payload
1268
- };
1269
- }
1270
- var InMemoryClientChannelStorage = class {
1271
- constructor() {
1272
- this.channels = /* @__PURE__ */ new Map();
1273
- }
1274
- /**
1275
- * Returns the channel record for `key` if present.
1276
- *
1277
- * @param key - Channel storage key (a canonical `bytes32` channel id).
1278
- * @returns Persisted context or undefined.
1279
- */
1280
- async get(key) {
1281
- return this.channels.get(normalizeChannelId(key));
1282
- }
1283
- /**
1284
- * Stores or replaces the channel record for `key`.
1285
- *
1286
- * @param key - Channel storage key (a canonical `bytes32` channel id).
1287
- * @param context - Channel fields to persist.
1288
- * @returns Resolves when stored.
1289
- */
1290
- async set(key, context) {
1291
- this.channels.set(normalizeChannelId(key), context);
1292
- }
1293
- /**
1294
- * Removes the channel record for `key` if it exists.
1295
- *
1296
- * @param key - Channel storage key (a canonical `bytes32` channel id).
1297
- * @returns Resolves when removed.
1298
- */
1299
- async delete(key) {
1300
- this.channels.delete(normalizeChannelId(key));
1301
- }
1302
- };
1303
- var DEFAULT_SALT = "0x0000000000000000000000000000000000000000000000000000000000000000";
1304
- function isBatchSettlementEvmSchemeOptions(o) {
1305
- 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);
1306
- }
1307
- function resolveClientOptions(second) {
1308
- if (second === void 0) {
1309
- return { storage: new InMemoryClientChannelStorage(), salt: DEFAULT_SALT };
1310
- }
1311
- if (isBatchSettlementEvmSchemeOptions(second)) {
1312
- return {
1313
- storage: second.storage ?? new InMemoryClientChannelStorage(),
1314
- depositPolicy: second.depositPolicy,
1315
- depositStrategy: second.depositStrategy,
1316
- salt: second.salt ?? DEFAULT_SALT,
1317
- payerAuthorizer: second.payerAuthorizer,
1318
- voucherSigner: second.voucherSigner,
1319
- extensionRpcOptions: second.rpcUrl ? { rpcUrl: second.rpcUrl } : void 0
1320
- };
1321
- }
1322
- return {
1323
- storage: new InMemoryClientChannelStorage(),
1324
- depositPolicy: second,
1325
- salt: DEFAULT_SALT
1326
- };
1327
- }
1328
- function validateDepositPolicy(policy) {
1329
- if (!policy) return;
1330
- const m = policy.depositMultiplier;
1331
- if (m !== void 0 && (!Number.isInteger(m) || m < 3)) {
1332
- throw new Error("depositMultiplier must be an integer >= 3");
1333
- }
1334
- }
1335
- function depositAmountForRequest(policy, requestAmount) {
1336
- const mult = BigInt(policy?.depositMultiplier ?? 5);
1337
- return (mult * requestAmount).toString();
1338
- }
1339
- function readResponseChannelState(extra) {
1340
- const channelState = extra.channelState;
1341
- if (typeof channelState !== "object" || channelState === null) {
1342
- return void 0;
1343
- }
1344
- return channelState;
1345
- }
1346
- function buildChannelConfig(deps, paymentRequirements) {
1347
- const extra = paymentRequirements.extra;
1348
- const receiverAuthorizer = extra?.receiverAuthorizer;
1349
- if (!receiverAuthorizer || getAddress(receiverAuthorizer) === "0x0000000000000000000000000000000000000000") {
1350
- throw new Error("Payment requirements must include a non-zero extra.receiverAuthorizer");
1351
- }
1352
- return {
1353
- payer: deps.signer.address,
1354
- payerAuthorizer: getAddress(
1355
- deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
1356
- ),
1357
- receiver: paymentRequirements.payTo,
1358
- receiverAuthorizer: getAddress(receiverAuthorizer),
1359
- token: paymentRequirements.asset,
1360
- withdrawDelay: typeof extra?.withdrawDelay === "number" ? extra.withdrawDelay : MIN_WITHDRAW_DELAY,
1361
- salt: deps.salt
1362
- };
1363
- }
1364
- async function processSettleResponse(storage, settle) {
1365
- const extra = settle.extra ?? {};
1366
- const channelState = readResponseChannelState(extra);
1367
- if (!channelState) return;
1368
- const channelId = channelState.channelId;
1369
- const key = channelId.toLowerCase();
1370
- const prev = await storage.get(key);
1371
- const next = { ...prev ?? {} };
1372
- if (channelState.chargedCumulativeAmount !== void 0) {
1373
- next.chargedCumulativeAmount = String(channelState.chargedCumulativeAmount);
1374
- }
1375
- if (channelState.balance !== void 0) {
1376
- next.balance = String(channelState.balance);
1377
- }
1378
- if (channelState.totalClaimed !== void 0) {
1379
- next.totalClaimed = String(channelState.totalClaimed);
1380
- }
1381
- await storage.set(key, next);
1382
- }
1383
- async function updateChannelAfterRefund(storage, channelKey, settleExtra) {
1384
- const channelState = readResponseChannelState(settleExtra);
1385
- if (!channelState) {
1386
- await storage.delete(channelKey);
1387
- return;
1388
- }
1389
- const balanceAfter = channelState.balance !== void 0 ? BigInt(String(channelState.balance)) : void 0;
1390
- if (balanceAfter === void 0 || balanceAfter <= 0n) {
1391
- await storage.delete(channelKey);
1392
- return;
1393
- }
1394
- const prev = await storage.get(channelKey);
1395
- const next = { ...prev ?? {} };
1396
- next.balance = balanceAfter.toString();
1397
- if (channelState.chargedCumulativeAmount !== void 0) {
1398
- next.chargedCumulativeAmount = String(channelState.chargedCumulativeAmount);
1399
- }
1400
- if (channelState.totalClaimed !== void 0) {
1401
- next.totalClaimed = String(channelState.totalClaimed);
1402
- }
1403
- await storage.set(channelKey, next);
1404
- }
1405
- async function recoverChannel(deps, paymentRequirements) {
1406
- if (!deps.signer.readContract) {
1407
- throw new Error("recoverChannel requires ClientEvmSigner.readContract");
1408
- }
1409
- const config = buildChannelConfig(deps, paymentRequirements);
1410
- const channelId = computeChannelId(config, paymentRequirements.network);
1411
- const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1412
- deps.signer,
1413
- channelId
1414
- );
1415
- const ctx = {
1416
- chargedCumulativeAmount: chTotalClaimed.toString(),
1417
- balance: chBalance.toString(),
1418
- totalClaimed: chTotalClaimed.toString()
1419
- };
1420
- await deps.storage.set(channelId.toLowerCase(), ctx);
1421
- return ctx;
1422
- }
1423
- async function readChannelBalanceAndTotalClaimed(signer, channelId) {
1424
- if (!signer.readContract) {
1425
- throw new Error("readChannelBalanceAndTotalClaimed requires ClientEvmSigner.readContract");
1426
- }
1427
- return await signer.readContract({
1428
- address: BATCH_SETTLEMENT_ADDRESS,
1429
- abi: batchSettlementABI,
1430
- functionName: "channels",
1431
- args: [channelId]
1432
- });
1433
- }
1434
- async function processCorrectivePaymentRequired(deps, paymentRequired) {
1435
- if (paymentRequired.error !== ErrCumulativeAmountMismatch && paymentRequired.error !== ErrCumulativeAmountBelowClaimed) {
1436
- return false;
1437
- }
1438
- const accept = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
1439
- if (!accept) {
1440
- return false;
1441
- }
1442
- const channelState = accept.extra.channelState;
1443
- const voucherState = accept.extra.voucherState;
1444
- const hasSig = channelState?.chargedCumulativeAmount !== void 0 && voucherState?.signedMaxClaimable !== void 0 && voucherState.signature !== void 0;
1445
- if (!hasSig) {
1446
- return recoverFromOnChainState(deps, accept);
1447
- }
1448
- return recoverFromSignature(deps, accept, channelState, voucherState);
1449
- }
1450
- async function recoverFromSignature(deps, accept, channelState, voucherState) {
1451
- const chargedRaw = channelState.chargedCumulativeAmount;
1452
- const signedRaw = voucherState.signedMaxClaimable;
1453
- const sig = voucherState.signature;
1454
- const charged = BigInt(String(chargedRaw));
1455
- const signed = BigInt(String(signedRaw));
1456
- if (charged > signed) {
1457
- return false;
1458
- }
1459
- const config = buildChannelConfig(deps, accept);
1460
- const channelId = computeChannelId(config, accept.network);
1461
- if (!deps.signer.readContract) {
1462
- return false;
1463
- }
1464
- const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1465
- deps.signer,
1466
- channelId
1467
- );
1468
- if (charged < chTotalClaimed) {
1469
- return false;
1470
- }
1471
- const chainId = getEvmChainId(accept.network);
1472
- const recovered = await recoverTypedDataAddress({
1473
- domain: getBatchSettlementEip712Domain(chainId),
1474
- types: voucherTypes,
1475
- primaryType: "Voucher",
1476
- message: {
1477
- channelId,
1478
- maxClaimableAmount: signed
1479
- },
1480
- signature: sig
1481
- });
1482
- const expectedSigner = getAddress(
1483
- deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
1484
- );
1485
- if (recovered.toLowerCase() !== expectedSigner.toLowerCase()) {
1486
- return false;
1487
- }
1488
- const ctx = {
1489
- chargedCumulativeAmount: charged.toString(),
1490
- signedMaxClaimable: signed.toString(),
1491
- signature: sig,
1492
- balance: chBalance.toString(),
1493
- totalClaimed: chTotalClaimed.toString()
1494
- };
1495
- await deps.storage.set(channelId.toLowerCase(), ctx);
1496
- return true;
1497
- }
1498
- async function recoverFromOnChainState(deps, accept) {
1499
- if (!deps.signer.readContract) {
1500
- return false;
1501
- }
1502
- const config = buildChannelConfig(deps, accept);
1503
- const channelId = computeChannelId(config, accept.network);
1504
- const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1505
- deps.signer,
1506
- channelId
1507
- );
1508
- const ctx = {
1509
- chargedCumulativeAmount: chTotalClaimed.toString(),
1510
- balance: chBalance.toString(),
1511
- totalClaimed: chTotalClaimed.toString()
1512
- };
1513
- await deps.storage.set(channelId.toLowerCase(), ctx);
1514
- return true;
1515
- }
1516
- function createBatchSettlementClientHooks(deps) {
1517
- return {
1518
- onPaymentResponse: (ctx) => handleBatchSettlementPaymentResponse(deps, ctx)
1519
- };
1520
- }
1521
- async function handleBatchSettlementPaymentResponse(deps, ctx) {
1522
- if (ctx.settleResponse) {
1523
- if (isBatchSettlementRefundPayload(ctx.paymentPayload.payload)) {
1524
- const extra = ctx.settleResponse.extra ?? {};
1525
- const channelState = extra.channelState;
1526
- const channelId = typeof channelState === "object" && channelState !== null && "channelId" in channelState ? channelState.channelId : void 0;
1527
- if (typeof channelId === "string" && channelId) {
1528
- await updateChannelAfterRefund(deps.storage, channelId.toLowerCase(), extra);
1529
- }
1530
- return;
1531
- }
1532
- await processSettleResponse(deps.storage, ctx.settleResponse);
1533
- return;
1534
- }
1535
- if (ctx.paymentRequired) {
1536
- const recovered = await processCorrectivePaymentRequired(deps, ctx.paymentRequired);
1537
- return recovered ? { recovered: true } : void 0;
1538
- }
1539
- }
1540
- var NON_RECOVERABLE_REFUND_ERRORS = /* @__PURE__ */ new Set([
1541
- ErrRefundNoBalance,
1542
- ErrRefundAmountInvalid
1543
- ]);
1544
- async function refundChannel(ctx, url, options) {
1545
- const fetchImpl = options?.fetch ?? globalThis.fetch;
1546
- if (!fetchImpl) {
1547
- throw new Error("refund requires a fetch implementation (globalThis.fetch unavailable)");
1548
- }
1549
- const refundAmount = normalizeRefundAmount(options?.amount);
1550
- const probe = await probeRefundRequirements(url, fetchImpl);
1551
- return executeRefund(ctx, url, probe, refundAmount, fetchImpl);
1552
- }
1553
- async function probeRefundRequirements(url, fetchImpl) {
1554
- const probe = await fetchImpl(url, { method: "GET" });
1555
- if (probe.status !== 402) {
1556
- throw new Error(`Refund probe expected 402, got ${probe.status}`);
1557
- }
1558
- const header = probe.headers.get("PAYMENT-REQUIRED");
1559
- if (!header) {
1560
- throw new Error("Refund probe response missing PAYMENT-REQUIRED header");
1561
- }
1562
- const paymentRequired = decodePaymentRequiredHeader(header);
1563
- const requirements = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
1564
- if (!requirements) {
1565
- throw new Error(`No ${BATCH_SETTLEMENT_SCHEME} payment option at ${url}`);
1566
- }
1567
- const extra = requirements.extra;
1568
- if (!extra?.receiverAuthorizer) {
1569
- throw new Error("Refund requires a configured receiverAuthorizer on the receiver");
1570
- }
1571
- return { paymentRequired, requirements };
1572
- }
1573
- async function executeRefund(ctx, url, probe, refundAmount, fetchImpl) {
1574
- const maxAttempts = 2;
1575
- const { paymentRequired, requirements } = probe;
1576
- const httpClient = createRefundHttpClient(ctx, requirements);
1577
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
1578
- const paymentPayload = await buildRefundPaymentPayload(
1579
- ctx,
1580
- paymentRequired,
1581
- requirements,
1582
- refundAmount
1583
- );
1584
- const headers = httpClient.encodePaymentSignatureHeader(paymentPayload);
1585
- const response = await fetchImpl(url, { method: "GET", headers });
1586
- if (response.status === 402) {
1587
- const nonRecoverable = getNonRecoverableRefundFailure(response);
1588
- if (nonRecoverable) {
1589
- throw new Error(nonRecoverable);
1590
- }
1591
- }
1592
- const result = await httpClient.processPaymentResult(
1593
- paymentPayload,
1594
- (name) => response.headers.get(name),
1595
- response.status
1596
- );
1597
- if (response.status === 402) {
1598
- if (result.recovered && attempt < maxAttempts) {
1599
- continue;
1600
- }
1601
- if (result.recovered) {
1602
- throw new Error(`Refund failed: server returned 402 after ${attempt} attempt(s)`);
1603
- }
1604
- const corrective = getRefundPaymentRequired(response);
1605
- throw new Error(`Refund failed: ${corrective.error ?? "unknown"}`);
1606
- }
1607
- if (!result.settleResponse) {
1608
- throw new Error(
1609
- `Refund response missing PAYMENT-RESPONSE header (status ${response.status})`
1610
- );
1611
- }
1612
- return result.settleResponse;
1613
- }
1614
- throw new Error("Refund failed: retry budget exhausted");
1615
- }
1616
- async function buildRefundPaymentPayload(ctx, paymentRequired, requirements, refundAmount) {
1617
- const config = buildChannelConfig(ctx, requirements);
1618
- const channelId = computeChannelId(config, requirements.network);
1619
- const key = channelId.toLowerCase();
1620
- let channel = await ctx.storage.get(key);
1621
- if (channel === void 0 && ctx.signer.readContract) {
1622
- channel = await recoverChannel(ctx, requirements);
1623
- }
1624
- if (channel === void 0) {
1625
- throw new Error(
1626
- "Refund requires an existing channel record; deposit first or call from a context with an EVM RPC"
1627
- );
1628
- }
1629
- const charged = channel.chargedCumulativeAmount ?? "0";
1630
- if (channel.balance !== void 0 && BigInt(channel.balance) <= BigInt(charged)) {
1631
- throw new Error(
1632
- `Refund failed: channel has no remaining balance (balance=${channel.balance}, chargedCumulativeAmount=${charged})`
1633
- );
1634
- }
1635
- const voucherSigner = ctx.voucherSigner ?? ctx.signer;
1636
- const voucher = await signVoucher(voucherSigner, channelId, charged, requirements.network);
1637
- const payload = {
1638
- type: "refund",
1639
- channelConfig: config,
1640
- voucher,
1641
- ...refundAmount !== void 0 ? { amount: refundAmount } : {}
1642
- };
1643
- return {
1644
- x402Version: 2,
1645
- accepted: requirements,
1646
- payload,
1647
- ...paymentRequired.resource ? { resource: paymentRequired.resource } : {},
1648
- ...paymentRequired.extensions ? { extensions: paymentRequired.extensions } : {}
1649
- };
1650
- }
1651
- function createRefundHttpClient(ctx, requirements) {
1652
- const client = new x402Client().register(requirements.network, {
1653
- scheme: BATCH_SETTLEMENT_SCHEME,
1654
- schemeHooks: createBatchSettlementClientHooks(ctx),
1655
- createPaymentPayload: async () => {
1656
- throw new Error("Refund payloads are built by refundChannel");
1657
- }
1658
- });
1659
- return new x402HTTPClient(client);
1660
- }
1661
- function getNonRecoverableRefundFailure(response) {
1662
- const settleHeader = response.headers.get("PAYMENT-RESPONSE");
1663
- if (settleHeader) {
1664
- return formatRefundFailure(decodePaymentResponseHeader(settleHeader));
1665
- }
1666
- const paymentRequired = getRefundPaymentRequired(response);
1667
- const errorCode = paymentRequired.error;
1668
- if (errorCode && NON_RECOVERABLE_REFUND_ERRORS.has(errorCode)) {
1669
- return `Refund failed: ${errorCode}`;
1670
- }
1671
- }
1672
- function getRefundPaymentRequired(response) {
1673
- const requiredHeader = response.headers.get("PAYMENT-REQUIRED");
1674
- if (!requiredHeader) {
1675
- throw new Error("Refund 402 missing PAYMENT-REQUIRED header");
1676
- }
1677
- return decodePaymentRequiredHeader(requiredHeader);
1678
- }
1679
- function formatRefundFailure(settle) {
1680
- const reason = settle.errorReason ?? "unknown_settlement_error";
1681
- const message = settle.errorMessage;
1682
- if (message && message !== reason) {
1683
- return `Refund failed: ${reason}: ${message}`;
1684
- }
1685
- return `Refund failed: ${reason}`;
1686
- }
1687
- function normalizeRefundAmount(amount) {
1688
- if (amount === void 0) return void 0;
1689
- if (!/^\d+$/.test(amount) || amount === "0") {
1690
- throw new Error(`Invalid refund amount "${amount}": must be a positive integer string`);
1691
- }
1692
- return amount;
1693
- }
1694
- async function createBatchSettlementPermit2DepositPayload(signer, x402Version2, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
1695
- const chainId = getEvmChainId(paymentRequirements.network);
1696
- const nonce = createPermit2Nonce();
1697
- const deadline = Math.floor(Date.now() / 1e3 + paymentRequirements.maxTimeoutSeconds).toString();
1698
- const channelId = computeChannelId(channelConfig, paymentRequirements.network);
1699
- const permit2Authorization = {
1700
- from: signer.address,
1701
- permitted: {
1702
- token: getAddress(paymentRequirements.asset),
1703
- amount: depositAmount
1704
- },
1705
- spender: getAddress(PERMIT2_DEPOSIT_COLLECTOR_ADDRESS),
1706
- nonce,
1707
- deadline,
1708
- witness: {
1709
- channelId
1710
- }
1711
- };
1712
- const signature = await signer.signTypedData({
1713
- domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
1714
- types: batchPermit2WitnessTypes,
1715
- primaryType: "PermitWitnessTransferFrom",
1716
- message: {
1717
- permitted: {
1718
- token: permit2Authorization.permitted.token,
1719
- amount: BigInt(permit2Authorization.permitted.amount)
1720
- },
1721
- spender: permit2Authorization.spender,
1722
- nonce: BigInt(permit2Authorization.nonce),
1723
- deadline: BigInt(permit2Authorization.deadline),
1724
- witness: {
1725
- channelId
1726
- }
1727
- }
1728
- });
1729
- const voucher = await signVoucher(
1730
- voucherSigner ?? signer,
1731
- channelId,
1732
- maxClaimableAmount,
1733
- paymentRequirements.network
1734
- );
1735
- const payload = {
1736
- type: "deposit",
1737
- channelConfig,
1738
- voucher,
1739
- deposit: {
1740
- amount: depositAmount,
1741
- authorization: {
1742
- permit2Authorization: {
1743
- ...permit2Authorization,
1744
- signature
1745
- }
1746
- }
1747
- }
1748
- };
1749
- return { x402Version: x402Version2, payload };
1750
- }
1751
- var BatchSettlementEvmScheme = class {
1752
- /**
1753
- * Constructs a batched client scheme.
1754
- *
1755
- * @param signer - Client EVM wallet used for signing vouchers and ERC-3009 authorizations.
1756
- * @param optionsOrPolicy - Either a full options object or a bare deposit-policy.
1757
- */
1758
- constructor(signer, optionsOrPolicy) {
1759
- this.signer = signer;
1760
- this.scheme = BATCH_SETTLEMENT_SCHEME;
1761
- const {
1762
- storage,
1763
- depositPolicy,
1764
- depositStrategy,
1765
- salt,
1766
- payerAuthorizer,
1767
- voucherSigner,
1768
- extensionRpcOptions
1769
- } = resolveClientOptions(optionsOrPolicy);
1770
- this.storage = storage;
1771
- this.depositPolicy = depositPolicy;
1772
- this.depositStrategy = depositStrategy;
1773
- this.salt = salt;
1774
- this.payerAuthorizer = payerAuthorizer;
1775
- this.voucherSigner = voucherSigner;
1776
- this.extensionRpcOptions = extensionRpcOptions;
1777
- if (payerAuthorizer !== void 0 && voucherSigner !== void 0 && getAddress(payerAuthorizer) !== getAddress(voucherSigner.address)) {
1778
- throw new Error("payerAuthorizer address must match voucherSigner.address");
1779
- }
1780
- validateDepositPolicy(depositPolicy);
1781
- this.schemeHooks = createBatchSettlementClientHooks(this.deps());
1782
- }
1783
- /**
1784
- * Creates the payment payload for a batched request.
1785
- *
1786
- * If the channel has no onchain deposit (or needs a top-up), builds an
1787
- * ERC-3009 deposit payload bundled with a voucher. Otherwise, signs and
1788
- * returns a voucher-only payload.
1789
- *
1790
- * @param x402Version - Protocol version for the payload envelope.
1791
- * @param paymentRequirements - Server payment requirements (scheme, network, asset, amount).
1792
- * @param context - Optional payment payload context with extension hints.
1793
- * @returns A {@link PaymentPayloadResult} ready to be sent as the `X-PAYMENT` header.
1794
- */
1795
- async createPaymentPayload(x402Version2, paymentRequirements, context) {
1796
- const deps = this.deps();
1797
- const config = buildChannelConfig(deps, paymentRequirements);
1798
- const channelId = computeChannelId(config, paymentRequirements.network);
1799
- const key = channelId.toLowerCase();
1800
- let batchedCtx = await this.storage.get(key);
1801
- if (batchedCtx === void 0 && this.signer.readContract) {
1802
- batchedCtx = await recoverChannel(deps, paymentRequirements);
1803
- }
1804
- batchedCtx = batchedCtx ?? {};
1805
- const needsInitialDeposit = !batchedCtx.balance || batchedCtx.balance === "0";
1806
- const baseCumulative = BigInt(batchedCtx.chargedCumulativeAmount ?? "0");
1807
- const requestAmount = BigInt(paymentRequirements.amount);
1808
- const maxClaimableAmount = (baseCumulative + requestAmount).toString();
1809
- const currentBalance = BigInt(batchedCtx.balance ?? "0");
1810
- const needsTopUp = !needsInitialDeposit && BigInt(maxClaimableAmount) > currentBalance;
1811
- if (needsInitialDeposit || needsTopUp) {
1812
- const computedDeposit = depositAmountForRequest(this.depositPolicy, requestAmount);
1813
- const minimumDepositAmount = BigInt(maxClaimableAmount) - currentBalance;
1814
- const depositAmount = await this.resolveDepositAmount({
1815
- paymentRequirements,
1816
- channelConfig: config,
1817
- channelId,
1818
- clientContext: batchedCtx,
1819
- requestAmount: requestAmount.toString(),
1820
- maxClaimableAmount,
1821
- currentBalance: currentBalance.toString(),
1822
- minimumDepositAmount: minimumDepositAmount.toString(),
1823
- depositAmount: computedDeposit
1824
- });
1825
- if (depositAmount === false) {
1826
- return this.createVoucherPayload(
1827
- x402Version2,
1828
- channelId,
1829
- maxClaimableAmount,
1830
- paymentRequirements.network,
1831
- config
1832
- );
1833
- }
1834
- const assetTransferMethod = paymentRequirements.extra?.assetTransferMethod ?? "eip3009";
1835
- if (assetTransferMethod === "eip3009") {
1836
- return createBatchSettlementEIP3009DepositPayload(
1837
- this.signer,
1838
- x402Version2,
1839
- paymentRequirements,
1840
- config,
1841
- depositAmount,
1842
- maxClaimableAmount,
1843
- this.voucherSigner
1844
- );
1845
- }
1846
- if (assetTransferMethod !== "permit2") {
1847
- throw new Error(`unsupported batch-settlement assetTransferMethod: ${assetTransferMethod}`);
1848
- }
1849
- const result = await createBatchSettlementPermit2DepositPayload(
1850
- this.signer,
1851
- x402Version2,
1852
- paymentRequirements,
1853
- config,
1854
- depositAmount,
1855
- maxClaimableAmount,
1856
- this.voucherSigner
1857
- );
1858
- const eip2612Extensions = await trySignEip2612PermitExtension(
1859
- this.signer,
1860
- this.extensionRpcOptions,
1861
- paymentRequirements,
1862
- result,
1863
- context,
1864
- depositAmount
1865
- );
1866
- if (eip2612Extensions) {
1867
- return { ...result, extensions: eip2612Extensions };
1868
- }
1869
- const erc20Extensions = await trySignErc20ApprovalExtension(
1870
- this.signer,
1871
- this.extensionRpcOptions,
1872
- paymentRequirements,
1873
- context,
1874
- depositAmount
1875
- );
1876
- if (erc20Extensions) {
1877
- return { ...result, extensions: erc20Extensions };
1878
- }
1879
- return result;
1880
- }
1881
- return this.createVoucherPayload(
1882
- x402Version2,
1883
- channelId,
1884
- maxClaimableAmount,
1885
- paymentRequirements.network,
1886
- config
1887
- );
1888
- }
1889
- /**
1890
- * Sends a cooperative refund request.
1891
- *
1892
- * @param url - The route URL backing the channel to refund.
1893
- * @param options - Optional `amount` (partial refund) and `fetch` override.
1894
- * @returns The settle response describing the refund outcome.
1895
- */
1896
- async refund(url, options) {
1897
- return refundChannel(this.deps(), url, options);
1898
- }
1899
- /**
1900
- * Updates local channel state from a settle response.
1901
- *
1902
- * @param settle - The parsed settle response from the server.
1903
- * @returns Resolves when local channel state has been updated.
1904
- */
1905
- async processSettleResponse(settle) {
1906
- return processSettleResponse(this.storage, settle);
1907
- }
1908
- /**
1909
- * Resyncs local channel state from a corrective 402 response.
1910
- *
1911
- * @param paymentRequired - The decoded 402 response body.
1912
- * @returns `true` if local state was successfully resynced and a retry is warranted.
1913
- */
1914
- async processCorrectivePaymentRequired(paymentRequired) {
1915
- return processCorrectivePaymentRequired(this.deps(), paymentRequired);
1916
- }
1917
- /**
1918
- * Builds the immutable {@link ChannelConfig} for a given set of payment
1919
- * requirements, using the scheme's own signer and salt.
1920
- *
1921
- * @param paymentRequirements - Server payment requirements for the channel.
1922
- * @returns The channel config that uniquely identifies the payment channel.
1923
- */
1924
- buildChannelConfig(paymentRequirements) {
1925
- return buildChannelConfig(this.deps(), paymentRequirements);
1926
- }
1927
- /**
1928
- * Resolves the deposit amount after applying the optional custom strategy.
1929
- *
1930
- * @param context - Deposit attempt context exposed to the strategy.
1931
- * @returns The deposit amount to sign, or `false` to skip this deposit attempt.
1932
- */
1933
- async resolveDepositAmount(context) {
1934
- const strategyResult = await this.depositStrategy?.(context);
1935
- if (strategyResult === false) return false;
1936
- if (strategyResult === void 0) return context.depositAmount;
1937
- const depositAmount = this.normalizeStrategyDepositAmount(strategyResult);
1938
- if (BigInt(depositAmount) < BigInt(context.minimumDepositAmount)) {
1939
- throw new Error(
1940
- `depositStrategy returned ${depositAmount}, below required top-up ${context.minimumDepositAmount}`
1941
- );
1942
- }
1943
- return depositAmount;
1944
- }
1945
- /**
1946
- * Normalizes and validates a strategy-provided base-unit deposit amount.
1947
- *
1948
- * @param value - Strategy-provided string or bigint amount.
1949
- * @returns Normalized decimal string.
1950
- */
1951
- normalizeStrategyDepositAmount(value) {
1952
- if (typeof value === "bigint") {
1953
- if (value <= 0n) {
1954
- throw new Error("depositStrategy must return a positive integer deposit amount");
1955
- }
1956
- return value.toString();
1957
- }
1958
- if (/^\d+$/.test(value) && BigInt(value) > 0n) {
1959
- return BigInt(value).toString();
1960
- }
1961
- throw new Error("depositStrategy must return a positive integer deposit amount");
1962
- }
1963
- /**
1964
- * Signs a voucher-only payment payload for the current channel.
1965
- *
1966
- * @param x402Version - Protocol version for the payload envelope.
1967
- * @param channelId - Channel identifier for the voucher.
1968
- * @param maxClaimableAmount - Cumulative ceiling for the voucher.
1969
- * @param network - CAIP-2 network identifier.
1970
- * @param config - Immutable channel configuration.
1971
- * @returns Voucher-only payment payload.
1972
- */
1973
- async createVoucherPayload(x402Version2, channelId, maxClaimableAmount, network, config) {
1974
- const voucherSigner = this.voucherSigner ?? this.signer;
1975
- const voucher = await signVoucher(voucherSigner, channelId, maxClaimableAmount, network);
1976
- const payload = {
1977
- type: "voucher",
1978
- channelConfig: config,
1979
- voucher
1980
- };
1981
- return {
1982
- x402Version: x402Version2,
1983
- payload
1984
- };
1985
- }
1986
- /**
1987
- * Bundles the class state into the {@link BatchSettlementClientDeps} shape
1988
- * consumed by the `channel`, `recovery`, and `refund` modules.
1989
- *
1990
- * @returns Client deps wrapping the scheme's own signer and storage.
1991
- */
1992
- deps() {
1993
- return {
1994
- signer: this.signer,
1995
- storage: this.storage,
1996
- salt: this.salt,
1997
- payerAuthorizer: this.payerAuthorizer,
1998
- voucherSigner: this.voucherSigner
1999
- };
2000
- }
2001
- };
2002
-
2003
- // node_modules/@x402/evm/dist/esm/chunk-NVFLWXGP.mjs
2004
- var EVM_NETWORK_CHAIN_ID_MAP = {
2005
- ethereum: 1,
2006
- sepolia: 11155111,
2007
- abstract: 2741,
2008
- "abstract-testnet": 11124,
2009
- "base-sepolia": 84532,
2010
- base: 8453,
2011
- "avalanche-fuji": 43113,
2012
- avalanche: 43114,
2013
- iotex: 4689,
2014
- sei: 1329,
2015
- "sei-testnet": 1328,
2016
- polygon: 137,
2017
- "polygon-amoy": 80002,
2018
- peaq: 3338,
2019
- story: 1514,
2020
- educhain: 41923,
2021
- "skale-base-sepolia": 324705682,
2022
- megaeth: 4326,
2023
- monad: 143,
2024
- stable: 988,
2025
- "stable-testnet": 2201,
2026
- celo: 42220,
2027
- flare: 14
2028
- };
2029
- var NETWORKS = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);
2030
-
2031
- // node_modules/@x402/evm/dist/esm/chunk-UBBS476I.mjs
2032
- var MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2033
-
2034
- // node_modules/@x402/evm/dist/esm/index.mjs
2035
- function toClientEvmSigner(signer, publicClient) {
2036
- const readContract = signer.readContract ?? publicClient?.readContract.bind(publicClient);
2037
- const result = {
2038
- address: signer.address,
2039
- signTypedData: (msg) => signer.signTypedData(msg)
2040
- };
2041
- if (readContract) {
2042
- result.readContract = readContract;
2043
- }
2044
- const signTransaction = signer.signTransaction;
2045
- if (signTransaction) {
2046
- result.signTransaction = (args) => signTransaction(args);
2047
- }
2048
- const getTransactionCount = signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);
2049
- if (getTransactionCount) {
2050
- result.getTransactionCount = (args) => getTransactionCount(args);
2051
- }
2052
- const estimateFeesPerGas = signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);
2053
- if (estimateFeesPerGas) {
2054
- result.estimateFeesPerGas = () => estimateFeesPerGas();
2055
- }
2056
- return result;
2057
- }
2058
-
2059
- // src/lib/x402/batch-abi.ts
2060
- var X402_CHANNEL_CONFIG_COMPONENTS = [
2061
- { name: "payer", type: "address" },
2062
- { name: "payerAuthorizer", type: "address" },
2063
- { name: "receiver", type: "address" },
2064
- { name: "receiverAuthorizer", type: "address" },
2065
- { name: "token", type: "address" },
2066
- { name: "withdrawDelay", type: "uint40" },
2067
- { name: "salt", type: "bytes32" }
2068
- ];
2069
- var X402_BATCH_CHANNEL_ABI = [
2070
- {
2071
- type: "function",
2072
- name: "initiateWithdraw",
2073
- inputs: [
2074
- { name: "config", type: "tuple", components: X402_CHANNEL_CONFIG_COMPONENTS },
2075
- { name: "amount", type: "uint128" }
2076
- ],
2077
- outputs: [],
2078
- stateMutability: "nonpayable"
2079
- },
2080
- {
2081
- type: "function",
2082
- name: "finalizeWithdraw",
2083
- inputs: [{ name: "config", type: "tuple", components: X402_CHANNEL_CONFIG_COMPONENTS }],
2084
- outputs: [],
2085
- stateMutability: "nonpayable"
2086
- },
2087
- {
2088
- type: "function",
2089
- name: "channels",
2090
- inputs: [{ name: "channelId", type: "bytes32" }],
2091
- outputs: [
2092
- { name: "balance", type: "uint128" },
2093
- { name: "totalClaimed", type: "uint128" }
2094
- ],
2095
- stateMutability: "view"
2096
- },
2097
- {
2098
- type: "function",
2099
- name: "pendingWithdrawals",
2100
- inputs: [{ name: "channelId", type: "bytes32" }],
2101
- outputs: [
2102
- { name: "amount", type: "uint128" },
2103
- { name: "initiatedAt", type: "uint40" }
2104
- ],
2105
- stateMutability: "view"
2106
- },
2107
- {
2108
- type: "function",
2109
- name: "refundNonce",
2110
- inputs: [{ name: "channelId", type: "bytes32" }],
2111
- outputs: [{ name: "", type: "uint256" }],
2112
- stateMutability: "view"
2113
- },
2114
- {
2115
- type: "event",
2116
- name: "WithdrawInitiated",
2117
- inputs: [
2118
- { name: "channelId", type: "bytes32", indexed: true },
2119
- { name: "amount", type: "uint128", indexed: false },
2120
- { name: "finalizeAfter", type: "uint40", indexed: false }
2121
- ]
2122
- },
2123
- {
2124
- type: "event",
2125
- name: "WithdrawFinalized",
2126
- inputs: [
2127
- { name: "channelId", type: "bytes32", indexed: true },
2128
- { name: "sender", type: "address", indexed: true },
2129
- { name: "amount", type: "uint128", indexed: false }
2130
- ]
2131
- }
2132
- ];
2133
-
2134
- // src/lib/x402/channel-rpc.ts
2135
- function resolveX402ChannelRpc(channelNetwork, configuredNetwork, bundled) {
2136
- const override = resolveRpcOverride(process.env.DVM_X402_RPC_URL);
2137
- if (override.source === "override" && channelNetwork === configuredNetwork) {
2138
- return { url: override.url, source: "override", overrideOutOfScope: false };
2139
- }
2140
- return {
2141
- url: bundled,
2142
- source: "bundled",
2143
- overrideOutOfScope: override.source === "override"
2144
- };
2145
- }
2146
-
2147
- // src/lib/x402/lifecycle.ts
2148
- async function assertX402WalletIdle(wallet, intent) {
2149
- const payerAddress = wallet.address;
2150
- const owned = listX402Channels({ payer: payerAddress });
2151
- const clients = /* @__PURE__ */ new Map();
2152
- for (const channel of owned) {
2153
- const state = await readChannelState(channel, wallet.network, clients, "guard");
2154
- if (state.balance === 0n && state.pendingWithdrawal === 0n) continue;
2155
- throw new DvmError(
2156
- "x402_wallet_in_use",
2157
- state.balance > 0n ? `The connected x402 wallet still holds ${formatUsdcMicrounits(state.balance)} USDC in an open channel with ${channel.endpoint}.` : `The connected x402 wallet has a timed withdrawal of ${formatUsdcMicrounits(state.pendingWithdrawal)} USDC still in flight on its channel with ${channel.endpoint}.`,
2158
- `Only this key can move those funds. Empty the channel first \u2014 'dvm credit drain' for the cooperative exit, or 'dvm wallet x402-withdraw-initiate --channel-id ${channel.channelId}' and then finalize after the delay \u2014 and ${intentClause(intent)}.`,
2159
- {
2160
- anchor: "x402_channel_live",
2161
- address: payerAddress,
2162
- channel_id: channel.channelId,
2163
- endpoint: channel.endpoint,
2164
- network: channel.network,
2165
- balance_micro: state.balance.toString(),
2166
- pending_withdrawal_micro: state.pendingWithdrawal.toString()
2167
- }
2168
- );
2169
- }
2170
- }
2171
- function assertX402ChannelPayer(channel, address) {
2172
- if (channel.config.payer.toLowerCase() === address.toLowerCase()) return;
2173
- throw new DvmError(
2174
- "x402_wallet_mismatch",
2175
- `The connected x402 wallet ${address} is not the payer recorded for the channel with ${channel.endpoint} \u2014 that channel was opened by ${channel.config.payer}.`,
2176
- `Reconnect that exact key ('dvm wallet x402-connect --key-file <path>', or DVM_X402_KEY=<key> dvm wallet x402-connect), then retry. Nothing was signed or moved, and the channel's balance is untouched \u2014 only ${channel.config.payer} can move it.`,
2177
- {
2178
- anchor: "x402_channel_payer_mismatch",
2179
- channel_id: channel.channelId,
2180
- endpoint: channel.endpoint,
2181
- network: channel.network,
2182
- recorded_payer: channel.config.payer,
2183
- connected_payer: address
2184
- }
2185
- );
2186
- }
2187
- async function readX402ChannelOnChain(args) {
2188
- const { channel } = args;
2189
- const clients = args.clients ?? /* @__PURE__ */ new Map();
2190
- let state;
2191
- let error;
2192
- try {
2193
- state = await readChannelState(channel, args.configuredNetwork, clients, "report");
2194
- } catch (err) {
2195
- error = err instanceof DvmError ? err : new DvmError(
2196
- "x402_chain_read_failed",
2197
- `Reading the x402 channel with ${channel.endpoint} on ${channel.network} failed: ${redactUrlsInText(err instanceof Error ? err.message : String(err))}`
2198
- );
2199
- }
2200
- let status = state ? classifyX402ChannelState(state) : "unreadable";
2201
- if (state && status === "unconfirmed") {
2202
- const refunds = await readChannelRefundNonce(channel, args.configuredNetwork, clients).catch(
2203
- () => 0n
2204
- );
2205
- if (refunds > 0n) status = "closed";
2206
- }
2207
- const accounted = status === "unconfirmed" ? void 0 : state;
2208
- const stored = accounted ? void 0 : await storedChannelBalance(channel.channelId);
2209
- const depositMicro = accounted ? Number(accounted.balance) : stored?.balanceMicro;
2210
- return {
2211
- status,
2212
- channelId: channel.channelId,
2213
- ...depositMicro !== void 0 ? { depositMicro } : {},
2214
- ...state ? {
2215
- settledMicro: Number(state.totalClaimed),
2216
- ...depositMicro !== void 0 ? { uncommittedMicro: Math.max(depositMicro - Number(state.totalClaimed), 0) } : {},
2217
- pendingWithdrawalMicro: Number(state.pendingWithdrawal)
2218
- } : {},
2219
- ...depositMicro !== void 0 && stored?.unreconciledAt !== void 0 ? { balanceUnreconciledAt: stored.unreconciledAt } : {},
2220
- ...error ? { error } : {}
2221
- };
2222
- }
2223
- function x402ChannelControlledBy(channel, address) {
2224
- if (!address) return false;
2225
- return channel.config.payer.toLowerCase() === address.toLowerCase();
2226
- }
2227
- async function storedChannelBalance(channelId) {
2228
- try {
2229
- const balance = (await new DvmX402ChannelStorage().get(channelId))?.balance;
2230
- const unreconciledAt = x402ChannelBalanceUnreconciledAt(channelId);
2231
- return {
2232
- ...balance !== void 0 ? { balanceMicro: Number(balance) } : {},
2233
- ...unreconciledAt !== void 0 ? { unreconciledAt } : {}
2234
- };
2235
- } catch {
2236
- return void 0;
2237
- }
2238
- }
2239
- function classifyX402ChannelState(state) {
2240
- if (state.pendingWithdrawal > 0n) return "closing";
2241
- if (state.balance > 0n) return "open";
2242
- return state.totalClaimed > 0n ? "closed" : "unconfirmed";
2243
- }
2244
- async function resolveChannelRead(channel, configuredNetwork, clients, posture) {
2245
- const spec = x402NetworkByCaip2(channel.network);
2246
- if (!spec) {
2247
- throw new DvmError(
2248
- "x402_unsupported_network",
2249
- `The channel with ${channel.endpoint} is recorded on ${channel.network}, a chain this rail can't read.`,
2250
- posture === "guard" ? `${x402SupportedNetworksHint()} The key stays connected: with no way to read that channel, there is no way to show it is empty.` : `${x402SupportedNetworksHint()} The local channel record is kept: with no way to read that chain, there is no way to show what the contract holds for it.`,
2251
- { channel_id: channel.channelId, endpoint: channel.endpoint, network: channel.network }
2252
- );
2253
- }
2254
- const chains = await import("./chains-PINFXYUE.js");
2255
- const { createPublicClient: createPublicClient2, http: http2 } = await import("./_esm-M2HUAA3B.js");
2256
- const bundled = chains[spec.viemChain]?.rpcUrls?.default.http[0];
2257
- const { url, source, overrideOutOfScope } = resolveX402ChannelRpc(
2258
- channel.network,
2259
- configuredNetwork,
2260
- bundled
2261
- );
2262
- let client = clients.get(channel.network);
2263
- if (!client) {
2264
- const transportOptions = resolveRpcHttpTransportOptions(
2265
- source,
2266
- process.env.DVM_X402_RPC_HEADERS_JSON
2267
- );
2268
- client = createPublicClient2({
2269
- chain: chains[spec.viemChain],
2270
- transport: transportOptions ? http2(url, transportOptions) : http2(url)
2271
- });
2272
- clients.set(channel.network, client);
2273
- }
2274
- return { client, label: spec.label, url, source, overrideOutOfScope };
2275
- }
2276
- async function readChannelState(channel, configuredNetwork, clients, posture) {
2277
- const read = await resolveChannelRead(channel, configuredNetwork, clients, posture);
2278
- let onchain;
2279
- let pending;
2280
- try {
2281
- [onchain, pending] = await Promise.all([
2282
- read.client.readContract({
2283
- address: BATCH_SETTLEMENT_ADDRESS,
2284
- abi: X402_BATCH_CHANNEL_ABI,
2285
- functionName: "channels",
2286
- args: [channel.channelId]
2287
- }),
2288
- read.client.readContract({
2289
- address: BATCH_SETTLEMENT_ADDRESS,
2290
- abi: X402_BATCH_CHANNEL_ABI,
2291
- functionName: "pendingWithdrawals",
2292
- args: [channel.channelId]
2293
- })
2294
- ]);
2295
- } catch (err) {
2296
- throw rpcError(err, channel, read, posture);
2297
- }
2298
- await new DvmX402ChannelStorage().reconcileChainState(channel.channelId, {
2299
- balance: onchain[0].toString(),
2300
- totalClaimed: BigInt(onchain[1]).toString()
2301
- }).catch(() => void 0);
2302
- return {
2303
- balance: onchain[0],
2304
- totalClaimed: BigInt(onchain[1]),
2305
- pendingWithdrawal: pending[0]
2306
- };
2307
- }
2308
- async function readChannelRefundNonce(channel, configuredNetwork, clients) {
2309
- const read = await resolveChannelRead(channel, configuredNetwork, clients, "report");
2310
- try {
2311
- return await read.client.readContract({
2312
- address: BATCH_SETTLEMENT_ADDRESS,
2313
- abi: X402_BATCH_CHANNEL_ABI,
2314
- functionName: "refundNonce",
2315
- args: [channel.channelId]
2316
- });
2317
- } catch (err) {
2318
- throw rpcError(err, channel, read, "report");
2319
- }
2320
- }
2321
- function rpcError(err, channel, read, posture) {
2322
- const { label, url, source, overrideOutOfScope } = read;
2323
- const cause = redactUrlsInText(err instanceof Error ? err.message : String(err));
2324
- const opening = posture === "guard" ? "The x402 wallet is untouched. " : "Nothing was read or changed. ";
2325
- const closing = posture === "guard" ? " then retry \u2014 until the channel reads as empty the key stays connected." : " then re-run 'dvm wallet balance'. The local channel record is kept until the chain can be read, because it is the only route back to any collateral the contract does hold.";
2326
- const scopeClause = overrideOutOfScope ? `This channel is on ${label}, not the chain the wallet is pinned to, so DVM_X402_RPC_URL did not apply to it \u2014 it stays scoped to the pinned chain, because the settlement contract shares one address across chains and a cross-chain read would answer "empty" for a channel that isn't. Verify connectivity to ${label}'s bundled endpoint${url ? ` (${redactUrl(url)})` : ""},` : `Verify connectivity to ${label}'s bundled endpoint${url ? ` (${redactUrl(url)})` : ""}, or send the read somewhere else with DVM_X402_RPC_URL,`;
2327
- const diagnosis = source === "override" ? `DVM_X402_RPC_URL sent this read to ${redactUrl(url ?? "")}. Correct it, or unset it to fall back to ${label}'s bundled endpoint,` : scopeClause;
2328
- return new DvmError(
2329
- "x402_rpc_error",
2330
- `Reading the x402 channel with ${channel.endpoint} on ${label} failed: ${cause}`,
2331
- `${opening}${diagnosis}${closing}`,
2332
- { channel_id: channel.channelId, endpoint: channel.endpoint, network: channel.network }
2333
- );
2334
- }
2335
- function intentClause(intent) {
2336
- return intent === "replace" ? "retry the replacement" : "retry 'dvm wallet x402-disconnect'";
2337
- }
2338
-
2339
- export {
2340
- BATCH_SETTLEMENT_ADDRESS,
2341
- computeChannelId,
2342
- readChannelBalanceAndTotalClaimed,
2343
- BatchSettlementEvmScheme,
2344
- toClientEvmSigner,
2345
- X402_BATCH_CHANNEL_ABI,
2346
- resolveX402ChannelRpc,
2347
- assertX402WalletIdle,
2348
- assertX402ChannelPayer,
2349
- readX402ChannelOnChain,
2350
- x402ChannelControlledBy
2351
- };