viem 0.0.1-alpha.8 → 0.0.1-cjs.10

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 (39) hide show
  1. package/actions/package.json +1 -1
  2. package/chains/package.json +1 -1
  3. package/clients/package.json +1 -1
  4. package/dist/actions/index.d.ts +5 -4
  5. package/dist/actions/index.js +125 -124
  6. package/dist/actions/index.mjs +125 -0
  7. package/dist/chains.d.ts +2 -2
  8. package/dist/chains.js +75 -76
  9. package/dist/chains.mjs +133 -0
  10. package/dist/chunk-2FDH6XP5.mjs +2616 -0
  11. package/dist/chunk-46ZFLVHC.js +1084 -0
  12. package/dist/chunk-5ZBNF5WM.js +2616 -0
  13. package/dist/{chunk-BIQ5KSX5.js → chunk-CWCWWGBC.mjs} +1 -1
  14. package/dist/{chunk-N6PIT2C5.js → chunk-HLVCJ7RV.mjs} +49 -12
  15. package/dist/chunk-SGTIBKHG.js +258 -0
  16. package/dist/clients/index.d.ts +3 -3
  17. package/dist/clients/index.js +23 -23
  18. package/dist/clients/index.mjs +23 -0
  19. package/dist/{createWalletClient-b5c3c89e.d.ts → createWalletClient-d612fe08.d.ts} +1 -1
  20. package/dist/{eip1193-100454ab.d.ts → eip1193-020a6f13.d.ts} +1 -1
  21. package/dist/index.d.ts +40 -18
  22. package/dist/index.js +374 -374
  23. package/dist/index.mjs +374 -0
  24. package/dist/{parseGwei-14f716fc.d.ts → parseGwei-7c87ff41.d.ts} +40 -118
  25. package/dist/transactionRequest-08d30731.d.ts +132 -0
  26. package/dist/utils/index.d.ts +38 -5
  27. package/dist/utils/index.js +148 -138
  28. package/dist/utils/index.mjs +148 -0
  29. package/dist/{watchAsset-e99e744d.d.ts → watchAsset-bc6373f4.d.ts} +17 -5
  30. package/dist/{webSocket-f4abf66c.d.ts → webSocket-7f88e9e0.d.ts} +1 -1
  31. package/dist/window.d.ts +1 -1
  32. package/dist/window.js +1 -0
  33. package/dist/window.mjs +0 -0
  34. package/package.json +9 -3
  35. package/utils/package.json +1 -1
  36. package/window/package.json +1 -1
  37. package/dist/chunk-4Z43OTO6.js +0 -1349
  38. package/dist/chunk-ALVD6MNU.js +0 -1113
  39. package/dist/transactionRequest-3e463099.d.ts +0 -44
