agents 0.2.9 → 0.2.11

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 (94) hide show
  1. package/dist/ai-chat-agent.d.ts +15 -18
  2. package/dist/ai-chat-agent.js +544 -656
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
  6. package/dist/ai-chat-v5-migration.d.ts +7 -4
  7. package/dist/ai-chat-v5-migration.js +3 -20
  8. package/dist/ai-react.d.ts +14 -24
  9. package/dist/ai-react.js +257 -343
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types-B0GBFDwi.js +20 -0
  12. package/dist/ai-types-B0GBFDwi.js.map +1 -0
  13. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  14. package/dist/ai-types.d.ts +6 -92
  15. package/dist/ai-types.js +3 -8
  16. package/dist/client-C-u-lCFT.d.ts +5311 -0
  17. package/dist/client-CmMi85Sj.d.ts +104 -0
  18. package/dist/client-WbaRgKYN.js +788 -0
  19. package/dist/client-WbaRgKYN.js.map +1 -0
  20. package/dist/client-zS-OCVJA.js +117 -0
  21. package/dist/client-zS-OCVJA.js.map +1 -0
  22. package/dist/client.d.ts +11 -92
  23. package/dist/client.js +4 -13
  24. package/dist/codemode/ai.d.ts +19 -17
  25. package/dist/codemode/ai.js +90 -5139
  26. package/dist/codemode/ai.js.map +1 -1
  27. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  29. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  30. package/dist/index-DWcUTPtX.d.ts +558 -0
  31. package/dist/index-W4JUkafc.d.ts +54 -0
  32. package/dist/index.d.ts +55 -542
  33. package/dist/index.js +7 -32
  34. package/dist/mcp/client.d.ts +4 -12
  35. package/dist/mcp/client.js +3 -10
  36. package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
  37. package/dist/mcp/do-oauth-client-provider.js +3 -8
  38. package/dist/mcp/index.d.ts +72 -76
  39. package/dist/mcp/index.js +830 -1082
  40. package/dist/mcp/index.js.map +1 -1
  41. package/dist/mcp/x402.d.ts +22 -27
  42. package/dist/mcp/x402.js +186 -3187
  43. package/dist/mcp/x402.js.map +1 -1
  44. package/dist/{mcp-BH1fJeiU.d.ts → mcp-BEwaCsxO.d.ts} +6 -3
  45. package/dist/observability/index.d.ts +3 -34
  46. package/dist/observability/index.js +7 -12
  47. package/dist/react-B8BT6PYZ.d.ts +113 -0
  48. package/dist/react.d.ts +10 -127
  49. package/dist/react.js +173 -200
  50. package/dist/react.js.map +1 -1
  51. package/dist/schedule.d.ts +13 -10
  52. package/dist/schedule.js +43 -33
  53. package/dist/schedule.js.map +1 -1
  54. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  55. package/dist/serializable.d.ts +7 -32
  56. package/dist/serializable.js +1 -1
  57. package/dist/src-C9xZ0CrH.js +1179 -0
  58. package/dist/src-C9xZ0CrH.js.map +1 -0
  59. package/package.json +9 -3
  60. package/dist/_esm-LV5FJ3HK.js +0 -3922
  61. package/dist/_esm-LV5FJ3HK.js.map +0 -1
  62. package/dist/ai-chat-v5-migration.js.map +0 -1
  63. package/dist/ai-types.js.map +0 -1
  64. package/dist/ccip-CMBYN64O.js +0 -15
  65. package/dist/ccip-CMBYN64O.js.map +0 -1
  66. package/dist/chunk-5Y6BEZDY.js +0 -276
  67. package/dist/chunk-5Y6BEZDY.js.map +0 -1
  68. package/dist/chunk-BER7KXUJ.js +0 -18
  69. package/dist/chunk-BER7KXUJ.js.map +0 -1
  70. package/dist/chunk-C2OEBJZ2.js +0 -113
  71. package/dist/chunk-C2OEBJZ2.js.map +0 -1
  72. package/dist/chunk-JJBFIGUC.js +0 -5202
  73. package/dist/chunk-JJBFIGUC.js.map +0 -1
  74. package/dist/chunk-PR4QN5HX.js +0 -43
  75. package/dist/chunk-PR4QN5HX.js.map +0 -1
  76. package/dist/chunk-QEVM4BVL.js +0 -116
  77. package/dist/chunk-QEVM4BVL.js.map +0 -1
  78. package/dist/chunk-TYAY6AU6.js +0 -159
  79. package/dist/chunk-TYAY6AU6.js.map +0 -1
  80. package/dist/chunk-UJVEAURM.js +0 -150
  81. package/dist/chunk-UJVEAURM.js.map +0 -1
  82. package/dist/chunk-XGMKNUJA.js +0 -1343
  83. package/dist/chunk-XGMKNUJA.js.map +0 -1
  84. package/dist/chunk-ZMMHNOMZ.js +0 -942
  85. package/dist/chunk-ZMMHNOMZ.js.map +0 -1
  86. package/dist/client-C8tswVoM.d.ts +0 -5248
  87. package/dist/client.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/mcp/client.js.map +0 -1
  90. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  91. package/dist/observability/index.js.map +0 -1
  92. package/dist/secp256k1-M22GZP2U.js +0 -2193
  93. package/dist/secp256k1-M22GZP2U.js.map +0 -1
  94. package/dist/serializable.js.map +0 -1
