@bankofai/x402-evm 1.0.0-beta.0

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 (176) hide show
  1. package/README.md +172 -0
  2. package/dist/cjs/auth-capture/client/index.d.ts +44 -0
  3. package/dist/cjs/auth-capture/client/index.js +298 -0
  4. package/dist/cjs/auth-capture/client/index.js.map +1 -0
  5. package/dist/cjs/batch-settlement/client/file-storage.d.ts +47 -0
  6. package/dist/cjs/batch-settlement/client/file-storage.js +116 -0
  7. package/dist/cjs/batch-settlement/client/file-storage.js.map +1 -0
  8. package/dist/cjs/batch-settlement/client/index.d.ts +111 -0
  9. package/dist/cjs/batch-settlement/client/index.js +1565 -0
  10. package/dist/cjs/batch-settlement/client/index.js.map +1 -0
  11. package/dist/cjs/batch-settlement/facilitator/index.d.ts +72 -0
  12. package/dist/cjs/batch-settlement/facilitator/index.js +2102 -0
  13. package/dist/cjs/batch-settlement/facilitator/index.js.map +1 -0
  14. package/dist/cjs/batch-settlement/server/file-storage.d.ts +53 -0
  15. package/dist/cjs/batch-settlement/server/file-storage.js +181 -0
  16. package/dist/cjs/batch-settlement/server/file-storage.js.map +1 -0
  17. package/dist/cjs/batch-settlement/server/index.d.ts +491 -0
  18. package/dist/cjs/batch-settlement/server/index.js +1978 -0
  19. package/dist/cjs/batch-settlement/server/index.js.map +1 -0
  20. package/dist/cjs/batch-settlement/server/redis-storage.d.ts +87 -0
  21. package/dist/cjs/batch-settlement/server/redis-storage.js +181 -0
  22. package/dist/cjs/batch-settlement/server/redis-storage.js.map +1 -0
  23. package/dist/cjs/client/agent-wallet.d.ts +69 -0
  24. package/dist/cjs/client/agent-wallet.js +84 -0
  25. package/dist/cjs/client/agent-wallet.js.map +1 -0
  26. package/dist/cjs/exact/client/index.d.ts +63 -0
  27. package/dist/cjs/exact/client/index.js +739 -0
  28. package/dist/cjs/exact/client/index.js.map +1 -0
  29. package/dist/cjs/exact/facilitator/index.d.ts +141 -0
  30. package/dist/cjs/exact/facilitator/index.js +1989 -0
  31. package/dist/cjs/exact/facilitator/index.js.map +1 -0
  32. package/dist/cjs/exact/server/index.d.ts +118 -0
  33. package/dist/cjs/exact/server/index.js +326 -0
  34. package/dist/cjs/exact/server/index.js.map +1 -0
  35. package/dist/cjs/exact/v1/client/index.d.ts +38 -0
  36. package/dist/cjs/exact/v1/client/index.js +193 -0
  37. package/dist/cjs/exact/v1/client/index.js.map +1 -0
  38. package/dist/cjs/exact/v1/facilitator/index.d.ts +84 -0
  39. package/dist/cjs/exact/v1/facilitator/index.js +739 -0
  40. package/dist/cjs/exact/v1/facilitator/index.js.map +1 -0
  41. package/dist/cjs/facilitator/agent-wallet.d.ts +109 -0
  42. package/dist/cjs/facilitator/agent-wallet.js +105 -0
  43. package/dist/cjs/facilitator/agent-wallet.js.map +1 -0
  44. package/dist/cjs/index.d.ts +338 -0
  45. package/dist/cjs/index.js +2860 -0
  46. package/dist/cjs/index.js.map +1 -0
  47. package/dist/cjs/permit2-DK5A8alk.d.ts +729 -0
  48. package/dist/cjs/permit2-DhJRUcgY.d.ts +729 -0
  49. package/dist/cjs/rpc-DULZzRne.d.ts +13 -0
  50. package/dist/cjs/scheme-7ehldYoO.d.ts +307 -0
  51. package/dist/cjs/scheme-BjBJzHF7.d.ts +307 -0
  52. package/dist/cjs/scheme-DWgpkDgz.d.ts +47 -0
  53. package/dist/cjs/signer-BFelv8DL.d.ts +170 -0
  54. package/dist/cjs/storage-6W5MO46W.d.ts +50 -0
  55. package/dist/cjs/storage-CHNote8s.d.ts +81 -0
  56. package/dist/cjs/storage-DjCv5IPh.d.ts +81 -0
  57. package/dist/cjs/types-CKd3Xoi1.d.ts +180 -0
  58. package/dist/cjs/types-DIt9uAUy.d.ts +180 -0
  59. package/dist/cjs/upto/client/index.d.ts +34 -0
  60. package/dist/cjs/upto/client/index.js +509 -0
  61. package/dist/cjs/upto/client/index.js.map +1 -0
  62. package/dist/cjs/upto/facilitator/index.d.ts +54 -0
  63. package/dist/cjs/upto/facilitator/index.js +1313 -0
  64. package/dist/cjs/upto/facilitator/index.js.map +1 -0
  65. package/dist/cjs/upto/server/index.d.ts +69 -0
  66. package/dist/cjs/upto/server/index.js +296 -0
  67. package/dist/cjs/upto/server/index.js.map +1 -0
  68. package/dist/cjs/v1/index.d.ts +40 -0
  69. package/dist/cjs/v1/index.js +199 -0
  70. package/dist/cjs/v1/index.js.map +1 -0
  71. package/dist/esm/auth-capture/client/index.d.mts +44 -0
  72. package/dist/esm/auth-capture/client/index.mjs +8 -0
  73. package/dist/esm/auth-capture/client/index.mjs.map +1 -0
  74. package/dist/esm/batch-settlement/client/file-storage.d.mts +47 -0
  75. package/dist/esm/batch-settlement/client/file-storage.mjs +63 -0
  76. package/dist/esm/batch-settlement/client/file-storage.mjs.map +1 -0
  77. package/dist/esm/batch-settlement/client/index.d.mts +111 -0
  78. package/dist/esm/batch-settlement/client/index.mjs +58 -0
  79. package/dist/esm/batch-settlement/client/index.mjs.map +1 -0
  80. package/dist/esm/batch-settlement/facilitator/index.d.mts +72 -0
  81. package/dist/esm/batch-settlement/facilitator/index.mjs +1252 -0
  82. package/dist/esm/batch-settlement/facilitator/index.mjs.map +1 -0
  83. package/dist/esm/batch-settlement/server/file-storage.d.mts +53 -0
  84. package/dist/esm/batch-settlement/server/file-storage.mjs +128 -0
  85. package/dist/esm/batch-settlement/server/file-storage.mjs.map +1 -0
  86. package/dist/esm/batch-settlement/server/index.d.mts +491 -0
  87. package/dist/esm/batch-settlement/server/index.mjs +1640 -0
  88. package/dist/esm/batch-settlement/server/index.mjs.map +1 -0
  89. package/dist/esm/batch-settlement/server/redis-storage.d.mts +87 -0
  90. package/dist/esm/batch-settlement/server/redis-storage.mjs +156 -0
  91. package/dist/esm/batch-settlement/server/redis-storage.mjs.map +1 -0
  92. package/dist/esm/chunk-2EUQTNJO.mjs +38 -0
  93. package/dist/esm/chunk-2EUQTNJO.mjs.map +1 -0
  94. package/dist/esm/chunk-3WZF6722.mjs +36 -0
  95. package/dist/esm/chunk-3WZF6722.mjs.map +1 -0
  96. package/dist/esm/chunk-E4Z7PNXC.mjs +275 -0
  97. package/dist/esm/chunk-E4Z7PNXC.mjs.map +1 -0
  98. package/dist/esm/chunk-GQVMVP4N.mjs +911 -0
  99. package/dist/esm/chunk-GQVMVP4N.mjs.map +1 -0
  100. package/dist/esm/chunk-H2EYJIZL.mjs +489 -0
  101. package/dist/esm/chunk-H2EYJIZL.mjs.map +1 -0
  102. package/dist/esm/chunk-H3KPLYGI.mjs +152 -0
  103. package/dist/esm/chunk-H3KPLYGI.mjs.map +1 -0
  104. package/dist/esm/chunk-HYABYUBD.mjs +432 -0
  105. package/dist/esm/chunk-HYABYUBD.mjs.map +1 -0
  106. package/dist/esm/chunk-I2DVUHM5.mjs +123 -0
  107. package/dist/esm/chunk-I2DVUHM5.mjs.map +1 -0
  108. package/dist/esm/chunk-JK7SLLF7.mjs +34 -0
  109. package/dist/esm/chunk-JK7SLLF7.mjs.map +1 -0
  110. package/dist/esm/chunk-JNT7C46S.mjs +352 -0
  111. package/dist/esm/chunk-JNT7C46S.mjs.map +1 -0
  112. package/dist/esm/chunk-MACPBXCT.mjs +415 -0
  113. package/dist/esm/chunk-MACPBXCT.mjs.map +1 -0
  114. package/dist/esm/chunk-P3QOX3QZ.mjs +113 -0
  115. package/dist/esm/chunk-P3QOX3QZ.mjs.map +1 -0
  116. package/dist/esm/chunk-QVATVA3J.mjs +47 -0
  117. package/dist/esm/chunk-QVATVA3J.mjs.map +1 -0
  118. package/dist/esm/chunk-SHJFA25H.mjs +159 -0
  119. package/dist/esm/chunk-SHJFA25H.mjs.map +1 -0
  120. package/dist/esm/chunk-TW7Z65AO.mjs +34 -0
  121. package/dist/esm/chunk-TW7Z65AO.mjs.map +1 -0
  122. package/dist/esm/chunk-U4HCGTLU.mjs +35 -0
  123. package/dist/esm/chunk-U4HCGTLU.mjs.map +1 -0
  124. package/dist/esm/chunk-VS3RYAYE.mjs +80 -0
  125. package/dist/esm/chunk-VS3RYAYE.mjs.map +1 -0
  126. package/dist/esm/chunk-W6ON4LG2.mjs +39 -0
  127. package/dist/esm/chunk-W6ON4LG2.mjs.map +1 -0
  128. package/dist/esm/chunk-XG2JLZVJ.mjs +627 -0
  129. package/dist/esm/chunk-XG2JLZVJ.mjs.map +1 -0
  130. package/dist/esm/chunk-ZCJRY5LQ.mjs +162 -0
  131. package/dist/esm/chunk-ZCJRY5LQ.mjs.map +1 -0
  132. package/dist/esm/client/agent-wallet.d.mts +69 -0
  133. package/dist/esm/client/agent-wallet.mjs +36 -0
  134. package/dist/esm/client/agent-wallet.mjs.map +1 -0
  135. package/dist/esm/exact/client/index.d.mts +63 -0
  136. package/dist/esm/exact/client/index.mjs +25 -0
  137. package/dist/esm/exact/client/index.mjs.map +1 -0
  138. package/dist/esm/exact/facilitator/index.d.mts +141 -0
  139. package/dist/esm/exact/facilitator/index.mjs +694 -0
  140. package/dist/esm/exact/facilitator/index.mjs.map +1 -0
  141. package/dist/esm/exact/server/index.d.mts +118 -0
  142. package/dist/esm/exact/server/index.mjs +153 -0
  143. package/dist/esm/exact/server/index.mjs.map +1 -0
  144. package/dist/esm/exact/v1/client/index.d.mts +38 -0
  145. package/dist/esm/exact/v1/client/index.mjs +12 -0
  146. package/dist/esm/exact/v1/client/index.mjs.map +1 -0
  147. package/dist/esm/exact/v1/facilitator/index.d.mts +84 -0
  148. package/dist/esm/exact/v1/facilitator/index.mjs +12 -0
  149. package/dist/esm/exact/v1/facilitator/index.mjs.map +1 -0
  150. package/dist/esm/facilitator/agent-wallet.d.mts +109 -0
  151. package/dist/esm/facilitator/agent-wallet.mjs +74 -0
  152. package/dist/esm/facilitator/agent-wallet.mjs.map +1 -0
  153. package/dist/esm/index.d.mts +338 -0
  154. package/dist/esm/index.mjs +144 -0
  155. package/dist/esm/index.mjs.map +1 -0
  156. package/dist/esm/permit2-DhJRUcgY.d.mts +729 -0
  157. package/dist/esm/rpc-DULZzRne.d.mts +13 -0
  158. package/dist/esm/scheme-CkNhpXrG.d.mts +307 -0
  159. package/dist/esm/scheme-D8ZbykGV.d.mts +47 -0
  160. package/dist/esm/signer-BFelv8DL.d.mts +170 -0
  161. package/dist/esm/storage-6W5MO46W.d.mts +50 -0
  162. package/dist/esm/storage-BEzTEiUr.d.mts +81 -0
  163. package/dist/esm/types-DIt9uAUy.d.mts +180 -0
  164. package/dist/esm/upto/client/index.d.mts +34 -0
  165. package/dist/esm/upto/client/index.mjs +22 -0
  166. package/dist/esm/upto/client/index.mjs.map +1 -0
  167. package/dist/esm/upto/facilitator/index.d.mts +54 -0
  168. package/dist/esm/upto/facilitator/index.mjs +507 -0
  169. package/dist/esm/upto/facilitator/index.mjs.map +1 -0
  170. package/dist/esm/upto/server/index.d.mts +69 -0
  171. package/dist/esm/upto/server/index.mjs +124 -0
  172. package/dist/esm/upto/server/index.mjs.map +1 -0
  173. package/dist/esm/v1/index.d.mts +40 -0
  174. package/dist/esm/v1/index.mjs +18 -0
  175. package/dist/esm/v1/index.mjs.map +1 -0
  176. package/package.json +250 -0
