viem 0.0.1-alpha.3 → 0.0.1-alpha.30

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 (101) hide show
  1. package/chains/package.json +1 -1
  2. package/contract/package.json +4 -0
  3. package/dist/chain-00b37e4e.d.ts +543 -0
  4. package/dist/chain-38182d92.d.ts +5 -0
  5. package/dist/chains.d.ts +1305 -74
  6. package/dist/chains.js +125 -130
  7. package/dist/chains.js.map +1 -0
  8. package/dist/chains.mjs +129 -0
  9. package/dist/chains.mjs.map +1 -0
  10. package/dist/chunk-23UHN6UC.mjs +210 -0
  11. package/dist/chunk-23UHN6UC.mjs.map +1 -0
  12. package/dist/chunk-25AJVKAT.mjs +3436 -0
  13. package/dist/chunk-25AJVKAT.mjs.map +1 -0
  14. package/dist/chunk-AO7KQBK3.mjs +265 -0
  15. package/dist/chunk-AO7KQBK3.mjs.map +1 -0
  16. package/dist/chunk-BHMSFL4W.js +265 -0
  17. package/dist/chunk-BHMSFL4W.js.map +1 -0
  18. package/dist/chunk-EAD66IDC.js +3436 -0
  19. package/dist/chunk-EAD66IDC.js.map +1 -0
  20. package/dist/{chunk-YZEQFYZ3.js → chunk-EYRMK2SV.mjs} +725 -556
  21. package/dist/chunk-EYRMK2SV.mjs.map +1 -0
  22. package/dist/chunk-IP3NSE7H.mjs +197 -0
  23. package/dist/chunk-IP3NSE7H.mjs.map +1 -0
  24. package/dist/chunk-NPFW67BV.js +210 -0
  25. package/dist/chunk-NPFW67BV.js.map +1 -0
  26. package/dist/chunk-VOK5ALIT.js +197 -0
  27. package/dist/chunk-VOK5ALIT.js.map +1 -0
  28. package/dist/chunk-ZX4U6QKQ.js +1216 -0
  29. package/dist/chunk-ZX4U6QKQ.js.map +1 -0
  30. package/dist/contract.d.ts +11 -0
  31. package/dist/contract.js +57 -0
  32. package/dist/contract.js.map +1 -0
  33. package/dist/contract.mjs +57 -0
  34. package/dist/contract.mjs.map +1 -0
  35. package/dist/createClient-5258d590.d.ts +70 -0
  36. package/dist/createPublicClient-99be385b.d.ts +650 -0
  37. package/dist/{eip1193-8b4d90ce.d.ts → eip1193-fcdeee04.d.ts} +13 -10
  38. package/dist/ens.d.ts +22 -0
  39. package/dist/ens.js +22 -0
  40. package/dist/ens.js.map +1 -0
  41. package/dist/ens.mjs +22 -0
  42. package/dist/ens.mjs.map +1 -0
  43. package/dist/formatAbiItem-50cb39d8.d.ts +14 -0
  44. package/dist/getAbiItem-6d4f64d2.d.ts +97 -0
  45. package/dist/index.d.ts +245 -66
  46. package/dist/index.js +767 -344
  47. package/dist/index.js.map +1 -0
  48. package/dist/index.mjs +767 -0
  49. package/dist/index.mjs.map +1 -0
  50. package/dist/namehash-88f4639d.d.ts +22 -0
  51. package/dist/parseGwei-e299cf13.d.ts +506 -0
  52. package/dist/public.d.ts +29 -0
  53. package/dist/public.js +60 -0
  54. package/dist/public.js.map +1 -0
  55. package/dist/public.mjs +60 -0
  56. package/dist/public.mjs.map +1 -0
  57. package/dist/test-79ec416c.d.ts +213 -0
  58. package/dist/test.d.ts +20 -0
  59. package/dist/test.js +62 -0
  60. package/dist/test.js.map +1 -0
  61. package/dist/test.mjs +62 -0
  62. package/dist/test.mjs.map +1 -0
  63. package/dist/utils/index.d.ts +52 -7
  64. package/dist/utils/index.js +185 -126
  65. package/dist/utils/index.js.map +1 -0
  66. package/dist/utils/index.mjs +185 -0
  67. package/dist/utils/index.mjs.map +1 -0
  68. package/dist/wallet-cf5c8351.d.ts +115 -0
  69. package/dist/wallet.d.ts +7 -0
  70. package/dist/wallet.js +24 -0
  71. package/dist/wallet.js.map +1 -0
  72. package/dist/wallet.mjs +24 -0
  73. package/dist/wallet.mjs.map +1 -0
  74. package/dist/window.d.ts +5 -2
  75. package/dist/window.js +1 -0
  76. package/dist/window.js.map +1 -0
  77. package/dist/window.mjs +1 -0
  78. package/dist/window.mjs.map +1 -0
  79. package/ens/package.json +4 -0
  80. package/package.json +46 -73
  81. package/public/package.json +4 -0
  82. package/test/package.json +4 -0
  83. package/utils/package.json +1 -1
  84. package/wallet/package.json +4 -0
  85. package/window/package.json +1 -1
  86. package/actions/package.json +0 -4
  87. package/clients/package.json +0 -4
  88. package/dist/actions/index.d.ts +0 -7
  89. package/dist/actions/index.js +0 -124
  90. package/dist/chunk-SRDTRROA.js +0 -1214
  91. package/dist/chunk-TLEMV4T3.js +0 -258
  92. package/dist/chunk-WZITKXV3.js +0 -996
  93. package/dist/clients/index.d.ts +0 -7
  94. package/dist/clients/index.js +0 -23
  95. package/dist/createWalletClient-15ad1601.d.ts +0 -130
  96. package/dist/parseGwei-0f85e8ca.d.ts +0 -248
  97. package/dist/rpc-15b85963.d.ts +0 -292
  98. package/dist/rpc-26932bae.d.ts +0 -61
  99. package/dist/transactionRequest-f538ea86.d.ts +0 -44
  100. package/dist/watchAsset-0c9d01e2.d.ts +0 -522
  101. package/dist/webSocket-b55b0951.d.ts +0 -83