package/dist/mcp/x402.js CHANGED
@@ -1,3195 +1,194 @@
1
- import {
2
- AbiDecodingZeroDataError,
3
- AtomicReadyWalletRejectedUpgradeError,
4
- AtomicityNotSupportedError,
5
- BaseError,
6
- BundleTooLargeError,
7
- BytesSizeMismatchError,
8
- ChainDisconnectedError,
9
- ChainMismatchError,
10
- ChainNotFoundError,
11
- ContractFunctionExecutionError,
12
- ContractFunctionRevertedError,
13
- ContractFunctionZeroDataError,
14
- DuplicateIdError,
15
- FeeCapTooHighError,
16
- HttpRequestError,
17
- InternalRpcError,
18
- InvalidAddressError,
19
- InvalidChainIdError,
20
- InvalidInputRpcError,
21
- InvalidLegacyVError,
22
- InvalidParamsRpcError,
23
- InvalidRequestRpcError,
24
- InvalidSerializableTransactionError,
25
- InvalidStorageKeySizeError,
26
- JsonRpcVersionUnsupportedError,
27
- LimitExceededRpcError,
28
- LruMap,
29
- MethodNotFoundRpcError,
30
- MethodNotSupportedRpcError,
31
- ParseRpcError,
32
- ProviderDisconnectedError,
33
- RawContractError,
34
- ResourceNotFoundRpcError,
35
- ResourceUnavailableRpcError,
36
- RpcRequestError,
37
- SwitchChainError,
38
- TimeoutError,
39
- TipAboveFeeCapError,
40
- TransactionExecutionError,
41
- TransactionRejectedRpcError,
42
- UnauthorizedProviderError,
43
- UnknownBundleIdError,
44
- UnknownNodeError,
45
- UnknownRpcError,
46
- UnsupportedChainIdError,
47
- UnsupportedNonOptionalCapabilityError,
48
- UnsupportedProviderMethodError,
49
- UserRejectedRequestError,
50
- assertRequest,
51
- bytesRegex,
52
- bytesToHex,
53
- checksumAddress,
54
- concat,
55
- concatHex,
56
- createBatchScheduler,
57
- createCursor,
58
- defineFormatter,
59
- encodeDeployData,
60
- encodeFunctionData,
61
- extract,
62
- formatEther,
63
- formatGwei,
64
- formatTransactionRequest,
65
- getAddress,
66
- getNodeError,
67
- hexToBigInt,
68
- hexToBytes,
69
- hexToNumber,
70
- integerRegex,
71
- isAddress,
72
- isAddressEqual,
73
- isHex,
74
- keccak256,
75
- maxUint256,
76
- numberToHex,
77
- parseAccount,
78
- prettyPrint,
79
- serializeStateOverride,
80
- size,
81
- slice,
82
- sliceHex,
83
- stringToHex,
84
- stringify,
85
- toBytes,
86
- toHex,
87
- trim,
88
- withResolvers
89
- } from "../chunk-JJBFIGUC.js";
90
- import {
91
- sha256
92
- } from "../chunk-5Y6BEZDY.js";
93
- import "../chunk-TYAY6AU6.js";
94
- import "../chunk-PR4QN5HX.js";
95
-
96
- // ../../node_modules/viem/_esm/utils/chain/defineChain.js
97
- function defineChain(chain) {
98
- return {
99
- formatters: void 0,
100
- fees: void 0,
101
- serializers: void 0,
102
- ...chain
103
- };
104
- }
105
-
106
- // ../../node_modules/viem/_esm/utils/formatters/transaction.js
107
- var transactionType = {
108
- "0x0": "legacy",
109
- "0x1": "eip2930",
110
- "0x2": "eip1559",
111
- "0x3": "eip4844",
112
- "0x4": "eip7702"
113
- };
114
- function formatTransaction(transaction) {
115
- const transaction_ = {
116
- ...transaction,
117
- blockHash: transaction.blockHash ? transaction.blockHash : null,
118
- blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
119
- chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0,
120
- gas: transaction.gas ? BigInt(transaction.gas) : void 0,
121
- gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
122
- maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0,
123
- maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
124
- maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
125
- nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
126
- to: transaction.to ? transaction.to : null,
127
- transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
128
- type: transaction.type ? transactionType[transaction.type] : void 0,
129
- typeHex: transaction.type ? transaction.type : void 0,
130
- value: transaction.value ? BigInt(transaction.value) : void 0,
131
- v: transaction.v ? BigInt(transaction.v) : void 0
132
- };
133
- if (transaction.authorizationList)
134
- transaction_.authorizationList = formatAuthorizationList(transaction.authorizationList);
135
- transaction_.yParity = (() => {
136
- if (transaction.yParity)
137
- return Number(transaction.yParity);
138
- if (typeof transaction_.v === "bigint") {
139
- if (transaction_.v === 0n || transaction_.v === 27n)
140
- return 0;
141
- if (transaction_.v === 1n || transaction_.v === 28n)
142
- return 1;
143
- if (transaction_.v >= 35n)
144
- return transaction_.v % 2n === 0n ? 1 : 0;
145
- }
146
- return void 0;
147
- })();
148
- if (transaction_.type === "legacy") {
149
- delete transaction_.accessList;
150
- delete transaction_.maxFeePerBlobGas;
151
- delete transaction_.maxFeePerGas;
152
- delete transaction_.maxPriorityFeePerGas;
153
- delete transaction_.yParity;
154
- }
155
- if (transaction_.type === "eip2930") {
156
- delete transaction_.maxFeePerBlobGas;
157
- delete transaction_.maxFeePerGas;
158
- delete transaction_.maxPriorityFeePerGas;
159
- }
160
- if (transaction_.type === "eip1559") {
161
- delete transaction_.maxFeePerBlobGas;
162
- }
163
- return transaction_;
164
- }
165
- var defineTransaction = /* @__PURE__ */ defineFormatter("transaction", formatTransaction);
166
- function formatAuthorizationList(authorizationList) {
167
- return authorizationList.map((authorization) => ({
168
- address: authorization.address,
169
- chainId: Number(authorization.chainId),
170
- nonce: Number(authorization.nonce),
171
- r: authorization.r,
172
- s: authorization.s,
173
- yParity: Number(authorization.yParity)
174
- }));
175
- }
176
-
177
- // ../../node_modules/viem/_esm/utils/formatters/block.js
178
- function formatBlock(block) {
179
- const transactions = (block.transactions ?? []).map((transaction) => {
180
- if (typeof transaction === "string")
181
- return transaction;
182
- return formatTransaction(transaction);
183
- });
184
- return {
185
- ...block,
186
- baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
187
- blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0,
188
- difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
189
- excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0,
190
- gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
191
- gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
192
- hash: block.hash ? block.hash : null,
193
- logsBloom: block.logsBloom ? block.logsBloom : null,
194
- nonce: block.nonce ? block.nonce : null,
195
- number: block.number ? BigInt(block.number) : null,
196
- size: block.size ? BigInt(block.size) : void 0,
197
- timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
198
- transactions,
199
- totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
200
- };
201
- }
202
- var defineBlock = /* @__PURE__ */ defineFormatter("block", formatBlock);
203
-
204
- // ../../node_modules/viem/_esm/utils/formatters/log.js
205
- function formatLog(log, { args, eventName } = {}) {
206
- return {
207
- ...log,
208
- blockHash: log.blockHash ? log.blockHash : null,
209
- blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
210
- logIndex: log.logIndex ? Number(log.logIndex) : null,
211
- transactionHash: log.transactionHash ? log.transactionHash : null,
212
- transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null,
213
- ...eventName ? { args, eventName } : {}
214
- };
215
- }
216
-
217
- // ../../node_modules/viem/_esm/utils/formatters/transactionReceipt.js
218
- var receiptStatuses = {
219
- "0x0": "reverted",
220
- "0x1": "success"
221
- };
222
- function formatTransactionReceipt(transactionReceipt) {
223
- const receipt = {
224
- ...transactionReceipt,
225
- blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null,
226
- contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null,
227
- cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
228
- effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
229
- gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
230
- logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null,
231
- to: transactionReceipt.to ? transactionReceipt.to : null,
232
- transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
233
- status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null,
234
- type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null
235
- };
236
- if (transactionReceipt.blobGasPrice)
237
- receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice);
238
- if (transactionReceipt.blobGasUsed)
239
- receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed);
240
- return receipt;
241
- }
242
- var defineTransactionReceipt = /* @__PURE__ */ defineFormatter("transactionReceipt", formatTransactionReceipt);
243
-
244
- // ../../node_modules/viem/_esm/utils/encoding/toRlp.js
245
- function toRlp(bytes, to = "hex") {
246
- const encodable = getEncodable(bytes);
247
- const cursor = createCursor(new Uint8Array(encodable.length));
248
- encodable.encode(cursor);
249
- if (to === "hex")
250
- return bytesToHex(cursor.bytes);
251
- return cursor.bytes;
252
- }
253
- function getEncodable(bytes) {
254
- if (Array.isArray(bytes))
255
- return getEncodableList(bytes.map((x) => getEncodable(x)));
256
- return getEncodableBytes(bytes);
257
- }
258
- function getEncodableList(list) {
259
- const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
260
- const sizeOfBodyLength = getSizeOfLength(bodyLength);
261
- const length = (() => {
262
- if (bodyLength <= 55)
263
- return 1 + bodyLength;
264
- return 1 + sizeOfBodyLength + bodyLength;
265
- })();
266
- return {
267
- length,
268
- encode(cursor) {
269
- if (bodyLength <= 55) {
270
- cursor.pushByte(192 + bodyLength);
271
- } else {
272
- cursor.pushByte(192 + 55 + sizeOfBodyLength);
273
- if (sizeOfBodyLength === 1)
274
- cursor.pushUint8(bodyLength);
275
- else if (sizeOfBodyLength === 2)
276
- cursor.pushUint16(bodyLength);
277
- else if (sizeOfBodyLength === 3)
278
- cursor.pushUint24(bodyLength);
279
- else
280
- cursor.pushUint32(bodyLength);
281
- }
282
- for (const { encode } of list) {
283
- encode(cursor);
284
- }
285
- }
286
- };
287
- }
288
- function getEncodableBytes(bytesOrHex) {
289
- const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex;
290
- const sizeOfBytesLength = getSizeOfLength(bytes.length);
291
- const length = (() => {
292
- if (bytes.length === 1 && bytes[0] < 128)
293
- return 1;
294
- if (bytes.length <= 55)
295
- return 1 + bytes.length;
296
- return 1 + sizeOfBytesLength + bytes.length;
297
- })();
298
- return {
299
- length,
300
- encode(cursor) {
301
- if (bytes.length === 1 && bytes[0] < 128) {
302
- cursor.pushBytes(bytes);
303
- } else if (bytes.length <= 55) {
304
- cursor.pushByte(128 + bytes.length);
305
- cursor.pushBytes(bytes);
306
- } else {
307
- cursor.pushByte(128 + 55 + sizeOfBytesLength);
308
- if (sizeOfBytesLength === 1)
309
- cursor.pushUint8(bytes.length);
310
- else if (sizeOfBytesLength === 2)
311
- cursor.pushUint16(bytes.length);
312
- else if (sizeOfBytesLength === 3)
313
- cursor.pushUint24(bytes.length);
314
- else
315
- cursor.pushUint32(bytes.length);
316
- cursor.pushBytes(bytes);
317
- }
318
- }
319
- };
320
- }
321
- function getSizeOfLength(length) {
322
- if (length < 2 ** 8)
323
- return 1;
324
- if (length < 2 ** 16)
325
- return 2;
326
- if (length < 2 ** 24)
327
- return 3;
328
- if (length < 2 ** 32)
329
- return 4;
330
- throw new BaseError("Length is too large.");
331
- }
332
-
333
- // ../../node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js
334
- function serializeAuthorizationList(authorizationList) {
335
- if (!authorizationList || authorizationList.length === 0)
336
- return [];
337
- const serializedAuthorizationList = [];
338
- for (const authorization of authorizationList) {
339
- const { chainId, nonce, ...signature } = authorization;
340
- const contractAddress = authorization.address;
341
- serializedAuthorizationList.push([
342
- chainId ? toHex(chainId) : "0x",
343
- contractAddress,
344
- nonce ? toHex(nonce) : "0x",
345
- ...toYParitySignatureArray({}, signature)
346
- ]);
347
- }
348
- return serializedAuthorizationList;
349
- }
350
-
351
- // ../../node_modules/viem/_esm/utils/blob/blobsToCommitments.js
352
- function blobsToCommitments(parameters) {
353
- const { kzg } = parameters;
354
- const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
355
- const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
356
- const commitments = [];
357
- for (const blob of blobs)
358
- commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
359
- return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x));
360
- }
361
-
362
- // ../../node_modules/viem/_esm/utils/blob/blobsToProofs.js
363
- function blobsToProofs(parameters) {
364
- const { kzg } = parameters;
365
- const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
366
- const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
367
- const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments;
368
- const proofs = [];
369
- for (let i = 0; i < blobs.length; i++) {
370
- const blob = blobs[i];
371
- const commitment = commitments[i];
372
- proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
373
- }
374
- return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x));
375
- }
376
-
377
- // ../../node_modules/@noble/hashes/esm/sha256.js
378
- var sha2562 = sha256;
379
-
380
- // ../../node_modules/viem/_esm/utils/hash/sha256.js
381
- function sha2563(value, to_) {
382
- const to = to_ || "hex";
383
- const bytes = sha2562(isHex(value, { strict: false }) ? toBytes(value) : value);
384
- if (to === "bytes")
385
- return bytes;
386
- return toHex(bytes);
387
- }
388
-
389
- // ../../node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js
390
- function commitmentToVersionedHash(parameters) {
391
- const { commitment, version = 1 } = parameters;
392
- const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes");
393
- const versionedHash = sha2563(commitment, "bytes");
394
- versionedHash.set([version], 0);
395
- return to === "bytes" ? versionedHash : bytesToHex(versionedHash);
396
- }
397
-
398
- // ../../node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js
399
- function commitmentsToVersionedHashes(parameters) {
400
- const { commitments, version } = parameters;
401
- const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes");
402
- const hashes = [];
403
- for (const commitment of commitments) {
404
- hashes.push(commitmentToVersionedHash({
405
- commitment,
406
- to,
407
- version
408
- }));
409
- }
410
- return hashes;
411
- }
412
-
413
- // ../../node_modules/viem/_esm/constants/blob.js
414
- var blobsPerTransaction = 6;
415
- var bytesPerFieldElement = 32;
416
- var fieldElementsPerBlob = 4096;
417
- var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
418
- var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80).
419
- 1 - // zero byte (0x00) appended to each field element.
420
- 1 * fieldElementsPerBlob * blobsPerTransaction;
421
-
422
- // ../../node_modules/viem/_esm/constants/kzg.js
423
- var versionedHashVersionKzg = 1;
424
-
425
- // ../../node_modules/viem/_esm/errors/blob.js
426
- var BlobSizeTooLargeError = class extends BaseError {
427
- constructor({ maxSize, size: size3 }) {
428
- super("Blob size is too large.", {
429
- metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size3} bytes`],
430
- name: "BlobSizeTooLargeError"
431
- });
432
- }
433
- };
434
- var EmptyBlobError = class extends BaseError {
435
- constructor() {
436
- super("Blob data must not be empty.", { name: "EmptyBlobError" });
437
- }
438
- };
439
- var InvalidVersionedHashSizeError = class extends BaseError {
440
- constructor({ hash, size: size3 }) {
441
- super(`Versioned hash "${hash}" size is invalid.`, {
442
- metaMessages: ["Expected: 32", `Received: ${size3}`],
443
- name: "InvalidVersionedHashSizeError"
444
- });
445
- }
446
- };
447
- var InvalidVersionedHashVersionError = class extends BaseError {
448
- constructor({ hash, version }) {
449
- super(`Versioned hash "${hash}" version is invalid.`, {
450
- metaMessages: [
451
- `Expected: ${versionedHashVersionKzg}`,
452
- `Received: ${version}`
453
- ],
454
- name: "InvalidVersionedHashVersionError"
455
- });
456
- }
457
- };
458
-
459
- // ../../node_modules/viem/_esm/utils/blob/toBlobs.js
460
- function toBlobs(parameters) {
461
- const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes");
462
- const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data;
463
- const size_ = size(data);
464
- if (!size_)
465
- throw new EmptyBlobError();
466
- if (size_ > maxBytesPerTransaction)
467
- throw new BlobSizeTooLargeError({
468
- maxSize: maxBytesPerTransaction,
469
- size: size_
470
- });
471
- const blobs = [];
472
- let active = true;
473
- let position = 0;
474
- while (active) {
475
- const blob = createCursor(new Uint8Array(bytesPerBlob));
476
- let size3 = 0;
477
- while (size3 < fieldElementsPerBlob) {
478
- const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
479
- blob.pushByte(0);
480
- blob.pushBytes(bytes);
481
- if (bytes.length < 31) {
482
- blob.pushByte(128);
483
- active = false;
484
- break;
485
- }
486
- size3++;
487
- position += 31;
488
- }
489
- blobs.push(blob);
490
- }
491
- return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes));
492
- }
493
-
494
- // ../../node_modules/viem/_esm/utils/blob/toBlobSidecars.js
495
- function toBlobSidecars(parameters) {
496
- const { data, kzg, to } = parameters;
497
- const blobs = parameters.blobs ?? toBlobs({ data, to });
498
- const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to });
499
- const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to });
500
- const sidecars = [];
501
- for (let i = 0; i < blobs.length; i++)
502
- sidecars.push({
503
- blob: blobs[i],
504
- commitment: commitments[i],
505
- proof: proofs[i]
506
- });
507
- return sidecars;
508
- }
509
-
510
- // ../../node_modules/viem/_esm/utils/transaction/assertTransaction.js
511
- function assertTransactionEIP7702(transaction) {
512
- const { authorizationList } = transaction;
513
- if (authorizationList) {
514
- for (const authorization of authorizationList) {
515
- const { chainId } = authorization;
516
- const address = authorization.address;
517
- if (!isAddress(address))
518
- throw new InvalidAddressError({ address });
519
- if (chainId < 0)
520
- throw new InvalidChainIdError({ chainId });
521
- }
522
- }
523
- assertTransactionEIP1559(transaction);
524
- }
525
- function assertTransactionEIP4844(transaction) {
526
- const { blobVersionedHashes } = transaction;
527
- if (blobVersionedHashes) {
528
- if (blobVersionedHashes.length === 0)
529
- throw new EmptyBlobError();
530
- for (const hash of blobVersionedHashes) {
531
- const size_ = size(hash);
532
- const version = hexToNumber(slice(hash, 0, 1));
533
- if (size_ !== 32)
534
- throw new InvalidVersionedHashSizeError({ hash, size: size_ });
535
- if (version !== versionedHashVersionKzg)
536
- throw new InvalidVersionedHashVersionError({
537
- hash,
538
- version
539
- });
540
- }
541
- }
542
- assertTransactionEIP1559(transaction);
543
- }
544
- function assertTransactionEIP1559(transaction) {
545
- const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
546
- if (chainId <= 0)
547
- throw new InvalidChainIdError({ chainId });
548
- if (to && !isAddress(to))
549
- throw new InvalidAddressError({ address: to });
550
- if (maxFeePerGas && maxFeePerGas > maxUint256)
551
- throw new FeeCapTooHighError({ maxFeePerGas });
552
- if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
553
- throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
554
- }
555
- function assertTransactionEIP2930(transaction) {
556
- const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
557
- if (chainId <= 0)
558
- throw new InvalidChainIdError({ chainId });
559
- if (to && !isAddress(to))
560
- throw new InvalidAddressError({ address: to });
561
- if (maxPriorityFeePerGas || maxFeePerGas)
562
- throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");
563
- if (gasPrice && gasPrice > maxUint256)
564
- throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
565
- }
566
- function assertTransactionLegacy(transaction) {
567
- const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
568
- if (to && !isAddress(to))
569
- throw new InvalidAddressError({ address: to });
570
- if (typeof chainId !== "undefined" && chainId <= 0)
571
- throw new InvalidChainIdError({ chainId });
572
- if (maxPriorityFeePerGas || maxFeePerGas)
573
- throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");
574
- if (gasPrice && gasPrice > maxUint256)
575
- throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
576
- }
577
-
578
- // ../../node_modules/viem/_esm/utils/transaction/getTransactionType.js
579
- function getTransactionType(transaction) {
580
- if (transaction.type)
581
- return transaction.type;
582
- if (typeof transaction.authorizationList !== "undefined")
583
- return "eip7702";
584
- if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined")
585
- return "eip4844";
586
- if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") {
587
- return "eip1559";
588
- }
589
- if (typeof transaction.gasPrice !== "undefined") {
590
- if (typeof transaction.accessList !== "undefined")
591
- return "eip2930";
592
- return "legacy";
593
- }
594
- throw new InvalidSerializableTransactionError({ transaction });
595
- }
596
-
597
- // ../../node_modules/viem/_esm/utils/transaction/serializeAccessList.js
598
- function serializeAccessList(accessList) {
599
- if (!accessList || accessList.length === 0)
600
- return [];
601
- const serializedAccessList = [];
602
- for (let i = 0; i < accessList.length; i++) {
603
- const { address, storageKeys } = accessList[i];
604
- for (let j = 0; j < storageKeys.length; j++) {
605
- if (storageKeys[j].length - 2 !== 64) {
606
- throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
607
- }
608
- }
609
- if (!isAddress(address, { strict: false })) {
610
- throw new InvalidAddressError({ address });
611
- }
612
- serializedAccessList.push([address, storageKeys]);
613
- }
614
- return serializedAccessList;
615
- }
616
-
617
- // ../../node_modules/viem/_esm/utils/transaction/serializeTransaction.js
618
- function serializeTransaction(transaction, signature) {
619
- const type = getTransactionType(transaction);
620
- if (type === "eip1559")
621
- return serializeTransactionEIP1559(transaction, signature);
622
- if (type === "eip2930")
623
- return serializeTransactionEIP2930(transaction, signature);
624
- if (type === "eip4844")
625
- return serializeTransactionEIP4844(transaction, signature);
626
- if (type === "eip7702")
627
- return serializeTransactionEIP7702(transaction, signature);
628
- return serializeTransactionLegacy(transaction, signature);
629
- }
630
- function serializeTransactionEIP7702(transaction, signature) {
631
- const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
632
- assertTransactionEIP7702(transaction);
633
- const serializedAccessList = serializeAccessList(accessList);
634
- const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
635
- return concatHex([
636
- "0x04",
637
- toRlp([
638
- numberToHex(chainId),
639
- nonce ? numberToHex(nonce) : "0x",
640
- maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
641
- maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
642
- gas ? numberToHex(gas) : "0x",
643
- to ?? "0x",
644
- value ? numberToHex(value) : "0x",
645
- data ?? "0x",
646
- serializedAccessList,
647
- serializedAuthorizationList,
648
- ...toYParitySignatureArray(transaction, signature)
649
- ])
650
- ]);
651
- }
652
- function serializeTransactionEIP4844(transaction, signature) {
653
- const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
654
- assertTransactionEIP4844(transaction);
655
- let blobVersionedHashes = transaction.blobVersionedHashes;
656
- let sidecars = transaction.sidecars;
657
- if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) {
658
- const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x));
659
- const kzg = transaction.kzg;
660
- const commitments2 = blobsToCommitments({
661
- blobs: blobs2,
662
- kzg
663
- });
664
- if (typeof blobVersionedHashes === "undefined")
665
- blobVersionedHashes = commitmentsToVersionedHashes({
666
- commitments: commitments2
667
- });
668
- if (typeof sidecars === "undefined") {
669
- const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg });
670
- sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 });
671
- }
672
- }
673
- const serializedAccessList = serializeAccessList(accessList);
674
- const serializedTransaction = [
675
- numberToHex(chainId),
676
- nonce ? numberToHex(nonce) : "0x",
677
- maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
678
- maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
679
- gas ? numberToHex(gas) : "0x",
680
- to ?? "0x",
681
- value ? numberToHex(value) : "0x",
682
- data ?? "0x",
683
- serializedAccessList,
684
- maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : "0x",
685
- blobVersionedHashes ?? [],
686
- ...toYParitySignatureArray(transaction, signature)
687
- ];
688
- const blobs = [];
689
- const commitments = [];
690
- const proofs = [];
691
- if (sidecars)
692
- for (let i = 0; i < sidecars.length; i++) {
693
- const { blob, commitment, proof } = sidecars[i];
694
- blobs.push(blob);
695
- commitments.push(commitment);
696
- proofs.push(proof);
697
- }
698
- return concatHex([
699
- "0x03",
700
- sidecars ? (
701
- // If sidecars are enabled, envelope turns into a "wrapper":
702
- toRlp([serializedTransaction, blobs, commitments, proofs])
703
- ) : (
704
- // If sidecars are disabled, standard envelope is used:
705
- toRlp(serializedTransaction)
706
- )
707
- ]);
708
- }
709
- function serializeTransactionEIP1559(transaction, signature) {
710
- const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
711
- assertTransactionEIP1559(transaction);
712
- const serializedAccessList = serializeAccessList(accessList);
713
- const serializedTransaction = [
714
- numberToHex(chainId),
715
- nonce ? numberToHex(nonce) : "0x",
716
- maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
717
- maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
718
- gas ? numberToHex(gas) : "0x",
719
- to ?? "0x",
720
- value ? numberToHex(value) : "0x",
721
- data ?? "0x",
722
- serializedAccessList,
723
- ...toYParitySignatureArray(transaction, signature)
724
- ];
725
- return concatHex([
726
- "0x02",
727
- toRlp(serializedTransaction)
728
- ]);
729
- }
730
- function serializeTransactionEIP2930(transaction, signature) {
731
- const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
732
- assertTransactionEIP2930(transaction);
733
- const serializedAccessList = serializeAccessList(accessList);
734
- const serializedTransaction = [
735
- numberToHex(chainId),
736
- nonce ? numberToHex(nonce) : "0x",
737
- gasPrice ? numberToHex(gasPrice) : "0x",
738
- gas ? numberToHex(gas) : "0x",
739
- to ?? "0x",
740
- value ? numberToHex(value) : "0x",
741
- data ?? "0x",
742
- serializedAccessList,
743
- ...toYParitySignatureArray(transaction, signature)
744
- ];
745
- return concatHex([
746
- "0x01",
747
- toRlp(serializedTransaction)
748
- ]);
749
- }
750
- function serializeTransactionLegacy(transaction, signature) {
751
- const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
752
- assertTransactionLegacy(transaction);
753
- let serializedTransaction = [
754
- nonce ? numberToHex(nonce) : "0x",
755
- gasPrice ? numberToHex(gasPrice) : "0x",
756
- gas ? numberToHex(gas) : "0x",
757
- to ?? "0x",
758
- value ? numberToHex(value) : "0x",
759
- data ?? "0x"
760
- ];
761
- if (signature) {
762
- const v = (() => {
763
- if (signature.v >= 35n) {
764
- const inferredChainId = (signature.v - 35n) / 2n;
765
- if (inferredChainId > 0)
766
- return signature.v;
767
- return 27n + (signature.v === 35n ? 0n : 1n);
768
- }
769
- if (chainId > 0)
770
- return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);
771
- const v2 = 27n + (signature.v === 27n ? 0n : 1n);
772
- if (signature.v !== v2)
773
- throw new InvalidLegacyVError({ v: signature.v });
774
- return v2;
775
- })();
776
- const r = trim(signature.r);
777
- const s = trim(signature.s);
778
- serializedTransaction = [
779
- ...serializedTransaction,
780
- numberToHex(v),
781
- r === "0x00" ? "0x" : r,
782
- s === "0x00" ? "0x" : s
783
- ];
784
- } else if (chainId > 0) {
785
- serializedTransaction = [
786
- ...serializedTransaction,
787
- numberToHex(chainId),
788
- "0x",
789
- "0x"
790
- ];
791
- }
792
- return toRlp(serializedTransaction);
793
- }
794
- function toYParitySignatureArray(transaction, signature_) {
795
- const signature = signature_ ?? transaction;
796
- const { v, yParity } = signature;
797
- if (typeof signature.r === "undefined")
798
- return [];
799
- if (typeof signature.s === "undefined")
800
- return [];
801
- if (typeof v === "undefined" && typeof yParity === "undefined")
802
- return [];
803
- const r = trim(signature.r);
804
- const s = trim(signature.s);
805
- const yParity_ = (() => {
806
- if (typeof yParity === "number")
807
- return yParity ? numberToHex(1) : "0x";
808
- if (v === 0n)
809
- return "0x";
810
- if (v === 1n)
811
- return numberToHex(1);
812
- return v === 27n ? "0x" : numberToHex(1);
813
- })();
814
- return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s];
815
- }
816
-
817
- // ../../node_modules/viem/_esm/op-stack/contracts.js
818
- var contracts = {
819
- gasPriceOracle: { address: "0x420000000000000000000000000000000000000F" },
820
- l1Block: { address: "0x4200000000000000000000000000000000000015" },
821
- l2CrossDomainMessenger: {
822
- address: "0x4200000000000000000000000000000000000007"
823
- },
824
- l2Erc721Bridge: { address: "0x4200000000000000000000000000000000000014" },
825
- l2StandardBridge: { address: "0x4200000000000000000000000000000000000010" },
826
- l2ToL1MessagePasser: {
827
- address: "0x4200000000000000000000000000000000000016"
828
- }
829
- };
830
-
831
- // ../../node_modules/viem/_esm/op-stack/formatters.js
832
- var formatters = {
833
- block: /* @__PURE__ */ defineBlock({
834
- format(args) {
835
- const transactions = args.transactions?.map((transaction) => {
836
- if (typeof transaction === "string")
837
- return transaction;
838
- const formatted = formatTransaction(transaction);
839
- if (formatted.typeHex === "0x7e") {
840
- formatted.isSystemTx = transaction.isSystemTx;
841
- formatted.mint = transaction.mint ? hexToBigInt(transaction.mint) : void 0;
842
- formatted.sourceHash = transaction.sourceHash;
843
- formatted.type = "deposit";
844
- }
845
- return formatted;
846
- });
847
- return {
848
- transactions,
849
- stateRoot: args.stateRoot
850
- };
851
- }
852
- }),
853
- transaction: /* @__PURE__ */ defineTransaction({
854
- format(args) {
855
- const transaction = {};
856
- if (args.type === "0x7e") {
857
- transaction.isSystemTx = args.isSystemTx;
858
- transaction.mint = args.mint ? hexToBigInt(args.mint) : void 0;
859
- transaction.sourceHash = args.sourceHash;
860
- transaction.type = "deposit";
861
- }
862
- return transaction;
863
- }
864
- }),
865
- transactionReceipt: /* @__PURE__ */ defineTransactionReceipt({
866
- format(args) {
867
- return {
868
- l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,
869
- l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,
870
- l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,
871
- l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null
872
- };
873
- }
874
- })
875
- };
876
-
877
- // ../../node_modules/viem/_esm/op-stack/serializers.js
878
- function serializeTransaction2(transaction, signature) {
879
- if (isDeposit(transaction))
880
- return serializeTransactionDeposit(transaction);
881
- return serializeTransaction(transaction, signature);
882
- }
883
- var serializers = {
884
- transaction: serializeTransaction2
885
- };
886
- function serializeTransactionDeposit(transaction) {
887
- assertTransactionDeposit(transaction);
888
- const { sourceHash, data, from, gas, isSystemTx, mint, to, value } = transaction;
889
- const serializedTransaction = [
890
- sourceHash,
891
- from,
892
- to ?? "0x",
893
- mint ? toHex(mint) : "0x",
894
- value ? toHex(value) : "0x",
895
- gas ? toHex(gas) : "0x",
896
- isSystemTx ? "0x1" : "0x",
897
- data ?? "0x"
898
- ];
899
- return concatHex([
900
- "0x7e",
901
- toRlp(serializedTransaction)
902
- ]);
903
- }
904
- function isDeposit(transaction) {
905
- if (transaction.type === "deposit")
906
- return true;
907
- if (typeof transaction.sourceHash !== "undefined")
908
- return true;
909
- return false;
910
- }
911
- function assertTransactionDeposit(transaction) {
912
- const { from, to } = transaction;
913
- if (from && !isAddress(from))
914
- throw new InvalidAddressError({ address: from });
915
- if (to && !isAddress(to))
916
- throw new InvalidAddressError({ address: to });
917
- }
918
-
919
- // ../../node_modules/viem/_esm/op-stack/chainConfig.js
920
- var chainConfig = {
921
- blockTime: 2e3,
922
- contracts,
923
- formatters,
924
- serializers
925
- };
926
-
927
- // ../../node_modules/viem/_esm/chains/definitions/base.js
928
- var sourceId = 1;
929
- var base = /* @__PURE__ */ defineChain({
930
- ...chainConfig,
931
- id: 8453,
932
- name: "Base",
933
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
934
- rpcUrls: {
935
- default: {
936
- http: ["https://mainnet.base.org"]
937
- }
938
- },
939
- blockExplorers: {
940
- default: {
941
- name: "Basescan",
942
- url: "https://basescan.org",
943
- apiUrl: "https://api.basescan.org/api"
944
- }
945
- },
946
- contracts: {
947
- ...chainConfig.contracts,
948
- disputeGameFactory: {
949
- [sourceId]: {
950
- address: "0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"
951
- }
952
- },
953
- l2OutputOracle: {
954
- [sourceId]: {
955
- address: "0x56315b90c40730925ec5485cf004d835058518A0"
956
- }
957
- },
958
- multicall3: {
959
- address: "0xca11bde05977b3631167028862be2a173976ca11",
960
- blockCreated: 5022
961
- },
962
- portal: {
963
- [sourceId]: {
964
- address: "0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",
965
- blockCreated: 17482143
966
- }
967
- },
968
- l1StandardBridge: {
969
- [sourceId]: {
970
- address: "0x3154Cf16ccdb4C6d922629664174b904d80F2C35",
971
- blockCreated: 17482143
972
- }
973
- }
974
- },
975
- sourceId
976
- });
977
- var basePreconf = /* @__PURE__ */ defineChain({
978
- ...base,
979
- experimental_preconfirmationTime: 200,
980
- rpcUrls: {
981
- default: {
982
- http: ["https://mainnet-preconf.base.org"]
983
- }
984
- }
985
- });
986
-
987
- // ../../node_modules/viem/_esm/chains/definitions/baseSepolia.js
988
- var sourceId2 = 11155111;
989
- var baseSepolia = /* @__PURE__ */ defineChain({
990
- ...chainConfig,
991
- id: 84532,
992
- network: "base-sepolia",
993
- name: "Base Sepolia",
994
- nativeCurrency: { name: "Sepolia Ether", symbol: "ETH", decimals: 18 },
995
- rpcUrls: {
996
- default: {
997
- http: ["https://sepolia.base.org"]
998
- }
999
- },
1000
- blockExplorers: {
1001
- default: {
1002
- name: "Basescan",
1003
- url: "https://sepolia.basescan.org",
1004
- apiUrl: "https://api-sepolia.basescan.org/api"
1005
- }
1006
- },
1007
- contracts: {
1008
- ...chainConfig.contracts,
1009
- disputeGameFactory: {
1010
- [sourceId2]: {
1011
- address: "0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"
1012
- }
1013
- },
1014
- l2OutputOracle: {
1015
- [sourceId2]: {
1016
- address: "0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"
1017
- }
1018
- },
1019
- portal: {
1020
- [sourceId2]: {
1021
- address: "0x49f53e41452c74589e85ca1677426ba426459e85",
1022
- blockCreated: 4446677
1023
- }
1024
- },
1025
- l1StandardBridge: {
1026
- [sourceId2]: {
1027
- address: "0xfd0Bf71F60660E2f608ed56e1659C450eB113120",
1028
- blockCreated: 4446677
1029
- }
1030
- },
1031
- multicall3: {
1032
- address: "0xca11bde05977b3631167028862be2a173976ca11",
1033
- blockCreated: 1059647
1034
- }
1035
- },
1036
- testnet: true,
1037
- sourceId: sourceId2
1038
- });
1039
- var baseSepoliaPreconf = /* @__PURE__ */ defineChain({
1040
- ...baseSepolia,
1041
- experimental_preconfirmationTime: 200,
1042
- rpcUrls: {
1043
- default: {
1044
- http: ["https://sepolia-preconf.base.org"]
1045
- }
1046
- }
1047
- });
1048
-
1049
- // ../../node_modules/viem/_esm/utils/chain/assertCurrentChain.js
1050
- function assertCurrentChain({ chain, currentChainId }) {
1051
- if (!chain)
1052
- throw new ChainNotFoundError();
1053
- if (currentChainId !== chain.id)
1054
- throw new ChainMismatchError({ chain, currentChainId });
1055
- }
1056
-
1057
- // ../../node_modules/viem/_esm/errors/account.js
1058
- var AccountNotFoundError = class extends BaseError {
1059
- constructor({ docsPath } = {}) {
1060
- super([
1061
- "Could not find an Account to execute with this Action.",
1062
- "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."
1063
- ].join("\n"), {
1064
- docsPath,
1065
- docsSlug: "account",
1066
- name: "AccountNotFoundError"
1067
- });
1068
- }
1069
- };
1070
- var AccountTypeNotSupportedError = class extends BaseError {
1071
- constructor({ docsPath, metaMessages, type }) {
1072
- super(`Account type "${type}" is not supported.`, {
1073
- docsPath,
1074
- metaMessages,
1075
- name: "AccountTypeNotSupportedError"
1076
- });
1077
- }
1078
- };
1079
-
1080
- // src/mcp/x402.ts
1
+ import { base, baseSepolia } from "viem/chains";
1081
2
  import { processPriceToAtomicAmount } from "x402/shared";
1082
3
  import { exact } from "x402/schemes";
1083
4
  import { useFacilitator } from "x402/verify";
1084
-
1085
- // ../../node_modules/viem/_esm/utils/getAction.js
1086
- function getAction(client, actionFn, name) {
1087
- const action_implicit = client[actionFn.name];
1088
- if (typeof action_implicit === "function")
1089
- return action_implicit;
1090
- const action_explicit = client[name];
1091
- if (typeof action_explicit === "function")
1092
- return action_explicit;
1093
- return (params) => actionFn(client, params);
1094
- }
1095
-
1096
- // ../../node_modules/viem/_esm/utils/errors/getContractError.js
1097
- var EXECUTION_REVERTED_ERROR_CODE = 3;
1098
- function getContractError(err, { abi, address, args, docsPath, functionName, sender }) {
1099
- const error = err instanceof RawContractError ? err : err instanceof BaseError ? err.walk((err2) => "data" in err2) || err.walk() : {};
1100
- const { code, data, details, message, shortMessage } = error;
1101
- const cause = (() => {
1102
- if (err instanceof AbiDecodingZeroDataError)
1103
- return new ContractFunctionZeroDataError({ functionName });
1104
- if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage)) {
1105
- return new ContractFunctionRevertedError({
1106
- abi,
1107
- data: typeof data === "object" ? data.data : data,
1108
- functionName,
1109
- message: error instanceof RpcRequestError ? details : shortMessage ?? message
1110
- });
1111
- }
1112
- return err;
1113
- })();
1114
- return new ContractFunctionExecutionError(cause, {
1115
- abi,
1116
- args,
1117
- contractAddress: address,
1118
- docsPath,
1119
- functionName,
1120
- sender
1121
- });
1122
- }
1123
-
1124
- // ../../node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
1125
- function publicKeyToAddress(publicKey) {
1126
- const address = keccak256(`0x${publicKey.substring(4)}`).substring(26);
1127
- return checksumAddress(`0x${address}`);
1128
- }
1129
-
1130
- // ../../node_modules/viem/_esm/utils/signature/recoverPublicKey.js
1131
- async function recoverPublicKey({ hash, signature }) {
1132
- const hashHex = isHex(hash) ? hash : toHex(hash);
1133
- const { secp256k1 } = await import("../secp256k1-M22GZP2U.js");
1134
- const signature_ = (() => {
1135
- if (typeof signature === "object" && "r" in signature && "s" in signature) {
1136
- const { r, s, v, yParity } = signature;
1137
- const yParityOrV2 = Number(yParity ?? v);
1138
- const recoveryBit2 = toRecoveryBit(yParityOrV2);
1139
- return new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2);
1140
- }
1141
- const signatureHex = isHex(signature) ? signature : toHex(signature);
1142
- if (size(signatureHex) !== 65)
1143
- throw new Error("invalid signature length");
1144
- const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`);
1145
- const recoveryBit = toRecoveryBit(yParityOrV);
1146
- return secp256k1.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit);
1147
- })();
1148
- const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false);
1149
- return `0x${publicKey}`;
1150
- }
1151
- function toRecoveryBit(yParityOrV) {
1152
- if (yParityOrV === 0 || yParityOrV === 1)
1153
- return yParityOrV;
1154
- if (yParityOrV === 27)
1155
- return 0;
1156
- if (yParityOrV === 28)
1157
- return 1;
1158
- throw new Error("Invalid yParityOrV value");
1159
- }
1160
-
1161
- // ../../node_modules/viem/_esm/utils/signature/recoverAddress.js
1162
- async function recoverAddress({ hash, signature }) {
1163
- return publicKeyToAddress(await recoverPublicKey({ hash, signature }));
1164
- }
1165
-
1166
- // ../../node_modules/viem/_esm/utils/authorization/hashAuthorization.js
1167
- function hashAuthorization(parameters) {
1168
- const { chainId, nonce, to } = parameters;
1169
- const address = parameters.contractAddress ?? parameters.address;
1170
- const hash = keccak256(concatHex([
1171
- "0x05",
1172
- toRlp([
1173
- chainId ? numberToHex(chainId) : "0x",
1174
- address,
1175
- nonce ? numberToHex(nonce) : "0x"
1176
- ])
1177
- ]));
1178
- if (to === "bytes")
1179
- return hexToBytes(hash);
1180
- return hash;
1181
- }
1182
-
1183
- // ../../node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js
1184
- async function recoverAuthorizationAddress(parameters) {
1185
- const { authorization, signature } = parameters;
1186
- return recoverAddress({
1187
- hash: hashAuthorization(authorization),
1188
- signature: signature ?? authorization
1189
- });
1190
- }
1191
-
1192
- // ../../node_modules/viem/_esm/errors/estimateGas.js
1193
- var EstimateGasExecutionError = class extends BaseError {
1194
- constructor(cause, { account, docsPath, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) {
1195
- const prettyArgs = prettyPrint({
1196
- from: account?.address,
1197
- to,
1198
- value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`,
1199
- data,
1200
- gas,
1201
- gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
1202
- maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
1203
- maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
1204
- nonce
1205
- });
1206
- super(cause.shortMessage, {
1207
- cause,
1208
- docsPath,
1209
- metaMessages: [
1210
- ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
1211
- "Estimate Gas Arguments:",
1212
- prettyArgs
1213
- ].filter(Boolean),
1214
- name: "EstimateGasExecutionError"
1215
- });
1216
- Object.defineProperty(this, "cause", {
1217
- enumerable: true,
1218
- configurable: true,
1219
- writable: true,
1220
- value: void 0
1221
- });
1222
- this.cause = cause;
1223
- }
1224
- };
1225
-
1226
- // ../../node_modules/viem/_esm/utils/errors/getEstimateGasError.js
1227
- function getEstimateGasError(err, { docsPath, ...args }) {
1228
- const cause = (() => {
1229
- const cause2 = getNodeError(err, args);
1230
- if (cause2 instanceof UnknownNodeError)
1231
- return err;
1232
- return cause2;
1233
- })();
1234
- return new EstimateGasExecutionError(cause, {
1235
- docsPath,
1236
- ...args
1237
- });
1238
- }
1239
-
1240
- // ../../node_modules/viem/_esm/errors/fee.js
1241
- var BaseFeeScalarError = class extends BaseError {
1242
- constructor() {
1243
- super("`baseFeeMultiplier` must be greater than 1.", {
1244
- name: "BaseFeeScalarError"
1245
- });
1246
- }
1247
- };
1248
- var Eip1559FeesNotSupportedError = class extends BaseError {
1249
- constructor() {
1250
- super("Chain does not support EIP-1559 fees.", {
1251
- name: "Eip1559FeesNotSupportedError"
1252
- });
1253
- }
1254
- };
1255
- var MaxFeePerGasTooLowError = class extends BaseError {
1256
- constructor({ maxPriorityFeePerGas }) {
1257
- super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" });
1258
- }
1259
- };
1260
-
1261
- // ../../node_modules/viem/_esm/errors/block.js
1262
- var BlockNotFoundError = class extends BaseError {
1263
- constructor({ blockHash, blockNumber }) {
1264
- let identifier = "Block";
1265
- if (blockHash)
1266
- identifier = `Block at hash "${blockHash}"`;
1267
- if (blockNumber)
1268
- identifier = `Block at number "${blockNumber}"`;
1269
- super(`${identifier} could not be found.`, { name: "BlockNotFoundError" });
1270
- }
1271
- };
1272
-
1273
- // ../../node_modules/viem/_esm/actions/public/getBlock.js
1274
- async function getBlock(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", includeTransactions: includeTransactions_ } = {}) {
1275
- const includeTransactions = includeTransactions_ ?? false;
1276
- const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
1277
- let block = null;
1278
- if (blockHash) {
1279
- block = await client.request({
1280
- method: "eth_getBlockByHash",
1281
- params: [blockHash, includeTransactions]
1282
- }, { dedupe: true });
1283
- } else {
1284
- block = await client.request({
1285
- method: "eth_getBlockByNumber",
1286
- params: [blockNumberHex || blockTag, includeTransactions]
1287
- }, { dedupe: Boolean(blockNumberHex) });
1288
- }
1289
- if (!block)
1290
- throw new BlockNotFoundError({ blockHash, blockNumber });
1291
- const format = client.chain?.formatters?.block?.format || formatBlock;
1292
- return format(block);
1293
- }
1294
-
1295
- // ../../node_modules/viem/_esm/actions/public/getGasPrice.js
1296
- async function getGasPrice(client) {
1297
- const gasPrice = await client.request({
1298
- method: "eth_gasPrice"
1299
- });
1300
- return BigInt(gasPrice);
1301
- }
1302
-
1303
- // ../../node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js
1304
- async function internal_estimateMaxPriorityFeePerGas(client, args) {
1305
- const { block: block_, chain = client.chain, request } = args || {};
1306
- try {
1307
- const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee;
1308
- if (typeof maxPriorityFeePerGas === "function") {
1309
- const block = block_ || await getAction(client, getBlock, "getBlock")({});
1310
- const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({
1311
- block,
1312
- client,
1313
- request
1314
- });
1315
- if (maxPriorityFeePerGas_ === null)
1316
- throw new Error();
1317
- return maxPriorityFeePerGas_;
1318
- }
1319
- if (typeof maxPriorityFeePerGas !== "undefined")
1320
- return maxPriorityFeePerGas;
1321
- const maxPriorityFeePerGasHex = await client.request({
1322
- method: "eth_maxPriorityFeePerGas"
1323
- });
1324
- return hexToBigInt(maxPriorityFeePerGasHex);
1325
- } catch {
1326
- const [block, gasPrice] = await Promise.all([
1327
- block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}),
1328
- getAction(client, getGasPrice, "getGasPrice")({})
1329
- ]);
1330
- if (typeof block.baseFeePerGas !== "bigint")
1331
- throw new Eip1559FeesNotSupportedError();
1332
- const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas;
1333
- if (maxPriorityFeePerGas < 0n)
1334
- return 0n;
1335
- return maxPriorityFeePerGas;
1336
- }
1337
- }
1338
-
1339
- // ../../node_modules/viem/_esm/actions/public/estimateFeesPerGas.js
1340
- async function internal_estimateFeesPerGas(client, args) {
1341
- const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {};
1342
- const baseFeeMultiplier = await (async () => {
1343
- if (typeof chain?.fees?.baseFeeMultiplier === "function")
1344
- return chain.fees.baseFeeMultiplier({
1345
- block: block_,
1346
- client,
1347
- request
1348
- });
1349
- return chain?.fees?.baseFeeMultiplier ?? 1.2;
1350
- })();
1351
- if (baseFeeMultiplier < 1)
1352
- throw new BaseFeeScalarError();
1353
- const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0;
1354
- const denominator = 10 ** decimals;
1355
- const multiply = (base2) => base2 * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator);
1356
- const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({});
1357
- if (typeof chain?.fees?.estimateFeesPerGas === "function") {
1358
- const fees = await chain.fees.estimateFeesPerGas({
1359
- block: block_,
1360
- client,
1361
- multiply,
1362
- request,
1363
- type
1364
- });
1365
- if (fees !== null)
1366
- return fees;
1367
- }
1368
- if (type === "eip1559") {
1369
- if (typeof block.baseFeePerGas !== "bigint")
1370
- throw new Eip1559FeesNotSupportedError();
1371
- const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, {
1372
- block,
1373
- chain,
1374
- request
1375
- });
1376
- const baseFeePerGas = multiply(block.baseFeePerGas);
1377
- const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas;
1378
- return {
1379
- maxFeePerGas,
1380
- maxPriorityFeePerGas
1381
- };
1382
- }
1383
- const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({}));
1384
- return {
1385
- gasPrice
1386
- };
1387
- }
1388
-
1389
- // ../../node_modules/viem/_esm/actions/public/getTransactionCount.js
1390
- async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) {
1391
- const count = await client.request({
1392
- method: "eth_getTransactionCount",
1393
- params: [
1394
- address,
1395
- typeof blockNumber === "bigint" ? numberToHex(blockNumber) : blockTag
1396
- ]
1397
- }, {
1398
- dedupe: Boolean(blockNumber)
1399
- });
1400
- return hexToNumber(count);
1401
- }
1402
-
1403
- // ../../node_modules/viem/_esm/actions/public/getChainId.js
1404
- async function getChainId(client) {
1405
- const chainIdHex = await client.request({
1406
- method: "eth_chainId"
1407
- }, { dedupe: true });
1408
- return hexToNumber(chainIdHex);
1409
- }
1410
-
1411
- // ../../node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js
1412
- var defaultParameters = [
1413
- "blobVersionedHashes",
1414
- "chainId",
1415
- "fees",
1416
- "gas",
1417
- "nonce",
1418
- "type"
1419
- ];
1420
- var eip1559NetworkCache = /* @__PURE__ */ new Map();
1421
- async function prepareTransactionRequest(client, args) {
1422
- const { account: account_ = client.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args;
1423
- const account = account_ ? parseAccount(account_) : account_;
1424
- const request = { ...args, ...account ? { from: account?.address } : {} };
1425
- let block;
1426
- async function getBlock2() {
1427
- if (block)
1428
- return block;
1429
- block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" });
1430
- return block;
1431
- }
1432
- let chainId;
1433
- async function getChainId2() {
1434
- if (chainId)
1435
- return chainId;
1436
- if (chain)
1437
- return chain.id;
1438
- if (typeof args.chainId !== "undefined")
1439
- return args.chainId;
1440
- const chainId_ = await getAction(client, getChainId, "getChainId")({});
1441
- chainId = chainId_;
1442
- return chainId;
1443
- }
1444
- if (parameters.includes("nonce") && typeof nonce === "undefined" && account) {
1445
- if (nonceManager) {
1446
- const chainId2 = await getChainId2();
1447
- request.nonce = await nonceManager.consume({
1448
- address: account.address,
1449
- chainId: chainId2,
1450
- client
1451
- });
1452
- } else {
1453
- request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
1454
- address: account.address,
1455
- blockTag: "pending"
1456
- });
1457
- }
1458
- }
1459
- if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) {
1460
- const commitments = blobsToCommitments({ blobs, kzg });
1461
- if (parameters.includes("blobVersionedHashes")) {
1462
- const versionedHashes = commitmentsToVersionedHashes({
1463
- commitments,
1464
- to: "hex"
1465
- });
1466
- request.blobVersionedHashes = versionedHashes;
1467
- }
1468
- if (parameters.includes("sidecars")) {
1469
- const proofs = blobsToProofs({ blobs, commitments, kzg });
1470
- const sidecars = toBlobSidecars({
1471
- blobs,
1472
- commitments,
1473
- proofs,
1474
- to: "hex"
1475
- });
1476
- request.sidecars = sidecars;
1477
- }
1478
- }
1479
- if (parameters.includes("chainId"))
1480
- request.chainId = await getChainId2();
1481
- if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") {
1482
- try {
1483
- request.type = getTransactionType(request);
1484
- } catch {
1485
- let isEip1559Network = eip1559NetworkCache.get(client.uid);
1486
- if (typeof isEip1559Network === "undefined") {
1487
- const block2 = await getBlock2();
1488
- isEip1559Network = typeof block2?.baseFeePerGas === "bigint";
1489
- eip1559NetworkCache.set(client.uid, isEip1559Network);
1490
- }
1491
- request.type = isEip1559Network ? "eip1559" : "legacy";
1492
- }
1493
- }
1494
- if (parameters.includes("fees")) {
1495
- if (request.type !== "legacy" && request.type !== "eip2930") {
1496
- if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") {
1497
- const block2 = await getBlock2();
1498
- const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, {
1499
- block: block2,
1500
- chain,
1501
- request
1502
- });
1503
- if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas)
1504
- throw new MaxFeePerGasTooLowError({
1505
- maxPriorityFeePerGas
1506
- });
1507
- request.maxPriorityFeePerGas = maxPriorityFeePerGas;
1508
- request.maxFeePerGas = maxFeePerGas;
1509
- }
1510
- } else {
1511
- if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined")
1512
- throw new Eip1559FeesNotSupportedError();
1513
- if (typeof args.gasPrice === "undefined") {
1514
- const block2 = await getBlock2();
1515
- const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, {
1516
- block: block2,
1517
- chain,
1518
- request,
1519
- type: "legacy"
1520
- });
1521
- request.gasPrice = gasPrice_;
1522
- }
1523
- }
1524
- }
1525
- if (parameters.includes("gas") && typeof gas === "undefined")
1526
- request.gas = await getAction(client, estimateGas, "estimateGas")({
1527
- ...request,
1528
- account: account ? { address: account.address, type: "json-rpc" } : account
1529
- });
1530
- assertRequest(request);
1531
- delete request.parameters;
1532
- return request;
1533
- }
1534
-
1535
- // ../../node_modules/viem/_esm/actions/public/getBalance.js
1536
- async function getBalance(client, { address, blockNumber, blockTag = client.experimental_blockTag ?? "latest" }) {
1537
- const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
1538
- const balance = await client.request({
1539
- method: "eth_getBalance",
1540
- params: [address, blockNumberHex || blockTag]
1541
- });
1542
- return BigInt(balance);
1543
- }
1544
-
1545
- // ../../node_modules/viem/_esm/actions/public/estimateGas.js
1546
- async function estimateGas(client, args) {
1547
- const { account: account_ = client.account } = args;
1548
- const account = account_ ? parseAccount(account_) : void 0;
1549
- try {
1550
- let estimateGas_rpc2 = function(parameters) {
1551
- const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters;
1552
- return client.request({
1553
- method: "eth_estimateGas",
1554
- params: rpcStateOverride2 ? [
1555
- request2,
1556
- block2 ?? client.experimental_blockTag ?? "latest",
1557
- rpcStateOverride2
1558
- ] : block2 ? [request2, block2] : [request2]
1559
- });
1560
- };
1561
- var estimateGas_rpc = estimateGas_rpc2;
1562
- const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client, {
1563
- ...args,
1564
- parameters: (
1565
- // Some RPC Providers do not compute versioned hashes from blobs. We will need
1566
- // to compute them.
1567
- account?.type === "local" ? void 0 : ["blobVersionedHashes"]
1568
- )
1569
- });
1570
- const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
1571
- const block = blockNumberHex || blockTag;
1572
- const rpcStateOverride = serializeStateOverride(stateOverride);
1573
- const to = await (async () => {
1574
- if (rest.to)
1575
- return rest.to;
1576
- if (authorizationList && authorizationList.length > 0)
1577
- return await recoverAuthorizationAddress({
1578
- authorization: authorizationList[0]
1579
- }).catch(() => {
1580
- throw new BaseError("`to` is required. Could not infer from `authorizationList`");
1581
- });
1582
- return void 0;
1583
- })();
1584
- assertRequest(args);
1585
- const chainFormat = client.chain?.formatters?.transactionRequest?.format;
1586
- const format = chainFormat || formatTransactionRequest;
1587
- const request = format({
1588
- // Pick out extra data that might exist on the chain's transaction request type.
1589
- ...extract(rest, { format: chainFormat }),
1590
- from: account?.address,
1591
- accessList,
1592
- authorizationList,
1593
- blobs,
1594
- blobVersionedHashes,
1595
- data,
1596
- gas,
1597
- gasPrice,
1598
- maxFeePerBlobGas,
1599
- maxFeePerGas,
1600
- maxPriorityFeePerGas,
1601
- nonce,
1602
- to,
1603
- value
1604
- });
1605
- let estimate = BigInt(await estimateGas_rpc2({ block, request, rpcStateOverride }));
1606
- if (authorizationList) {
1607
- const value2 = await getBalance(client, { address: request.from });
1608
- const estimates = await Promise.all(authorizationList.map(async (authorization) => {
1609
- const { address } = authorization;
1610
- const estimate2 = await estimateGas_rpc2({
1611
- block,
1612
- request: {
1613
- authorizationList: void 0,
1614
- data,
1615
- from: account?.address,
1616
- to: address,
1617
- value: numberToHex(value2)
1618
- },
1619
- rpcStateOverride
1620
- }).catch(() => 100000n);
1621
- return 2n * BigInt(estimate2);
1622
- }));
1623
- estimate += estimates.reduce((acc, curr) => acc + curr, 0n);
1624
- }
1625
- return estimate;
1626
- } catch (err) {
1627
- throw getEstimateGasError(err, {
1628
- ...args,
1629
- account,
1630
- chain: client.chain
1631
- });
1632
- }
1633
- }
1634
-
1635
- // ../../node_modules/viem/_esm/utils/observe.js
1636
- var listenersCache = /* @__PURE__ */ new Map();
1637
- var cleanupCache = /* @__PURE__ */ new Map();
1638
- var callbackCount = 0;
1639
- function observe(observerId, callbacks, fn) {
1640
- const callbackId = ++callbackCount;
1641
- const getListeners = () => listenersCache.get(observerId) || [];
1642
- const unsubscribe = () => {
1643
- const listeners2 = getListeners();
1644
- listenersCache.set(observerId, listeners2.filter((cb) => cb.id !== callbackId));
1645
- };
1646
- const unwatch = () => {
1647
- const listeners2 = getListeners();
1648
- if (!listeners2.some((cb) => cb.id === callbackId))
1649
- return;
1650
- const cleanup2 = cleanupCache.get(observerId);
1651
- if (listeners2.length === 1 && cleanup2) {
1652
- const p = cleanup2();
1653
- if (p instanceof Promise)
1654
- p.catch(() => {
1655
- });
1656
- }
1657
- unsubscribe();
1658
- };
1659
- const listeners = getListeners();
1660
- listenersCache.set(observerId, [
1661
- ...listeners,
1662
- { id: callbackId, fns: callbacks }
1663
- ]);
1664
- if (listeners && listeners.length > 0)
1665
- return unwatch;
1666
- const emit = {};
1667
- for (const key in callbacks) {
1668
- emit[key] = ((...args) => {
1669
- const listeners2 = getListeners();
1670
- if (listeners2.length === 0)
1671
- return;
1672
- for (const listener of listeners2)
1673
- listener.fns[key]?.(...args);
1674
- });
1675
- }
1676
- const cleanup = fn(emit);
1677
- if (typeof cleanup === "function")
1678
- cleanupCache.set(observerId, cleanup);
1679
- return unwatch;
1680
- }
1681
-
1682
- // ../../node_modules/viem/_esm/utils/wait.js
1683
- async function wait(time) {
1684
- return new Promise((res) => setTimeout(res, time));
1685
- }
1686
-
1687
- // ../../node_modules/viem/_esm/utils/poll.js
1688
- function poll(fn, { emitOnBegin, initialWaitTime, interval }) {
1689
- let active = true;
1690
- const unwatch = () => active = false;
1691
- const watch = async () => {
1692
- let data;
1693
- if (emitOnBegin)
1694
- data = await fn({ unpoll: unwatch });
1695
- const initialWait = await initialWaitTime?.(data) ?? interval;
1696
- await wait(initialWait);
1697
- const poll2 = async () => {
1698
- if (!active)
1699
- return;
1700
- await fn({ unpoll: unwatch });
1701
- await wait(interval);
1702
- poll2();
1703
- };
1704
- poll2();
1705
- };
1706
- watch();
1707
- return unwatch;
1708
- }
1709
-
1710
- // ../../node_modules/viem/_esm/utils/errors/getTransactionError.js
1711
- function getTransactionError(err, { docsPath, ...args }) {
1712
- const cause = (() => {
1713
- const cause2 = getNodeError(err, args);
1714
- if (cause2 instanceof UnknownNodeError)
1715
- return err;
1716
- return cause2;
1717
- })();
1718
- return new TransactionExecutionError(cause, {
1719
- docsPath,
1720
- ...args
1721
- });
1722
- }
1723
-
1724
- // ../../node_modules/viem/_esm/actions/wallet/sendRawTransaction.js
1725
- async function sendRawTransaction(client, { serializedTransaction }) {
1726
- return client.request({
1727
- method: "eth_sendRawTransaction",
1728
- params: [serializedTransaction]
1729
- }, { retryCount: 0 });
1730
- }
1731
-
1732
- // ../../node_modules/viem/_esm/actions/wallet/sendTransaction.js
1733
- var supportsWalletNamespace = new LruMap(128);
1734
- async function sendTransaction(client, parameters) {
1735
- const { account: account_ = client.account, chain = client.chain, accessList, authorizationList, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, type, value, ...rest } = parameters;
1736
- if (typeof account_ === "undefined")
1737
- throw new AccountNotFoundError({
1738
- docsPath: "/docs/actions/wallet/sendTransaction"
1739
- });
1740
- const account = account_ ? parseAccount(account_) : null;
1741
- try {
1742
- assertRequest(parameters);
1743
- const to = await (async () => {
1744
- if (parameters.to)
1745
- return parameters.to;
1746
- if (parameters.to === null)
1747
- return void 0;
1748
- if (authorizationList && authorizationList.length > 0)
1749
- return await recoverAuthorizationAddress({
1750
- authorization: authorizationList[0]
1751
- }).catch(() => {
1752
- throw new BaseError("`to` is required. Could not infer from `authorizationList`.");
1753
- });
1754
- return void 0;
1755
- })();
1756
- if (account?.type === "json-rpc" || account === null) {
1757
- let chainId;
1758
- if (chain !== null) {
1759
- chainId = await getAction(client, getChainId, "getChainId")({});
1760
- assertCurrentChain({
1761
- currentChainId: chainId,
1762
- chain
1763
- });
1764
- }
1765
- const chainFormat = client.chain?.formatters?.transactionRequest?.format;
1766
- const format = chainFormat || formatTransactionRequest;
1767
- const request = format({
1768
- // Pick out extra data that might exist on the chain's transaction request type.
1769
- ...extract(rest, { format: chainFormat }),
1770
- accessList,
1771
- authorizationList,
1772
- blobs,
1773
- chainId,
1774
- data,
1775
- from: account?.address,
1776
- gas,
1777
- gasPrice,
1778
- maxFeePerBlobGas,
1779
- maxFeePerGas,
1780
- maxPriorityFeePerGas,
1781
- nonce,
1782
- to,
1783
- type,
1784
- value
1785
- });
1786
- const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid);
1787
- const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction";
1788
- try {
1789
- return await client.request({
1790
- method,
1791
- params: [request]
1792
- }, { retryCount: 0 });
1793
- } catch (e) {
1794
- if (isWalletNamespaceSupported === false)
1795
- throw e;
1796
- const error = e;
1797
- if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") {
1798
- return await client.request({
1799
- method: "wallet_sendTransaction",
1800
- params: [request]
1801
- }, { retryCount: 0 }).then((hash) => {
1802
- supportsWalletNamespace.set(client.uid, true);
1803
- return hash;
1804
- }).catch((e2) => {
1805
- const walletNamespaceError = e2;
1806
- if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") {
1807
- supportsWalletNamespace.set(client.uid, false);
1808
- throw error;
1809
- }
1810
- throw walletNamespaceError;
1811
- });
1812
- }
1813
- throw error;
1814
- }
1815
- }
1816
- if (account?.type === "local") {
1817
- const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({
1818
- account,
1819
- accessList,
1820
- authorizationList,
1821
- blobs,
1822
- chain,
1823
- data,
1824
- gas,
1825
- gasPrice,
1826
- maxFeePerBlobGas,
1827
- maxFeePerGas,
1828
- maxPriorityFeePerGas,
1829
- nonce,
1830
- nonceManager: account.nonceManager,
1831
- parameters: [...defaultParameters, "sidecars"],
1832
- type,
1833
- value,
1834
- ...rest,
1835
- to
1836
- });
1837
- const serializer = chain?.serializers?.transaction;
1838
- const serializedTransaction = await account.signTransaction(request, {
1839
- serializer
1840
- });
1841
- return await getAction(client, sendRawTransaction, "sendRawTransaction")({
1842
- serializedTransaction
1843
- });
1844
- }
1845
- if (account?.type === "smart")
1846
- throw new AccountTypeNotSupportedError({
1847
- metaMessages: [
1848
- "Consider using the `sendUserOperation` Action instead."
1849
- ],
1850
- docsPath: "/docs/actions/bundler/sendUserOperation",
1851
- type: "smart"
1852
- });
1853
- throw new AccountTypeNotSupportedError({
1854
- docsPath: "/docs/actions/wallet/sendTransaction",
1855
- type: account?.type
1856
- });
1857
- } catch (err) {
1858
- if (err instanceof AccountTypeNotSupportedError)
1859
- throw err;
1860
- throw getTransactionError(err, {
1861
- ...parameters,
1862
- account,
1863
- chain: parameters.chain || void 0
1864
- });
1865
- }
1866
- }
1867
-
1868
- // ../../node_modules/viem/_esm/actions/wallet/writeContract.js
1869
- async function writeContract(client, parameters) {
1870
- const { abi, account: account_ = client.account, address, args, dataSuffix, functionName, ...request } = parameters;
1871
- if (typeof account_ === "undefined")
1872
- throw new AccountNotFoundError({
1873
- docsPath: "/docs/contract/writeContract"
1874
- });
1875
- const account = account_ ? parseAccount(account_) : null;
1876
- const data = encodeFunctionData({
1877
- abi,
1878
- args,
1879
- functionName
1880
- });
1881
- try {
1882
- return await getAction(client, sendTransaction, "sendTransaction")({
1883
- data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
1884
- to: address,
1885
- account,
1886
- ...request
1887
- });
1888
- } catch (error) {
1889
- throw getContractError(error, {
1890
- abi,
1891
- address,
1892
- args,
1893
- docsPath: "/docs/contract/writeContract",
1894
- functionName,
1895
- sender: account?.address
1896
- });
1897
- }
1898
- }
1899
-
1900
- // ../../node_modules/viem/_esm/errors/calls.js
1901
- var BundleFailedError = class extends BaseError {
1902
- constructor(result) {
1903
- super(`Call bundle failed with status: ${result.statusCode}`, {
1904
- name: "BundleFailedError"
1905
- });
1906
- Object.defineProperty(this, "result", {
1907
- enumerable: true,
1908
- configurable: true,
1909
- writable: true,
1910
- value: void 0
1911
- });
1912
- this.result = result;
1913
- }
1914
- };
1915
-
1916
- // ../../node_modules/viem/_esm/utils/promise/withRetry.js
1917
- function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) {
1918
- return new Promise((resolve, reject) => {
1919
- const attemptRetry = async ({ count = 0 } = {}) => {
1920
- const retry = async ({ error }) => {
1921
- const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_;
1922
- if (delay)
1923
- await wait(delay);
1924
- attemptRetry({ count: count + 1 });
1925
- };
1926
- try {
1927
- const data = await fn();
1928
- resolve(data);
1929
- } catch (err) {
1930
- if (count < retryCount && await shouldRetry2({ count, error: err }))
1931
- return retry({ error: err });
1932
- reject(err);
1933
- }
1934
- };
1935
- attemptRetry();
1936
- });
1937
- }
1938
-
1939
- // ../../node_modules/viem/_esm/actions/wallet/sendCalls.js
1940
- var fallbackMagicIdentifier = "0x5792579257925792579257925792579257925792579257925792579257925792";
1941
- var fallbackTransactionErrorMagicIdentifier = numberToHex(0, {
1942
- size: 32
1943
- });
1944
- async function sendCalls(client, parameters) {
1945
- const { account: account_ = client.account, capabilities, chain = client.chain, experimental_fallback, experimental_fallbackDelay = 32, forceAtomic = false, id, version = "2.0.0" } = parameters;
1946
- const account = account_ ? parseAccount(account_) : null;
1947
- const calls = parameters.calls.map((call_) => {
1948
- const call = call_;
1949
- const data = call.abi ? encodeFunctionData({
1950
- abi: call.abi,
1951
- functionName: call.functionName,
1952
- args: call.args
1953
- }) : call.data;
1954
- return {
1955
- data: call.dataSuffix && data ? concat([data, call.dataSuffix]) : data,
1956
- to: call.to,
1957
- value: call.value ? numberToHex(call.value) : void 0
1958
- };
1959
- });
1960
- try {
1961
- const response = await client.request({
1962
- method: "wallet_sendCalls",
1963
- params: [
1964
- {
1965
- atomicRequired: forceAtomic,
1966
- calls,
1967
- capabilities,
1968
- chainId: numberToHex(chain.id),
1969
- from: account?.address,
1970
- id,
1971
- version
1972
- }
1973
- ]
1974
- }, { retryCount: 0 });
1975
- if (typeof response === "string")
1976
- return { id: response };
1977
- return response;
1978
- } catch (err) {
1979
- const error = err;
1980
- if (experimental_fallback && (error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError" || error.name === "UnknownRpcError" || error.details.toLowerCase().includes("does not exist / is not available") || error.details.toLowerCase().includes("missing or invalid. request()") || error.details.toLowerCase().includes("did not match any variant of untagged enum") || error.details.toLowerCase().includes("account upgraded to unsupported contract") || error.details.toLowerCase().includes("eip-7702 not supported") || error.details.toLowerCase().includes("unsupported wc_ method") || error.details.toLowerCase().includes("feature toggled misconfigured"))) {
1981
- if (capabilities) {
1982
- const hasNonOptionalCapability = Object.values(capabilities).some((capability) => !capability.optional);
1983
- if (hasNonOptionalCapability) {
1984
- const message = "non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";
1985
- throw new UnsupportedNonOptionalCapabilityError(new BaseError(message, {
1986
- details: message
1987
- }));
1988
- }
1989
- }
1990
- if (forceAtomic && calls.length > 1) {
1991
- const message = "`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";
1992
- throw new AtomicityNotSupportedError(new BaseError(message, {
1993
- details: message
1994
- }));
1995
- }
1996
- const promises = [];
1997
- for (const call of calls) {
1998
- const promise = sendTransaction(client, {
1999
- account,
2000
- chain,
2001
- data: call.data,
2002
- to: call.to,
2003
- value: call.value ? hexToBigInt(call.value) : void 0
2004
- });
2005
- promises.push(promise);
2006
- if (experimental_fallbackDelay > 0)
2007
- await new Promise((resolve) => setTimeout(resolve, experimental_fallbackDelay));
2008
- }
2009
- const results = await Promise.allSettled(promises);
2010
- if (results.every((r) => r.status === "rejected"))
2011
- throw results[0].reason;
2012
- const hashes = results.map((result) => {
2013
- if (result.status === "fulfilled")
2014
- return result.value;
2015
- return fallbackTransactionErrorMagicIdentifier;
2016
- });
2017
- return {
2018
- id: concat([
2019
- ...hashes,
2020
- numberToHex(chain.id, { size: 32 }),
2021
- fallbackMagicIdentifier
2022
- ])
2023
- };
2024
- }
2025
- throw getTransactionError(err, {
2026
- ...parameters,
2027
- account,
2028
- chain: parameters.chain
2029
- });
2030
- }
2031
- }
2032
-
2033
- // ../../node_modules/viem/_esm/actions/wallet/getCallsStatus.js
2034
- async function getCallsStatus(client, parameters) {
2035
- async function getStatus(id) {
2036
- const isTransactions = id.endsWith(fallbackMagicIdentifier.slice(2));
2037
- if (isTransactions) {
2038
- const chainId2 = trim(sliceHex(id, -64, -32));
2039
- const hashes = sliceHex(id, 0, -64).slice(2).match(/.{1,64}/g);
2040
- const receipts2 = await Promise.all(hashes.map((hash) => fallbackTransactionErrorMagicIdentifier.slice(2) !== hash ? client.request({
2041
- method: "eth_getTransactionReceipt",
2042
- params: [`0x${hash}`]
2043
- }, { dedupe: true }) : void 0));
2044
- const status2 = (() => {
2045
- if (receipts2.some((r) => r === null))
2046
- return 100;
2047
- if (receipts2.every((r) => r?.status === "0x1"))
2048
- return 200;
2049
- if (receipts2.every((r) => r?.status === "0x0"))
2050
- return 500;
2051
- return 600;
2052
- })();
2053
- return {
2054
- atomic: false,
2055
- chainId: hexToNumber(chainId2),
2056
- receipts: receipts2.filter(Boolean),
2057
- status: status2,
2058
- version: "2.0.0"
2059
- };
2060
- }
2061
- return client.request({
2062
- method: "wallet_getCallsStatus",
2063
- params: [id]
2064
- });
2065
- }
2066
- const { atomic = false, chainId, receipts, version = "2.0.0", ...response } = await getStatus(parameters.id);
2067
- const [status, statusCode] = (() => {
2068
- const statusCode2 = response.status;
2069
- if (statusCode2 >= 100 && statusCode2 < 200)
2070
- return ["pending", statusCode2];
2071
- if (statusCode2 >= 200 && statusCode2 < 300)
2072
- return ["success", statusCode2];
2073
- if (statusCode2 >= 300 && statusCode2 < 700)
2074
- return ["failure", statusCode2];
2075
- if (statusCode2 === "CONFIRMED")
2076
- return ["success", 200];
2077
- if (statusCode2 === "PENDING")
2078
- return ["pending", 100];
2079
- return [void 0, statusCode2];
2080
- })();
2081
- return {
2082
- ...response,
2083
- atomic,
2084
- // @ts-expect-error: for backwards compatibility
2085
- chainId: chainId ? hexToNumber(chainId) : void 0,
2086
- receipts: receipts?.map((receipt) => ({
2087
- ...receipt,
2088
- blockNumber: hexToBigInt(receipt.blockNumber),
2089
- gasUsed: hexToBigInt(receipt.gasUsed),
2090
- status: receiptStatuses[receipt.status]
2091
- })) ?? [],
2092
- statusCode,
2093
- status,
2094
- version
2095
- };
2096
- }
2097
-
2098
- // ../../node_modules/viem/_esm/actions/wallet/waitForCallsStatus.js
2099
- async function waitForCallsStatus(client, parameters) {
2100
- const {
2101
- id,
2102
- pollingInterval = client.pollingInterval,
2103
- status = ({ statusCode }) => statusCode === 200 || statusCode >= 300,
2104
- retryCount = 4,
2105
- retryDelay = ({ count }) => ~~(1 << count) * 200,
2106
- // exponential backoff
2107
- timeout = 6e4,
2108
- throwOnFailure = false
2109
- } = parameters;
2110
- const observerId = stringify(["waitForCallsStatus", client.uid, id]);
2111
- const { promise, resolve, reject } = withResolvers();
2112
- let timer;
2113
- const unobserve = observe(observerId, { resolve, reject }, (emit) => {
2114
- const unpoll = poll(async () => {
2115
- const done = (fn) => {
2116
- clearTimeout(timer);
2117
- unpoll();
2118
- fn();
2119
- unobserve();
2120
- };
2121
- try {
2122
- const result = await withRetry(async () => {
2123
- const result2 = await getAction(client, getCallsStatus, "getCallsStatus")({ id });
2124
- if (throwOnFailure && result2.status === "failure")
2125
- throw new BundleFailedError(result2);
2126
- return result2;
2127
- }, {
2128
- retryCount,
2129
- delay: retryDelay
2130
- });
2131
- if (!status(result))
2132
- return;
2133
- done(() => emit.resolve(result));
2134
- } catch (error) {
2135
- done(() => emit.reject(error));
2136
- }
2137
- }, {
2138
- interval: pollingInterval,
2139
- emitOnBegin: true
2140
- });
2141
- return unpoll;
2142
- });
2143
- timer = timeout ? setTimeout(() => {
2144
- unobserve();
2145
- clearTimeout(timer);
2146
- reject(new WaitForCallsStatusTimeoutError({ id }));
2147
- }, timeout) : void 0;
2148
- return await promise;
2149
- }
2150
- var WaitForCallsStatusTimeoutError = class extends BaseError {
2151
- constructor({ id }) {
2152
- super(`Timed out while waiting for call bundle with id "${id}" to be confirmed.`, { name: "WaitForCallsStatusTimeoutError" });
2153
- }
2154
- };
2155
-
2156
- // ../../node_modules/viem/_esm/utils/uid.js
2157
- var size2 = 256;
2158
- var index = size2;
2159
- var buffer;
2160
- function uid(length = 11) {
2161
- if (!buffer || index + length > size2 * 2) {
2162
- buffer = "";
2163
- index = 0;
2164
- for (let i = 0; i < size2; i++) {
2165
- buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1);
2166
- }
2167
- }
2168
- return buffer.substring(index, index++ + length);
2169
- }
2170
-
2171
- // ../../node_modules/viem/_esm/clients/createClient.js
2172
- function createClient(parameters) {
2173
- const { batch, chain, ccipRead, key = "base", name = "Base Client", type = "base" } = parameters;
2174
- const experimental_blockTag = parameters.experimental_blockTag ?? (typeof chain?.experimental_preconfirmationTime === "number" ? "pending" : void 0);
2175
- const blockTime = chain?.blockTime ?? 12e3;
2176
- const defaultPollingInterval = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4e3);
2177
- const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval;
2178
- const cacheTime = parameters.cacheTime ?? pollingInterval;
2179
- const account = parameters.account ? parseAccount(parameters.account) : void 0;
2180
- const { config, request, value } = parameters.transport({
2181
- chain,
2182
- pollingInterval
2183
- });
2184
- const transport = { ...config, ...value };
2185
- const client = {
2186
- account,
2187
- batch,
2188
- cacheTime,
2189
- ccipRead,
2190
- chain,
2191
- key,
2192
- name,
2193
- pollingInterval,
2194
- request,
2195
- transport,
2196
- type,
2197
- uid: uid(),
2198
- ...experimental_blockTag ? { experimental_blockTag } : {}
2199
- };
2200
- function extend(base2) {
2201
- return (extendFn) => {
2202
- const extended = extendFn(base2);
2203
- for (const key2 in client)
2204
- delete extended[key2];
2205
- const combined = { ...base2, ...extended };
2206
- return Object.assign(combined, { extend: extend(combined) });
2207
- };
2208
- }
2209
- return Object.assign(client, { extend: extend(client) });
2210
- }
2211
-
2212
- // ../../node_modules/viem/_esm/utils/promise/withDedupe.js
2213
- var promiseCache = /* @__PURE__ */ new LruMap(8192);
2214
- function withDedupe(fn, { enabled = true, id }) {
2215
- if (!enabled || !id)
2216
- return fn();
2217
- if (promiseCache.get(id))
2218
- return promiseCache.get(id);
2219
- const promise = fn().finally(() => promiseCache.delete(id));
2220
- promiseCache.set(id, promise);
2221
- return promise;
2222
- }
2223
-
2224
- // ../../node_modules/viem/_esm/utils/buildRequest.js
2225
- function buildRequest(request, options = {}) {
2226
- return async (args, overrideOptions = {}) => {
2227
- const { dedupe = false, methods, retryDelay = 150, retryCount = 3, uid: uid2 } = {
2228
- ...options,
2229
- ...overrideOptions
2230
- };
2231
- const { method } = args;
2232
- if (methods?.exclude?.includes(method))
2233
- throw new MethodNotSupportedRpcError(new Error("method not supported"), {
2234
- method
2235
- });
2236
- if (methods?.include && !methods.include.includes(method))
2237
- throw new MethodNotSupportedRpcError(new Error("method not supported"), {
2238
- method
2239
- });
2240
- const requestId = dedupe ? stringToHex(`${uid2}.${stringify(args)}`) : void 0;
2241
- return withDedupe(() => withRetry(async () => {
2242
- try {
2243
- return await request(args);
2244
- } catch (err_) {
2245
- const err = err_;
2246
- switch (err.code) {
2247
- // -32700
2248
- case ParseRpcError.code:
2249
- throw new ParseRpcError(err);
2250
- // -32600
2251
- case InvalidRequestRpcError.code:
2252
- throw new InvalidRequestRpcError(err);
2253
- // -32601
2254
- case MethodNotFoundRpcError.code:
2255
- throw new MethodNotFoundRpcError(err, { method: args.method });
2256
- // -32602
2257
- case InvalidParamsRpcError.code:
2258
- throw new InvalidParamsRpcError(err);
2259
- // -32603
2260
- case InternalRpcError.code:
2261
- throw new InternalRpcError(err);
2262
- // -32000
2263
- case InvalidInputRpcError.code:
2264
- throw new InvalidInputRpcError(err);
2265
- // -32001
2266
- case ResourceNotFoundRpcError.code:
2267
- throw new ResourceNotFoundRpcError(err);
2268
- // -32002
2269
- case ResourceUnavailableRpcError.code:
2270
- throw new ResourceUnavailableRpcError(err);
2271
- // -32003
2272
- case TransactionRejectedRpcError.code:
2273
- throw new TransactionRejectedRpcError(err);
2274
- // -32004
2275
- case MethodNotSupportedRpcError.code:
2276
- throw new MethodNotSupportedRpcError(err, {
2277
- method: args.method
2278
- });
2279
- // -32005
2280
- case LimitExceededRpcError.code:
2281
- throw new LimitExceededRpcError(err);
2282
- // -32006
2283
- case JsonRpcVersionUnsupportedError.code:
2284
- throw new JsonRpcVersionUnsupportedError(err);
2285
- // 4001
2286
- case UserRejectedRequestError.code:
2287
- throw new UserRejectedRequestError(err);
2288
- // 4100
2289
- case UnauthorizedProviderError.code:
2290
- throw new UnauthorizedProviderError(err);
2291
- // 4200
2292
- case UnsupportedProviderMethodError.code:
2293
- throw new UnsupportedProviderMethodError(err);
2294
- // 4900
2295
- case ProviderDisconnectedError.code:
2296
- throw new ProviderDisconnectedError(err);
2297
- // 4901
2298
- case ChainDisconnectedError.code:
2299
- throw new ChainDisconnectedError(err);
2300
- // 4902
2301
- case SwitchChainError.code:
2302
- throw new SwitchChainError(err);
2303
- // 5700
2304
- case UnsupportedNonOptionalCapabilityError.code:
2305
- throw new UnsupportedNonOptionalCapabilityError(err);
2306
- // 5710
2307
- case UnsupportedChainIdError.code:
2308
- throw new UnsupportedChainIdError(err);
2309
- // 5720
2310
- case DuplicateIdError.code:
2311
- throw new DuplicateIdError(err);
2312
- // 5730
2313
- case UnknownBundleIdError.code:
2314
- throw new UnknownBundleIdError(err);
2315
- // 5740
2316
- case BundleTooLargeError.code:
2317
- throw new BundleTooLargeError(err);
2318
- // 5750
2319
- case AtomicReadyWalletRejectedUpgradeError.code:
2320
- throw new AtomicReadyWalletRejectedUpgradeError(err);
2321
- // 5760
2322
- case AtomicityNotSupportedError.code:
2323
- throw new AtomicityNotSupportedError(err);
2324
- // CAIP-25: User Rejected Error
2325
- // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25
2326
- case 5e3:
2327
- throw new UserRejectedRequestError(err);
2328
- default:
2329
- if (err_ instanceof BaseError)
2330
- throw err_;
2331
- throw new UnknownRpcError(err);
2332
- }
2333
- }
2334
- }, {
2335
- delay: ({ count, error }) => {
2336
- if (error && error instanceof HttpRequestError) {
2337
- const retryAfter = error?.headers?.get("Retry-After");
2338
- if (retryAfter?.match(/\d/))
2339
- return Number.parseInt(retryAfter, 10) * 1e3;
2340
- }
2341
- return ~~(1 << count) * retryDelay;
2342
- },
2343
- retryCount,
2344
- shouldRetry: ({ error }) => shouldRetry(error)
2345
- }), { enabled: dedupe, id: requestId });
2346
- };
2347
- }
2348
- function shouldRetry(error) {
2349
- if ("code" in error && typeof error.code === "number") {
2350
- if (error.code === -1)
2351
- return true;
2352
- if (error.code === LimitExceededRpcError.code)
2353
- return true;
2354
- if (error.code === InternalRpcError.code)
2355
- return true;
2356
- return false;
2357
- }
2358
- if (error instanceof HttpRequestError && error.status) {
2359
- if (error.status === 403)
2360
- return true;
2361
- if (error.status === 408)
2362
- return true;
2363
- if (error.status === 413)
2364
- return true;
2365
- if (error.status === 429)
2366
- return true;
2367
- if (error.status === 500)
2368
- return true;
2369
- if (error.status === 502)
2370
- return true;
2371
- if (error.status === 503)
2372
- return true;
2373
- if (error.status === 504)
2374
- return true;
2375
- return false;
2376
- }
2377
- return true;
2378
- }
2379
-
2380
- // ../../node_modules/viem/_esm/utils/promise/withTimeout.js
2381
- function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) {
2382
- return new Promise((resolve, reject) => {
2383
- ;
2384
- (async () => {
2385
- let timeoutId;
2386
- try {
2387
- const controller = new AbortController();
2388
- if (timeout > 0) {
2389
- timeoutId = setTimeout(() => {
2390
- if (signal) {
2391
- controller.abort();
2392
- } else {
2393
- reject(errorInstance);
2394
- }
2395
- }, timeout);
2396
- }
2397
- resolve(await fn({ signal: controller?.signal || null }));
2398
- } catch (err) {
2399
- if (err?.name === "AbortError")
2400
- reject(errorInstance);
2401
- reject(err);
2402
- } finally {
2403
- clearTimeout(timeoutId);
2404
- }
2405
- })();
2406
- });
2407
- }
2408
-
2409
- // ../../node_modules/viem/_esm/utils/rpc/id.js
2410
- function createIdStore() {
2411
- return {
2412
- current: 0,
2413
- take() {
2414
- return this.current++;
2415
- },
2416
- reset() {
2417
- this.current = 0;
2418
- }
2419
- };
2420
- }
2421
- var idCache = /* @__PURE__ */ createIdStore();
2422
-
2423
- // ../../node_modules/viem/_esm/utils/rpc/http.js
2424
- function getHttpRpcClient(url, options = {}) {
2425
- return {
2426
- async request(params) {
2427
- const { body, fetchFn = options.fetchFn ?? fetch, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params;
2428
- const fetchOptions = {
2429
- ...options.fetchOptions ?? {},
2430
- ...params.fetchOptions ?? {}
2431
- };
2432
- const { headers, method, signal: signal_ } = fetchOptions;
2433
- try {
2434
- const response = await withTimeout(async ({ signal }) => {
2435
- const init = {
2436
- ...fetchOptions,
2437
- body: Array.isArray(body) ? stringify(body.map((body2) => ({
2438
- jsonrpc: "2.0",
2439
- id: body2.id ?? idCache.take(),
2440
- ...body2
2441
- }))) : stringify({
2442
- jsonrpc: "2.0",
2443
- id: body.id ?? idCache.take(),
2444
- ...body
2445
- }),
2446
- headers: {
2447
- "Content-Type": "application/json",
2448
- ...headers
2449
- },
2450
- method: method || "POST",
2451
- signal: signal_ || (timeout > 0 ? signal : null)
2452
- };
2453
- const request = new Request(url, init);
2454
- const args = await onRequest?.(request, init) ?? { ...init, url };
2455
- const response2 = await fetchFn(args.url ?? url, args);
2456
- return response2;
2457
- }, {
2458
- errorInstance: new TimeoutError({ body, url }),
2459
- timeout,
2460
- signal: true
2461
- });
2462
- if (onResponse)
2463
- await onResponse(response);
2464
- let data;
2465
- if (response.headers.get("Content-Type")?.startsWith("application/json"))
2466
- data = await response.json();
2467
- else {
2468
- data = await response.text();
2469
- try {
2470
- data = JSON.parse(data || "{}");
2471
- } catch (err) {
2472
- if (response.ok)
2473
- throw err;
2474
- data = { error: data };
2475
- }
2476
- }
2477
- if (!response.ok) {
2478
- throw new HttpRequestError({
2479
- body,
2480
- details: stringify(data.error) || response.statusText,
2481
- headers: response.headers,
2482
- status: response.status,
2483
- url
2484
- });
2485
- }
2486
- return data;
2487
- } catch (err) {
2488
- if (err instanceof HttpRequestError)
2489
- throw err;
2490
- if (err instanceof TimeoutError)
2491
- throw err;
2492
- throw new HttpRequestError({
2493
- body,
2494
- cause: err,
2495
- url
2496
- });
2497
- }
2498
- }
2499
- };
2500
- }
2501
-
2502
- // ../../node_modules/viem/_esm/errors/typedData.js
2503
- var InvalidDomainError = class extends BaseError {
2504
- constructor({ domain }) {
2505
- super(`Invalid domain "${stringify(domain)}".`, {
2506
- metaMessages: ["Must be a valid EIP-712 domain."]
2507
- });
2508
- }
2509
- };
2510
- var InvalidPrimaryTypeError = class extends BaseError {
2511
- constructor({ primaryType, types }) {
2512
- super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
2513
- docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
2514
- metaMessages: ["Check that the primary type is a key in `types`."]
2515
- });
2516
- }
2517
- };
2518
- var InvalidStructTypeError = class extends BaseError {
2519
- constructor({ type }) {
2520
- super(`Struct type "${type}" is invalid.`, {
2521
- metaMessages: ["Struct type must not be a Solidity type."],
2522
- name: "InvalidStructTypeError"
2523
- });
2524
- }
2525
- };
2526
-
2527
- // ../../node_modules/viem/_esm/utils/typedData.js
2528
- function serializeTypedData(parameters) {
2529
- const { domain: domain_, message: message_, primaryType, types } = parameters;
2530
- const normalizeData = (struct, data_) => {
2531
- const data = { ...data_ };
2532
- for (const param of struct) {
2533
- const { name, type } = param;
2534
- if (type === "address")
2535
- data[name] = data[name].toLowerCase();
2536
- }
2537
- return data;
2538
- };
2539
- const domain = (() => {
2540
- if (!types.EIP712Domain)
2541
- return {};
2542
- if (!domain_)
2543
- return {};
2544
- return normalizeData(types.EIP712Domain, domain_);
2545
- })();
2546
- const message = (() => {
2547
- if (primaryType === "EIP712Domain")
2548
- return void 0;
2549
- return normalizeData(types[primaryType], message_);
2550
- })();
2551
- return stringify({ domain, message, primaryType, types });
2552
- }
2553
- function validateTypedData(parameters) {
2554
- const { domain, message, primaryType, types } = parameters;
2555
- const validateData = (struct, data) => {
2556
- for (const param of struct) {
2557
- const { name, type } = param;
2558
- const value = data[name];
2559
- const integerMatch = type.match(integerRegex);
2560
- if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
2561
- const [_type, base2, size_] = integerMatch;
2562
- numberToHex(value, {
2563
- signed: base2 === "int",
2564
- size: Number.parseInt(size_, 10) / 8
2565
- });
2566
- }
2567
- if (type === "address" && typeof value === "string" && !isAddress(value))
2568
- throw new InvalidAddressError({ address: value });
2569
- const bytesMatch = type.match(bytesRegex);
2570
- if (bytesMatch) {
2571
- const [_type, size_] = bytesMatch;
2572
- if (size_ && size(value) !== Number.parseInt(size_, 10))
2573
- throw new BytesSizeMismatchError({
2574
- expectedSize: Number.parseInt(size_, 10),
2575
- givenSize: size(value)
2576
- });
2577
- }
2578
- const struct2 = types[type];
2579
- if (struct2) {
2580
- validateReference(type);
2581
- validateData(struct2, value);
2582
- }
2583
- }
2584
- };
2585
- if (types.EIP712Domain && domain) {
2586
- if (typeof domain !== "object")
2587
- throw new InvalidDomainError({ domain });
2588
- validateData(types.EIP712Domain, domain);
2589
- }
2590
- if (primaryType !== "EIP712Domain") {
2591
- if (types[primaryType])
2592
- validateData(types[primaryType], message);
2593
- else
2594
- throw new InvalidPrimaryTypeError({ primaryType, types });
2595
- }
2596
- }
2597
- function getTypesForEIP712Domain({ domain }) {
2598
- return [
2599
- typeof domain?.name === "string" && { name: "name", type: "string" },
2600
- domain?.version && { name: "version", type: "string" },
2601
- (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
2602
- name: "chainId",
2603
- type: "uint256"
2604
- },
2605
- domain?.verifyingContract && {
2606
- name: "verifyingContract",
2607
- type: "address"
2608
- },
2609
- domain?.salt && { name: "salt", type: "bytes32" }
2610
- ].filter(Boolean);
2611
- }
2612
- function validateReference(type) {
2613
- if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
2614
- throw new InvalidStructTypeError({ type });
2615
- }
2616
-
2617
- // ../../node_modules/viem/_esm/actions/wallet/addChain.js
2618
- async function addChain(client, { chain }) {
2619
- const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain;
2620
- await client.request({
2621
- method: "wallet_addEthereumChain",
2622
- params: [
2623
- {
2624
- chainId: numberToHex(id),
2625
- chainName: name,
2626
- nativeCurrency,
2627
- rpcUrls: rpcUrls.default.http,
2628
- blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : void 0
2629
- }
2630
- ]
2631
- }, { dedupe: true, retryCount: 0 });
2632
- }
2633
-
2634
- // ../../node_modules/viem/_esm/actions/wallet/deployContract.js
2635
- function deployContract(walletClient, parameters) {
2636
- const { abi, args, bytecode, ...request } = parameters;
2637
- const calldata = encodeDeployData({ abi, args, bytecode });
2638
- return sendTransaction(walletClient, {
2639
- ...request,
2640
- ...request.authorizationList ? { to: null } : {},
2641
- data: calldata
2642
- });
2643
- }
2644
-
2645
- // ../../node_modules/viem/_esm/actions/wallet/getAddresses.js
2646
- async function getAddresses(client) {
2647
- if (client.account?.type === "local")
2648
- return [client.account.address];
2649
- const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true });
2650
- return addresses.map((address) => checksumAddress(address));
2651
- }
2652
-
2653
- // ../../node_modules/viem/_esm/actions/wallet/getCapabilities.js
2654
- async function getCapabilities(client, parameters = {}) {
2655
- const { account = client.account, chainId } = parameters;
2656
- const account_ = account ? parseAccount(account) : void 0;
2657
- const params = chainId ? [account_?.address, [numberToHex(chainId)]] : [account_?.address];
2658
- const capabilities_raw = await client.request({
2659
- method: "wallet_getCapabilities",
2660
- params
2661
- });
2662
- const capabilities = {};
2663
- for (const [chainId2, capabilities_] of Object.entries(capabilities_raw)) {
2664
- capabilities[Number(chainId2)] = {};
2665
- for (let [key, value] of Object.entries(capabilities_)) {
2666
- if (key === "addSubAccount")
2667
- key = "unstable_addSubAccount";
2668
- capabilities[Number(chainId2)][key] = value;
2669
- }
2670
- }
2671
- return typeof chainId === "number" ? capabilities[chainId] : capabilities;
2672
- }
2673
-
2674
- // ../../node_modules/viem/_esm/actions/wallet/getPermissions.js
2675
- async function getPermissions(client) {
2676
- const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true });
2677
- return permissions;
2678
- }
2679
-
2680
- // ../../node_modules/viem/_esm/actions/wallet/prepareAuthorization.js
2681
- async function prepareAuthorization(client, parameters) {
2682
- const { account: account_ = client.account, chainId, nonce } = parameters;
2683
- if (!account_)
2684
- throw new AccountNotFoundError({
2685
- docsPath: "/docs/eip7702/prepareAuthorization"
2686
- });
2687
- const account = parseAccount(account_);
2688
- const executor = (() => {
2689
- if (!parameters.executor)
2690
- return void 0;
2691
- if (parameters.executor === "self")
2692
- return parameters.executor;
2693
- return parseAccount(parameters.executor);
2694
- })();
2695
- const authorization = {
2696
- address: parameters.contractAddress ?? parameters.address,
2697
- chainId,
2698
- nonce
2699
- };
2700
- if (typeof authorization.chainId === "undefined")
2701
- authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({});
2702
- if (typeof authorization.nonce === "undefined") {
2703
- authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
2704
- address: account.address,
2705
- blockTag: "pending"
2706
- });
2707
- if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address))
2708
- authorization.nonce += 1;
2709
- }
2710
- return authorization;
2711
- }
2712
-
2713
- // ../../node_modules/viem/_esm/actions/wallet/requestAddresses.js
2714
- async function requestAddresses(client) {
2715
- const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 });
2716
- return addresses.map((address) => getAddress(address));
2717
- }
2718
-
2719
- // ../../node_modules/viem/_esm/actions/wallet/requestPermissions.js
2720
- async function requestPermissions(client, permissions) {
2721
- return client.request({
2722
- method: "wallet_requestPermissions",
2723
- params: [permissions]
2724
- }, { retryCount: 0 });
2725
- }
2726
-
2727
- // ../../node_modules/viem/_esm/actions/wallet/showCallsStatus.js
2728
- async function showCallsStatus(client, parameters) {
2729
- const { id } = parameters;
2730
- await client.request({
2731
- method: "wallet_showCallsStatus",
2732
- params: [id]
2733
- });
2734
- return;
2735
- }
2736
-
2737
- // ../../node_modules/viem/_esm/actions/wallet/signAuthorization.js
2738
- async function signAuthorization(client, parameters) {
2739
- const { account: account_ = client.account } = parameters;
2740
- if (!account_)
2741
- throw new AccountNotFoundError({
2742
- docsPath: "/docs/eip7702/signAuthorization"
2743
- });
2744
- const account = parseAccount(account_);
2745
- if (!account.signAuthorization)
2746
- throw new AccountTypeNotSupportedError({
2747
- docsPath: "/docs/eip7702/signAuthorization",
2748
- metaMessages: [
2749
- "The `signAuthorization` Action does not support JSON-RPC Accounts."
2750
- ],
2751
- type: account.type
2752
- });
2753
- const authorization = await prepareAuthorization(client, parameters);
2754
- return account.signAuthorization(authorization);
2755
- }
2756
-
2757
- // ../../node_modules/viem/_esm/actions/wallet/signMessage.js
2758
- async function signMessage(client, { account: account_ = client.account, message }) {
2759
- if (!account_)
2760
- throw new AccountNotFoundError({
2761
- docsPath: "/docs/actions/wallet/signMessage"
2762
- });
2763
- const account = parseAccount(account_);
2764
- if (account.signMessage)
2765
- return account.signMessage({ message });
2766
- const message_ = (() => {
2767
- if (typeof message === "string")
2768
- return stringToHex(message);
2769
- if (message.raw instanceof Uint8Array)
2770
- return toHex(message.raw);
2771
- return message.raw;
2772
- })();
2773
- return client.request({
2774
- method: "personal_sign",
2775
- params: [message_, account.address]
2776
- }, { retryCount: 0 });
2777
- }
2778
-
2779
- // ../../node_modules/viem/_esm/actions/wallet/signTransaction.js
2780
- async function signTransaction(client, parameters) {
2781
- const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters;
2782
- if (!account_)
2783
- throw new AccountNotFoundError({
2784
- docsPath: "/docs/actions/wallet/signTransaction"
2785
- });
2786
- const account = parseAccount(account_);
2787
- assertRequest({
2788
- account,
2789
- ...parameters
2790
- });
2791
- const chainId = await getAction(client, getChainId, "getChainId")({});
2792
- if (chain !== null)
2793
- assertCurrentChain({
2794
- currentChainId: chainId,
2795
- chain
2796
- });
2797
- const formatters2 = chain?.formatters || client.chain?.formatters;
2798
- const format = formatters2?.transactionRequest?.format || formatTransactionRequest;
2799
- if (account.signTransaction)
2800
- return account.signTransaction({
2801
- ...transaction,
2802
- chainId
2803
- }, { serializer: client.chain?.serializers?.transaction });
2804
- return await client.request({
2805
- method: "eth_signTransaction",
2806
- params: [
2807
- {
2808
- ...format(transaction),
2809
- chainId: numberToHex(chainId),
2810
- from: account.address
2811
- }
2812
- ]
2813
- }, { retryCount: 0 });
2814
- }
2815
-
2816
- // ../../node_modules/viem/_esm/actions/wallet/signTypedData.js
2817
- async function signTypedData(client, parameters) {
2818
- const { account: account_ = client.account, domain, message, primaryType } = parameters;
2819
- if (!account_)
2820
- throw new AccountNotFoundError({
2821
- docsPath: "/docs/actions/wallet/signTypedData"
2822
- });
2823
- const account = parseAccount(account_);
2824
- const types = {
2825
- EIP712Domain: getTypesForEIP712Domain({ domain }),
2826
- ...parameters.types
2827
- };
2828
- validateTypedData({ domain, message, primaryType, types });
2829
- if (account.signTypedData)
2830
- return account.signTypedData({ domain, message, primaryType, types });
2831
- const typedData = serializeTypedData({ domain, message, primaryType, types });
2832
- return client.request({
2833
- method: "eth_signTypedData_v4",
2834
- params: [account.address, typedData]
2835
- }, { retryCount: 0 });
2836
- }
2837
-
2838
- // ../../node_modules/viem/_esm/actions/wallet/switchChain.js
2839
- async function switchChain(client, { id }) {
2840
- await client.request({
2841
- method: "wallet_switchEthereumChain",
2842
- params: [
2843
- {
2844
- chainId: numberToHex(id)
2845
- }
2846
- ]
2847
- }, { retryCount: 0 });
2848
- }
2849
-
2850
- // ../../node_modules/viem/_esm/actions/wallet/watchAsset.js
2851
- async function watchAsset(client, params) {
2852
- const added = await client.request({
2853
- method: "wallet_watchAsset",
2854
- params
2855
- }, { retryCount: 0 });
2856
- return added;
2857
- }
2858
-
2859
- // ../../node_modules/viem/_esm/clients/decorators/wallet.js
2860
- function walletActions(client) {
2861
- return {
2862
- addChain: (args) => addChain(client, args),
2863
- deployContract: (args) => deployContract(client, args),
2864
- getAddresses: () => getAddresses(client),
2865
- getCallsStatus: (args) => getCallsStatus(client, args),
2866
- getCapabilities: (args) => getCapabilities(client, args),
2867
- getChainId: () => getChainId(client),
2868
- getPermissions: () => getPermissions(client),
2869
- prepareAuthorization: (args) => prepareAuthorization(client, args),
2870
- prepareTransactionRequest: (args) => prepareTransactionRequest(client, args),
2871
- requestAddresses: () => requestAddresses(client),
2872
- requestPermissions: (args) => requestPermissions(client, args),
2873
- sendCalls: (args) => sendCalls(client, args),
2874
- sendRawTransaction: (args) => sendRawTransaction(client, args),
2875
- sendTransaction: (args) => sendTransaction(client, args),
2876
- showCallsStatus: (args) => showCallsStatus(client, args),
2877
- signAuthorization: (args) => signAuthorization(client, args),
2878
- signMessage: (args) => signMessage(client, args),
2879
- signTransaction: (args) => signTransaction(client, args),
2880
- signTypedData: (args) => signTypedData(client, args),
2881
- switchChain: (args) => switchChain(client, args),
2882
- waitForCallsStatus: (args) => waitForCallsStatus(client, args),
2883
- watchAsset: (args) => watchAsset(client, args),
2884
- writeContract: (args) => writeContract(client, args)
2885
- };
2886
- }
2887
-
2888
- // ../../node_modules/viem/_esm/clients/createWalletClient.js
2889
- function createWalletClient(parameters) {
2890
- const { key = "wallet", name = "Wallet Client", transport } = parameters;
2891
- const client = createClient({
2892
- ...parameters,
2893
- key,
2894
- name,
2895
- transport,
2896
- type: "walletClient"
2897
- });
2898
- return client.extend(walletActions);
2899
- }
2900
-
2901
- // ../../node_modules/viem/_esm/clients/transports/createTransport.js
2902
- function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) {
2903
- const uid2 = uid();
2904
- return {
2905
- config: {
2906
- key,
2907
- methods,
2908
- name,
2909
- request,
2910
- retryCount,
2911
- retryDelay,
2912
- timeout,
2913
- type
2914
- },
2915
- request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }),
2916
- value
2917
- };
2918
- }
2919
-
2920
- // ../../node_modules/viem/_esm/errors/transport.js
2921
- var UrlRequiredError = class extends BaseError {
2922
- constructor() {
2923
- super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", {
2924
- docsPath: "/docs/clients/intro",
2925
- name: "UrlRequiredError"
2926
- });
2927
- }
2928
- };
2929
-
2930
- // ../../node_modules/viem/_esm/clients/transports/http.js
2931
- function http(url, config = {}) {
2932
- const { batch, fetchFn, fetchOptions, key = "http", methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw } = config;
2933
- return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {
2934
- const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {};
2935
- const retryCount = config.retryCount ?? retryCount_;
2936
- const timeout = timeout_ ?? config.timeout ?? 1e4;
2937
- const url_ = url || chain?.rpcUrls.default.http[0];
2938
- if (!url_)
2939
- throw new UrlRequiredError();
2940
- const rpcClient = getHttpRpcClient(url_, {
2941
- fetchFn,
2942
- fetchOptions,
2943
- onRequest: onFetchRequest,
2944
- onResponse: onFetchResponse,
2945
- timeout
2946
- });
2947
- return createTransport({
2948
- key,
2949
- methods,
2950
- name,
2951
- async request({ method, params }) {
2952
- const body = { method, params };
2953
- const { schedule } = createBatchScheduler({
2954
- id: url_,
2955
- wait: wait2,
2956
- shouldSplitBatch(requests) {
2957
- return requests.length > batchSize;
2958
- },
2959
- fn: (body2) => rpcClient.request({
2960
- body: body2
2961
- }),
2962
- sort: (a, b) => a.id - b.id
2963
- });
2964
- const fn = async (body2) => batch ? schedule(body2) : [
2965
- await rpcClient.request({
2966
- body: body2
2967
- })
2968
- ];
2969
- const [{ error, result }] = await fn(body);
2970
- if (raw)
2971
- return { error, result };
2972
- if (error)
2973
- throw new RpcRequestError({
2974
- body,
2975
- error,
2976
- url: url_
2977
- });
2978
- return result;
2979
- },
2980
- retryCount,
2981
- retryDelay,
2982
- timeout,
2983
- type: "http"
2984
- }, {
2985
- fetchOptions,
2986
- url: url_
2987
- });
2988
- };
2989
- }
2990
-
2991
- // src/mcp/x402.ts
5
+ import { createWalletClient, http } from "viem";
2992
6
  import { createPaymentHeader } from "x402/client";