@@ -0,0 +1,2616 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }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 (& JavaScript) Interface for Ethereum",
12
+ version: "0.0.1-alpha.9",
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
+ dev: "DEV=true tsup",
22
+ "dev:docs": "pnpm -r --filter site dev",
23
+ format: "rome format src/ test/ --write",
24
+ lint: "rome check .",
25
+ "lint:fix": "pnpm lint --apply-suggested",
26
+ playground: "pnpm --filter playground-dev dev",
27
+ "playground:benchmark": "pnpm --filter playground-benchmark dev",
28
+ postinstall: "pnpm dev",
29
+ preinstall: "npx only-allow pnpm",
30
+ prepare: "npx simple-git-hooks",
31
+ test: "vitest dev --coverage --no-threads",
32
+ "test:ci": "CI=true vitest --coverage --no-threads",
33
+ "test:ui": "vitest dev --ui --no-threads",
34
+ typecheck: "tsc --noEmit"
35
+ },
36
+ files: [
37
+ "/actions",
38
+ "/chains",
39
+ "/dist",
40
+ "/clients",
41
+ "/types",
42
+ "/utils",
43
+ "/window"
44
+ ],
45
+ exports: {
46
+ ".": {
47
+ types: "./dist/index.d.ts",
48
+ module: "./dist/index.mjs",
49
+ default: "./dist/index.js"
50
+ },
51
+ "./actions": {
52
+ types: "./dist/actions/index.d.ts",
53
+ module: "./dist/actions/index.mjs",
54
+ default: "./dist/actions/index.js"
55
+ },
56
+ "./chains": {
57
+ types: "./dist/chains.d.ts",
58
+ module: "./dist/chains.mjs",
59
+ default: "./dist/chains.js"
60
+ },
61
+ "./clients": {
62
+ types: "./dist/clients/index.d.ts",
63
+ module: "./dist/clients/index.mjs",
64
+ default: "./dist/clients/index.js"
65
+ },
66
+ "./utils": {
67
+ types: "./dist/utils/index.d.ts",
68
+ module: "./dist/utils/index.mjs",
69
+ default: "./dist/utils/index.js"
70
+ },
71
+ "./window": {
72
+ types: "./dist/window.d.ts",
73
+ module: "./dist/window.mjs",
74
+ default: "./dist/window.js"
75
+ },
76
+ "./package.json": "./package.json"
77
+ },
78
+ main: "dist/index.js",
79
+ module: "dist/index.mjs",
80
+ types: "dist/index.d.ts",
81
+ sideEffects: false,
82
+ dependencies: {
83
+ "@noble/hashes": "^1.1.2",
84
+ "@wagmi/chains": "^0.1.0",
85
+ abitype: "^0.2.5"
86
+ },
87
+ devDependencies: {
88
+ "@actions/core": "^1.10.0",
89
+ "@actions/github": "^5.1.1",
90
+ "@changesets/changelog-github": "^0.4.5",
91
+ "@changesets/cli": "^2.23.2",
92
+ "@testing-library/jest-dom": "^5.16.5",
93
+ "@types/dedent": "^0.7.0",
94
+ "@types/fs-extra": "^9.0.13",
95
+ "@types/node": "^17.0.45",
96
+ "@vitest/coverage-c8": "^0.24.3",
97
+ "@vitest/ui": "^0.19.1",
98
+ bundlewatch: "^0.3.3",
99
+ dedent: "^0.7.0",
100
+ esbuild: "^0.16.12",
101
+ "esbuild-register": "^3.4.2",
102
+ "essential-eth": "^0.6.2",
103
+ ethers: "^5.7.2",
104
+ execa: "^6.1.0",
105
+ "fs-extra": "^10.1.0",
106
+ jsdom: "^20.0.0",
107
+ rome: "^11.0.0",
108
+ "simple-git-hooks": "^2.8.1",
109
+ tsup: "^6.5.0",
110
+ typescript: "^4.9.3",
111
+ vite: "^3.0.4",
112
+ vitest: "^0.25.2",
113
+ web3: "^1.8.1"
114
+ },
115
+ license: "MIT",
116
+ repository: "wagmi-dev/viem",
117
+ authors: [
118
+ "awkweb.eth",
119
+ "jxom.eth"
120
+ ],
121
+ keywords: [
122
+ "eth",
123
+ "ethereum",
124
+ "dapps",
125
+ "wallet",
126
+ "web3"
127
+ ],
128
+ "simple-git-hooks": {
129
+ "pre-commit": "pnpm format & pnpm lint:fix"
130
+ },
131
+ pnpm: {
132
+ patchedDependencies: {
133
+ "vitepress@1.0.0-alpha.34": "patches/vitepress@1.0.0-alpha.34.patch"
134
+ }
135
+ }
136
+ };
137
+
138
+ // src/utils/stringify.ts
139
+ function stringify(value) {
140
+ return JSON.stringify(
141
+ value,
142
+ (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2
143
+ );
144
+ }
145
+
146
+ // src/errors/base.ts
147
+ var version = process.env.TEST ? "1.0.2" : package_default.version;
148
+ var BaseError = class extends Error {
149
+ constructor(humanMessage, args = {}) {
150
+ const details = args.cause instanceof BaseError ? args.cause.details : _optionalChain([args, 'access', _2 => _2.cause, 'optionalAccess', _3 => _3.message]) ? args.cause.message : args.details;
151
+ const docsPath5 = args.cause instanceof BaseError ? args.cause.docsPath || args.docsPath : args.docsPath;
152
+ const message = [
153
+ humanMessage,
154
+ ...docsPath5 ? ["", `Docs: https://viem.sh${docsPath5}`] : [],
155
+ "",
156
+ ...details ? [`Details: ${details}`] : [],
157
+ `Version: viem@${version}`,
158
+ ...args.cause && !(args.cause instanceof BaseError) && Object.keys(args.cause).length > 0 ? [`Internal Error: ${stringify(args.cause)}`] : []
159
+ ].join("\n");
160
+ super(message);
161
+ __publicField(this, "humanMessage");
162
+ __publicField(this, "details");
163
+ __publicField(this, "docsPath");
164
+ __publicField(this, "name", "ViemError");
165
+ if (args.cause)
166
+ this.cause = args.cause;
167
+ this.details = details;
168
+ this.docsPath = docsPath5;
169
+ this.humanMessage = humanMessage;
170
+ }
171
+ };
172
+
173
+ // src/errors/abi.ts
174
+ var AbiConstructorNotFoundError = class extends BaseError {
175
+ constructor({ docsPath: docsPath5 }) {
176
+ super(
177
+ [
178
+ "A constructor was not found on the ABI.",
179
+ "Make sure you are using the correct ABI and that the constructor exists on it."
180
+ ].join("\n"),
181
+ {
182
+ docsPath: docsPath5
183
+ }
184
+ );
185
+ __publicField(this, "name", "AbiConstructorNotFoundError");
186
+ }
187
+ };
188
+ var AbiConstructorParamsNotFoundError = class extends BaseError {
189
+ constructor({ docsPath: docsPath5 }) {
190
+ super(
191
+ [
192
+ "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.",
193
+ "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."
194
+ ].join("\n"),
195
+ {
196
+ docsPath: docsPath5
197
+ }
198
+ );
199
+ __publicField(this, "name", "AbiConstructorParamsNotFoundError");
200
+ }
201
+ };
202
+ var AbiDecodingDataSizeInvalidError = class extends BaseError {
203
+ constructor(size2) {
204
+ super(
205
+ [
206
+ `Data size of ${size2} bytes is invalid.`,
207
+ "Size must be in increments of 32 bytes (size % 32 === 0)."
208
+ ].join("\n")
209
+ );
210
+ __publicField(this, "name", "AbiDecodingDataSizeInvalidError");
211
+ }
212
+ };
213
+ var AbiDecodingZeroDataError = class extends BaseError {
214
+ constructor() {
215
+ super('Cannot decode zero data ("0x") with ABI parameters.');
216
+ __publicField(this, "name", "AbiDecodingZeroDataError");
217
+ }
218
+ };
219
+ var AbiEncodingArrayLengthMismatchError = class extends BaseError {
220
+ constructor({
221
+ expectedLength,
222
+ givenLength,
223
+ type
224
+ }) {
225
+ super(
226
+ [
227
+ `ABI encoding array length mismatch for type ${type}.`,
228
+ `Expected length: ${expectedLength}`,
229
+ `Given length: ${givenLength}`
230
+ ].join("\n")
231
+ );
232
+ __publicField(this, "name", "AbiEncodingArrayLengthMismatchError");
233
+ }
234
+ };
235
+ var AbiEncodingLengthMismatchError = class extends BaseError {
236
+ constructor({
237
+ expectedLength,
238
+ givenLength
239
+ }) {
240
+ super(
241
+ [
242
+ "ABI encoding params/values length mismatch.",
243
+ `Expected length (params): ${expectedLength}`,
244
+ `Given length (values): ${givenLength}`
245
+ ].join("\n")
246
+ );
247
+ __publicField(this, "name", "AbiEncodingLengthMismatchError");
248
+ }
249
+ };
250
+ var AbiErrorInputsNotFoundError = class extends BaseError {
251
+ constructor(errorName, { docsPath: docsPath5 }) {
252
+ super(
253
+ [
254
+ `Arguments (\`args\`) were provided to "${errorName}", but "${errorName}" on the ABI does not contain any parameters (\`inputs\`).`,
255
+ "Cannot encode error result without knowing what the parameter types are.",
256
+ "Make sure you are using the correct ABI and that the inputs exist on it."
257
+ ].join("\n"),
258
+ {
259
+ docsPath: docsPath5
260
+ }
261
+ );
262
+ __publicField(this, "name", "AbiErrorInputsNotFoundError");
263
+ }
264
+ };
265
+ var AbiErrorNotFoundError = class extends BaseError {
266
+ constructor(errorName, { docsPath: docsPath5 }) {
267
+ super(
268
+ [
269
+ `Error "${errorName}" not found on ABI.`,
270
+ "Make sure you are using the correct ABI and that the error exists on it."
271
+ ].join("\n"),
272
+ {
273
+ docsPath: docsPath5
274
+ }
275
+ );
276
+ __publicField(this, "name", "AbiErrorNotFoundError");
277
+ }
278
+ };
279
+ var AbiErrorSignatureNotFoundError = class extends BaseError {
280
+ constructor(signature, { docsPath: docsPath5 }) {
281
+ super(
282
+ [
283
+ `Encoded error signature "${signature}" not found on ABI.`,
284
+ "Make sure you are using the correct ABI and that the error exists on it.",
285
+ `You can look up the signature "${signature}" here: https://sig.eth.samczsun.com/.`
286
+ ].join("\n"),
287
+ {
288
+ docsPath: docsPath5
289
+ }
290
+ );
291
+ __publicField(this, "name", "AbiErrorSignatureNotFoundError");
292
+ }
293
+ };
294
+ var AbiEventNotFoundError = class extends BaseError {
295
+ constructor(eventName, { docsPath: docsPath5 }) {
296
+ super(
297
+ [
298
+ `Event "${eventName}" not found on ABI.`,
299
+ "Make sure you are using the correct ABI and that the event exists on it."
300
+ ].join("\n"),
301
+ {
302
+ docsPath: docsPath5
303
+ }
304
+ );
305
+ __publicField(this, "name", "AbiEventNotFoundError");
306
+ }
307
+ };
308
+ var AbiFunctionNotFoundError = class extends BaseError {
309
+ constructor(functionName, { docsPath: docsPath5 }) {
310
+ super(
311
+ [
312
+ `Function "${functionName}" not found on ABI.`,
313
+ "Make sure you are using the correct ABI and that the function exists on it."
314
+ ].join("\n"),
315
+ {
316
+ docsPath: docsPath5
317
+ }
318
+ );
319
+ __publicField(this, "name", "AbiFunctionNotFoundError");
320
+ }
321
+ };
322
+ var AbiFunctionOutputsNotFoundError = class extends BaseError {
323
+ constructor(functionName, { docsPath: docsPath5 }) {
324
+ super(
325
+ [
326
+ `Function "${functionName}" does not contain any \`outputs\` on ABI.`,
327
+ "Cannot decode function result without knowing what the parameter types are.",
328
+ "Make sure you are using the correct ABI and that the function exists on it."
329
+ ].join("\n"),
330
+ {
331
+ docsPath: docsPath5
332
+ }
333
+ );
334
+ __publicField(this, "name", "AbiFunctionOutputsNotFoundError");
335
+ }
336
+ };
337
+ var AbiFunctionSignatureNotFoundError = class extends BaseError {
338
+ constructor(signature, { docsPath: docsPath5 }) {
339
+ super(
340
+ [
341
+ `Encoded function signature "${signature}" not found on ABI.`,
342
+ "Make sure you are using the correct ABI and that the function exists on it.",
343
+ `You can look up the signature "${signature}" here: https://sig.eth.samczsun.com/.`
344
+ ].join("\n"),
345
+ {
346
+ docsPath: docsPath5
347
+ }
348
+ );
349
+ __publicField(this, "name", "AbiFunctionSignatureNotFoundError");
350
+ }
351
+ };
352
+ var InvalidAbiEncodingTypeError = class extends BaseError {
353
+ constructor(type, { docsPath: docsPath5 }) {
354
+ super(
355
+ [
356
+ `Type "${type}" is not a valid encoding type.`,
357
+ "Please provide a valid ABI type."
358
+ ].join("\n"),
359
+ { docsPath: docsPath5 }
360
+ );
361
+ __publicField(this, "name", "InvalidAbiEncodingType");
362
+ }
363
+ };
364
+ var InvalidAbiDecodingTypeError = class extends BaseError {
365
+ constructor(type, { docsPath: docsPath5 }) {
366
+ super(
367
+ [
368
+ `Type "${type}" is not a valid decoding type.`,
369
+ "Please provide a valid ABI type."
370
+ ].join("\n"),
371
+ { docsPath: docsPath5 }
372
+ );
373
+ __publicField(this, "name", "InvalidAbiDecodingType");
374
+ }
375
+ };
376
+ var InvalidArrayError = class extends BaseError {
377
+ constructor(value) {
378
+ super([`Value "${value}" is not a valid array.`].join("\n"));
379
+ __publicField(this, "name", "InvalidArrayError");
380
+ }
381
+ };
382
+ var InvalidDefinitionTypeError = class extends BaseError {
383
+ constructor(type) {
384
+ super(
385
+ [
386
+ `"${type}" is not a valid definition type.`,
387
+ 'Valid types: "function", "event", "error"'
388
+ ].join("\n")
389
+ );
390
+ __publicField(this, "name", "InvalidDefinitionTypeError");
391
+ }
392
+ };
393
+
394
+ // src/errors/address.ts
395
+ var InvalidAddressError = class extends BaseError {
396
+ constructor({ address }) {
397
+ super(`Address "${address}" is invalid.`);
398
+ __publicField(this, "name", "InvalidAddressError");
399
+ }
400
+ };
401
+
402
+ // src/errors/block.ts
403
+ var BlockNotFoundError = class extends BaseError {
404
+ constructor({
405
+ blockHash,
406
+ blockNumber
407
+ }) {
408
+ let identifier = "Block";
409
+ if (blockHash)
410
+ identifier = `Block at hash "${blockHash}"`;
411
+ if (blockNumber)
412
+ identifier = `Block at number "${blockNumber}"`;
413
+ super(`${identifier} could not be found.`);
414
+ __publicField(this, "name", "BlockNotFoundError");
415
+ }
416
+ };
417
+
418
+ // src/errors/contract.ts
419
+ var ContractMethodExecutionError = class extends BaseError {
420
+ constructor(message, {
421
+ abi,
422
+ args,
423
+ cause,
424
+ contractAddress,
425
+ formattedArgs,
426
+ functionName,
427
+ functionWithParams,
428
+ sender
429
+ } = {}) {
430
+ super(
431
+ [
432
+ message,
433
+ " ",
434
+ sender && `Sender: ${sender}`,
435
+ contractAddress && `Contract: ${process.env.TEST ? "0x0000000000000000000000000000000000000000" : contractAddress}`,
436
+ functionWithParams && `Function: ${functionWithParams}`,
437
+ formattedArgs && `Arguments: ${[...Array(_nullishCoalesce(_optionalChain([functionName, 'optionalAccess', _4 => _4.length]), () => ( 0))).keys()].map(() => " ").join("")}${formattedArgs}`
438
+ ].filter(Boolean).join("\n"),
439
+ {
440
+ cause
441
+ }
442
+ );
443
+ __publicField(this, "abi");
444
+ __publicField(this, "args");
445
+ __publicField(this, "contractAddress");
446
+ __publicField(this, "formattedArgs");
447
+ __publicField(this, "functionName");
448
+ __publicField(this, "reason");
449
+ __publicField(this, "sender");
450
+ __publicField(this, "name", "ContractMethodExecutionError");
451
+ if (message)
452
+ this.reason = message;
453
+ this.abi = abi;
454
+ this.args = args;
455
+ this.contractAddress = contractAddress;
456
+ this.functionName = functionName;
457
+ this.sender = sender;
458
+ }
459
+ };
460
+ var ContractMethodZeroDataError = class extends BaseError {
461
+ constructor({
462
+ abi,
463
+ args,
464
+ cause,
465
+ contractAddress,
466
+ functionName,
467
+ functionWithParams
468
+ } = {}) {
469
+ super(
470
+ [
471
+ `The contract method "${functionName}" returned no data ("0x"). This could be due to any of the following:`,
472
+ `- The contract does not have the function "${functionName}",`,
473
+ "- The parameters passed to the contract function may be invalid, or",
474
+ "- The address is not a contract.",
475
+ " ",
476
+ contractAddress && `Contract: ${process.env.TEST ? "0x0000000000000000000000000000000000000000" : contractAddress}`,
477
+ functionWithParams && `Function: ${functionWithParams}`,
478
+ functionWithParams && ` > "0x"`
479
+ ].filter(Boolean).join("\n"),
480
+ {
481
+ cause
482
+ }
483
+ );
484
+ __publicField(this, "abi");
485
+ __publicField(this, "args");
486
+ __publicField(this, "contractAddress");
487
+ __publicField(this, "functionName");
488
+ __publicField(this, "functionWithParams");
489
+ __publicField(this, "name", "ContractMethodZeroDataError");
490
+ this.abi = abi;
491
+ this.args = args;
492
+ this.contractAddress = contractAddress;
493
+ this.functionName = functionName;
494
+ }
495
+ };
496
+
497
+ // src/errors/data.ts
498
+ var SizeExceedsPaddingSizeError = class extends BaseError {
499
+ constructor({
500
+ size: size2,
501
+ targetSize,
502
+ type
503
+ }) {
504
+ super(
505
+ `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`
506
+ );
507
+ __publicField(this, "name", "SizeExceedsPaddingSizeError");
508
+ }
509
+ };
510
+
511
+ // src/errors/encoding.ts
512
+ var DataLengthTooLongError = class extends BaseError {
513
+ constructor({ consumed, length }) {
514
+ super(
515
+ `Consumed bytes (${consumed}) is shorter than data length (${length - 1}).`
516
+ );
517
+ __publicField(this, "name", "DataLengthTooLongError");
518
+ }
519
+ };
520
+ var DataLengthTooShortError = class extends BaseError {
521
+ constructor({ length, dataLength }) {
522
+ super(
523
+ `Data length (${dataLength - 1}) is shorter than prefix length (${length - 1}).`
524
+ );
525
+ __publicField(this, "name", "DataLengthTooShortError");
526
+ }
527
+ };
528
+ var InvalidBytesBooleanError = class extends BaseError {
529
+ constructor(bytes) {
530
+ super(
531
+ `Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`
532
+ );
533
+ __publicField(this, "name", "InvalidBytesBooleanError");
534
+ }
535
+ };
536
+ var InvalidHexBooleanError = class extends BaseError {
537
+ constructor(hex) {
538
+ super(
539
+ `Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`
540
+ );
541
+ __publicField(this, "name", "InvalidHexBooleanError");
542
+ }
543
+ };
544
+ var InvalidHexValueError = class extends BaseError {
545
+ constructor(value) {
546
+ super(
547
+ `Hex value "${value}" is an odd length (${value.length}). It must be an even length.`
548
+ );
549
+ __publicField(this, "name", "InvalidHexValueError");
550
+ }
551
+ };
552
+ var OffsetOutOfBoundsError = class extends BaseError {
553
+ constructor({ nextOffset, offset }) {
554
+ super(
555
+ `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`
556
+ );
557
+ __publicField(this, "name", "OffsetOutOfBoundsError");
558
+ }
559
+ };
560
+
561
+ // src/errors/log.ts
562
+ var FilterTypeNotSupportedError = class extends BaseError {
563
+ constructor(type) {
564
+ super(`Filter type "${type}" is not supported.`);
565
+ __publicField(this, "name", "FilterTypeNotSupportedError");
566
+ }
567
+ };
568
+
569
+ // src/errors/request.ts
570
+ var RequestError = class extends BaseError {
571
+ constructor(err, { docsPath: docsPath5, humanMessage }) {
572
+ super(humanMessage, {
573
+ cause: err,
574
+ docsPath: docsPath5
575
+ });
576
+ this.name = err.name;
577
+ }
578
+ };
579
+ var RpcRequestError = class extends RequestError {
580
+ constructor(err, { docsPath: docsPath5, humanMessage }) {
581
+ super(err, { docsPath: docsPath5, humanMessage });
582
+ __publicField(this, "code");
583
+ this.code = err.code;
584
+ this.name = err.name;
585
+ }
586
+ };
587
+ var ParseRpcError = class extends RpcRequestError {
588
+ constructor(err) {
589
+ super(err, {
590
+ humanMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
591
+ });
592
+ __publicField(this, "name", "ParseRpcError");
593
+ __publicField(this, "code", -32700);
594
+ }
595
+ };
596
+ var InvalidRequestRpcError = class extends RpcRequestError {
597
+ constructor(err) {
598
+ super(err, { humanMessage: "JSON is not a valid request object." });
599
+ __publicField(this, "name", "InvalidRequestRpcError");
600
+ __publicField(this, "code", -32600);
601
+ }
602
+ };
603
+ var MethodNotFoundRpcError = class extends RpcRequestError {
604
+ constructor(err) {
605
+ super(err, {
606
+ humanMessage: "The method does not exist / is not available."
607
+ });
608
+ __publicField(this, "name", "MethodNotFoundRpcError");
609
+ __publicField(this, "code", -32601);
610
+ }
611
+ };
612
+ var InvalidParamsRpcError = class extends RpcRequestError {
613
+ constructor(err) {
614
+ super(err, {
615
+ humanMessage: [
616
+ "Invalid parameters were provided to the RPC method.",
617
+ "Double check you have provided the correct parameters."
618
+ ].join("\n")
619
+ });
620
+ __publicField(this, "name", "InvalidParamsRpcError");
621
+ __publicField(this, "code", -32602);
622
+ }
623
+ };
624
+ var InternalRpcError = class extends RpcRequestError {
625
+ constructor(err) {
626
+ super(err, { humanMessage: "An internal error was received." });
627
+ __publicField(this, "name", "InternalRpcError");
628
+ __publicField(this, "code", -32603);
629
+ }
630
+ };
631
+ var InvalidInputRpcError = class extends RpcRequestError {
632
+ constructor(err) {
633
+ super(err, {
634
+ humanMessage: [
635
+ "Missing or invalid parameters.",
636
+ "Double check you have provided the correct parameters."
637
+ ].join("\n")
638
+ });
639
+ __publicField(this, "name", "InvalidInputRpcError");
640
+ __publicField(this, "code", -32e3);
641
+ }
642
+ };
643
+ var ResourceNotFoundRpcError = class extends RpcRequestError {
644
+ constructor(err) {
645
+ super(err, { humanMessage: "Requested resource not found." });
646
+ __publicField(this, "name", "ResourceNotFoundRpcError");
647
+ __publicField(this, "code", -32001);
648
+ }
649
+ };
650
+ var ResourceUnavailableRpcError = class extends RpcRequestError {
651
+ constructor(err) {
652
+ super(err, { humanMessage: "Requested resource not available." });
653
+ __publicField(this, "name", "ResourceUnavailableRpcError");
654
+ __publicField(this, "code", -32002);
655
+ }
656
+ };
657
+ var TransactionRejectedRpcError = class extends RpcRequestError {
658
+ constructor(err) {
659
+ super(err, { humanMessage: "Transaction creation failed." });
660
+ __publicField(this, "name", "TransactionRejectedRpcError");
661
+ __publicField(this, "code", -32003);
662
+ }
663
+ };
664
+ var MethodNotSupportedRpcError = class extends RpcRequestError {
665
+ constructor(err) {
666
+ super(err, { humanMessage: "Method is not implemented." });
667
+ __publicField(this, "name", "MethodNotSupportedRpcError");
668
+ __publicField(this, "code", -32004);
669
+ }
670
+ };
671
+ var LimitExceededRpcError = class extends RpcRequestError {
672
+ constructor(err) {
673
+ super(err, { humanMessage: "Request exceeds defined limit." });
674
+ __publicField(this, "name", "LimitExceededRpcError");
675
+ __publicField(this, "code", -32005);
676
+ }
677
+ };
678
+ var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
679
+ constructor(err) {
680
+ super(err, {
681
+ humanMessage: "Version of JSON-RPC protocol is not supported."
682
+ });
683
+ __publicField(this, "name", "JsonRpcVersionUnsupportedError");
684
+ __publicField(this, "code", -32006);
685
+ }
686
+ };
687
+ var UnknownRpcError = class extends RequestError {
688
+ constructor(err) {
689
+ super(err, {
690
+ humanMessage: "An unknown RPC error occurred."
691
+ });
692
+ __publicField(this, "name", "UnknownRpcError");
693
+ }
694
+ };
695
+
696
+ // src/errors/rpc.ts
697
+ var HttpRequestError = class extends BaseError {
698
+ constructor({
699
+ body,
700
+ details,
701
+ status,
702
+ url
703
+ }) {
704
+ super(
705
+ [
706
+ "HTTP request failed.",
707
+ "",
708
+ `Status: ${status}`,
709
+ `URL: ${url}`,
710
+ `Request body: ${stringify(body)}`
711
+ ].join("\n"),
712
+ {
713
+ details
714
+ }
715
+ );
716
+ __publicField(this, "name", "HttpRequestError");
717
+ __publicField(this, "status");
718
+ this.status = status;
719
+ }
720
+ };
721
+ var WebSocketRequestError = class extends BaseError {
722
+ constructor({
723
+ body,
724
+ details,
725
+ url
726
+ }) {
727
+ super(
728
+ [
729
+ "WebSocket request failed.",
730
+ "",
731
+ `URL: ${url}`,
732
+ `Request body: ${stringify(body)}`
733
+ ].join("\n"),
734
+ {
735
+ details
736
+ }
737
+ );
738
+ __publicField(this, "name", "WebSocketRequestError");
739
+ }
740
+ };
741
+ var RpcError = class extends BaseError {
742
+ constructor({
743
+ body,
744
+ error,
745
+ url
746
+ }) {
747
+ super(
748
+ [
749
+ "RPC Request failed.",
750
+ "",
751
+ `URL: ${url}`,
752
+ `Request body: ${stringify(body)}`
753
+ ].join("\n"),
754
+ {
755
+ cause: error,
756
+ details: error.message
757
+ }
758
+ );
759
+ __publicField(this, "code");
760
+ __publicField(this, "name", "RpcError");
761
+ this.code = error.code;
762
+ }
763
+ };
764
+ var TimeoutError = class extends BaseError {
765
+ constructor({
766
+ body,
767
+ url
768
+ }) {
769
+ super(
770
+ [
771
+ "The request took too long to respond.",
772
+ "",
773
+ `URL: ${url}`,
774
+ `Request body: ${stringify(body)}`
775
+ ].join("\n"),
776
+ {
777
+ details: "The request timed out."
778
+ }
779
+ );
780
+ __publicField(this, "name", "TimeoutError");
781
+ }
782
+ };
783
+
784
+ // src/errors/transaction.ts
785
+ var InvalidGasArgumentsError = class extends BaseError {
786
+ constructor() {
787
+ super("`maxFeePerGas` cannot be less than `maxPriorityFeePerGas`");
788
+ __publicField(this, "name", "InvalidGasArgumentsError");
789
+ }
790
+ };
791
+ var TransactionNotFoundError = class extends BaseError {
792
+ constructor({
793
+ blockHash,
794
+ blockNumber,
795
+ blockTag,
796
+ hash: hash2,
797
+ index
798
+ }) {
799
+ let identifier = "Transaction";
800
+ if (blockTag && index !== void 0)
801
+ identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
802
+ if (blockHash && index !== void 0)
803
+ identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
804
+ if (blockNumber && index !== void 0)
805
+ identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
806
+ if (hash2)
807
+ identifier = `Transaction with hash "${hash2}"`;
808
+ super(`${identifier} could not be found.`);
809
+ __publicField(this, "name", "TransactionNotFoundError");
810
+ }
811
+ };
812
+ var TransactionReceiptNotFoundError = class extends BaseError {
813
+ constructor({ hash: hash2 }) {
814
+ super(
815
+ `Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`
816
+ );
817
+ __publicField(this, "name", "TransactionReceiptNotFoundError");
818
+ }
819
+ };
820
+ var WaitForTransactionReceiptTimeoutError = class extends BaseError {
821
+ constructor({ hash: hash2 }) {
822
+ super(
823
+ `Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`
824
+ );
825
+ __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
826
+ }
827
+ };
828
+
829
+ // src/errors/transport.ts
830
+ var UrlRequiredError = class extends BaseError {
831
+ constructor() {
832
+ super(
833
+ "No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",
834
+ {
835
+ docsPath: "/docs/clients/intro"
836
+ }
837
+ );
838
+ }
839
+ };
840
+
841
+ // src/utils/data/concat.ts
842
+ function concat(values) {
843
+ if (typeof values[0] === "string")
844
+ return concatHex(values);
845
+ return concatBytes(values);
846
+ }
847
+ function concatBytes(values) {
848
+ let length = 0;
849
+ for (const arr of values) {
850
+ length += arr.length;
851
+ }
852
+ const result = new Uint8Array(length);
853
+ let offset = 0;
854
+ for (const arr of values) {
855
+ result.set(arr, offset);
856
+ offset += arr.length;
857
+ }
858
+ return result;
859
+ }
860
+ function concatHex(values) {
861
+ return `0x${values.reduce(
862
+ (acc, x) => acc + x.replace("0x", ""),
863
+ ""
864
+ )}`;
865
+ }
866
+
867
+ // src/utils/data/isBytes.ts
868
+ function isBytes(value) {
869
+ if (!value)
870
+ return false;
871
+ if (typeof value !== "object")
872
+ return false;
873
+ return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
874
+ }
875
+
876
+ // src/utils/data/isHex.ts
877
+ function isHex(value) {
878
+ if (!value)
879
+ return false;
880
+ if (typeof value !== "string")
881
+ return false;
882
+ return /^0x[0-9a-fA-F]*$/.test(value);
883
+ }
884
+
885
+ // src/utils/data/pad.ts
886
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
887
+ if (typeof hexOrBytes === "string")
888
+ return padHex(hexOrBytes, { dir, size: size2 });
889
+ return padBytes(hexOrBytes, { dir, size: size2 });
890
+ }
891
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
892
+ let hex = hex_.replace("0x", "");
893
+ if (hex.length > size2 * 2)
894
+ throw new SizeExceedsPaddingSizeError({
895
+ size: Math.ceil(hex.length / 2),
896
+ targetSize: size2,
897
+ type: "hex"
898
+ });
899
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](
900
+ size2 * 2,
901
+ "0"
902
+ )}`;
903
+ }
904
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
905
+ if (bytes.length > size2)
906
+ throw new SizeExceedsPaddingSizeError({
907
+ size: bytes.length,
908
+ targetSize: size2,
909
+ type: "bytes"
910
+ });
911
+ const paddedBytes = new Uint8Array(size2);
912
+ for (let i = 0; i < size2; i++) {
913
+ const padEnd = dir === "right";
914
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
915
+ }
916
+ return paddedBytes;
917
+ }
918
+
919
+ // src/utils/data/trim.ts
920
+ function trim(hexOrBytes, { dir = "left" } = {}) {
921
+ let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
922
+ let sliceLength = 0;
923
+ for (let i = 0; i < data.length - 1; i++) {
924
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
925
+ sliceLength++;
926
+ else
927
+ break;
928
+ }
929
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
930
+ if (typeof hexOrBytes === "string") {
931
+ if (data.length === 1 && dir === "right")
932
+ data = `${data}0`;
933
+ return `0x${data}`;
934
+ }
935
+ return data;
936
+ }
937
+
938
+ // src/utils/data/size.ts
939
+ function size(value) {
940
+ if (isHex(value))
941
+ return Math.ceil((value.length - 2) / 2);
942
+ return value.length;
943
+ }
944
+
945
+ // src/utils/data/slice.ts
946
+ function slice(value, start, end) {
947
+ if (isHex(value))
948
+ return sliceHex(value, start, end);
949
+ return sliceBytes(value, start, end);
950
+ }
951
+ function assertStartOffset(value, start) {
952
+ if (typeof start === "number" && start > 0 && start > size(value) - 1)
953
+ throw new Error(
954
+ `Slice starting at offset "${start}" is out-of-bounds (size: ${size(
955
+ value
956
+ )}).`
957
+ );
958
+ }
959
+ function sliceBytes(value, start, end) {
960
+ assertStartOffset(value, start);
961
+ return value.slice(start, end);
962
+ }
963
+ function sliceHex(value_, start, end) {
964
+ assertStartOffset(value_, start);
965
+ const value = value_.replace("0x", "").slice((_nullishCoalesce(start, () => ( 0))) * 2, (_nullishCoalesce(end, () => ( value_.length))) * 2);
966
+ return `0x${value}`;
967
+ }
968
+
969
+ // src/utils/encoding/encodeHex.ts
970
+ var hexes = Array.from(
971
+ { length: 256 },
972
+ (v, i) => i.toString(16).padStart(2, "0")
973
+ );
974
+ function boolToHex(value) {
975
+ return `0x${Number(value)}`;
976
+ }
977
+ function bytesToHex(value) {
978
+ let hex = "";
979
+ for (let i = 0; i < value.length; i++) {
980
+ hex += hexes[value[i]];
981
+ }
982
+ return `0x${hex}`;
983
+ }
984
+ function encodeHex(value) {
985
+ if (typeof value === "number" || typeof value === "bigint")
986
+ return numberToHex(value);
987
+ if (typeof value === "string") {
988
+ return stringToHex(value);
989
+ }
990
+ if (typeof value === "boolean")
991
+ return boolToHex(value);
992
+ return bytesToHex(value);
993
+ }
994
+ function numberToHex(value_, opts = {}) {
995
+ const { signed, size: size2 } = opts;
996
+ let value = BigInt(value_);
997
+ let maxValue;
998
+ if (size2) {
999
+ if (signed)
1000
+ maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
1001
+ else
1002
+ maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
1003
+ } else if (typeof value_ === "number") {
1004
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
1005
+ }
1006
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
1007
+ if (maxValue && value > maxValue || value < minValue) {
1008
+ const suffix = typeof value_ === "bigint" ? "n" : "";
1009
+ throw new Error(
1010
+ `Number "${value_}${suffix}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${maxValue ? `(${minValue}${suffix} to ${maxValue}${suffix})` : `(above ${minValue})`}`
1011
+ );
1012
+ }
1013
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
1014
+ if (size2)
1015
+ return pad(hex, { size: size2 });
1016
+ return hex;
1017
+ }
1018
+ function stringToHex(value) {
1019
+ let hex = "";
1020
+ for (let i = 0; i < value.length; i++) {
1021
+ hex += value.charCodeAt(i).toString(16);
1022
+ }
1023
+ return `0x${hex}`;
1024
+ }
1025
+
1026
+ // src/utils/encoding/encodeBytes.ts
1027
+ var encoder = new TextEncoder();
1028
+ function boolToBytes(value) {
1029
+ const bytes = new Uint8Array(1);
1030
+ bytes[0] = Number(value);
1031
+ return bytes;
1032
+ }
1033
+ function encodeBytes(value) {
1034
+ if (typeof value === "number" || typeof value === "bigint")
1035
+ return numberToBytes(value);
1036
+ if (typeof value === "boolean")
1037
+ return boolToBytes(value);
1038
+ if (value.startsWith("0x"))
1039
+ return hexToBytes(value);
1040
+ return stringToBytes(value);
1041
+ }
1042
+ function hexToBytes(hex_) {
1043
+ let hex = hex_.slice(2);
1044
+ if (hex.length % 2)
1045
+ hex = `0${hex}`;
1046
+ const bytes = new Uint8Array(hex.length / 2);
1047
+ for (let index = 0; index < bytes.length; index++) {
1048
+ const start = index * 2;
1049
+ const hexByte = hex.slice(start, start + 2);
1050
+ const byte = Number.parseInt(hexByte, 16);
1051
+ if (Number.isNaN(byte) || byte < 0)
1052
+ throw new Error("Invalid byte sequence");
1053
+ bytes[index] = byte;
1054
+ }
1055
+ return bytes;
1056
+ }
1057
+ function numberToBytes(value, opts) {
1058
+ const hex = numberToHex(value, opts);
1059
+ return hexToBytes(hex);
1060
+ }
1061
+ function stringToBytes(value) {
1062
+ return encoder.encode(value);
1063
+ }
1064
+
1065
+ // src/utils/encoding/encodeRlp.ts
1066
+ function encodeRlp(hexOrBytes, to_) {
1067
+ const to = to_ || "hex";
1068
+ return format(bytesToRlp(parse(hexOrBytes)), to);
1069
+ }
1070
+ function parse(hexOrBytes) {
1071
+ if (Array.isArray(hexOrBytes))
1072
+ return hexOrBytes.map(parse);
1073
+ return typeof hexOrBytes === "string" ? encodeBytes(hexOrBytes) : hexOrBytes;
1074
+ }
1075
+ function format(bytes, type = "bytes") {
1076
+ return type === "hex" ? bytesToHex(bytes) : bytes;
1077
+ }
1078
+ function bytesToRlp(bytes) {
1079
+ if (Array.isArray(bytes)) {
1080
+ const encoded = concat(bytes.map(bytesToRlp));
1081
+ return new Uint8Array([...encodeLength(encoded.length, 192), ...encoded]);
1082
+ }
1083
+ if (bytes.length === 1 && bytes[0] < 128)
1084
+ return bytes;
1085
+ return new Uint8Array([...encodeLength(bytes.length, 128), ...bytes]);
1086
+ }
1087
+ function encodeLength(length, offset) {
1088
+ if (length < 56)
1089
+ return [offset + length];
1090
+ return [encodeBytes(length).length + offset + 55, ...encodeBytes(length)];
1091
+ }
1092
+
1093
+ // src/utils/encoding/decodeHex.ts
1094
+ function decodeHex(hex, to) {
1095
+ if (to === "number")
1096
+ return hexToNumber(hex);
1097
+ if (to === "bigint")
1098
+ return hexToBigInt(hex);
1099
+ if (to === "string")
1100
+ return hexToString(hex);
1101
+ if (to === "boolean")
1102
+ return hexToBool(hex);
1103
+ return hexToBytes(hex);
1104
+ }
1105
+ function hexToBigInt(hex, opts = {}) {
1106
+ const { signed } = opts;
1107
+ const value = BigInt(hex);
1108
+ if (!signed)
1109
+ return value;
1110
+ const size2 = (hex.length - 2) / 2;
1111
+ const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
1112
+ if (value <= max)
1113
+ return value;
1114
+ return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
1115
+ }
1116
+ function hexToBool(hex) {
1117
+ if (trim(hex) === "0x0")
1118
+ return false;
1119
+ if (trim(hex) === "0x1")
1120
+ return true;
1121
+ throw new InvalidHexBooleanError(hex);
1122
+ }
1123
+ function hexToNumber(hex, opts = {}) {
1124
+ return Number(hexToBigInt(hex, opts));
1125
+ }
1126
+ function hexToString(hex) {
1127
+ const bytes = hexToBytes(hex);
1128
+ return new TextDecoder().decode(bytes);
1129
+ }
1130
+
1131
+ // src/utils/encoding/decodeBytes.ts
1132
+ function decodeBytes(bytes, to) {
1133
+ if (to === "number")
1134
+ return bytesToNumber(bytes);
1135
+ if (to === "bigint")
1136
+ return bytesToBigint(bytes);
1137
+ if (to === "boolean")
1138
+ return bytesToBool(bytes);
1139
+ if (to === "string")
1140
+ return bytesToString(bytes);
1141
+ return bytesToHex(bytes);
1142
+ }
1143
+ function bytesToBigint(bytes) {
1144
+ const hex = bytesToHex(bytes);
1145
+ return hexToBigInt(hex);
1146
+ }
1147
+ function bytesToBool(bytes) {
1148
+ if (bytes.length > 1 || bytes[0] > 1)
1149
+ throw new InvalidBytesBooleanError(bytes);
1150
+ return Boolean(bytes[0]);
1151
+ }
1152
+ function bytesToNumber(bytes) {
1153
+ const hex = bytesToHex(bytes);
1154
+ return hexToNumber(hex);
1155
+ }
1156
+ function bytesToString(bytes) {
1157
+ return new TextDecoder().decode(bytes);
1158
+ }
1159
+
1160
+ // src/utils/encoding/decodeRlp.ts
1161
+ function decodeRlp(value, to) {
1162
+ const bytes = parse2(value);
1163
+ const [data, consumed] = rlpToBytes(bytes);
1164
+ if (consumed < bytes.length)
1165
+ throw new DataLengthTooLongError({
1166
+ consumed,
1167
+ length: bytes.length
1168
+ });
1169
+ return format2(data, to);
1170
+ }
1171
+ function parse2(value) {
1172
+ if (typeof value === "string") {
1173
+ if (value.length > 3 && value.length % 2 !== 0)
1174
+ throw new InvalidHexValueError(value);
1175
+ return hexToBytes(value);
1176
+ }
1177
+ return value;
1178
+ }
1179
+ function format2(bytes, to) {
1180
+ if (Array.isArray(bytes))
1181
+ return bytes.map((b) => format2(b, to));
1182
+ return to === "hex" ? trim(bytesToHex(bytes)) : bytes;
1183
+ }
1184
+ function rlpToBytes(bytes, offset = 0) {
1185
+ if (bytes.length === 0)
1186
+ return [new Uint8Array([]), 0];
1187
+ const prefix = bytes[offset];
1188
+ if (prefix <= 127)
1189
+ return [new Uint8Array([bytes[offset]]), 1];
1190
+ if (prefix <= 183) {
1191
+ const length2 = prefix - 128;
1192
+ const offset_ = offset + 1;
1193
+ if (offset_ + length2 > bytes.length)
1194
+ throw new DataLengthTooShortError({
1195
+ length: offset_ + length2,
1196
+ dataLength: bytes.length
1197
+ });
1198
+ return [bytes.slice(offset_, offset_ + length2), 1 + length2];
1199
+ }
1200
+ if (prefix <= 191) {
1201
+ const lengthOfLength2 = prefix - 183;
1202
+ const offset_ = offset + 1;
1203
+ const length2 = bytesToNumber(bytes.slice(offset_, offset_ + lengthOfLength2));
1204
+ if (offset_ + lengthOfLength2 + length2 > bytes.length)
1205
+ throw new DataLengthTooShortError({
1206
+ length: lengthOfLength2 + length2,
1207
+ dataLength: bytes.length - lengthOfLength2
1208
+ });
1209
+ return [
1210
+ bytes.slice(offset_ + lengthOfLength2, offset_ + lengthOfLength2 + length2),
1211
+ 1 + lengthOfLength2 + length2
1212
+ ];
1213
+ }
1214
+ let lengthOfLength = 0;
1215
+ let length = prefix - 192;
1216
+ if (prefix > 247) {
1217
+ lengthOfLength = prefix - 247;
1218
+ length = bytesToNumber(bytes.slice(offset + 1, offset + 1 + lengthOfLength));
1219
+ }
1220
+ let nextOffset = offset + 1 + lengthOfLength;
1221
+ if (nextOffset > bytes.length)
1222
+ throw new DataLengthTooShortError({
1223
+ length: nextOffset,
1224
+ dataLength: bytes.length
1225
+ });
1226
+ let consumed = 1 + lengthOfLength + length;
1227
+ let result = [];
1228
+ while (nextOffset < offset + consumed) {
1229
+ const decoded = rlpToBytes(bytes, nextOffset);
1230
+ result.push(decoded[0]);
1231
+ nextOffset += decoded[1];
1232
+ if (nextOffset > offset + consumed)
1233
+ throw new OffsetOutOfBoundsError({
1234
+ nextOffset,
1235
+ offset: offset + consumed
1236
+ });
1237
+ }
1238
+ return [result, consumed];
1239
+ }
1240
+
1241
+ // src/utils/contract/extractFunctionParts.ts
1242
+ var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
1243
+ function extractFunctionParts(def) {
1244
+ const parts = def.match(paramsRegex);
1245
+ const type = _optionalChain([parts, 'optionalAccess', _5 => _5[2]]) || void 0;
1246
+ const name = _optionalChain([parts, 'optionalAccess', _6 => _6[3]]);
1247
+ const params = _optionalChain([parts, 'optionalAccess', _7 => _7[5]]) || void 0;
1248
+ return { type, name, params };
1249
+ }
1250
+ function extractFunctionName(def) {
1251
+ return extractFunctionParts(def).name;
1252
+ }
1253
+ function extractFunctionParams(def) {
1254
+ const params = extractFunctionParts(def).params;
1255
+ const splitParams = _optionalChain([params, 'optionalAccess', _8 => _8.split, 'call', _9 => _9(","), 'access', _10 => _10.map, 'call', _11 => _11((x) => x.trim().split(" "))]);
1256
+ return _optionalChain([splitParams, 'optionalAccess', _12 => _12.map, 'call', _13 => _13((param) => ({
1257
+ type: param[0],
1258
+ name: param[1] === "indexed" ? param[2] : param[1],
1259
+ ...param[1] === "indexed" ? { indexed: true } : {}
1260
+ }))]);
1261
+ }
1262
+ function extractFunctionType(def) {
1263
+ return extractFunctionParts(def).type;
1264
+ }
1265
+
1266
+ // src/utils/contract/getContractError.ts
1267
+ function getContractError(err, {
1268
+ abi,
1269
+ address,
1270
+ args,
1271
+ functionName,
1272
+ sender
1273
+ }) {
1274
+ const { code, message } = err.cause || {};
1275
+ const abiItem = getAbiItem({ abi, name: functionName });
1276
+ const formattedArgs = abiItem ? formatAbiItemWithArgs({
1277
+ abiItem,
1278
+ args,
1279
+ includeFunctionName: false,
1280
+ includeName: false
1281
+ }) : void 0;
1282
+ const functionWithParams = abiItem ? formatAbiItemWithParams(abiItem, { includeName: true }) : void 0;
1283
+ if (err instanceof AbiDecodingZeroDataError) {
1284
+ return new ContractMethodZeroDataError({
1285
+ abi,
1286
+ args,
1287
+ cause: err,
1288
+ contractAddress: address,
1289
+ functionName,
1290
+ functionWithParams
1291
+ });
1292
+ }
1293
+ if (code === 3 || _optionalChain([message, 'optionalAccess', _14 => _14.includes, 'call', _15 => _15("execution reverted")])) {
1294
+ const message_ = _optionalChain([message, 'optionalAccess', _16 => _16.replace, 'call', _17 => _17("execution reverted: ", "")]);
1295
+ return new ContractMethodExecutionError(message_, {
1296
+ abi,
1297
+ args,
1298
+ cause: err,
1299
+ contractAddress: address,
1300
+ formattedArgs,
1301
+ functionName,
1302
+ functionWithParams,
1303
+ sender
1304
+ });
1305
+ }
1306
+ return err;
1307
+ }
1308
+
1309
+ // src/utils/hash/keccak256.ts
1310
+ var _sha3 = require('@noble/hashes/sha3');
1311
+ function keccak256(value, to_) {
1312
+ const to = to_ || "hex";
1313
+ const bytes = _sha3.keccak_256.call(void 0, value);
1314
+ if (to === "bytes")
1315
+ return bytes;
1316
+ return encodeHex(bytes);
1317
+ }
1318
+
1319
+ // src/utils/hash/hashFunction.ts
1320
+ var hash = (value) => keccak256(encodeBytes(value));
1321
+ function hashFunction(def) {
1322
+ const name = extractFunctionName(def);
1323
+ const params = extractFunctionParams(def);
1324
+ if (!params || params.length === 0)
1325
+ return hash(def.replace(/ /g, ""));
1326
+ return hash(`${name}(${params.map(({ type }) => type).join(",")})`);
1327
+ }
1328
+
1329
+ // src/utils/hash/getEventSignature.ts
1330
+ var getEventSignature = (event) => hashFunction(event);
1331
+
1332
+ // src/utils/hash/getFunctionSignature.ts
1333
+ var getFunctionSignature = (fn) => slice(hashFunction(fn), 0, 4);
1334
+
1335
+ // src/utils/address/getAddress.ts
1336
+ var addressRegex = /^(0x)?[a-fA-F0-9]{40}$/;
1337
+ function checksumAddress(address_) {
1338
+ const hexAddress = address_.substring(2).toLowerCase();
1339
+ const hash2 = keccak256(stringToBytes(hexAddress), "bytes");
1340
+ let address = hexAddress.split("");
1341
+ for (let i = 0; i < 40; i += 2) {
1342
+ if (_optionalChain([hash2, 'optionalAccess', _18 => _18[i >> 1]]) >> 4 >= 8 && address[i]) {
1343
+ address[i] = address[i].toUpperCase();
1344
+ }
1345
+ if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) {
1346
+ address[i + 1] = address[i + 1].toUpperCase();
1347
+ }
1348
+ }
1349
+ return `0x${address.join("")}`;
1350
+ }
1351
+ function getAddress(address) {
1352
+ if (!addressRegex.test(address))
1353
+ throw new InvalidAddressError({ address });
1354
+ return checksumAddress(address);
1355
+ }
1356
+
1357
+ // src/utils/address/getContractAddress.ts
1358
+ function getContractAddress(opts) {
1359
+ if (opts.opcode === "CREATE2")
1360
+ return getCreate2Address(opts);
1361
+ return getCreateAddress(opts);
1362
+ }
1363
+ function getCreateAddress(opts) {
1364
+ const from = encodeBytes(getAddress(opts.from));
1365
+ let nonce = encodeBytes(opts.nonce);
1366
+ if (nonce[0] === 0)
1367
+ nonce = new Uint8Array([]);
1368
+ return getAddress(
1369
+ `0x${keccak256(encodeRlp([from, nonce], "bytes")).slice(26)}`
1370
+ );
1371
+ }
1372
+ function getCreate2Address(opts) {
1373
+ const from = encodeBytes(getAddress(opts.from));
1374
+ const salt = pad(
1375
+ isBytes(opts.salt) ? opts.salt : encodeBytes(opts.salt),
1376
+ { size: 32 }
1377
+ );
1378
+ const bytecodeHash = encodeBytes(
1379
+ keccak256(
1380
+ isBytes(opts.bytecode) ? opts.bytecode : encodeBytes(opts.bytecode)
1381
+ )
1382
+ );
1383
+ return getAddress(
1384
+ slice(
1385
+ keccak256(concat([encodeBytes("0xff"), from, salt, bytecodeHash])),
1386
+ 12
1387
+ )
1388
+ );
1389
+ }
1390
+
1391
+ // src/utils/address/isAddress.ts
1392
+ function isAddress(address) {
1393
+ try {
1394
+ return Boolean(getAddress(address));
1395
+ } catch (e) {
1396
+ return false;
1397
+ }
1398
+ }
1399
+
1400
+ // src/utils/address/isAddressEqual.ts
1401
+ function isAddressEqual(a, b) {
1402
+ return getAddress(a) === getAddress(b);
1403
+ }
1404
+
1405
+ // src/utils/abi/encodeAbi.ts
1406
+ function encodeAbi({
1407
+ params,
1408
+ values
1409
+ }) {
1410
+ if (params.length !== values.length)
1411
+ throw new AbiEncodingLengthMismatchError({
1412
+ expectedLength: params.length,
1413
+ givenLength: values.length
1414
+ });
1415
+ const preparedParams = prepareParams({ params, values });
1416
+ const data = encodeParams(preparedParams);
1417
+ if (data.length === 0)
1418
+ return "0x";
1419
+ return data;
1420
+ }
1421
+ function prepareParams({
1422
+ params,
1423
+ values
1424
+ }) {
1425
+ let preparedParams = [];
1426
+ for (let i = 0; i < params.length; i++) {
1427
+ preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
1428
+ }
1429
+ return preparedParams;
1430
+ }
1431
+ function prepareParam({
1432
+ param,
1433
+ value
1434
+ }) {
1435
+ const arrayComponents = getArrayComponents(param.type);
1436
+ if (arrayComponents) {
1437
+ const [length, type] = arrayComponents;
1438
+ return encodeArray(value, { length, param: { ...param, type } });
1439
+ }
1440
+ if (param.type === "tuple") {
1441
+ return encodeTuple(value, {
1442
+ param
1443
+ });
1444
+ }
1445
+ if (param.type === "address") {
1446
+ return encodeAddress(value);
1447
+ }
1448
+ if (param.type === "bool") {
1449
+ return encodeBool(value);
1450
+ }
1451
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
1452
+ const signed = param.type.startsWith("int");
1453
+ return encodeNumber(value, { signed });
1454
+ }
1455
+ if (param.type.startsWith("bytes")) {
1456
+ return encodeBytes2(value, { param });
1457
+ }
1458
+ if (param.type === "string") {
1459
+ return encodeString(value);
1460
+ }
1461
+ throw new InvalidAbiEncodingTypeError(param.type, {
1462
+ docsPath: "/docs/contract/encodeAbi"
1463
+ });
1464
+ }
1465
+ function encodeParams(preparedParams) {
1466
+ let staticSize = 0;
1467
+ for (let i = 0; i < preparedParams.length; i++) {
1468
+ const { dynamic, encoded } = preparedParams[i];
1469
+ if (dynamic)
1470
+ staticSize += 32;
1471
+ else
1472
+ staticSize += size(encoded);
1473
+ }
1474
+ let staticParams = [];
1475
+ let dynamicParams = [];
1476
+ let dynamicSize = 0;
1477
+ for (let i = 0; i < preparedParams.length; i++) {
1478
+ const { dynamic, encoded } = preparedParams[i];
1479
+ if (dynamic) {
1480
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
1481
+ dynamicParams.push(encoded);
1482
+ dynamicSize += size(encoded);
1483
+ } else {
1484
+ staticParams.push(encoded);
1485
+ }
1486
+ }
1487
+ return concat([...staticParams, ...dynamicParams]);
1488
+ }
1489
+ function encodeAddress(value) {
1490
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
1491
+ }
1492
+ function encodeArray(value, {
1493
+ length,
1494
+ param
1495
+ }) {
1496
+ let dynamic = length === null;
1497
+ if (!Array.isArray(value))
1498
+ throw new InvalidArrayError(value);
1499
+ if (!dynamic && value.length !== length)
1500
+ throw new AbiEncodingArrayLengthMismatchError({
1501
+ expectedLength: length,
1502
+ givenLength: value.length,
1503
+ type: `${param.type}[${length}]`
1504
+ });
1505
+ let dynamicChild = false;
1506
+ let preparedParams = [];
1507
+ for (let i = 0; i < value.length; i++) {
1508
+ const preparedParam = prepareParam({ param, value: value[i] });
1509
+ if (preparedParam.dynamic)
1510
+ dynamicChild = true;
1511
+ preparedParams.push(preparedParam);
1512
+ }
1513
+ if (dynamic || dynamicChild) {
1514
+ const data = encodeParams(preparedParams);
1515
+ if (dynamic) {
1516
+ const length2 = numberToHex(preparedParams.length, { size: 32 });
1517
+ return {
1518
+ dynamic: true,
1519
+ encoded: preparedParams.length > 0 ? concat([length2, data]) : length2
1520
+ };
1521
+ }
1522
+ if (dynamicChild)
1523
+ return { dynamic: true, encoded: data };
1524
+ }
1525
+ return {
1526
+ dynamic: false,
1527
+ encoded: concat(preparedParams.map(({ encoded }) => encoded))
1528
+ };
1529
+ }
1530
+ function encodeBytes2(value, { param }) {
1531
+ const [_, size_] = param.type.split("bytes");
1532
+ if (!size_)
1533
+ return {
1534
+ dynamic: true,
1535
+ encoded: concat([
1536
+ padHex(numberToHex(size(value), { size: 32 })),
1537
+ padHex(value, { dir: "right" })
1538
+ ])
1539
+ };
1540
+ return { dynamic: false, encoded: padHex(value, { dir: "right" }) };
1541
+ }
1542
+ function encodeBool(value) {
1543
+ return { dynamic: false, encoded: padHex(boolToHex(value)) };
1544
+ }
1545
+ function encodeNumber(value, { signed }) {
1546
+ return {
1547
+ dynamic: false,
1548
+ encoded: numberToHex(value, {
1549
+ size: 32,
1550
+ signed
1551
+ })
1552
+ };
1553
+ }
1554
+ function encodeString(value) {
1555
+ return {
1556
+ dynamic: true,
1557
+ encoded: concat([
1558
+ padHex(numberToHex(value.length, { size: 32 })),
1559
+ padHex(stringToHex(value), { dir: "right" })
1560
+ ])
1561
+ };
1562
+ }
1563
+ function encodeTuple(value, { param }) {
1564
+ let dynamic = false;
1565
+ let preparedParams = [];
1566
+ for (let i = 0; i < param.components.length; i++) {
1567
+ const param_ = param.components[i];
1568
+ const index = Array.isArray(value) ? i : param_.name;
1569
+ const preparedParam = prepareParam({
1570
+ param: param_,
1571
+ value: value[index]
1572
+ });
1573
+ preparedParams.push(preparedParam);
1574
+ dynamic = preparedParam.dynamic;
1575
+ }
1576
+ return {
1577
+ dynamic,
1578
+ encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
1579
+ };
1580
+ }
1581
+ function getArrayComponents(type) {
1582
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
1583
+ return matches ? [matches[2] ? Number(matches[2]) : null, matches[1]] : void 0;
1584
+ }
1585
+
1586
+ // src/utils/abi/decodeAbi.ts
1587
+ function decodeAbi({
1588
+ data,
1589
+ params
1590
+ }) {
1591
+ if (data === "0x" && params.length > 0)
1592
+ throw new AbiDecodingZeroDataError();
1593
+ if (size(data) % 32 !== 0)
1594
+ throw new AbiDecodingDataSizeInvalidError(size(data));
1595
+ const values = decodeParams({
1596
+ data,
1597
+ params
1598
+ });
1599
+ if (values.length === 0)
1600
+ return void 0;
1601
+ return values;
1602
+ }
1603
+ function decodeParams({
1604
+ data,
1605
+ params
1606
+ }) {
1607
+ let decodedValues = [];
1608
+ let position = 0;
1609
+ for (let i = 0; i < params.length; i++) {
1610
+ const param = params[i];
1611
+ const { consumed, value } = decodeParam({ data, param, position });
1612
+ decodedValues.push(value);
1613
+ position += consumed;
1614
+ }
1615
+ return decodedValues;
1616
+ }
1617
+ function decodeParam({
1618
+ data,
1619
+ param,
1620
+ position
1621
+ }) {
1622
+ const arrayComponents = getArrayComponents(param.type);
1623
+ if (arrayComponents) {
1624
+ const [length, type] = arrayComponents;
1625
+ return decodeArray(data, {
1626
+ length,
1627
+ param: { ...param, type },
1628
+ position
1629
+ });
1630
+ }
1631
+ if (param.type === "tuple") {
1632
+ return decodeTuple(data, { param, position });
1633
+ }
1634
+ if (param.type === "string") {
1635
+ return decodeString(data, { position });
1636
+ }
1637
+ if (param.type.startsWith("bytes")) {
1638
+ return decodeBytes2(data, { param, position });
1639
+ }
1640
+ let value = slice(data, position, position + 32);
1641
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
1642
+ return decodeNumber(value, { param });
1643
+ }
1644
+ if (param.type === "address") {
1645
+ return decodeAddress(value);
1646
+ }
1647
+ if (param.type === "bool") {
1648
+ return decodeBool(value);
1649
+ }
1650
+ throw new InvalidAbiDecodingTypeError(param.type, {
1651
+ docsPath: "/docs/contract/decodeAbi"
1652
+ });
1653
+ }
1654
+ function decodeAddress(value) {
1655
+ return { consumed: 32, value: checksumAddress(slice(value, -20)) };
1656
+ }
1657
+ function decodeArray(data, {
1658
+ param,
1659
+ length,
1660
+ position
1661
+ }) {
1662
+ if (!length) {
1663
+ const offset = hexToNumber(slice(data, position, position + 32));
1664
+ const length2 = hexToNumber(slice(data, offset, offset + 32));
1665
+ let consumed2 = 0;
1666
+ let value2 = [];
1667
+ for (let i = 0; i < length2; ++i) {
1668
+ const decodedChild = decodeParam({
1669
+ data: slice(data, offset + 32),
1670
+ param,
1671
+ position: consumed2
1672
+ });
1673
+ consumed2 += decodedChild.consumed;
1674
+ value2.push(decodedChild.value);
1675
+ }
1676
+ return { value: value2, consumed: 32 };
1677
+ }
1678
+ if (hasDynamicChild(param)) {
1679
+ const arrayComponents = getArrayComponents(param.type);
1680
+ const dynamicChild = !_optionalChain([arrayComponents, 'optionalAccess', _19 => _19[0]]);
1681
+ let consumed2 = 0;
1682
+ let value2 = [];
1683
+ for (let i = 0; i < length; ++i) {
1684
+ const offset = hexToNumber(slice(data, position, position + 32));
1685
+ const decodedChild = decodeParam({
1686
+ data: slice(data, offset),
1687
+ param,
1688
+ position: dynamicChild ? consumed2 : i * 32
1689
+ });
1690
+ consumed2 += decodedChild.consumed;
1691
+ value2.push(decodedChild.value);
1692
+ }
1693
+ return { value: value2, consumed: consumed2 };
1694
+ }
1695
+ let consumed = 0;
1696
+ let value = [];
1697
+ for (let i = 0; i < length; ++i) {
1698
+ const decodedChild = decodeParam({
1699
+ data,
1700
+ param,
1701
+ position: position + consumed
1702
+ });
1703
+ consumed += decodedChild.consumed;
1704
+ value.push(decodedChild.value);
1705
+ }
1706
+ return { value, consumed };
1707
+ }
1708
+ function decodeBool(value) {
1709
+ return { consumed: 32, value: hexToBool(value) };
1710
+ }
1711
+ function decodeBytes2(data, { param, position }) {
1712
+ const [_, size2] = param.type.split("bytes");
1713
+ if (!size2) {
1714
+ const offset = hexToNumber(slice(data, position, position + 32));
1715
+ const length = hexToNumber(slice(data, offset, offset + 32));
1716
+ const value2 = slice(data, offset + 32, offset + 32 + length);
1717
+ return { consumed: 32, value: value2 };
1718
+ }
1719
+ const value = slice(data, position, position + parseInt(size2));
1720
+ return { consumed: 32, value };
1721
+ }
1722
+ function decodeNumber(value, { param }) {
1723
+ const signed = param.type.startsWith("int");
1724
+ const size2 = parseInt(param.type.split("int")[1] || "256");
1725
+ return {
1726
+ consumed: 32,
1727
+ value: size2 > 48 ? hexToBigInt(value, { signed }) : hexToNumber(value, { signed })
1728
+ };
1729
+ }
1730
+ function decodeString(data, { position }) {
1731
+ const offset = hexToNumber(slice(data, position, position + 32));
1732
+ const length = hexToNumber(slice(data, offset, offset + 32));
1733
+ const value = hexToString(
1734
+ trim(slice(data, offset + 32, offset + 32 + length))
1735
+ );
1736
+ return { consumed: 32, value };
1737
+ }
1738
+ function decodeTuple(data, { param, position }) {
1739
+ const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name);
1740
+ let value = hasUnnamedChild ? [] : {};
1741
+ let consumed = 0;
1742
+ if (hasDynamicChild(param)) {
1743
+ const offset = hexToNumber(slice(data, position, position + 32));
1744
+ for (let i = 0; i < param.components.length; ++i) {
1745
+ const component = param.components[i];
1746
+ const decodedChild = decodeParam({
1747
+ data: slice(data, offset),
1748
+ param: component,
1749
+ position: consumed
1750
+ });
1751
+ consumed += decodedChild.consumed;
1752
+ value[hasUnnamedChild ? i : _optionalChain([component, 'optionalAccess', _20 => _20.name])] = decodedChild.value;
1753
+ }
1754
+ return { consumed: 32, value };
1755
+ }
1756
+ for (let i = 0; i < param.components.length; ++i) {
1757
+ const component = param.components[i];
1758
+ const decodedChild = decodeParam({
1759
+ data,
1760
+ param: component,
1761
+ position: position + consumed
1762
+ });
1763
+ consumed += decodedChild.consumed;
1764
+ value[hasUnnamedChild ? i : _optionalChain([component, 'optionalAccess', _21 => _21.name])] = decodedChild.value;
1765
+ }
1766
+ return { consumed, value };
1767
+ }
1768
+ function hasDynamicChild(param) {
1769
+ const { type } = param;
1770
+ if (type === "string")
1771
+ return true;
1772
+ if (type === "bytes")
1773
+ return true;
1774
+ if (type.endsWith("[]"))
1775
+ return true;
1776
+ if (type === "tuple")
1777
+ return _optionalChain([param, 'access', _22 => _22.components, 'optionalAccess', _23 => _23.some, 'call', _24 => _24(hasDynamicChild)]);
1778
+ const arrayComponents = getArrayComponents(param.type);
1779
+ if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] }))
1780
+ return true;
1781
+ return false;
1782
+ }
1783
+
1784
+ // src/utils/abi/formatAbiItemWithParams.ts
1785
+ function formatAbiItemWithParams(abiItem, { includeName = false } = {}) {
1786
+ if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error")
1787
+ throw new InvalidDefinitionTypeError(abiItem.type);
1788
+ return `${abiItem.name}(${getParams(abiItem.inputs, { includeName })})`;
1789
+ }
1790
+ function getParams(params, { includeName }) {
1791
+ if (!params)
1792
+ return "";
1793
+ return params.map((param) => getParam(param, { includeName })).join(includeName ? ", " : ",");
1794
+ }
1795
+ function getParam(param, { includeName }) {
1796
+ if (param.type.startsWith("tuple")) {
1797
+ return `(${getParams(
1798
+ param.components,
1799
+ { includeName }
1800
+ )})${param.type.slice("tuple".length)}`;
1801
+ }
1802
+ return param.type + (includeName && param.name ? ` ${param.name}` : "");
1803
+ }
1804
+
1805
+ // src/utils/abi/decodeErrorResult.ts
1806
+ function decodeErrorResult({ abi, data }) {
1807
+ const signature = slice(data, 0, 4);
1808
+ const description = abi.find(
1809
+ (x) => signature === getFunctionSignature(formatAbiItemWithParams(x))
1810
+ );
1811
+ if (!description)
1812
+ throw new AbiErrorSignatureNotFoundError(signature, {
1813
+ docsPath: "/docs/contract/decodeErrorResult"
1814
+ });
1815
+ return {
1816
+ errorName: description.name,
1817
+ args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: description.inputs }) : void 0
1818
+ };
1819
+ }
1820
+
1821
+ // src/utils/abi/decodeFunctionData.ts
1822
+ function decodeFunctionData({ abi, data }) {
1823
+ const signature = slice(data, 0, 4);
1824
+ const description = abi.find(
1825
+ (x) => signature === getFunctionSignature(formatAbiItemWithParams(x))
1826
+ );
1827
+ if (!description)
1828
+ throw new AbiFunctionSignatureNotFoundError(signature, {
1829
+ docsPath: "/docs/contract/decodeFunctionData"
1830
+ });
1831
+ return {
1832
+ functionName: description.name,
1833
+ args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: description.inputs }) : void 0
1834
+ };
1835
+ }
1836
+
1837
+ // src/utils/abi/decodeFunctionResult.ts
1838
+ var docsPath = "/docs/contract/decodeFunctionResult";
1839
+ function decodeFunctionResult({
1840
+ abi,
1841
+ functionName,
1842
+ data
1843
+ }) {
1844
+ const description = abi.find(
1845
+ (x) => "name" in x && x.name === functionName
1846
+ );
1847
+ if (!description)
1848
+ throw new AbiFunctionNotFoundError(functionName, { docsPath });
1849
+ if (!("outputs" in description))
1850
+ throw new AbiFunctionOutputsNotFoundError(functionName, { docsPath });
1851
+ const values = decodeAbi({ data, params: description.outputs });
1852
+ if (values && values.length > 1)
1853
+ return values;
1854
+ if (values && values.length === 1)
1855
+ return values[0];
1856
+ return void 0;
1857
+ }
1858
+
1859
+ // src/utils/abi/encodeDeployData.ts
1860
+ var docsPath2 = "/docs/contract/encodeDeployData";
1861
+ function encodeDeployData({
1862
+ abi,
1863
+ args,
1864
+ bytecode
1865
+ }) {
1866
+ if (!args || args.length === 0)
1867
+ return bytecode;
1868
+ const description = abi.find((x) => "type" in x && x.type === "constructor");
1869
+ if (!description)
1870
+ throw new AbiConstructorNotFoundError({ docsPath: docsPath2 });
1871
+ if (!("inputs" in description))
1872
+ throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 });
1873
+ if (!description.inputs || description.inputs.length === 0)
1874
+ throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 });
1875
+ const data = encodeAbi({
1876
+ params: description.inputs,
1877
+ values: args
1878
+ });
1879
+ return concatHex([bytecode, data]);
1880
+ }
1881
+
1882
+ // src/utils/abi/getAbiItem.ts
1883
+ function getAbiItem({ abi, name }) {
1884
+ return abi.find((x) => "name" in x && x.name === name);
1885
+ }
1886
+
1887
+ // src/utils/abi/encodeErrorResult.ts
1888
+ var docsPath3 = "/docs/contract/encodeErrorResult";
1889
+ function encodeErrorResult({ abi, errorName, args }) {
1890
+ const description = getAbiItem({ abi, name: errorName });
1891
+ if (!description)
1892
+ throw new AbiErrorNotFoundError(errorName, { docsPath: docsPath3 });
1893
+ const definition = formatAbiItemWithParams(description);
1894
+ const signature = getFunctionSignature(definition);
1895
+ let data = "0x";
1896
+ if (args && args.length > 0) {
1897
+ if (!("inputs" in description && description.inputs))
1898
+ throw new AbiErrorInputsNotFoundError(errorName, { docsPath: docsPath3 });
1899
+ data = encodeAbi({ params: description.inputs, values: args });
1900
+ }
1901
+ return concatHex([signature, data]);
1902
+ }
1903
+
1904
+ // src/utils/abi/encodeEventTopics.ts
1905
+ function encodeEventTopics({ abi, eventName, args }) {
1906
+ const abiItem = getAbiItem({ abi, name: eventName });
1907
+ if (!abiItem)
1908
+ throw new AbiEventNotFoundError(eventName, {
1909
+ docsPath: "/docs/contract/encodeEventTopics"
1910
+ });
1911
+ const definition = formatAbiItemWithParams(abiItem);
1912
+ const signature = getEventSignature(definition);
1913
+ let topics = [];
1914
+ if (args && "inputs" in abiItem) {
1915
+ const args_ = Array.isArray(args) ? args : _nullishCoalesce(_optionalChain([abiItem, 'access', _25 => _25.inputs, 'optionalAccess', _26 => _26.map, 'call', _27 => _27((x) => args[x.name])]), () => ( []));
1916
+ topics = _nullishCoalesce(_optionalChain([abiItem, 'access', _28 => _28.inputs, 'optionalAccess', _29 => _29.filter, 'call', _30 => _30((param) => "indexed" in param && param.indexed), 'access', _31 => _31.map, 'call', _32 => _32(
1917
+ (param, i) => Array.isArray(args_[i]) ? args_[i].map(
1918
+ (_, j) => encodeArg({ param, value: args_[i][j] })
1919
+ ) : args_[i] ? encodeArg({ param, value: args_[i] }) : null
1920
+ )]), () => ( []));
1921
+ }
1922
+ return [signature, ...topics];
1923
+ }
1924
+ function encodeArg({
1925
+ param,
1926
+ value
1927
+ }) {
1928
+ if (param.type === "string" || param.type === "bytes")
1929
+ return keccak256(encodeBytes(value));
1930
+ if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
1931
+ throw new FilterTypeNotSupportedError(param.type);
1932
+ return encodeAbi({ params: [param], values: [value] });
1933
+ }
1934
+
1935
+ // src/utils/abi/encodeFunctionData.ts
1936
+ function encodeFunctionData({ abi, args, functionName }) {
1937
+ const description = getAbiItem({ abi, name: functionName });
1938
+ if (!description)
1939
+ throw new AbiFunctionNotFoundError(functionName, {
1940
+ docsPath: "/docs/contract/encodeFunctionData"
1941
+ });
1942
+ const definition = formatAbiItemWithParams(description);
1943
+ const signature = getFunctionSignature(definition);
1944
+ const data = "inputs" in description && description.inputs ? encodeAbi({
1945
+ params: description.inputs,
1946
+ values: _nullishCoalesce(args, () => ( []))
1947
+ }) : void 0;
1948
+ return concatHex([signature, _nullishCoalesce(data, () => ( "0x"))]);
1949
+ }
1950
+
1951
+ // src/utils/abi/encodeFunctionResult.ts
1952
+ var docsPath4 = "/docs/contract/encodeFunctionResult";
1953
+ function encodeFunctionResult({
1954
+ abi,
1955
+ functionName,
1956
+ result
1957
+ }) {
1958
+ const description = abi.find((x) => "name" in x && x.name === functionName);
1959
+ if (!description)
1960
+ throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 });
1961
+ if (!("outputs" in description))
1962
+ throw new AbiFunctionOutputsNotFoundError(functionName, { docsPath: docsPath4 });
1963
+ let values = Array.isArray(result) ? result : [result];
1964
+ if (description.outputs.length === 0 && !values[0])
1965
+ values = [];
1966
+ return encodeAbi({ params: description.outputs, values });
1967
+ }
1968
+
1969
+ // src/utils/abi/formatAbiItemWithArgs.ts
1970
+ function formatAbiItemWithArgs({
1971
+ abiItem,
1972
+ args,
1973
+ includeFunctionName = true,
1974
+ includeName = false
1975
+ }) {
1976
+ if (!("name" in abiItem))
1977
+ return;
1978
+ if (!("inputs" in abiItem))
1979
+ return;
1980
+ if (!abiItem.inputs)
1981
+ return;
1982
+ return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map(
1983
+ (input, i) => `${includeName && input.name ? `${input.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`
1984
+ ).join(", ")})`;
1985
+ }
1986
+
1987
+ // src/utils/buildRequest.ts
1988
+ function buildRequest(request) {
1989
+ return async (args) => {
1990
+ try {
1991
+ return await request(args);
1992
+ } catch (err_) {
1993
+ let err = err_;
1994
+ if (err.code === -32700)
1995
+ throw new ParseRpcError(err);
1996
+ if (err.code === -32600)
1997
+ throw new InvalidRequestRpcError(err);
1998
+ if (err.code === -32601)
1999
+ throw new MethodNotFoundRpcError(err);
2000
+ if (err.code === -32602)
2001
+ throw new InvalidParamsRpcError(err);
2002
+ if (err.code === -32603)
2003
+ throw new InternalRpcError(err);
2004
+ if (err.code === -32e3)
2005
+ throw new InvalidInputRpcError(err);
2006
+ if (err.code === -32001)
2007
+ throw new ResourceNotFoundRpcError(err);
2008
+ if (err.code === -32002)
2009
+ throw new ResourceUnavailableRpcError(err);
2010
+ if (err.code === -32003)
2011
+ throw new TransactionRejectedRpcError(err);
2012
+ if (err.code === -32004)
2013
+ throw new MethodNotSupportedRpcError(err);
2014
+ if (err.code === -32005)
2015
+ throw new LimitExceededRpcError(err);
2016
+ if (err.code === -32006)
2017
+ throw new JsonRpcVersionUnsupportedError(err);
2018
+ if (err_ instanceof BaseError)
2019
+ throw err_;
2020
+ throw new UnknownRpcError(err);
2021
+ }
2022
+ };
2023
+ }
2024
+
2025
+ // src/constants.ts
2026
+ var etherUnits = {
2027
+ gwei: 9,
2028
+ wei: 18
2029
+ };
2030
+ var gweiUnits = {
2031
+ ether: -9,
2032
+ wei: 9
2033
+ };
2034
+ var weiUnits = {
2035
+ ether: -18,
2036
+ gwei: -9
2037
+ };
2038
+ var transactionType = {
2039
+ "0x0": "legacy",
2040
+ "0x1": "eip2930",
2041
+ "0x2": "eip1559"
2042
+ };
2043
+
2044
+ // src/utils/formatters/transaction.ts
2045
+ function formatTransaction(transaction) {
2046
+ const transaction_ = {
2047
+ ...transaction,
2048
+ blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
2049
+ gas: transaction.gas ? BigInt(transaction.gas) : void 0,
2050
+ gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
2051
+ maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
2052
+ maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
2053
+ nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
2054
+ transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
2055
+ type: transaction.type ? transactionType[transaction.type] : void 0,
2056
+ value: transaction.value ? BigInt(transaction.value) : void 0,
2057
+ v: transaction.v ? BigInt(transaction.v) : void 0
2058
+ };
2059
+ if (transaction_.type === "legacy") {
2060
+ delete transaction_["accessList"];
2061
+ delete transaction_["maxFeePerGas"];
2062
+ delete transaction_["maxPriorityFeePerGas"];
2063
+ }
2064
+ if (transaction_.type === "eip2930") {
2065
+ delete transaction_["maxFeePerGas"];
2066
+ delete transaction_["maxPriorityFeePerGas"];
2067
+ }
2068
+ return transaction_;
2069
+ }
2070
+
2071
+ // src/utils/formatters/block.ts
2072
+ function formatBlock(block) {
2073
+ const transactions = _optionalChain([block, 'access', _33 => _33.transactions, 'optionalAccess', _34 => _34.map, 'call', _35 => _35((transaction) => {
2074
+ if (typeof transaction === "string")
2075
+ return transaction;
2076
+ return formatTransaction(transaction);
2077
+ })]);
2078
+ return {
2079
+ ...block,
2080
+ baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
2081
+ difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
2082
+ gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
2083
+ gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
2084
+ number: block.number ? BigInt(block.number) : null,
2085
+ size: block.size ? BigInt(block.size) : void 0,
2086
+ timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
2087
+ transactions,
2088
+ totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
2089
+ };
2090
+ }
2091
+
2092
+ // src/utils/formatters/feeHistory.ts
2093
+ function formatFeeHistory(feeHistory) {
2094
+ return {
2095
+ baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),
2096
+ gasUsedRatio: feeHistory.gasUsedRatio,
2097
+ oldestBlock: BigInt(feeHistory.oldestBlock),
2098
+ reward: _optionalChain([feeHistory, 'access', _36 => _36.reward, 'optionalAccess', _37 => _37.map, 'call', _38 => _38(
2099
+ (reward) => reward.map((value) => BigInt(value))
2100
+ )])
2101
+ };
2102
+ }
2103
+
2104
+ // src/utils/formatters/format.ts
2105
+ function format3(data, { formatter }) {
2106
+ return formatter(data);
2107
+ }
2108
+
2109
+ // src/utils/formatters/log.ts
2110
+ function formatLog(log) {
2111
+ return {
2112
+ ...log,
2113
+ blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
2114
+ logIndex: log.logIndex ? BigInt(log.logIndex) : null,
2115
+ transactionIndex: log.transactionIndex ? BigInt(log.transactionIndex) : null
2116
+ };
2117
+ }
2118
+
2119
+ // src/utils/formatters/transactionReceipt.ts
2120
+ var statuses = {
2121
+ "0x0": "reverted",
2122
+ "0x1": "success"
2123
+ };
2124
+ function formatTransactionReceipt(transactionReceipt) {
2125
+ return {
2126
+ ...transactionReceipt,
2127
+ blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null,
2128
+ cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
2129
+ effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
2130
+ gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
2131
+ logs: transactionReceipt.logs ? transactionReceipt.logs.map(formatLog) : null,
2132
+ transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
2133
+ status: transactionReceipt.status ? statuses[transactionReceipt.status] : null,
2134
+ type: transactionReceipt.type ? transactionType[transactionReceipt.type] : null
2135
+ };
2136
+ }
2137
+
2138
+ // src/utils/formatters/transactionRequest.ts
2139
+ function formatTransactionRequest(transactionRequest) {
2140
+ return {
2141
+ ...transactionRequest,
2142
+ gas: typeof transactionRequest.gas !== "undefined" ? numberToHex(transactionRequest.gas) : void 0,
2143
+ gasPrice: typeof transactionRequest.gasPrice !== "undefined" ? numberToHex(transactionRequest.gasPrice) : void 0,
2144
+ maxFeePerGas: typeof transactionRequest.maxFeePerGas !== "undefined" ? numberToHex(transactionRequest.maxFeePerGas) : void 0,
2145
+ maxPriorityFeePerGas: typeof transactionRequest.maxPriorityFeePerGas !== "undefined" ? numberToHex(transactionRequest.maxPriorityFeePerGas) : void 0,
2146
+ nonce: typeof transactionRequest.nonce !== "undefined" ? numberToHex(transactionRequest.nonce) : void 0,
2147
+ value: typeof transactionRequest.value !== "undefined" ? numberToHex(transactionRequest.value) : void 0
2148
+ };
2149
+ }
2150
+
2151
+ // src/utils/promise/withCache.ts
2152
+ var promiseCache = /* @__PURE__ */ new Map();
2153
+ var responseCache = /* @__PURE__ */ new Map();
2154
+ function getCache(cacheKey) {
2155
+ const buildCache = (cacheKey2, cache) => ({
2156
+ clear: () => cache.delete(cacheKey2),
2157
+ get: () => cache.get(cacheKey2),
2158
+ set: (data) => cache.set(cacheKey2, data)
2159
+ });
2160
+ const promise = buildCache(cacheKey, promiseCache);
2161
+ const response = buildCache(
2162
+ cacheKey,
2163
+ responseCache
2164
+ );
2165
+ return {
2166
+ clear: () => {
2167
+ promise.clear();
2168
+ response.clear();
2169
+ },
2170
+ promise,
2171
+ response
2172
+ };
2173
+ }
2174
+ async function withCache(fn, { cacheKey, maxAge = Infinity }) {
2175
+ const cache = getCache(cacheKey);
2176
+ const response = cache.response.get();
2177
+ if (response && maxAge > 0) {
2178
+ const age = new Date().getTime() - response.created.getTime();
2179
+ if (age < maxAge)
2180
+ return response.data;
2181
+ }
2182
+ let promise = cache.promise.get();
2183
+ if (!promise) {
2184
+ promise = fn();
2185
+ cache.promise.set(promise);
2186
+ }
2187
+ const data = await promise;
2188
+ cache.promise.clear();
2189
+ cache.response.set({ created: new Date(), data });
2190
+ return data;
2191
+ }
2192
+
2193
+ // src/utils/wait.ts
2194
+ async function wait(time) {
2195
+ return new Promise((res) => setTimeout(res, time));
2196
+ }
2197
+
2198
+ // src/utils/promise/withRetry.ts
2199
+ function withRetry(fn, {
2200
+ delay: delay_ = 100,
2201
+ retryCount = 2,
2202
+ shouldRetryOnResponse = () => false,
2203
+ shouldRetryOnError = () => false
2204
+ } = {}) {
2205
+ return new Promise((resolve, reject) => {
2206
+ const attemptRetry = async ({ count = 0 } = {}) => {
2207
+ const retry = async ({ data } = {}) => {
2208
+ const delay = typeof delay_ === "function" ? delay_({ count, data }) : delay_;
2209
+ if (delay)
2210
+ await wait(delay);
2211
+ attemptRetry({ count: count + 1 });
2212
+ };
2213
+ try {
2214
+ const data = await fn();
2215
+ if (count < retryCount && await shouldRetryOnResponse({ count, data }))
2216
+ return retry({ data });
2217
+ resolve(data);
2218
+ } catch (err) {
2219
+ if (count < retryCount && await shouldRetryOnError({ count, error: err }))
2220
+ return retry();
2221
+ reject(err);
2222
+ }
2223
+ };
2224
+ attemptRetry();
2225
+ });
2226
+ }
2227
+
2228
+ // src/utils/promise/withTimeout.ts
2229
+ function withTimeout(fn, {
2230
+ errorInstance,
2231
+ timeout,
2232
+ signal
2233
+ }) {
2234
+ return new Promise((resolve, reject) => {
2235
+ ;
2236
+ (async () => {
2237
+ let timeoutId;
2238
+ try {
2239
+ const controller = new AbortController();
2240
+ if (timeout > 0) {
2241
+ timeoutId = setTimeout(() => {
2242
+ if (signal) {
2243
+ controller.abort();
2244
+ } else {
2245
+ reject(errorInstance);
2246
+ }
2247
+ }, timeout);
2248
+ }
2249
+ resolve(await fn({ signal: _optionalChain([controller, 'optionalAccess', _39 => _39.signal]) }));
2250
+ } catch (err) {
2251
+ if (err.name === "AbortError")
2252
+ reject(errorInstance);
2253
+ reject(err);
2254
+ } finally {
2255
+ clearTimeout(timeoutId);
2256
+ }
2257
+ })();
2258
+ });
2259
+ }
2260
+
2261
+ // src/utils/rpc.ts
2262
+ var id = 0;
2263
+ async function http(url, {
2264
+ body,
2265
+ retryDelay = 100,
2266
+ retryCount = 2,
2267
+ timeout = 0
2268
+ }) {
2269
+ const response = await withRetry(
2270
+ () => withTimeout(
2271
+ async ({ signal }) => {
2272
+ const response2 = await fetch(url, {
2273
+ headers: {
2274
+ "Content-Type": "application/json"
2275
+ },
2276
+ method: "POST",
2277
+ body: stringify({ jsonrpc: "2.0", id: id++, ...body }),
2278
+ signal: timeout > 0 ? signal : void 0
2279
+ });
2280
+ return response2;
2281
+ },
2282
+ {
2283
+ errorInstance: new TimeoutError({ body, url }),
2284
+ timeout,
2285
+ signal: true
2286
+ }
2287
+ ),
2288
+ {
2289
+ delay: ({ count, data: data2 }) => {
2290
+ const retryAfter = _optionalChain([data2, 'optionalAccess', _40 => _40.headers, 'access', _41 => _41.get, 'call', _42 => _42("Retry-After")]);
2291
+ if (_optionalChain([retryAfter, 'optionalAccess', _43 => _43.match, 'call', _44 => _44(/\d/)]))
2292
+ return parseInt(retryAfter) * 1e3;
2293
+ return ~~((Math.random() + 0.5) * (1 << count)) * retryDelay;
2294
+ },
2295
+ retryCount,
2296
+ shouldRetryOnResponse: async ({ data: data2 }) => {
2297
+ if (data2.status >= 500)
2298
+ return true;
2299
+ if ([408, 413, 429].includes(data2.status))
2300
+ return true;
2301
+ return false;
2302
+ }
2303
+ }
2304
+ );
2305
+ let data;
2306
+ if (_optionalChain([response, 'access', _45 => _45.headers, 'access', _46 => _46.get, 'call', _47 => _47("Content-Type"), 'optionalAccess', _48 => _48.startsWith, 'call', _49 => _49("application/json")])) {
2307
+ data = await response.json();
2308
+ } else {
2309
+ data = await response.text();
2310
+ }
2311
+ if (!response.ok) {
2312
+ throw new HttpRequestError({
2313
+ body,
2314
+ details: stringify(data.error) || response.statusText,
2315
+ status: response.status,
2316
+ url
2317
+ });
2318
+ }
2319
+ if (data.error) {
2320
+ throw new RpcError({ body, error: data.error, url });
2321
+ }
2322
+ return data;
2323
+ }
2324
+ var sockets = /* @__PURE__ */ new Map();
2325
+ async function getSocket(url_) {
2326
+ const url = new URL(url_);
2327
+ const urlKey = url.toString();
2328
+ let socket = sockets.get(urlKey);
2329
+ if (socket)
2330
+ return socket;
2331
+ const webSocket2 = new WebSocket(url);
2332
+ const requests = /* @__PURE__ */ new Map();
2333
+ const subscriptions = /* @__PURE__ */ new Map();
2334
+ const onMessage = ({ data }) => {
2335
+ const message = JSON.parse(data);
2336
+ const isSubscription = message.method === "eth_subscription";
2337
+ const id2 = isSubscription ? message.params.subscription : message.id;
2338
+ const cache = isSubscription ? subscriptions : requests;
2339
+ const callback = cache.get(id2);
2340
+ if (callback)
2341
+ callback({ data });
2342
+ if (!isSubscription)
2343
+ cache.delete(id2);
2344
+ };
2345
+ const onClose = () => {
2346
+ sockets.delete(urlKey);
2347
+ webSocket2.removeEventListener("close", onClose);
2348
+ webSocket2.removeEventListener("message", onMessage);
2349
+ };
2350
+ webSocket2.addEventListener("close", onClose);
2351
+ webSocket2.addEventListener("message", onMessage);
2352
+ if (webSocket2.readyState === WebSocket.CONNECTING) {
2353
+ await new Promise((resolve, reject) => {
2354
+ if (!webSocket2)
2355
+ return;
2356
+ webSocket2.onopen = resolve;
2357
+ webSocket2.onerror = reject;
2358
+ });
2359
+ }
2360
+ socket = Object.assign(webSocket2, {
2361
+ requests,
2362
+ subscriptions
2363
+ });
2364
+ sockets.set(urlKey, socket);
2365
+ return socket;
2366
+ }
2367
+ function webSocket(socket, {
2368
+ body,
2369
+ onData,
2370
+ onError
2371
+ }) {
2372
+ if (socket.readyState === socket.CLOSED || socket.readyState === socket.CLOSING)
2373
+ throw new WebSocketRequestError({
2374
+ body,
2375
+ url: socket.url,
2376
+ details: "Socket is closed."
2377
+ });
2378
+ const id_ = id++;
2379
+ const callback = ({ data }) => {
2380
+ const message = JSON.parse(data);
2381
+ if (typeof message.id === "number" && id_ !== message.id)
2382
+ return;
2383
+ if (message.error) {
2384
+ _optionalChain([onError, 'optionalCall', _50 => _50(new RpcError({ body, error: message.error, url: socket.url }))]);
2385
+ } else {
2386
+ _optionalChain([onData, 'optionalCall', _51 => _51(message)]);
2387
+ }
2388
+ if (body.method === "eth_subscribe" && typeof message.result === "string") {
2389
+ socket.subscriptions.set(message.result, callback);
2390
+ }
2391
+ if (body.method === "eth_unsubscribe") {
2392
+ socket.subscriptions.delete(_optionalChain([body, 'access', _52 => _52.params, 'optionalAccess', _53 => _53[0]]));
2393
+ }
2394
+ };
2395
+ socket.requests.set(id_, callback);
2396
+ socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
2397
+ return socket;
2398
+ }
2399
+ async function webSocketAsync(socket, {
2400
+ body,
2401
+ timeout = 0
2402
+ }) {
2403
+ return withTimeout(
2404
+ () => new Promise(
2405
+ (onData, onError) => rpc.webSocket(socket, {
2406
+ body,
2407
+ onData,
2408
+ onError
2409
+ })
2410
+ ),
2411
+ {
2412
+ errorInstance: new TimeoutError({ body, url: socket.url }),
2413
+ timeout
2414
+ }
2415
+ );
2416
+ }
2417
+ var rpc = {
2418
+ http,
2419
+ webSocket,
2420
+ webSocketAsync
2421
+ };
2422
+
2423
+ // src/utils/unit/formatUnit.ts
2424
+ function formatUnit(value, decimals) {
2425
+ let display = value.toString();
2426
+ const negative = display.startsWith("-");
2427
+ if (negative)
2428
+ display = display.slice(1);
2429
+ let [integer, fraction] = [
2430
+ display.slice(0, display.length - decimals),
2431
+ display.slice(display.length - decimals)
2432
+ ];
2433
+ fraction = fraction.padStart(decimals, "0");
2434
+ fraction = fraction.replace(/(0+)$/, "");
2435
+ return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
2436
+ }
2437
+
2438
+ // src/utils/unit/formatEther.ts
2439
+ function formatEther(wei, unit = "wei") {
2440
+ return formatUnit(wei, etherUnits[unit]);
2441
+ }
2442
+
2443
+ // src/utils/unit/formatGwei.ts
2444
+ function formatGwei(wei, unit = "wei") {
2445
+ return formatUnit(wei, gweiUnits[unit]);
2446
+ }
2447
+
2448
+ // src/utils/unit/parseUnit.ts
2449
+ function parseUnit(value, decimals) {
2450
+ let [integer, fraction = "0"] = value.split(".");
2451
+ const negative = integer.startsWith("-");
2452
+ if (negative)
2453
+ integer = integer.slice(1);
2454
+ fraction = fraction.replace(/(0+)$/, "");
2455
+ if (decimals === 0) {
2456
+ integer = `${Math.round(Number(`${integer}.${fraction}`))}`;
2457
+ fraction = "";
2458
+ } else if (fraction.length > decimals) {
2459
+ const [before, after] = [
2460
+ fraction.slice(0, decimals),
2461
+ fraction.slice(decimals)
2462
+ ];
2463
+ fraction = `${/^0+$/.test(before) ? before.slice(0, before.length - 1) : ""}${Math.round(Number(`${before}.${after}`))}`;
2464
+ } else {
2465
+ fraction = fraction.padEnd(decimals, "0");
2466
+ }
2467
+ return BigInt(`${negative ? "-" : ""}${integer}${fraction}`);
2468
+ }
2469
+
2470
+ // src/utils/unit/parseEther.ts
2471
+ function parseEther(ether, unit = "wei") {
2472
+ return parseUnit(ether, etherUnits[unit]);
2473
+ }
2474
+
2475
+ // src/utils/unit/parseGwei.ts
2476
+ function parseGwei(ether, unit = "wei") {
2477
+ return parseUnit(ether, gweiUnits[unit]);
2478
+ }
2479
+
2480
+
2481
+
2482
+
2483
+
2484
+
2485
+
2486
+
2487
+
2488
+
2489
+
2490
+
2491
+
2492
+
2493
+
2494
+
2495
+
2496
+
2497
+
2498
+
2499
+
2500
+
2501
+
2502
+
2503
+
2504
+
2505
+
2506
+
2507
+
2508
+
2509
+
2510
+
2511
+
2512
+
2513
+
2514
+
2515
+
2516
+
2517
+
2518
+
2519
+
2520
+
2521
+
2522
+
2523
+
2524
+
2525
+
2526
+
2527
+
2528
+
2529
+
2530
+
2531
+
2532
+
2533
+
2534
+
2535
+
2536
+
2537
+
2538
+
2539
+
2540
+
2541
+
2542
+
2543
+
2544
+
2545
+
2546
+
2547
+
2548
+
2549
+
2550
+
2551
+
2552
+
2553
+
2554
+
2555
+
2556
+
2557
+
2558
+
2559
+
2560
+
2561
+
2562
+
2563
+
2564
+
2565
+
2566
+
2567
+
2568
+
2569
+
2570
+
2571
+
2572
+
2573
+
2574
+
2575
+
2576
+
2577
+
2578
+
2579
+
2580
+
2581
+
2582
+
2583
+
2584
+
2585
+
2586
+
2587
+
2588
+
2589
+
2590
+
2591
+
2592
+
2593
+
2594
+
2595
+
2596
+
2597
+
2598
+
2599
+
2600
+
2601
+
2602
+
2603
+
2604
+
2605
+
2606
+
2607
+
2608
+
2609
+
2610
+
2611
+
2612
+
2613
+
2614
+
2615
+
2616
+ exports.stringify = stringify; exports.BaseError = BaseError; exports.AbiConstructorNotFoundError = AbiConstructorNotFoundError; exports.AbiConstructorParamsNotFoundError = AbiConstructorParamsNotFoundError; exports.AbiDecodingDataSizeInvalidError = AbiDecodingDataSizeInvalidError; exports.AbiEncodingArrayLengthMismatchError = AbiEncodingArrayLengthMismatchError; exports.AbiEncodingLengthMismatchError = AbiEncodingLengthMismatchError; exports.AbiErrorInputsNotFoundError = AbiErrorInputsNotFoundError; exports.AbiErrorNotFoundError = AbiErrorNotFoundError; exports.AbiErrorSignatureNotFoundError = AbiErrorSignatureNotFoundError; exports.AbiEventNotFoundError = AbiEventNotFoundError; exports.AbiFunctionNotFoundError = AbiFunctionNotFoundError; exports.AbiFunctionOutputsNotFoundError = AbiFunctionOutputsNotFoundError; exports.AbiFunctionSignatureNotFoundError = AbiFunctionSignatureNotFoundError; exports.InvalidAbiEncodingTypeError = InvalidAbiEncodingTypeError; exports.InvalidAbiDecodingTypeError = InvalidAbiDecodingTypeError; exports.InvalidArrayError = InvalidArrayError; exports.InvalidDefinitionTypeError = InvalidDefinitionTypeError; exports.InvalidAddressError = InvalidAddressError; exports.BlockNotFoundError = BlockNotFoundError; exports.SizeExceedsPaddingSizeError = SizeExceedsPaddingSizeError; exports.DataLengthTooLongError = DataLengthTooLongError; exports.DataLengthTooShortError = DataLengthTooShortError; exports.InvalidBytesBooleanError = InvalidBytesBooleanError; exports.InvalidHexBooleanError = InvalidHexBooleanError; exports.InvalidHexValueError = InvalidHexValueError; exports.OffsetOutOfBoundsError = OffsetOutOfBoundsError; exports.FilterTypeNotSupportedError = FilterTypeNotSupportedError; exports.RequestError = RequestError; exports.RpcRequestError = RpcRequestError; exports.ParseRpcError = ParseRpcError; exports.InvalidRequestRpcError = InvalidRequestRpcError; exports.MethodNotFoundRpcError = MethodNotFoundRpcError; exports.InvalidParamsRpcError = InvalidParamsRpcError; exports.InternalRpcError = InternalRpcError; exports.InvalidInputRpcError = InvalidInputRpcError; exports.ResourceNotFoundRpcError = ResourceNotFoundRpcError; exports.ResourceUnavailableRpcError = ResourceUnavailableRpcError; exports.TransactionRejectedRpcError = TransactionRejectedRpcError; exports.MethodNotSupportedRpcError = MethodNotSupportedRpcError; exports.LimitExceededRpcError = LimitExceededRpcError; exports.JsonRpcVersionUnsupportedError = JsonRpcVersionUnsupportedError; exports.UnknownRpcError = UnknownRpcError; exports.isBytes = isBytes; exports.isHex = isHex; exports.pad = pad; exports.padHex = padHex; exports.padBytes = padBytes; exports.trim = trim; exports.size = size; exports.slice = slice; exports.sliceBytes = sliceBytes; exports.sliceHex = sliceHex; exports.boolToHex = boolToHex; exports.bytesToHex = bytesToHex; exports.encodeHex = encodeHex; exports.numberToHex = numberToHex; exports.stringToHex = stringToHex; exports.boolToBytes = boolToBytes; exports.encodeBytes = encodeBytes; exports.hexToBytes = hexToBytes; exports.numberToBytes = numberToBytes; exports.stringToBytes = stringToBytes; exports.encodeRlp = encodeRlp; exports.decodeHex = decodeHex; exports.hexToBigInt = hexToBigInt; exports.hexToBool = hexToBool; exports.hexToNumber = hexToNumber; exports.hexToString = hexToString; exports.decodeBytes = decodeBytes; exports.bytesToBigint = bytesToBigint; exports.bytesToBool = bytesToBool; exports.bytesToNumber = bytesToNumber; exports.bytesToString = bytesToString; exports.decodeRlp = decodeRlp; exports.extractFunctionParts = extractFunctionParts; exports.extractFunctionName = extractFunctionName; exports.extractFunctionParams = extractFunctionParams; exports.extractFunctionType = extractFunctionType; exports.getContractError = getContractError; exports.keccak256 = keccak256; exports.getEventSignature = getEventSignature; exports.getFunctionSignature = getFunctionSignature; exports.checksumAddress = checksumAddress; exports.getAddress = getAddress; exports.getContractAddress = getContractAddress; exports.getCreateAddress = getCreateAddress; exports.getCreate2Address = getCreate2Address; exports.isAddress = isAddress; exports.isAddressEqual = isAddressEqual; exports.encodeAbi = encodeAbi; exports.decodeAbi = decodeAbi; exports.formatAbiItemWithParams = formatAbiItemWithParams; exports.decodeErrorResult = decodeErrorResult; exports.decodeFunctionData = decodeFunctionData; exports.decodeFunctionResult = decodeFunctionResult; exports.encodeDeployData = encodeDeployData; exports.getAbiItem = getAbiItem; exports.encodeErrorResult = encodeErrorResult; exports.encodeEventTopics = encodeEventTopics; exports.encodeFunctionData = encodeFunctionData; exports.encodeFunctionResult = encodeFunctionResult; exports.formatAbiItemWithArgs = formatAbiItemWithArgs; exports.buildRequest = buildRequest; exports.etherUnits = etherUnits; exports.gweiUnits = gweiUnits; exports.weiUnits = weiUnits; exports.transactionType = transactionType; exports.formatTransaction = formatTransaction; exports.formatBlock = formatBlock; exports.formatFeeHistory = formatFeeHistory; exports.format = format3; exports.formatLog = formatLog; exports.formatTransactionReceipt = formatTransactionReceipt; exports.formatTransactionRequest = formatTransactionRequest; exports.getCache = getCache; exports.withCache = withCache; exports.wait = wait; exports.getSocket = getSocket; exports.rpc = rpc; exports.formatUnit = formatUnit; exports.formatEther = formatEther; exports.formatGwei = formatGwei; exports.parseUnit = parseUnit; exports.parseEther = parseEther; exports.parseGwei = parseGwei; exports.HttpRequestError = HttpRequestError; exports.WebSocketRequestError = WebSocketRequestError; exports.RpcError = RpcError; exports.TimeoutError = TimeoutError; exports.InvalidGasArgumentsError = InvalidGasArgumentsError; exports.TransactionNotFoundError = TransactionNotFoundError; exports.TransactionReceiptNotFoundError = TransactionReceiptNotFoundError; exports.WaitForTransactionReceiptTimeoutError = WaitForTransactionReceiptTimeoutError; exports.UrlRequiredError = UrlRequiredError;