@payai/x402-evm 2.4.0 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/dist/cjs/batch-settlement/client/file-storage.d.ts +47 -0
  2. package/dist/cjs/batch-settlement/client/file-storage.js +116 -0
  3. package/dist/cjs/batch-settlement/client/file-storage.js.map +1 -0
  4. package/dist/cjs/batch-settlement/client/index.d.ts +111 -0
  5. package/dist/cjs/batch-settlement/client/index.js +1565 -0
  6. package/dist/cjs/batch-settlement/client/index.js.map +1 -0
  7. package/dist/cjs/batch-settlement/facilitator/index.d.ts +71 -0
  8. package/dist/cjs/batch-settlement/facilitator/index.js +2032 -0
  9. package/dist/cjs/batch-settlement/facilitator/index.js.map +1 -0
  10. package/dist/cjs/batch-settlement/server/file-storage.d.ts +53 -0
  11. package/dist/cjs/batch-settlement/server/file-storage.js +181 -0
  12. package/dist/cjs/batch-settlement/server/file-storage.js.map +1 -0
  13. package/dist/cjs/batch-settlement/server/index.d.ts +491 -0
  14. package/dist/cjs/batch-settlement/server/index.js +1960 -0
  15. package/dist/cjs/batch-settlement/server/index.js.map +1 -0
  16. package/dist/cjs/batch-settlement/server/redis-storage.d.ts +87 -0
  17. package/dist/cjs/batch-settlement/server/redis-storage.js +181 -0
  18. package/dist/cjs/batch-settlement/server/redis-storage.js.map +1 -0
  19. package/dist/cjs/exact/client/index.d.ts +6 -4
  20. package/dist/cjs/exact/client/index.js +7 -5
  21. package/dist/cjs/exact/client/index.js.map +1 -1
  22. package/dist/cjs/exact/facilitator/index.d.ts +16 -9
  23. package/dist/cjs/exact/facilitator/index.js +56 -9
  24. package/dist/cjs/exact/facilitator/index.js.map +1 -1
  25. package/dist/cjs/exact/server/index.d.ts +0 -8
  26. package/dist/cjs/exact/server/index.js +53 -19
  27. package/dist/cjs/exact/server/index.js.map +1 -1
  28. package/dist/cjs/exact/v1/client/index.d.ts +2 -1
  29. package/dist/cjs/exact/v1/client/index.js.map +1 -1
  30. package/dist/cjs/exact/v1/facilitator/index.d.ts +11 -5
  31. package/dist/cjs/exact/v1/facilitator/index.js +16 -2
  32. package/dist/cjs/exact/v1/facilitator/index.js.map +1 -1
  33. package/dist/cjs/index.d.ts +113 -7
  34. package/dist/cjs/index.js +1353 -5
  35. package/dist/cjs/index.js.map +1 -1
  36. package/dist/{esm/permit2-CyZxwngN.d.mts → cjs/permit2-DhJRUcgY.d.ts} +1 -13
  37. package/dist/cjs/rpc-DULZzRne.d.ts +13 -0
  38. package/dist/cjs/scheme-CvkPJXBD.d.ts +307 -0
  39. package/dist/{esm/scheme-DCR7hsa3.d.mts → cjs/scheme-DTQFE9xp.d.ts} +2 -2
  40. package/dist/{esm/signer-D912R4mq.d.mts → cjs/signer-tYS6Y46X.d.ts} +3 -0
  41. package/dist/cjs/storage-6W5MO46W.d.ts +50 -0
  42. package/dist/cjs/storage-Bl6aD0Xg.d.ts +81 -0
  43. package/dist/cjs/types-CF8P2-NM.d.ts +180 -0
  44. package/dist/cjs/upto/client/index.d.ts +5 -3
  45. package/dist/cjs/upto/client/index.js +7 -5
  46. package/dist/cjs/upto/client/index.js.map +1 -1
  47. package/dist/cjs/upto/facilitator/index.d.ts +2 -1
  48. package/dist/cjs/upto/facilitator/index.js +2 -1
  49. package/dist/cjs/upto/facilitator/index.js.map +1 -1
  50. package/dist/cjs/upto/server/index.d.ts +0 -8
  51. package/dist/cjs/upto/server/index.js +51 -19
  52. package/dist/cjs/upto/server/index.js.map +1 -1
  53. package/dist/cjs/v1/index.d.ts +2 -1
  54. package/dist/cjs/v1/index.js.map +1 -1
  55. package/dist/esm/batch-settlement/client/file-storage.d.mts +47 -0
  56. package/dist/esm/batch-settlement/client/file-storage.mjs +63 -0
  57. package/dist/esm/batch-settlement/client/file-storage.mjs.map +1 -0
  58. package/dist/esm/batch-settlement/client/index.d.mts +111 -0
  59. package/dist/esm/batch-settlement/client/index.mjs +59 -0
  60. package/dist/esm/batch-settlement/client/index.mjs.map +1 -0
  61. package/dist/esm/batch-settlement/facilitator/index.d.mts +71 -0
  62. package/dist/esm/batch-settlement/facilitator/index.mjs +1235 -0
  63. package/dist/esm/batch-settlement/facilitator/index.mjs.map +1 -0
  64. package/dist/esm/batch-settlement/server/file-storage.d.mts +53 -0
  65. package/dist/esm/batch-settlement/server/file-storage.mjs +128 -0
  66. package/dist/esm/batch-settlement/server/file-storage.mjs.map +1 -0
  67. package/dist/esm/batch-settlement/server/index.d.mts +491 -0
  68. package/dist/esm/batch-settlement/server/index.mjs +1645 -0
  69. package/dist/esm/batch-settlement/server/index.mjs.map +1 -0
  70. package/dist/esm/batch-settlement/server/redis-storage.d.mts +87 -0
  71. package/dist/esm/batch-settlement/server/redis-storage.mjs +156 -0
  72. package/dist/esm/batch-settlement/server/redis-storage.mjs.map +1 -0
  73. package/dist/esm/chunk-2EUQTNJO.mjs +38 -0
  74. package/dist/esm/chunk-2EUQTNJO.mjs.map +1 -0
  75. package/dist/esm/chunk-53USC5VE.mjs +47 -0
  76. package/dist/esm/chunk-53USC5VE.mjs.map +1 -0
  77. package/dist/esm/{chunk-GJ57SZGI.mjs → chunk-6WQOGWBE.mjs} +7 -5
  78. package/dist/esm/{chunk-GJ57SZGI.mjs.map → chunk-6WQOGWBE.mjs.map} +1 -1
  79. package/dist/esm/{chunk-NSFLAANF.mjs → chunk-BTYNCDNS.mjs} +51 -2
  80. package/dist/esm/chunk-BTYNCDNS.mjs.map +1 -0
  81. package/dist/esm/{chunk-RYT6M3PA.mjs → chunk-CSQS7ZON.mjs} +47 -7
  82. package/dist/esm/chunk-CSQS7ZON.mjs.map +1 -0
  83. package/dist/esm/chunk-GD4MKCN7.mjs +57 -0
  84. package/dist/esm/chunk-GD4MKCN7.mjs.map +1 -0
  85. package/dist/esm/chunk-HYABYUBD.mjs +432 -0
  86. package/dist/esm/chunk-HYABYUBD.mjs.map +1 -0
  87. package/dist/esm/chunk-IN5YIT5C.mjs +159 -0
  88. package/dist/esm/chunk-IN5YIT5C.mjs.map +1 -0
  89. package/dist/esm/{chunk-JII456TS.mjs → chunk-JK7SLLF7.mjs} +1 -1
  90. package/dist/esm/chunk-JK7SLLF7.mjs.map +1 -0
  91. package/dist/esm/{chunk-C4ZQMS77.mjs → chunk-MACPBXCT.mjs} +2 -216
  92. package/dist/esm/chunk-MACPBXCT.mjs.map +1 -0
  93. package/dist/esm/chunk-NKYVYGRA.mjs +911 -0
  94. package/dist/esm/chunk-NKYVYGRA.mjs.map +1 -0
  95. package/dist/esm/{chunk-D6RXZXOS.mjs → chunk-R7I3RZFF.mjs} +10 -6
  96. package/dist/esm/{chunk-D6RXZXOS.mjs.map → chunk-R7I3RZFF.mjs.map} +1 -1
  97. package/dist/esm/{chunk-CRT6YNY5.mjs → chunk-RWLVVO3B.mjs} +21 -61
  98. package/dist/esm/chunk-RWLVVO3B.mjs.map +1 -0
  99. package/dist/esm/chunk-TGFAVNUD.mjs +111 -0
  100. package/dist/esm/chunk-TGFAVNUD.mjs.map +1 -0
  101. package/dist/esm/chunk-TW7Z65AO.mjs +34 -0
  102. package/dist/esm/chunk-TW7Z65AO.mjs.map +1 -0
  103. package/dist/esm/chunk-U4HCGTLU.mjs +35 -0
  104. package/dist/esm/chunk-U4HCGTLU.mjs.map +1 -0
  105. package/dist/esm/chunk-VS3RYAYE.mjs +80 -0
  106. package/dist/esm/chunk-VS3RYAYE.mjs.map +1 -0
  107. package/dist/esm/chunk-W6ON4LG2.mjs +39 -0
  108. package/dist/esm/chunk-W6ON4LG2.mjs.map +1 -0
  109. package/dist/esm/{chunk-WKBC5YMI.mjs → chunk-YMQCTKDU.mjs} +23 -55
  110. package/dist/esm/chunk-YMQCTKDU.mjs.map +1 -0
  111. package/dist/esm/exact/client/index.d.mts +6 -4
  112. package/dist/esm/exact/client/index.mjs +10 -5
  113. package/dist/esm/exact/facilitator/index.d.mts +16 -9
  114. package/dist/esm/exact/facilitator/index.mjs +39 -16
  115. package/dist/esm/exact/facilitator/index.mjs.map +1 -1
  116. package/dist/esm/exact/server/index.d.mts +0 -8
  117. package/dist/esm/exact/server/index.mjs +3 -19
  118. package/dist/esm/exact/server/index.mjs.map +1 -1
  119. package/dist/esm/exact/v1/client/index.d.mts +2 -1
  120. package/dist/esm/exact/v1/client/index.mjs +5 -2
  121. package/dist/esm/exact/v1/facilitator/index.d.mts +11 -5
  122. package/dist/esm/exact/v1/facilitator/index.mjs +5 -2
  123. package/dist/esm/index.d.mts +113 -7
  124. package/dist/esm/index.mjs +53 -7
  125. package/dist/esm/index.mjs.map +1 -1
  126. package/dist/esm/permit2-DhJRUcgY.d.mts +729 -0
  127. package/dist/esm/rpc-DULZzRne.d.mts +13 -0
  128. package/dist/esm/scheme-DtbSS4Fk.d.mts +307 -0
  129. package/dist/esm/scheme-gtqAIYPJ.d.mts +47 -0
  130. package/dist/esm/signer-tYS6Y46X.d.mts +170 -0
  131. package/dist/esm/storage-6W5MO46W.d.mts +50 -0
  132. package/dist/esm/storage-sZ1CDS4P.d.mts +81 -0
  133. package/dist/esm/types-CF8P2-NM.d.mts +180 -0
  134. package/dist/esm/upto/client/index.d.mts +5 -3
  135. package/dist/esm/upto/client/index.mjs +9 -4
  136. package/dist/esm/upto/facilitator/index.d.mts +2 -1
  137. package/dist/esm/upto/facilitator/index.mjs +17 -9
  138. package/dist/esm/upto/facilitator/index.mjs.map +1 -1
  139. package/dist/esm/upto/server/index.d.mts +0 -8
  140. package/dist/esm/upto/server/index.mjs +3 -19
  141. package/dist/esm/upto/server/index.mjs.map +1 -1
  142. package/dist/esm/v1/index.d.mts +2 -1
  143. package/dist/esm/v1/index.mjs +5 -2
  144. package/package.json +5 -5
  145. package/dist/esm/chunk-C4ZQMS77.mjs.map +0 -1
  146. package/dist/esm/chunk-CRT6YNY5.mjs.map +0 -1
  147. package/dist/esm/chunk-JII456TS.mjs.map +0 -1
  148. package/dist/esm/chunk-NSFLAANF.mjs.map +0 -1
  149. package/dist/esm/chunk-RYT6M3PA.mjs.map +0 -1
  150. package/dist/esm/chunk-WKBC5YMI.mjs.map +0 -1