7
+
8
+ //#region src/mcp/x402.ts
2993
9
  function withX402(server, cfg) {
2994
- const { verify, settle } = useFacilitator(cfg.facilitator);
2995
- const x402Version = cfg.version ?? 1;
2996
- function paidTool(name, description, priceUSD, paramsSchema, annotations, cb) {
2997
- return server.tool(
2998
- name,
2999
- description,
3000
- paramsSchema,
3001
- { ...annotations, paymentHint: true, paymentPriceUSD: priceUSD },
3002
- (async (args, extra) => {
3003
- const atomic = processPriceToAtomicAmount(priceUSD, cfg.network);
3004
- if ("error" in atomic) {
3005
- const payload = { x402Version, error: "PRICE_COMPUTE_FAILED" };
3006
- return {
3007
- isError: true,
3008
- _meta: { "x402/error": payload },
3009
- content: [{ type: "text", text: JSON.stringify(payload) }]
3010
- };
3011
- }
3012
- const { maxAmountRequired, asset } = atomic;
3013
- const requirements = {
3014
- scheme: "exact",
3015
- network: cfg.network,
3016
- maxAmountRequired,
3017
- payTo: cfg.recipient,
3018
- asset: asset.address,
3019
- maxTimeoutSeconds: 300,
3020
- resource: `x402://${name}`,
3021
- mimeType: "application/json",
3022
- description,
3023
- extra: "eip712" in asset ? asset.eip712 : void 0
3024
- };
3025
- const headers = extra?.requestInfo?.headers ?? {};
3026
- const token = extra?._meta?.["x402/payment"] ?? headers["X-PAYMENT"];
3027
- const paymentRequired = (reason = "PAYMENT_REQUIRED", extraFields = {}) => {
3028
- const payload = {
3029
- x402Version,
3030
- error: reason,
3031
- accepts: [requirements],
3032
- ...extraFields
3033
- };
3034
- return {
3035
- isError: true,
3036
- _meta: { "x402/error": payload },
3037
- content: [{ type: "text", text: JSON.stringify(payload) }]
3038
- };
3039
- };
3040
- if (!token || typeof token !== "string") return paymentRequired();
3041
- let decoded;
3042
- try {
3043
- decoded = exact.evm.decodePayment(token);
3044
- decoded.x402Version = x402Version;
3045
- } catch {
3046
- return paymentRequired("INVALID_PAYMENT");
3047
- }
3048
- const vr = await verify(decoded, requirements);
3049
- if (!vr.isValid) {
3050
- return paymentRequired(vr.invalidReason ?? "INVALID_PAYMENT", {
3051
- payer: vr.payer
3052
- });
3053
- }
3054
- let result;
3055
- let failed = false;
3056
- try {
3057
- result = await cb(args, extra);
3058
- if (result && typeof result === "object" && "isError" in result && result.isError) {
3059
- failed = true;
3060
- }
3061
- } catch (e) {
3062
- failed = true;
3063
- result = {
3064
- isError: true,
3065
- content: [
3066
- { type: "text", text: `Tool execution failed: ${String(e)}` }
3067
- ]
3068
- };
3069
- }
3070
- if (!failed) {
3071
- try {
3072
- const s = await settle(decoded, requirements);
3073
- if (s.success) {
3074
- result._meta ??= {};
3075
- result._meta["x402/payment-response"] = {
3076
- success: true,
3077
- transaction: s.transaction,
3078
- network: s.network,
3079
- payer: s.payer
3080
- };
3081
- } else {
3082
- return paymentRequired(s.errorReason ?? "SETTLEMENT_FAILED");
3083
- }
3084
- } catch {
3085
- return paymentRequired("SETTLEMENT_FAILED");
3086
- }
3087
- }
3088
- return result;
3089
- })
3090
- );
3091
- }
3092
- Object.defineProperty(server, "paidTool", {
3093
- value: paidTool,
3094
- writable: false,
3095
- enumerable: false,
3096
- configurable: true
3097
- });
3098
- return server;
3099
- }
3100
- var toChain = (network) => {
3101
- switch (network) {
3102
- case "base":
3103
- return base;
3104
- case "base-sepolia":
3105
- return baseSepolia;
3106
- default:
3107
- throw new Error(`Unsupported network: ${network}`);
3108
- }
10
+ const { verify, settle } = useFacilitator(cfg.facilitator);
11
+ const x402Version = cfg.version ?? 1;
12
+ function paidTool(name, description, priceUSD, paramsSchema, annotations, cb) {
13
+ return server.tool(name, description, paramsSchema, {
14
+ ...annotations,
15
+ paymentHint: true,
16
+ paymentPriceUSD: priceUSD
17
+ }, (async (args, extra) => {
18
+ const atomic = processPriceToAtomicAmount(priceUSD, cfg.network);
19
+ if ("error" in atomic) {
20
+ const payload = {
21
+ x402Version,
22
+ error: "PRICE_COMPUTE_FAILED"
23
+ };
24
+ return {
25
+ isError: true,
26
+ _meta: { "x402/error": payload },
27
+ content: [{
28
+ type: "text",
29
+ text: JSON.stringify(payload)
30
+ }]
31
+ };
32
+ }
33
+ const { maxAmountRequired, asset } = atomic;
34
+ const requirements = {
35
+ scheme: "exact",
36
+ network: cfg.network,
37
+ maxAmountRequired,
38
+ payTo: cfg.recipient,
39
+ asset: asset.address,
40
+ maxTimeoutSeconds: 300,
41
+ resource: `x402://${name}`,
42
+ mimeType: "application/json",
43
+ description,
44
+ extra: "eip712" in asset ? asset.eip712 : void 0
45
+ };
46
+ const headers = extra?.requestInfo?.headers ?? {};
47
+ const token = extra?._meta?.["x402/payment"] ?? headers["X-PAYMENT"];
48
+ const paymentRequired = (reason = "PAYMENT_REQUIRED", extraFields = {}) => {
49
+ const payload = {
50
+ x402Version,
51
+ error: reason,
52
+ accepts: [requirements],
53
+ ...extraFields
54
+ };
55
+ return {
56
+ isError: true,
57
+ _meta: { "x402/error": payload },
58
+ content: [{
59
+ type: "text",
60
+ text: JSON.stringify(payload)
61
+ }]
62
+ };
63
+ };
64
+ if (!token || typeof token !== "string") return paymentRequired();
65
+ let decoded;
66
+ try {
67
+ decoded = exact.evm.decodePayment(token);
68
+ decoded.x402Version = x402Version;
69
+ } catch {
70
+ return paymentRequired("INVALID_PAYMENT");
71
+ }
72
+ const vr = await verify(decoded, requirements);
73
+ if (!vr.isValid) return paymentRequired(vr.invalidReason ?? "INVALID_PAYMENT", { payer: vr.payer });
74
+ let result;
75
+ let failed = false;
76
+ try {
77
+ result = await cb(args, extra);
78
+ if (result && typeof result === "object" && "isError" in result && result.isError) failed = true;
79
+ } catch (e) {
80
+ failed = true;
81
+ result = {
82
+ isError: true,
83
+ content: [{
84
+ type: "text",
85
+ text: `Tool execution failed: ${String(e)}`
86
+ }]
87
+ };
88
+ }
89
+ if (!failed) try {
90
+ const s = await settle(decoded, requirements);
91
+ if (s.success) {
92
+ result._meta ??= {};
93
+ result._meta["x402/payment-response"] = {
94
+ success: true,
95
+ transaction: s.transaction,
96
+ network: s.network,
97
+ payer: s.payer
98
+ };
99
+ } else return paymentRequired(s.errorReason ?? "SETTLEMENT_FAILED");
100
+ } catch {
101
+ return paymentRequired("SETTLEMENT_FAILED");
102
+ }
103
+ return result;
104
+ }));
105
+ }
106
+ Object.defineProperty(server, "paidTool", {
107
+ value: paidTool,
108
+ writable: false,
109
+ enumerable: false,
110
+ configurable: true
111
+ });
112
+ return server;
113
+ }
114
+ const toChain = (network) => {
115
+ switch (network) {
116
+ case "base": return base;
117
+ case "base-sepolia": return baseSepolia;
118
+ default: throw new Error(`Unsupported network: ${network}`);
119
+ }
3109
120
  };
