@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,1313 @@
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/upto/facilitator/index.ts
21
+ var facilitator_exports = {};
22
+ __export(facilitator_exports, {
23
+ UptoEvmScheme: () => UptoEvmScheme
24
+ });
25
+ module.exports = __toCommonJS(facilitator_exports);
26
+
27
+ // src/types.ts
28
+ function isUptoPermit2Payload(payload) {
29
+ if (typeof payload.signature !== "string") return false;
30
+ if (!("permit2Authorization" in payload)) return false;
31
+ const auth = payload.permit2Authorization;
32
+ if (typeof auth !== "object" || auth === null) return false;
33
+ const a = auth;
34
+ if (typeof a.from !== "string") return false;
35
+ if (typeof a.spender !== "string") return false;
36
+ if (typeof a.nonce !== "string") return false;
37
+ if (typeof a.deadline !== "string") return false;
38
+ const permitted = a.permitted;
39
+ if (typeof permitted !== "object" || permitted === null) return false;
40
+ const p = permitted;
41
+ if (typeof p.token !== "string") return false;
42
+ if (typeof p.amount !== "string") return false;
43
+ const witness = a.witness;
44
+ if (typeof witness !== "object" || witness === null) return false;
45
+ const w = witness;
46
+ return typeof w.facilitator === "string" && typeof w.to === "string" && typeof w.validAfter === "string";
47
+ }
48
+
49
+ // src/exact/extensions.ts
50
+ var EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
51
+ var ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
52
+ function _extractInfo(payload, extensionKey) {
53
+ const extensions = payload.extensions;
54
+ if (!extensions) return null;
55
+ const extension = extensions[extensionKey];
56
+ if (!extension?.info) return null;
57
+ return extension.info;
58
+ }
59
+ function extractEip2612GasSponsoringInfo(payload) {
60
+ const info = _extractInfo(payload, EIP2612_GAS_SPONSORING_KEY);
61
+ if (!info) return null;
62
+ if (!info.from || !info.asset || !info.spender || !info.amount || !info.nonce || !info.deadline || !info.signature || !info.version) {
63
+ return null;
64
+ }
65
+ return info;
66
+ }
67
+ function validateEip2612GasSponsoringInfo(info) {
68
+ const addressPattern = /^0x[a-fA-F0-9]{40}$/;
69
+ const numericPattern = /^[0-9]+$/;
70
+ const hexPattern = /^0x[a-fA-F0-9]+$/;
71
+ const versionPattern = /^[0-9]+(\.[0-9]+)*$/;
72
+ 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);
73
+ }
74
+ function extractErc20ApprovalGasSponsoringInfo(payload) {
75
+ const info = _extractInfo(payload, ERC20_APPROVAL_GAS_SPONSORING_KEY);
76
+ if (!info) return null;
77
+ if (!info.from || !info.asset || !info.spender || !info.amount || !info.signedTransaction || !info.version) {
78
+ return null;
79
+ }
80
+ return info;
81
+ }
82
+ function validateErc20ApprovalGasSponsoringInfo(info) {
83
+ const addressPattern = /^0x[a-fA-F0-9]{40}$/;
84
+ const numericPattern = /^[0-9]+$/;
85
+ const hexPattern = /^0x[a-fA-F0-9]+$/;
86
+ const versionPattern = /^[0-9]+(\.[0-9]+)*$/;
87
+ 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);
88
+ }
89
+ function resolveErc20ApprovalExtensionSigner(extension, network) {
90
+ if (!extension) return void 0;
91
+ return extension.signerForNetwork?.(network) ?? extension.signer;
92
+ }
93
+
94
+ // src/upto/facilitator/permit2.ts
95
+ var import_viem9 = require("viem");
96
+
97
+ // src/shared/extensions/gasSponsoring.ts
98
+ var import_viem5 = require("viem");
99
+
100
+ // src/constants.ts
101
+ var uptoPermit2WitnessTypes = {
102
+ PermitWitnessTransferFrom: [
103
+ { name: "permitted", type: "TokenPermissions" },
104
+ { name: "spender", type: "address" },
105
+ { name: "nonce", type: "uint256" },
106
+ { name: "deadline", type: "uint256" },
107
+ { name: "witness", type: "Witness" }
108
+ ],
109
+ TokenPermissions: [
110
+ { name: "token", type: "address" },
111
+ { name: "amount", type: "uint256" }
112
+ ],
113
+ Witness: [
114
+ { name: "to", type: "address" },
115
+ { name: "facilitator", type: "address" },
116
+ { name: "validAfter", type: "uint256" }
117
+ ]
118
+ };
119
+ var eip3009ABI = [
120
+ {
121
+ inputs: [
122
+ { name: "from", type: "address" },
123
+ { name: "to", type: "address" },
124
+ { name: "value", type: "uint256" },
125
+ { name: "validAfter", type: "uint256" },
126
+ { name: "validBefore", type: "uint256" },
127
+ { name: "nonce", type: "bytes32" },
128
+ { name: "v", type: "uint8" },
129
+ { name: "r", type: "bytes32" },
130
+ { name: "s", type: "bytes32" }
131
+ ],
132
+ name: "transferWithAuthorization",
133
+ outputs: [],
134
+ stateMutability: "nonpayable",
135
+ type: "function"
136
+ },
137
+ {
138
+ inputs: [
139
+ { name: "from", type: "address" },
140
+ { name: "to", type: "address" },
141
+ { name: "value", type: "uint256" },
142
+ { name: "validAfter", type: "uint256" },
143
+ { name: "validBefore", type: "uint256" },
144
+ { name: "nonce", type: "bytes32" },
145
+ { name: "signature", type: "bytes" }
146
+ ],
147
+ name: "transferWithAuthorization",
148
+ outputs: [],
149
+ stateMutability: "nonpayable",
150
+ type: "function"
151
+ },
152
+ {
153
+ inputs: [{ name: "account", type: "address" }],
154
+ name: "balanceOf",
155
+ outputs: [{ name: "", type: "uint256" }],
156
+ stateMutability: "view",
157
+ type: "function"
158
+ },
159
+ {
160
+ inputs: [],
161
+ name: "version",
162
+ outputs: [{ name: "", type: "string" }],
163
+ stateMutability: "view",
164
+ type: "function"
165
+ },
166
+ {
167
+ inputs: [],
168
+ name: "name",
169
+ outputs: [{ name: "", type: "string" }],
170
+ stateMutability: "view",
171
+ type: "function"
172
+ },
173
+ {
174
+ inputs: [
175
+ { name: "authorizer", type: "address" },
176
+ { name: "nonce", type: "bytes32" }
177
+ ],
178
+ name: "authorizationState",
179
+ outputs: [{ name: "", type: "bool" }],
180
+ stateMutability: "view",
181
+ type: "function"
182
+ }
183
+ ];
184
+ var erc20ApproveAbi = [
185
+ {
186
+ type: "function",
187
+ name: "approve",
188
+ inputs: [
189
+ { name: "spender", type: "address" },
190
+ { name: "amount", type: "uint256" }
191
+ ],
192
+ outputs: [{ type: "bool" }],
193
+ stateMutability: "nonpayable"
194
+ }
195
+ ];
196
+ var erc20AllowanceAbi = [
197
+ {
198
+ type: "function",
199
+ name: "allowance",
200
+ inputs: [
201
+ { name: "owner", type: "address" },
202
+ { name: "spender", type: "address" }
203
+ ],
204
+ outputs: [{ type: "uint256" }],
205
+ stateMutability: "view"
206
+ }
207
+ ];
208
+ var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
209
+ var x402UptoPermit2ProxyAddress = "0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002";
210
+ var uptoPermit2WitnessABIComponents = [
211
+ { name: "to", type: "address", internalType: "address" },
212
+ { name: "facilitator", type: "address", internalType: "address" },
213
+ { name: "validAfter", type: "uint256", internalType: "uint256" }
214
+ ];
215
+ var x402UptoPermit2ProxyABI = [
216
+ {
217
+ type: "function",
218
+ name: "PERMIT2",
219
+ inputs: [],
220
+ outputs: [{ name: "", type: "address", internalType: "contract ISignatureTransfer" }],
221
+ stateMutability: "view"
222
+ },
223
+ {
224
+ type: "function",
225
+ name: "WITNESS_TYPEHASH",
226
+ inputs: [],
227
+ outputs: [{ name: "", type: "bytes32", internalType: "bytes32" }],
228
+ stateMutability: "view"
229
+ },
230
+ {
231
+ type: "function",
232
+ name: "WITNESS_TYPE_STRING",
233
+ inputs: [],
234
+ outputs: [{ name: "", type: "string", internalType: "string" }],
235
+ stateMutability: "view"
236
+ },
237
+ {
238
+ type: "function",
239
+ name: "settle",
240
+ inputs: [
241
+ {
242
+ name: "permit",
243
+ type: "tuple",
244
+ internalType: "struct ISignatureTransfer.PermitTransferFrom",
245
+ components: [
246
+ {
247
+ name: "permitted",
248
+ type: "tuple",
249
+ internalType: "struct ISignatureTransfer.TokenPermissions",
250
+ components: [
251
+ { name: "token", type: "address", internalType: "address" },
252
+ { name: "amount", type: "uint256", internalType: "uint256" }
253
+ ]
254
+ },
255
+ { name: "nonce", type: "uint256", internalType: "uint256" },
256
+ { name: "deadline", type: "uint256", internalType: "uint256" }
257
+ ]
258
+ },
259
+ { name: "amount", type: "uint256", internalType: "uint256" },
260
+ { name: "owner", type: "address", internalType: "address" },
261
+ {
262
+ name: "witness",
263
+ type: "tuple",
264
+ internalType: "struct x402UptoPermit2Proxy.Witness",
265
+ components: uptoPermit2WitnessABIComponents
266
+ },
267
+ { name: "signature", type: "bytes", internalType: "bytes" }
268
+ ],
269
+ outputs: [],
270
+ stateMutability: "nonpayable"
271
+ },
272
+ {
273
+ type: "function",
274
+ name: "settleWithPermit",
275
+ inputs: [
276
+ {
277
+ name: "permit2612",
278
+ type: "tuple",
279
+ internalType: "struct x402UptoPermit2Proxy.EIP2612Permit",
280
+ components: [
281
+ { name: "value", type: "uint256", internalType: "uint256" },
282
+ { name: "deadline", type: "uint256", internalType: "uint256" },
283
+ { name: "r", type: "bytes32", internalType: "bytes32" },
284
+ { name: "s", type: "bytes32", internalType: "bytes32" },
285
+ { name: "v", type: "uint8", internalType: "uint8" }
286
+ ]
287
+ },
288
+ {
289
+ name: "permit",
290
+ type: "tuple",
291
+ internalType: "struct ISignatureTransfer.PermitTransferFrom",
292
+ components: [
293
+ {
294
+ name: "permitted",
295
+ type: "tuple",
296
+ internalType: "struct ISignatureTransfer.TokenPermissions",
297
+ components: [
298
+ { name: "token", type: "address", internalType: "address" },
299
+ { name: "amount", type: "uint256", internalType: "uint256" }
300
+ ]
301
+ },
302
+ { name: "nonce", type: "uint256", internalType: "uint256" },
303
+ { name: "deadline", type: "uint256", internalType: "uint256" }
304
+ ]
305
+ },
306
+ { name: "amount", type: "uint256", internalType: "uint256" },
307
+ { name: "owner", type: "address", internalType: "address" },
308
+ {
309
+ name: "witness",
310
+ type: "tuple",
311
+ internalType: "struct x402UptoPermit2Proxy.Witness",
312
+ components: uptoPermit2WitnessABIComponents
313
+ },
314
+ { name: "signature", type: "bytes", internalType: "bytes" }
315
+ ],
316
+ outputs: [],
317
+ stateMutability: "nonpayable"
318
+ },
319
+ { type: "event", name: "Settled", inputs: [], anonymous: false },
320
+ { type: "event", name: "SettledWithPermit", inputs: [], anonymous: false },
321
+ { type: "error", name: "AmountExceedsPermitted", inputs: [] },
322
+ { type: "error", name: "InvalidDestination", inputs: [] },
323
+ { type: "error", name: "InvalidOwner", inputs: [] },
324
+ { type: "error", name: "InvalidPermit2Address", inputs: [] },
325
+ { type: "error", name: "PaymentTooEarly", inputs: [] },
326
+ { type: "error", name: "Permit2612AmountMismatch", inputs: [] },
327
+ { type: "error", name: "ReentrancyGuardReentrantCall", inputs: [] },
328
+ { type: "error", name: "UnauthorizedFacilitator", inputs: [] }
329
+ ];
330
+
331
+ // src/utils.ts
332
+ var import_viem = require("viem");
333
+ function getEvmChainId(network) {
334
+ if (network.startsWith("eip155:")) {
335
+ const idStr = network.split(":")[1];
336
+ const chainId = parseInt(idStr, 10);
337
+ if (isNaN(chainId)) {
338
+ throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
339
+ }
340
+ return chainId;
341
+ }
342
+ throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
343
+ }
344
+
345
+ // src/exact/client/eip2612.ts
346
+ var import_viem2 = require("viem");
347
+
348
+ // src/exact/client/erc20approval.ts
349
+ var import_viem3 = require("viem");
350
+
351
+ // src/shared/rpc.ts
352
+ var import_viem4 = require("viem");
353
+
354
+ // src/shared/extensions/builderCode.ts
355
+ var BUILDER_CODE_KEY = "builder-code";
356
+ var BUILDER_CODE_RESOLVER = async (context, ctx) => {
357
+ const ext = context.getExtension(BUILDER_CODE_KEY);
358
+ if (!ext?.buildDataSuffix) {
359
+ return void 0;
360
+ }
361
+ return ext.buildDataSuffix(ctx);
362
+ };
363
+ var DATA_SUFFIX_RESOLVERS = [BUILDER_CODE_RESOLVER];
364
+ async function resolveDataSuffix(context, ctx) {
365
+ if (!context) {
366
+ return void 0;
367
+ }
368
+ const parts = [];
369
+ for (const resolver of DATA_SUFFIX_RESOLVERS) {
370
+ const suffix = await resolver(context, ctx);
371
+ if (suffix && suffix !== "0x" && suffix.length > 2) {
372
+ parts.push(suffix);
373
+ }
374
+ }
375
+ if (parts.length === 0) {
376
+ return void 0;
377
+ }
378
+ if (parts.length === 1) {
379
+ return parts[0];
380
+ }
381
+ return parts.reduce((acc, part, index) => {
382
+ if (index === 0) {
383
+ return part;
384
+ }
385
+ const stripped = part.startsWith("0x") ? part.slice(2) : part;
386
+ return `${acc}${stripped}`;
387
+ });
388
+ }
389
+ function appendDataSuffix(calldata, suffix) {
390
+ if (!suffix || suffix === "0x" || suffix.length <= 2) {
391
+ return calldata;
392
+ }
393
+ const suffixHex = suffix.startsWith("0x") ? suffix.slice(2) : suffix;
394
+ return `${calldata}${suffixHex}`;
395
+ }
396
+
397
+ // src/exact/facilitator/errors.ts
398
+ var ErrAssetNotDeployedContract = "asset_not_deployed_contract";
399
+ var ErrTransactionFailed = "invalid_exact_evm_transaction_failed";
400
+ var ErrPermit2AmountMismatch = "permit2_amount_mismatch";
401
+ var ErrPermit2InvalidSignature = "invalid_permit2_signature";
402
+ var ErrPermit2AllowanceRequired = "permit2_allowance_required";
403
+ var ErrPermit2SimulationFailed = "permit2_simulation_failed";
404
+ var ErrPermit2InsufficientBalance = "permit2_insufficient_balance";
405
+ var ErrPermit2ProxyNotDeployed = "permit2_proxy_not_deployed";
406
+ var ErrPermit2InvalidAmount = "permit2_invalid_amount";
407
+ var ErrPermit2InvalidDestination = "permit2_invalid_destination";
408
+ var ErrPermit2InvalidOwner = "permit2_invalid_owner";
409
+ var ErrPermit2PaymentTooEarly = "permit2_payment_too_early";
410
+ var ErrPermit2InvalidNonce = "permit2_invalid_nonce";
411
+ var ErrPermit2612AmountMismatch = "permit2_2612_amount_mismatch";
412
+ var ErrErc20ApprovalInvalidFormat = "invalid_erc20_approval_extension_format";
413
+ var ErrErc20ApprovalFromMismatch = "erc20_approval_from_mismatch";
414
+ var ErrErc20ApprovalAssetMismatch = "erc20_approval_asset_mismatch";
415
+ var ErrErc20ApprovalSpenderNotPermit2 = "erc20_approval_spender_not_permit2";
416
+ var ErrErc20ApprovalTxWrongTarget = "erc20_approval_tx_wrong_target";
417
+ var ErrErc20ApprovalTxWrongSelector = "erc20_approval_tx_wrong_selector";
418
+ var ErrErc20ApprovalTxWrongSpender = "erc20_approval_tx_wrong_spender";
419
+ var ErrErc20ApprovalTxInvalidCalldata = "erc20_approval_tx_invalid_calldata";
420
+ var ErrErc20ApprovalTxSignerMismatch = "erc20_approval_tx_signer_mismatch";
421
+ var ErrErc20ApprovalTxInvalidSignature = "erc20_approval_tx_invalid_signature";
422
+ var ErrErc20ApprovalTxParseFailed = "erc20_approval_tx_parse_failed";
423
+ var ErrErc20ApprovalTxFailed = "erc20_approval_tx_failed";
424
+ var ErrInvalidEip2612ExtensionFormat = "invalid_eip2612_extension_format";
425
+ var ErrEip2612FromMismatch = "eip2612_from_mismatch";
426
+ var ErrEip2612AssetMismatch = "eip2612_asset_mismatch";
427
+ var ErrEip2612SpenderNotPermit2 = "eip2612_spender_not_permit2";
428
+ var ErrEip2612DeadlineExpired = "eip2612_deadline_expired";
429
+ var ErrInvalidTransactionState = "invalid_transaction_state";
430
+
431
+ // src/upto/facilitator/errors.ts
432
+ var ErrUptoInvalidScheme = "invalid_upto_evm_scheme";
433
+ var ErrUptoNetworkMismatch = "invalid_upto_evm_network_mismatch";
434
+ var ErrUptoSettlementExceedsAmount = "invalid_upto_evm_payload_settlement_exceeds_amount";
435
+ var ErrUptoAmountExceedsPermitted = "upto_amount_exceeds_permitted";
436
+ var ErrUptoUnauthorizedFacilitator = "upto_unauthorized_facilitator";
437
+ var ErrUptoFacilitatorMismatch = "upto_facilitator_mismatch";
438
+
439
+ // src/shared/erc20approval.ts
440
+ var import_viem6 = require("viem");
441
+ var APPROVE_SELECTOR = "0x095ea7b3";
442
+ async function validateErc20ApprovalForPayment(info, payer, tokenAddress) {
443
+ if (!validateErc20ApprovalGasSponsoringInfo(info)) {
444
+ return {
445
+ isValid: false,
446
+ invalidReason: ErrErc20ApprovalInvalidFormat,
447
+ invalidMessage: "ERC-20 approval extension info failed schema validation"
448
+ };
449
+ }
450
+ if ((0, import_viem6.getAddress)(info.from) !== (0, import_viem6.getAddress)(payer)) {
451
+ return {
452
+ isValid: false,
453
+ invalidReason: ErrErc20ApprovalFromMismatch,
454
+ invalidMessage: `Expected from=${payer}, got ${info.from}`
455
+ };
456
+ }
457
+ if ((0, import_viem6.getAddress)(info.asset) !== tokenAddress) {
458
+ return {
459
+ isValid: false,
460
+ invalidReason: ErrErc20ApprovalAssetMismatch,
461
+ invalidMessage: `Expected asset=${tokenAddress}, got ${info.asset}`
462
+ };
463
+ }
464
+ if ((0, import_viem6.getAddress)(info.spender) !== (0, import_viem6.getAddress)(PERMIT2_ADDRESS)) {
465
+ return {
466
+ isValid: false,
467
+ invalidReason: ErrErc20ApprovalSpenderNotPermit2,
468
+ invalidMessage: `Expected spender=${PERMIT2_ADDRESS}, got ${info.spender}`
469
+ };
470
+ }
471
+ try {
472
+ const serializedTx = info.signedTransaction;
473
+ const tx = (0, import_viem6.parseTransaction)(serializedTx);
474
+ if (!tx.to || (0, import_viem6.getAddress)(tx.to) !== tokenAddress) {
475
+ return {
476
+ isValid: false,
477
+ invalidReason: ErrErc20ApprovalTxWrongTarget,
478
+ invalidMessage: `Transaction targets ${tx.to ?? "null"}, expected ${tokenAddress}`
479
+ };
480
+ }
481
+ const data = tx.data ?? "0x";
482
+ if (!data.startsWith(APPROVE_SELECTOR)) {
483
+ return {
484
+ isValid: false,
485
+ invalidReason: ErrErc20ApprovalTxWrongSelector,
486
+ invalidMessage: `Transaction calldata does not start with approve() selector ${APPROVE_SELECTOR}`
487
+ };
488
+ }
489
+ try {
490
+ const decoded = (0, import_viem6.decodeFunctionData)({
491
+ abi: erc20ApproveAbi,
492
+ data
493
+ });
494
+ const calldataSpender = (0, import_viem6.getAddress)(decoded.args[0]);
495
+ if (calldataSpender !== (0, import_viem6.getAddress)(PERMIT2_ADDRESS)) {
496
+ return {
497
+ isValid: false,
498
+ invalidReason: ErrErc20ApprovalTxWrongSpender,
499
+ invalidMessage: `approve() spender is ${calldataSpender}, expected Permit2 ${PERMIT2_ADDRESS}`
500
+ };
501
+ }
502
+ } catch {
503
+ return {
504
+ isValid: false,
505
+ invalidReason: ErrErc20ApprovalTxInvalidCalldata,
506
+ invalidMessage: "Failed to decode approve() calldata from the signed transaction"
507
+ };
508
+ }
509
+ try {
510
+ const recoveredAddress = await (0, import_viem6.recoverTransactionAddress)({
511
+ serializedTransaction: serializedTx
512
+ });
513
+ if ((0, import_viem6.getAddress)(recoveredAddress) !== (0, import_viem6.getAddress)(payer)) {
514
+ return {
515
+ isValid: false,
516
+ invalidReason: ErrErc20ApprovalTxSignerMismatch,
517
+ invalidMessage: `Transaction signed by ${recoveredAddress}, expected payer ${payer}`
518
+ };
519
+ }
520
+ } catch {
521
+ return {
522
+ isValid: false,
523
+ invalidReason: ErrErc20ApprovalTxInvalidSignature,
524
+ invalidMessage: "Failed to recover signer from the signed transaction"
525
+ };
526
+ }
527
+ } catch {
528
+ return {
529
+ isValid: false,
530
+ invalidReason: ErrErc20ApprovalTxParseFailed,
531
+ invalidMessage: "Failed to parse the signed transaction"
532
+ };
533
+ }
534
+ return { isValid: true };
535
+ }
536
+
537
+ // src/shared/permit2.ts
538
+ var import_viem8 = require("viem");
539
+
540
+ // src/multicall.ts
541
+ var import_viem7 = require("viem");
542
+ var MULTICALL3_ADDRESS = "0xcA11bde05977b3631167028862bE2a173976CA11";
543
+ var multicall3ABI = [
544
+ {
545
+ inputs: [
546
+ { name: "requireSuccess", type: "bool" },
547
+ {
548
+ name: "calls",
549
+ type: "tuple[]",
550
+ components: [
551
+ { name: "target", type: "address" },
552
+ { name: "callData", type: "bytes" }
553
+ ]
554
+ }
555
+ ],
556
+ name: "tryAggregate",
557
+ outputs: [
558
+ {
559
+ name: "returnData",
560
+ type: "tuple[]",
561
+ components: [
562
+ { name: "success", type: "bool" },
563
+ { name: "returnData", type: "bytes" }
564
+ ]
565
+ }
566
+ ],
567
+ stateMutability: "payable",
568
+ type: "function"
569
+ }
570
+ ];
571
+ async function multicall(readContract, calls) {
572
+ const aggregateCalls = calls.map((call) => {
573
+ if ("callData" in call) {
574
+ return { target: call.address, callData: call.callData };
575
+ }
576
+ const callData = (0, import_viem7.encodeFunctionData)({
577
+ abi: call.abi,
578
+ functionName: call.functionName,
579
+ args: call.args
580
+ });
581
+ return { target: call.address, callData };
582
+ });
583
+ const rawResults = await readContract({
584
+ address: MULTICALL3_ADDRESS,
585
+ abi: multicall3ABI,
586
+ functionName: "tryAggregate",
587
+ args: [false, aggregateCalls]
588
+ });
589
+ return rawResults.map((raw, i) => {
590
+ if (!raw.success) {
591
+ return {
592
+ status: "failure",
593
+ error: new Error(`multicall: call reverted (returnData: ${raw.returnData})`)
594
+ };
595
+ }
596
+ const call = calls[i];
597
+ if ("callData" in call) {
598
+ return { status: "success", result: void 0 };
599
+ }
600
+ try {
601
+ const decoded = (0, import_viem7.decodeFunctionResult)({
602
+ abi: call.abi,
603
+ functionName: call.functionName,
604
+ data: raw.returnData
605
+ });
606
+ return { status: "success", result: decoded };
607
+ } catch (err) {
608
+ return {
609
+ status: "failure",
610
+ error: err instanceof Error ? err : new Error(String(err))
611
+ };
612
+ }
613
+ });
614
+ }
615
+
616
+ // src/shared/permit2.ts
617
+ async function waitAndReturnSettleResponse(signer, tx, payload, payer) {
618
+ const receipt = await signer.waitForTransactionReceipt({ hash: tx });
619
+ if (receipt.status !== "success") {
620
+ return {
621
+ success: false,
622
+ errorReason: ErrInvalidTransactionState,
623
+ transaction: tx,
624
+ network: payload.accepted.network,
625
+ payer
626
+ };
627
+ }
628
+ return {
629
+ success: true,
630
+ transaction: tx,
631
+ network: payload.accepted.network,
632
+ payer
633
+ };
634
+ }
635
+ function mapSettleError(error, payload, payer) {
636
+ let errorReason = ErrTransactionFailed;
637
+ if (error instanceof Error) {
638
+ const message = error.message;
639
+ if (message.includes("Permit2612AmountMismatch")) {
640
+ errorReason = ErrPermit2612AmountMismatch;
641
+ } else if (message.includes("InvalidAmount")) {
642
+ errorReason = ErrPermit2InvalidAmount;
643
+ } else if (message.includes("InvalidDestination")) {
644
+ errorReason = ErrPermit2InvalidDestination;
645
+ } else if (message.includes("InvalidOwner")) {
646
+ errorReason = ErrPermit2InvalidOwner;
647
+ } else if (message.includes("PaymentTooEarly")) {
648
+ errorReason = ErrPermit2PaymentTooEarly;
649
+ } else if (message.includes("InvalidSignature") || message.includes("SignatureExpired")) {
650
+ errorReason = ErrPermit2InvalidSignature;
651
+ } else if (message.includes("InvalidNonce")) {
652
+ errorReason = ErrPermit2InvalidNonce;
653
+ } else if (message.includes("erc20_approval_tx_failed")) {
654
+ errorReason = ErrErc20ApprovalTxFailed;
655
+ } else if (message.includes("AmountExceedsPermitted")) {
656
+ errorReason = ErrUptoAmountExceedsPermitted;
657
+ } else if (message.includes("UnauthorizedFacilitator")) {
658
+ errorReason = ErrUptoUnauthorizedFacilitator;
659
+ } else {
660
+ errorReason = `${ErrTransactionFailed}: ${message.slice(0, 500)}`;
661
+ }
662
+ }
663
+ return {
664
+ success: false,
665
+ errorReason,
666
+ transaction: "",
667
+ network: payload.accepted.network,
668
+ payer
669
+ };
670
+ }
671
+ function validateEip2612PermitForPayment(info, payer, tokenAddress) {
672
+ if (!validateEip2612GasSponsoringInfo(info)) {
673
+ return { isValid: false, invalidReason: ErrInvalidEip2612ExtensionFormat };
674
+ }
675
+ if ((0, import_viem8.getAddress)(info.from) !== (0, import_viem8.getAddress)(payer)) {
676
+ return { isValid: false, invalidReason: ErrEip2612FromMismatch };
677
+ }
678
+ if ((0, import_viem8.getAddress)(info.asset) !== tokenAddress) {
679
+ return { isValid: false, invalidReason: ErrEip2612AssetMismatch };
680
+ }
681
+ if ((0, import_viem8.getAddress)(info.spender) !== (0, import_viem8.getAddress)(PERMIT2_ADDRESS)) {
682
+ return { isValid: false, invalidReason: ErrEip2612SpenderNotPermit2 };
683
+ }
684
+ const now = Math.floor(Date.now() / 1e3);
685
+ if (BigInt(info.deadline) < BigInt(now + 6)) {
686
+ return { isValid: false, invalidReason: ErrEip2612DeadlineExpired };
687
+ }
688
+ return { isValid: true };
689
+ }
690
+ async function simulatePermit2Settle(config, signer, settleArgs) {
691
+ try {
692
+ await signer.readContract({
693
+ address: config.proxyAddress,
694
+ abi: config.proxyABI,
695
+ functionName: "settle",
696
+ args: settleArgs
697
+ });
698
+ return true;
699
+ } catch {
700
+ return false;
701
+ }
702
+ }
703
+ async function simulatePermit2SettleWithPermit(config, signer, settleArgs, eip2612Info) {
704
+ try {
705
+ const { v, r, s } = splitEip2612Signature(eip2612Info.signature);
706
+ await signer.readContract({
707
+ address: config.proxyAddress,
708
+ abi: config.proxyABI,
709
+ functionName: "settleWithPermit",
710
+ args: [
711
+ {
712
+ value: BigInt(eip2612Info.amount),
713
+ deadline: BigInt(eip2612Info.deadline),
714
+ r,
715
+ s,
716
+ v
717
+ },
718
+ ...settleArgs
719
+ ]
720
+ });
721
+ return true;
722
+ } catch {
723
+ return false;
724
+ }
725
+ }
726
+ async function simulatePermit2SettleWithErc20Approval(config, extensionSigner, settleArgs, erc20Info) {
727
+ if (!extensionSigner.simulateTransactions) {
728
+ return false;
729
+ }
730
+ try {
731
+ const settleData = (0, import_viem8.encodeFunctionData)({
732
+ abi: config.proxyABI,
733
+ functionName: "settle",
734
+ args: settleArgs
735
+ });
736
+ return await extensionSigner.simulateTransactions([
737
+ erc20Info.signedTransaction,
738
+ { to: config.proxyAddress, data: settleData, gas: BigInt(3e5) }
739
+ ]);
740
+ } catch {
741
+ return false;
742
+ }
743
+ }
744
+ async function diagnosePermit2SimulationFailure(config, signer, tokenAddress, permit2Payload, amountRequired) {
745
+ const payer = permit2Payload.permit2Authorization.from;
746
+ const diagnosticCalls = [
747
+ {
748
+ address: config.proxyAddress,
749
+ abi: config.proxyABI,
750
+ functionName: "PERMIT2"
751
+ },
752
+ {
753
+ address: tokenAddress,
754
+ abi: eip3009ABI,
755
+ functionName: "balanceOf",
756
+ args: [payer]
757
+ },
758
+ {
759
+ address: tokenAddress,
760
+ abi: erc20AllowanceAbi,
761
+ functionName: "allowance",
762
+ args: [payer, PERMIT2_ADDRESS]
763
+ }
764
+ ];
765
+ try {
766
+ const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);
767
+ const [proxyResult, balanceResult, allowanceResult] = results;
768
+ if (proxyResult.status === "failure") {
769
+ return { isValid: false, invalidReason: ErrPermit2ProxyNotDeployed, payer };
770
+ }
771
+ if (balanceResult.status === "success") {
772
+ const balance = balanceResult.result;
773
+ if (balance < BigInt(amountRequired)) {
774
+ return { isValid: false, invalidReason: ErrPermit2InsufficientBalance, payer };
775
+ }
776
+ }
777
+ if (allowanceResult.status === "success") {
778
+ const allowance = allowanceResult.result;
779
+ if (allowance < BigInt(amountRequired)) {
780
+ return { isValid: false, invalidReason: ErrPermit2AllowanceRequired, payer };
781
+ }
782
+ }
783
+ } catch {
784
+ }
785
+ return { isValid: false, invalidReason: ErrPermit2SimulationFailed, payer };
786
+ }
787
+ async function checkPermit2Prerequisites(config, signer, tokenAddress, payer, amountRequired) {
788
+ const diagnosticCalls = [
789
+ {
790
+ address: config.proxyAddress,
791
+ abi: config.proxyABI,
792
+ functionName: "PERMIT2"
793
+ },
794
+ {
795
+ address: tokenAddress,
796
+ abi: eip3009ABI,
797
+ functionName: "balanceOf",
798
+ args: [payer]
799
+ }
800
+ ];
801
+ try {
802
+ const results = await multicall(signer.readContract.bind(signer), diagnosticCalls);
803
+ const [proxyResult, balanceResult] = results;
804
+ if (proxyResult.status === "failure") {
805
+ return { isValid: false, invalidReason: ErrPermit2ProxyNotDeployed, payer };
806
+ }
807
+ if (balanceResult.status === "success") {
808
+ const balance = balanceResult.result;
809
+ if (balance < BigInt(amountRequired)) {
810
+ return { isValid: false, invalidReason: ErrPermit2InsufficientBalance, payer };
811
+ }
812
+ }
813
+ } catch {
814
+ }
815
+ return { isValid: true, invalidReason: void 0, payer };
816
+ }
817
+ function buildUptoPermit2SettleArgs(permit2Payload, settlementAmount, facilitatorAddress) {
818
+ const { signature } = (0, import_viem8.parseErc6492Signature)(permit2Payload.signature);
819
+ return [
820
+ {
821
+ permitted: {
822
+ token: (0, import_viem8.getAddress)(permit2Payload.permit2Authorization.permitted.token),
823
+ amount: BigInt(permit2Payload.permit2Authorization.permitted.amount)
824
+ },
825
+ nonce: BigInt(permit2Payload.permit2Authorization.nonce),
826
+ deadline: BigInt(permit2Payload.permit2Authorization.deadline)
827
+ },
828
+ settlementAmount,
829
+ (0, import_viem8.getAddress)(permit2Payload.permit2Authorization.from),
830
+ {
831
+ to: (0, import_viem8.getAddress)(permit2Payload.permit2Authorization.witness.to),
832
+ facilitator: (0, import_viem8.getAddress)(facilitatorAddress),
833
+ validAfter: BigInt(permit2Payload.permit2Authorization.witness.validAfter)
834
+ },
835
+ signature
836
+ ];
837
+ }
838
+ function splitEip2612Signature(signature) {
839
+ const sig = signature.startsWith("0x") ? signature.slice(2) : signature;
840
+ if (sig.length !== 130) {
841
+ throw new Error(
842
+ `invalid EIP-2612 signature length: expected 65 bytes (130 hex chars), got ${sig.length / 2} bytes`
843
+ );
844
+ }
845
+ const r = `0x${sig.slice(0, 64)}`;
846
+ const s = `0x${sig.slice(64, 128)}`;
847
+ const v = parseInt(sig.slice(128, 130), 16);
848
+ return { v, r, s };
849
+ }
850
+
851
+ // src/upto/facilitator/permit2.ts
852
+ var uptoProxyConfig = {
853
+ proxyAddress: x402UptoPermit2ProxyAddress,
854
+ proxyABI: x402UptoPermit2ProxyABI
855
+ };
856
+ async function verifyUptoPermit2(signer, payload, requirements, permit2Payload, context, options) {
857
+ const payer = permit2Payload.permit2Authorization.from;
858
+ if (payload.accepted.scheme !== "upto" || requirements.scheme !== "upto") {
859
+ return {
860
+ isValid: false,
861
+ invalidReason: ErrUptoInvalidScheme,
862
+ payer
863
+ };
864
+ }
865
+ if (payload.accepted.network !== requirements.network) {
866
+ return {
867
+ isValid: false,
868
+ invalidReason: ErrUptoNetworkMismatch,
869
+ payer
870
+ };
871
+ }
872
+ const chainId = getEvmChainId(requirements.network);
873
+ const tokenAddress = (0, import_viem9.getAddress)(requirements.asset);
874
+ const assetBytecode = await signer.getCode({ address: tokenAddress });
875
+ if (!assetBytecode || assetBytecode === "0x") {
876
+ return { isValid: false, invalidReason: ErrAssetNotDeployedContract, payer };
877
+ }
878
+ if ((0, import_viem9.getAddress)(permit2Payload.permit2Authorization.spender) !== (0, import_viem9.getAddress)(x402UptoPermit2ProxyAddress)) {
879
+ return {
880
+ isValid: false,
881
+ invalidReason: "invalid_permit2_spender",
882
+ payer
883
+ };
884
+ }
885
+ if ((0, import_viem9.getAddress)(permit2Payload.permit2Authorization.witness.to) !== (0, import_viem9.getAddress)(requirements.payTo)) {
886
+ return {
887
+ isValid: false,
888
+ invalidReason: "invalid_permit2_recipient_mismatch",
889
+ payer
890
+ };
891
+ }
892
+ const facilitatorAddresses = signer.getAddresses();
893
+ const witnessFacilitator = (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.witness.facilitator);
894
+ const isFacilitatorMatch = facilitatorAddresses.some(
895
+ (addr) => (0, import_viem9.getAddress)(addr) === witnessFacilitator
896
+ );
897
+ if (!isFacilitatorMatch) {
898
+ return {
899
+ isValid: false,
900
+ invalidReason: ErrUptoFacilitatorMismatch,
901
+ payer
902
+ };
903
+ }
904
+ const now = Math.floor(Date.now() / 1e3);
905
+ if (BigInt(permit2Payload.permit2Authorization.deadline) < BigInt(now + 6)) {
906
+ return {
907
+ isValid: false,
908
+ invalidReason: "permit2_deadline_expired",
909
+ payer
910
+ };
911
+ }
912
+ if (BigInt(permit2Payload.permit2Authorization.witness.validAfter) > BigInt(now)) {
913
+ return {
914
+ isValid: false,
915
+ invalidReason: "permit2_not_yet_valid",
916
+ payer
917
+ };
918
+ }
919
+ if (BigInt(permit2Payload.permit2Authorization.permitted.amount) !== BigInt(requirements.amount)) {
920
+ return {
921
+ isValid: false,
922
+ invalidReason: ErrPermit2AmountMismatch,
923
+ payer
924
+ };
925
+ }
926
+ if ((0, import_viem9.getAddress)(permit2Payload.permit2Authorization.permitted.token) !== tokenAddress) {
927
+ return {
928
+ isValid: false,
929
+ invalidReason: "permit2_token_mismatch",
930
+ payer
931
+ };
932
+ }
933
+ const permit2TypedData = {
934
+ types: uptoPermit2WitnessTypes,
935
+ primaryType: "PermitWitnessTransferFrom",
936
+ domain: {
937
+ name: "Permit2",
938
+ chainId,
939
+ verifyingContract: PERMIT2_ADDRESS
940
+ },
941
+ message: {
942
+ permitted: {
943
+ token: (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.permitted.token),
944
+ amount: BigInt(permit2Payload.permit2Authorization.permitted.amount)
945
+ },
946
+ spender: (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.spender),
947
+ nonce: BigInt(permit2Payload.permit2Authorization.nonce),
948
+ deadline: BigInt(permit2Payload.permit2Authorization.deadline),
949
+ witness: {
950
+ to: (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.witness.to),
951
+ facilitator: (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.witness.facilitator),
952
+ validAfter: BigInt(permit2Payload.permit2Authorization.witness.validAfter)
953
+ }
954
+ }
955
+ };
956
+ let signatureValid = false;
957
+ try {
958
+ signatureValid = await signer.verifyTypedData({
959
+ address: payer,
960
+ ...permit2TypedData,
961
+ signature: permit2Payload.signature
962
+ });
963
+ } catch {
964
+ signatureValid = false;
965
+ }
966
+ if (!signatureValid) {
967
+ const bytecode = await signer.getCode({ address: payer });
968
+ const isDeployedContract = bytecode && bytecode !== "0x";
969
+ if (!isDeployedContract) {
970
+ return {
971
+ isValid: false,
972
+ invalidReason: "invalid_permit2_signature",
973
+ payer
974
+ };
975
+ }
976
+ }
977
+ if (options?.simulate === false) {
978
+ return { isValid: true, invalidReason: void 0, payer };
979
+ }
980
+ const facilitatorAddress = (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.witness.facilitator);
981
+ const uptoSettleArgs = buildUptoPermit2SettleArgs(
982
+ permit2Payload,
983
+ BigInt(requirements.amount),
984
+ facilitatorAddress
985
+ );
986
+ const eip2612InfoForSim = extractEip2612GasSponsoringInfo(payload);
987
+ if (eip2612InfoForSim) {
988
+ const fieldResult = validateEip2612PermitForPayment(eip2612InfoForSim, payer, tokenAddress);
989
+ if (!fieldResult.isValid) {
990
+ return { isValid: false, invalidReason: fieldResult.invalidReason, payer };
991
+ }
992
+ const simOk2 = await simulatePermit2SettleWithPermit(
993
+ uptoProxyConfig,
994
+ signer,
995
+ uptoSettleArgs,
996
+ eip2612InfoForSim
997
+ );
998
+ if (!simOk2) {
999
+ return diagnosePermit2SimulationFailure(
1000
+ uptoProxyConfig,
1001
+ signer,
1002
+ tokenAddress,
1003
+ permit2Payload,
1004
+ requirements.amount
1005
+ );
1006
+ }
1007
+ return { isValid: true, invalidReason: void 0, payer };
1008
+ }
1009
+ const erc20GasSponsorshipExtension = context?.getExtension(
1010
+ ERC20_APPROVAL_GAS_SPONSORING_KEY
1011
+ );
1012
+ if (erc20GasSponsorshipExtension) {
1013
+ const erc20Info = extractErc20ApprovalGasSponsoringInfo(payload);
1014
+ if (erc20Info) {
1015
+ const fieldResult = await validateErc20ApprovalForPayment(erc20Info, payer, tokenAddress);
1016
+ if (!fieldResult.isValid) {
1017
+ return { isValid: false, invalidReason: fieldResult.invalidReason, payer };
1018
+ }
1019
+ const extensionSigner = resolveErc20ApprovalExtensionSigner(
1020
+ erc20GasSponsorshipExtension,
1021
+ requirements.network
1022
+ );
1023
+ if (extensionSigner?.simulateTransactions) {
1024
+ const simOk2 = await simulatePermit2SettleWithErc20Approval(
1025
+ uptoProxyConfig,
1026
+ extensionSigner,
1027
+ uptoSettleArgs,
1028
+ erc20Info
1029
+ );
1030
+ if (!simOk2) {
1031
+ return diagnosePermit2SimulationFailure(
1032
+ uptoProxyConfig,
1033
+ signer,
1034
+ tokenAddress,
1035
+ permit2Payload,
1036
+ requirements.amount
1037
+ );
1038
+ }
1039
+ return { isValid: true, invalidReason: void 0, payer };
1040
+ }
1041
+ return checkPermit2Prerequisites(
1042
+ uptoProxyConfig,
1043
+ signer,
1044
+ tokenAddress,
1045
+ payer,
1046
+ requirements.amount
1047
+ );
1048
+ }
1049
+ }
1050
+ const simOk = await simulatePermit2Settle(uptoProxyConfig, signer, uptoSettleArgs);
1051
+ if (!simOk) {
1052
+ return diagnosePermit2SimulationFailure(
1053
+ uptoProxyConfig,
1054
+ signer,
1055
+ tokenAddress,
1056
+ permit2Payload,
1057
+ requirements.amount
1058
+ );
1059
+ }
1060
+ return {
1061
+ isValid: true,
1062
+ invalidReason: void 0,
1063
+ payer
1064
+ };
1065
+ }
1066
+ async function settleUptoPermit2(signer, payload, requirements, permit2Payload, context, config) {
1067
+ const payer = permit2Payload.permit2Authorization.from;
1068
+ const settlementAmount = BigInt(requirements.amount);
1069
+ const verifyRequirements = {
1070
+ ...requirements,
1071
+ amount: permit2Payload.permit2Authorization.permitted.amount
1072
+ };
1073
+ const valid = await verifyUptoPermit2(
1074
+ signer,
1075
+ payload,
1076
+ verifyRequirements,
1077
+ permit2Payload,
1078
+ context,
1079
+ { simulate: config?.simulateInSettle ?? true }
1080
+ );
1081
+ if (!valid.isValid) {
1082
+ return {
1083
+ success: false,
1084
+ network: payload.accepted.network,
1085
+ transaction: "",
1086
+ errorReason: valid.invalidReason ?? "invalid_scheme",
1087
+ payer
1088
+ };
1089
+ }
1090
+ if (settlementAmount === 0n) {
1091
+ return {
1092
+ success: true,
1093
+ transaction: "",
1094
+ network: payload.accepted.network,
1095
+ payer,
1096
+ amount: "0"
1097
+ };
1098
+ }
1099
+ if (settlementAmount > BigInt(permit2Payload.permit2Authorization.permitted.amount)) {
1100
+ return {
1101
+ success: false,
1102
+ network: payload.accepted.network,
1103
+ transaction: "",
1104
+ errorReason: ErrUptoSettlementExceedsAmount,
1105
+ payer
1106
+ };
1107
+ }
1108
+ const facilitatorAddress = (0, import_viem9.getAddress)(permit2Payload.permit2Authorization.witness.facilitator);
1109
+ const dataSuffix = await resolveDataSuffix(context, {
1110
+ paymentPayload: payload,
1111
+ paymentRequirements: requirements
1112
+ });
1113
+ const eip2612Info = extractEip2612GasSponsoringInfo(payload);
1114
+ if (eip2612Info) {
1115
+ return settleUptoWithEIP2612(
1116
+ signer,
1117
+ payload,
1118
+ permit2Payload,
1119
+ eip2612Info,
1120
+ settlementAmount,
1121
+ facilitatorAddress,
1122
+ dataSuffix
1123
+ );
1124
+ }
1125
+ const erc20Info = extractErc20ApprovalGasSponsoringInfo(payload);
1126
+ if (erc20Info) {
1127
+ const erc20GasSponsorshipExtension = context?.getExtension(
1128
+ ERC20_APPROVAL_GAS_SPONSORING_KEY
1129
+ );
1130
+ const extensionSigner = resolveErc20ApprovalExtensionSigner(
1131
+ erc20GasSponsorshipExtension,
1132
+ payload.accepted.network
1133
+ );
1134
+ if (extensionSigner) {
1135
+ return settleUptoWithERC20Approval(
1136
+ extensionSigner,
1137
+ payload,
1138
+ permit2Payload,
1139
+ erc20Info,
1140
+ settlementAmount,
1141
+ facilitatorAddress,
1142
+ dataSuffix
1143
+ );
1144
+ }
1145
+ }
1146
+ return settleUptoDirect(
1147
+ signer,
1148
+ payload,
1149
+ permit2Payload,
1150
+ settlementAmount,
1151
+ facilitatorAddress,
1152
+ dataSuffix
1153
+ );
1154
+ }
1155
+ async function settleUptoWithEIP2612(signer, payload, permit2Payload, eip2612Info, settlementAmount, facilitatorAddress, dataSuffix) {
1156
+ const payer = permit2Payload.permit2Authorization.from;
1157
+ try {
1158
+ const { v, r, s } = splitEip2612Signature(eip2612Info.signature);
1159
+ const tx = await signer.writeContract({
1160
+ address: uptoProxyConfig.proxyAddress,
1161
+ abi: uptoProxyConfig.proxyABI,
1162
+ functionName: "settleWithPermit",
1163
+ args: [
1164
+ {
1165
+ value: BigInt(eip2612Info.amount),
1166
+ deadline: BigInt(eip2612Info.deadline),
1167
+ r,
1168
+ s,
1169
+ v
1170
+ },
1171
+ ...buildUptoPermit2SettleArgs(permit2Payload, settlementAmount, facilitatorAddress)
1172
+ ],
1173
+ dataSuffix
1174
+ });
1175
+ const response = await waitAndReturnSettleResponse(signer, tx, payload, payer);
1176
+ return { ...response, amount: settlementAmount.toString() };
1177
+ } catch (error) {
1178
+ return mapSettleError(error, payload, payer);
1179
+ }
1180
+ }
1181
+ async function settleUptoWithERC20Approval(extensionSigner, payload, permit2Payload, erc20Info, settlementAmount, facilitatorAddress, dataSuffix) {
1182
+ const payer = permit2Payload.permit2Authorization.from;
1183
+ try {
1184
+ const settleData = appendDataSuffix(
1185
+ (0, import_viem9.encodeFunctionData)({
1186
+ abi: uptoProxyConfig.proxyABI,
1187
+ functionName: "settle",
1188
+ args: buildUptoPermit2SettleArgs(permit2Payload, settlementAmount, facilitatorAddress)
1189
+ }),
1190
+ dataSuffix
1191
+ );
1192
+ const txHashes = await extensionSigner.sendTransactions([
1193
+ erc20Info.signedTransaction,
1194
+ { to: uptoProxyConfig.proxyAddress, data: settleData, gas: BigInt(3e5) }
1195
+ ]);
1196
+ const settleTxHash = txHashes[txHashes.length - 1];
1197
+ const response = await waitAndReturnSettleResponse(
1198
+ extensionSigner,
1199
+ settleTxHash,
1200
+ payload,
1201
+ payer
1202
+ );
1203
+ return { ...response, amount: settlementAmount.toString() };
1204
+ } catch (error) {
1205
+ return mapSettleError(error, payload, payer);
1206
+ }
1207
+ }
1208
+ async function settleUptoDirect(signer, payload, permit2Payload, settlementAmount, facilitatorAddress, dataSuffix) {
1209
+ const payer = permit2Payload.permit2Authorization.from;
1210
+ try {
1211
+ const tx = await signer.writeContract({
1212
+ address: uptoProxyConfig.proxyAddress,
1213
+ abi: uptoProxyConfig.proxyABI,
1214
+ functionName: "settle",
1215
+ args: buildUptoPermit2SettleArgs(permit2Payload, settlementAmount, facilitatorAddress),
1216
+ dataSuffix
1217
+ });
1218
+ const response = await waitAndReturnSettleResponse(signer, tx, payload, payer);
1219
+ return { ...response, amount: settlementAmount.toString() };
1220
+ } catch (error) {
1221
+ return mapSettleError(error, payload, payer);
1222
+ }
1223
+ }
1224
+
1225
+ // src/upto/facilitator/scheme.ts
1226
+ var UptoEvmScheme = class {
1227
+ /**
1228
+ * Creates a new UptoEvmScheme facilitator instance.
1229
+ *
1230
+ * @param signer - The EVM signer for facilitator operations
1231
+ */
1232
+ constructor(signer) {
1233
+ this.signer = signer;
1234
+ this.scheme = "upto";
1235
+ this.caipFamily = "eip155:*";
1236
+ }
1237
+ /**
1238
+ * Returns extra metadata required by the upto scheme, including the facilitator address.
1239
+ *
1240
+ * @param _ - The network identifier (unused)
1241
+ * @returns Object with facilitatorAddress, or undefined if no signer addresses are available
1242
+ */
1243
+ getExtra(_) {
1244
+ const addresses = this.signer.getAddresses();
1245
+ if (addresses.length === 0) {
1246
+ return void 0;
1247
+ }
1248
+ return { facilitatorAddress: addresses[Math.floor(Math.random() * addresses.length)] };
1249
+ }
1250
+ /**
1251
+ * Returns the list of facilitator signer addresses for the upto scheme.
1252
+ *
1253
+ * @param _ - The network identifier (unused)
1254
+ * @returns Array of facilitator signer addresses
1255
+ */
1256
+ getSigners(_) {
1257
+ return [...this.signer.getAddresses()];
1258
+ }
1259
+ /**
1260
+ * Verifies an upto Permit2 payment payload against the given requirements.
1261
+ *
1262
+ * @param payload - The payment payload to verify
1263
+ * @param requirements - The payment requirements to verify against
1264
+ * @param context - Optional facilitator context
1265
+ * @param _ - Payment required extensions (unused; reserved for interface parity)
1266
+ * @returns Promise resolving to a verification response
1267
+ */
1268
+ async verify(payload, requirements, context, _) {
1269
+ const rawPayload = payload.payload;
1270
+ if (!isUptoPermit2Payload(rawPayload)) {
1271
+ return { isValid: false, invalidReason: "unsupported_payload_type", payer: "" };
1272
+ }
1273
+ return verifyUptoPermit2(
1274
+ this.signer,
1275
+ payload,
1276
+ requirements,
1277
+ rawPayload,
1278
+ context
1279
+ );
1280
+ }
1281
+ /**
1282
+ * Settles an upto Permit2 payment on-chain.
1283
+ *
1284
+ * @param payload - The payment payload to settle
1285
+ * @param requirements - The payment requirements
1286
+ * @param context - Optional facilitator context
1287
+ * @returns Promise resolving to a settlement response
1288
+ */
1289
+ async settle(payload, requirements, context) {
1290
+ const rawPayload = payload.payload;
1291
+ if (!isUptoPermit2Payload(rawPayload)) {
1292
+ return {
1293
+ success: false,
1294
+ network: payload.accepted.network,
1295
+ transaction: "",
1296
+ errorReason: "unsupported_payload_type",
1297
+ payer: ""
1298
+ };
1299
+ }
1300
+ return settleUptoPermit2(
1301
+ this.signer,
1302
+ payload,
1303
+ requirements,
1304
+ rawPayload,
1305
+ context
1306
+ );
1307
+ }
1308
+ };
1309
+ // Annotate the CommonJS export names for ESM import in node:
1310
+ 0 && (module.exports = {
1311
+ UptoEvmScheme
1312
+ });
1313
+ //# sourceMappingURL=index.js.map