@@ -0,0 +1,1645 @@
1
+ import {
2
+ signClaimBatch,
3
+ signRefund,
4
+ validateChannelConfig
5
+ } from "../../chunk-IN5YIT5C.mjs";
6
+ import {
7
+ BATCH_SETTLEMENT_SCHEME,
8
+ ErrChannelBusy,
9
+ ErrChannelIdMismatch,
10
+ ErrChargeExceedsSignedCumulative,
11
+ ErrCumulativeAmountBelowClaimed,
12
+ ErrCumulativeAmountMismatch,
13
+ ErrCumulativeExceedsBalance,
14
+ ErrInvalidVoucherSignature,
15
+ ErrMissingChannel,
16
+ ErrRefundAmountInvalid,
17
+ ErrRefundNoBalance,
18
+ ErrRefundPayload,
19
+ MIN_WITHDRAW_DELAY,
20
+ computeChannelId,
21
+ getBatchSettlementEip712Domain,
22
+ voucherTypes
23
+ } from "../../chunk-HYABYUBD.mjs";
24
+ import {
25
+ getDefaultAsset
26
+ } from "../../chunk-BTYNCDNS.mjs";
27
+ import {
28
+ isBatchSettlementDepositPayload,
29
+ isBatchSettlementRefundPayload,
30
+ isBatchSettlementVoucherPayload
31
+ } from "../../chunk-U4HCGTLU.mjs";
32
+ import "../../chunk-VS3RYAYE.mjs";
33
+ import {
34
+ createNonce,
35
+ getEvmChainId
36
+ } from "../../chunk-TW7Z65AO.mjs";
37
+
38
+ // src/batch-settlement/server/scheme.ts
39
+ import { convertToTokenAmount, numberToDecimalString } from "@payai/x402/utils";
40
+ import { getAddress as getAddress2 } from "viem";
41
+
42
+ // src/batch-settlement/server/channelManager.ts
43
+ var AUTO_JOB_PRIORITY = ["claim", "settle", "refund"];
44
+ function formatFacilitatorFailure(operation, response) {
45
+ return `${operation} failed: ${response.errorReason ?? "unknown"} \u2014 ${response.errorMessage ?? ""}`;
46
+ }
47
+ function hasLivePendingRequest(channel, now = Date.now()) {
48
+ return channel.pendingRequest !== void 0 && channel.pendingRequest.expiresAt > now;
49
+ }
50
+ var BatchSettlementChannelManager = class {
51
+ /**
52
+ * Creates a new channel manager.
53
+ *
54
+ * @param config - Manager configuration: scheme, facilitator, receiver, token, network.
55
+ */
56
+ constructor(config) {
57
+ this.timers = {};
58
+ this.lastClaimTime = 0;
59
+ this.lastSettleTime = 0;
60
+ this.pendingSettle = false;
61
+ this.running = false;
62
+ this.pendingJobs = /* @__PURE__ */ new Set();
63
+ this.drainingJobs = false;
64
+ this.autoSettleConfig = {};
65
+ this.scheme = config.scheme;
66
+ this.facilitator = config.facilitator;
67
+ this.receiver = config.receiver;
68
+ this.token = config.token;
69
+ this.network = config.network;
70
+ }
71
+ /**
72
+ * Collects claimable vouchers and submits them in batches to the facilitator via `claim()`.
73
+ *
74
+ * @param opts - Optional claim execution and target selection options.
75
+ * @param opts.maxClaimsPerBatch - Max vouchers per facilitator `claim` batch.
76
+ * @param opts.idleSecs - When set, only include channels idle for at least this many seconds.
77
+ * @param opts.selectClaimChannels - Optional selector for choosing channels before claimability checks.
78
+ * @returns Array of claim results (one per batch).
79
+ */
80
+ async claim(opts) {
81
+ const channels = await this.selectClaimTargets(opts);
82
+ return this.claimFromChannels(channels, {
83
+ maxClaimsPerBatch: opts?.maxClaimsPerBatch ?? 100,
84
+ ...opts?.idleSecs !== void 0 ? { idleSecs: opts.idleSecs } : {}
85
+ });
86
+ }
87
+ /**
88
+ * Transfers claimed (but unsettled) funds to the receiver by calling `settle(receiver, token)`.
89
+ *
90
+ * @returns Settle result with the transaction hash.
91
+ */
92
+ async settle() {
93
+ const paymentPayload = this.buildSettlePaymentPayload();
94
+ const requirements = this.buildPaymentRequirements();
95
+ const response = await this.facilitator.settle(paymentPayload, requirements);
96
+ if (!response.success) {
97
+ throw new Error(formatFacilitatorFailure("Settle", response));
98
+ }
99
+ this.pendingSettle = false;
100
+ return { transaction: response.transaction };
101
+ }
102
+ /**
103
+ * Convenience: claims all eligible vouchers then settles in one call.
104
+ *
105
+ * @param opts - Optional claim execution and target selection options.
106
+ * @param opts.maxClaimsPerBatch - Max vouchers per claim batch before settling.
107
+ * @param opts.idleSecs - When set, only include channels idle for at least this many seconds.
108
+ * @param opts.selectClaimChannels - Optional selector for choosing channels before claimability checks.
109
+ * @returns Combined claim and settle results.
110
+ */
111
+ async claimAndSettle(opts) {
112
+ const claims = await this.claim(opts);
113
+ let settleResult;
114
+ if (claims.length > 0) {
115
+ settleResult = await this.settle();
116
+ }
117
+ return { claims, settle: settleResult };
118
+ }
119
+ /**
120
+ * Initiates cooperative refunds for one or more channels.
121
+ *
122
+ * @param channelIds - Specific channels to refund; defaults to all sessions.
123
+ * @returns One result per successfully refunded channel.
124
+ */
125
+ async refund(channelIds) {
126
+ const storage = this.scheme.getStorage();
127
+ const channels = await storage.list();
128
+ const now = Date.now();
129
+ const targets = (channelIds ? channels.filter(
130
+ (s) => channelIds.some((id) => id.toLowerCase() === s.channelId.toLowerCase())
131
+ ) : channels).filter((channel) => !hasLivePendingRequest(channel, now));
132
+ if (targets.length === 0) {
133
+ return [];
134
+ }
135
+ return this.refundChannels(targets);
136
+ }
137
+ /**
138
+ * Refunds idle channels with non-zero balances.
139
+ *
140
+ * @param opts - Idle refund options.
141
+ * @param opts.idleSecs - Minimum seconds since the last request.
142
+ * @returns One result per successfully refunded channel.
143
+ */
144
+ async refundIdleChannels(opts) {
145
+ const channels = await this.getIdleChannelsForRefund(opts.idleSecs);
146
+ return this.refundChannels(channels);
147
+ }
148
+ /**
149
+ * Collects vouchers that are eligible for onchain claiming.
150
+ *
151
+ * A voucher is claimable when its `chargedCumulativeAmount` exceeds what has already
152
+ * been claimed onchain. An optional idle filter skips sessions that received a
153
+ * request within the last `idleSecs` seconds.
154
+ *
155
+ * @param opts - Optional filtering: `idleSecs` to only return idle channels.
156
+ * @param opts.idleSecs - Minimum seconds since last request for a channel to be included.
157
+ * @returns Array of {@link BatchSettlementVoucherClaim} entries for batch submission.
158
+ */
159
+ async getClaimableVouchers(opts) {
160
+ const channels = await this.scheme.getStorage().list();
161
+ return this.getClaimableVouchersFromChannels(channels, opts);
162
+ }
163
+ /**
164
+ * Returns channels that have a pending payer-initiated withdrawal.
165
+ *
166
+ * @returns All stored channel records with `withdrawRequestedAt` set.
167
+ */
168
+ async getWithdrawalPendingSessions() {
169
+ const channels = await this.scheme.getStorage().list();
170
+ return channels.filter((s) => s.withdrawRequestedAt > 0);
171
+ }
172
+ /**
173
+ * Starts auto-settlement jobs for configured claim, settle, and refund intervals.
174
+ *
175
+ * @param config - Auto-settlement policy configuration.
176
+ */
177
+ start(config = {}) {
178
+ if (this.running) {
179
+ return;
180
+ }
181
+ const now = Date.now();
182
+ this.lastClaimTime = now;
183
+ this.lastSettleTime = now;
184
+ this.running = true;
185
+ this.autoSettleConfig = config;
186
+ this.startAutoTimer("claim", config.claimIntervalSecs);
187
+ this.startAutoTimer("settle", config.settleIntervalSecs);
188
+ this.startAutoTimer("refund", config.refundIntervalSecs);
189
+ }
190
+ /**
191
+ * Stops the auto-settlement loop.
192
+ *
193
+ * @param opts - Stop options.
194
+ * @param opts.flush - When true, run `claimAndSettle` before stopping.
195
+ * @returns Resolves when the loop is stopped (and flush work completes, if requested).
196
+ */
197
+ async stop(opts) {
198
+ this.running = false;
199
+ for (const timer of Object.values(this.timers)) {
200
+ clearInterval(timer);
201
+ }
202
+ this.timers = {};
203
+ this.pendingJobs.clear();
204
+ if (opts?.flush) {
205
+ await this.claimAndSettle({
206
+ maxClaimsPerBatch: this.autoSettleConfig.maxClaimsPerBatch,
207
+ selectClaimChannels: this.autoSettleConfig.selectClaimChannels
208
+ });
209
+ }
210
+ }
211
+ /**
212
+ * Refunds a single channel and removes it from storage after success.
213
+ *
214
+ * @param target - Channel to refund.
215
+ * @returns Successful refund transaction.
216
+ */
217
+ async refundChannel(target) {
218
+ const authorizerSigner = this.scheme.getReceiverAuthorizerSigner();
219
+ const claims = this.buildRefundClaims(target);
220
+ const refundAmount = (BigInt(target.balance) - BigInt(target.chargedCumulativeAmount)).toString();
221
+ const nonce = String(target.refundNonce ?? 0);
222
+ const refundAuthorizerSignature = authorizerSigner ? await signRefund(
223
+ authorizerSigner,
224
+ target.channelId,
225
+ refundAmount,
226
+ nonce,
227
+ this.network
228
+ ) : void 0;
229
+ const claimAuthorizerSignature = authorizerSigner && claims.length > 0 ? await signClaimBatch(authorizerSigner, claims, this.network) : void 0;
230
+ const paymentPayload = {
231
+ x402Version: 2,
232
+ accepted: this.buildPaymentRequirements(),
233
+ payload: {
234
+ type: "refund",
235
+ channelConfig: target.channelConfig,
236
+ voucher: {
237
+ channelId: target.channelId,
238
+ maxClaimableAmount: target.signedMaxClaimable,
239
+ signature: target.signature
240
+ },
241
+ amount: refundAmount,
242
+ refundNonce: nonce,
243
+ claims,
244
+ ...refundAuthorizerSignature ? { refundAuthorizerSignature } : {},
245
+ ...claimAuthorizerSignature ? { claimAuthorizerSignature } : {}
246
+ }
247
+ };
248
+ const response = await this.facilitator.settle(paymentPayload, this.buildPaymentRequirements());
249
+ if (!response.success) {
250
+ throw new Error(formatFacilitatorFailure("Refund", response));
251
+ }
252
+ await this.scheme.getStorage().updateChannel(
253
+ target.channelId,
254
+ (current) => current && !hasLivePendingRequest(current) ? void 0 : current
255
+ );
256
+ return {
257
+ channel: target.channelId,
258
+ transaction: response.transaction
259
+ };
260
+ }
261
+ /**
262
+ * Starts a recurring timer for one auto job.
263
+ *
264
+ * @param job - Job to enqueue when the interval fires.
265
+ * @param intervalSecs - Timer interval in seconds.
266
+ */
267
+ startAutoTimer(job, intervalSecs) {
268
+ if (intervalSecs === void 0) {
269
+ return;
270
+ }
271
+ this.timers[job] = setInterval(() => {
272
+ this.enqueueJob(job);
273
+ }, intervalSecs * 1e3);
274
+ }
275
+ /**
276
+ * Adds an auto job to the coalescing queue.
277
+ *
278
+ * @param job - Job to run.
279
+ */
280
+ enqueueJob(job) {
281
+ if (!this.running) {
282
+ return;
283
+ }
284
+ this.pendingJobs.add(job);
285
+ if (!this.drainingJobs) {
286
+ void this.drainJobs();
287
+ }
288
+ }
289
+ /**
290
+ * Drains queued auto jobs in priority order.
291
+ */
292
+ async drainJobs() {
293
+ if (this.drainingJobs) {
294
+ return;
295
+ }
296
+ this.drainingJobs = true;
297
+ try {
298
+ while (this.running && this.pendingJobs.size > 0) {
299
+ const job = this.nextPendingJob();
300
+ if (!job) {
301
+ return;
302
+ }
303
+ this.pendingJobs.delete(job);
304
+ await this.runAutoJob(job);
305
+ }
306
+ } finally {
307
+ this.drainingJobs = false;
308
+ }
309
+ }
310
+ /**
311
+ * Returns the highest-priority queued auto job.
312
+ *
313
+ * @returns Next job to run.
314
+ */
315
+ nextPendingJob() {
316
+ return AUTO_JOB_PRIORITY.find((job) => this.pendingJobs.has(job));
317
+ }
318
+ /**
319
+ * Runs one auto job.
320
+ *
321
+ * @param job - Job to run.
322
+ */
323
+ async runAutoJob(job) {
324
+ switch (job) {
325
+ case "claim":
326
+ await this.runClaimJob();
327
+ return;
328
+ case "settle":
329
+ await this.runSettleJob();
330
+ return;
331
+ case "refund":
332
+ await this.runRefundJob();
333
+ return;
334
+ }
335
+ }
336
+ /**
337
+ * Runs the claim auto job.
338
+ */
339
+ async runClaimJob() {
340
+ const cfg = this.autoSettleConfig;
341
+ try {
342
+ const targets = await this.selectClaimTargets({
343
+ selectClaimChannels: cfg.selectClaimChannels
344
+ });
345
+ const results = await this.claimFromChannels(targets, {
346
+ maxClaimsPerBatch: cfg.maxClaimsPerBatch ?? 100
347
+ });
348
+ this.lastClaimTime = Date.now();
349
+ for (const result of results) {
350
+ cfg.onClaim?.(result);
351
+ }
352
+ } catch (err) {
353
+ cfg.onError?.(err);
354
+ }
355
+ }
356
+ /**
357
+ * Runs the settlement auto job.
358
+ */
359
+ async runSettleJob() {
360
+ const cfg = this.autoSettleConfig;
361
+ const context = this.buildAutoSettlementContext(Date.now());
362
+ if (!context.pendingSettle) {
363
+ return;
364
+ }
365
+ try {
366
+ if (cfg.shouldSettle && !await cfg.shouldSettle(context)) {
367
+ return;
368
+ }
369
+ const result = await this.settle();
370
+ this.lastSettleTime = Date.now();
371
+ cfg.onSettle?.(result);
372
+ } catch (err) {
373
+ cfg.onError?.(err);
374
+ }
375
+ }
376
+ /**
377
+ * Runs the refund auto job.
378
+ */
379
+ async runRefundJob() {
380
+ const cfg = this.autoSettleConfig;
381
+ if (!cfg.selectRefundChannels) {
382
+ return;
383
+ }
384
+ try {
385
+ const context = this.buildAutoSettlementContext(Date.now());
386
+ const channels = await this.scheme.getStorage().list();
387
+ const targets = await cfg.selectRefundChannels(channels, context);
388
+ for (const result of await this.refundChannels(targets)) {
389
+ cfg.onRefund?.(result);
390
+ }
391
+ } catch (err) {
392
+ cfg.onError?.(err);
393
+ }
394
+ }
395
+ /**
396
+ * Claims vouchers from a provided channel snapshot.
397
+ *
398
+ * @param channels - Channels to inspect for claimable vouchers.
399
+ * @param opts - Claim batching and filtering options.
400
+ * @param opts.maxClaimsPerBatch - Max vouchers per facilitator claim transaction.
401
+ * @param opts.idleSecs - Optional idle filter.
402
+ * @returns Claim results, one per submitted batch.
403
+ */
404
+ async claimFromChannels(channels, opts) {
405
+ const allClaims = this.getClaimableVouchersFromChannels(
406
+ channels,
407
+ opts.idleSecs !== void 0 ? { idleSecs: opts.idleSecs } : void 0
408
+ );
409
+ if (allClaims.length === 0) {
410
+ return [];
411
+ }
412
+ const results = [];
413
+ for (let i = 0; i < allClaims.length; i += opts.maxClaimsPerBatch) {
414
+ const batch = allClaims.slice(i, i + opts.maxClaimsPerBatch);
415
+ const result = await this.submitClaim(batch);
416
+ results.push(result);
417
+ await this.updateClaimedSessions(batch);
418
+ }
419
+ if (results.length > 0) {
420
+ this.pendingSettle = true;
421
+ }
422
+ return results;
423
+ }
424
+ /**
425
+ * Loads stored channels and applies the configured claim selector, if any.
426
+ *
427
+ * @param opts - Claim options containing an optional target selector.
428
+ * @returns The channel snapshot that should be inspected for claimable vouchers.
429
+ */
430
+ async selectClaimTargets(opts) {
431
+ const channels = await this.scheme.getStorage().list();
432
+ if (!opts?.selectClaimChannels) {
433
+ return channels;
434
+ }
435
+ const context = this.buildAutoSettlementContext(Date.now());
436
+ return opts.selectClaimChannels(channels, context);
437
+ }
438
+ /**
439
+ * Refunds each eligible channel independently.
440
+ *
441
+ * @param channels - Channels to refund.
442
+ * @returns Successful refund results.
443
+ */
444
+ async refundChannels(channels) {
445
+ const results = [];
446
+ for (const channel of channels) {
447
+ if (hasLivePendingRequest(channel)) {
448
+ continue;
449
+ }
450
+ results.push(await this.refundChannel(channel));
451
+ }
452
+ return results;
453
+ }
454
+ /**
455
+ * Builds an outstanding voucher claim for a refund payload.
456
+ *
457
+ * @param channel - Channel being refunded.
458
+ * @returns Claim payloads needed before refunding unclaimed balance.
459
+ */
460
+ buildRefundClaims(channel) {
461
+ if (BigInt(channel.chargedCumulativeAmount) <= BigInt(channel.totalClaimed)) {
462
+ return [];
463
+ }
464
+ return [
465
+ {
466
+ voucher: {
467
+ channel: channel.channelConfig,
468
+ maxClaimableAmount: channel.signedMaxClaimable
469
+ },
470
+ signature: channel.signature,
471
+ totalClaimed: channel.chargedCumulativeAmount
472
+ }
473
+ ];
474
+ }
475
+ /**
476
+ * Builds the policy context passed to interval hooks.
477
+ *
478
+ * @param now - Current wall-clock time in milliseconds.
479
+ * @returns Auto-settlement policy context.
480
+ */
481
+ buildAutoSettlementContext(now) {
482
+ return {
483
+ now,
484
+ lastClaimTime: this.lastClaimTime,
485
+ lastSettleTime: this.lastSettleTime,
486
+ pendingSettle: this.pendingSettle
487
+ };
488
+ }
489
+ /**
490
+ * Collects claimable vouchers from a provided channel snapshot.
491
+ *
492
+ * @param channels - Channels to inspect.
493
+ * @param opts - Optional idle filter.
494
+ * @param opts.idleSecs - Minimum seconds since last request.
495
+ * @returns Claimable voucher payloads.
496
+ */
497
+ getClaimableVouchersFromChannels(channels, opts) {
498
+ const now = Date.now();
499
+ const claims = [];
500
+ for (const c of channels) {
501
+ if (BigInt(c.chargedCumulativeAmount) <= BigInt(c.totalClaimed)) {
502
+ continue;
503
+ }
504
+ if (opts?.idleSecs !== void 0) {
505
+ const idleMs = now - c.lastRequestTimestamp;
506
+ if (idleMs < opts.idleSecs * 1e3) {
507
+ continue;
508
+ }
509
+ }
510
+ claims.push({
511
+ voucher: {
512
+ channel: c.channelConfig,
513
+ maxClaimableAmount: c.signedMaxClaimable
514
+ },
515
+ signature: c.signature,
516
+ totalClaimed: c.chargedCumulativeAmount
517
+ });
518
+ }
519
+ return claims;
520
+ }
521
+ /**
522
+ * Filters idle channels that can be cooperatively refunded.
523
+ *
524
+ * @param channels - Channels to inspect.
525
+ * @param idleSecs - Minimum seconds since the last request.
526
+ * @returns Idle refundable channels.
527
+ */
528
+ getIdleChannelsForRefundFromChannels(channels, idleSecs) {
529
+ const now = Date.now();
530
+ const idleMs = idleSecs * 1e3;
531
+ return channels.filter((c) => {
532
+ if (BigInt(c.balance) === 0n) return false;
533
+ if (hasLivePendingRequest(c, now)) return false;
534
+ return now - c.lastRequestTimestamp >= idleMs;
535
+ });
536
+ }
537
+ /**
538
+ * Returns channels that have been idle longer than `idleSecs` and still have
539
+ * a non-zero balance (candidates for cooperative refund).
540
+ *
541
+ * @param idleSecs - Minimum seconds since last request for a session to count as idle.
542
+ * @returns Channels meeting the idle and balance criteria.
543
+ */
544
+ async getIdleChannelsForRefund(idleSecs) {
545
+ const channels = await this.scheme.getStorage().list();
546
+ return this.getIdleChannelsForRefundFromChannels(channels, idleSecs);
547
+ }
548
+ /**
549
+ * Submits a batch of voucher claims to the facilitator.
550
+ *
551
+ * @param claims - Voucher claims to send in one `type: "claim"` payload.
552
+ * @returns Per-batch claim summary (count and transaction hash).
553
+ */
554
+ async submitClaim(claims) {
555
+ const authorizerSigner = this.scheme.getReceiverAuthorizerSigner();
556
+ const claimAuthorizerSignature = authorizerSigner ? await signClaimBatch(authorizerSigner, claims, this.network) : void 0;
557
+ const paymentPayload = {
558
+ x402Version: 2,
559
+ accepted: this.buildPaymentRequirements(),
560
+ payload: {
561
+ type: "claim",
562
+ claims,
563
+ ...claimAuthorizerSignature ? { claimAuthorizerSignature } : {}
564
+ }
565
+ };
566
+ const response = await this.facilitator.settle(
567
+ paymentPayload,
568
+ this.buildPaymentRequirements()
569
+ );
570
+ if (!response.success) {
571
+ throw new Error(formatFacilitatorFailure("Claim", response));
572
+ }
573
+ return { vouchers: claims.length, transaction: response.transaction };
574
+ }
575
+ /**
576
+ * Builds a settlement payment payload for `settle(receiver, token)`.
577
+ *
578
+ * @returns Payload with `type: "settle"` and receiver/token fields.
579
+ */
580
+ buildSettlePaymentPayload() {
581
+ return {
582
+ x402Version: 2,
583
+ accepted: this.buildPaymentRequirements(),
584
+ payload: {
585
+ type: "settle",
586
+ receiver: this.receiver,
587
+ token: this.token
588
+ }
589
+ };
590
+ }
591
+ /**
592
+ * Builds a minimal {@link PaymentRequirements} for channel manager operations.
593
+ *
594
+ * @returns Requirements describing batched operations for this manager.
595
+ */
596
+ buildPaymentRequirements() {
597
+ return {
598
+ scheme: BATCH_SETTLEMENT_SCHEME,
599
+ network: this.network,
600
+ asset: this.token,
601
+ amount: "0",
602
+ payTo: this.receiver,
603
+ maxTimeoutSeconds: 0,
604
+ extra: {}
605
+ };
606
+ }
607
+ /**
608
+ * Updates session records after a successful claim submission so that
609
+ * `getClaimableVouchers` no longer returns already-claimed vouchers.
610
+ *
611
+ * @param claims - Voucher claims that were included in the submitted settlement transaction.
612
+ */
613
+ async updateClaimedSessions(claims) {
614
+ const storage = this.scheme.getStorage();
615
+ for (const claim of claims) {
616
+ const channelId = computeChannelId(claim.voucher.channel, this.network);
617
+ const channel = await storage.get(channelId);
618
+ if (!channel) {
619
+ continue;
620
+ }
621
+ const claimedAmount = BigInt(claim.totalClaimed);
622
+ if (claimedAmount <= BigInt(channel.totalClaimed)) {
623
+ continue;
624
+ }
625
+ await storage.updateChannel(channelId, (current) => {
626
+ if (!current || claimedAmount <= BigInt(current.totalClaimed)) {
627
+ return current;
628
+ }
629
+ return {
630
+ ...current,
631
+ totalClaimed: claimedAmount.toString()
632
+ };
633
+ });
634
+ }
635
+ }
636
+ };
637
+
638
+ // src/batch-settlement/server/storage.ts
639
+ var InMemoryChannelStorage = class {
640
+ constructor() {
641
+ this.channels = /* @__PURE__ */ new Map();
642
+ this.channelLocks = /* @__PURE__ */ new Map();
643
+ }
644
+ /**
645
+ * Returns the channel record for a channel, if present.
646
+ *
647
+ * @param channelId - The channel identifier.
648
+ * @returns The channel record or undefined when not found.
649
+ */
650
+ async get(channelId) {
651
+ return this.channels.get(channelId.toLowerCase());
652
+ }
653
+ /**
654
+ * Lists all stored channel records.
655
+ *
656
+ * @returns All channel records in storage.
657
+ */
658
+ async list() {
659
+ return [...this.channels.values()];
660
+ }
661
+ /**
662
+ * Atomically inspects and mutates a channel record while holding a per-channel lock.
663
+ *
664
+ * @param channelId - The channel identifier.
665
+ * @param update - Mutation callback. Return `undefined` to delete, or `current` to leave unchanged.
666
+ * @returns The final stored channel and whether storage updated, stayed unchanged, or deleted.
667
+ */
668
+ async updateChannel(channelId, update) {
669
+ const key = channelId.toLowerCase();
670
+ return this.withChannelLock(key, async () => {
671
+ const current = this.channels.get(key);
672
+ const next = update(current);
673
+ if (next === current) {
674
+ return { channel: current, status: "unchanged" };
675
+ }
676
+ if (!next) {
677
+ this.channels.delete(key);
678
+ return { channel: void 0, status: current ? "deleted" : "unchanged" };
679
+ }
680
+ this.channels.set(key, next);
681
+ return { channel: next, status: "updated" };
682
+ });
683
+ }
684
+ /**
685
+ * Runs `fn` after any prior locked work for the same channel key has finished.
686
+ *
687
+ * @param key - Lowercased channel id used as the lock key.
688
+ * @param fn - Async work to run while holding the logical per-channel lock.
689
+ * @returns The resolved result of `fn`.
690
+ */
691
+ async withChannelLock(key, fn) {
692
+ const previous = this.channelLocks.get(key) ?? Promise.resolve();
693
+ let release;
694
+ const current = new Promise((resolve) => {
695
+ release = resolve;
696
+ });
697
+ const next = previous.catch(() => {
698
+ }).then(() => current);
699
+ this.channelLocks.set(key, next);
700
+ await previous.catch(() => {
701
+ });
702
+ try {
703
+ return await fn();
704
+ } finally {
705
+ release();
706
+ if (this.channelLocks.get(key) === next) {
707
+ this.channelLocks.delete(key);
708
+ }
709
+ }
710
+ }
711
+ };
712
+
713
+ // src/batch-settlement/server/verify.ts
714
+ import { getAddress, verifyTypedData } from "viem";
715
+
716
+ // src/batch-settlement/server/utils.ts
717
+ function readChannelStateExtra(extra) {
718
+ const value = extra?.channelState;
719
+ if (typeof value !== "object" || value === null) {
720
+ return void 0;
721
+ }
722
+ return value;
723
+ }
724
+ function readExtraString(extra, key, fallback) {
725
+ const value = extra?.[key];
726
+ if (typeof value === "string") return value;
727
+ if (typeof value === "number") return String(value);
728
+ return fallback;
729
+ }
730
+ function readExtraNumber(extra, key, fallback) {
731
+ const value = extra?.[key];
732
+ if (typeof value === "number") return value;
733
+ if (typeof value === "string") return parseInt(value, 10) || fallback;
734
+ return fallback;
735
+ }
736
+ function parseRefundSettlementSnapshot(extra) {
737
+ const channelState = readChannelStateExtra(extra);
738
+ return {
739
+ balance: parseUintStringExtra(channelState, "balance"),
740
+ totalClaimed: parseUintStringExtra(channelState, "totalClaimed"),
741
+ withdrawRequestedAt: parseUintNumberExtra(channelState, "withdrawRequestedAt"),
742
+ refundNonce: parseUintNumberExtra(channelState, "refundNonce")
743
+ };
744
+ }
745
+ function parseUintStringExtra(extra, key) {
746
+ const value = extra?.[key];
747
+ if (typeof value === "string" && /^\d+$/.test(value)) return value;
748
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0) return String(value);
749
+ throw new Error(ErrRefundPayload);
750
+ }
751
+ function parseUintNumberExtra(extra, key) {
752
+ const value = extra?.[key];
753
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0) return value;
754
+ if (typeof value === "string" && /^\d+$/.test(value)) {
755
+ const parsed = parseInt(value, 10);
756
+ if (!Number.isNaN(parsed)) return parsed;
757
+ }
758
+ throw new Error(ErrRefundPayload);
759
+ }
760
+
761
+ // src/batch-settlement/server/verify.ts
762
+ var MIN_PENDING_TTL_MS = 5e3;
763
+ var MAX_PENDING_TTL_MS = 10 * 60 * 1e3;
764
+ function pendingExpiresAt(maxTimeoutSeconds, now) {
765
+ const requestedMs = Math.max(0, maxTimeoutSeconds ?? 0) * 1e3;
766
+ const ttlMs = Math.min(MAX_PENDING_TTL_MS, Math.max(MIN_PENDING_TTL_MS, requestedMs));
767
+ return now + ttlMs;
768
+ }
769
+ function isPendingLive(pending, now) {
770
+ return pending !== void 0 && pending.expiresAt > now;
771
+ }
772
+ async function handleBeforeVerify(scheme, ctx) {
773
+ const { paymentPayload, requirements } = ctx;
774
+ const raw = paymentPayload.payload;
775
+ const isPaidPayload = isBatchSettlementVoucherPayload(raw) || isBatchSettlementDepositPayload(raw);
776
+ const isZeroChargePayload = isBatchSettlementRefundPayload(raw);
777
+ if (!isPaidPayload && !isZeroChargePayload) {
778
+ return;
779
+ }
780
+ const channelId = raw.voucher.channelId;
781
+ const now = Date.now();
782
+ const pendingId = createNonce();
783
+ let outcome;
784
+ await scheme.getStorage().updateChannel(channelId, (current) => {
785
+ if (isPendingLive(current?.pendingRequest, now)) {
786
+ outcome = { status: "busy" };
787
+ return current;
788
+ }
789
+ const chargedCumulativeAmount = current?.chargedCumulativeAmount ?? inferMissingLocalChargedAmount(
790
+ raw.voucher.maxClaimableAmount,
791
+ requirements.amount,
792
+ isPaidPayload
793
+ );
794
+ const expectedMaxClaimable = isZeroChargePayload ? BigInt(chargedCumulativeAmount) : BigInt(chargedCumulativeAmount) + BigInt(requirements.amount);
795
+ if (BigInt(raw.voucher.maxClaimableAmount) !== expectedMaxClaimable) {
796
+ if (current) {
797
+ outcome = { status: "mismatch", channel: current };
798
+ } else {
799
+ outcome = {
800
+ status: "mismatch",
801
+ channel: buildProvisionalChannel(raw, chargedCumulativeAmount)
802
+ };
803
+ }
804
+ return current;
805
+ }
806
+ const pendingRequest = {
807
+ pendingId,
808
+ signedMaxClaimable: raw.voucher.maxClaimableAmount,
809
+ expiresAt: pendingExpiresAt(requirements.maxTimeoutSeconds, now)
810
+ };
811
+ outcome = { status: "reserved", channelSnapshot: current };
812
+ return {
813
+ ...current ?? buildProvisionalChannel(raw, chargedCumulativeAmount),
814
+ pendingRequest,
815
+ lastRequestTimestamp: now
816
+ };
817
+ });
818
+ if (outcome?.status === "busy") {
819
+ return {
820
+ abort: true,
821
+ reason: ErrChannelBusy,
822
+ message: "Channel is already processing a request"
823
+ };
824
+ }
825
+ if (outcome?.status === "mismatch") {
826
+ scheme.rememberChannelSnapshot(paymentPayload, outcome.channel);
827
+ return {
828
+ abort: true,
829
+ reason: ErrCumulativeAmountMismatch,
830
+ message: "Client voucher base does not match server state"
831
+ };
832
+ }
833
+ if (outcome?.status === "reserved") {
834
+ scheme.mergeRequestContext(paymentPayload, {
835
+ channelId,
836
+ pendingId,
837
+ channelSnapshot: outcome.channelSnapshot
838
+ });
839
+ if (isBatchSettlementVoucherPayload(raw)) {
840
+ const localResult = await verifyVoucherLocally(
841
+ scheme,
842
+ raw,
843
+ requirements,
844
+ outcome.channelSnapshot,
845
+ now
846
+ );
847
+ if (localResult) {
848
+ scheme.mergeRequestContext(paymentPayload, { localVerify: true });
849
+ return { skip: true, result: localResult };
850
+ }
851
+ }
852
+ }
853
+ }
854
+ async function handleEnrichPaymentRequiredResponse(scheme, ctx) {
855
+ if (ctx.error !== ErrCumulativeAmountMismatch) {
856
+ return;
857
+ }
858
+ const { paymentPayload } = ctx;
859
+ if (!paymentPayload) {
860
+ return;
861
+ }
862
+ const raw = paymentPayload.payload;
863
+ if (!isBatchSettlementVoucherPayload(raw) && !isBatchSettlementDepositPayload(raw) && !isBatchSettlementRefundPayload(raw)) {
864
+ return;
865
+ }
866
+ const channel = scheme.takeChannelSnapshot(paymentPayload) ?? await scheme.getStorage().get(raw.voucher.channelId);
867
+ if (!channel) {
868
+ return;
869
+ }
870
+ const accept = ctx.requirements.find(
871
+ (req) => req.scheme === BATCH_SETTLEMENT_SCHEME && req.network === paymentPayload.accepted.network
872
+ );
873
+ if (!accept) {
874
+ return;
875
+ }
876
+ accept.extra = {
877
+ ...accept.extra,
878
+ channelState: {
879
+ channelId: channel.channelId,
880
+ balance: channel.balance,
881
+ totalClaimed: channel.totalClaimed,
882
+ withdrawRequestedAt: channel.withdrawRequestedAt,
883
+ refundNonce: String(channel.refundNonce),
884
+ chargedCumulativeAmount: channel.chargedCumulativeAmount
885
+ },
886
+ voucherState: {
887
+ signedMaxClaimable: channel.signedMaxClaimable,
888
+ signature: channel.signature
889
+ }
890
+ };
891
+ }
892
+ async function handleAfterVerify(scheme, ctx) {
893
+ const { paymentPayload, result } = ctx;
894
+ if (!result.isValid || !result.payer) {
895
+ await scheme.clearPendingRequest(paymentPayload);
896
+ return;
897
+ }
898
+ const raw = paymentPayload.payload;
899
+ let channelId;
900
+ let signedMaxClaimable;
901
+ let signature;
902
+ let channelConfig;
903
+ let isRefundVoucher = false;
904
+ if (isBatchSettlementDepositPayload(raw)) {
905
+ channelId = raw.voucher.channelId;
906
+ signedMaxClaimable = raw.voucher.maxClaimableAmount;
907
+ signature = raw.voucher.signature;
908
+ channelConfig = raw.channelConfig;
909
+ } else if (isBatchSettlementVoucherPayload(raw)) {
910
+ channelId = raw.voucher.channelId;
911
+ signedMaxClaimable = raw.voucher.maxClaimableAmount;
912
+ signature = raw.voucher.signature;
913
+ channelConfig = raw.channelConfig;
914
+ } else if (isBatchSettlementRefundPayload(raw)) {
915
+ channelId = raw.voucher.channelId;
916
+ signedMaxClaimable = raw.voucher.maxClaimableAmount;
917
+ signature = raw.voucher.signature;
918
+ channelConfig = raw.channelConfig;
919
+ isRefundVoucher = true;
920
+ } else {
921
+ return;
922
+ }
923
+ const ex = result.extra ?? {};
924
+ const balance = readExtraString(ex, "balance", "0");
925
+ const totalClaimed = readExtraString(ex, "totalClaimed", "0");
926
+ const withdrawRequestedAt = readExtraNumber(ex, "withdrawRequestedAt", 0);
927
+ const refundNonce = readExtraNumber(ex, "refundNonce", 0);
928
+ const now = Date.now();
929
+ const storage = scheme.getStorage();
930
+ const requestContext = scheme.readRequestContext(paymentPayload);
931
+ if (!requestContext?.pendingId) {
932
+ return;
933
+ }
934
+ if (requestContext.localVerify && isBatchSettlementVoucherPayload(raw)) {
935
+ return;
936
+ }
937
+ const updateResult = await storage.updateChannel(channelId, (current) => {
938
+ if (!current || current.pendingRequest?.pendingId !== requestContext.pendingId) {
939
+ return current;
940
+ }
941
+ const channel = {
942
+ channelId,
943
+ channelConfig,
944
+ chargedCumulativeAmount: current.chargedCumulativeAmount,
945
+ signedMaxClaimable,
946
+ signature,
947
+ balance,
948
+ totalClaimed,
949
+ withdrawRequestedAt,
950
+ refundNonce,
951
+ onchainSyncedAt: requestContext.localVerify ? current.onchainSyncedAt : now,
952
+ lastRequestTimestamp: now,
953
+ pendingRequest: current.pendingRequest
954
+ };
955
+ return channel;
956
+ });
957
+ if (updateResult.status === "updated" && updateResult.channel) {
958
+ scheme.rememberChannelSnapshot(paymentPayload, updateResult.channel);
959
+ }
960
+ if (isRefundVoucher && updateResult.status === "updated") {
961
+ return {
962
+ skipHandler: true,
963
+ response: {
964
+ contentType: "application/json",
965
+ body: { message: "Refund acknowledged", channelId }
966
+ }
967
+ };
968
+ }
969
+ }
970
+ async function handleVerifyFailure(scheme, ctx) {
971
+ await scheme.clearPendingRequest(ctx.paymentPayload);
972
+ }
973
+ async function handleVerifiedPaymentCanceled(scheme, ctx) {
974
+ if (ctx.reason !== "handler_threw" && ctx.reason !== "handler_failed") {
975
+ return;
976
+ }
977
+ await scheme.clearPendingRequest(ctx.paymentPayload);
978
+ }
979
+ async function verifyVoucherLocally(scheme, raw, requirements, channel, now) {
980
+ if (!channel || !isOnchainStateFresh(channel, scheme.getOnchainStateTtlMs(), now)) {
981
+ return;
982
+ }
983
+ if (raw.channelConfig.payerAuthorizer === "0x0000000000000000000000000000000000000000") {
984
+ return;
985
+ }
986
+ const payer = raw.channelConfig.payer;
987
+ const configErr = validateChannelConfig(
988
+ raw.channelConfig,
989
+ raw.voucher.channelId,
990
+ requirements
991
+ );
992
+ if (configErr) {
993
+ return invalidVerifyResponse(payer, configErr);
994
+ }
995
+ if (computeChannelId(raw.channelConfig, requirements.network).toLowerCase() !== channel.channelId.toLowerCase()) {
996
+ return invalidVerifyResponse(payer, ErrChannelIdMismatch);
997
+ }
998
+ const signatureOk = await verifyLocalVoucherSignature(raw, requirements.network);
999
+ if (!signatureOk) {
1000
+ return invalidVerifyResponse(payer, ErrInvalidVoucherSignature);
1001
+ }
1002
+ const maxClaimableAmount = BigInt(raw.voucher.maxClaimableAmount);
1003
+ if (maxClaimableAmount > BigInt(channel.balance)) {
1004
+ return invalidVerifyResponse(payer, ErrCumulativeExceedsBalance);
1005
+ }
1006
+ if (maxClaimableAmount <= BigInt(channel.totalClaimed)) {
1007
+ return invalidVerifyResponse(payer, ErrCumulativeAmountBelowClaimed);
1008
+ }
1009
+ return {
1010
+ isValid: true,
1011
+ payer,
1012
+ extra: {
1013
+ channelId: raw.voucher.channelId,
1014
+ balance: channel.balance,
1015
+ totalClaimed: channel.totalClaimed,
1016
+ withdrawRequestedAt: channel.withdrawRequestedAt,
1017
+ refundNonce: channel.refundNonce.toString()
1018
+ }
1019
+ };
1020
+ }
1021
+ function isOnchainStateFresh(channel, ttlMs, now) {
1022
+ return channel.onchainSyncedAt !== void 0 && now - channel.onchainSyncedAt <= ttlMs;
1023
+ }
1024
+ async function verifyLocalVoucherSignature(raw, network) {
1025
+ try {
1026
+ return await verifyTypedData({
1027
+ address: getAddress(raw.channelConfig.payerAuthorizer),
1028
+ domain: getBatchSettlementEip712Domain(getEvmChainId(network)),
1029
+ types: voucherTypes,
1030
+ primaryType: "Voucher",
1031
+ message: {
1032
+ channelId: raw.voucher.channelId,
1033
+ maxClaimableAmount: BigInt(raw.voucher.maxClaimableAmount)
1034
+ },
1035
+ signature: raw.voucher.signature
1036
+ });
1037
+ } catch {
1038
+ return false;
1039
+ }
1040
+ }
1041
+ function invalidVerifyResponse(payer, invalidReason) {
1042
+ return { isValid: false, invalidReason, payer };
1043
+ }
1044
+ function buildProvisionalChannel(raw, chargedCumulativeAmount) {
1045
+ return {
1046
+ channelId: raw.voucher.channelId,
1047
+ channelConfig: raw.channelConfig,
1048
+ chargedCumulativeAmount,
1049
+ signedMaxClaimable: raw.voucher.maxClaimableAmount,
1050
+ signature: raw.voucher.signature,
1051
+ balance: "0",
1052
+ totalClaimed: "0",
1053
+ withdrawRequestedAt: 0,
1054
+ refundNonce: 0,
1055
+ lastRequestTimestamp: Date.now()
1056
+ };
1057
+ }
1058
+ function inferMissingLocalChargedAmount(signedMaxClaimable, price, isPaidPayload) {
1059
+ if (!isPaidPayload) {
1060
+ return signedMaxClaimable;
1061
+ }
1062
+ const signed = BigInt(signedMaxClaimable);
1063
+ const amount = BigInt(price);
1064
+ if (signed < amount) {
1065
+ return "0";
1066
+ }
1067
+ return (signed - amount).toString();
1068
+ }
1069
+
1070
+ // src/batch-settlement/server/settle.ts
1071
+ function channelStateExtra(channel, chargedCumulativeAmount) {
1072
+ return {
1073
+ channelId: channel.channelId,
1074
+ balance: channel.balance,
1075
+ totalClaimed: channel.totalClaimed,
1076
+ withdrawRequestedAt: channel.withdrawRequestedAt,
1077
+ refundNonce: String(channel.refundNonce),
1078
+ ...chargedCumulativeAmount !== void 0 ? { chargedCumulativeAmount } : {}
1079
+ };
1080
+ }
1081
+ async function handleBeforeSettle(scheme, ctx) {
1082
+ const { paymentPayload, requirements } = ctx;
1083
+ const raw = paymentPayload.payload;
1084
+ const storage = scheme.getStorage();
1085
+ if (!isBatchSettlementVoucherPayload(raw)) {
1086
+ return;
1087
+ }
1088
+ const { voucher } = raw;
1089
+ const channelId = voucher.channelId;
1090
+ const pendingId = scheme.readRequestContext(paymentPayload)?.pendingId;
1091
+ const increment = BigInt(requirements.amount);
1092
+ const signedCap = BigInt(voucher.maxClaimableAmount);
1093
+ let outcome;
1094
+ const updateResult = await storage.updateChannel(channelId, (current) => {
1095
+ if (!current) {
1096
+ outcome = { status: "missing" };
1097
+ return current;
1098
+ }
1099
+ if (!pendingId || current.pendingRequest?.pendingId !== pendingId) {
1100
+ outcome = { status: "pending_mismatch" };
1101
+ return current;
1102
+ }
1103
+ const newCharged = BigInt(current.chargedCumulativeAmount) + increment;
1104
+ if (newCharged > signedCap) {
1105
+ outcome = { status: "cap_exceeded", charged: newCharged.toString() };
1106
+ return {
1107
+ ...current,
1108
+ pendingRequest: void 0
1109
+ };
1110
+ }
1111
+ const updatedChannel = {
1112
+ ...current,
1113
+ chargedCumulativeAmount: newCharged.toString(),
1114
+ signedMaxClaimable: voucher.maxClaimableAmount,
1115
+ signature: voucher.signature,
1116
+ lastRequestTimestamp: Date.now(),
1117
+ pendingRequest: void 0
1118
+ };
1119
+ outcome = { status: "committed", previous: current, current: updatedChannel };
1120
+ return updatedChannel;
1121
+ });
1122
+ if (outcome?.status === "missing") {
1123
+ scheme.takeRequestContext(paymentPayload);
1124
+ return {
1125
+ abort: true,
1126
+ reason: ErrMissingChannel,
1127
+ message: "No channel record"
1128
+ };
1129
+ }
1130
+ if (outcome?.status === "cap_exceeded") {
1131
+ scheme.takeRequestContext(paymentPayload);
1132
+ return {
1133
+ abort: true,
1134
+ reason: ErrChargeExceedsSignedCumulative,
1135
+ message: `Charged ${outcome.charged} exceeds signed max ${signedCap.toString()}`
1136
+ };
1137
+ }
1138
+ if (updateResult.status !== "updated" || outcome?.status !== "committed") {
1139
+ scheme.takeRequestContext(paymentPayload);
1140
+ return {
1141
+ abort: true,
1142
+ reason: ErrChannelBusy,
1143
+ message: "Concurrent request modified channel state"
1144
+ };
1145
+ }
1146
+ scheme.takeRequestContext(paymentPayload);
1147
+ const skipExtra = {
1148
+ channelState: channelStateExtra(outcome.previous, outcome.current.chargedCumulativeAmount),
1149
+ chargedAmount: requirements.amount
1150
+ };
1151
+ return {
1152
+ skip: true,
1153
+ result: {
1154
+ success: true,
1155
+ payer: outcome.previous.channelConfig.payer.toLowerCase(),
1156
+ transaction: "",
1157
+ network: requirements.network,
1158
+ amount: "",
1159
+ extra: skipExtra
1160
+ }
1161
+ };
1162
+ }
1163
+ async function handleEnrichSettlementPayload(scheme, ctx) {
1164
+ const { paymentPayload, requirements } = ctx;
1165
+ const raw = paymentPayload.payload;
1166
+ if (!isBatchSettlementRefundPayload(raw)) {
1167
+ return;
1168
+ }
1169
+ const channelId = computeChannelId(raw.channelConfig, requirements.network);
1170
+ if (raw.voucher.channelId !== channelId) {
1171
+ throw new Error("refund channelId does not match channelConfig");
1172
+ }
1173
+ const channel = await scheme.getStorage().get(channelId);
1174
+ if (!channel) {
1175
+ throw new Error(ErrMissingChannel);
1176
+ }
1177
+ const pendingId = scheme.readRequestContext(paymentPayload)?.pendingId;
1178
+ if (!pendingId || channel.pendingRequest?.pendingId !== pendingId) {
1179
+ throw new Error(ErrChannelBusy);
1180
+ }
1181
+ if (BigInt(raw.voucher.maxClaimableAmount) !== BigInt(channel.chargedCumulativeAmount)) {
1182
+ throw new Error(ErrCumulativeAmountMismatch);
1183
+ }
1184
+ if (raw.voucher.signature !== channel.signature) {
1185
+ throw new Error(ErrInvalidVoucherSignature);
1186
+ }
1187
+ const config = raw.channelConfig;
1188
+ const claimEntry = {
1189
+ voucher: {
1190
+ channel: config,
1191
+ maxClaimableAmount: raw.voucher.maxClaimableAmount
1192
+ },
1193
+ signature: raw.voucher.signature,
1194
+ totalClaimed: channel.chargedCumulativeAmount
1195
+ };
1196
+ const remainder = BigInt(channel.balance) - BigInt(channel.chargedCumulativeAmount);
1197
+ if (remainder <= 0n) {
1198
+ throw new Error(ErrRefundNoBalance);
1199
+ }
1200
+ let refundAmountBig = remainder;
1201
+ if (raw.amount !== void 0) {
1202
+ if (!/^\d+$/.test(raw.amount)) {
1203
+ throw new Error(ErrRefundAmountInvalid);
1204
+ }
1205
+ const requested = BigInt(raw.amount);
1206
+ if (requested <= 0n) {
1207
+ throw new Error(ErrRefundAmountInvalid);
1208
+ }
1209
+ refundAmountBig = requested;
1210
+ }
1211
+ const refundAmount = refundAmountBig.toString();
1212
+ const nonce = String(channel.refundNonce ?? 0);
1213
+ const receiverAuthorizerSigner = scheme.getReceiverAuthorizerSigner();
1214
+ const refundAuthorizerSignature = receiverAuthorizerSigner ? await signRefund(
1215
+ receiverAuthorizerSigner,
1216
+ channelId,
1217
+ refundAmount,
1218
+ nonce,
1219
+ requirements.network
1220
+ ) : void 0;
1221
+ const claimAuthorizerSignature = receiverAuthorizerSigner ? await signClaimBatch(receiverAuthorizerSigner, [claimEntry], requirements.network) : void 0;
1222
+ scheme.rememberChannelSnapshot(paymentPayload, channel);
1223
+ return {
1224
+ ...raw.amount === void 0 ? { amount: refundAmount } : {},
1225
+ refundNonce: nonce,
1226
+ claims: [claimEntry],
1227
+ refundAuthorizerSignature,
1228
+ claimAuthorizerSignature
1229
+ };
1230
+ }
1231
+ async function handleAfterSettle(scheme, ctx) {
1232
+ const { paymentPayload, requirements, result } = ctx;
1233
+ if (!result.success) {
1234
+ return;
1235
+ }
1236
+ const raw = paymentPayload.payload;
1237
+ const storage = scheme.getStorage();
1238
+ if (isBatchSettlementRefundPayload(raw)) {
1239
+ const channelId = computeChannelId(raw.channelConfig, requirements.network);
1240
+ const pendingId = scheme.readRequestContext(paymentPayload)?.pendingId;
1241
+ const now = Date.now();
1242
+ const snapshot = parseRefundSettlementSnapshot(result.extra);
1243
+ const updateResult = await storage.updateChannel(channelId, (current) => {
1244
+ if (!current) {
1245
+ return current;
1246
+ }
1247
+ if (!pendingId || current.pendingRequest?.pendingId !== pendingId) {
1248
+ return current;
1249
+ }
1250
+ if (BigInt(snapshot.balance) <= BigInt(current.chargedCumulativeAmount)) {
1251
+ return void 0;
1252
+ }
1253
+ return {
1254
+ ...current,
1255
+ ...snapshot,
1256
+ onchainSyncedAt: now,
1257
+ lastRequestTimestamp: now,
1258
+ pendingRequest: void 0
1259
+ };
1260
+ });
1261
+ if (updateResult.status === "unchanged") {
1262
+ throw new Error(ErrChannelBusy);
1263
+ }
1264
+ if (!updateResult.channel) {
1265
+ return;
1266
+ }
1267
+ return;
1268
+ }
1269
+ if (isBatchSettlementVoucherPayload(raw)) {
1270
+ return;
1271
+ }
1272
+ if (isBatchSettlementDepositPayload(raw)) {
1273
+ const channelId = raw.voucher.channelId;
1274
+ const pendingId = scheme.readRequestContext(paymentPayload)?.pendingId;
1275
+ const ex = result.extra ?? {};
1276
+ const channelState = readChannelStateExtra(ex);
1277
+ const config = raw.channelConfig;
1278
+ const signedMaxClaimable = raw.voucher.maxClaimableAmount;
1279
+ const now = Date.now();
1280
+ const updateResult = await storage.updateChannel(channelId, (current) => {
1281
+ if (!current) {
1282
+ return current;
1283
+ }
1284
+ if (!pendingId || current.pendingRequest?.pendingId !== pendingId) {
1285
+ return current;
1286
+ }
1287
+ const chargedActual = (BigInt(current.chargedCumulativeAmount) + BigInt(requirements.amount)).toString();
1288
+ return {
1289
+ channelId,
1290
+ channelConfig: config,
1291
+ chargedCumulativeAmount: chargedActual,
1292
+ signedMaxClaimable,
1293
+ signature: raw.voucher.signature,
1294
+ balance: readExtraString(channelState, "balance", current.balance),
1295
+ totalClaimed: readExtraString(channelState, "totalClaimed", current.totalClaimed),
1296
+ withdrawRequestedAt: readExtraNumber(
1297
+ channelState,
1298
+ "withdrawRequestedAt",
1299
+ current.withdrawRequestedAt
1300
+ ),
1301
+ refundNonce: readExtraNumber(channelState, "refundNonce", current.refundNonce),
1302
+ onchainSyncedAt: now,
1303
+ lastRequestTimestamp: now
1304
+ };
1305
+ });
1306
+ if (updateResult.status === "updated" && updateResult.channel) {
1307
+ scheme.rememberChannelSnapshot(paymentPayload, updateResult.channel);
1308
+ return;
1309
+ }
1310
+ scheme.takeRequestContext(paymentPayload);
1311
+ throw new Error(ErrChannelBusy);
1312
+ }
1313
+ }
1314
+ async function handleSettleFailure(scheme, ctx) {
1315
+ await scheme.clearPendingRequest(ctx.paymentPayload);
1316
+ }
1317
+ async function handleEnrichSettlementResponse(scheme, ctx) {
1318
+ const raw = ctx.paymentPayload.payload;
1319
+ if (isBatchSettlementVoucherPayload(raw)) {
1320
+ return;
1321
+ }
1322
+ const channel = scheme.takeChannelSnapshot(ctx.paymentPayload);
1323
+ if (!channel) {
1324
+ return;
1325
+ }
1326
+ if (isBatchSettlementRefundPayload(raw)) {
1327
+ return {
1328
+ channelState: {
1329
+ chargedCumulativeAmount: channel.chargedCumulativeAmount
1330
+ }
1331
+ };
1332
+ }
1333
+ if (isBatchSettlementDepositPayload(raw)) {
1334
+ return {
1335
+ channelState: {
1336
+ chargedCumulativeAmount: channel.chargedCumulativeAmount
1337
+ },
1338
+ chargedAmount: ctx.requirements.amount
1339
+ };
1340
+ }
1341
+ return {
1342
+ channelState: {
1343
+ chargedCumulativeAmount: channel.chargedCumulativeAmount
1344
+ }
1345
+ };
1346
+ }
1347
+
1348
+ // src/batch-settlement/server/scheme.ts
1349
+ var BatchSettlementEvmScheme = class {
1350
+ /**
1351
+ * Constructs a batched server scheme.
1352
+ *
1353
+ * @param receiverAddress - The server's receiver address (payTo).
1354
+ * @param config - Optional configuration for storage, receiver-authorizer signer, and withdraw delay.
1355
+ */
1356
+ constructor(receiverAddress, config) {
1357
+ this.scheme = BATCH_SETTLEMENT_SCHEME;
1358
+ this.requestContexts = /* @__PURE__ */ new WeakMap();
1359
+ this.moneyParsers = [];
1360
+ /**
1361
+ * Adds server-owned settlement fields before facilitator settlement.
1362
+ *
1363
+ * @param ctx - Settlement context for the current payment.
1364
+ * @returns Additive payload fields, or nothing when no enrichment is needed.
1365
+ */
1366
+ this.enrichSettlementPayload = (ctx) => handleEnrichSettlementPayload(this, ctx);
1367
+ /**
1368
+ * Adds corrective channel state to payment-required responses when available.
1369
+ *
1370
+ * @param ctx - Payment-required response context for the current request.
1371
+ * @returns Updated payment requirements, or nothing when no enrichment is needed.
1372
+ */
1373
+ this.enrichPaymentRequiredResponse = (ctx) => handleEnrichPaymentRequiredResponse(this, ctx);
1374
+ /**
1375
+ * Adds server-owned extra fields after facilitator settlement.
1376
+ *
1377
+ * @param ctx - Settlement result context for the current payment.
1378
+ * @returns Additive response extra fields, or nothing when no enrichment is needed.
1379
+ */
1380
+ this.enrichSettlementResponse = (ctx) => handleEnrichSettlementResponse(this, ctx);
1381
+ this.receiverAddress = receiverAddress;
1382
+ this.storage = config?.storage ?? new InMemoryChannelStorage();
1383
+ this.receiverAuthorizerSigner = config?.receiverAuthorizerSigner;
1384
+ this.withdrawDelay = config?.withdrawDelay ?? MIN_WITHDRAW_DELAY;
1385
+ this.onchainStateTtlMs = config?.onchainStateTtlMs ?? defaultOnchainStateTtlMs(this.withdrawDelay);
1386
+ this.schemeHooks = {
1387
+ onBeforeVerify: (ctx) => handleBeforeVerify(this, ctx),
1388
+ onAfterVerify: (ctx) => handleAfterVerify(this, ctx),
1389
+ onBeforeSettle: (ctx) => handleBeforeSettle(this, ctx),
1390
+ onAfterSettle: (ctx) => handleAfterSettle(this, ctx),
1391
+ onVerifyFailure: (ctx) => handleVerifyFailure(this, ctx),
1392
+ onSettleFailure: (ctx) => handleSettleFailure(this, ctx),
1393
+ onVerifiedPaymentCanceled: (ctx) => handleVerifiedPaymentCanceled(this, ctx)
1394
+ };
1395
+ }
1396
+ /**
1397
+ * Merges batch-settlement state into the current request context.
1398
+ *
1399
+ * @param payload - Request-scoped payment payload object.
1400
+ * @param context - Partial context fields to merge.
1401
+ */
1402
+ mergeRequestContext(payload, context) {
1403
+ this.requestContexts.set(payload, {
1404
+ ...this.requestContexts.get(payload),
1405
+ ...context
1406
+ });
1407
+ }
1408
+ /**
1409
+ * Reads batch-settlement state for the current request without clearing it.
1410
+ *
1411
+ * @param payload - Request-scoped payment payload object.
1412
+ * @returns Request context, if one was recorded.
1413
+ */
1414
+ readRequestContext(payload) {
1415
+ return this.requestContexts.get(payload);
1416
+ }
1417
+ /**
1418
+ * Reads and clears batch-settlement state for the current request.
1419
+ *
1420
+ * @param payload - Request-scoped payment payload object.
1421
+ * @returns Request context, if one was recorded.
1422
+ */
1423
+ takeRequestContext(payload) {
1424
+ const context = this.requestContexts.get(payload);
1425
+ this.requestContexts.delete(payload);
1426
+ return context;
1427
+ }
1428
+ /**
1429
+ * Stores a channel snapshot for the current settlement request.
1430
+ *
1431
+ * @param payload - Request-scoped payment payload object.
1432
+ * @param channel - Channel state to use during response enrichment.
1433
+ */
1434
+ rememberChannelSnapshot(payload, channel) {
1435
+ this.mergeRequestContext(payload, {
1436
+ channelId: channel.channelId,
1437
+ channelSnapshot: channel
1438
+ });
1439
+ }
1440
+ /**
1441
+ * Reads and clears a channel snapshot for the current settlement request.
1442
+ *
1443
+ * @param payload - Request-scoped payment payload object.
1444
+ * @returns Stored channel state, if one was recorded.
1445
+ */
1446
+ takeChannelSnapshot(payload) {
1447
+ return this.takeRequestContext(payload)?.channelSnapshot;
1448
+ }
1449
+ /**
1450
+ * Clears this request's pending reservation without touching newer reservations.
1451
+ *
1452
+ * @param payload - Request-scoped payment payload object.
1453
+ */
1454
+ async clearPendingRequest(payload) {
1455
+ const context = this.takeRequestContext(payload);
1456
+ if (!context?.channelId || !context.pendingId) {
1457
+ return;
1458
+ }
1459
+ await this.storage.updateChannel(context.channelId, (current) => {
1460
+ if (!current || current.pendingRequest?.pendingId !== context.pendingId) {
1461
+ return current;
1462
+ }
1463
+ if (!context.channelSnapshot) {
1464
+ return void 0;
1465
+ }
1466
+ return {
1467
+ ...current,
1468
+ pendingRequest: void 0
1469
+ };
1470
+ });
1471
+ }
1472
+ /**
1473
+ * Registers a custom money parser for converting price strings to token amounts.
1474
+ *
1475
+ * @param parser - A parser function to try before the default USD→token conversion.
1476
+ * @returns `this` for chaining.
1477
+ */
1478
+ registerMoneyParser(parser) {
1479
+ this.moneyParsers.push(parser);
1480
+ return this;
1481
+ }
1482
+ /**
1483
+ * Resolves a human-readable price (e.g. `"$0.01"`) into an onchain token amount.
1484
+ *
1485
+ * @param price - A price string, number, or explicit {@link AssetAmount}.
1486
+ * @param network - CAIP-2 network identifier for looking up the default asset.
1487
+ * @returns Token amount with asset address and metadata.
1488
+ */
1489
+ async parsePrice(price, network) {
1490
+ if (typeof price === "object" && price !== null && "amount" in price) {
1491
+ if (!price.asset) {
1492
+ throw new Error(`Asset address must be specified for AssetAmount on network ${network}`);
1493
+ }
1494
+ return {
1495
+ amount: price.amount,
1496
+ asset: price.asset,
1497
+ extra: price.extra || {}
1498
+ };
1499
+ }
1500
+ const amount = this.parseMoneyToDecimal(price);
1501
+ for (const parser of this.moneyParsers) {
1502
+ const result = await parser(amount, network);
1503
+ if (result !== null) {
1504
+ return result;
1505
+ }
1506
+ }
1507
+ return this.defaultMoneyConversion(amount, network);
1508
+ }
1509
+ /**
1510
+ * Injects batched-specific fields into the payment requirements returned to
1511
+ * the client (receiverAuthorizer, withdrawDelay, EIP-712 domain info).
1512
+ *
1513
+ * @param paymentRequirements - Base payment requirements from the middleware.
1514
+ * @param supportedKind - Matched scheme/network kind (extra may contain overrides).
1515
+ * @param supportedKind.x402Version - Protocol version from the matched kind.
1516
+ * @param supportedKind.scheme - Scheme name from the matched kind.
1517
+ * @param supportedKind.network - Network identifier from the matched kind.
1518
+ * @param supportedKind.extra - Optional extra fields on the matched kind.
1519
+ * @param _extensionKeys - Extension keys (unused).
1520
+ * @returns Enhanced payment requirements with batched fields in `extra`.
1521
+ */
1522
+ async enhancePaymentRequirements(paymentRequirements, supportedKind, _extensionKeys) {
1523
+ void _extensionKeys;
1524
+ const assetInfo = getDefaultAsset(paymentRequirements.network);
1525
+ const receiverAuthorizer = this.receiverAuthorizerSigner?.address ?? (typeof supportedKind.extra?.receiverAuthorizer === "string" ? supportedKind.extra.receiverAuthorizer : void 0);
1526
+ if (!receiverAuthorizer || getAddress2(receiverAuthorizer) === "0x0000000000000000000000000000000000000000") {
1527
+ throw new Error("Payment requirements must include a non-zero extra.receiverAuthorizer");
1528
+ }
1529
+ return {
1530
+ ...paymentRequirements,
1531
+ extra: {
1532
+ ...paymentRequirements.extra,
1533
+ receiverAuthorizer: getAddress2(receiverAuthorizer),
1534
+ withdrawDelay: this.withdrawDelay,
1535
+ name: assetInfo.name,
1536
+ version: assetInfo.version,
1537
+ assetTransferMethod: paymentRequirements.extra?.assetTransferMethod ?? assetInfo.assetTransferMethod
1538
+ }
1539
+ };
1540
+ }
1541
+ /**
1542
+ * Returns the underlying channel storage instance.
1543
+ *
1544
+ * @returns The configured {@link ChannelStorage} backend.
1545
+ */
1546
+ getStorage() {
1547
+ return this.storage;
1548
+ }
1549
+ /**
1550
+ * Returns the server's receiver address.
1551
+ *
1552
+ * @returns Receiver wallet address for the payment channel.
1553
+ */
1554
+ getReceiverAddress() {
1555
+ return this.receiverAddress;
1556
+ }
1557
+ /**
1558
+ * Returns the configured withdraw delay (seconds).
1559
+ *
1560
+ * @returns Withdraw delay in seconds before uncooperative withdrawal is allowed.
1561
+ */
1562
+ getWithdrawDelay() {
1563
+ return this.withdrawDelay;
1564
+ }
1565
+ /**
1566
+ * Returns how long mirrored onchain channel state is trusted for local voucher verification.
1567
+ *
1568
+ * @returns Freshness window in milliseconds.
1569
+ */
1570
+ getOnchainStateTtlMs() {
1571
+ return this.onchainStateTtlMs;
1572
+ }
1573
+ /**
1574
+ * Returns the receiver-authorizer signer, if configured.
1575
+ *
1576
+ * @returns Receiver-authorizer signer, or `undefined` when not set.
1577
+ */
1578
+ getReceiverAuthorizerSigner() {
1579
+ return this.receiverAuthorizerSigner;
1580
+ }
1581
+ /**
1582
+ * Creates a {@link BatchSettlementChannelManager} pre-configured with this scheme's
1583
+ * receiver, default token for the given network, and the provided facilitator.
1584
+ *
1585
+ * @param facilitator - Facilitator client for submitting onchain claims/settlements.
1586
+ * @param network - CAIP-2 network identifier (e.g. `"eip155:84532"`).
1587
+ * @returns A ready-to-use channel manager.
1588
+ */
1589
+ createChannelManager(facilitator, network) {
1590
+ const token = getDefaultAsset(network).address;
1591
+ return new BatchSettlementChannelManager({
1592
+ scheme: this,
1593
+ facilitator,
1594
+ receiver: this.receiverAddress,
1595
+ token,
1596
+ network
1597
+ });
1598
+ }
1599
+ /**
1600
+ * Parses a human-readable money string (e.g. `"$1.50"`) into a decimal number.
1601
+ *
1602
+ * @param money - Money string (may include `$`) or numeric amount.
1603
+ * @returns Parsed finite number.
1604
+ */
1605
+ parseMoneyToDecimal(money) {
1606
+ if (typeof money === "number") {
1607
+ return money;
1608
+ }
1609
+ const cleanMoney = money.replace(/^\$/, "").trim();
1610
+ const amount = parseFloat(cleanMoney);
1611
+ if (isNaN(amount)) {
1612
+ throw new Error(`Invalid money format: ${money}`);
1613
+ }
1614
+ return amount;
1615
+ }
1616
+ /**
1617
+ * Converts a decimal dollar amount to the network's default token amount.
1618
+ *
1619
+ * @param amount - Decimal amount in display units.
1620
+ * @param network - Target chain/network for default asset resolution.
1621
+ * @returns {@link AssetAmount} with integer token amount, contract address, and metadata.
1622
+ */
1623
+ defaultMoneyConversion(amount, network) {
1624
+ const assetInfo = getDefaultAsset(network);
1625
+ const tokenAmount = convertToTokenAmount(numberToDecimalString(amount), assetInfo.decimals);
1626
+ return {
1627
+ amount: tokenAmount,
1628
+ asset: assetInfo.address,
1629
+ extra: {
1630
+ name: assetInfo.name,
1631
+ version: assetInfo.version
1632
+ }
1633
+ };
1634
+ }
1635
+ };
1636
+ function defaultOnchainStateTtlMs(withdrawDelaySeconds) {
1637
+ const withdrawDelayMs = Math.max(0, withdrawDelaySeconds) * 1e3;
1638
+ return Math.min(5 * 60 * 1e3, Math.max(30 * 1e3, Math.floor(withdrawDelayMs / 3)));
1639
+ }
1640
+ export {
1641
+ BatchSettlementChannelManager,
1642
+ BatchSettlementEvmScheme,
1643
+ InMemoryChannelStorage
1644
+ };
1645
+ //# sourceMappingURL=index.mjs.map