@@ -0,0 +1,2102 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/batch-settlement/facilitator/index.ts
21
+ var facilitator_exports = {};
22
+ __export(facilitator_exports, {
23
+ BatchSettlementEvmScheme: () => BatchSettlementEvmScheme
24
+ });
25
+ module.exports = __toCommonJS(facilitator_exports);
26
+
27
+ // src/batch-settlement/constants.ts
28
+ var import_viem = require("viem");
29
+ var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
30
+ var BATCH_SETTLEMENT_ADDRESS = "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003";
31
+ var ERC3009_DEPOSIT_COLLECTOR_ADDRESS = "0x4020806089470a89826cB9fB1f4059150b550004";
32
+ var PERMIT2_DEPOSIT_COLLECTOR_ADDRESS = "0x4020425FAf3B746C082C2f942b4E5159887B0005";
33
+ var MIN_WITHDRAW_DELAY = 900;
34
+ var MAX_WITHDRAW_DELAY = 2592e3;
35
+ var BATCH_SETTLEMENT_DOMAIN = {
36
+ name: "x402 Batch Settlement",
37
+ version: "1"
38
+ };
39
+ var CHANNEL_CONFIG_TYPEHASH = (0, import_viem.keccak256)(
40
+ (0, import_viem.toBytes)(
41
+ "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
42
+ )
43
+ );
44
+ var channelConfigTypes = {
45
+ ChannelConfig: [
46
+ { name: "payer", type: "address" },
47
+ { name: "payerAuthorizer", type: "address" },
48
+ { name: "receiver", type: "address" },
49
+ { name: "receiverAuthorizer", type: "address" },
50
+ { name: "token", type: "address" },
51
+ { name: "withdrawDelay", type: "uint40" },
52
+ { name: "salt", type: "bytes32" }
53
+ ]
54
+ };
55
+ var voucherTypes = {
56
+ Voucher: [
57
+ { name: "channelId", type: "bytes32" },
58
+ { name: "maxClaimableAmount", type: "uint128" }
59
+ ]
60
+ };
61
+ var refundTypes = {
62
+ Refund: [
63
+ { name: "channelId", type: "bytes32" },
64
+ { name: "nonce", type: "uint256" },
65
+ { name: "amount", type: "uint128" }
66
+ ]
67
+ };
68
+ var claimBatchTypes = {
69
+ ClaimBatch: [{ name: "claims", type: "ClaimEntry[]" }],
70
+ ClaimEntry: [
71
+ { name: "channelId", type: "bytes32" },
72
+ { name: "maxClaimableAmount", type: "uint128" },
73
+ { name: "totalClaimed", type: "uint128" }
74
+ ]
75
+ };
76
+ var receiveAuthorizationTypes = {
77
+ ReceiveWithAuthorization: [
78
+ { name: "from", type: "address" },
79
+ { name: "to", type: "address" },
80
+ { name: "value", type: "uint256" },
81
+ { name: "validAfter", type: "uint256" },
82
+ { name: "validBefore", type: "uint256" },
83
+ { name: "nonce", type: "bytes32" }
84
+ ]
85
+ };
86
+ var batchPermit2WitnessTypes = {
87
+ PermitWitnessTransferFrom: [
88
+ { name: "permitted", type: "TokenPermissions" },
89
+ { name: "spender", type: "address" },
90
+ { name: "nonce", type: "uint256" },
91
+ { name: "deadline", type: "uint256" },
92
+ { name: "witness", type: "DepositWitness" }
93
+ ],
94
+ TokenPermissions: [
95
+ { name: "token", type: "address" },
96
+ { name: "amount", type: "uint256" }
97
+ ],
98
+ DepositWitness: [{ name: "channelId", type: "bytes32" }]
99
+ };
100
+
101
+ // src/batch-settlement/types.ts
102
+ function isObject(payload) {
103
+ return typeof payload === "object" && payload !== null;
104
+ }
105
+ function isVoucherFields(payload) {
106
+ return isObject(payload) && "channelId" in payload && "maxClaimableAmount" in payload && "signature" in payload;
107
+ }
108
+ function isBatchSettlementDepositPayload(payload) {
109
+ return isObject(payload) && payload.type === "deposit" && "channelConfig" in payload && isVoucherFields(payload.voucher) && isObject(payload.deposit) && typeof payload.deposit.amount === "string" && isObject(payload.deposit.authorization);
110
+ }
111
+ function isBatchSettlementVoucherPayload(payload) {
112
+ return isObject(payload) && payload.type === "voucher" && "channelConfig" in payload && isVoucherFields(payload.voucher);
113
+ }
114
+ function isBatchSettlementRefundPayload(payload) {
115
+ return isObject(payload) && payload.type === "refund" && "channelConfig" in payload && isVoucherFields(payload.voucher);
116
+ }
117
+ function isBatchSettlementClaimPayload(payload) {
118
+ return isObject(payload) && payload.type === "claim" && "claims" in payload;
119
+ }
120
+ function isBatchSettlementSettlePayload(payload) {
121
+ return isObject(payload) && payload.type === "settle" && "receiver" in payload && "token" in payload;
122
+ }
123
+ function isBatchSettlementEnrichedRefundPayload(payload) {
124
+ return isBatchSettlementRefundPayload(payload) && "amount" in payload && "refundNonce" in payload && "claims" in payload;
125
+ }
126
+
127
+ // src/batch-settlement/facilitator/deposit.ts
128
+ var import_viem15 = require("viem");
129
+
130
+ // src/batch-settlement/abi.ts
131
+ var channelConfigComponents = [
132
+ { name: "payer", type: "address" },
133
+ { name: "payerAuthorizer", type: "address" },
134
+ { name: "receiver", type: "address" },
135
+ { name: "receiverAuthorizer", type: "address" },
136
+ { name: "token", type: "address" },
137
+ { name: "withdrawDelay", type: "uint40" },
138
+ { name: "salt", type: "bytes32" }
139
+ ];
140
+ var voucherClaimComponents = [
141
+ {
142
+ name: "voucher",
143
+ type: "tuple",
144
+ components: [
145
+ {
146
+ name: "channel",
147
+ type: "tuple",
148
+ components: channelConfigComponents
149
+ },
150
+ { name: "maxClaimableAmount", type: "uint128" }
151
+ ]
152
+ },
153
+ { name: "signature", type: "bytes" },
154
+ { name: "totalClaimed", type: "uint128" }
155
+ ];
156
+ var batchSettlementABI = [
157
+ {
158
+ type: "function",
159
+ name: "multicall",
160
+ inputs: [{ name: "data", type: "bytes[]" }],
161
+ outputs: [{ name: "results", type: "bytes[]" }],
162
+ stateMutability: "nonpayable"
163
+ },
164
+ {
165
+ type: "function",
166
+ name: "deposit",
167
+ inputs: [
168
+ { name: "config", type: "tuple", components: channelConfigComponents },
169
+ { name: "amount", type: "uint128" },
170
+ { name: "collector", type: "address" },
171
+ { name: "collectorData", type: "bytes" }
172
+ ],
173
+ outputs: [],
174
+ stateMutability: "nonpayable"
175
+ },
176
+ {
177
+ type: "function",
178
+ name: "claim",
179
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
180
+ outputs: [],
181
+ stateMutability: "nonpayable"
182
+ },
183
+ {
184
+ type: "function",
185
+ name: "claimWithSignature",
186
+ inputs: [
187
+ { name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents },
188
+ { name: "authorizerSignature", type: "bytes" }
189
+ ],
190
+ outputs: [],
191
+ stateMutability: "nonpayable"
192
+ },
193
+ {
194
+ type: "function",
195
+ name: "settle",
196
+ inputs: [
197
+ { name: "receiver", type: "address" },
198
+ { name: "token", type: "address" }
199
+ ],
200
+ outputs: [],
201
+ stateMutability: "nonpayable"
202
+ },
203
+ {
204
+ type: "function",
205
+ name: "initiateWithdraw",
206
+ inputs: [
207
+ { name: "config", type: "tuple", components: channelConfigComponents },
208
+ { name: "amount", type: "uint128" }
209
+ ],
210
+ outputs: [],
211
+ stateMutability: "nonpayable"
212
+ },
213
+ {
214
+ type: "function",
215
+ name: "finalizeWithdraw",
216
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
217
+ outputs: [],
218
+ stateMutability: "nonpayable"
219
+ },
220
+ {
221
+ type: "function",
222
+ name: "refund",
223
+ inputs: [
224
+ { name: "config", type: "tuple", components: channelConfigComponents },
225
+ { name: "amount", type: "uint128" }
226
+ ],
227
+ outputs: [],
228
+ stateMutability: "nonpayable"
229
+ },
230
+ {
231
+ type: "function",
232
+ name: "refundWithSignature",
233
+ inputs: [
234
+ { name: "config", type: "tuple", components: channelConfigComponents },
235
+ { name: "amount", type: "uint128" },
236
+ { name: "nonce", type: "uint256" },
237
+ { name: "receiverAuthorizerSignature", type: "bytes" }
238
+ ],
239
+ outputs: [],
240
+ stateMutability: "nonpayable"
241
+ },
242
+ {
243
+ type: "function",
244
+ name: "getChannelId",
245
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
246
+ outputs: [{ name: "", type: "bytes32" }],
247
+ stateMutability: "view"
248
+ },
249
+ {
250
+ type: "function",
251
+ name: "CHANNEL_CONFIG_TYPEHASH",
252
+ inputs: [],
253
+ outputs: [{ name: "", type: "bytes32" }],
254
+ stateMutability: "view"
255
+ },
256
+ {
257
+ type: "function",
258
+ name: "channels",
259
+ inputs: [{ name: "channelId", type: "bytes32" }],
260
+ outputs: [
261
+ { name: "balance", type: "uint128" },
262
+ { name: "totalClaimed", type: "uint128" }
263
+ ],
264
+ stateMutability: "view"
265
+ },
266
+ {
267
+ type: "function",
268
+ name: "pendingWithdrawals",
269
+ inputs: [{ name: "channelId", type: "bytes32" }],
270
+ outputs: [
271
+ { name: "amount", type: "uint128" },
272
+ { name: "initiatedAt", type: "uint40" }
273
+ ],
274
+ stateMutability: "view"
275
+ },
276
+ {
277
+ type: "function",
278
+ name: "receivers",
279
+ inputs: [
280
+ { name: "receiver", type: "address" },
281
+ { name: "token", type: "address" }
282
+ ],
283
+ outputs: [
284
+ { name: "totalClaimed", type: "uint128" },
285
+ { name: "totalSettled", type: "uint128" }
286
+ ],
287
+ stateMutability: "view"
288
+ },
289
+ {
290
+ type: "function",
291
+ name: "getVoucherDigest",
292
+ inputs: [
293
+ { name: "channelId", type: "bytes32" },
294
+ { name: "maxClaimableAmount", type: "uint128" }
295
+ ],
296
+ outputs: [{ name: "", type: "bytes32" }],
297
+ stateMutability: "view"
298
+ },
299
+ {
300
+ type: "function",
301
+ name: "getRefundDigest",
302
+ inputs: [
303
+ { name: "channelId", type: "bytes32" },
304
+ { name: "nonce", type: "uint256" },
305
+ { name: "amount", type: "uint128" }
306
+ ],
307
+ outputs: [{ name: "", type: "bytes32" }],
308
+ stateMutability: "view"
309
+ },
310
+ {
311
+ type: "function",
312
+ name: "refundNonce",
313
+ inputs: [{ name: "channelId", type: "bytes32" }],
314
+ outputs: [{ name: "", type: "uint256" }],
315
+ stateMutability: "view"
316
+ },
317
+ {
318
+ type: "function",
319
+ name: "getClaimBatchDigest",
320
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
321
+ outputs: [{ name: "", type: "bytes32" }],
322
+ stateMutability: "view"
323
+ },
324
+ {
325
+ type: "event",
326
+ name: "Settled",
327
+ inputs: [
328
+ { name: "receiver", type: "address", indexed: true },
329
+ { name: "token", type: "address", indexed: true },
330
+ { name: "sender", type: "address", indexed: true },
331
+ { name: "amount", type: "uint128", indexed: false }
332
+ ],
333
+ anonymous: false
334
+ }
335
+ ];
336
+ var erc20BalanceOfABI = [
337
+ {
338
+ type: "function",
339
+ name: "balanceOf",
340
+ inputs: [{ name: "account", type: "address" }],
341
+ outputs: [{ name: "", type: "uint256" }],
342
+ stateMutability: "view"
343
+ }
344
+ ];
345
+
346
+ // src/utils.ts
347
+ var import_viem2 = require("viem");
348
+ function getEvmChainId(network) {
349
+ if (network.startsWith("eip155:")) {
350
+ const idStr = network.split(":")[1];
351
+ const chainId = parseInt(idStr, 10);
352
+ if (isNaN(chainId)) {
353
+ throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
354
+ }
355
+ return chainId;
356
+ }
357
+ throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
358
+ }
359
+
360
+ // src/multicall.ts
361
+ var import_viem3 = require("viem");
362
+ var MULTICALL3_ADDRESS = "0xcA11bde05977b3631167028862bE2a173976CA11";
363
+ var multicall3ABI = [
364
+ {
365
+ inputs: [
366
+ { name: "requireSuccess", type: "bool" },
367
+ {
368
+ name: "calls",
369
+ type: "tuple[]",
370
+ components: [
371
+ { name: "target", type: "address" },
372
+ { name: "callData", type: "bytes" }
373
+ ]
374
+ }
375
+ ],
376
+ name: "tryAggregate",
377
+ outputs: [
378
+ {
379
+ name: "returnData",
380
+ type: "tuple[]",
381
+ components: [
382
+ { name: "success", type: "bool" },
383
+ { name: "returnData", type: "bytes" }
384
+ ]
385
+ }
386
+ ],
387
+ stateMutability: "payable",
388
+ type: "function"
389
+ }
390
+ ];
391
+ async function multicall(readContract, calls) {
392
+ const aggregateCalls = calls.map((call) => {
393
+ if ("callData" in call) {
394
+ return { target: call.address, callData: call.callData };
395
+ }
396
+ const callData = (0, import_viem3.encodeFunctionData)({
397
+ abi: call.abi,
398
+ functionName: call.functionName,
399
+ args: call.args
400
+ });
401
+ return { target: call.address, callData };
402
+ });
403
+ const rawResults = await readContract({
404
+ address: MULTICALL3_ADDRESS,
405
+ abi: multicall3ABI,
406
+ functionName: "tryAggregate",
407
+ args: [false, aggregateCalls]
408
+ });
409
+ return rawResults.map((raw, i) => {
410
+ if (!raw.success) {
411
+ return {
412
+ status: "failure",
413
+ error: new Error(`multicall: call reverted (returnData: ${raw.returnData})`)
414
+ };
415
+ }
416
+ const call = calls[i];
417
+ if ("callData" in call) {
418
+ return { status: "success", result: void 0 };
419
+ }
420
+ try {
421
+ const decoded = (0, import_viem3.decodeFunctionResult)({
422
+ abi: call.abi,
423
+ functionName: call.functionName,
424
+ data: raw.returnData
425
+ });
426
+ return { status: "success", result: decoded };
427
+ } catch (err) {
428
+ return {
429
+ status: "failure",
430
+ error: err instanceof Error ? err : new Error(String(err))
431
+ };
432
+ }
433
+ });
434
+ }
435
+
436
+ // src/batch-settlement/errors.ts
437
+ var ErrChannelNotFound = "invalid_batch_settlement_evm_channel_not_found";
438
+ var ErrTokenMismatch = "invalid_batch_settlement_evm_token_mismatch";
439
+ var ErrInvalidVoucherSignature = "invalid_batch_settlement_evm_voucher_signature";
440
+ var ErrCumulativeExceedsBalance = "invalid_batch_settlement_evm_cumulative_exceeds_balance";
441
+ var ErrCumulativeAmountBelowClaimed = "invalid_batch_settlement_evm_cumulative_below_claimed";
442
+ var ErrInsufficientBalance = "invalid_batch_settlement_evm_insufficient_balance";
443
+ var ErrDepositTransactionFailed = "invalid_batch_settlement_evm_deposit_transaction_failed";
444
+ var ErrClaimTransactionFailed = "invalid_batch_settlement_evm_claim_transaction_failed";
445
+ var ErrSettleTransactionFailed = "invalid_batch_settlement_evm_settle_transaction_failed";
446
+ var ErrInvalidScheme = "invalid_batch_settlement_evm_scheme";
447
+ var ErrNetworkMismatch = "invalid_batch_settlement_evm_network_mismatch";
448
+ var ErrMissingEip712Domain = "invalid_batch_settlement_evm_missing_eip712_domain";
449
+ var ErrValidBeforeExpired = "invalid_batch_settlement_evm_payload_authorization_valid_before";
450
+ var ErrValidAfterInFuture = "invalid_batch_settlement_evm_payload_authorization_valid_after";
451
+ var ErrInvalidReceiveAuthorizationSignature = "invalid_batch_settlement_evm_receive_authorization_signature";
452
+ var ErrErc3009AuthorizationRequired = "invalid_batch_settlement_evm_erc3009_authorization_required";
453
+ var ErrRefundTransactionFailed = "invalid_batch_settlement_evm_refund_transaction_failed";
454
+ var ErrInvalidPayloadType = "invalid_batch_settlement_evm_payload_type";
455
+ var ErrWithdrawDelayOutOfRange = "invalid_batch_settlement_evm_withdraw_delay_out_of_range";
456
+ var ErrChannelIdMismatch = "invalid_batch_settlement_evm_channel_id_mismatch";
457
+ var ErrReceiverMismatch = "invalid_batch_settlement_evm_receiver_mismatch";
458
+ var ErrReceiverAuthorizerMismatch = "invalid_batch_settlement_evm_receiver_authorizer_mismatch";
459
+ var ErrWithdrawDelayMismatch = "invalid_batch_settlement_evm_withdraw_delay_mismatch";
460
+ var ErrAuthorizerAddressMismatch = "invalid_batch_settlement_evm_authorizer_address_mismatch";
461
+ var ErrDepositSimulationFailed = "invalid_batch_settlement_evm_deposit_simulation_failed";
462
+ var ErrClaimSimulationFailed = "invalid_batch_settlement_evm_claim_simulation_failed";
463
+ var ErrSettleSimulationFailed = "invalid_batch_settlement_evm_settle_simulation_failed";
464
+ var ErrNothingToSettle = "invalid_batch_settlement_evm_nothing_to_settle";
465
+ var ErrRefundSimulationFailed = "invalid_batch_settlement_evm_refund_simulation_failed";
466
+ var ErrRpcReadFailed = "invalid_batch_settlement_evm_rpc_read_failed";
467
+ var ErrPermit2AuthorizationRequired = "invalid_batch_settlement_evm_permit2_authorization_required";
468
+ var ErrPermit2InvalidSpender = "invalid_batch_settlement_evm_permit2_invalid_spender";
469
+ var ErrPermit2AmountMismatch = "invalid_batch_settlement_evm_permit2_amount_mismatch";
470
+ var ErrPermit2DeadlineExpired = "invalid_batch_settlement_evm_permit2_deadline_expired";
471
+ var ErrPermit2InvalidSignature = "invalid_batch_settlement_evm_permit2_invalid_signature";
472
+ var ErrPermit2AllowanceRequired = "invalid_batch_settlement_evm_permit2_allowance_required";
473
+ var ErrEip2612AmountMismatch = "invalid_batch_settlement_evm_eip2612_amount_mismatch";
474
+ var ErrErc20ApprovalUnavailable = "invalid_batch_settlement_evm_erc20_approval_unavailable";
475
+ var ErrRefundNoBalance = "invalid_batch_settlement_evm_refund_no_balance";
476
+
477
+ // src/batch-settlement/facilitator/utils.ts
478
+ var import_viem5 = require("viem");
479
+
480
+ // src/batch-settlement/utils.ts
481
+ var import_viem4 = require("viem");
482
+ function computeChannelId(config, networkOrChainId) {
483
+ const chainId = typeof networkOrChainId === "number" ? networkOrChainId : getEvmChainId(networkOrChainId);
484
+ return (0, import_viem4.hashTypedData)({
485
+ domain: getBatchSettlementEip712Domain(chainId),
486
+ types: channelConfigTypes,
487
+ primaryType: "ChannelConfig",
488
+ message: {
489
+ payer: config.payer,
490
+ payerAuthorizer: config.payerAuthorizer,
491
+ receiver: config.receiver,
492
+ receiverAuthorizer: config.receiverAuthorizer,
493
+ token: config.token,
494
+ withdrawDelay: config.withdrawDelay,
495
+ salt: config.salt
496
+ }
497
+ });
498
+ }
499
+ function getBatchSettlementEip712Domain(chainId) {
500
+ return {
501
+ ...BATCH_SETTLEMENT_DOMAIN,
502
+ chainId,
503
+ verifyingContract: (0, import_viem4.getAddress)(BATCH_SETTLEMENT_ADDRESS)
504
+ };
505
+ }
506
+
507
+ // src/batch-settlement/facilitator/utils.ts
508
+ function toContractChannelConfig(config) {
509
+ return {
510
+ payer: (0, import_viem5.getAddress)(config.payer),
511
+ payerAuthorizer: (0, import_viem5.getAddress)(config.payerAuthorizer),
512
+ receiver: (0, import_viem5.getAddress)(config.receiver),
513
+ receiverAuthorizer: (0, import_viem5.getAddress)(config.receiverAuthorizer),
514
+ token: (0, import_viem5.getAddress)(config.token),
515
+ withdrawDelay: config.withdrawDelay,
516
+ salt: config.salt
517
+ };
518
+ }
519
+ function erc3009AuthorizationTimeInvalidReason(validAfter, validBefore) {
520
+ const now = Math.floor(Date.now() / 1e3);
521
+ if (validBefore < BigInt(now + 6)) return ErrValidBeforeExpired;
522
+ if (validAfter > BigInt(now)) return ErrValidAfterInFuture;
523
+ return void 0;
524
+ }
525
+ async function verifyBatchSettlementVoucherTypedData(signer, params, chainId) {
526
+ const domain = getBatchSettlementEip712Domain(chainId);
527
+ const message = {
528
+ channelId: params.channelId,
529
+ maxClaimableAmount: BigInt(params.maxClaimableAmount)
530
+ };
531
+ const zeroAddress = "0x0000000000000000000000000000000000000000";
532
+ if (params.payerAuthorizer !== zeroAddress) {
533
+ return (0, import_viem5.verifyTypedData)({
534
+ address: (0, import_viem5.getAddress)(params.payerAuthorizer),
535
+ domain,
536
+ types: voucherTypes,
537
+ primaryType: "Voucher",
538
+ message,
539
+ signature: params.signature
540
+ });
541
+ }
542
+ return signer.verifyTypedData({
543
+ address: (0, import_viem5.getAddress)(params.payer),
544
+ domain,
545
+ types: voucherTypes,
546
+ primaryType: "Voucher",
547
+ message,
548
+ signature: params.signature
549
+ });
550
+ }
551
+ function validateChannelConfig(config, channelId, requirements) {
552
+ const computedId = computeChannelId(config, requirements.network);
553
+ if (computedId.toLowerCase() !== channelId.toLowerCase()) {
554
+ return ErrChannelIdMismatch;
555
+ }
556
+ if ((0, import_viem5.getAddress)(config.receiver) !== (0, import_viem5.getAddress)(requirements.payTo)) {
557
+ return ErrReceiverMismatch;
558
+ }
559
+ const extra = requirements.extra;
560
+ const requiredReceiverAuthorizer = extra?.receiverAuthorizer;
561
+ if (!requiredReceiverAuthorizer || (0, import_viem5.getAddress)(requiredReceiverAuthorizer) === "0x0000000000000000000000000000000000000000" || (0, import_viem5.getAddress)(config.receiverAuthorizer) !== (0, import_viem5.getAddress)(requiredReceiverAuthorizer)) {
562
+ return ErrReceiverAuthorizerMismatch;
563
+ }
564
+ if ((0, import_viem5.getAddress)(config.token) !== (0, import_viem5.getAddress)(requirements.asset)) {
565
+ return ErrTokenMismatch;
566
+ }
567
+ if (extra?.withdrawDelay !== void 0 && config.withdrawDelay !== Number(extra.withdrawDelay)) {
568
+ return ErrWithdrawDelayMismatch;
569
+ }
570
+ if (config.withdrawDelay < MIN_WITHDRAW_DELAY || config.withdrawDelay > MAX_WITHDRAW_DELAY) {
571
+ return ErrWithdrawDelayOutOfRange;
572
+ }
573
+ return void 0;
574
+ }
575
+ async function readChannelState(signer, channelId) {
576
+ const target = (0, import_viem5.getAddress)(BATCH_SETTLEMENT_ADDRESS);
577
+ const mcResults = await multicall(signer.readContract.bind(signer), [
578
+ { address: target, abi: batchSettlementABI, functionName: "channels", args: [channelId] },
579
+ {
580
+ address: target,
581
+ abi: batchSettlementABI,
582
+ functionName: "pendingWithdrawals",
583
+ args: [channelId]
584
+ },
585
+ { address: target, abi: batchSettlementABI, functionName: "refundNonce", args: [channelId] }
586
+ ]);
587
+ const [chRes, wdRes, rnRes] = mcResults;
588
+ if (chRes.status === "failure" || wdRes.status === "failure" || rnRes.status === "failure") {
589
+ throw new Error(`${ErrRpcReadFailed}: multicall returned failure for ${channelId}`);
590
+ }
591
+ const [balance, totalClaimed] = chRes.result;
592
+ const [, wdInitiatedAt] = wdRes.result;
593
+ const refundNonce = rnRes.result;
594
+ return { balance, totalClaimed, withdrawRequestedAt: Number(wdInitiatedAt), refundNonce };
595
+ }
596
+
597
+ // src/batch-settlement/facilitator/deposit-eip3009.ts
598
+ var import_viem7 = require("viem");
599
+
600
+ // src/batch-settlement/encoding.ts
601
+ var import_viem6 = require("viem");
602
+ function buildErc3009DepositNonce(channelId, salt) {
603
+ return (0, import_viem6.keccak256)(
604
+ (0, import_viem6.encodeAbiParameters)([{ type: "bytes32" }, { type: "uint256" }], [channelId, BigInt(salt)])
605
+ );
606
+ }
607
+ function buildErc3009CollectorData(validAfter, validBefore, salt, signature) {
608
+ return (0, import_viem6.encodeAbiParameters)(
609
+ [{ type: "uint256" }, { type: "uint256" }, { type: "uint256" }, { type: "bytes" }],
610
+ [BigInt(validAfter), BigInt(validBefore), BigInt(salt), signature]
611
+ );
612
+ }
613
+ function buildEip2612PermitData(params) {
614
+ return (0, import_viem6.encodeAbiParameters)(
615
+ [
616
+ { type: "uint256" },
617
+ { type: "uint256" },
618
+ { type: "uint8" },
619
+ { type: "bytes32" },
620
+ { type: "bytes32" }
621
+ ],
622
+ [BigInt(params.value), BigInt(params.deadline), params.v, params.r, params.s]
623
+ );
624
+ }
625
+ function buildPermit2CollectorData(nonce, deadline, permit2Signature, eip2612PermitData = "0x") {
626
+ return (0, import_viem6.encodeAbiParameters)(
627
+ [{ type: "uint256" }, { type: "uint256" }, { type: "bytes" }, { type: "bytes" }],
628
+ [BigInt(nonce), BigInt(deadline), permit2Signature, eip2612PermitData]
629
+ );
630
+ }
631
+
632
+ // src/batch-settlement/facilitator/deposit-eip3009.ts
633
+ function getEip3009DepositCollectorAddress() {
634
+ return (0, import_viem7.getAddress)(ERC3009_DEPOSIT_COLLECTOR_ADDRESS);
635
+ }
636
+ function buildEip3009DepositCollectorData(payload) {
637
+ const auth = payload.deposit.authorization.erc3009Authorization;
638
+ if (!auth) {
639
+ throw new Error(ErrErc3009AuthorizationRequired);
640
+ }
641
+ const { signature } = (0, import_viem7.parseErc6492Signature)(auth.signature);
642
+ return buildErc3009CollectorData(auth.validAfter, auth.validBefore, auth.salt, signature);
643
+ }
644
+ async function verifyEip3009DepositAuthorization(signer, payload, requirements, chainId) {
645
+ const { deposit, voucher } = payload;
646
+ const payer = payload.channelConfig.payer;
647
+ const auth = deposit.authorization.erc3009Authorization;
648
+ if (!auth) {
649
+ return { isValid: false, invalidReason: ErrErc3009AuthorizationRequired, payer };
650
+ }
651
+ const extra = requirements.extra;
652
+ if (!extra?.name || !extra?.version) {
653
+ return { isValid: false, invalidReason: ErrMissingEip712Domain, payer };
654
+ }
655
+ const validAfter = BigInt(auth.validAfter);
656
+ const validBefore = BigInt(auth.validBefore);
657
+ const timeInvalid = erc3009AuthorizationTimeInvalidReason(validAfter, validBefore);
658
+ if (timeInvalid) {
659
+ return { isValid: false, invalidReason: timeInvalid, payer };
660
+ }
661
+ const erc3009Nonce = buildErc3009DepositNonce(voucher.channelId, auth.salt);
662
+ const receiveAuthOk = await verifyReceiveAuth(signer, {
663
+ payer,
664
+ asset: requirements.asset,
665
+ name: extra.name,
666
+ version: extra.version,
667
+ chainId,
668
+ amount: deposit.amount,
669
+ validAfter,
670
+ validBefore,
671
+ nonce: erc3009Nonce,
672
+ signature: auth.signature
673
+ });
674
+ if (!receiveAuthOk) {
675
+ return { isValid: false, invalidReason: ErrInvalidReceiveAuthorizationSignature, payer };
676
+ }
677
+ return null;
678
+ }
679
+ async function verifyReceiveAuth(signer, params) {
680
+ try {
681
+ return await signer.verifyTypedData({
682
+ address: (0, import_viem7.getAddress)(params.payer),
683
+ domain: {
684
+ name: params.name,
685
+ version: params.version,
686
+ chainId: params.chainId,
687
+ verifyingContract: (0, import_viem7.getAddress)(params.asset)
688
+ },
689
+ types: receiveAuthorizationTypes,
690
+ primaryType: "ReceiveWithAuthorization",
691
+ message: {
692
+ from: (0, import_viem7.getAddress)(params.payer),
693
+ to: (0, import_viem7.getAddress)(ERC3009_DEPOSIT_COLLECTOR_ADDRESS),
694
+ value: BigInt(params.amount),
695
+ validAfter: params.validAfter,
696
+ validBefore: params.validBefore,
697
+ nonce: params.nonce
698
+ },
699
+ signature: params.signature
700
+ });
701
+ } catch {
702
+ return false;
703
+ }
704
+ }
705
+
706
+ // src/batch-settlement/facilitator/deposit-permit2.ts
707
+ var import_viem14 = require("viem");
708
+
709
+ // src/exact/extensions.ts
710
+ var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
711
+ var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
712
+ function _extractInfo(payload, extensionKey) {
713
+ const extensions = payload.extensions;
714
+ if (!extensions) return null;
715
+ const extension = extensions[extensionKey];
716
+ if (!extension?.info) return null;
717
+ return extension.info;
718
+ }
719
+ function extractEip2612GasSponsoringInfo(payload) {
720
+ const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);
721
+ if (!info) return null;
722
+ if (!info.from || !info.asset || !info.spender || !info.amount || !info.nonce || !info.deadline || !info.signature || !info.version) {
723
+ return null;
724
+ }
725
+ return info;
726
+ }
727
+ function validateEip2612GasSponsoringInfo(info) {
728
+ const addressPattern = /^0x[a-fA-F0-9]{40}$/;
729
+ const numericPattern = /^[0-9]+$/;
730
+ const hexPattern = /^0x[a-fA-F0-9]+$/;
731
+ const versionPattern = /^[0-9]+(\.[0-9]+)*$/;
732
+ return addressPattern.test(info.from) && addressPattern.test(info.asset) && addressPattern.test(info.spender) && numericPattern.test(info.amount) && numericPattern.test(info.nonce) && numericPattern.test(info.deadline) && hexPattern.test(info.signature) && versionPattern.test(info.version);
733
+ }
734
+ function extractErc20ApprovalGasSponsoringInfo(payload) {
735
+ const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);
736
+ if (!info) return null;
737
+ if (!info.from || !info.asset || !info.spender || !info.amount || !info.signedTransaction || !info.version) {
738
+ return null;
739
+ }
740
+ return info;
741
+ }
742
+ function validateErc20ApprovalGasSponsoringInfo(info) {
743
+ const addressPattern = /^0x[a-fA-F0-9]{40}$/;
744
+ const numericPattern = /^[0-9]+$/;
745
+ const hexPattern = /^0x[a-fA-F0-9]+$/;
746
+ const versionPattern = /^[0-9]+(\.[0-9]+)*$/;
747
+ return addressPattern.test(info.from) && addressPattern.test(info.asset) && addressPattern.test(info.spender) && numericPattern.test(info.amount) && hexPattern.test(info.signedTransaction) && versionPattern.test(info.version);
748
+ }
749
+ function resolveErc20ApprovalExtensionSigner(extension, network) {
750
+ if (!extension) return void 0;
751
+ return extension.signerForNetwork?.(network) ?? extension.signer;
752
+ }
753
+
754
+ // src/shared/extensions/gasSponsoring.ts
755
+ var import_viem11 = require("viem");
756
+
757
+ // src/constants.ts
758
+ var erc20ApproveAbi = [
759
+ {
760
+ type: "function",
761
+ name: "approve",
762
+ inputs: [
763
+ { name: "spender", type: "address" },
764
+ { name: "amount", type: "uint256" }
765
+ ],
766
+ outputs: [{ type: "bool" }],
767
+ stateMutability: "nonpayable"
768
+ }
769
+ ];
770
+ var erc20AllowanceAbi = [
771
+ {
772
+ type: "function",
773
+ name: "allowance",
774
+ inputs: [
775
+ { name: "owner", type: "address" },
776
+ { name: "spender", type: "address" }
777
+ ],
778
+ outputs: [{ type: "uint256" }],
779
+ stateMutability: "view"
780
+ }
781
+ ];
782
+ var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
783
+
784
+ // src/exact/client/eip2612.ts
785
+ var import_viem8 = require("viem");
786
+
787
+ // src/exact/client/erc20approval.ts
788
+ var import_viem9 = require("viem");
789
+
790
+ // src/shared/rpc.ts
791
+ var import_viem10 = require("viem");
792
+
793
+ // src/shared/extensions/builderCode.ts
794
+ var BUILDER_CODE_KEY = "builder-code";
795
+ var BUILDER_CODE_RESOLVER = async (context, ctx) => {
796
+ const ext = context.getExtension(BUILDER_CODE_KEY);
797
+ if (!ext?.buildDataSuffix) {
798
+ return void 0;
799
+ }
800
+ return ext.buildDataSuffix(ctx);
801
+ };
802
+ var DATA_SUFFIX_RESOLVERS = [BUILDER_CODE_RESOLVER];
803
+ async function resolveDataSuffix(context, ctx) {
804
+ if (!context) {
805
+ return void 0;
806
+ }
807
+ const parts = [];
808
+ for (const resolver of DATA_SUFFIX_RESOLVERS) {
809
+ const suffix = await resolver(context, ctx);
810
+ if (suffix && suffix !== "0x" && suffix.length > 2) {
811
+ parts.push(suffix);
812
+ }
813
+ }
814
+ if (parts.length === 0) {
815
+ return void 0;
816
+ }
817
+ if (parts.length === 1) {
818
+ return parts[0];
819
+ }
820
+ return parts.reduce((acc, part, index) => {
821
+ if (index === 0) {
822
+ return part;
823
+ }
824
+ const stripped = part.startsWith("0x") ? part.slice(2) : part;
825
+ return `${acc}${stripped}`;
826
+ });
827
+ }
828
+ function appendDataSuffix(calldata, suffix) {
829
+ if (!suffix || suffix === "0x" || suffix.length <= 2) {
830
+ return calldata;
831
+ }
832
+ const suffixHex = suffix.startsWith("0x") ? suffix.slice(2) : suffix;
833
+ return `${calldata}${suffixHex}`;
834
+ }
835
+
836
+ // src/shared/erc20approval.ts
837
+ var import_viem12 = require("viem");
838
+
839
+ // src/exact/facilitator/errors.ts
840
+ var ErrErc20ApprovalInvalidFormat = "invalid_erc20_approval_extension_format";
841
+ var ErrErc20ApprovalFromMismatch = "erc20_approval_from_mismatch";
842
+ var ErrErc20ApprovalAssetMismatch = "erc20_approval_asset_mismatch";
843
+ var ErrErc20ApprovalSpenderNotPermit2 = "erc20_approval_spender_not_permit2";
844
+ var ErrErc20ApprovalTxWrongTarget = "erc20_approval_tx_wrong_target";
845
+ var ErrErc20ApprovalTxWrongSelector = "erc20_approval_tx_wrong_selector";
846
+ var ErrErc20ApprovalTxWrongSpender = "erc20_approval_tx_wrong_spender";
847
+ var ErrErc20ApprovalTxInvalidCalldata = "erc20_approval_tx_invalid_calldata";
848
+ var ErrErc20ApprovalTxSignerMismatch = "erc20_approval_tx_signer_mismatch";
849
+ var ErrErc20ApprovalTxInvalidSignature = "erc20_approval_tx_invalid_signature";
850
+ var ErrErc20ApprovalTxParseFailed = "erc20_approval_tx_parse_failed";
851
+ var ErrInvalidEip2612ExtensionFormat = "invalid_eip2612_extension_format";
852
+ var ErrEip2612FromMismatch = "eip2612_from_mismatch";
853
+ var ErrEip2612AssetMismatch = "eip2612_asset_mismatch";
854
+ var ErrEip2612SpenderNotPermit2 = "eip2612_spender_not_permit2";
855
+ var ErrEip2612DeadlineExpired = "eip2612_deadline_expired";
856
+
857
+ // src/shared/erc20approval.ts
858
+ var APPROVE_SELECTOR = "0x095ea7b3";
859
+ async function validateErc20ApprovalForPayment(info, payer, tokenAddress) {
860
+ if (!validateErc20ApprovalGasSponsoringInfo(info)) {
861
+ return {
862
+ isValid: false,
863
+ invalidReason: ErrErc20ApprovalInvalidFormat,
864
+ invalidMessage: "ERC-20 approval extension info failed schema validation"
865
+ };
866
+ }
867
+ if ((0, import_viem12.getAddress)(info.from) !== (0, import_viem12.getAddress)(payer)) {
868
+ return {
869
+ isValid: false,
870
+ invalidReason: ErrErc20ApprovalFromMismatch,
871
+ invalidMessage: `Expected from=${payer}, got ${info.from}`
872
+ };
873
+ }
874
+ if ((0, import_viem12.getAddress)(info.asset) !== tokenAddress) {
875
+ return {
876
+ isValid: false,
877
+ invalidReason: ErrErc20ApprovalAssetMismatch,
878
+ invalidMessage: `Expected asset=${tokenAddress}, got ${info.asset}`
879
+ };
880
+ }
881
+ if ((0, import_viem12.getAddress)(info.spender) !== (0, import_viem12.getAddress)(PERMIT2_ADDRESS)) {
882
+ return {
883
+ isValid: false,
884
+ invalidReason: ErrErc20ApprovalSpenderNotPermit2,
885
+ invalidMessage: `Expected spender=${PERMIT2_ADDRESS}, got ${info.spender}`
886
+ };
887
+ }
888
+ try {
889
+ const serializedTx = info.signedTransaction;
890
+ const tx = (0, import_viem12.parseTransaction)(serializedTx);
891
+ if (!tx.to || (0, import_viem12.getAddress)(tx.to) !== tokenAddress) {
892
+ return {
893
+ isValid: false,
894
+ invalidReason: ErrErc20ApprovalTxWrongTarget,
895
+ invalidMessage: `Transaction targets ${tx.to ?? "null"}, expected ${tokenAddress}`
896
+ };
897
+ }
898
+ const data = tx.data ?? "0x";
899
+ if (!data.startsWith(APPROVE_SELECTOR)) {
900
+ return {
901
+ isValid: false,
902
+ invalidReason: ErrErc20ApprovalTxWrongSelector,
903
+ invalidMessage: `Transaction calldata does not start with approve() selector ${APPROVE_SELECTOR}`
904
+ };
905
+ }
906
+ try {
907
+ const decoded = (0, import_viem12.decodeFunctionData)({
908
+ abi: erc20ApproveAbi,
909
+ data
910
+ });
911
+ const calldataSpender = (0, import_viem12.getAddress)(decoded.args[0]);
912
+ if (calldataSpender !== (0, import_viem12.getAddress)(PERMIT2_ADDRESS)) {
913
+ return {
914
+ isValid: false,
915
+ invalidReason: ErrErc20ApprovalTxWrongSpender,
916
+ invalidMessage: `approve() spender is ${calldataSpender}, expected Permit2 ${PERMIT2_ADDRESS}`
917
+ };
918
+ }
919
+ } catch {
920
+ return {
921
+ isValid: false,
922
+ invalidReason: ErrErc20ApprovalTxInvalidCalldata,
923
+ invalidMessage: "Failed to decode approve() calldata from the signed transaction"
924
+ };
925
+ }
926
+ try {
927
+ const recoveredAddress = await (0, import_viem12.recoverTransactionAddress)({
928
+ serializedTransaction: serializedTx
929
+ });
930
+ if ((0, import_viem12.getAddress)(recoveredAddress) !== (0, import_viem12.getAddress)(payer)) {
931
+ return {
932
+ isValid: false,
933
+ invalidReason: ErrErc20ApprovalTxSignerMismatch,
934
+ invalidMessage: `Transaction signed by ${recoveredAddress}, expected payer ${payer}`
935
+ };
936
+ }
937
+ } catch {
938
+ return {
939
+ isValid: false,
940
+ invalidReason: ErrErc20ApprovalTxInvalidSignature,
941
+ invalidMessage: "Failed to recover signer from the signed transaction"
942
+ };
943
+ }
944
+ } catch {
945
+ return {
946
+ isValid: false,
947
+ invalidReason: ErrErc20ApprovalTxParseFailed,
948
+ invalidMessage: "Failed to parse the signed transaction"
949
+ };
950
+ }
951
+ return { isValid: true };
952
+ }
953
+
954
+ // src/shared/permit2.ts
955
+ var import_viem13 = require("viem");
956
+ function validateEip2612PermitForPayment(info, payer, tokenAddress) {
957
+ if (!validateEip2612GasSponsoringInfo(info)) {
958
+ return { isValid: false, invalidReason: ErrInvalidEip2612ExtensionFormat };
959
+ }
960
+ if ((0, import_viem13.getAddress)(info.from) !== (0, import_viem13.getAddress)(payer)) {
961
+ return { isValid: false, invalidReason: ErrEip2612FromMismatch };
962
+ }
963
+ if ((0, import_viem13.getAddress)(info.asset) !== tokenAddress) {
964
+ return { isValid: false, invalidReason: ErrEip2612AssetMismatch };
965
+ }
966
+ if ((0, import_viem13.getAddress)(info.spender) !== (0, import_viem13.getAddress)(PERMIT2_ADDRESS)) {
967
+ return { isValid: false, invalidReason: ErrEip2612SpenderNotPermit2 };
968
+ }
969
+ const now = Math.floor(Date.now() / 1e3);
970
+ if (BigInt(info.deadline) < BigInt(now + 6)) {
971
+ return { isValid: false, invalidReason: ErrEip2612DeadlineExpired };
972
+ }
973
+ return { isValid: true };
974
+ }
975
+ function splitEip2612Signature(signature) {
976
+ const sig = signature.startsWith("0x") ? signature.slice(2) : signature;
977
+ if (sig.length !== 130) {
978
+ throw new Error(
979
+ `invalid EIP-2612 signature length: expected 65 bytes (130 hex chars), got ${sig.length / 2} bytes`
980
+ );
981
+ }
982
+ const r = `0x${sig.slice(0, 64)}`;
983
+ const s = `0x${sig.slice(64, 128)}`;
984
+ const v = parseInt(sig.slice(128, 130), 16);
985
+ return { v, r, s };
986
+ }
987
+
988
+ // src/batch-settlement/facilitator/deposit-permit2.ts
989
+ function getPermit2DepositCollectorAddress() {
990
+ return (0, import_viem14.getAddress)(PERMIT2_DEPOSIT_COLLECTOR_ADDRESS);
991
+ }
992
+ function buildPermit2DepositCollectorData(payload, eip2612PermitData = "0x") {
993
+ const auth = payload.deposit.authorization.permit2Authorization;
994
+ if (!auth) {
995
+ throw new Error(ErrPermit2AuthorizationRequired);
996
+ }
997
+ const { signature } = (0, import_viem14.parseErc6492Signature)(auth.signature);
998
+ return buildPermit2CollectorData(auth.nonce, auth.deadline, signature, eip2612PermitData);
999
+ }
1000
+ async function verifyPermit2DepositAuthorization(signer, payment, payload, requirements, chainId, context) {
1001
+ const authResult = await verifyPermit2TypedData(signer, payload, requirements, chainId);
1002
+ if (authResult) {
1003
+ return authResult;
1004
+ }
1005
+ const branchResult = await resolvePermit2DepositBranch(
1006
+ signer,
1007
+ payment,
1008
+ payload,
1009
+ requirements,
1010
+ context
1011
+ );
1012
+ if ("isValid" in branchResult) {
1013
+ return branchResult;
1014
+ }
1015
+ if (branchResult.kind !== "erc20Approval" || !branchResult.extensionSigner.simulateTransactions) {
1016
+ return null;
1017
+ }
1018
+ const ok = await branchResult.extensionSigner.simulateTransactions([
1019
+ branchResult.signedTransaction,
1020
+ buildDepositTransaction(payload, branchResult.collectorData)
1021
+ ]);
1022
+ if (!ok) {
1023
+ return {
1024
+ isValid: false,
1025
+ invalidReason: ErrDepositSimulationFailed,
1026
+ payer: payload.channelConfig.payer
1027
+ };
1028
+ }
1029
+ return null;
1030
+ }
1031
+ async function resolvePermit2DepositBranch(signer, payment, payload, requirements, context) {
1032
+ const payer = payload.channelConfig.payer;
1033
+ const tokenAddress = (0, import_viem14.getAddress)(requirements.asset);
1034
+ const eip2612Info = extractEip2612GasSponsoringInfo(payment);
1035
+ if (eip2612Info) {
1036
+ const result = validateBatchEip2612Permit(
1037
+ eip2612Info,
1038
+ payer,
1039
+ tokenAddress,
1040
+ payload.deposit.amount
1041
+ );
1042
+ if (!result.isValid) {
1043
+ return { isValid: false, invalidReason: result.invalidReason, payer };
1044
+ }
1045
+ const { v, r, s } = splitEip2612Signature(eip2612Info.signature);
1046
+ return {
1047
+ kind: "eip2612",
1048
+ collectorData: buildPermit2DepositCollectorData(
1049
+ payload,
1050
+ buildEip2612PermitData({
1051
+ value: eip2612Info.amount,
1052
+ deadline: eip2612Info.deadline,
1053
+ v,
1054
+ r,
1055
+ s
1056
+ })
1057
+ )
1058
+ };
1059
+ }
1060
+ const erc20Info = extractErc20ApprovalGasSponsoringInfo(payment);
1061
+ if (erc20Info) {
1062
+ const extensionSigner = resolveErc20ApprovalExtensionSigner(
1063
+ context?.getExtension(
1064
+ ERC20_APPROVAL_GAS_SPONSORING_KEY
1065
+ ),
1066
+ requirements.network
1067
+ );
1068
+ if (!extensionSigner) {
1069
+ return { isValid: false, invalidReason: ErrErc20ApprovalUnavailable, payer };
1070
+ }
1071
+ const result = await validateErc20ApprovalForPayment(erc20Info, payer, tokenAddress);
1072
+ if (!result.isValid) {
1073
+ return {
1074
+ isValid: false,
1075
+ invalidReason: result.invalidReason,
1076
+ invalidMessage: result.invalidMessage,
1077
+ payer
1078
+ };
1079
+ }
1080
+ return {
1081
+ kind: "erc20Approval",
1082
+ collectorData: buildPermit2DepositCollectorData(payload),
1083
+ signedTransaction: erc20Info.signedTransaction,
1084
+ extensionSigner
1085
+ };
1086
+ }
1087
+ try {
1088
+ const allowance = await signer.readContract({
1089
+ address: tokenAddress,
1090
+ abi: erc20AllowanceAbi,
1091
+ functionName: "allowance",
1092
+ args: [payer, PERMIT2_ADDRESS]
1093
+ });
1094
+ if (allowance < BigInt(payload.deposit.amount)) {
1095
+ return { isValid: false, invalidReason: ErrPermit2AllowanceRequired, payer };
1096
+ }
1097
+ } catch {
1098
+ return { isValid: false, invalidReason: ErrPermit2AllowanceRequired, payer };
1099
+ }
1100
+ return {
1101
+ kind: "standard",
1102
+ collectorData: buildPermit2DepositCollectorData(payload)
1103
+ };
1104
+ }
1105
+ function buildDepositTransaction(payload, collectorData, dataSuffix) {
1106
+ const data = (0, import_viem14.encodeFunctionData)({
1107
+ abi: batchSettlementABI,
1108
+ functionName: "deposit",
1109
+ args: [
1110
+ toContractChannelConfig(payload.channelConfig),
1111
+ BigInt(payload.deposit.amount),
1112
+ getPermit2DepositCollectorAddress(),
1113
+ collectorData
1114
+ ]
1115
+ });
1116
+ return {
1117
+ to: (0, import_viem14.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1118
+ data: appendDataSuffix(data, dataSuffix),
1119
+ gas: 300000n
1120
+ };
1121
+ }
1122
+ async function verifyPermit2TypedData(signer, payload, requirements, chainId) {
1123
+ const auth = payload.deposit.authorization.permit2Authorization;
1124
+ const payer = payload.channelConfig.payer;
1125
+ if (!auth) {
1126
+ return { isValid: false, invalidReason: ErrPermit2AuthorizationRequired, payer };
1127
+ }
1128
+ if ((0, import_viem14.getAddress)(auth.from) !== (0, import_viem14.getAddress)(payer)) {
1129
+ return { isValid: false, invalidReason: ErrPermit2InvalidSignature, payer };
1130
+ }
1131
+ if ((0, import_viem14.getAddress)(auth.spender) !== getPermit2DepositCollectorAddress()) {
1132
+ return { isValid: false, invalidReason: ErrPermit2InvalidSpender, payer };
1133
+ }
1134
+ if ((0, import_viem14.getAddress)(auth.permitted.token) !== (0, import_viem14.getAddress)(requirements.asset)) {
1135
+ return { isValid: false, invalidReason: ErrTokenMismatch, payer };
1136
+ }
1137
+ if (BigInt(auth.permitted.amount) !== BigInt(payload.deposit.amount)) {
1138
+ return { isValid: false, invalidReason: ErrPermit2AmountMismatch, payer };
1139
+ }
1140
+ if (auth.witness.channelId !== payload.voucher.channelId) {
1141
+ return { isValid: false, invalidReason: ErrChannelIdMismatch, payer };
1142
+ }
1143
+ const now = Math.floor(Date.now() / 1e3);
1144
+ if (BigInt(auth.deadline) < BigInt(now + 6)) {
1145
+ return { isValid: false, invalidReason: ErrPermit2DeadlineExpired, payer };
1146
+ }
1147
+ try {
1148
+ const ok = await signer.verifyTypedData({
1149
+ address: (0, import_viem14.getAddress)(auth.from),
1150
+ domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
1151
+ types: batchPermit2WitnessTypes,
1152
+ primaryType: "PermitWitnessTransferFrom",
1153
+ message: {
1154
+ permitted: {
1155
+ token: (0, import_viem14.getAddress)(auth.permitted.token),
1156
+ amount: BigInt(auth.permitted.amount)
1157
+ },
1158
+ spender: (0, import_viem14.getAddress)(auth.spender),
1159
+ nonce: BigInt(auth.nonce),
1160
+ deadline: BigInt(auth.deadline),
1161
+ witness: {
1162
+ channelId: auth.witness.channelId
1163
+ }
1164
+ },
1165
+ signature: auth.signature
1166
+ });
1167
+ if (!ok) {
1168
+ return { isValid: false, invalidReason: ErrPermit2InvalidSignature, payer };
1169
+ }
1170
+ } catch {
1171
+ return { isValid: false, invalidReason: ErrPermit2InvalidSignature, payer };
1172
+ }
1173
+ return null;
1174
+ }
1175
+ function validateBatchEip2612Permit(info, payer, tokenAddress, depositAmount) {
1176
+ const baseline = validateEip2612PermitForPayment(info, payer, tokenAddress);
1177
+ if (!baseline.isValid) {
1178
+ return {
1179
+ isValid: false,
1180
+ invalidReason: baseline.invalidReason ?? ErrInvalidPayloadType
1181
+ };
1182
+ }
1183
+ if (BigInt(info.amount) !== BigInt(depositAmount)) {
1184
+ return { isValid: false, invalidReason: ErrEip2612AmountMismatch };
1185
+ }
1186
+ return { isValid: true };
1187
+ }
1188
+
1189
+ // src/batch-settlement/facilitator/deposit.ts
1190
+ async function verifyDeposit(signer, payment, payload, requirements, context) {
1191
+ const payer = payload.channelConfig.payer;
1192
+ const chainId = getEvmChainId(requirements.network);
1193
+ const configErr = validateChannelConfig(
1194
+ payload.channelConfig,
1195
+ payload.voucher.channelId,
1196
+ requirements
1197
+ );
1198
+ if (configErr) {
1199
+ return { isValid: false, invalidReason: configErr, payer };
1200
+ }
1201
+ const transferMethod = resolveDepositTransferMethod(payload, requirements);
1202
+ if (transferMethod === "permit2" && !payload.deposit.authorization.permit2Authorization) {
1203
+ return { isValid: false, invalidReason: ErrInvalidPayloadType, payer };
1204
+ }
1205
+ const methodErr = transferMethod === "permit2" ? await verifyPermit2DepositAuthorization(
1206
+ signer,
1207
+ payment,
1208
+ payload,
1209
+ requirements,
1210
+ chainId,
1211
+ context
1212
+ ) : await verifyEip3009DepositAuthorization(signer, payload, requirements, chainId);
1213
+ if (methodErr) {
1214
+ return methodErr;
1215
+ }
1216
+ const shared = await verifySharedDepositState(signer, payload, requirements);
1217
+ if (!shared.ok) {
1218
+ return shared.response;
1219
+ }
1220
+ const { depositAmount, chBalance, chTotalClaimed, wdInitiatedAt, refundNonceVal } = shared;
1221
+ const execution = await resolveDepositExecution(signer, payment, payload, requirements, context);
1222
+ if ("isValid" in execution) {
1223
+ return execution;
1224
+ }
1225
+ if (!execution.skipDirectSimulation) {
1226
+ try {
1227
+ await signer.readContract({
1228
+ address: (0, import_viem15.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1229
+ abi: batchSettlementABI,
1230
+ functionName: "deposit",
1231
+ args: [
1232
+ toContractChannelConfig(payload.channelConfig),
1233
+ depositAmount,
1234
+ execution.collector,
1235
+ execution.collectorData
1236
+ ]
1237
+ });
1238
+ } catch (e) {
1239
+ return {
1240
+ isValid: false,
1241
+ invalidReason: ErrDepositSimulationFailed,
1242
+ invalidMessage: e instanceof Error ? e.message : String(e),
1243
+ payer
1244
+ };
1245
+ }
1246
+ }
1247
+ return {
1248
+ isValid: true,
1249
+ payer,
1250
+ extra: {
1251
+ channelId: payload.voucher.channelId,
1252
+ balance: chBalance.toString(),
1253
+ totalClaimed: chTotalClaimed.toString(),
1254
+ withdrawRequestedAt: Number(wdInitiatedAt),
1255
+ refundNonce: refundNonceVal.toString()
1256
+ }
1257
+ };
1258
+ }
1259
+ async function verifySharedDepositState(signer, payload, requirements) {
1260
+ const { deposit, voucher } = payload;
1261
+ const config = payload.channelConfig;
1262
+ const payer = config.payer;
1263
+ const chainId = getEvmChainId(requirements.network);
1264
+ const configErr = validateChannelConfig(config, voucher.channelId, requirements);
1265
+ if (configErr) {
1266
+ return { ok: false, response: { isValid: false, invalidReason: configErr, payer } };
1267
+ }
1268
+ const voucherOk = await verifyBatchSettlementVoucherTypedData(
1269
+ signer,
1270
+ {
1271
+ channelId: voucher.channelId,
1272
+ maxClaimableAmount: voucher.maxClaimableAmount,
1273
+ payerAuthorizer: config.payerAuthorizer,
1274
+ payer: config.payer,
1275
+ signature: voucher.signature
1276
+ },
1277
+ chainId
1278
+ );
1279
+ if (!voucherOk) {
1280
+ return {
1281
+ ok: false,
1282
+ response: { isValid: false, invalidReason: ErrInvalidVoucherSignature, payer }
1283
+ };
1284
+ }
1285
+ const mcResults = await multicall(signer.readContract.bind(signer), [
1286
+ {
1287
+ address: (0, import_viem15.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1288
+ abi: batchSettlementABI,
1289
+ functionName: "channels",
1290
+ args: [voucher.channelId]
1291
+ },
1292
+ {
1293
+ address: (0, import_viem15.getAddress)(requirements.asset),
1294
+ abi: erc20BalanceOfABI,
1295
+ functionName: "balanceOf",
1296
+ args: [(0, import_viem15.getAddress)(payer)]
1297
+ },
1298
+ {
1299
+ address: (0, import_viem15.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1300
+ abi: batchSettlementABI,
1301
+ functionName: "pendingWithdrawals",
1302
+ args: [voucher.channelId]
1303
+ },
1304
+ {
1305
+ address: (0, import_viem15.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1306
+ abi: batchSettlementABI,
1307
+ functionName: "refundNonce",
1308
+ args: [voucher.channelId]
1309
+ }
1310
+ ]);
1311
+ const [chRes, balRes, wdRes, rnRes] = mcResults;
1312
+ if (chRes.status === "failure" || balRes.status === "failure" || wdRes.status === "failure" || rnRes.status === "failure") {
1313
+ return {
1314
+ ok: false,
1315
+ response: { isValid: false, invalidReason: ErrRpcReadFailed, payer }
1316
+ };
1317
+ }
1318
+ const [chBalance, chTotalClaimed] = chRes.result;
1319
+ const payerBalance = balRes.result;
1320
+ const [, wdInitiatedAt] = wdRes.result;
1321
+ const refundNonceVal = rnRes.result;
1322
+ const depositAmount = BigInt(deposit.amount);
1323
+ if (payerBalance < depositAmount) {
1324
+ return {
1325
+ ok: false,
1326
+ response: { isValid: false, invalidReason: ErrInsufficientBalance, payer }
1327
+ };
1328
+ }
1329
+ const effectiveBalance = chBalance + depositAmount;
1330
+ const maxClaimableAmount = BigInt(voucher.maxClaimableAmount);
1331
+ if (maxClaimableAmount > effectiveBalance) {
1332
+ return {
1333
+ ok: false,
1334
+ response: { isValid: false, invalidReason: ErrCumulativeExceedsBalance, payer }
1335
+ };
1336
+ }
1337
+ if (maxClaimableAmount <= chTotalClaimed) {
1338
+ return {
1339
+ ok: false,
1340
+ response: { isValid: false, invalidReason: ErrCumulativeAmountBelowClaimed, payer }
1341
+ };
1342
+ }
1343
+ return {
1344
+ ok: true,
1345
+ chainId,
1346
+ depositAmount,
1347
+ payer,
1348
+ chBalance,
1349
+ chTotalClaimed,
1350
+ wdInitiatedAt,
1351
+ refundNonceVal
1352
+ };
1353
+ }
1354
+ async function settleDeposit(signer, payment, payload, requirements, context, dataSuffix) {
1355
+ const { deposit, voucher } = payload;
1356
+ const config = payload.channelConfig;
1357
+ const payer = config.payer;
1358
+ const verified = await verifyDeposit(signer, payment, payload, requirements, context);
1359
+ if (!verified.isValid) {
1360
+ const reason = verified.invalidReason ?? ErrInvalidPayloadType;
1361
+ return {
1362
+ success: false,
1363
+ errorReason: reason,
1364
+ errorMessage: verified.invalidMessage ?? reason,
1365
+ transaction: "",
1366
+ network: requirements.network,
1367
+ payer: verified.payer
1368
+ };
1369
+ }
1370
+ try {
1371
+ const execution = await resolveDepositExecution(
1372
+ signer,
1373
+ payment,
1374
+ payload,
1375
+ requirements,
1376
+ context
1377
+ );
1378
+ if ("isValid" in execution) {
1379
+ const reason = execution.invalidReason ?? ErrInvalidPayloadType;
1380
+ return {
1381
+ success: false,
1382
+ errorReason: reason,
1383
+ errorMessage: execution.invalidMessage ?? reason,
1384
+ transaction: "",
1385
+ network: requirements.network,
1386
+ payer: execution.payer
1387
+ };
1388
+ }
1389
+ const depositTx = buildDepositTransaction(payload, execution.collectorData, dataSuffix);
1390
+ const tx = execution.kind === "erc20Approval" ? (await execution.extensionSigner.sendTransactions([
1391
+ execution.signedTransaction,
1392
+ depositTx
1393
+ ]))[1] : await signer.writeContract({
1394
+ address: (0, import_viem15.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1395
+ abi: batchSettlementABI,
1396
+ functionName: "deposit",
1397
+ args: [
1398
+ toContractChannelConfig(config),
1399
+ BigInt(deposit.amount),
1400
+ execution.collector,
1401
+ execution.collectorData
1402
+ ],
1403
+ dataSuffix
1404
+ });
1405
+ const receipt = await signer.waitForTransactionReceipt({ hash: tx });
1406
+ if (receipt.status !== "success") {
1407
+ return {
1408
+ success: false,
1409
+ errorReason: ErrDepositTransactionFailed,
1410
+ errorMessage: `transaction reverted (receipt status ${receipt.status})`,
1411
+ transaction: tx,
1412
+ network: requirements.network,
1413
+ payer
1414
+ };
1415
+ }
1416
+ const optimisticExtra = {
1417
+ channelState: {
1418
+ channelId: voucher.channelId,
1419
+ balance: (BigInt(String(verified.extra?.balance ?? "0")) + BigInt(deposit.amount)).toString(),
1420
+ totalClaimed: String(verified.extra?.totalClaimed ?? "0"),
1421
+ withdrawRequestedAt: Number(verified.extra?.withdrawRequestedAt ?? 0),
1422
+ refundNonce: String(verified.extra?.refundNonce ?? "0")
1423
+ }
1424
+ };
1425
+ const expectedMinBalance = BigInt(optimisticExtra.channelState.balance);
1426
+ const rpcDeadline = Date.now() + 2e3;
1427
+ let postState = await readChannelState(signer, voucher.channelId);
1428
+ while (postState.balance < expectedMinBalance && Date.now() < rpcDeadline) {
1429
+ await new Promise((resolve) => setTimeout(resolve, 150));
1430
+ postState = await readChannelState(signer, voucher.channelId);
1431
+ }
1432
+ const rpcCaughtUp = postState.balance >= expectedMinBalance;
1433
+ return {
1434
+ success: true,
1435
+ transaction: tx,
1436
+ network: requirements.network,
1437
+ payer,
1438
+ amount: deposit.amount,
1439
+ extra: rpcCaughtUp ? {
1440
+ ...optimisticExtra,
1441
+ channelState: {
1442
+ channelId: voucher.channelId,
1443
+ balance: postState.balance.toString(),
1444
+ totalClaimed: postState.totalClaimed.toString(),
1445
+ withdrawRequestedAt: postState.withdrawRequestedAt,
1446
+ refundNonce: postState.refundNonce.toString()
1447
+ }
1448
+ } : optimisticExtra
1449
+ };
1450
+ } catch (e) {
1451
+ return {
1452
+ success: false,
1453
+ errorReason: ErrDepositTransactionFailed,
1454
+ errorMessage: e instanceof Error ? e.message : String(e),
1455
+ transaction: "",
1456
+ network: requirements.network,
1457
+ payer
1458
+ };
1459
+ }
1460
+ }
1461
+ async function resolveDepositExecution(signer, payment, payload, requirements, context) {
1462
+ const transferMethod = resolveDepositTransferMethod(payload, requirements);
1463
+ if (transferMethod === "eip3009") {
1464
+ return {
1465
+ kind: "direct",
1466
+ collector: getEip3009DepositCollectorAddress(),
1467
+ collectorData: buildEip3009DepositCollectorData(payload)
1468
+ };
1469
+ }
1470
+ const branch = await resolvePermit2DepositBranch(signer, payment, payload, requirements, context);
1471
+ if ("isValid" in branch) {
1472
+ return branch;
1473
+ }
1474
+ if (branch.kind === "erc20Approval") {
1475
+ return {
1476
+ kind: "erc20Approval",
1477
+ collector: getPermit2DepositCollectorAddress(),
1478
+ collectorData: branch.collectorData,
1479
+ signedTransaction: branch.signedTransaction,
1480
+ extensionSigner: branch.extensionSigner,
1481
+ skipDirectSimulation: true
1482
+ };
1483
+ }
1484
+ return {
1485
+ kind: "direct",
1486
+ collector: getPermit2DepositCollectorAddress(),
1487
+ collectorData: branch.collectorData
1488
+ };
1489
+ }
1490
+ function resolveDepositTransferMethod(payload, requirements) {
1491
+ const hinted = requirements.extra?.assetTransferMethod;
1492
+ if (hinted) {
1493
+ return hinted;
1494
+ }
1495
+ return payload.deposit.authorization.permit2Authorization ? "permit2" : "eip3009";
1496
+ }
1497
+
1498
+ // src/batch-settlement/facilitator/voucher.ts
1499
+ async function verifyVoucher(signer, payload, requirements, channelConfig) {
1500
+ const { voucher } = payload;
1501
+ const channelId = voucher.channelId;
1502
+ const chainId = getEvmChainId(requirements.network);
1503
+ const configErr = validateChannelConfig(channelConfig, channelId, requirements);
1504
+ if (configErr) {
1505
+ return { isValid: false, invalidReason: configErr, payer: channelConfig.payer };
1506
+ }
1507
+ const voucherOk = await verifyBatchSettlementVoucherTypedData(
1508
+ signer,
1509
+ {
1510
+ channelId,
1511
+ maxClaimableAmount: voucher.maxClaimableAmount,
1512
+ payerAuthorizer: channelConfig.payerAuthorizer,
1513
+ payer: channelConfig.payer,
1514
+ signature: voucher.signature
1515
+ },
1516
+ chainId
1517
+ );
1518
+ if (!voucherOk) {
1519
+ return {
1520
+ isValid: false,
1521
+ invalidReason: ErrInvalidVoucherSignature,
1522
+ payer: channelConfig.payer
1523
+ };
1524
+ }
1525
+ const state = await readChannelState(signer, channelId);
1526
+ if (state.balance === 0n) {
1527
+ return { isValid: false, invalidReason: ErrChannelNotFound, payer: channelConfig.payer };
1528
+ }
1529
+ const maxClaimableAmount = BigInt(voucher.maxClaimableAmount);
1530
+ if (maxClaimableAmount > state.balance) {
1531
+ return {
1532
+ isValid: false,
1533
+ invalidReason: ErrCumulativeExceedsBalance,
1534
+ payer: channelConfig.payer
1535
+ };
1536
+ }
1537
+ const belowClaimed = payload.type === "refund" ? maxClaimableAmount < state.totalClaimed : maxClaimableAmount <= state.totalClaimed;
1538
+ if (belowClaimed) {
1539
+ return {
1540
+ isValid: false,
1541
+ invalidReason: ErrCumulativeAmountBelowClaimed,
1542
+ payer: channelConfig.payer
1543
+ };
1544
+ }
1545
+ return {
1546
+ isValid: true,
1547
+ payer: channelConfig.payer,
1548
+ extra: {
1549
+ channelId,
1550
+ balance: state.balance.toString(),
1551
+ totalClaimed: state.totalClaimed.toString(),
1552
+ withdrawRequestedAt: state.withdrawRequestedAt,
1553
+ refundNonce: state.refundNonce.toString()
1554
+ }
1555
+ };
1556
+ }
1557
+
1558
+ // src/batch-settlement/facilitator/claim.ts
1559
+ var import_viem16 = require("viem");
1560
+
1561
+ // src/batch-settlement/authorizerSigner.ts
1562
+ async function signClaimBatch(signer, claims, network) {
1563
+ const chainId = getEvmChainId(network);
1564
+ const claimEntries = claims.map((c) => ({
1565
+ channelId: computeChannelId(c.voucher.channel, chainId),
1566
+ maxClaimableAmount: BigInt(c.voucher.maxClaimableAmount),
1567
+ totalClaimed: BigInt(c.totalClaimed)
1568
+ }));
1569
+ return signer.signTypedData({
1570
+ domain: getBatchSettlementEip712Domain(chainId),
1571
+ types: claimBatchTypes,
1572
+ primaryType: "ClaimBatch",
1573
+ message: {
1574
+ claims: claimEntries
1575
+ }
1576
+ });
1577
+ }
1578
+ async function signRefund(signer, channelId, amount, nonce, network) {
1579
+ const chainId = getEvmChainId(network);
1580
+ return signer.signTypedData({
1581
+ domain: getBatchSettlementEip712Domain(chainId),
1582
+ types: refundTypes,
1583
+ primaryType: "Refund",
1584
+ message: {
1585
+ channelId,
1586
+ nonce: BigInt(nonce),
1587
+ amount: BigInt(amount)
1588
+ }
1589
+ });
1590
+ }
1591
+
1592
+ // src/batch-settlement/facilitator/claim.ts
1593
+ function buildVoucherClaimArgs(claims) {
1594
+ return claims.map((c) => ({
1595
+ voucher: {
1596
+ channel: toContractChannelConfig(c.voucher.channel),
1597
+ maxClaimableAmount: BigInt(c.voucher.maxClaimableAmount)
1598
+ },
1599
+ signature: c.signature,
1600
+ totalClaimed: BigInt(c.totalClaimed)
1601
+ }));
1602
+ }
1603
+ async function executeClaimWithSignature(signer, payload, requirements, authorizerSigner, dataSuffix) {
1604
+ const network = requirements.network;
1605
+ const claimArgs = buildVoucherClaimArgs(payload.claims);
1606
+ let sig = payload.claimAuthorizerSignature;
1607
+ if (!sig) {
1608
+ for (const claim of payload.claims) {
1609
+ if ((0, import_viem16.getAddress)(claim.voucher.channel.receiverAuthorizer) !== (0, import_viem16.getAddress)(authorizerSigner.address)) {
1610
+ return {
1611
+ success: false,
1612
+ errorReason: ErrAuthorizerAddressMismatch,
1613
+ transaction: "",
1614
+ network
1615
+ };
1616
+ }
1617
+ }
1618
+ sig = await signClaimBatch(authorizerSigner, payload.claims, network);
1619
+ }
1620
+ try {
1621
+ await signer.readContract({
1622
+ address: (0, import_viem16.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1623
+ abi: batchSettlementABI,
1624
+ functionName: "claimWithSignature",
1625
+ args: [claimArgs, sig]
1626
+ });
1627
+ } catch (e) {
1628
+ return {
1629
+ success: false,
1630
+ errorReason: ErrClaimSimulationFailed,
1631
+ errorMessage: e instanceof Error ? e.message : String(e),
1632
+ transaction: "",
1633
+ network
1634
+ };
1635
+ }
1636
+ try {
1637
+ const tx = await signer.writeContract({
1638
+ address: (0, import_viem16.getAddress)(BATCH_SETTLEMENT_ADDRESS),
1639
+ abi: batchSettlementABI,
1640
+ functionName: "claimWithSignature",
1641
+ args: [claimArgs, sig],
1642
+ dataSuffix
1643
+ });
1644
+ const receipt = await signer.waitForTransactionReceipt({ hash: tx });
1645
+ if (receipt.status !== "success") {
1646
+ return {
1647
+ success: false,
1648
+ errorReason: ErrClaimTransactionFailed,
1649
+ errorMessage: `transaction reverted (receipt status ${receipt.status})`,
1650
+ transaction: tx,
1651
+ network
1652
+ };
1653
+ }
1654
+ return {
1655
+ success: true,
1656
+ transaction: tx,
1657
+ network,
1658
+ amount: ""
1659
+ };
1660
+ } catch (e) {
1661
+ return {
1662
+ success: false,
1663
+ errorReason: ErrClaimTransactionFailed,
1664
+ errorMessage: e instanceof Error ? e.message : String(e),
1665
+ transaction: "",
1666
+ network
1667
+ };
1668
+ }
1669
+ }
1670
+
1671
+ // src/batch-settlement/facilitator/settle.ts
1672
+ var import_viem17 = require("viem");
1673
+ var SETTLE_GAS_LIMIT = 120000n;
1674
+ async function executeSettle(signer, payload, requirements, dataSuffix) {
1675
+ const network = requirements.network;
1676
+ const contractAddr = (0, import_viem17.getAddress)(BATCH_SETTLEMENT_ADDRESS);
1677
+ const receiver = (0, import_viem17.getAddress)(payload.receiver);
1678
+ const token = (0, import_viem17.getAddress)(payload.token);
1679
+ try {
1680
+ const [totalClaimed, totalSettled] = await signer.readContract({
1681
+ address: contractAddr,
1682
+ abi: batchSettlementABI,
1683
+ functionName: "receivers",
1684
+ args: [receiver, token]
1685
+ });
1686
+ if (totalClaimed <= totalSettled) {
1687
+ return {
1688
+ success: false,
1689
+ errorReason: ErrNothingToSettle,
1690
+ errorMessage: "nothing to settle for receiver and token",
1691
+ transaction: "",
1692
+ network
1693
+ };
1694
+ }
1695
+ } catch (e) {
1696
+ return {
1697
+ success: false,
1698
+ errorReason: ErrRpcReadFailed,
1699
+ errorMessage: e instanceof Error ? e.message : String(e),
1700
+ transaction: "",
1701
+ network
1702
+ };
1703
+ }
1704
+ try {
1705
+ await signer.readContract({
1706
+ address: contractAddr,
1707
+ abi: batchSettlementABI,
1708
+ functionName: "settle",
1709
+ args: [receiver, token]
1710
+ });
1711
+ } catch (e) {
1712
+ return {
1713
+ success: false,
1714
+ errorReason: ErrSettleSimulationFailed,
1715
+ errorMessage: e instanceof Error ? e.message : String(e),
1716
+ transaction: "",
1717
+ network
1718
+ };
1719
+ }
1720
+ try {
1721
+ const tx = await signer.writeContract({
1722
+ address: contractAddr,
1723
+ abi: batchSettlementABI,
1724
+ functionName: "settle",
1725
+ args: [receiver, token],
1726
+ gas: SETTLE_GAS_LIMIT,
1727
+ dataSuffix
1728
+ });
1729
+ const receipt = await signer.waitForTransactionReceipt({ hash: tx });
1730
+ if (receipt.status !== "success") {
1731
+ return {
1732
+ success: false,
1733
+ errorReason: ErrSettleTransactionFailed,
1734
+ errorMessage: `transaction reverted (receipt status ${receipt.status})`,
1735
+ transaction: tx,
1736
+ network
1737
+ };
1738
+ }
1739
+ let amount = "";
1740
+ if (receipt.logs) {
1741
+ const logs = (0, import_viem17.parseEventLogs)({
1742
+ abi: batchSettlementABI,
1743
+ eventName: "Settled",
1744
+ logs: receipt.logs.filter((log) => (0, import_viem17.isAddressEqual)(log.address, contractAddr))
1745
+ });
1746
+ const settledLog = logs.find(
1747
+ (log) => (0, import_viem17.isAddressEqual)(log.args.receiver, receiver) && (0, import_viem17.isAddressEqual)(log.args.token, token)
1748
+ );
1749
+ amount = settledLog?.args.amount.toString() ?? "0";
1750
+ }
1751
+ return {
1752
+ success: true,
1753
+ transaction: tx,
1754
+ network,
1755
+ amount
1756
+ };
1757
+ } catch (e) {
1758
+ return {
1759
+ success: false,
1760
+ errorReason: ErrSettleTransactionFailed,
1761
+ errorMessage: e instanceof Error ? e.message : String(e),
1762
+ transaction: "",
1763
+ network
1764
+ };
1765
+ }
1766
+ }
1767
+
1768
+ // src/batch-settlement/facilitator/refund.ts
1769
+ var import_viem18 = require("viem");
1770
+ var REFUND_STATE_POLL_MS = 2e3;
1771
+ var REFUND_STATE_POLL_INTERVAL_MS = 150;
1772
+ function getRefundableAmount(payload, preState, channelId, network) {
1773
+ const postClaimTotalClaimed = payload.claims.reduce((max, claim) => {
1774
+ const claimChannelId = computeChannelId(claim.voucher.channel, network);
1775
+ if (claimChannelId.toLowerCase() !== channelId.toLowerCase()) {
1776
+ return max;
1777
+ }
1778
+ const totalClaimed = BigInt(claim.totalClaimed);
1779
+ return totalClaimed > max ? totalClaimed : max;
1780
+ }, preState.totalClaimed);
1781
+ if (postClaimTotalClaimed > preState.balance) {
1782
+ return null;
1783
+ }
1784
+ const requestedAmount = BigInt(payload.amount);
1785
+ if (requestedAmount === 0n) {
1786
+ return null;
1787
+ }
1788
+ const available = preState.balance - postClaimTotalClaimed;
1789
+ return requestedAmount > available ? available : requestedAmount;
1790
+ }
1791
+ function buildRefundExtra(payload, channelId, preState) {
1792
+ const preTotalClaimed = preState?.totalClaimed ?? 0n;
1793
+ const preBalance = preState?.balance ?? 0n;
1794
+ const lastClaimTotal = payload.claims.length > 0 ? BigInt(payload.claims[payload.claims.length - 1].totalClaimed) : preTotalClaimed;
1795
+ const postClaimTotalClaimed = lastClaimTotal > preTotalClaimed ? lastClaimTotal : preTotalClaimed;
1796
+ const available = preBalance - postClaimTotalClaimed;
1797
+ const requestedAmount = BigInt(payload.amount);
1798
+ const actualRefund = requestedAmount > available ? available : requestedAmount;
1799
+ return {
1800
+ amount: actualRefund.toString(),
1801
+ extra: {
1802
+ channelState: {
1803
+ channelId,
1804
+ balance: (preBalance - actualRefund).toString(),
1805
+ totalClaimed: postClaimTotalClaimed.toString(),
1806
+ withdrawRequestedAt: 0,
1807
+ refundNonce: String((preState?.refundNonce ?? 0n) + 1n)
1808
+ }
1809
+ }
1810
+ };
1811
+ }
1812
+ async function readPostRefundState(signer, channelId, submittedNonce) {
1813
+ const expectedNonce = BigInt(submittedNonce) + 1n;
1814
+ const deadline = Date.now() + REFUND_STATE_POLL_MS;
1815
+ do {
1816
+ let state;
1817
+ try {
1818
+ state = await readChannelState(signer, channelId);
1819
+ } catch {
1820
+ return null;
1821
+ }
1822
+ if (state.refundNonce >= expectedNonce) {
1823
+ return state;
1824
+ }
1825
+ await new Promise((resolve) => setTimeout(resolve, REFUND_STATE_POLL_INTERVAL_MS));
1826
+ } while (Date.now() < deadline);
1827
+ return null;
1828
+ }
1829
+ function buildRefundExtraFromPostState(channelId, preState, postState) {
1830
+ const actualRefund = preState.balance > postState.balance ? preState.balance - postState.balance : 0n;
1831
+ return {
1832
+ amount: actualRefund.toString(),
1833
+ extra: {
1834
+ channelState: {
1835
+ channelId,
1836
+ balance: postState.balance.toString(),
1837
+ totalClaimed: postState.totalClaimed.toString(),
1838
+ withdrawRequestedAt: postState.withdrawRequestedAt,
1839
+ refundNonce: postState.refundNonce.toString()
1840
+ }
1841
+ }
1842
+ };
1843
+ }
1844
+ async function executeRefundWithSignature(signer, payload, requirements, authorizerSigner, dataSuffix) {
1845
+ const network = requirements.network;
1846
+ try {
1847
+ const channelId = computeChannelId(payload.channelConfig, network);
1848
+ const preState = await readChannelState(signer, channelId);
1849
+ const contractAddr = (0, import_viem18.getAddress)(BATCH_SETTLEMENT_ADDRESS);
1850
+ const refundableAmount = getRefundableAmount(payload, preState, channelId, network);
1851
+ if (refundableAmount === 0n) {
1852
+ return {
1853
+ success: false,
1854
+ errorReason: ErrRefundNoBalance,
1855
+ errorMessage: "Nothing to refund",
1856
+ transaction: "",
1857
+ network
1858
+ };
1859
+ }
1860
+ const hasClientSig = payload.refundAuthorizerSignature !== void 0;
1861
+ const authorizerMismatch = (0, import_viem18.getAddress)(payload.channelConfig.receiverAuthorizer) !== (0, import_viem18.getAddress)(authorizerSigner.address);
1862
+ if (!hasClientSig && authorizerMismatch) {
1863
+ return {
1864
+ success: false,
1865
+ errorReason: ErrAuthorizerAddressMismatch,
1866
+ transaction: "",
1867
+ network
1868
+ };
1869
+ }
1870
+ const refundSig = payload.refundAuthorizerSignature ?? await signRefund(authorizerSigner, channelId, payload.amount, payload.refundNonce, network);
1871
+ const refundCalldata = (0, import_viem18.encodeFunctionData)({
1872
+ abi: batchSettlementABI,
1873
+ functionName: "refundWithSignature",
1874
+ args: [
1875
+ toContractChannelConfig(payload.channelConfig),
1876
+ BigInt(payload.amount),
1877
+ BigInt(payload.refundNonce),
1878
+ refundSig
1879
+ ]
1880
+ });
1881
+ let tx;
1882
+ if (payload.claims.length > 0) {
1883
+ let claimSig = payload.claimAuthorizerSignature;
1884
+ if (!claimSig) {
1885
+ claimSig = await signClaimBatch(authorizerSigner, payload.claims, network);
1886
+ }
1887
+ const claimCalldata = (0, import_viem18.encodeFunctionData)({
1888
+ abi: batchSettlementABI,
1889
+ functionName: "claimWithSignature",
1890
+ args: [buildVoucherClaimArgs(payload.claims), claimSig]
1891
+ });
1892
+ try {
1893
+ await signer.readContract({
1894
+ address: contractAddr,
1895
+ abi: batchSettlementABI,
1896
+ functionName: "multicall",
1897
+ args: [[claimCalldata, refundCalldata]]
1898
+ });
1899
+ } catch (e) {
1900
+ return {
1901
+ success: false,
1902
+ errorReason: ErrRefundSimulationFailed,
1903
+ errorMessage: e instanceof Error ? e.message : String(e),
1904
+ transaction: "",
1905
+ network
1906
+ };
1907
+ }
1908
+ tx = await signer.writeContract({
1909
+ address: contractAddr,
1910
+ abi: batchSettlementABI,
1911
+ functionName: "multicall",
1912
+ args: [[claimCalldata, refundCalldata]],
1913
+ dataSuffix
1914
+ });
1915
+ } else {
1916
+ try {
1917
+ await signer.readContract({
1918
+ address: contractAddr,
1919
+ abi: batchSettlementABI,
1920
+ functionName: "refundWithSignature",
1921
+ args: [
1922
+ toContractChannelConfig(payload.channelConfig),
1923
+ BigInt(payload.amount),
1924
+ BigInt(payload.refundNonce),
1925
+ refundSig
1926
+ ]
1927
+ });
1928
+ } catch (e) {
1929
+ return {
1930
+ success: false,
1931
+ errorReason: ErrRefundSimulationFailed,
1932
+ errorMessage: e instanceof Error ? e.message : String(e),
1933
+ transaction: "",
1934
+ network
1935
+ };
1936
+ }
1937
+ tx = await signer.writeContract({
1938
+ address: contractAddr,
1939
+ abi: batchSettlementABI,
1940
+ functionName: "refundWithSignature",
1941
+ args: [
1942
+ toContractChannelConfig(payload.channelConfig),
1943
+ BigInt(payload.amount),
1944
+ BigInt(payload.refundNonce),
1945
+ refundSig
1946
+ ],
1947
+ dataSuffix
1948
+ });
1949
+ }
1950
+ const receipt = await signer.waitForTransactionReceipt({ hash: tx });
1951
+ if (receipt.status !== "success") {
1952
+ return {
1953
+ success: false,
1954
+ errorReason: ErrRefundTransactionFailed,
1955
+ errorMessage: `transaction reverted (receipt status ${receipt.status})`,
1956
+ transaction: tx,
1957
+ network
1958
+ };
1959
+ }
1960
+ const postState = preState && preState.withdrawRequestedAt !== 0 ? await readPostRefundState(signer, channelId, payload.refundNonce) : null;
1961
+ const refundDetails = preState && postState ? buildRefundExtraFromPostState(channelId, preState, postState) : buildRefundExtra(payload, channelId, preState);
1962
+ return {
1963
+ success: true,
1964
+ transaction: tx,
1965
+ network,
1966
+ payer: payload.channelConfig.payer,
1967
+ amount: refundDetails.amount,
1968
+ extra: refundDetails.extra
1969
+ };
1970
+ } catch (e) {
1971
+ return {
1972
+ success: false,
1973
+ errorReason: ErrRefundTransactionFailed,
1974
+ errorMessage: e instanceof Error ? e.message : String(e),
1975
+ transaction: "",
1976
+ network
1977
+ };
1978
+ }
1979
+ }
1980
+
1981
+ // src/batch-settlement/facilitator/scheme.ts
1982
+ var BatchSettlementEvmScheme = class {
1983
+ /**
1984
+ * Creates a facilitator scheme for verifying and settling batch-settlement payments.
1985
+ *
1986
+ * @param signer - Facilitator EVM signer(s) used for tx submission and onchain reads.
1987
+ * @param authorizerSigner - Dedicated key that provides EIP-712 signatures for
1988
+ * `claimWithSignature` / `refundWithSignature`. The facilitator will sign missing
1989
+ * authorizer signatures using this key when the server omits them.
1990
+ */
1991
+ constructor(signer, authorizerSigner) {
1992
+ this.signer = signer;
1993
+ this.authorizerSigner = authorizerSigner;
1994
+ this.scheme = BATCH_SETTLEMENT_SCHEME;
1995
+ this.caipFamily = "eip155:*";
1996
+ }
1997
+ /**
1998
+ * Returns facilitator-specific extra fields to be merged into payment requirements.
1999
+ *
2000
+ * Exposes the configured `receiverAuthorizer` address so the server and client can
2001
+ * embed it in `ChannelConfig`.
2002
+ *
2003
+ * @param _ - Network identifier (unused).
2004
+ * @returns Extra fields containing `receiverAuthorizer`.
2005
+ */
2006
+ getExtra(_) {
2007
+ return { receiverAuthorizer: this.authorizerSigner.address };
2008
+ }
2009
+ /**
2010
+ * Returns all facilitator signer addresses available for the given network.
2011
+ *
2012
+ * @param _ - Network identifier (unused).
2013
+ * @returns Array of hex addresses.
2014
+ */
2015
+ getSigners(_) {
2016
+ return [...this.signer.getAddresses()];
2017
+ }
2018
+ /**
2019
+ * Verifies a payment payload (deposit or voucher) without executing settlement.
2020
+ *
2021
+ * @param payload - The x402 payment payload envelope.
2022
+ * @param requirements - Server payment requirements (scheme, network, asset, amount).
2023
+ * @param context - Optional facilitator extension context.
2024
+ * @param _ - Payment required extensions (unused; reserved for interface parity)
2025
+ * @returns A {@link VerifyResponse} indicating validity with payer and channel state in `extra`.
2026
+ */
2027
+ async verify(payload, requirements, context, _) {
2028
+ const rawPayload = payload.payload;
2029
+ if (payload.accepted.scheme !== BATCH_SETTLEMENT_SCHEME || requirements.scheme !== BATCH_SETTLEMENT_SCHEME) {
2030
+ return { isValid: false, invalidReason: ErrInvalidScheme };
2031
+ }
2032
+ if (payload.accepted.network !== requirements.network) {
2033
+ return { isValid: false, invalidReason: ErrNetworkMismatch };
2034
+ }
2035
+ if (isBatchSettlementDepositPayload(rawPayload)) {
2036
+ return verifyDeposit(this.signer, payload, rawPayload, requirements, context);
2037
+ }
2038
+ if (isBatchSettlementVoucherPayload(rawPayload)) {
2039
+ return verifyVoucher(this.signer, rawPayload, requirements, rawPayload.channelConfig);
2040
+ }
2041
+ if (isBatchSettlementRefundPayload(rawPayload)) {
2042
+ return verifyVoucher(this.signer, rawPayload, requirements, rawPayload.channelConfig);
2043
+ }
2044
+ return { isValid: false, invalidReason: ErrInvalidPayloadType };
2045
+ }
2046
+ /**
2047
+ * Executes settlement for a payment payload.
2048
+ *
2049
+ * Dispatches to the correct handler based on payload settle action:
2050
+ * - `deposit` → onchain `deposit(config, amount, collector, collectorData)`
2051
+ * - `claim` → onchain `claimWithSignature(VoucherClaim[], bytes)`
2052
+ * - `settle` → onchain `settle(receiver, token)`
2053
+ * - `refund` → optional claim + onchain `refundWithSignature(config, amount, nonce, sig)`
2054
+ *
2055
+ * @param payload - The x402 payment payload envelope.
2056
+ * @param requirements - Server payment requirements.
2057
+ * @param context - Optional facilitator extension context.
2058
+ * @returns A {@link SettleResponse} with the transaction hash on success.
2059
+ */
2060
+ async settle(payload, requirements, context) {
2061
+ const rawPayload = payload.payload;
2062
+ const dataSuffix = await resolveDataSuffix(context, {
2063
+ paymentPayload: payload,
2064
+ paymentRequirements: requirements
2065
+ });
2066
+ if (isBatchSettlementDepositPayload(rawPayload)) {
2067
+ return settleDeposit(this.signer, payload, rawPayload, requirements, context, dataSuffix);
2068
+ }
2069
+ if (isBatchSettlementClaimPayload(rawPayload)) {
2070
+ return executeClaimWithSignature(
2071
+ this.signer,
2072
+ rawPayload,
2073
+ requirements,
2074
+ this.authorizerSigner,
2075
+ dataSuffix
2076
+ );
2077
+ }
2078
+ if (isBatchSettlementEnrichedRefundPayload(rawPayload)) {
2079
+ return executeRefundWithSignature(
2080
+ this.signer,
2081
+ rawPayload,
2082
+ requirements,
2083
+ this.authorizerSigner,
2084
+ dataSuffix
2085
+ );
2086
+ }
2087
+ if (isBatchSettlementSettlePayload(rawPayload)) {
2088
+ return executeSettle(this.signer, rawPayload, requirements, dataSuffix);
2089
+ }
2090
+ return {
2091
+ success: false,
2092
+ errorReason: ErrInvalidPayloadType,
2093
+ transaction: "",
2094
+ network: requirements.network
2095
+ };
2096
+ }
2097
+ };
2098
+ // Annotate the CommonJS export names for ESM import in node:
2099
+ 0 && (module.exports = {
2100
+ BatchSettlementEvmScheme
2101
+ });
2102
+ //# sourceMappingURL=index.js.map