@@ -0,0 +1,3436 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+
8
+ // package.json
9
+ var package_default = {
10
+ name: "viem",
11
+ description: "TypeScript Interface for Ethereum",
12
+ version: "0.0.1-alpha.30",
13
+ scripts: {
14
+ anvil: "source .env && anvil --fork-url $VITE_ANVIL_FORK_URL --fork-block-number $VITE_ANVIL_BLOCK_NUMBER --block-time $VITE_ANVIL_BLOCK_TIME",
15
+ bench: "vitest bench --no-threads",
16
+ "bench:ci": "CI=true vitest bench --no-threads",
17
+ build: "tsup",
18
+ changeset: "changeset",
19
+ "changeset:release": "pnpm build && changeset publish",
20
+ "changeset:version": "changeset version && pnpm install --lockfile-only",
21
+ clean: "rimraf dist chains contract ens public test utils wallet window",
22
+ "contracts:build": "wagmi generate",
23
+ dev: "DEV=true tsup",
24
+ "dev:docs": "pnpm -r --filter site dev",
25
+ format: "rome format src/ --write",
26
+ lint: "rome check .",
27
+ "lint:fix": "pnpm lint --apply-suggested",
28
+ playground: "pnpm --filter playground-browser dev",
29
+ postinstall: "pnpm dev && pnpm contracts:build",
30
+ preinstall: "npx only-allow pnpm",
31
+ prepublishOnly: "pnpm bun scripts/prepublishOnly.ts",
32
+ prepare: "npx simple-git-hooks",
33
+ test: "vitest dev --no-threads",
34
+ "test:cov": "vitest dev --coverage --no-threads",
35
+ "test:ci": "CI=true vitest --coverage --no-threads",
36
+ "test:ui": "vitest dev --ui --no-threads",
37
+ "ts-node": "bun",
38
+ typecheck: "tsc --noEmit"
39
+ },
40
+ tsup: {
41
+ entry: [
42
+ "src/index.ts",
43
+ "src/chains.ts",
44
+ "src/contract.ts",
45
+ "src/ens.ts",
46
+ "src/public.ts",
47
+ "src/test.ts",
48
+ "src/utils/index.ts",
49
+ "src/wallet.ts",
50
+ "src/window.ts"
51
+ ]
52
+ },
53
+ files: [
54
+ "/dist",
55
+ "/chains",
56
+ "/contract",
57
+ "/ens",
58
+ "/public",
59
+ "/test",
60
+ "/utils",
61
+ "/wallet",
62
+ "/window"
63
+ ],
64
+ exports: {
65
+ ".": {
66
+ types: "./dist/index.d.ts",
67
+ module: "./dist/index.mts",
68
+ default: "./dist/index.js"
69
+ },
70
+ "./chains": {
71
+ types: "./dist/chains.d.ts",
72
+ module: "./dist/chains.mts",
73
+ default: "./dist/chains.js"
74
+ },
75
+ "./contract": {
76
+ types: "./dist/contract.d.ts",
77
+ module: "./dist/contract.mts",
78
+ default: "./dist/contract.js"
79
+ },
80
+ "./ens": {
81
+ types: "./dist/ens.d.ts",
82
+ module: "./dist/ens.mts",
83
+ default: "./dist/ens.js"
84
+ },
85
+ "./public": {
86
+ types: "./dist/public.d.ts",
87
+ module: "./dist/public.mts",
88
+ default: "./dist/public.js"
89
+ },
90
+ "./test": {
91
+ types: "./dist/test.d.ts",
92
+ module: "./dist/test.mts",
93
+ default: "./dist/test.js"
94
+ },
95
+ "./utils": {
96
+ types: "./dist/utils/index.d.ts",
97
+ module: "./dist/utils/index.mts",
98
+ default: "./dist/utils/index.js"
99
+ },
100
+ "./wallet": {
101
+ types: "./dist/wallet.d.ts",
102
+ module: "./dist/wallet.mts",
103
+ default: "./dist/wallet.js"
104
+ },
105
+ "./window": {
106
+ types: "./dist/window.d.ts",
107
+ module: "./dist/window.mts",
108
+ default: "./dist/window.js"
109
+ },
110
+ "./package.json": "./package.json"
111
+ },
112
+ main: "dist/index.js",
113
+ module: "dist/index.mjs",
114
+ types: "dist/index.d.ts",
115
+ sideEffects: false,
116
+ dependencies: {
117
+ "@noble/hashes": "^1.1.2",
118
+ "@wagmi/chains": "~0.2.8",
119
+ abitype: "~0.3.0",
120
+ "idna-uts46-hx": "^4.1.2",
121
+ "isomorphic-ws": "^5.0.0",
122
+ ws: "^8.12.0"
123
+ },
124
+ devDependencies: {
125
+ "@actions/core": "^1.10.0",
126
+ "@actions/github": "^5.1.1",
127
+ "@adraffy/ens-normalize": "^1.8.9",
128
+ "@changesets/changelog-github": "^0.4.5",
129
+ "@changesets/cli": "^2.23.2",
130
+ "@types/dedent": "^0.7.0",
131
+ "@types/fs-extra": "^9.0.13",
132
+ "@types/node": "^17.0.45",
133
+ "@types/ws": "^8.5.4",
134
+ "@vitest/coverage-c8": "^0.24.3",
135
+ "@vitest/ui": "^0.19.1",
136
+ "@wagmi/cli": "^0.1.6",
137
+ bun: "^0.5.5",
138
+ bundlewatch: "^0.3.3",
139
+ dedent: "^0.7.0",
140
+ ethers: "^5.7.2",
141
+ "ethers@6": "npm:ethers@^6.0.2",
142
+ execa: "^6.1.0",
143
+ "fs-extra": "^10.1.0",
144
+ rimraf: "^4.1.2",
145
+ rome: "^11.0.0",
146
+ "simple-git-hooks": "^2.8.1",
147
+ tsup: "^6.6.0",
148
+ typescript: "^4.9.4",
149
+ vite: "^3.2.5",
150
+ vitest: "~0.25.8",
151
+ web3: "^1.8.1"
152
+ },
153
+ license: "MIT",
154
+ repository: "wagmi-dev/viem",
155
+ authors: [
156
+ "awkweb.eth",
157
+ "jxom.eth"
158
+ ],
159
+ keywords: [
160
+ "eth",
161
+ "ethereum",
162
+ "dapps",
163
+ "wallet",
164
+ "web3"
165
+ ],
166
+ "simple-git-hooks": {
167
+ "pre-commit": "pnpm format && pnpm lint:fix"
168
+ },
169
+ pnpm: {
170
+ patchedDependencies: {
171
+ "vitepress@1.0.0-alpha.34": "patches/vitepress@1.0.0-alpha.34.patch"
172
+ }
173
+ }
174
+ };
175
+
176
+ // src/errors/utils.ts
177
+ var getContractAddress = (address) => address;
178
+ var getUrl = (url) => url;
179
+ var getVersion = () => `${package_default.name}@${package_default.version}`;
180
+
181
+ // src/errors/base.ts
182
+ var BaseError = class extends Error {
183
+ constructor(shortMessage, args = {}) {
184
+ const details = args.cause instanceof BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details;
185
+ const docsPath5 = args.cause instanceof BaseError ? args.cause.docsPath || args.docsPath : args.docsPath;
186
+ const message = [
187
+ shortMessage || "An error occurred.",
188
+ "",
189
+ ...args.metaMessages ? [...args.metaMessages, ""] : [],
190
+ ...docsPath5 ? [`Docs: https://viem.sh${docsPath5}`] : [],
191
+ ...details ? [`Details: ${details}`] : [],
192
+ `Version: ${getVersion()}`
193
+ ].join("\n");
194
+ super(message);
195
+ __publicField(this, "details");
196
+ __publicField(this, "docsPath");
197
+ __publicField(this, "metaMessages");
198
+ __publicField(this, "shortMessage");
199
+ __publicField(this, "name", "ViemError");
200
+ if (args.cause)
201
+ this.cause = args.cause;
202
+ this.details = details;
203
+ this.docsPath = docsPath5;
204
+ this.metaMessages = args.metaMessages;
205
+ this.shortMessage = shortMessage;
206
+ }
207
+ };
208
+
209
+ // src/errors/abi.ts
210
+ var AbiConstructorNotFoundError = class extends BaseError {
211
+ constructor({ docsPath: docsPath5 }) {
212
+ super(
213
+ [
214
+ "A constructor was not found on the ABI.",
215
+ "Make sure you are using the correct ABI and that the constructor exists on it."
216
+ ].join("\n"),
217
+ {
218
+ docsPath: docsPath5
219
+ }
220
+ );
221
+ __publicField(this, "name", "AbiConstructorNotFoundError");
222
+ }
223
+ };
224
+ var AbiConstructorParamsNotFoundError = class extends BaseError {
225
+ constructor({ docsPath: docsPath5 }) {
226
+ super(
227
+ [
228
+ "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.",
229
+ "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."
230
+ ].join("\n"),
231
+ {
232
+ docsPath: docsPath5
233
+ }
234
+ );
235
+ __publicField(this, "name", "AbiConstructorParamsNotFoundError");
236
+ }
237
+ };
238
+ var AbiDecodingDataSizeInvalidError = class extends BaseError {
239
+ constructor(size2) {
240
+ super(
241
+ [
242
+ `Data size of ${size2} bytes is invalid.`,
243
+ "Size must be in increments of 32 bytes (size % 32 === 0)."
244
+ ].join("\n")
245
+ );
246
+ __publicField(this, "name", "AbiDecodingDataSizeInvalidError");
247
+ }
248
+ };
249
+ var AbiDecodingZeroDataError = class extends BaseError {
250
+ constructor() {
251
+ super('Cannot decode zero data ("0x") with ABI parameters.');
252
+ __publicField(this, "name", "AbiDecodingZeroDataError");
253
+ }
254
+ };
255
+ var AbiEncodingArrayLengthMismatchError = class extends BaseError {
256
+ constructor({
257
+ expectedLength,
258
+ givenLength,
259
+ type
260
+ }) {
261
+ super(
262
+ [
263
+ `ABI encoding array length mismatch for type ${type}.`,
264
+ `Expected length: ${expectedLength}`,
265
+ `Given length: ${givenLength}`
266
+ ].join("\n")
267
+ );
268
+ __publicField(this, "name", "AbiEncodingArrayLengthMismatchError");
269
+ }
270
+ };
271
+ var AbiEncodingLengthMismatchError = class extends BaseError {
272
+ constructor({
273
+ expectedLength,
274
+ givenLength
275
+ }) {
276
+ super(
277
+ [
278
+ "ABI encoding params/values length mismatch.",
279
+ `Expected length (params): ${expectedLength}`,
280
+ `Given length (values): ${givenLength}`
281
+ ].join("\n")
282
+ );
283
+ __publicField(this, "name", "AbiEncodingLengthMismatchError");
284
+ }
285
+ };
286
+ var AbiErrorInputsNotFoundError = class extends BaseError {
287
+ constructor(errorName, { docsPath: docsPath5 }) {
288
+ super(
289
+ [
290
+ `Arguments (\`args\`) were provided to "${errorName}", but "${errorName}" on the ABI does not contain any parameters (\`inputs\`).`,
291
+ "Cannot encode error result without knowing what the parameter types are.",
292
+ "Make sure you are using the correct ABI and that the inputs exist on it."
293
+ ].join("\n"),
294
+ {
295
+ docsPath: docsPath5
296
+ }
297
+ );
298
+ __publicField(this, "name", "AbiErrorInputsNotFoundError");
299
+ }
300
+ };
301
+ var AbiErrorNotFoundError = class extends BaseError {
302
+ constructor(errorName, { docsPath: docsPath5 }) {
303
+ super(
304
+ [
305
+ `Error "${errorName}" not found on ABI.`,
306
+ "Make sure you are using the correct ABI and that the error exists on it."
307
+ ].join("\n"),
308
+ {
309
+ docsPath: docsPath5
310
+ }
311
+ );
312
+ __publicField(this, "name", "AbiErrorNotFoundError");
313
+ }
314
+ };
315
+ var AbiErrorSignatureNotFoundError = class extends BaseError {
316
+ constructor(signature, { docsPath: docsPath5 }) {
317
+ super(
318
+ [
319
+ `Encoded error signature "${signature}" not found on ABI.`,
320
+ "Make sure you are using the correct ABI and that the error exists on it.",
321
+ `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`
322
+ ].join("\n"),
323
+ {
324
+ docsPath: docsPath5
325
+ }
326
+ );
327
+ __publicField(this, "name", "AbiErrorSignatureNotFoundError");
328
+ }
329
+ };
330
+ var AbiEventSignatureNotFoundError = class extends BaseError {
331
+ constructor(signature, { docsPath: docsPath5 }) {
332
+ super(
333
+ [
334
+ `Encoded event signature "${signature}" not found on ABI.`,
335
+ "Make sure you are using the correct ABI and that the event exists on it.",
336
+ `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`
337
+ ].join("\n"),
338
+ {
339
+ docsPath: docsPath5
340
+ }
341
+ );
342
+ __publicField(this, "name", "AbiEventSignatureNotFoundError");
343
+ }
344
+ };
345
+ var AbiEventNotFoundError = class extends BaseError {
346
+ constructor(eventName, { docsPath: docsPath5 }) {
347
+ super(
348
+ [
349
+ `Event "${eventName}" not found on ABI.`,
350
+ "Make sure you are using the correct ABI and that the event exists on it."
351
+ ].join("\n"),
352
+ {
353
+ docsPath: docsPath5
354
+ }
355
+ );
356
+ __publicField(this, "name", "AbiEventNotFoundError");
357
+ }
358
+ };
359
+ var AbiFunctionNotFoundError = class extends BaseError {
360
+ constructor(functionName, { docsPath: docsPath5 }) {
361
+ super(
362
+ [
363
+ `Function "${functionName}" not found on ABI.`,
364
+ "Make sure you are using the correct ABI and that the function exists on it."
365
+ ].join("\n"),
366
+ {
367
+ docsPath: docsPath5
368
+ }
369
+ );
370
+ __publicField(this, "name", "AbiFunctionNotFoundError");
371
+ }
372
+ };
373
+ var AbiFunctionOutputsNotFoundError = class extends BaseError {
374
+ constructor(functionName, { docsPath: docsPath5 }) {
375
+ super(
376
+ [
377
+ `Function "${functionName}" does not contain any \`outputs\` on ABI.`,
378
+ "Cannot decode function result without knowing what the parameter types are.",
379
+ "Make sure you are using the correct ABI and that the function exists on it."
380
+ ].join("\n"),
381
+ {
382
+ docsPath: docsPath5
383
+ }
384
+ );
385
+ __publicField(this, "name", "AbiFunctionOutputsNotFoundError");
386
+ }
387
+ };
388
+ var AbiFunctionSignatureNotFoundError = class extends BaseError {
389
+ constructor(signature, { docsPath: docsPath5 }) {
390
+ super(
391
+ [
392
+ `Encoded function signature "${signature}" not found on ABI.`,
393
+ "Make sure you are using the correct ABI and that the function exists on it.",
394
+ `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`
395
+ ].join("\n"),
396
+ {
397
+ docsPath: docsPath5
398
+ }
399
+ );
400
+ __publicField(this, "name", "AbiFunctionSignatureNotFoundError");
401
+ }
402
+ };
403
+ var InvalidAbiEncodingTypeError = class extends BaseError {
404
+ constructor(type, { docsPath: docsPath5 }) {
405
+ super(
406
+ [
407
+ `Type "${type}" is not a valid encoding type.`,
408
+ "Please provide a valid ABI type."
409
+ ].join("\n"),
410
+ { docsPath: docsPath5 }
411
+ );
412
+ __publicField(this, "name", "InvalidAbiEncodingType");
413
+ }
414
+ };
415
+ var InvalidAbiDecodingTypeError = class extends BaseError {
416
+ constructor(type, { docsPath: docsPath5 }) {
417
+ super(
418
+ [
419
+ `Type "${type}" is not a valid decoding type.`,
420
+ "Please provide a valid ABI type."
421
+ ].join("\n"),
422
+ { docsPath: docsPath5 }
423
+ );
424
+ __publicField(this, "name", "InvalidAbiDecodingType");
425
+ }
426
+ };
427
+ var InvalidArrayError = class extends BaseError {
428
+ constructor(value) {
429
+ super([`Value "${value}" is not a valid array.`].join("\n"));
430
+ __publicField(this, "name", "InvalidArrayError");
431
+ }
432
+ };
433
+ var InvalidDefinitionTypeError = class extends BaseError {
434
+ constructor(type) {
435
+ super(
436
+ [
437
+ `"${type}" is not a valid definition type.`,
438
+ 'Valid types: "function", "event", "error"'
439
+ ].join("\n")
440
+ );
441
+ __publicField(this, "name", "InvalidDefinitionTypeError");
442
+ }
443
+ };
444
+
445
+ // src/errors/address.ts
446
+ var InvalidAddressError = class extends BaseError {
447
+ constructor({ address }) {
448
+ super(`Address "${address}" is invalid.`);
449
+ __publicField(this, "name", "InvalidAddressError");
450
+ }
451
+ };
452
+
453
+ // src/errors/block.ts
454
+ var BlockNotFoundError = class extends BaseError {
455
+ constructor({
456
+ blockHash,
457
+ blockNumber
458
+ }) {
459
+ let identifier = "Block";
460
+ if (blockHash)
461
+ identifier = `Block at hash "${blockHash}"`;
462
+ if (blockNumber)
463
+ identifier = `Block at number "${blockNumber}"`;
464
+ super(`${identifier} could not be found.`);
465
+ __publicField(this, "name", "BlockNotFoundError");
466
+ }
467
+ };
468
+
469
+ // src/errors/chain.ts
470
+ var ChainDoesNotSupportContract = class extends BaseError {
471
+ constructor({
472
+ blockNumber,
473
+ chain,
474
+ contract
475
+ }) {
476
+ super(
477
+ `Chain "${chain.name}" does not support contract "${contract.name}".`,
478
+ {
479
+ metaMessages: [
480
+ "This could be due to any of the following:",
481
+ ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [
482
+ `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`
483
+ ] : [
484
+ `- The chain does not have the contract "${contract.name}" configured.`
485
+ ]
486
+ ]
487
+ }
488
+ );
489
+ __publicField(this, "name", "ChainDoesNotSupportContract");
490
+ }
491
+ };
492
+
493
+ // src/constants/abis.ts
494
+ var multicall3Abi = [
495
+ {
496
+ inputs: [
497
+ {
498
+ components: [
499
+ {
500
+ name: "target",
501
+ type: "address"
502
+ },
503
+ {
504
+ name: "allowFailure",
505
+ type: "bool"
506
+ },
507
+ {
508
+ name: "callData",
509
+ type: "bytes"
510
+ }
511
+ ],
512
+ name: "calls",
513
+ type: "tuple[]"
514
+ }
515
+ ],
516
+ name: "aggregate3",
517
+ outputs: [
518
+ {
519
+ components: [
520
+ {
521
+ name: "success",
522
+ type: "bool"
523
+ },
524
+ {
525
+ name: "returnData",
526
+ type: "bytes"
527
+ }
528
+ ],
529
+ name: "returnData",
530
+ type: "tuple[]"
531
+ }
532
+ ],
533
+ stateMutability: "view",
534
+ type: "function"
535
+ }
536
+ ];
537
+
538
+ // src/constants/solidity.ts
539
+ var panicReasons = {
540
+ 1: "An `assert` condition failed.",
541
+ 17: "Arithmic operation resulted in underflow or overflow.",
542
+ 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",
543
+ 33: "Attempted to convert to an invalid type.",
544
+ 34: "Attempted to access a storage byte array that is incorrectly encoded.",
545
+ 49: "Performed `.pop()` on an empty array",
546
+ 50: "Array index is out of bounds.",
547
+ 65: "Allocated too much memory or created an array which is too large.",
548
+ 81: "Attempted to call a zero-initialized variable of internal function type."
549
+ };
550
+ var solidityError = {
551
+ inputs: [
552
+ {
553
+ name: "message",
554
+ type: "string"
555
+ }
556
+ ],
557
+ name: "Error",
558
+ type: "error"
559
+ };
560
+ var solidityPanic = {
561
+ inputs: [
562
+ {
563
+ name: "reason",
564
+ type: "uint256"
565
+ }
566
+ ],
567
+ name: "Panic",
568
+ type: "error"
569
+ };
570
+
571
+ // src/errors/transaction.ts
572
+ function prettyPrint(args) {
573
+ const entries = Object.entries(args).map(([key, value]) => {
574
+ if (value === void 0 || value === false)
575
+ return null;
576
+ return [key, value];
577
+ }).filter(Boolean);
578
+ const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
579
+ return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n");
580
+ }
581
+ var TransactionExecutionError = class extends BaseError {
582
+ constructor(cause, {
583
+ docsPath: docsPath5,
584
+ from,
585
+ chain,
586
+ data,
587
+ gas,
588
+ gasPrice,
589
+ maxFeePerGas,
590
+ maxPriorityFeePerGas,
591
+ nonce,
592
+ to,
593
+ value
594
+ }) {
595
+ const prettyArgs = prettyPrint({
596
+ from,
597
+ to,
598
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
599
+ data,
600
+ gas,
601
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
602
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
603
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
604
+ nonce
605
+ });
606
+ super(cause.shortMessage, {
607
+ cause,
608
+ docsPath: docsPath5,
609
+ metaMessages: [
610
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
611
+ "Request Arguments:",
612
+ prettyArgs
613
+ ].filter(Boolean)
614
+ });
615
+ __publicField(this, "cause");
616
+ __publicField(this, "name", "TransactionExecutionError");
617
+ this.cause = cause;
618
+ }
619
+ };
620
+ var TransactionNotFoundError = class extends BaseError {
621
+ constructor({
622
+ blockHash,
623
+ blockNumber,
624
+ blockTag,
625
+ hash: hash2,
626
+ index
627
+ }) {
628
+ let identifier = "Transaction";
629
+ if (blockTag && index !== void 0)
630
+ identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
631
+ if (blockHash && index !== void 0)
632
+ identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
633
+ if (blockNumber && index !== void 0)
634
+ identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
635
+ if (hash2)
636
+ identifier = `Transaction with hash "${hash2}"`;
637
+ super(`${identifier} could not be found.`);
638
+ __publicField(this, "name", "TransactionNotFoundError");
639
+ }
640
+ };
641
+ var TransactionReceiptNotFoundError = class extends BaseError {
642
+ constructor({ hash: hash2 }) {
643
+ super(
644
+ `Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`
645
+ );
646
+ __publicField(this, "name", "TransactionReceiptNotFoundError");
647
+ }
648
+ };
649
+ var WaitForTransactionReceiptTimeoutError = class extends BaseError {
650
+ constructor({ hash: hash2 }) {
651
+ super(
652
+ `Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`
653
+ );
654
+ __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
655
+ }
656
+ };
657
+
658
+ // src/errors/contract.ts
659
+ var CallExecutionError = class extends BaseError {
660
+ constructor(cause, {
661
+ docsPath: docsPath5,
662
+ from,
663
+ chain,
664
+ data,
665
+ gas,
666
+ gasPrice,
667
+ maxFeePerGas,
668
+ maxPriorityFeePerGas,
669
+ nonce,
670
+ to,
671
+ value
672
+ }) {
673
+ const prettyArgs = prettyPrint({
674
+ from,
675
+ to,
676
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
677
+ data,
678
+ gas,
679
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
680
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
681
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
682
+ nonce
683
+ });
684
+ super(cause.shortMessage, {
685
+ cause,
686
+ docsPath: docsPath5,
687
+ metaMessages: [
688
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
689
+ "Raw Call Arguments:",
690
+ prettyArgs
691
+ ].filter(Boolean)
692
+ });
693
+ __publicField(this, "cause");
694
+ __publicField(this, "name", "CallExecutionError");
695
+ this.cause = cause;
696
+ }
697
+ };
698
+ var ContractFunctionExecutionError = class extends BaseError {
699
+ constructor(cause, {
700
+ abi,
701
+ args,
702
+ contractAddress,
703
+ docsPath: docsPath5,
704
+ functionName,
705
+ sender
706
+ }) {
707
+ const abiItem = getAbiItem({ abi, args, name: functionName });
708
+ const formattedArgs = abiItem ? formatAbiItemWithArgs({
709
+ abiItem,
710
+ args,
711
+ includeFunctionName: false,
712
+ includeName: false
713
+ }) : void 0;
714
+ const functionWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
715
+ const prettyArgs = prettyPrint({
716
+ address: contractAddress && getContractAddress(contractAddress),
717
+ function: functionWithParams,
718
+ args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`,
719
+ sender
720
+ });
721
+ super(
722
+ cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`,
723
+ {
724
+ cause,
725
+ docsPath: docsPath5,
726
+ metaMessages: [
727
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
728
+ "Contract Call:",
729
+ prettyArgs
730
+ ].filter(Boolean)
731
+ }
732
+ );
733
+ __publicField(this, "abi");
734
+ __publicField(this, "args");
735
+ __publicField(this, "cause");
736
+ __publicField(this, "contractAddress");
737
+ __publicField(this, "formattedArgs");
738
+ __publicField(this, "functionName");
739
+ __publicField(this, "sender");
740
+ __publicField(this, "name", "ContractFunctionExecutionError");
741
+ this.abi = abi;
742
+ this.args = args;
743
+ this.cause = cause;
744
+ this.contractAddress = contractAddress;
745
+ this.functionName = functionName;
746
+ this.sender = sender;
747
+ }
748
+ };
749
+ var ContractFunctionRevertedError = class extends BaseError {
750
+ constructor({
751
+ abi,
752
+ data,
753
+ functionName,
754
+ message
755
+ }) {
756
+ let decodedData = void 0;
757
+ let metaMessages;
758
+ let reason;
759
+ if (data && data !== "0x") {
760
+ decodedData = decodeErrorResult({ abi, data });
761
+ const { abiItem, errorName, args: errorArgs } = decodedData;
762
+ if (errorName === "Error") {
763
+ reason = errorArgs[0];
764
+ } else if (errorName === "Panic") {
765
+ const [firstArg] = errorArgs;
766
+ reason = panicReasons[firstArg];
767
+ } else if (errorArgs) {
768
+ const errorWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
769
+ const formattedArgs = abiItem ? formatAbiItemWithArgs({
770
+ abiItem,
771
+ args: errorArgs,
772
+ includeFunctionName: false,
773
+ includeName: false
774
+ }) : void 0;
775
+ metaMessages = [
776
+ errorWithParams ? `Error: ${errorWithParams}` : "",
777
+ formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : ""
778
+ ];
779
+ }
780
+ } else if (message)
781
+ reason = message;
782
+ super(
783
+ reason ? [
784
+ `The contract function "${functionName}" reverted with the following reason:`,
785
+ reason
786
+ ].join("\n") : `The contract function "${functionName}" reverted.`,
787
+ {
788
+ metaMessages
789
+ }
790
+ );
791
+ __publicField(this, "name", "ContractFunctionRevertedError");
792
+ __publicField(this, "data");
793
+ __publicField(this, "reason");
794
+ this.reason = reason;
795
+ this.data = decodedData;
796
+ }
797
+ };
798
+ var ContractFunctionZeroDataError = class extends BaseError {
799
+ constructor({ functionName }) {
800
+ super(`The contract function "${functionName}" returned no data ("0x").`, {
801
+ metaMessages: [
802
+ "This could be due to any of the following:",
803
+ ` - The contract does not have the function "${functionName}",`,
804
+ " - The parameters passed to the contract function may be invalid, or",
805
+ " - The address is not a contract."
806
+ ]
807
+ });
808
+ __publicField(this, "name", "ContractFunctionZeroDataError");
809
+ }
810
+ };
811
+ var RawContractError = class extends BaseError {
812
+ constructor({ data, message }) {
813
+ super(message || "");
814
+ __publicField(this, "code", 3);
815
+ __publicField(this, "name", "RawContractError");
816
+ __publicField(this, "data");
817
+ this.data = data;
818
+ }
819
+ };
820
+
821
+ // src/errors/data.ts
822
+ var SizeExceedsPaddingSizeError = class extends BaseError {
823
+ constructor({
824
+ size: size2,
825
+ targetSize,
826
+ type
827
+ }) {
828
+ super(
829
+ `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`
830
+ );
831
+ __publicField(this, "name", "SizeExceedsPaddingSizeError");
832
+ }
833
+ };
834
+
835
+ // src/errors/encoding.ts
836
+ var DataLengthTooLongError = class extends BaseError {
837
+ constructor({ consumed, length }) {
838
+ super(
839
+ `Consumed bytes (${consumed}) is shorter than data length (${length - 1}).`
840
+ );
841
+ __publicField(this, "name", "DataLengthTooLongError");
842
+ }
843
+ };
844
+ var DataLengthTooShortError = class extends BaseError {
845
+ constructor({ length, dataLength }) {
846
+ super(
847
+ `Data length (${dataLength - 1}) is shorter than prefix length (${length - 1}).`
848
+ );
849
+ __publicField(this, "name", "DataLengthTooShortError");
850
+ }
851
+ };
852
+ var InvalidBytesBooleanError = class extends BaseError {
853
+ constructor(bytes) {
854
+ super(
855
+ `Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`
856
+ );
857
+ __publicField(this, "name", "InvalidBytesBooleanError");
858
+ }
859
+ };
860
+ var InvalidHexBooleanError = class extends BaseError {
861
+ constructor(hex) {
862
+ super(
863
+ `Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`
864
+ );
865
+ __publicField(this, "name", "InvalidHexBooleanError");
866
+ }
867
+ };
868
+ var InvalidHexValueError = class extends BaseError {
869
+ constructor(value) {
870
+ super(
871
+ `Hex value "${value}" is an odd length (${value.length}). It must be an even length.`
872
+ );
873
+ __publicField(this, "name", "InvalidHexValueError");
874
+ }
875
+ };
876
+ var OffsetOutOfBoundsError = class extends BaseError {
877
+ constructor({ nextOffset, offset }) {
878
+ super(
879
+ `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`
880
+ );
881
+ __publicField(this, "name", "OffsetOutOfBoundsError");
882
+ }
883
+ };
884
+
885
+ // src/errors/estimateGas.ts
886
+ var EstimateGasExecutionError = class extends BaseError {
887
+ constructor(cause, {
888
+ docsPath: docsPath5,
889
+ from,
890
+ chain,
891
+ data,
892
+ gas,
893
+ gasPrice,
894
+ maxFeePerGas,
895
+ maxPriorityFeePerGas,
896
+ nonce,
897
+ to,
898
+ value
899
+ }) {
900
+ const prettyArgs = prettyPrint({
901
+ from,
902
+ to,
903
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
904
+ data,
905
+ gas,
906
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
907
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
908
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
909
+ nonce
910
+ });
911
+ super(cause.shortMessage, {
912
+ cause,
913
+ docsPath: docsPath5,
914
+ metaMessages: [
915
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
916
+ "Estimate Gas Arguments:",
917
+ prettyArgs
918
+ ].filter(Boolean)
919
+ });
920
+ __publicField(this, "cause");
921
+ __publicField(this, "name", "EstimateGasExecutionError");
922
+ this.cause = cause;
923
+ }
924
+ };
925
+
926
+ // src/errors/log.ts
927
+ var FilterTypeNotSupportedError = class extends BaseError {
928
+ constructor(type) {
929
+ super(`Filter type "${type}" is not supported.`);
930
+ __publicField(this, "name", "FilterTypeNotSupportedError");
931
+ }
932
+ };
933
+
934
+ // src/errors/node.ts
935
+ var ExecutionRevertedError = class extends BaseError {
936
+ constructor({
937
+ cause,
938
+ message
939
+ } = {}) {
940
+ const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", "");
941
+ super(
942
+ `Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`,
943
+ {
944
+ cause
945
+ }
946
+ );
947
+ __publicField(this, "name", "ExecutionRevertedError");
948
+ }
949
+ };
950
+ __publicField(ExecutionRevertedError, "code", 3);
951
+ __publicField(ExecutionRevertedError, "nodeMessage", /execution reverted/);
952
+ var FeeCapTooHighError = class extends BaseError {
953
+ constructor({
954
+ cause,
955
+ maxFeePerGas
956
+ } = {}) {
957
+ super(
958
+ `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`,
959
+ {
960
+ cause
961
+ }
962
+ );
963
+ __publicField(this, "name", "FeeCapTooHigh");
964
+ }
965
+ };
966
+ __publicField(FeeCapTooHighError, "nodeMessage", /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/);
967
+ var FeeCapTooLowError = class extends BaseError {
968
+ constructor({
969
+ cause,
970
+ maxFeePerGas
971
+ } = {}) {
972
+ super(
973
+ `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`,
974
+ {
975
+ cause
976
+ }
977
+ );
978
+ __publicField(this, "name", "FeeCapTooLow");
979
+ }
980
+ };
981
+ __publicField(FeeCapTooLowError, "nodeMessage", /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/);
982
+ var NonceTooHighError = class extends BaseError {
983
+ constructor({ cause, nonce } = {}) {
984
+ super(
985
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`,
986
+ { cause }
987
+ );
988
+ __publicField(this, "name", "NonceTooHighError");
989
+ }
990
+ };
991
+ __publicField(NonceTooHighError, "nodeMessage", /nonce too high/);
992
+ var NonceTooLowError = class extends BaseError {
993
+ constructor({ cause, nonce } = {}) {
994
+ super(
995
+ [
996
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`,
997
+ "Try increasing the nonce or find the latest nonce with `getTransactionCount`."
998
+ ].join("\n"),
999
+ { cause }
1000
+ );
1001
+ __publicField(this, "name", "NonceTooLowError");
1002
+ }
1003
+ };
1004
+ __publicField(NonceTooLowError, "nodeMessage", /nonce too low|transaction already imported/);
1005
+ var NonceMaxValueError = class extends BaseError {
1006
+ constructor({ cause, nonce } = {}) {
1007
+ super(
1008
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`,
1009
+ { cause }
1010
+ );
1011
+ __publicField(this, "name", "NonceMaxValueError");
1012
+ }
1013
+ };
1014
+ __publicField(NonceMaxValueError, "nodeMessage", /nonce has max value/);
1015
+ var InsufficientFundsError = class extends BaseError {
1016
+ constructor({ cause } = {}) {
1017
+ super(
1018
+ [
1019
+ "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."
1020
+ ].join("\n"),
1021
+ {
1022
+ cause,
1023
+ metaMessages: [
1024
+ "This error could arise when the account does not have enough funds to:",
1025
+ " - pay for the total gas fee,",
1026
+ " - pay for the value to send.",
1027
+ " ",
1028
+ "The cost of the transaction is calculated as `gas * gas fee + value`, where:",
1029
+ " - `gas` is the amount of gas needed for transaction to execute,",
1030
+ " - `gas fee` is the gas fee,",
1031
+ " - `value` is the amount of ether to send to the recipient."
1032
+ ]
1033
+ }
1034
+ );
1035
+ __publicField(this, "name", "InsufficientFundsError");
1036
+ }
1037
+ };
1038
+ __publicField(InsufficientFundsError, "nodeMessage", /insufficient funds/);
1039
+ var IntrinsicGasTooHighError = class extends BaseError {
1040
+ constructor({ cause, gas } = {}) {
1041
+ super(
1042
+ `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`,
1043
+ {
1044
+ cause
1045
+ }
1046
+ );
1047
+ __publicField(this, "name", "IntrinsicGasTooHighError");
1048
+ }
1049
+ };
1050
+ __publicField(IntrinsicGasTooHighError, "nodeMessage", /intrinsic gas too high|gas limit reached/);
1051
+ var IntrinsicGasTooLowError = class extends BaseError {
1052
+ constructor({ cause, gas } = {}) {
1053
+ super(
1054
+ `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`,
1055
+ {
1056
+ cause
1057
+ }
1058
+ );
1059
+ __publicField(this, "name", "IntrinsicGasTooLowError");
1060
+ }
1061
+ };
1062
+ __publicField(IntrinsicGasTooLowError, "nodeMessage", /intrinsic gas too low/);
1063
+ var TransactionTypeNotSupportedError = class extends BaseError {
1064
+ constructor({ cause }) {
1065
+ super("The transaction type is not supported for this chain.", {
1066
+ cause
1067
+ });
1068
+ __publicField(this, "name", "TransactionTypeNotSupportedError");
1069
+ }
1070
+ };
1071
+ __publicField(TransactionTypeNotSupportedError, "nodeMessage", /transaction type not valid/);
1072
+ var TipAboveFeeCapError = class extends BaseError {
1073
+ constructor({
1074
+ cause,
1075
+ maxPriorityFeePerGas,
1076
+ maxFeePerGas
1077
+ } = {}) {
1078
+ super(
1079
+ [
1080
+ `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).`
1081
+ ].join("\n"),
1082
+ {
1083
+ cause
1084
+ }
1085
+ );
1086
+ __publicField(this, "name", "TipAboveFeeCapError");
1087
+ }
1088
+ };
1089
+ __publicField(TipAboveFeeCapError, "nodeMessage", /max priority fee per gas higher than max fee per gas|tip higher than fee cap/);
1090
+ var UnknownNodeError = class extends BaseError {
1091
+ constructor({ cause }) {
1092
+ super(`An error occurred while executing: ${cause?.message}`, {
1093
+ cause
1094
+ });
1095
+ __publicField(this, "name", "UnknownNodeError");
1096
+ }
1097
+ };
1098
+
1099
+ // src/errors/request.ts
1100
+ var RequestError = class extends BaseError {
1101
+ constructor(err, {
1102
+ docsPath: docsPath5,
1103
+ metaMessages,
1104
+ shortMessage
1105
+ }) {
1106
+ super(shortMessage, {
1107
+ cause: err,
1108
+ docsPath: docsPath5,
1109
+ metaMessages
1110
+ });
1111
+ this.name = err.name;
1112
+ }
1113
+ };
1114
+ var RpcRequestError = class extends RequestError {
1115
+ constructor(err, { docsPath: docsPath5, shortMessage }) {
1116
+ super(err, { docsPath: docsPath5, metaMessages: err.metaMessages, shortMessage });
1117
+ __publicField(this, "code");
1118
+ this.code = err.code;
1119
+ this.name = err.name;
1120
+ }
1121
+ };
1122
+ var ParseRpcError = class extends RpcRequestError {
1123
+ constructor(err) {
1124
+ super(err, {
1125
+ shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
1126
+ });
1127
+ __publicField(this, "name", "ParseRpcError");
1128
+ __publicField(this, "code", -32700);
1129
+ }
1130
+ };
1131
+ var InvalidRequestRpcError = class extends RpcRequestError {
1132
+ constructor(err) {
1133
+ super(err, { shortMessage: "JSON is not a valid request object." });
1134
+ __publicField(this, "name", "InvalidRequestRpcError");
1135
+ __publicField(this, "code", -32600);
1136
+ }
1137
+ };
1138
+ var MethodNotFoundRpcError = class extends RpcRequestError {
1139
+ constructor(err) {
1140
+ super(err, {
1141
+ shortMessage: "The method does not exist / is not available."
1142
+ });
1143
+ __publicField(this, "name", "MethodNotFoundRpcError");
1144
+ __publicField(this, "code", -32601);
1145
+ }
1146
+ };
1147
+ var InvalidParamsRpcError = class extends RpcRequestError {
1148
+ constructor(err) {
1149
+ super(err, {
1150
+ shortMessage: [
1151
+ "Invalid parameters were provided to the RPC method.",
1152
+ "Double check you have provided the correct parameters."
1153
+ ].join("\n")
1154
+ });
1155
+ __publicField(this, "name", "InvalidParamsRpcError");
1156
+ __publicField(this, "code", -32602);
1157
+ }
1158
+ };
1159
+ var InternalRpcError = class extends RpcRequestError {
1160
+ constructor(err) {
1161
+ super(err, { shortMessage: "An internal error was received." });
1162
+ __publicField(this, "name", "InternalRpcError");
1163
+ __publicField(this, "code", -32603);
1164
+ }
1165
+ };
1166
+ var InvalidInputRpcError = class extends RpcRequestError {
1167
+ constructor(err) {
1168
+ super(err, {
1169
+ shortMessage: [
1170
+ "Missing or invalid parameters.",
1171
+ "Double check you have provided the correct parameters."
1172
+ ].join("\n")
1173
+ });
1174
+ __publicField(this, "name", "InvalidInputRpcError");
1175
+ __publicField(this, "code", -32e3);
1176
+ }
1177
+ };
1178
+ var ResourceNotFoundRpcError = class extends RpcRequestError {
1179
+ constructor(err) {
1180
+ super(err, { shortMessage: "Requested resource not found." });
1181
+ __publicField(this, "name", "ResourceNotFoundRpcError");
1182
+ __publicField(this, "code", -32001);
1183
+ }
1184
+ };
1185
+ var ResourceUnavailableRpcError = class extends RpcRequestError {
1186
+ constructor(err) {
1187
+ super(err, { shortMessage: "Requested resource not available." });
1188
+ __publicField(this, "name", "ResourceUnavailableRpcError");
1189
+ __publicField(this, "code", -32002);
1190
+ }
1191
+ };
1192
+ var TransactionRejectedRpcError = class extends RpcRequestError {
1193
+ constructor(err) {
1194
+ super(err, { shortMessage: "Transaction creation failed." });
1195
+ __publicField(this, "name", "TransactionRejectedRpcError");
1196
+ __publicField(this, "code", -32003);
1197
+ }
1198
+ };
1199
+ var MethodNotSupportedRpcError = class extends RpcRequestError {
1200
+ constructor(err) {
1201
+ super(err, { shortMessage: "Method is not implemented." });
1202
+ __publicField(this, "name", "MethodNotSupportedRpcError");
1203
+ __publicField(this, "code", -32004);
1204
+ }
1205
+ };
1206
+ var LimitExceededRpcError = class extends RpcRequestError {
1207
+ constructor(err) {
1208
+ super(err, { shortMessage: "Request exceeds defined limit." });
1209
+ __publicField(this, "name", "LimitExceededRpcError");
1210
+ __publicField(this, "code", -32005);
1211
+ }
1212
+ };
1213
+ var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
1214
+ constructor(err) {
1215
+ super(err, {
1216
+ shortMessage: "Version of JSON-RPC protocol is not supported."
1217
+ });
1218
+ __publicField(this, "name", "JsonRpcVersionUnsupportedError");
1219
+ __publicField(this, "code", -32006);
1220
+ }
1221
+ };
1222
+ var UnknownRpcError = class extends RequestError {
1223
+ constructor(err) {
1224
+ super(err, {
1225
+ shortMessage: "An unknown RPC error occurred."
1226
+ });
1227
+ __publicField(this, "name", "UnknownRpcError");
1228
+ }
1229
+ };
1230
+
1231
+ // src/errors/rpc.ts
1232
+ var HttpRequestError = class extends BaseError {
1233
+ constructor({
1234
+ body,
1235
+ details,
1236
+ headers,
1237
+ status,
1238
+ url
1239
+ }) {
1240
+ super("HTTP request failed.", {
1241
+ details,
1242
+ metaMessages: [
1243
+ status && `Status: ${status}`,
1244
+ `URL: ${getUrl(url)}`,
1245
+ `Request body: ${stringify(body)}`
1246
+ ].filter(Boolean)
1247
+ });
1248
+ __publicField(this, "name", "HttpRequestError");
1249
+ __publicField(this, "body");
1250
+ __publicField(this, "headers");
1251
+ __publicField(this, "status");
1252
+ __publicField(this, "url");
1253
+ this.body = body;
1254
+ this.headers = headers;
1255
+ this.status = status;
1256
+ this.url = url;
1257
+ }
1258
+ };
1259
+ var WebSocketRequestError = class extends BaseError {
1260
+ constructor({
1261
+ body,
1262
+ details,
1263
+ url
1264
+ }) {
1265
+ super("WebSocket request failed.", {
1266
+ details,
1267
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1268
+ });
1269
+ __publicField(this, "name", "WebSocketRequestError");
1270
+ }
1271
+ };
1272
+ var RpcError = class extends BaseError {
1273
+ constructor({
1274
+ body,
1275
+ error,
1276
+ url
1277
+ }) {
1278
+ super("RPC Request failed.", {
1279
+ cause: error,
1280
+ details: error.message,
1281
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1282
+ });
1283
+ __publicField(this, "code");
1284
+ __publicField(this, "name", "RpcError");
1285
+ this.code = error.code;
1286
+ }
1287
+ };
1288
+ var TimeoutError = class extends BaseError {
1289
+ constructor({
1290
+ body,
1291
+ url
1292
+ }) {
1293
+ super("The request took too long to respond.", {
1294
+ details: "The request timed out.",
1295
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1296
+ });
1297
+ __publicField(this, "name", "TimeoutError");
1298
+ }
1299
+ };
1300
+
1301
+ // src/errors/transport.ts
1302
+ var UrlRequiredError = class extends BaseError {
1303
+ constructor() {
1304
+ super(
1305
+ "No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",
1306
+ {
1307
+ docsPath: "/docs/clients/intro"
1308
+ }
1309
+ );
1310
+ }
1311
+ };
1312
+
1313
+ // src/utils/data/concat.ts
1314
+ function concat(values) {
1315
+ if (typeof values[0] === "string")
1316
+ return concatHex(values);
1317
+ return concatBytes(values);
1318
+ }
1319
+ function concatBytes(values) {
1320
+ let length = 0;
1321
+ for (const arr of values) {
1322
+ length += arr.length;
1323
+ }
1324
+ const result = new Uint8Array(length);
1325
+ let offset = 0;
1326
+ for (const arr of values) {
1327
+ result.set(arr, offset);
1328
+ offset += arr.length;
1329
+ }
1330
+ return result;
1331
+ }
1332
+ function concatHex(values) {
1333
+ return `0x${values.reduce(
1334
+ (acc, x) => acc + x.replace("0x", ""),
1335
+ ""
1336
+ )}`;
1337
+ }
1338
+
1339
+ // src/utils/data/isBytes.ts
1340
+ function isBytes(value) {
1341
+ if (!value)
1342
+ return false;
1343
+ if (typeof value !== "object")
1344
+ return false;
1345
+ if (!("BYTES_PER_ELEMENT" in value))
1346
+ return false;
1347
+ return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
1348
+ }
1349
+
1350
+ // src/utils/data/isHex.ts
1351
+ function isHex(value) {
1352
+ if (!value)
1353
+ return false;
1354
+ if (typeof value !== "string")
1355
+ return false;
1356
+ return /^0x[0-9a-fA-F]*$/.test(value);
1357
+ }
1358
+
1359
+ // src/utils/data/pad.ts
1360
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
1361
+ if (typeof hexOrBytes === "string")
1362
+ return padHex(hexOrBytes, { dir, size: size2 });
1363
+ return padBytes(hexOrBytes, { dir, size: size2 });
1364
+ }
1365
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
1366
+ let hex = hex_.replace("0x", "");
1367
+ if (hex.length > size2 * 2)
1368
+ throw new SizeExceedsPaddingSizeError({
1369
+ size: Math.ceil(hex.length / 2),
1370
+ targetSize: size2,
1371
+ type: "hex"
1372
+ });
1373
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](
1374
+ size2 * 2,
1375
+ "0"
1376
+ )}`;
1377
+ }
1378
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
1379
+ if (bytes.length > size2)
1380
+ throw new SizeExceedsPaddingSizeError({
1381
+ size: bytes.length,
1382
+ targetSize: size2,
1383
+ type: "bytes"
1384
+ });
1385
+ const paddedBytes = new Uint8Array(size2);
1386
+ for (let i = 0; i < size2; i++) {
1387
+ const padEnd = dir === "right";
1388
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
1389
+ }
1390
+ return paddedBytes;
1391
+ }
1392
+
1393
+ // src/utils/data/trim.ts
1394
+ function trim(hexOrBytes, { dir = "left" } = {}) {
1395
+ let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
1396
+ let sliceLength = 0;
1397
+ for (let i = 0; i < data.length - 1; i++) {
1398
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
1399
+ sliceLength++;
1400
+ else
1401
+ break;
1402
+ }
1403
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
1404
+ if (typeof hexOrBytes === "string") {
1405
+ if (data.length === 1 && dir === "right")
1406
+ data = `${data}0`;
1407
+ return `0x${data}`;
1408
+ }
1409
+ return data;
1410
+ }
1411
+
1412
+ // src/utils/data/size.ts
1413
+ function size(value) {
1414
+ if (isHex(value))
1415
+ return Math.ceil((value.length - 2) / 2);
1416
+ return value.length;
1417
+ }
1418
+
1419
+ // src/utils/data/slice.ts
1420
+ function slice(value, start, end) {
1421
+ if (isHex(value))
1422
+ return sliceHex(value, start, end);
1423
+ return sliceBytes(value, start, end);
1424
+ }
1425
+ function assertStartOffset(value, start) {
1426
+ if (typeof start === "number" && start > 0 && start > size(value) - 1)
1427
+ throw new Error(
1428
+ `Slice starting at offset "${start}" is out-of-bounds (size: ${size(
1429
+ value
1430
+ )}).`
1431
+ );
1432
+ }
1433
+ function sliceBytes(value, start, end) {
1434
+ assertStartOffset(value, start);
1435
+ return value.slice(start, end);
1436
+ }
1437
+ function sliceHex(value_, start, end) {
1438
+ assertStartOffset(value_, start);
1439
+ const value = value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2);
1440
+ return `0x${value}`;
1441
+ }
1442
+
1443
+ // src/utils/encoding/toHex.ts
1444
+ var hexes = Array.from(
1445
+ { length: 256 },
1446
+ (v, i) => i.toString(16).padStart(2, "0")
1447
+ );
1448
+ function boolToHex(value) {
1449
+ return `0x${Number(value)}`;
1450
+ }
1451
+ function bytesToHex(value) {
1452
+ let hex = "";
1453
+ for (let i = 0; i < value.length; i++) {
1454
+ hex += hexes[value[i]];
1455
+ }
1456
+ return `0x${hex}`;
1457
+ }
1458
+ function toHex(value) {
1459
+ if (typeof value === "number" || typeof value === "bigint")
1460
+ return numberToHex(value);
1461
+ if (typeof value === "string") {
1462
+ return stringToHex(value);
1463
+ }
1464
+ if (typeof value === "boolean")
1465
+ return boolToHex(value);
1466
+ return bytesToHex(value);
1467
+ }
1468
+ function numberToHex(value_, opts = {}) {
1469
+ const { signed, size: size2 } = opts;
1470
+ let value = BigInt(value_);
1471
+ let maxValue;
1472
+ if (size2) {
1473
+ if (signed)
1474
+ maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
1475
+ else
1476
+ maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
1477
+ } else if (typeof value_ === "number") {
1478
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
1479
+ }
1480
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
1481
+ if (maxValue && value > maxValue || value < minValue) {
1482
+ const suffix = typeof value_ === "bigint" ? "n" : "";
1483
+ throw new Error(
1484
+ `Number "${value_}${suffix}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${maxValue ? `(${minValue}${suffix} to ${maxValue}${suffix})` : `(above ${minValue})`}`
1485
+ );
1486
+ }
1487
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
1488
+ if (size2)
1489
+ return pad(hex, { size: size2 });
1490
+ return hex;
1491
+ }
1492
+ function stringToHex(value) {
1493
+ let hex = "";
1494
+ for (let i = 0; i < value.length; i++) {
1495
+ hex += value.charCodeAt(i).toString(16);
1496
+ }
1497
+ return `0x${hex}`;
1498
+ }
1499
+
1500
+ // src/utils/encoding/toBytes.ts
1501
+ var encoder = new TextEncoder();
1502
+ function boolToBytes(value) {
1503
+ const bytes = new Uint8Array(1);
1504
+ bytes[0] = Number(value);
1505
+ return bytes;
1506
+ }
1507
+ function toBytes(value) {
1508
+ if (typeof value === "number" || typeof value === "bigint")
1509
+ return numberToBytes(value);
1510
+ if (typeof value === "boolean")
1511
+ return boolToBytes(value);
1512
+ if (value.startsWith("0x"))
1513
+ return hexToBytes(value);
1514
+ return stringToBytes(value);
1515
+ }
1516
+ function hexToBytes(hex_) {
1517
+ let hex = hex_.slice(2);
1518
+ if (hex.length % 2)
1519
+ hex = `0${hex}`;
1520
+ const bytes = new Uint8Array(hex.length / 2);
1521
+ for (let index = 0; index < bytes.length; index++) {
1522
+ const start = index * 2;
1523
+ const hexByte = hex.slice(start, start + 2);
1524
+ const byte = Number.parseInt(hexByte, 16);
1525
+ if (Number.isNaN(byte) || byte < 0)
1526
+ throw new Error("Invalid byte sequence");
1527
+ bytes[index] = byte;
1528
+ }
1529
+ return bytes;
1530
+ }
1531
+ function numberToBytes(value, opts) {
1532
+ const hex = numberToHex(value, opts);
1533
+ return hexToBytes(hex);
1534
+ }
1535
+ function stringToBytes(value) {
1536
+ return encoder.encode(value);
1537
+ }
1538
+
1539
+ // src/utils/encoding/toRlp.ts
1540
+ function toRlp(hexOrBytes, to_) {
1541
+ const to = to_ || "hex";
1542
+ return format(bytesToRlp(parse(hexOrBytes)), to);
1543
+ }
1544
+ function parse(hexOrBytes) {
1545
+ if (Array.isArray(hexOrBytes))
1546
+ return hexOrBytes.map(parse);
1547
+ return typeof hexOrBytes === "string" ? toBytes(hexOrBytes) : hexOrBytes;
1548
+ }
1549
+ function format(bytes, type = "bytes") {
1550
+ return type === "hex" ? bytesToHex(bytes) : bytes;
1551
+ }
1552
+ function bytesToRlp(bytes) {
1553
+ if (Array.isArray(bytes)) {
1554
+ const encoded = concat(bytes.map(bytesToRlp));
1555
+ return new Uint8Array([...encodeLength(encoded.length, 192), ...encoded]);
1556
+ }
1557
+ if (bytes.length === 1 && bytes[0] < 128)
1558
+ return bytes;
1559
+ return new Uint8Array([...encodeLength(bytes.length, 128), ...bytes]);
1560
+ }
1561
+ function encodeLength(length, offset) {
1562
+ if (length < 56)
1563
+ return [offset + length];
1564
+ return [toBytes(length).length + offset + 55, ...toBytes(length)];
1565
+ }
1566
+
1567
+ // src/utils/encoding/fromHex.ts
1568
+ function fromHex(hex, to) {
1569
+ if (to === "number")
1570
+ return hexToNumber(hex);
1571
+ if (to === "bigint")
1572
+ return hexToBigInt(hex);
1573
+ if (to === "string")
1574
+ return hexToString(hex);
1575
+ if (to === "boolean")
1576
+ return hexToBool(hex);
1577
+ return hexToBytes(hex);
1578
+ }
1579
+ function hexToBigInt(hex, opts = {}) {
1580
+ const { signed } = opts;
1581
+ const value = BigInt(hex);
1582
+ if (!signed)
1583
+ return value;
1584
+ const size2 = (hex.length - 2) / 2;
1585
+ const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
1586
+ if (value <= max)
1587
+ return value;
1588
+ return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
1589
+ }
1590
+ function hexToBool(hex) {
1591
+ if (trim(hex) === "0x0")
1592
+ return false;
1593
+ if (trim(hex) === "0x1")
1594
+ return true;
1595
+ throw new InvalidHexBooleanError(hex);
1596
+ }
1597
+ function hexToNumber(hex, opts = {}) {
1598
+ return Number(hexToBigInt(hex, opts));
1599
+ }
1600
+ function hexToString(hex) {
1601
+ const bytes = hexToBytes(hex);
1602
+ return new TextDecoder().decode(bytes);
1603
+ }
1604
+
1605
+ // src/utils/encoding/fromBytes.ts
1606
+ function fromBytes(bytes, to) {
1607
+ if (to === "number")
1608
+ return bytesToNumber(bytes);
1609
+ if (to === "bigint")
1610
+ return bytesToBigint(bytes);
1611
+ if (to === "boolean")
1612
+ return bytesToBool(bytes);
1613
+ if (to === "string")
1614
+ return bytesToString(bytes);
1615
+ return bytesToHex(bytes);
1616
+ }
1617
+ function bytesToBigint(bytes) {
1618
+ const hex = bytesToHex(bytes);
1619
+ return hexToBigInt(hex);
1620
+ }
1621
+ function bytesToBool(bytes) {
1622
+ if (bytes.length > 1 || bytes[0] > 1)
1623
+ throw new InvalidBytesBooleanError(bytes);
1624
+ return Boolean(bytes[0]);
1625
+ }
1626
+ function bytesToNumber(bytes) {
1627
+ const hex = bytesToHex(bytes);
1628
+ return hexToNumber(hex);
1629
+ }
1630
+ function bytesToString(bytes) {
1631
+ return new TextDecoder().decode(bytes);
1632
+ }
1633
+
1634
+ // src/utils/encoding/fromRlp.ts
1635
+ function fromRlp(value, to) {
1636
+ const bytes = parse2(value);
1637
+ const [data, consumed] = rlpToBytes(bytes);
1638
+ if (consumed < bytes.length)
1639
+ throw new DataLengthTooLongError({
1640
+ consumed,
1641
+ length: bytes.length
1642
+ });
1643
+ return format2(data, to);
1644
+ }
1645
+ function parse2(value) {
1646
+ if (typeof value === "string") {
1647
+ if (value.length > 3 && value.length % 2 !== 0)
1648
+ throw new InvalidHexValueError(value);
1649
+ return hexToBytes(value);
1650
+ }
1651
+ return value;
1652
+ }
1653
+ function format2(bytes, to) {
1654
+ if (Array.isArray(bytes))
1655
+ return bytes.map((b) => format2(b, to));
1656
+ return to === "hex" ? trim(bytesToHex(bytes)) : bytes;
1657
+ }
1658
+ function rlpToBytes(bytes, offset = 0) {
1659
+ if (bytes.length === 0)
1660
+ return [new Uint8Array([]), 0];
1661
+ const prefix = bytes[offset];
1662
+ if (prefix <= 127)
1663
+ return [new Uint8Array([bytes[offset]]), 1];
1664
+ if (prefix <= 183) {
1665
+ const length2 = prefix - 128;
1666
+ const offset_ = offset + 1;
1667
+ if (offset_ + length2 > bytes.length)
1668
+ throw new DataLengthTooShortError({
1669
+ length: offset_ + length2,
1670
+ dataLength: bytes.length
1671
+ });
1672
+ return [bytes.slice(offset_, offset_ + length2), 1 + length2];
1673
+ }
1674
+ if (prefix <= 191) {
1675
+ const lengthOfLength2 = prefix - 183;
1676
+ const offset_ = offset + 1;
1677
+ const length2 = bytesToNumber(bytes.slice(offset_, offset_ + lengthOfLength2));
1678
+ if (offset_ + lengthOfLength2 + length2 > bytes.length)
1679
+ throw new DataLengthTooShortError({
1680
+ length: lengthOfLength2 + length2,
1681
+ dataLength: bytes.length - lengthOfLength2
1682
+ });
1683
+ return [
1684
+ bytes.slice(offset_ + lengthOfLength2, offset_ + lengthOfLength2 + length2),
1685
+ 1 + lengthOfLength2 + length2
1686
+ ];
1687
+ }
1688
+ let lengthOfLength = 0;
1689
+ let length = prefix - 192;
1690
+ if (prefix > 247) {
1691
+ lengthOfLength = prefix - 247;
1692
+ length = bytesToNumber(bytes.slice(offset + 1, offset + 1 + lengthOfLength));
1693
+ }
1694
+ let nextOffset = offset + 1 + lengthOfLength;
1695
+ if (nextOffset > bytes.length)
1696
+ throw new DataLengthTooShortError({
1697
+ length: nextOffset,
1698
+ dataLength: bytes.length
1699
+ });
1700
+ let consumed = 1 + lengthOfLength + length;
1701
+ let result = [];
1702
+ while (nextOffset < offset + consumed) {
1703
+ const decoded = rlpToBytes(bytes, nextOffset);
1704
+ result.push(decoded[0]);
1705
+ nextOffset += decoded[1];
1706
+ if (nextOffset > offset + consumed)
1707
+ throw new OffsetOutOfBoundsError({
1708
+ nextOffset,
1709
+ offset: offset + consumed
1710
+ });
1711
+ }
1712
+ return [result, consumed];
1713
+ }
1714
+
1715
+ // src/utils/contract/extractFunctionParts.ts
1716
+ var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
1717
+ function extractFunctionParts(def) {
1718
+ const parts = def.match(paramsRegex);
1719
+ const type = parts?.[2] || void 0;
1720
+ const name = parts?.[3];
1721
+ const params = parts?.[5] || void 0;
1722
+ return { type, name, params };
1723
+ }
1724
+ function extractFunctionName(def) {
1725
+ return extractFunctionParts(def).name;
1726
+ }
1727
+ function extractFunctionParams(def) {
1728
+ const params = extractFunctionParts(def).params;
1729
+ const splitParams = params?.split(",").map((x) => x.trim().split(" "));
1730
+ return splitParams?.map((param) => ({
1731
+ type: param[0],
1732
+ name: param[1] === "indexed" ? param[2] : param[1],
1733
+ ...param[1] === "indexed" ? { indexed: true } : {}
1734
+ }));
1735
+ }
1736
+ function extractFunctionType(def) {
1737
+ return extractFunctionParts(def).type;
1738
+ }
1739
+
1740
+ // src/utils/hash/keccak256.ts
1741
+ import { keccak_256 } from "@noble/hashes/sha3";
1742
+ function keccak256(value, to_) {
1743
+ const to = to_ || "hex";
1744
+ const bytes = keccak_256(value);
1745
+ if (to === "bytes")
1746
+ return bytes;
1747
+ return toHex(bytes);
1748
+ }
1749
+
1750
+ // src/utils/hash/hashFunction.ts
1751
+ var hash = (value) => keccak256(toBytes(value));
1752
+ function hashFunction(def) {
1753
+ const name = extractFunctionName(def);
1754
+ const params = extractFunctionParams(def);
1755
+ if (!params || params.length === 0)
1756
+ return hash(def.replace(/ /g, ""));
1757
+ return hash(`${name}(${params.map(({ type }) => type).join(",")})`);
1758
+ }
1759
+
1760
+ // src/utils/hash/getEventSignature.ts
1761
+ var getEventSignature = (event) => hashFunction(event);
1762
+
1763
+ // src/utils/hash/getFunctionSignature.ts
1764
+ var getFunctionSignature = (fn) => slice(hashFunction(fn), 0, 4);
1765
+
1766
+ // src/utils/address/isAddress.ts
1767
+ var addressRegex = /^0x[a-fA-F0-9]{40}$/;
1768
+ function isAddress(address) {
1769
+ return addressRegex.test(address);
1770
+ }
1771
+
1772
+ // src/utils/address/getAddress.ts
1773
+ function checksumAddress(address_) {
1774
+ const hexAddress = address_.substring(2).toLowerCase();
1775
+ const hash2 = keccak256(stringToBytes(hexAddress), "bytes");
1776
+ let address = hexAddress.split("");
1777
+ for (let i = 0; i < 40; i += 2) {
1778
+ if (hash2[i >> 1] >> 4 >= 8 && address[i]) {
1779
+ address[i] = address[i].toUpperCase();
1780
+ }
1781
+ if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) {
1782
+ address[i + 1] = address[i + 1].toUpperCase();
1783
+ }
1784
+ }
1785
+ return `0x${address.join("")}`;
1786
+ }
1787
+ function getAddress(address) {
1788
+ if (!isAddress(address))
1789
+ throw new InvalidAddressError({ address });
1790
+ return checksumAddress(address);
1791
+ }
1792
+
1793
+ // src/utils/address/getContractAddress.ts
1794
+ function getContractAddress2(opts) {
1795
+ if (opts.opcode === "CREATE2")
1796
+ return getCreate2Address(opts);
1797
+ return getCreateAddress(opts);
1798
+ }
1799
+ function getCreateAddress(opts) {
1800
+ const from = toBytes(getAddress(opts.from));
1801
+ let nonce = toBytes(opts.nonce);
1802
+ if (nonce[0] === 0)
1803
+ nonce = new Uint8Array([]);
1804
+ return getAddress(
1805
+ `0x${keccak256(toRlp([from, nonce], "bytes")).slice(26)}`
1806
+ );
1807
+ }
1808
+ function getCreate2Address(opts) {
1809
+ const from = toBytes(getAddress(opts.from));
1810
+ const salt = pad(isBytes(opts.salt) ? opts.salt : toBytes(opts.salt), {
1811
+ size: 32
1812
+ });
1813
+ const bytecodeHash = toBytes(
1814
+ keccak256(
1815
+ isBytes(opts.bytecode) ? opts.bytecode : toBytes(opts.bytecode)
1816
+ )
1817
+ );
1818
+ return getAddress(
1819
+ slice(keccak256(concat([toBytes("0xff"), from, salt, bytecodeHash])), 12)
1820
+ );
1821
+ }
1822
+
1823
+ // src/utils/address/isAddressEqual.ts
1824
+ function isAddressEqual(a, b) {
1825
+ if (!isAddress(a))
1826
+ throw new InvalidAddressError({ address: a });
1827
+ if (!isAddress(b))
1828
+ throw new InvalidAddressError({ address: b });
1829
+ return a.toLowerCase() === b.toLowerCase();
1830
+ }
1831
+
1832
+ // src/utils/abi/encodeAbi.ts
1833
+ function encodeAbi({ params, values }) {
1834
+ if (params.length !== values.length)
1835
+ throw new AbiEncodingLengthMismatchError({
1836
+ expectedLength: params.length,
1837
+ givenLength: values.length
1838
+ });
1839
+ const preparedParams = prepareParams({
1840
+ params,
1841
+ values
1842
+ });
1843
+ const data = encodeParams(preparedParams);
1844
+ if (data.length === 0)
1845
+ return "0x";
1846
+ return data;
1847
+ }
1848
+ function prepareParams({
1849
+ params,
1850
+ values
1851
+ }) {
1852
+ let preparedParams = [];
1853
+ for (let i = 0; i < params.length; i++) {
1854
+ preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
1855
+ }
1856
+ return preparedParams;
1857
+ }
1858
+ function prepareParam({
1859
+ param,
1860
+ value
1861
+ }) {
1862
+ const arrayComponents = getArrayComponents(param.type);
1863
+ if (arrayComponents) {
1864
+ const [length, type] = arrayComponents;
1865
+ return encodeArray(value, { length, param: { ...param, type } });
1866
+ }
1867
+ if (param.type === "tuple") {
1868
+ return encodeTuple(value, {
1869
+ param
1870
+ });
1871
+ }
1872
+ if (param.type === "address") {
1873
+ return encodeAddress(value);
1874
+ }
1875
+ if (param.type === "bool") {
1876
+ return encodeBool(value);
1877
+ }
1878
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
1879
+ const signed = param.type.startsWith("int");
1880
+ return encodeNumber(value, { signed });
1881
+ }
1882
+ if (param.type.startsWith("bytes")) {
1883
+ return toBytes2(value, { param });
1884
+ }
1885
+ if (param.type === "string") {
1886
+ return encodeString(value);
1887
+ }
1888
+ throw new InvalidAbiEncodingTypeError(param.type, {
1889
+ docsPath: "/docs/contract/encodeAbi"
1890
+ });
1891
+ }
1892
+ function encodeParams(preparedParams) {
1893
+ let staticSize = 0;
1894
+ for (let i = 0; i < preparedParams.length; i++) {
1895
+ const { dynamic, encoded } = preparedParams[i];
1896
+ if (dynamic)
1897
+ staticSize += 32;
1898
+ else
1899
+ staticSize += size(encoded);
1900
+ }
1901
+ let staticParams = [];
1902
+ let dynamicParams = [];
1903
+ let dynamicSize = 0;
1904
+ for (let i = 0; i < preparedParams.length; i++) {
1905
+ const { dynamic, encoded } = preparedParams[i];
1906
+ if (dynamic) {
1907
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
1908
+ dynamicParams.push(encoded);
1909
+ dynamicSize += size(encoded);
1910
+ } else {
1911
+ staticParams.push(encoded);
1912
+ }
1913
+ }
1914
+ return concat([...staticParams, ...dynamicParams]);
1915
+ }
1916
+ function encodeAddress(value) {
1917
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
1918
+ }
1919
+ function encodeArray(value, {
1920
+ length,
1921
+ param
1922
+ }) {
1923
+ let dynamic = length === null;
1924
+ if (!Array.isArray(value))
1925
+ throw new InvalidArrayError(value);
1926
+ if (!dynamic && value.length !== length)
1927
+ throw new AbiEncodingArrayLengthMismatchError({
1928
+ expectedLength: length,
1929
+ givenLength: value.length,
1930
+ type: `${param.type}[${length}]`
1931
+ });
1932
+ let dynamicChild = false;
1933
+ let preparedParams = [];
1934
+ for (let i = 0; i < value.length; i++) {
1935
+ const preparedParam = prepareParam({ param, value: value[i] });
1936
+ if (preparedParam.dynamic)
1937
+ dynamicChild = true;
1938
+ preparedParams.push(preparedParam);
1939
+ }
1940
+ if (dynamic || dynamicChild) {
1941
+ const data = encodeParams(preparedParams);
1942
+ if (dynamic) {
1943
+ const length2 = numberToHex(preparedParams.length, { size: 32 });
1944
+ return {
1945
+ dynamic: true,
1946
+ encoded: preparedParams.length > 0 ? concat([length2, data]) : length2
1947
+ };
1948
+ }
1949
+ if (dynamicChild)
1950
+ return { dynamic: true, encoded: data };
1951
+ }
1952
+ return {
1953
+ dynamic: false,
1954
+ encoded: concat(preparedParams.map(({ encoded }) => encoded))
1955
+ };
1956
+ }
1957
+ function toBytes2(value, { param }) {
1958
+ const [_, size_] = param.type.split("bytes");
1959
+ if (!size_) {
1960
+ const partsLength = Math.floor(size(value) / 32);
1961
+ const parts = [];
1962
+ for (let i = 0; i < partsLength + 1; i++) {
1963
+ parts.push(padHex(slice(value, i * 32, (i + 1) * 32), { dir: "right" }));
1964
+ }
1965
+ return {
1966
+ dynamic: true,
1967
+ encoded: concat([
1968
+ padHex(numberToHex(size(value), { size: 32 })),
1969
+ ...parts
1970
+ ])
1971
+ };
1972
+ }
1973
+ return { dynamic: false, encoded: padHex(value, { dir: "right" }) };
1974
+ }
1975
+ function encodeBool(value) {
1976
+ return { dynamic: false, encoded: padHex(boolToHex(value)) };
1977
+ }
1978
+ function encodeNumber(value, { signed }) {
1979
+ return {
1980
+ dynamic: false,
1981
+ encoded: numberToHex(value, {
1982
+ size: 32,
1983
+ signed
1984
+ })
1985
+ };
1986
+ }
1987
+ function encodeString(value) {
1988
+ return {
1989
+ dynamic: true,
1990
+ encoded: concat([
1991
+ padHex(numberToHex(value.length, { size: 32 })),
1992
+ padHex(stringToHex(value), { dir: "right" })
1993
+ ])
1994
+ };
1995
+ }
1996
+ function encodeTuple(value, { param }) {
1997
+ let dynamic = false;
1998
+ let preparedParams = [];
1999
+ for (let i = 0; i < param.components.length; i++) {
2000
+ const param_ = param.components[i];
2001
+ const index = Array.isArray(value) ? i : param_.name;
2002
+ const preparedParam = prepareParam({
2003
+ param: param_,
2004
+ value: value[index]
2005
+ });
2006
+ preparedParams.push(preparedParam);
2007
+ dynamic = preparedParam.dynamic;
2008
+ }
2009
+ return {
2010
+ dynamic,
2011
+ encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
2012
+ };
2013
+ }
2014
+ function getArrayComponents(type) {
2015
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
2016
+ return matches ? (
2017
+ // Return `null` if the array is dynamic.
2018
+ [matches[2] ? Number(matches[2]) : null, matches[1]]
2019
+ ) : void 0;
2020
+ }
2021
+
2022
+ // src/utils/abi/decodeAbi.ts
2023
+ function decodeAbi({ data, params }) {
2024
+ if (data === "0x" && params.length > 0)
2025
+ throw new AbiDecodingZeroDataError();
2026
+ if (size(data) % 32 !== 0)
2027
+ throw new AbiDecodingDataSizeInvalidError(size(data));
2028
+ const values = decodeParams({
2029
+ data,
2030
+ params
2031
+ });
2032
+ if (values.length === 0)
2033
+ return void 0;
2034
+ return values;
2035
+ }
2036
+ function decodeParams({
2037
+ data,
2038
+ params
2039
+ }) {
2040
+ let decodedValues = [];
2041
+ let position = 0;
2042
+ for (let i = 0; i < params.length; i++) {
2043
+ const param = params[i];
2044
+ const { consumed, value } = decodeParam({ data, param, position });
2045
+ decodedValues.push(value);
2046
+ position += consumed;
2047
+ }
2048
+ return decodedValues;
2049
+ }
2050
+ function decodeParam({
2051
+ data,
2052
+ param,
2053
+ position
2054
+ }) {
2055
+ const arrayComponents = getArrayComponents(param.type);
2056
+ if (arrayComponents) {
2057
+ const [length, type] = arrayComponents;
2058
+ return decodeArray(data, {
2059
+ length,
2060
+ param: { ...param, type },
2061
+ position
2062
+ });
2063
+ }
2064
+ if (param.type === "tuple") {
2065
+ return decodeTuple(data, { param, position });
2066
+ }
2067
+ if (param.type === "string") {
2068
+ return decodeString(data, { position });
2069
+ }
2070
+ if (param.type.startsWith("bytes")) {
2071
+ return fromBytes2(data, { param, position });
2072
+ }
2073
+ let value = slice(data, position, position + 32);
2074
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
2075
+ return decodeNumber(value, { param });
2076
+ }
2077
+ if (param.type === "address") {
2078
+ return decodeAddress(value);
2079
+ }
2080
+ if (param.type === "bool") {
2081
+ return decodeBool(value);
2082
+ }
2083
+ throw new InvalidAbiDecodingTypeError(param.type, {
2084
+ docsPath: "/docs/contract/decodeAbi"
2085
+ });
2086
+ }
2087
+ function decodeAddress(value) {
2088
+ return { consumed: 32, value: checksumAddress(slice(value, -20)) };
2089
+ }
2090
+ function decodeArray(data, {
2091
+ param,
2092
+ length,
2093
+ position
2094
+ }) {
2095
+ if (!length) {
2096
+ const offset = hexToNumber(slice(data, position, position + 32));
2097
+ const length2 = hexToNumber(slice(data, offset, offset + 32));
2098
+ let consumed2 = 0;
2099
+ let value2 = [];
2100
+ for (let i = 0; i < length2; ++i) {
2101
+ const decodedChild = decodeParam({
2102
+ data: slice(data, offset + 32),
2103
+ param,
2104
+ position: consumed2
2105
+ });
2106
+ consumed2 += decodedChild.consumed;
2107
+ value2.push(decodedChild.value);
2108
+ }
2109
+ return { value: value2, consumed: 32 };
2110
+ }
2111
+ if (hasDynamicChild(param)) {
2112
+ const arrayComponents = getArrayComponents(param.type);
2113
+ const dynamicChild = !arrayComponents?.[0];
2114
+ let consumed2 = 0;
2115
+ let value2 = [];
2116
+ for (let i = 0; i < length; ++i) {
2117
+ const offset = hexToNumber(slice(data, position, position + 32));
2118
+ const decodedChild = decodeParam({
2119
+ data: slice(data, offset),
2120
+ param,
2121
+ position: dynamicChild ? consumed2 : i * 32
2122
+ });
2123
+ consumed2 += decodedChild.consumed;
2124
+ value2.push(decodedChild.value);
2125
+ }
2126
+ return { value: value2, consumed: consumed2 };
2127
+ }
2128
+ let consumed = 0;
2129
+ let value = [];
2130
+ for (let i = 0; i < length; ++i) {
2131
+ const decodedChild = decodeParam({
2132
+ data,
2133
+ param,
2134
+ position: position + consumed
2135
+ });
2136
+ consumed += decodedChild.consumed;
2137
+ value.push(decodedChild.value);
2138
+ }
2139
+ return { value, consumed };
2140
+ }
2141
+ function decodeBool(value) {
2142
+ return { consumed: 32, value: hexToBool(value) };
2143
+ }
2144
+ function fromBytes2(data, { param, position }) {
2145
+ const [_, size2] = param.type.split("bytes");
2146
+ if (!size2) {
2147
+ const offset = hexToNumber(slice(data, position, position + 32));
2148
+ const length = hexToNumber(slice(data, offset, offset + 32));
2149
+ const value2 = slice(data, offset + 32, offset + 32 + length);
2150
+ return { consumed: 32, value: value2 };
2151
+ }
2152
+ const value = slice(data, position, position + parseInt(size2));
2153
+ return { consumed: 32, value };
2154
+ }
2155
+ function decodeNumber(value, { param }) {
2156
+ const signed = param.type.startsWith("int");
2157
+ const size2 = parseInt(param.type.split("int")[1] || "256");
2158
+ return {
2159
+ consumed: 32,
2160
+ value: size2 > 48 ? hexToBigInt(value, { signed }) : hexToNumber(value, { signed })
2161
+ };
2162
+ }
2163
+ function decodeString(data, { position }) {
2164
+ const offset = hexToNumber(slice(data, position, position + 32));
2165
+ const length = hexToNumber(slice(data, offset, offset + 32));
2166
+ const value = hexToString(
2167
+ trim(slice(data, offset + 32, offset + 32 + length))
2168
+ );
2169
+ return { consumed: 32, value };
2170
+ }
2171
+ function decodeTuple(data, { param, position }) {
2172
+ const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name);
2173
+ let value = hasUnnamedChild ? [] : {};
2174
+ let consumed = 0;
2175
+ if (hasDynamicChild(param)) {
2176
+ const offset = hexToNumber(slice(data, position, position + 32));
2177
+ for (let i = 0; i < param.components.length; ++i) {
2178
+ const component = param.components[i];
2179
+ const decodedChild = decodeParam({
2180
+ data: slice(data, offset),
2181
+ param: component,
2182
+ position: consumed
2183
+ });
2184
+ consumed += decodedChild.consumed;
2185
+ value[hasUnnamedChild ? i : component?.name] = decodedChild.value;
2186
+ }
2187
+ return { consumed: 32, value };
2188
+ }
2189
+ for (let i = 0; i < param.components.length; ++i) {
2190
+ const component = param.components[i];
2191
+ const decodedChild = decodeParam({
2192
+ data,
2193
+ param: component,
2194
+ position: position + consumed
2195
+ });
2196
+ consumed += decodedChild.consumed;
2197
+ value[hasUnnamedChild ? i : component?.name] = decodedChild.value;
2198
+ }
2199
+ return { consumed, value };
2200
+ }
2201
+ function hasDynamicChild(param) {
2202
+ const { type } = param;
2203
+ if (type === "string")
2204
+ return true;
2205
+ if (type === "bytes")
2206
+ return true;
2207
+ if (type.endsWith("[]"))
2208
+ return true;
2209
+ if (type === "tuple")
2210
+ return param.components?.some(hasDynamicChild);
2211
+ const arrayComponents = getArrayComponents(param.type);
2212
+ if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] }))
2213
+ return true;
2214
+ return false;
2215
+ }
2216
+
2217
+ // src/utils/abi/formatAbiItem.ts
2218
+ function formatAbiItem(abiItem, { includeName = false } = {}) {
2219
+ if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error")
2220
+ throw new InvalidDefinitionTypeError(abiItem.type);
2221
+ return `${abiItem.name}(${getParams(abiItem.inputs, { includeName })})`;
2222
+ }
2223
+ function getParams(params, { includeName }) {
2224
+ if (!params)
2225
+ return "";
2226
+ return params.map((param) => getParam(param, { includeName })).join(includeName ? ", " : ",");
2227
+ }
2228
+ function getParam(param, { includeName }) {
2229
+ if (param.type.startsWith("tuple")) {
2230
+ return `(${getParams(
2231
+ param.components,
2232
+ { includeName }
2233
+ )})${param.type.slice("tuple".length)}`;
2234
+ }
2235
+ return param.type + (includeName && param.name ? ` ${param.name}` : "");
2236
+ }
2237
+
2238
+ // src/utils/abi/decodeErrorResult.ts
2239
+ function decodeErrorResult({
2240
+ abi,
2241
+ data
2242
+ }) {
2243
+ const signature = slice(data, 0, 4);
2244
+ if (signature === "0x")
2245
+ throw new AbiDecodingZeroDataError();
2246
+ const abi_ = [...abi || [], solidityError, solidityPanic];
2247
+ const abiItem = abi_.find(
2248
+ (x) => x.type === "error" && signature === getFunctionSignature(formatAbiItem(x))
2249
+ );
2250
+ if (!abiItem)
2251
+ throw new AbiErrorSignatureNotFoundError(signature, {
2252
+ docsPath: "/docs/contract/decodeErrorResult"
2253
+ });
2254
+ return {
2255
+ abiItem,
2256
+ args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: abiItem.inputs }) : void 0,
2257
+ errorName: abiItem.name
2258
+ };
2259
+ }
2260
+
2261
+ // src/utils/abi/decodeEventLog.ts
2262
+ function decodeEventLog({
2263
+ abi,
2264
+ data,
2265
+ topics
2266
+ }) {
2267
+ const [signature, ...argTopics] = topics;
2268
+ const abiItem = abi.find(
2269
+ (x) => signature === getEventSignature(formatAbiItem(x))
2270
+ );
2271
+ if (!(abiItem && "name" in abiItem))
2272
+ throw new AbiEventSignatureNotFoundError(signature, {
2273
+ docsPath: "/docs/contract/decodeEventLog"
2274
+ });
2275
+ const { name, inputs } = abiItem;
2276
+ const isUnnamed = inputs?.some((x) => !("name" in x && x.name));
2277
+ let args = isUnnamed ? [] : {};
2278
+ for (let i = 0; i < inputs.length; i++) {
2279
+ const param = inputs[i];
2280
+ const topic = argTopics[i];
2281
+ if (topic === null)
2282
+ args[param.name || i] = null;
2283
+ if (!topic)
2284
+ continue;
2285
+ if (Array.isArray(topic)) {
2286
+ args[param.name || i] = topic.map((t) => decodeTopic({ param, value: t }));
2287
+ } else {
2288
+ args[param.name || i] = decodeTopic({ param, value: topic });
2289
+ }
2290
+ }
2291
+ if (data && data !== "0x") {
2292
+ const params = inputs.filter((x) => !("indexed" in x && x.indexed));
2293
+ const decodedData = decodeAbi({ params, data });
2294
+ if (decodedData) {
2295
+ if (isUnnamed)
2296
+ args = [...args, ...decodedData];
2297
+ else {
2298
+ for (let i = 0; i < params.length; i++) {
2299
+ args[params[i].name] = decodedData[i];
2300
+ }
2301
+ }
2302
+ }
2303
+ }
2304
+ return {
2305
+ eventName: name,
2306
+ args: Object.values(args).length > 0 ? args : void 0
2307
+ };
2308
+ }
2309
+ function decodeTopic({ param, value }) {
2310
+ if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
2311
+ return value;
2312
+ const decodedArg = decodeAbi({ params: [param], data: value }) || [];
2313
+ return decodedArg[0];
2314
+ }
2315
+
2316
+ // src/utils/abi/decodeFunctionData.ts
2317
+ function decodeFunctionData({ abi, data }) {
2318
+ const signature = slice(data, 0, 4);
2319
+ const description = abi.find(
2320
+ (x) => signature === getFunctionSignature(formatAbiItem(x))
2321
+ );
2322
+ if (!description)
2323
+ throw new AbiFunctionSignatureNotFoundError(signature, {
2324
+ docsPath: "/docs/contract/decodeFunctionData"
2325
+ });
2326
+ return {
2327
+ functionName: description.name,
2328
+ args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: description.inputs }) : void 0
2329
+ };
2330
+ }
2331
+
2332
+ // src/utils/abi/getAbiItem.ts
2333
+ function getAbiItem({ abi, args = [], name }) {
2334
+ const abiItems = abi.filter((x) => "name" in x && x.name === name);
2335
+ if (abiItems.length === 0)
2336
+ return void 0;
2337
+ if (abiItems.length === 1)
2338
+ return abiItems[0];
2339
+ for (const abiItem of abiItems) {
2340
+ if (!("inputs" in abiItem))
2341
+ continue;
2342
+ if (!args || args.length === 0) {
2343
+ if (!abiItem.inputs || abiItem.inputs.length === 0)
2344
+ return abiItem;
2345
+ continue;
2346
+ }
2347
+ if (!abiItem.inputs)
2348
+ continue;
2349
+ if (abiItem.inputs.length === 0)
2350
+ continue;
2351
+ const matched = args.every((arg, index) => {
2352
+ const abiParameter = "inputs" in abiItem && abiItem.inputs[index];
2353
+ if (!abiParameter)
2354
+ return false;
2355
+ return isArgOfType(arg, abiParameter);
2356
+ });
2357
+ if (matched)
2358
+ return abiItem;
2359
+ }
2360
+ return abiItems[0];
2361
+ }
2362
+ function isArgOfType(arg, abiParameter) {
2363
+ const argType = typeof arg;
2364
+ const abiParameterType = abiParameter.type;
2365
+ switch (abiParameterType) {
2366
+ case "address":
2367
+ return isAddress(arg);
2368
+ case "bool":
2369
+ return argType === "boolean";
2370
+ case "function":
2371
+ return argType === "string";
2372
+ case "string":
2373
+ return argType === "string";
2374
+ default: {
2375
+ if (abiParameterType === "tuple" && "components" in abiParameter)
2376
+ return Object.values(abiParameter.components).every(
2377
+ (component, index) => {
2378
+ return isArgOfType(
2379
+ Object.values(arg)[index],
2380
+ component
2381
+ );
2382
+ }
2383
+ );
2384
+ if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(
2385
+ abiParameterType
2386
+ ))
2387
+ return argType === "number" || argType === "bigint";
2388
+ if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
2389
+ return argType === "string" || arg instanceof Uint8Array;
2390
+ if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
2391
+ return Array.isArray(arg) && arg.every(
2392
+ (x) => isArgOfType(x, {
2393
+ ...abiParameter,
2394
+ // Pop off `[]` or `[M]` from end of type
2395
+ type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "")
2396
+ })
2397
+ );
2398
+ }
2399
+ return false;
2400
+ }
2401
+ }
2402
+ }
2403
+
2404
+ // src/utils/abi/decodeFunctionResult.ts
2405
+ var docsPath = "/docs/contract/decodeFunctionResult";
2406
+ function decodeFunctionResult({
2407
+ abi,
2408
+ args,
2409
+ functionName,
2410
+ data
2411
+ }) {
2412
+ const description = getAbiItem({
2413
+ abi,
2414
+ args,
2415
+ name: functionName
2416
+ });
2417
+ if (!description)
2418
+ throw new AbiFunctionNotFoundError(functionName, { docsPath });
2419
+ if (!("outputs" in description))
2420
+ throw new AbiFunctionOutputsNotFoundError(functionName, { docsPath });
2421
+ const values = decodeAbi({ data, params: description.outputs });
2422
+ if (values && values.length > 1)
2423
+ return values;
2424
+ if (values && values.length === 1)
2425
+ return values[0];
2426
+ return void 0;
2427
+ }
2428
+
2429
+ // src/utils/abi/encodeDeployData.ts
2430
+ var docsPath2 = "/docs/contract/encodeDeployData";
2431
+ function encodeDeployData({
2432
+ abi,
2433
+ args,
2434
+ bytecode
2435
+ }) {
2436
+ if (!args || args.length === 0)
2437
+ return bytecode;
2438
+ const description = abi.find(
2439
+ (x) => "type" in x && x.type === "constructor"
2440
+ );
2441
+ if (!description)
2442
+ throw new AbiConstructorNotFoundError({ docsPath: docsPath2 });
2443
+ if (!("inputs" in description))
2444
+ throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 });
2445
+ if (!description.inputs || description.inputs.length === 0)
2446
+ throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 });
2447
+ const data = encodeAbi({
2448
+ params: description.inputs,
2449
+ values: args
2450
+ });
2451
+ return concatHex([bytecode, data]);
2452
+ }
2453
+
2454
+ // src/utils/abi/encodeErrorResult.ts
2455
+ var docsPath3 = "/docs/contract/encodeErrorResult";
2456
+ function encodeErrorResult({ abi, errorName, args }) {
2457
+ const description = getAbiItem({
2458
+ abi,
2459
+ args,
2460
+ name: errorName
2461
+ });
2462
+ if (!description)
2463
+ throw new AbiErrorNotFoundError(errorName, { docsPath: docsPath3 });
2464
+ const definition = formatAbiItem(description);
2465
+ const signature = getFunctionSignature(definition);
2466
+ let data = "0x";
2467
+ if (args && args.length > 0) {
2468
+ if (!("inputs" in description && description.inputs))
2469
+ throw new AbiErrorInputsNotFoundError(errorName, { docsPath: docsPath3 });
2470
+ data = encodeAbi({ params: description.inputs, values: args });
2471
+ }
2472
+ return concatHex([signature, data]);
2473
+ }
2474
+
2475
+ // src/utils/abi/encodeEventTopics.ts
2476
+ function encodeEventTopics({ abi, eventName, args }) {
2477
+ const abiItem = getAbiItem({ abi, args, name: eventName });
2478
+ if (!abiItem)
2479
+ throw new AbiEventNotFoundError(eventName, {
2480
+ docsPath: "/docs/contract/encodeEventTopics"
2481
+ });
2482
+ const definition = formatAbiItem(abiItem);
2483
+ const signature = getEventSignature(definition);
2484
+ let topics = [];
2485
+ if (args && "inputs" in abiItem) {
2486
+ const args_ = Array.isArray(args) ? args : abiItem.inputs?.map((x) => args[x.name]) ?? [];
2487
+ topics = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed).map(
2488
+ (param, i) => Array.isArray(args_[i]) ? args_[i].map(
2489
+ (_, j) => encodeArg({ param, value: args_[i][j] })
2490
+ ) : args_[i] ? encodeArg({ param, value: args_[i] }) : null
2491
+ ) ?? [];
2492
+ }
2493
+ return [signature, ...topics];
2494
+ }
2495
+ function encodeArg({
2496
+ param,
2497
+ value
2498
+ }) {
2499
+ if (param.type === "string" || param.type === "bytes")
2500
+ return keccak256(toBytes(value));
2501
+ if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
2502
+ throw new FilterTypeNotSupportedError(param.type);
2503
+ return encodeAbi({ params: [param], values: [value] });
2504
+ }
2505
+
2506
+ // src/utils/abi/encodeFunctionData.ts
2507
+ function encodeFunctionData({ abi, args, functionName }) {
2508
+ const description = getAbiItem({
2509
+ abi,
2510
+ args,
2511
+ name: functionName
2512
+ });
2513
+ if (!description)
2514
+ throw new AbiFunctionNotFoundError(functionName, {
2515
+ docsPath: "/docs/contract/encodeFunctionData"
2516
+ });
2517
+ const definition = formatAbiItem(description);
2518
+ const signature = getFunctionSignature(definition);
2519
+ const data = "inputs" in description && description.inputs ? encodeAbi({
2520
+ params: description.inputs,
2521
+ values: args ?? []
2522
+ }) : void 0;
2523
+ return concatHex([signature, data ?? "0x"]);
2524
+ }
2525
+
2526
+ // src/utils/abi/encodeFunctionResult.ts
2527
+ var docsPath4 = "/docs/contract/encodeFunctionResult";
2528
+ function encodeFunctionResult({
2529
+ abi,
2530
+ functionName,
2531
+ result
2532
+ }) {
2533
+ const description = abi.find(
2534
+ (x) => "name" in x && x.name === functionName
2535
+ );
2536
+ if (!description)
2537
+ throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 });
2538
+ if (!("outputs" in description))
2539
+ throw new AbiFunctionOutputsNotFoundError(functionName, { docsPath: docsPath4 });
2540
+ let values = Array.isArray(result) ? result : [result];
2541
+ if (description.outputs.length === 0 && !values[0])
2542
+ values = [];
2543
+ return encodeAbi({ params: description.outputs, values });
2544
+ }
2545
+
2546
+ // src/utils/abi/formatAbiItemWithArgs.ts
2547
+ function formatAbiItemWithArgs({
2548
+ abiItem,
2549
+ args,
2550
+ includeFunctionName = true,
2551
+ includeName = false
2552
+ }) {
2553
+ if (!("name" in abiItem))
2554
+ return;
2555
+ if (!("inputs" in abiItem))
2556
+ return;
2557
+ if (!abiItem.inputs)
2558
+ return;
2559
+ return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map(
2560
+ (input, i) => `${includeName && input.name ? `${input.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`
2561
+ ).join(", ")})`;
2562
+ }
2563
+
2564
+ // src/utils/promise/withCache.ts
2565
+ var promiseCache = /* @__PURE__ */ new Map();
2566
+ var responseCache = /* @__PURE__ */ new Map();
2567
+ function getCache(cacheKey) {
2568
+ const buildCache = (cacheKey2, cache) => ({
2569
+ clear: () => cache.delete(cacheKey2),
2570
+ get: () => cache.get(cacheKey2),
2571
+ set: (data) => cache.set(cacheKey2, data)
2572
+ });
2573
+ const promise = buildCache(cacheKey, promiseCache);
2574
+ const response = buildCache(
2575
+ cacheKey,
2576
+ responseCache
2577
+ );
2578
+ return {
2579
+ clear: () => {
2580
+ promise.clear();
2581
+ response.clear();
2582
+ },
2583
+ promise,
2584
+ response
2585
+ };
2586
+ }
2587
+ async function withCache(fn, { cacheKey, maxAge = Infinity }) {
2588
+ const cache = getCache(cacheKey);
2589
+ const response = cache.response.get();
2590
+ if (response && maxAge > 0) {
2591
+ const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime();
2592
+ if (age < maxAge)
2593
+ return response.data;
2594
+ }
2595
+ let promise = cache.promise.get();
2596
+ if (!promise) {
2597
+ promise = fn();
2598
+ cache.promise.set(promise);
2599
+ }
2600
+ const data = await promise;
2601
+ cache.promise.clear();
2602
+ cache.response.set({ created: /* @__PURE__ */ new Date(), data });
2603
+ return data;
2604
+ }
2605
+
2606
+ // src/utils/wait.ts
2607
+ async function wait(time) {
2608
+ return new Promise((res) => setTimeout(res, time));
2609
+ }
2610
+
2611
+ // src/utils/promise/withRetry.ts
2612
+ function withRetry(fn, {
2613
+ delay: delay_ = 100,
2614
+ retryCount = 2,
2615
+ shouldRetry = () => true
2616
+ } = {}) {
2617
+ return new Promise((resolve, reject) => {
2618
+ const attemptRetry = async ({ count = 0 } = {}) => {
2619
+ const retry = async ({ error }) => {
2620
+ const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_;
2621
+ if (delay)
2622
+ await wait(delay);
2623
+ attemptRetry({ count: count + 1 });
2624
+ };
2625
+ try {
2626
+ const data = await fn();
2627
+ resolve(data);
2628
+ } catch (err) {
2629
+ if (count < retryCount && await shouldRetry({ count, error: err }))
2630
+ return retry({ error: err });
2631
+ reject(err);
2632
+ }
2633
+ };
2634
+ attemptRetry();
2635
+ });
2636
+ }
2637
+
2638
+ // src/utils/promise/withTimeout.ts
2639
+ function withTimeout(fn, {
2640
+ errorInstance,
2641
+ timeout,
2642
+ signal
2643
+ }) {
2644
+ return new Promise((resolve, reject) => {
2645
+ ;
2646
+ (async () => {
2647
+ let timeoutId;
2648
+ try {
2649
+ const controller = new AbortController();
2650
+ if (timeout > 0) {
2651
+ timeoutId = setTimeout(() => {
2652
+ if (signal) {
2653
+ controller.abort();
2654
+ } else {
2655
+ reject(errorInstance);
2656
+ }
2657
+ }, timeout);
2658
+ }
2659
+ resolve(await fn({ signal: controller?.signal }));
2660
+ } catch (err) {
2661
+ if (err.name === "AbortError")
2662
+ reject(errorInstance);
2663
+ reject(err);
2664
+ } finally {
2665
+ clearTimeout(timeoutId);
2666
+ }
2667
+ })();
2668
+ });
2669
+ }
2670
+
2671
+ // src/utils/buildRequest.ts
2672
+ var isDeterministicError = (error) => {
2673
+ if ("code" in error)
2674
+ return error.code !== -32603 && error.code !== -32005;
2675
+ if (error instanceof HttpRequestError && error.status)
2676
+ return error.status !== 408 && error.status !== 413 && error.status !== 429 && error.status !== 500 && error.status !== 502 && error.status !== 503 && error.status !== 504;
2677
+ return false;
2678
+ };
2679
+ function buildRequest(request, {
2680
+ retryDelay = 150,
2681
+ retryCount = 3
2682
+ } = {}) {
2683
+ return async (args) => withRetry(
2684
+ async () => {
2685
+ try {
2686
+ return await request(args);
2687
+ } catch (err_) {
2688
+ let err = err_;
2689
+ if (err.code === -32700)
2690
+ throw new ParseRpcError(err);
2691
+ if (err.code === -32600)
2692
+ throw new InvalidRequestRpcError(err);
2693
+ if (err.code === -32601)
2694
+ throw new MethodNotFoundRpcError(err);
2695
+ if (err.code === -32602)
2696
+ throw new InvalidParamsRpcError(err);
2697
+ if (err.code === -32603)
2698
+ throw new InternalRpcError(err);
2699
+ if (err.code === -32e3)
2700
+ throw new InvalidInputRpcError(err);
2701
+ if (err.code === -32001)
2702
+ throw new ResourceNotFoundRpcError(err);
2703
+ if (err.code === -32002)
2704
+ throw new ResourceUnavailableRpcError(err);
2705
+ if (err.code === -32003)
2706
+ throw new TransactionRejectedRpcError(err);
2707
+ if (err.code === -32004)
2708
+ throw new MethodNotSupportedRpcError(err);
2709
+ if (err.code === -32005)
2710
+ throw new LimitExceededRpcError(err);
2711
+ if (err.code === -32006)
2712
+ throw new JsonRpcVersionUnsupportedError(err);
2713
+ if (err_ instanceof BaseError)
2714
+ throw err_;
2715
+ throw new UnknownRpcError(err);
2716
+ }
2717
+ },
2718
+ {
2719
+ delay: ({ count, error }) => {
2720
+ if (error && error instanceof HttpRequestError) {
2721
+ const retryAfter = error?.headers?.get("Retry-After");
2722
+ if (retryAfter?.match(/\d/))
2723
+ return parseInt(retryAfter) * 1e3;
2724
+ }
2725
+ return ~~(1 << count) * retryDelay;
2726
+ },
2727
+ retryCount,
2728
+ shouldRetry: ({ error }) => !isDeterministicError(error)
2729
+ }
2730
+ );
2731
+ }
2732
+
2733
+ // src/utils/chain.ts
2734
+ function defineChain(chain) {
2735
+ return chain;
2736
+ }
2737
+
2738
+ // src/utils/formatters/format.ts
2739
+ function format3(data, { formatter }) {
2740
+ return formatter(data);
2741
+ }
2742
+ function defineFormatter({
2743
+ format: format4
2744
+ }) {
2745
+ return ({
2746
+ exclude,
2747
+ format: formatOverride
2748
+ }) => (data) => {
2749
+ const formatted = format4(data);
2750
+ if (exclude) {
2751
+ for (const key of exclude) {
2752
+ delete formatted[key];
2753
+ }
2754
+ }
2755
+ return {
2756
+ ...formatted,
2757
+ ...formatOverride?.(data)
2758
+ };
2759
+ };
2760
+ }
2761
+
2762
+ // src/utils/formatters/transaction.ts
2763
+ var transactionType = {
2764
+ "0x0": "legacy",
2765
+ "0x1": "eip2930",
2766
+ "0x2": "eip1559"
2767
+ };
2768
+ function formatTransaction(transaction) {
2769
+ const transaction_ = {
2770
+ ...transaction,
2771
+ blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
2772
+ gas: transaction.gas ? BigInt(transaction.gas) : void 0,
2773
+ gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
2774
+ maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
2775
+ maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
2776
+ nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
2777
+ transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
2778
+ type: transaction.type ? transactionType[transaction.type] : void 0,
2779
+ value: transaction.value ? BigInt(transaction.value) : void 0,
2780
+ v: transaction.v ? BigInt(transaction.v) : void 0
2781
+ };
2782
+ if (transaction_.type === "legacy") {
2783
+ delete transaction_["accessList"];
2784
+ delete transaction_["maxFeePerGas"];
2785
+ delete transaction_["maxPriorityFeePerGas"];
2786
+ }
2787
+ if (transaction_.type === "eip2930") {
2788
+ delete transaction_["maxFeePerGas"];
2789
+ delete transaction_["maxPriorityFeePerGas"];
2790
+ }
2791
+ return transaction_;
2792
+ }
2793
+ var defineTransaction = defineFormatter({ format: formatTransaction });
2794
+
2795
+ // src/utils/formatters/block.ts
2796
+ function formatBlock(block) {
2797
+ const transactions = block.transactions?.map((transaction) => {
2798
+ if (typeof transaction === "string")
2799
+ return transaction;
2800
+ return formatTransaction(transaction);
2801
+ });
2802
+ return {
2803
+ ...block,
2804
+ baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
2805
+ difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
2806
+ gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
2807
+ gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
2808
+ number: block.number ? BigInt(block.number) : null,
2809
+ size: block.size ? BigInt(block.size) : void 0,
2810
+ timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
2811
+ transactions,
2812
+ totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
2813
+ };
2814
+ }
2815
+ var defineBlock = defineFormatter({ format: formatBlock });
2816
+
2817
+ // src/utils/formatters/extract.ts
2818
+ function extract(value, { formatter }) {
2819
+ if (!formatter)
2820
+ return {};
2821
+ const keys = Object.keys(formatter({}));
2822
+ return keys.reduce((data, key) => {
2823
+ if (value?.hasOwnProperty(key)) {
2824
+ ;
2825
+ data[key] = value[key];
2826
+ }
2827
+ return data;
2828
+ }, {});
2829
+ }
2830
+
2831
+ // src/utils/formatters/feeHistory.ts
2832
+ function formatFeeHistory(feeHistory) {
2833
+ return {
2834
+ baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),
2835
+ gasUsedRatio: feeHistory.gasUsedRatio,
2836
+ oldestBlock: BigInt(feeHistory.oldestBlock),
2837
+ reward: feeHistory.reward?.map(
2838
+ (reward) => reward.map((value) => BigInt(value))
2839
+ )
2840
+ };
2841
+ }
2842
+
2843
+ // src/utils/formatters/log.ts
2844
+ function formatLog(log, { args, eventName } = {}) {
2845
+ return {
2846
+ ...log,
2847
+ blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
2848
+ logIndex: log.logIndex ? BigInt(log.logIndex) : null,
2849
+ transactionIndex: log.transactionIndex ? BigInt(log.transactionIndex) : null,
2850
+ ...eventName ? { args, eventName } : {}
2851
+ };
2852
+ }
2853
+
2854
+ // src/utils/formatters/transactionReceipt.ts
2855
+ var statuses = {
2856
+ "0x0": "reverted",
2857
+ "0x1": "success"
2858
+ };
2859
+ function formatTransactionReceipt(transactionReceipt) {
2860
+ return {
2861
+ ...transactionReceipt,
2862
+ blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null,
2863
+ cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
2864
+ effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
2865
+ gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
2866
+ logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null,
2867
+ transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
2868
+ status: transactionReceipt.status ? statuses[transactionReceipt.status] : null,
2869
+ type: transactionReceipt.type ? transactionType[transactionReceipt.type] : null
2870
+ };
2871
+ }
2872
+ var defineTransactionReceipt = defineFormatter({
2873
+ format: formatTransactionReceipt
2874
+ });
2875
+
2876
+ // src/utils/formatters/transactionRequest.ts
2877
+ function formatTransactionRequest(transactionRequest) {
2878
+ return {
2879
+ ...transactionRequest,
2880
+ gas: typeof transactionRequest.gas !== "undefined" ? numberToHex(transactionRequest.gas) : void 0,
2881
+ gasPrice: typeof transactionRequest.gasPrice !== "undefined" ? numberToHex(transactionRequest.gasPrice) : void 0,
2882
+ maxFeePerGas: typeof transactionRequest.maxFeePerGas !== "undefined" ? numberToHex(transactionRequest.maxFeePerGas) : void 0,
2883
+ maxPriorityFeePerGas: typeof transactionRequest.maxPriorityFeePerGas !== "undefined" ? numberToHex(transactionRequest.maxPriorityFeePerGas) : void 0,
2884
+ nonce: typeof transactionRequest.nonce !== "undefined" ? numberToHex(transactionRequest.nonce) : void 0,
2885
+ value: typeof transactionRequest.value !== "undefined" ? numberToHex(transactionRequest.value) : void 0
2886
+ };
2887
+ }
2888
+ var defineTransactionRequest = defineFormatter({
2889
+ format: formatTransactionRequest
2890
+ });
2891
+
2892
+ // src/utils/errors/assertRequest.ts
2893
+ function assertRequest(args) {
2894
+ const { maxFeePerGas, maxPriorityFeePerGas } = args;
2895
+ if (maxFeePerGas && maxFeePerGas > 2n ** 256n - 1n)
2896
+ throw new FeeCapTooHighError({ maxFeePerGas });
2897
+ if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
2898
+ throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
2899
+ }
2900
+
2901
+ // src/utils/errors/getNodeError.ts
2902
+ function containsNodeError(err) {
2903
+ return err instanceof TransactionRejectedRpcError || err instanceof InvalidInputRpcError || err instanceof RpcError && err.code === ExecutionRevertedError.code;
2904
+ }
2905
+ function getNodeError(err, args = {}) {
2906
+ const message = err.details.toLowerCase();
2907
+ if (FeeCapTooHighError.nodeMessage.test(message))
2908
+ return new FeeCapTooHighError({
2909
+ cause: err,
2910
+ maxFeePerGas: args?.maxFeePerGas
2911
+ });
2912
+ else if (FeeCapTooLowError.nodeMessage.test(message))
2913
+ return new FeeCapTooLowError({
2914
+ cause: err,
2915
+ maxFeePerGas: args?.maxFeePerGas
2916
+ });
2917
+ else if (NonceTooHighError.nodeMessage.test(message))
2918
+ return new NonceTooHighError({ cause: err, nonce: args?.nonce });
2919
+ else if (NonceTooLowError.nodeMessage.test(message))
2920
+ return new NonceTooLowError({ cause: err, nonce: args?.nonce });
2921
+ else if (NonceMaxValueError.nodeMessage.test(message))
2922
+ return new NonceMaxValueError({ cause: err, nonce: args?.nonce });
2923
+ else if (InsufficientFundsError.nodeMessage.test(message))
2924
+ return new InsufficientFundsError({ cause: err });
2925
+ else if (IntrinsicGasTooHighError.nodeMessage.test(message))
2926
+ return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas });
2927
+ else if (IntrinsicGasTooLowError.nodeMessage.test(message))
2928
+ return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas });
2929
+ else if (TransactionTypeNotSupportedError.nodeMessage.test(message))
2930
+ return new TransactionTypeNotSupportedError({ cause: err });
2931
+ else if (TipAboveFeeCapError.nodeMessage.test(message))
2932
+ return new TipAboveFeeCapError({
2933
+ cause: err,
2934
+ maxFeePerGas: args?.maxFeePerGas,
2935
+ maxPriorityFeePerGas: args?.maxPriorityFeePerGas
2936
+ });
2937
+ else if (message.match(ExecutionRevertedError.nodeMessage) || "code" in err.cause && err.cause?.code === ExecutionRevertedError.code)
2938
+ return new ExecutionRevertedError({
2939
+ cause: err,
2940
+ message: err.cause.details
2941
+ });
2942
+ return new UnknownNodeError({
2943
+ cause: err.cause.cause
2944
+ });
2945
+ }
2946
+
2947
+ // src/utils/errors/getCallError.ts
2948
+ function getCallError(err, {
2949
+ docsPath: docsPath5,
2950
+ ...args
2951
+ }) {
2952
+ let cause = err;
2953
+ if (containsNodeError(err))
2954
+ cause = getNodeError(err, args);
2955
+ return new CallExecutionError(cause, {
2956
+ docsPath: docsPath5,
2957
+ ...args
2958
+ });
2959
+ }
2960
+
2961
+ // src/utils/errors/getContractError.ts
2962
+ var EXECUTION_REVERTED_ERROR_CODE = 3;
2963
+ function getContractError(err, {
2964
+ abi,
2965
+ address,
2966
+ args,
2967
+ docsPath: docsPath5,
2968
+ functionName,
2969
+ sender
2970
+ }) {
2971
+ const { code, data, message } = err instanceof RawContractError ? err : err instanceof CallExecutionError || err instanceof EstimateGasExecutionError ? err.cause?.cause?.cause || {} : err.cause || {};
2972
+ let cause = err;
2973
+ if (err instanceof AbiDecodingZeroDataError) {
2974
+ cause = new ContractFunctionZeroDataError({ functionName });
2975
+ } else if (code === EXECUTION_REVERTED_ERROR_CODE && (data || message)) {
2976
+ cause = new ContractFunctionRevertedError({
2977
+ abi,
2978
+ data,
2979
+ functionName,
2980
+ message
2981
+ });
2982
+ }
2983
+ return new ContractFunctionExecutionError(cause, {
2984
+ abi,
2985
+ args,
2986
+ contractAddress: address,
2987
+ docsPath: docsPath5,
2988
+ functionName,
2989
+ sender
2990
+ });
2991
+ }
2992
+
2993
+ // src/utils/errors/getEstimateGasError.ts
2994
+ function getEstimateGasError(err, {
2995
+ docsPath: docsPath5,
2996
+ ...args
2997
+ }) {
2998
+ let cause = err;
2999
+ if (containsNodeError(err))
3000
+ cause = getNodeError(err, args);
3001
+ return new EstimateGasExecutionError(cause, {
3002
+ docsPath: docsPath5,
3003
+ ...args
3004
+ });
3005
+ }
3006
+
3007
+ // src/utils/errors/getTransactionError.ts
3008
+ function getTransactionError(err, {
3009
+ docsPath: docsPath5,
3010
+ ...args
3011
+ }) {
3012
+ let cause = err;
3013
+ if (containsNodeError(err))
3014
+ cause = getNodeError(err, args);
3015
+ return new TransactionExecutionError(cause, {
3016
+ docsPath: docsPath5,
3017
+ ...args
3018
+ });
3019
+ }
3020
+
3021
+ // src/utils/rpc.ts
3022
+ import WebSocket from "isomorphic-ws";
3023
+
3024
+ // src/utils/stringify.ts
3025
+ function stringify(value) {
3026
+ return JSON.stringify(
3027
+ value,
3028
+ (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2
3029
+ );
3030
+ }
3031
+
3032
+ // src/utils/rpc.ts
3033
+ var id = 0;
3034
+ async function http(url, {
3035
+ body,
3036
+ timeout = 1e4
3037
+ }) {
3038
+ try {
3039
+ const response = await withTimeout(
3040
+ async ({ signal }) => {
3041
+ const response2 = await fetch(url, {
3042
+ headers: {
3043
+ "Content-Type": "application/json"
3044
+ },
3045
+ method: "POST",
3046
+ body: stringify({ jsonrpc: "2.0", id: id++, ...body }),
3047
+ signal: timeout > 0 ? signal : void 0
3048
+ });
3049
+ return response2;
3050
+ },
3051
+ {
3052
+ errorInstance: new TimeoutError({ body, url }),
3053
+ timeout,
3054
+ signal: true
3055
+ }
3056
+ );
3057
+ let data;
3058
+ if (response.headers.get("Content-Type")?.startsWith("application/json")) {
3059
+ data = await response.json();
3060
+ } else {
3061
+ data = await response.text();
3062
+ }
3063
+ if (!response.ok) {
3064
+ throw new HttpRequestError({
3065
+ body,
3066
+ details: stringify(data.error) || response.statusText,
3067
+ headers: response.headers,
3068
+ status: response.status,
3069
+ url
3070
+ });
3071
+ }
3072
+ if (data.error) {
3073
+ throw new RpcError({ body, error: data.error, url });
3074
+ }
3075
+ return data;
3076
+ } catch (err) {
3077
+ if (err instanceof HttpRequestError)
3078
+ throw err;
3079
+ if (err instanceof RpcError)
3080
+ throw err;
3081
+ if (err instanceof TimeoutError)
3082
+ throw err;
3083
+ throw new HttpRequestError({
3084
+ body,
3085
+ details: err.message,
3086
+ url
3087
+ });
3088
+ }
3089
+ }
3090
+ var sockets = /* @__PURE__ */ new Map();
3091
+ async function getSocket(url_) {
3092
+ const url = new URL(url_);
3093
+ const urlKey = url.toString();
3094
+ let socket = sockets.get(urlKey);
3095
+ if (socket)
3096
+ return socket;
3097
+ const webSocket2 = new WebSocket(url);
3098
+ const requests = /* @__PURE__ */ new Map();
3099
+ const subscriptions = /* @__PURE__ */ new Map();
3100
+ const onMessage = ({ data }) => {
3101
+ const message = JSON.parse(data);
3102
+ const isSubscription = message.method === "eth_subscription";
3103
+ const id2 = isSubscription ? message.params.subscription : message.id;
3104
+ const cache = isSubscription ? subscriptions : requests;
3105
+ const callback = cache.get(id2);
3106
+ if (callback)
3107
+ callback({ data });
3108
+ if (!isSubscription)
3109
+ cache.delete(id2);
3110
+ };
3111
+ const onClose = () => {
3112
+ sockets.delete(urlKey);
3113
+ webSocket2.removeEventListener("close", onClose);
3114
+ webSocket2.removeEventListener("message", onMessage);
3115
+ };
3116
+ webSocket2.addEventListener("close", onClose);
3117
+ webSocket2.addEventListener("message", onMessage);
3118
+ if (webSocket2.readyState === WebSocket.CONNECTING) {
3119
+ await new Promise((resolve, reject) => {
3120
+ if (!webSocket2)
3121
+ return;
3122
+ webSocket2.onopen = resolve;
3123
+ webSocket2.onerror = reject;
3124
+ });
3125
+ }
3126
+ socket = Object.assign(webSocket2, {
3127
+ requests,
3128
+ subscriptions
3129
+ });
3130
+ sockets.set(urlKey, socket);
3131
+ return socket;
3132
+ }
3133
+ function webSocket(socket, {
3134
+ body,
3135
+ onData,
3136
+ onError
3137
+ }) {
3138
+ if (socket.readyState === socket.CLOSED || socket.readyState === socket.CLOSING)
3139
+ throw new WebSocketRequestError({
3140
+ body,
3141
+ url: socket.url,
3142
+ details: "Socket is closed."
3143
+ });
3144
+ const id_ = id++;
3145
+ const callback = ({ data }) => {
3146
+ const message = JSON.parse(data);
3147
+ if (typeof message.id === "number" && id_ !== message.id)
3148
+ return;
3149
+ if (message.error) {
3150
+ onError?.(new RpcError({ body, error: message.error, url: socket.url }));
3151
+ } else {
3152
+ onData?.(message);
3153
+ }
3154
+ if (body.method === "eth_subscribe" && typeof message.result === "string") {
3155
+ socket.subscriptions.set(message.result, callback);
3156
+ }
3157
+ if (body.method === "eth_unsubscribe") {
3158
+ socket.subscriptions.delete(body.params?.[0]);
3159
+ }
3160
+ };
3161
+ socket.requests.set(id_, callback);
3162
+ socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
3163
+ return socket;
3164
+ }
3165
+ async function webSocketAsync(socket, {
3166
+ body,
3167
+ timeout = 1e4
3168
+ }) {
3169
+ return withTimeout(
3170
+ () => new Promise(
3171
+ (onData, onError) => rpc.webSocket(socket, {
3172
+ body,
3173
+ onData,
3174
+ onError
3175
+ })
3176
+ ),
3177
+ {
3178
+ errorInstance: new TimeoutError({ body, url: socket.url }),
3179
+ timeout
3180
+ }
3181
+ );
3182
+ }
3183
+ var rpc = {
3184
+ http,
3185
+ webSocket,
3186
+ webSocketAsync
3187
+ };
3188
+
3189
+ // src/utils/unit/constants.ts
3190
+ var etherUnits = {
3191
+ gwei: 9,
3192
+ wei: 18
3193
+ };
3194
+ var gweiUnits = {
3195
+ ether: -9,
3196
+ wei: 9
3197
+ };
3198
+ var weiUnits = {
3199
+ ether: -18,
3200
+ gwei: -9
3201
+ };
3202
+
3203
+ // src/utils/unit/formatUnit.ts
3204
+ function formatUnit(value, decimals) {
3205
+ let display = value.toString();
3206
+ const negative = display.startsWith("-");
3207
+ if (negative)
3208
+ display = display.slice(1);
3209
+ let [integer, fraction] = [
3210
+ display.slice(0, display.length - decimals),
3211
+ display.slice(display.length - decimals)
3212
+ ];
3213
+ fraction = fraction.padStart(decimals, "0");
3214
+ fraction = fraction.replace(/(0+)$/, "");
3215
+ return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
3216
+ }
3217
+
3218
+ // src/utils/unit/formatEther.ts
3219
+ function formatEther(wei, unit = "wei") {
3220
+ return formatUnit(wei, etherUnits[unit]);
3221
+ }
3222
+
3223
+ // src/utils/unit/formatGwei.ts
3224
+ function formatGwei(wei, unit = "wei") {
3225
+ return formatUnit(wei, gweiUnits[unit]);
3226
+ }
3227
+
3228
+ // src/utils/unit/parseUnit.ts
3229
+ function parseUnit(value, decimals) {
3230
+ let [integer, fraction = "0"] = value.split(".");
3231
+ const negative = integer.startsWith("-");
3232
+ if (negative)
3233
+ integer = integer.slice(1);
3234
+ fraction = fraction.replace(/(0+)$/, "");
3235
+ if (decimals === 0) {
3236
+ integer = `${Math.round(Number(`${integer}.${fraction}`))}`;
3237
+ fraction = "";
3238
+ } else if (fraction.length > decimals) {
3239
+ const [before, after] = [
3240
+ fraction.slice(0, decimals),
3241
+ fraction.slice(decimals)
3242
+ ];
3243
+ fraction = `${/^0+$/.test(before) ? before.slice(0, before.length - 1) : ""}${Math.round(Number(`${before}.${after}`))}`;
3244
+ } else {
3245
+ fraction = fraction.padEnd(decimals, "0");
3246
+ }
3247
+ return BigInt(`${negative ? "-" : ""}${integer}${fraction}`);
3248
+ }
3249
+
3250
+ // src/utils/unit/parseEther.ts
3251
+ function parseEther(ether, unit = "wei") {
3252
+ return parseUnit(ether, etherUnits[unit]);
3253
+ }
3254
+
3255
+ // src/utils/unit/parseGwei.ts
3256
+ function parseGwei(ether, unit = "wei") {
3257
+ return parseUnit(ether, gweiUnits[unit]);
3258
+ }
3259
+
3260
+ export {
3261
+ BaseError,
3262
+ AbiConstructorNotFoundError,
3263
+ AbiConstructorParamsNotFoundError,
3264
+ AbiDecodingDataSizeInvalidError,
3265
+ AbiDecodingZeroDataError,
3266
+ AbiEncodingArrayLengthMismatchError,
3267
+ AbiEncodingLengthMismatchError,
3268
+ AbiErrorInputsNotFoundError,
3269
+ AbiErrorNotFoundError,
3270
+ AbiErrorSignatureNotFoundError,
3271
+ AbiEventSignatureNotFoundError,
3272
+ AbiEventNotFoundError,
3273
+ AbiFunctionNotFoundError,
3274
+ AbiFunctionOutputsNotFoundError,
3275
+ AbiFunctionSignatureNotFoundError,
3276
+ InvalidAbiEncodingTypeError,
3277
+ InvalidAbiDecodingTypeError,
3278
+ InvalidArrayError,
3279
+ InvalidDefinitionTypeError,
3280
+ InvalidAddressError,
3281
+ BlockNotFoundError,
3282
+ ChainDoesNotSupportContract,
3283
+ multicall3Abi,
3284
+ panicReasons,
3285
+ TransactionExecutionError,
3286
+ TransactionNotFoundError,
3287
+ TransactionReceiptNotFoundError,
3288
+ WaitForTransactionReceiptTimeoutError,
3289
+ CallExecutionError,
3290
+ ContractFunctionExecutionError,
3291
+ ContractFunctionRevertedError,
3292
+ ContractFunctionZeroDataError,
3293
+ RawContractError,
3294
+ SizeExceedsPaddingSizeError,
3295
+ DataLengthTooLongError,
3296
+ DataLengthTooShortError,
3297
+ InvalidBytesBooleanError,
3298
+ InvalidHexBooleanError,
3299
+ InvalidHexValueError,
3300
+ OffsetOutOfBoundsError,
3301
+ EstimateGasExecutionError,
3302
+ FilterTypeNotSupportedError,
3303
+ ExecutionRevertedError,
3304
+ FeeCapTooHighError,
3305
+ FeeCapTooLowError,
3306
+ NonceTooHighError,
3307
+ NonceTooLowError,
3308
+ NonceMaxValueError,
3309
+ InsufficientFundsError,
3310
+ IntrinsicGasTooHighError,
3311
+ IntrinsicGasTooLowError,
3312
+ TransactionTypeNotSupportedError,
3313
+ TipAboveFeeCapError,
3314
+ UnknownNodeError,
3315
+ RequestError,
3316
+ RpcRequestError,
3317
+ ParseRpcError,
3318
+ InvalidRequestRpcError,
3319
+ MethodNotFoundRpcError,
3320
+ InvalidParamsRpcError,
3321
+ InternalRpcError,
3322
+ InvalidInputRpcError,
3323
+ ResourceNotFoundRpcError,
3324
+ ResourceUnavailableRpcError,
3325
+ TransactionRejectedRpcError,
3326
+ MethodNotSupportedRpcError,
3327
+ LimitExceededRpcError,
3328
+ JsonRpcVersionUnsupportedError,
3329
+ UnknownRpcError,
3330
+ HttpRequestError,
3331
+ WebSocketRequestError,
3332
+ RpcError,
3333
+ TimeoutError,
3334
+ UrlRequiredError,
3335
+ concat,
3336
+ isBytes,
3337
+ isHex,
3338
+ pad,
3339
+ padHex,
3340
+ padBytes,
3341
+ trim,
3342
+ size,
3343
+ slice,
3344
+ sliceBytes,
3345
+ sliceHex,
3346
+ boolToHex,
3347
+ bytesToHex,
3348
+ toHex,
3349
+ numberToHex,
3350
+ stringToHex,
3351
+ boolToBytes,
3352
+ toBytes,
3353
+ hexToBytes,
3354
+ numberToBytes,
3355
+ stringToBytes,
3356
+ toRlp,
3357
+ fromHex,
3358
+ hexToBigInt,
3359
+ hexToBool,
3360
+ hexToNumber,
3361
+ hexToString,
3362
+ fromBytes,
3363
+ bytesToBigint,
3364
+ bytesToBool,
3365
+ bytesToNumber,
3366
+ bytesToString,
3367
+ fromRlp,
3368
+ extractFunctionParts,
3369
+ extractFunctionName,
3370
+ extractFunctionParams,
3371
+ extractFunctionType,
3372
+ keccak256,
3373
+ getEventSignature,
3374
+ getFunctionSignature,
3375
+ isAddress,
3376
+ checksumAddress,
3377
+ getAddress,
3378
+ getContractAddress2 as getContractAddress,
3379
+ getCreateAddress,
3380
+ getCreate2Address,
3381
+ isAddressEqual,
3382
+ encodeAbi,
3383
+ decodeAbi,
3384
+ formatAbiItem,
3385
+ decodeErrorResult,
3386
+ decodeEventLog,
3387
+ decodeFunctionData,
3388
+ getAbiItem,
3389
+ decodeFunctionResult,
3390
+ encodeDeployData,
3391
+ encodeErrorResult,
3392
+ encodeEventTopics,
3393
+ encodeFunctionData,
3394
+ encodeFunctionResult,
3395
+ formatAbiItemWithArgs,
3396
+ getCache,
3397
+ withCache,
3398
+ wait,
3399
+ isDeterministicError,
3400
+ buildRequest,
3401
+ defineChain,
3402
+ format3 as format,
3403
+ defineFormatter,
3404
+ transactionType,
3405
+ formatTransaction,
3406
+ defineTransaction,
3407
+ formatBlock,
3408
+ defineBlock,
3409
+ extract,
3410
+ formatFeeHistory,
3411
+ formatLog,
3412
+ formatTransactionReceipt,
3413
+ defineTransactionReceipt,
3414
+ formatTransactionRequest,
3415
+ defineTransactionRequest,
3416
+ assertRequest,
3417
+ containsNodeError,
3418
+ getNodeError,
3419
+ getCallError,
3420
+ getContractError,
3421
+ getEstimateGasError,
3422
+ getTransactionError,
3423
+ stringify,
3424
+ getSocket,
3425
+ rpc,
3426
+ etherUnits,
3427
+ gweiUnits,
3428
+ weiUnits,
3429
+ formatUnit,
3430
+ formatEther,
3431
+ formatGwei,
3432
+ parseUnit,
3433
+ parseEther,
3434
+ parseGwei
3435
+ };
3436
+ //# sourceMappingURL=chunk-25AJVKAT.mjs.map