3110
121
  function withX402Client(client, x402Config) {
3111
- const { network, account, version } = x402Config;
3112
- const wallet = createWalletClient({
3113
- account,
3114
- transport: http(),
3115
- chain: toChain(network)
3116
- });
3117
- const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(0.1 * 10 ** 6);
3118
- const _listTools = client.listTools.bind(client);
3119
- const listTools = async (params, options) => {
3120
- const toolsRes = await _listTools(params, options);
3121
- toolsRes.tools = toolsRes.tools.map((tool) => {
3122
- let description = tool.description;
3123
- if (tool.annotations?.paymentHint) {
3124
- const cost = tool.annotations?.paymentPriceUSD ? `$${tool.annotations?.paymentPriceUSD}` : "an unknown amount";
3125
- description += ` (This is a paid tool, you will be charged ${cost} for its execution)`;
3126
- }
3127
- return {
3128
- ...tool,
3129
- description
3130
- };
3131
- });
3132
- return toolsRes;
3133
- };
3134
- const _callTool = client.callTool.bind(client);
3135
- const callToolWithPayment = async (x402ConfirmationCallback, params, resultSchema, options) => {
3136
- const res = await _callTool(params, resultSchema, options);
3137
- console.log("res", res);
3138
- const maybeX402Error = res._meta?.["x402/error"];
3139
- if (res.isError && maybeX402Error && maybeX402Error.accepts && Array.isArray(maybeX402Error.accepts) && maybeX402Error.accepts.length > 0) {
3140
- const accepts = maybeX402Error.accepts;
3141
- const confirmationCallback = x402ConfirmationCallback ?? x402Config.confirmationCallback;
3142
- if (confirmationCallback && !await confirmationCallback(accepts)) {
3143
- return {
3144
- isError: true,
3145
- content: [{ type: "text", text: "User declined payment" }]
3146
- };
3147
- }
3148
- const req = accepts.find((a) => a?.scheme === "exact" && a?.network === network) ?? accepts[0];
3149
- if (!req || req.scheme !== "exact") return res;
3150
- const maxAmountRequired = BigInt(req.maxAmountRequired);
3151
- if (maxAmountRequired > maxPaymentValue) {
3152
- return {
3153
- isError: true,
3154
- content: [
3155
- {
3156
- type: "text",
3157
- text: `Payment exceeds client cap: ${maxAmountRequired} > ${maxPaymentValue}`
3158
- }
3159
- ]
3160
- };
3161
- }
3162
- const token = await createPaymentHeader(
3163
- wallet,
3164
- version ?? 1,
3165
- req
3166
- );
3167
- return _callTool(
3168
- {
3169
- ...params,
3170
- _meta: {
3171
- ...params._meta,
3172
- "x402/payment": token
3173
- }
3174
- },
3175
- resultSchema,
3176
- options
3177
- );
3178
- }
3179
- return res;
3180
- };
3181
- const _client = client;
3182
- _client.listTools = listTools;
3183
- Object.defineProperty(_client, "callTool", {
3184
- value: callToolWithPayment,
3185
- writable: false,
3186
- enumerable: false,
3187
- configurable: true
3188
- });
3189
- return _client;
3190
- }
3191
- export {
3192
- withX402,
3193
- withX402Client
3194
- };
122
+ const { network, account, version } = x402Config;
123
+ const wallet = createWalletClient({
124
+ account,
125
+ transport: http(),
126
+ chain: toChain(network)
127
+ });
128
+ const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(.1 * 10 ** 6);
129
+ const _listTools = client.listTools.bind(client);
130
+ const listTools = async (params, options) => {
131
+ const toolsRes = await _listTools(params, options);
132
+ toolsRes.tools = toolsRes.tools.map((tool) => {
133
+ let description = tool.description;
134
+ if (tool.annotations?.paymentHint) {
135
+ const cost = tool.annotations?.paymentPriceUSD ? `$${tool.annotations?.paymentPriceUSD}` : "an unknown amount";
136
+ description += ` (This is a paid tool, you will be charged ${cost} for its execution)`;
137
+ }
138
+ return {
139
+ ...tool,
140
+ description
141
+ };
142
+ });
143
+ return toolsRes;
144
+ };
145
+ const _callTool = client.callTool.bind(client);
146
+ const callToolWithPayment = async (x402ConfirmationCallback, params, resultSchema, options) => {
147
+ const res = await _callTool(params, resultSchema, options);
148
+ console.log("res", res);
149
+ const maybeX402Error = res._meta?.["x402/error"];
150
+ if (res.isError && maybeX402Error && maybeX402Error.accepts && Array.isArray(maybeX402Error.accepts) && maybeX402Error.accepts.length > 0) {
151
+ const accepts = maybeX402Error.accepts;
152
+ const confirmationCallback = x402ConfirmationCallback ?? x402Config.confirmationCallback;
153
+ if (confirmationCallback && !await confirmationCallback(accepts)) return {
154
+ isError: true,
155
+ content: [{
156
+ type: "text",
157
+ text: "User declined payment"
158
+ }]
159
+ };
160
+ const req = accepts.find((a) => a?.scheme === "exact" && a?.network === network) ?? accepts[0];
161
+ if (!req || req.scheme !== "exact") return res;
162
+ const maxAmountRequired = BigInt(req.maxAmountRequired);
163
+ if (maxAmountRequired > maxPaymentValue) return {
164
+ isError: true,
165
+ content: [{
166
+ type: "text",
167
+ text: `Payment exceeds client cap: ${maxAmountRequired} > ${maxPaymentValue}`
168
+ }]
169
+ };
170
+ const token = await createPaymentHeader(wallet, version ?? 1, req);
171
+ return _callTool({
172
+ ...params,
173
+ _meta: {
174
+ ...params._meta,
175
+ "x402/payment": token
176
+ }
177
+ }, resultSchema, options);
178
+ }
179
+ return res;
180
+ };
181
+ const _client = client;
182
+ _client.listTools = listTools;
183
+ Object.defineProperty(_client, "callTool", {
184
+ value: callToolWithPayment,
185
+ writable: false,
186
+ enumerable: false,
187
+ configurable: true
188
+ });
189
+ return _client;
190
+ }
191
+
192
+ //#endregion
193
+ export { withX402, withX402Client };
3195
194
  //# sourceMappingURL=x402.js.map