@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,13 @@
1
+ type EvmSchemeConfig = {
2
+ rpcUrl?: string;
3
+ };
4
+ type EvmSchemeConfigByChainId = Record<number, EvmSchemeConfig>;
5
+ type EvmSchemeOptions = EvmSchemeConfig | EvmSchemeConfigByChainId;
6
+ /** @deprecated Use EvmSchemeConfig */
7
+ type ExactEvmSchemeConfig = EvmSchemeConfig;
8
+ /** @deprecated Use EvmSchemeConfigByChainId */
9
+ type ExactEvmSchemeConfigByChainId = EvmSchemeConfigByChainId;
10
+ /** @deprecated Use EvmSchemeOptions */
11
+ type ExactEvmSchemeOptions = EvmSchemeOptions;
12
+
13
+ export type { ExactEvmSchemeOptions as E, ExactEvmSchemeConfig as a, ExactEvmSchemeConfigByChainId as b, EvmSchemeOptions as c, EvmSchemeConfig as d, EvmSchemeConfigByChainId as e };
@@ -0,0 +1,307 @@
1
+ import { PaymentRequirements, SettleResponse, SchemeNetworkClient, SchemeClientHooks, PaymentPayloadContext, PaymentPayloadResult, PaymentRequired } from '@payai/x402/types';
2
+ import { C as ClientEvmSigner } from './signer-tYS6Y46X.mjs';
3
+ import { C as ChannelConfig } from './types-CF8P2-NM.mjs';
4
+ import { c as EvmSchemeOptions } from './rpc-DULZzRne.mjs';
5
+ import { B as BatchSettlementClientContext, C as ClientChannelStorage } from './storage-6W5MO46W.mjs';
6
+
7
+ /**
8
+ * Caller-tunable policy controlling how the client sizes channel deposits.
9
+ */
10
+ interface BatchSettlementDepositPolicy {
11
+ depositMultiplier?: number;
12
+ }
13
+ /**
14
+ * Return shape for custom deposit sizing.
15
+ */
16
+ type BatchSettlementDepositStrategyResult = string | bigint | false | undefined;
17
+ /**
18
+ * Information supplied before the client signs a deposit authorization.
19
+ */
20
+ interface BatchSettlementDepositStrategyContext {
21
+ paymentRequirements: PaymentRequirements;
22
+ channelConfig: ChannelConfig;
23
+ channelId: `0x${string}`;
24
+ clientContext: BatchSettlementClientContext;
25
+ requestAmount: string;
26
+ maxClaimableAmount: string;
27
+ currentBalance: string;
28
+ minimumDepositAmount: string;
29
+ depositAmount: string;
30
+ }
31
+ /**
32
+ * Custom deposit sizing callback for initial deposits and top-ups.
33
+ */
34
+ type BatchSettlementDepositStrategy = (context: BatchSettlementDepositStrategyContext) => BatchSettlementDepositStrategyResult | Promise<BatchSettlementDepositStrategyResult>;
35
+ /**
36
+ * Full options object accepted by `BatchSettlementEvmScheme`. Either this or a
37
+ * bare {@link BatchSettlementDepositPolicy} can be passed as the second
38
+ * constructor argument.
39
+ */
40
+ interface BatchSettlementEvmSchemeOptions {
41
+ depositPolicy?: BatchSettlementDepositPolicy;
42
+ /** Optional callback for app-specific deposit sizing or skipping. */
43
+ depositStrategy?: BatchSettlementDepositStrategy;
44
+ storage?: ClientChannelStorage;
45
+ salt?: `0x${string}`;
46
+ payerAuthorizer?: `0x${string}`;
47
+ rpcUrl?: string;
48
+ /** When set, EIP-712 vouchers are signed with this key; deposits still use the main `signer`. */
49
+ voucherSigner?: ClientEvmSigner;
50
+ }
51
+ /**
52
+ * Resolved options after merging defaults — used internally by the scheme,
53
+ * recovery, and refund modules.
54
+ */
55
+ interface ResolvedClientOptions {
56
+ depositPolicy?: BatchSettlementDepositPolicy;
57
+ depositStrategy?: BatchSettlementDepositStrategy;
58
+ storage: ClientChannelStorage;
59
+ salt: `0x${string}`;
60
+ payerAuthorizer?: `0x${string}`;
61
+ voucherSigner?: ClientEvmSigner;
62
+ extensionRpcOptions?: EvmSchemeOptions;
63
+ }
64
+ /**
65
+ * Discriminates a full options object from a bare deposit-policy object.
66
+ *
67
+ * @param o - Constructor argument that may be options, deposit policy only, or undefined.
68
+ * @returns `true` when `o` is a {@link BatchSettlementEvmSchemeOptions} object.
69
+ */
70
+ declare function isBatchSettlementEvmSchemeOptions(o: BatchSettlementEvmSchemeOptions | BatchSettlementDepositPolicy | undefined): o is BatchSettlementEvmSchemeOptions;
71
+ /**
72
+ * Normalises the constructor's second argument into a uniform options shape.
73
+ *
74
+ * @param second - Optional second constructor argument (options or deposit policy).
75
+ * @returns Resolved storage, salt, deposit policy, and optional payer authorizer.
76
+ */
77
+ declare function resolveClientOptions(second?: BatchSettlementEvmSchemeOptions | BatchSettlementDepositPolicy): ResolvedClientOptions;
78
+ /**
79
+ * Validates a {@link BatchSettlementDepositPolicy}, throwing on invalid fields.
80
+ *
81
+ * @param policy - The policy to validate (no-op when undefined).
82
+ */
83
+ declare function validateDepositPolicy(policy: BatchSettlementDepositPolicy | undefined): void;
84
+ /**
85
+ * Computes the deposit amount based on the deposit multiplier.
86
+ *
87
+ * @param policy - Deposit policy controlling multiplier (may be undefined).
88
+ * @param requestAmount - Amount requested for this operation, in token base units.
89
+ * @returns Deposit amount string in token base units.
90
+ */
91
+ declare function depositAmountForRequest(policy: BatchSettlementDepositPolicy | undefined, requestAmount: bigint): string;
92
+
93
+ /**
94
+ * Runtime dependency bag shared by every storage-bound client helper (channel,
95
+ * recovery, refund) and the {@link BatchSettlementEvmScheme} class.
96
+ */
97
+ interface BatchSettlementClientDeps {
98
+ signer: ClientEvmSigner;
99
+ storage: ClientChannelStorage;
100
+ salt: `0x${string}`;
101
+ payerAuthorizer?: `0x${string}`;
102
+ voucherSigner?: ClientEvmSigner;
103
+ }
104
+ /**
105
+ * Constructs the immutable {@link ChannelConfig} from payment requirements and
106
+ * a client deps bag (signer, salt, optional payerAuthorizer / voucherSigner).
107
+ *
108
+ * @param deps - Client identity inputs.
109
+ * @param paymentRequirements - Server payment requirements providing receiver, asset, and extra fields.
110
+ * @returns The ChannelConfig that uniquely identifies this payment channel.
111
+ */
112
+ declare function buildChannelConfig(deps: BatchSettlementClientDeps, paymentRequirements: PaymentRequirements): ChannelConfig;
113
+ /**
114
+ * Updates local channel state from a parsed `SettleResponse`.
115
+ *
116
+ * @param storage - Client channel storage.
117
+ * @param settle - The parsed settle response.
118
+ */
119
+ declare function processSettleResponse(storage: ClientChannelStorage, settle: SettleResponse): Promise<void>;
120
+ /**
121
+ * Reconciles local channel state with the outcome of a cooperative refund.
122
+ *
123
+ * Deletes the channel record when the post-refund balance is zero (full refund),
124
+ * otherwise updates local state from the server snapshot.
125
+ *
126
+ * @param storage - Client channel storage.
127
+ * @param channelKey - Lowercased channel id used as the storage key.
128
+ * @param settleExtra - The `extra` block from the refund settle response.
129
+ */
130
+ declare function updateChannelAfterRefund(storage: ClientChannelStorage, channelKey: string, settleExtra: Record<string, unknown>): Promise<void>;
131
+ /**
132
+ * Processes the `PAYMENT-RESPONSE` header after a successful request.
133
+ *
134
+ * Decodes the header into a `SettleResponse` and delegates to
135
+ * {@link processSettleResponse}.
136
+ *
137
+ * @param storage - Client channel storage.
138
+ * @param getHeader - Function to retrieve a response header by name.
139
+ */
140
+ declare function processPaymentResponse(storage: ClientChannelStorage, getHeader: (name: string) => string | null | undefined): Promise<void>;
141
+ /**
142
+ * Recovers a channel record from onchain state (useful after a cold start or
143
+ * channel record loss).
144
+ *
145
+ * @param deps - Signer + storage + identity inputs.
146
+ * @param paymentRequirements - Server payment requirements used to derive the ChannelConfig.
147
+ * @returns The recovered client context.
148
+ */
149
+ declare function recoverChannel(deps: BatchSettlementClientDeps, paymentRequirements: PaymentRequirements): Promise<BatchSettlementClientContext>;
150
+ /**
151
+ * Reads `channels(channelId)` returning `[balance, totalClaimed]`.
152
+ *
153
+ * @param signer - Signer providing `readContract`.
154
+ * @param channelId - The `bytes32` channel id to query.
155
+ * @returns Tuple of `[balance, totalClaimed]` as bigints.
156
+ */
157
+ declare function readChannelBalanceAndTotalClaimed(signer: ClientEvmSigner, channelId: `0x${string}`): Promise<[bigint, bigint]>;
158
+ /**
159
+ * Returns whether a local channel record exists for the given channel.
160
+ *
161
+ * @param storage - Client channel storage.
162
+ * @param channelId - The channel identifier to check.
163
+ * @returns `true` when a channel record is stored.
164
+ */
165
+ declare function hasChannel(storage: ClientChannelStorage, channelId: string): Promise<boolean>;
166
+ /**
167
+ * Returns the local channel context for a channel, if present.
168
+ *
169
+ * @param storage - Client channel storage.
170
+ * @param channelId - The channel identifier.
171
+ * @returns Stored context or `undefined`.
172
+ */
173
+ declare function getChannel(storage: ClientChannelStorage, channelId: string): Promise<BatchSettlementClientContext | undefined>;
174
+
175
+ /**
176
+ * Caller-facing options for {@link refundChannel}.
177
+ */
178
+ interface RefundOptions {
179
+ /** Token base units to refund; omit for a full refund (drains remaining balance). */
180
+ amount?: string;
181
+ /** Custom fetch implementation (defaults to `globalThis.fetch`). */
182
+ fetch?: typeof fetch;
183
+ }
184
+ /**
185
+ * Sends a cooperative refund request to the channel that backs `url`.
186
+ *
187
+ * Flow:
188
+ * 1. Probe the URL with `GET` (no payment) to obtain the route's payment requirements.
189
+ * 2. Build the `ChannelConfig` and resolve the local session (or recover it).
190
+ * 3. Sign a zero-charge refund voucher (`maxClaimableAmount = chargedCumulativeAmount`).
191
+ * 4. Send the voucher via `PAYMENT-SIGNATURE`. On a corrective 402, run the
192
+ * standard recovery path and retry once.
193
+ * 5. Return the parsed `SettleResponse` from the server.
194
+ *
195
+ * @param ctx - Identity inputs (storage, signers, salt, payerAuthorizer).
196
+ * @param url - Any protected route on the channel to refund (the resource handler is bypassed).
197
+ * @param options - Optional `amount` (partial refund) and `fetch` override.
198
+ * @returns The settle response describing the refund outcome.
199
+ * @throws When the probe fails, the receiver lacks an authorizer, or recovery fails.
200
+ */
201
+ declare function refundChannel(ctx: BatchSettlementClientDeps, url: string, options?: RefundOptions): Promise<SettleResponse>;
202
+
203
+ /**
204
+ * Client-side implementation of the `batch-settlement` scheme for EVM networks.
205
+ *
206
+ * Builds payment payloads (deposit + voucher or voucher-only), processes server
207
+ * responses to update local session state via {@link processSettleResponse},
208
+ * handles corrective 402 resynchronisation via
209
+ * {@link processCorrectivePaymentRequired}, and supports on-demand cooperative
210
+ * refund requests via {@link refundChannel}.
211
+ */
212
+ declare class BatchSettlementEvmScheme implements SchemeNetworkClient {
213
+ private readonly signer;
214
+ readonly scheme: "batch-settlement";
215
+ readonly schemeHooks: SchemeClientHooks;
216
+ private readonly storage;
217
+ private readonly depositPolicy;
218
+ private readonly depositStrategy;
219
+ private readonly salt;
220
+ private readonly payerAuthorizer;
221
+ private readonly voucherSigner;
222
+ private readonly extensionRpcOptions;
223
+ /**
224
+ * Constructs a batched client scheme.
225
+ *
226
+ * @param signer - Client EVM wallet used for signing vouchers and ERC-3009 authorizations.
227
+ * @param optionsOrPolicy - Either a full options object or a bare deposit-policy.
228
+ */
229
+ constructor(signer: ClientEvmSigner, optionsOrPolicy?: BatchSettlementEvmSchemeOptions | BatchSettlementDepositPolicy);
230
+ /**
231
+ * Creates the payment payload for a batched request.
232
+ *
233
+ * If the channel has no onchain deposit (or needs a top-up), builds an
234
+ * ERC-3009 deposit payload bundled with a voucher. Otherwise, signs and
235
+ * returns a voucher-only payload.
236
+ *
237
+ * @param x402Version - Protocol version for the payload envelope.
238
+ * @param paymentRequirements - Server payment requirements (scheme, network, asset, amount).
239
+ * @param context - Optional payment payload context with extension hints.
240
+ * @returns A {@link PaymentPayloadResult} ready to be sent as the `X-PAYMENT` header.
241
+ */
242
+ createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
243
+ /**
244
+ * Sends a cooperative refund request.
245
+ *
246
+ * @param url - The route URL backing the channel to refund.
247
+ * @param options - Optional `amount` (partial refund) and `fetch` override.
248
+ * @returns The settle response describing the refund outcome.
249
+ */
250
+ refund(url: string, options?: RefundOptions): Promise<SettleResponse>;
251
+ /**
252
+ * Updates local channel state from a settle response.
253
+ *
254
+ * @param settle - The parsed settle response from the server.
255
+ * @returns Resolves when local channel state has been updated.
256
+ */
257
+ processSettleResponse(settle: SettleResponse): Promise<void>;
258
+ /**
259
+ * Resyncs local channel state from a corrective 402 response.
260
+ *
261
+ * @param paymentRequired - The decoded 402 response body.
262
+ * @returns `true` if local state was successfully resynced and a retry is warranted.
263
+ */
264
+ processCorrectivePaymentRequired(paymentRequired: PaymentRequired): Promise<boolean>;
265
+ /**
266
+ * Builds the immutable {@link ChannelConfig} for a given set of payment
267
+ * requirements, using the scheme's own signer and salt.
268
+ *
269
+ * @param paymentRequirements - Server payment requirements for the channel.
270
+ * @returns The channel config that uniquely identifies the payment channel.
271
+ */
272
+ buildChannelConfig(paymentRequirements: PaymentRequirements): ChannelConfig;
273
+ /**
274
+ * Resolves the deposit amount after applying the optional custom strategy.
275
+ *
276
+ * @param context - Deposit attempt context exposed to the strategy.
277
+ * @returns The deposit amount to sign, or `false` to skip this deposit attempt.
278
+ */
279
+ private resolveDepositAmount;
280
+ /**
281
+ * Normalizes and validates a strategy-provided base-unit deposit amount.
282
+ *
283
+ * @param value - Strategy-provided string or bigint amount.
284
+ * @returns Normalized decimal string.
285
+ */
286
+ private normalizeStrategyDepositAmount;
287
+ /**
288
+ * Signs a voucher-only payment payload for the current channel.
289
+ *
290
+ * @param x402Version - Protocol version for the payload envelope.
291
+ * @param channelId - Channel identifier for the voucher.
292
+ * @param maxClaimableAmount - Cumulative ceiling for the voucher.
293
+ * @param network - CAIP-2 network identifier.
294
+ * @param config - Immutable channel configuration.
295
+ * @returns Voucher-only payment payload.
296
+ */
297
+ private createVoucherPayload;
298
+ /**
299
+ * Bundles the class state into the {@link BatchSettlementClientDeps} shape
300
+ * consumed by the `channel`, `recovery`, and `refund` modules.
301
+ *
302
+ * @returns Client deps wrapping the scheme's own signer and storage.
303
+ */
304
+ private deps;
305
+ }
306
+
307
+ export { BatchSettlementEvmScheme as B, type RefundOptions as R, type BatchSettlementClientDeps as a, type BatchSettlementDepositPolicy as b, type BatchSettlementDepositStrategy as c, type BatchSettlementDepositStrategyContext as d, type BatchSettlementDepositStrategyResult as e, type BatchSettlementEvmSchemeOptions as f, depositAmountForRequest as g, resolveClientOptions as h, isBatchSettlementEvmSchemeOptions as i, type ResolvedClientOptions as j, buildChannelConfig as k, getChannel as l, hasChannel as m, processSettleResponse as n, readChannelBalanceAndTotalClaimed as o, processPaymentResponse as p, recoverChannel as q, refundChannel as r, updateChannelAfterRefund as u, validateDepositPolicy as v };
@@ -0,0 +1,47 @@
1
+ import { SchemeNetworkClient, PaymentRequirements, PaymentPayloadContext, PaymentPayloadResult } from '@payai/x402/types';
2
+ import { C as ClientEvmSigner } from './signer-tYS6Y46X.mjs';
3
+ import { E as ExactEvmSchemeOptions } from './rpc-DULZzRne.mjs';
4
+
5
+ /**
6
+ * EVM client implementation for the Exact payment scheme.
7
+ * Supports both EIP-3009 (transferWithAuthorization) and Permit2 flows.
8
+ *
9
+ * Routes to the appropriate authorization method based on
10
+ * `requirements.extra.assetTransferMethod`. Defaults to EIP-3009
11
+ * for backward compatibility with older facilitators.
12
+ *
13
+ * When the server advertises `eip2612GasSponsoring` and the asset transfer
14
+ * method is `permit2`, the scheme automatically signs an EIP-2612 permit
15
+ * if the user lacks Permit2 approval. This requires `readContract` on the signer.
16
+ */
17
+ declare class ExactEvmScheme implements SchemeNetworkClient {
18
+ private readonly signer;
19
+ private readonly options?;
20
+ readonly scheme = "exact";
21
+ /**
22
+ * Creates a new ExactEvmClient instance.
23
+ *
24
+ * @param signer - The EVM signer for client operations.
25
+ * Base flow only requires `address` + `signTypedData`.
26
+ * Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally
27
+ * requires optional capabilities like `readContract` and tx signing helpers.
28
+ * @param options - Optional RPC configuration used to backfill extension capabilities.
29
+ */
30
+ constructor(signer: ClientEvmSigner, options?: ExactEvmSchemeOptions | undefined);
31
+ /**
32
+ * Creates a payment payload for the Exact scheme.
33
+ * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.
34
+ *
35
+ * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the
36
+ * signer supports `readContract`, automatically signs an EIP-2612 permit
37
+ * when Permit2 allowance is insufficient.
38
+ *
39
+ * @param x402Version - The x402 protocol version
40
+ * @param paymentRequirements - The payment requirements
41
+ * @param context - Optional context with server-declared extensions
42
+ * @returns Promise resolving to a payment payload result (with optional extensions)
43
+ */
44
+ createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements, context?: PaymentPayloadContext): Promise<PaymentPayloadResult>;
45
+ }
46
+
47
+ export { ExactEvmScheme as E };
@@ -0,0 +1,170 @@
1
+ import { Log } from 'viem';
2
+
3
+ /**
4
+ * ClientEvmSigner - Used by x402 clients to sign payment authorizations.
5
+ *
6
+ * Typically a viem WalletClient extended with publicActions:
7
+ * ```typescript
8
+ * const client = createWalletClient({
9
+ * account: privateKeyToAccount('0x...'),
10
+ * chain: baseSepolia,
11
+ * transport: http(),
12
+ * }).extend(publicActions);
13
+ * ```
14
+ *
15
+ * Or composed via `toClientEvmSigner(account, publicClient)`.
16
+ */
17
+ type ClientEvmSigner = {
18
+ readonly address: `0x${string}`;
19
+ signTypedData(message: {
20
+ domain: Record<string, unknown>;
21
+ types: Record<string, unknown>;
22
+ primaryType: string;
23
+ message: Record<string, unknown>;
24
+ }): Promise<`0x${string}`>;
25
+ /**
26
+ * Optional on-chain reads.
27
+ * Required only for extension enrichment (EIP-2612 / ERC-20 approval).
28
+ */
29
+ readContract?(args: {
30
+ address: `0x${string}`;
31
+ abi: readonly unknown[];
32
+ functionName: string;
33
+ args?: readonly unknown[];
34
+ }): Promise<unknown>;
35
+ /**
36
+ * Optional: Signs a raw EIP-1559 transaction without broadcasting.
37
+ * Required for ERC-20 approval gas sponsoring when the token lacks EIP-2612.
38
+ */
39
+ signTransaction?(args: {
40
+ to: `0x${string}`;
41
+ data: `0x${string}`;
42
+ nonce: number;
43
+ gas: bigint;
44
+ maxFeePerGas: bigint;
45
+ maxPriorityFeePerGas: bigint;
46
+ chainId: number;
47
+ }): Promise<`0x${string}`>;
48
+ /**
49
+ * Optional: Gets the current transaction count (nonce) for an address.
50
+ * Required for ERC-20 approval gas sponsoring.
51
+ */
52
+ getTransactionCount?(args: {
53
+ address: `0x${string}`;
54
+ }): Promise<number>;
55
+ /**
56
+ * Optional: Estimates current gas fees per gas.
57
+ * Required for ERC-20 approval gas sponsoring.
58
+ */
59
+ estimateFeesPerGas?(): Promise<{
60
+ maxFeePerGas: bigint;
61
+ maxPriorityFeePerGas: bigint;
62
+ }>;
63
+ };
64
+ /**
65
+ * FacilitatorEvmSigner - Used by x402 facilitators to verify and settle payments
66
+ * This is typically a viem PublicClient + WalletClient combination that can
67
+ * read contract state, verify signatures, write transactions, and wait for receipts
68
+ *
69
+ * Supports multiple addresses for load balancing, key rotation, and high availability
70
+ */
71
+ type FacilitatorEvmSigner = {
72
+ /**
73
+ * Get all addresses this facilitator can use for signing
74
+ * Enables dynamic address selection for load balancing and key rotation
75
+ */
76
+ getAddresses(): readonly `0x${string}`[];
77
+ readContract(args: {
78
+ address: `0x${string}`;
79
+ abi: readonly unknown[];
80
+ functionName: string;
81
+ args?: readonly unknown[];
82
+ }): Promise<unknown>;
83
+ verifyTypedData(args: {
84
+ address: `0x${string}`;
85
+ domain: Record<string, unknown>;
86
+ types: Record<string, unknown>;
87
+ primaryType: string;
88
+ message: Record<string, unknown>;
89
+ signature: `0x${string}`;
90
+ }): Promise<boolean>;
91
+ writeContract(args: {
92
+ address: `0x${string}`;
93
+ abi: readonly unknown[];
94
+ functionName: string;
95
+ args: readonly unknown[];
96
+ /** Optional gas limit. When provided, skips eth_estimateGas simulation. */
97
+ gas?: bigint;
98
+ }): Promise<`0x${string}`>;
99
+ sendTransaction(args: {
100
+ to: `0x${string}`;
101
+ data: `0x${string}`;
102
+ }): Promise<`0x${string}`>;
103
+ waitForTransactionReceipt(args: {
104
+ hash: `0x${string}`;
105
+ }): Promise<{
106
+ status: string;
107
+ logs?: readonly Log[];
108
+ }>;
109
+ getCode(args: {
110
+ address: `0x${string}`;
111
+ }): Promise<`0x${string}` | undefined>;
112
+ };
113
+ /**
114
+ * Composes a ClientEvmSigner from a local account and a public client.
115
+ *
116
+ * Use this when your signer (e.g., `privateKeyToAccount`) doesn't have
117
+ * `readContract`. The `publicClient` provides the on-chain read capability.
118
+ *
119
+ * Alternatively, use a WalletClient extended with publicActions directly:
120
+ * ```typescript
121
+ * const signer = createWalletClient({
122
+ * account: privateKeyToAccount('0x...'),
123
+ * chain: baseSepolia,
124
+ * transport: http(),
125
+ * }).extend(publicActions);
126
+ * ```
127
+ *
128
+ * @param signer - A signer with `address` and `signTypedData` (and optionally `readContract`)
129
+ * @param publicClient - A client with optional read/nonce/fee helpers
130
+ * @param publicClient.readContract - The readContract method from the public client
131
+ * @param publicClient.getTransactionCount - Optional getTransactionCount for ERC-20 approval
132
+ * @param publicClient.estimateFeesPerGas - Optional estimateFeesPerGas for ERC-20 approval
133
+ * @returns A ClientEvmSigner with any available optional capabilities
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * const account = privateKeyToAccount("0x...");
138
+ * const publicClient = createPublicClient({ chain: baseSepolia, transport: http() });
139
+ * const signer = toClientEvmSigner(account, publicClient);
140
+ * ```
141
+ */
142
+ declare function toClientEvmSigner(signer: Omit<ClientEvmSigner, "readContract"> & {
143
+ readContract?: ClientEvmSigner["readContract"];
144
+ }, publicClient?: {
145
+ readContract(args: {
146
+ address: `0x${string}`;
147
+ abi: readonly unknown[];
148
+ functionName: string;
149
+ args?: readonly unknown[];
150
+ }): Promise<unknown>;
151
+ getTransactionCount?(args: {
152
+ address: `0x${string}`;
153
+ }): Promise<number>;
154
+ estimateFeesPerGas?(): Promise<{
155
+ maxFeePerGas: bigint;
156
+ maxPriorityFeePerGas: bigint;
157
+ }>;
158
+ }): ClientEvmSigner;
159
+ /**
160
+ * Converts a viem client with single address to a FacilitatorEvmSigner
161
+ * Wraps the single address in a getAddresses() function for compatibility
162
+ *
163
+ * @param client - The client to convert (must have 'address' property)
164
+ * @returns FacilitatorEvmSigner with getAddresses() support
165
+ */
166
+ declare function toFacilitatorEvmSigner(client: Omit<FacilitatorEvmSigner, "getAddresses"> & {
167
+ address: `0x${string}`;
168
+ }): FacilitatorEvmSigner;
169
+
170
+ export { type ClientEvmSigner as C, type FacilitatorEvmSigner as F, toFacilitatorEvmSigner as a, toClientEvmSigner as t };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Client-side channel fields mirrored from PAYMENT-RESPONSE / recovery flows.
3
+ */
4
+ interface BatchSettlementClientContext {
5
+ /** Current cumulative amount charged by the server for this channel */
6
+ chargedCumulativeAmount?: string;
7
+ /** Current onchain channel balance */
8
+ balance?: string;
9
+ /** Total claimed onchain */
10
+ totalClaimed?: string;
11
+ /** Latest client-signed maxClaimableAmount cap (after corrective recovery, optional) */
12
+ signedMaxClaimable?: string;
13
+ /** Client voucher signature for {@link signedMaxClaimable} (optional) */
14
+ signature?: `0x${string}`;
15
+ }
16
+ interface ClientChannelStorage {
17
+ get(key: string): Promise<BatchSettlementClientContext | undefined>;
18
+ set(key: string, context: BatchSettlementClientContext): Promise<void>;
19
+ delete(key: string): Promise<void>;
20
+ }
21
+ /**
22
+ * Default in-memory {@link ClientChannelStorage} (channel records do not survive process restart).
23
+ */
24
+ declare class InMemoryClientChannelStorage implements ClientChannelStorage {
25
+ private readonly channels;
26
+ /**
27
+ * Returns the channel record for `key` if present.
28
+ *
29
+ * @param key - Channel storage key (channelId).
30
+ * @returns Persisted context or undefined.
31
+ */
32
+ get(key: string): Promise<BatchSettlementClientContext | undefined>;
33
+ /**
34
+ * Stores or replaces the channel record for `key`.
35
+ *
36
+ * @param key - Channel storage key.
37
+ * @param context - Channel fields to persist.
38
+ * @returns Resolves when stored.
39
+ */
40
+ set(key: string, context: BatchSettlementClientContext): Promise<void>;
41
+ /**
42
+ * Removes the channel record for `key` if it exists.
43
+ *
44
+ * @param key - Channel storage key.
45
+ * @returns Resolves when removed.
46
+ */
47
+ delete(key: string): Promise<void>;
48
+ }
49
+
50
+ export { type BatchSettlementClientContext as B, type ClientChannelStorage as C, InMemoryClientChannelStorage as I };
@@ -0,0 +1,81 @@
1
+ import { C as ChannelConfig } from './types-CF8P2-NM.mjs';
2
+
3
+ interface Channel {
4
+ channelId: string;
5
+ channelConfig: ChannelConfig;
6
+ chargedCumulativeAmount: string;
7
+ signedMaxClaimable: string;
8
+ signature: string;
9
+ balance: string;
10
+ totalClaimed: string;
11
+ withdrawRequestedAt: number;
12
+ refundNonce: number;
13
+ onchainSyncedAt?: number;
14
+ lastRequestTimestamp: number;
15
+ pendingRequest?: PendingRequest;
16
+ }
17
+ interface PendingRequest {
18
+ pendingId: string;
19
+ signedMaxClaimable: string;
20
+ expiresAt: number;
21
+ }
22
+ interface ChannelUpdateResult {
23
+ channel: Channel | undefined;
24
+ status: "updated" | "unchanged" | "deleted";
25
+ }
26
+ interface ChannelStorage {
27
+ get(channelId: string): Promise<Channel | undefined>;
28
+ list(): Promise<Channel[]>;
29
+ /**
30
+ * Atomically inspects and mutates a channel record.
31
+ *
32
+ * Implementations must guarantee that no concurrent mutation can interleave between
33
+ * reading `current` and writing the callback result for all application instances that
34
+ * share the backend. The in-memory backend only provides this guarantee inside one JS
35
+ * runtime; production multi-instance deployments need storage with backend-level atomic
36
+ * conditional mutation, such as Redis/Valkey Lua scripts, SQL transactions, or Durable Objects.
37
+ *
38
+ * @param channelId - The channel identifier.
39
+ * @param update - Mutation callback. Return `undefined` to delete, or `current` to leave unchanged.
40
+ * @returns The final stored channel and whether storage updated, stayed unchanged, or deleted.
41
+ */
42
+ updateChannel(channelId: string, update: (current: Channel | undefined) => Channel | undefined): Promise<ChannelUpdateResult>;
43
+ }
44
+ /**
45
+ * In-memory {@link ChannelStorage} backed by a Map keyed by `channelId`.
46
+ */
47
+ declare class InMemoryChannelStorage implements ChannelStorage {
48
+ private readonly channels;
49
+ private readonly channelLocks;
50
+ /**
51
+ * Returns the channel record for a channel, if present.
52
+ *
53
+ * @param channelId - The channel identifier.
54
+ * @returns The channel record or undefined when not found.
55
+ */
56
+ get(channelId: string): Promise<Channel | undefined>;
57
+ /**
58
+ * Lists all stored channel records.
59
+ *
60
+ * @returns All channel records in storage.
61
+ */
62
+ list(): Promise<Channel[]>;
63
+ /**
64
+ * Atomically inspects and mutates a channel record while holding a per-channel lock.
65
+ *
66
+ * @param channelId - The channel identifier.
67
+ * @param update - Mutation callback. Return `undefined` to delete, or `current` to leave unchanged.
68
+ * @returns The final stored channel and whether storage updated, stayed unchanged, or deleted.
69
+ */
70
+ updateChannel(channelId: string, update: (current: Channel | undefined) => Channel | undefined): Promise<ChannelUpdateResult>;
71
+ /**
72
+ * Runs `fn` after any prior locked work for the same channel key has finished.
73
+ *
74
+ * @param key - Lowercased channel id used as the lock key.
75
+ * @param fn - Async work to run while holding the logical per-channel lock.
76
+ * @returns The resolved result of `fn`.
77
+ */
78
+ private withChannelLock;
79
+ }
80
+
81
+ export { type ChannelStorage as C, InMemoryChannelStorage as I, type PendingRequest as P, type Channel as a, type ChannelUpdateResult as b };