viem 0.0.0 → 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1469 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+
8
+ // package.json
9
+ var package_default = {
10
+ name: "viem",
11
+ description: "TypeScript (& JavaScript) Interface for Ethereum",
12
+ version: "0.0.1-alpha.0",
13
+ scripts: {
14
+ build: "tsup",
15
+ dev: "DEV=true tsup"
16
+ },
17
+ dependencies: {
18
+ "@noble/hashes": "^1.1.2",
19
+ "@wagmi/chains": "^0.1.0",
20
+ abitype: "^0.2.5"
21
+ },
22
+ files: [
23
+ "/actions",
24
+ "/chains",
25
+ "/dist",
26
+ "/clients",
27
+ "/types",
28
+ "/utils",
29
+ "/window"
30
+ ],
31
+ exports: {
32
+ ".": {
33
+ types: "./dist/index.d.ts",
34
+ default: "./dist/index.js"
35
+ },
36
+ "./actions": {
37
+ types: "./dist/actions/index.d.ts",
38
+ default: "./dist/actions/index.js"
39
+ },
40
+ "./chains": {
41
+ types: "./dist/chains.d.ts",
42
+ default: "./dist/chains.js"
43
+ },
44
+ "./clients": {
45
+ types: "./dist/clients/index.d.ts",
46
+ default: "./dist/clients/index.js"
47
+ },
48
+ "./utils": {
49
+ types: "./dist/utils/index.d.ts",
50
+ default: "./dist/utils/index.js"
51
+ },
52
+ "./window": {
53
+ types: "./dist/window.d.ts",
54
+ default: "./dist/window.js"
55
+ },
56
+ "./package.json": "./package.json"
57
+ },
58
+ type: "module",
59
+ main: "dist/index.js",
60
+ types: "dist/index.d.ts",
61
+ sideEffects: false,
62
+ license: "WAGMIT",
63
+ repository: "wagmi-dev/viem",
64
+ author: "moxey.eth",
65
+ ethereum: "moxey.eth",
66
+ keywords: [
67
+ "eth",
68
+ "ethereum",
69
+ "dapps",
70
+ "wallet",
71
+ "web3"
72
+ ]
73
+ };
74
+
75
+ // src/utils/BaseError.ts
76
+ var version = process.env.TEST ? "1.0.2" : package_default.version;
77
+ var BaseError = class extends Error {
78
+ constructor(humanMessage, args = {}) {
79
+ const details = args.cause instanceof BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details;
80
+ const docsPath = args.cause instanceof BaseError ? args.cause.docsPath || args.docsPath : args.docsPath;
81
+ const message = [
82
+ humanMessage,
83
+ ...docsPath ? ["", "Docs: https://viem.sh" + docsPath] : [],
84
+ "",
85
+ ...details ? ["Details: " + details] : [],
86
+ "Version: viem@" + version,
87
+ ...args.cause && !(args.cause instanceof BaseError) && Object.keys(args.cause).length > 0 ? ["Internal Error: " + JSON.stringify(args.cause)] : []
88
+ ].join("\n");
89
+ super(message);
90
+ __publicField(this, "humanMessage");
91
+ __publicField(this, "details");
92
+ __publicField(this, "docsPath");
93
+ __publicField(this, "name", "ViemError");
94
+ if (args.cause)
95
+ this.cause = args.cause;
96
+ this.details = details;
97
+ this.docsPath = docsPath;
98
+ this.humanMessage = humanMessage;
99
+ }
100
+ };
101
+
102
+ // src/utils/data/concat.ts
103
+ function concat(values) {
104
+ if (typeof values[0] === "string")
105
+ return concatHex(values);
106
+ return concatBytes(values);
107
+ }
108
+ function concatBytes(values) {
109
+ let length = 0;
110
+ for (const arr of values) {
111
+ length += arr.length;
112
+ }
113
+ const result = new Uint8Array(length);
114
+ let offset = 0;
115
+ for (const arr of values) {
116
+ result.set(arr, offset);
117
+ offset += arr.length;
118
+ }
119
+ return result;
120
+ }
121
+ function concatHex(values) {
122
+ return `0x${values.reduce(
123
+ (acc, x) => acc + x.replace("0x", ""),
124
+ ""
125
+ )}`;
126
+ }
127
+
128
+ // src/utils/data/isBytes.ts
129
+ function isBytes(value) {
130
+ if (!value)
131
+ return false;
132
+ if (typeof value !== "object")
133
+ return false;
134
+ return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
135
+ }
136
+
137
+ // src/utils/data/isHex.ts
138
+ function isHex(value) {
139
+ if (!value)
140
+ return false;
141
+ if (typeof value !== "string")
142
+ return false;
143
+ return /^0x[0-9a-fA-F]*$/.test(value);
144
+ }
145
+
146
+ // src/utils/data/pad.ts
147
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
148
+ if (typeof hexOrBytes === "string")
149
+ return padHex(hexOrBytes, { dir, size: size2 });
150
+ return padBytes(hexOrBytes, { dir, size: size2 });
151
+ }
152
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
153
+ let hex = hex_.replace("0x", "");
154
+ if (hex.length > size2 * 2)
155
+ throw new SizeExceedsPaddingSizeError({
156
+ size: Math.ceil(hex.length / 2),
157
+ targetSize: size2,
158
+ type: "hex"
159
+ });
160
+ return "0x" + hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0");
161
+ }
162
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
163
+ if (bytes.length > size2)
164
+ throw new SizeExceedsPaddingSizeError({
165
+ size: bytes.length,
166
+ targetSize: size2,
167
+ type: "bytes"
168
+ });
169
+ const paddedBytes = new Uint8Array(size2);
170
+ for (let i = 0; i < size2; i++) {
171
+ const padEnd = dir === "right";
172
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
173
+ }
174
+ return paddedBytes;
175
+ }
176
+ var SizeExceedsPaddingSizeError = class extends BaseError {
177
+ constructor({
178
+ size: size2,
179
+ targetSize,
180
+ type
181
+ }) {
182
+ super(
183
+ `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`
184
+ );
185
+ __publicField(this, "name", "SizeExceedsPaddingSizeError");
186
+ }
187
+ };
188
+
189
+ // src/utils/data/trim.ts
190
+ function trim(hexOrBytes, { dir = "left" } = {}) {
191
+ let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
192
+ let sliceLength = 0;
193
+ for (let i = 0; i < data.length - 1; i++) {
194
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
195
+ sliceLength++;
196
+ else
197
+ break;
198
+ }
199
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
200
+ if (typeof hexOrBytes === "string") {
201
+ if (data.length === 1 && dir === "right")
202
+ data = data + "0";
203
+ return `0x${data}`;
204
+ }
205
+ return data;
206
+ }
207
+
208
+ // src/utils/data/size.ts
209
+ function size(value) {
210
+ if (isHex(value))
211
+ return Math.ceil((value.length - 2) / 2);
212
+ return value.length;
213
+ }
214
+
215
+ // src/utils/data/slice.ts
216
+ function slice(value, start, end) {
217
+ if (isHex(value))
218
+ return sliceHex(value, start, end);
219
+ return sliceBytes(value, start, end);
220
+ }
221
+ function assertStartOffset(value, start) {
222
+ if (typeof start === "number" && start > 0 && start > size(value) - 1)
223
+ throw new Error(
224
+ `Slice starting at offset "${start}" is out-of-bounds (size: ${size(
225
+ value
226
+ )}).`
227
+ );
228
+ }
229
+ function sliceBytes(value, start, end) {
230
+ assertStartOffset(value, start);
231
+ return value.slice(start, end);
232
+ }
233
+ function sliceHex(value_, start, end) {
234
+ assertStartOffset(value_, start);
235
+ const value = value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2);
236
+ return `0x${value}`;
237
+ }
238
+
239
+ // src/utils/encoding/encodeHex.ts
240
+ var hexes = Array.from(
241
+ { length: 256 },
242
+ (v, i) => i.toString(16).padStart(2, "0")
243
+ );
244
+ function boolToHex(value) {
245
+ return `0x${Number(value)}`;
246
+ }
247
+ function bytesToHex(value) {
248
+ let hex = "";
249
+ for (let i = 0; i < value.length; i++) {
250
+ hex += hexes[value[i]];
251
+ }
252
+ return `0x${hex}`;
253
+ }
254
+ function encodeHex(value) {
255
+ if (typeof value === "number" || typeof value === "bigint")
256
+ return numberToHex(value);
257
+ if (typeof value === "string") {
258
+ return stringToHex(value);
259
+ }
260
+ if (typeof value === "boolean")
261
+ return boolToHex(value);
262
+ return bytesToHex(value);
263
+ }
264
+ function numberToHex(value_, opts = {}) {
265
+ const { signed, size: size2 } = opts;
266
+ let value = BigInt(value_);
267
+ let maxValue;
268
+ if (size2) {
269
+ if (signed)
270
+ maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
271
+ else
272
+ maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
273
+ } else if (typeof value_ === "number") {
274
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
275
+ }
276
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
277
+ if (maxValue && value > maxValue || value < minValue) {
278
+ const suffix = typeof value_ === "bigint" ? "n" : "";
279
+ throw new Error(
280
+ `Number "${value_}${suffix}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${maxValue ? `(${minValue}${suffix} to ${maxValue}${suffix})` : `(above ${minValue})`}`
281
+ );
282
+ }
283
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
284
+ if (size2)
285
+ return pad(hex, { size: size2 });
286
+ return hex;
287
+ }
288
+ function stringToHex(value) {
289
+ let hex = "";
290
+ for (let i = 0; i < value.length; i++) {
291
+ hex += value.charCodeAt(i).toString(16);
292
+ }
293
+ return `0x${hex}`;
294
+ }
295
+
296
+ // src/utils/encoding/encodeBytes.ts
297
+ var encoder = new TextEncoder();
298
+ function boolToBytes(value) {
299
+ const bytes = new Uint8Array(1);
300
+ bytes[0] = Number(value);
301
+ return bytes;
302
+ }
303
+ function encodeBytes(value) {
304
+ if (typeof value === "number" || typeof value === "bigint")
305
+ return numberToBytes(value);
306
+ if (typeof value === "boolean")
307
+ return boolToBytes(value);
308
+ if (value.startsWith("0x"))
309
+ return hexToBytes(value);
310
+ return stringToBytes(value);
311
+ }
312
+ function hexToBytes(hex_) {
313
+ let hex = hex_.slice(2);
314
+ if (hex.length % 2)
315
+ hex = "0" + hex;
316
+ const bytes = new Uint8Array(hex.length / 2);
317
+ for (let index = 0; index < bytes.length; index++) {
318
+ const start = index * 2;
319
+ const hexByte = hex.slice(start, start + 2);
320
+ const byte = Number.parseInt(hexByte, 16);
321
+ if (Number.isNaN(byte) || byte < 0)
322
+ throw new Error("Invalid byte sequence");
323
+ bytes[index] = byte;
324
+ }
325
+ return bytes;
326
+ }
327
+ function numberToBytes(value, opts) {
328
+ const hex = numberToHex(value, opts);
329
+ return hexToBytes(hex);
330
+ }
331
+ function stringToBytes(value) {
332
+ return encoder.encode(value);
333
+ }
334
+
335
+ // src/utils/encoding/encodeRlp.ts
336
+ function encodeRlp(hexOrBytes, to_) {
337
+ const to = to_ || "hex";
338
+ return format(bytesToRlp(parse(hexOrBytes)), to);
339
+ }
340
+ function parse(hexOrBytes) {
341
+ if (Array.isArray(hexOrBytes))
342
+ return hexOrBytes.map(parse);
343
+ return typeof hexOrBytes === "string" ? encodeBytes(hexOrBytes) : hexOrBytes;
344
+ }
345
+ function format(bytes, type = "bytes") {
346
+ return type === "hex" ? bytesToHex(bytes) : bytes;
347
+ }
348
+ function bytesToRlp(bytes) {
349
+ if (Array.isArray(bytes)) {
350
+ const encoded = concat(bytes.map(bytesToRlp));
351
+ return new Uint8Array([...encodeLength(encoded.length, 192), ...encoded]);
352
+ }
353
+ if (bytes.length === 1 && bytes[0] < 128)
354
+ return bytes;
355
+ return new Uint8Array([...encodeLength(bytes.length, 128), ...bytes]);
356
+ }
357
+ function encodeLength(length, offset) {
358
+ if (length < 56)
359
+ return [offset + length];
360
+ return [encodeBytes(length).length + offset + 55, ...encodeBytes(length)];
361
+ }
362
+
363
+ // src/utils/encoding/decodeHex.ts
364
+ function decodeHex(hex, to) {
365
+ if (to === "number")
366
+ return hexToNumber(hex);
367
+ if (to === "bigint")
368
+ return hexToBigInt(hex);
369
+ if (to === "string")
370
+ return hexToString(hex);
371
+ if (to === "boolean")
372
+ return hexToBool(hex);
373
+ return hexToBytes(hex);
374
+ }
375
+ function hexToBigInt(hex) {
376
+ return BigInt(hex);
377
+ }
378
+ function hexToBool(hex) {
379
+ if (hex === "0x0")
380
+ return false;
381
+ if (hex === "0x1")
382
+ return true;
383
+ throw new InvalidHexBooleanError(hex);
384
+ }
385
+ function hexToNumber(hex) {
386
+ return Number(BigInt(hex));
387
+ }
388
+ function hexToString(hex) {
389
+ const bytes = hexToBytes(hex);
390
+ return new TextDecoder().decode(bytes);
391
+ }
392
+ var InvalidHexBooleanError = class extends BaseError {
393
+ constructor(hex) {
394
+ super(
395
+ `Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`
396
+ );
397
+ __publicField(this, "name", "InvalidHexBooleanError");
398
+ }
399
+ };
400
+
401
+ // src/utils/encoding/decodeBytes.ts
402
+ function decodeBytes(bytes, to) {
403
+ if (to === "number")
404
+ return bytesToNumber(bytes);
405
+ if (to === "bigint")
406
+ return bytesToBigint(bytes);
407
+ if (to === "boolean")
408
+ return bytesToBool(bytes);
409
+ if (to === "string")
410
+ return bytesToString(bytes);
411
+ return bytesToHex(bytes);
412
+ }
413
+ function bytesToBigint(bytes) {
414
+ const hex = bytesToHex(bytes);
415
+ return hexToBigInt(hex);
416
+ }
417
+ function bytesToBool(bytes) {
418
+ if (bytes.length > 1 || bytes[0] > 1)
419
+ throw new InvalidBytesBooleanError(bytes);
420
+ return Boolean(bytes[0]);
421
+ }
422
+ function bytesToNumber(bytes) {
423
+ const hex = bytesToHex(bytes);
424
+ return hexToNumber(hex);
425
+ }
426
+ function bytesToString(bytes) {
427
+ return new TextDecoder().decode(bytes);
428
+ }
429
+ var InvalidBytesBooleanError = class extends BaseError {
430
+ constructor(bytes) {
431
+ super(
432
+ `Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`
433
+ );
434
+ __publicField(this, "name", "InvalidBytesBooleanError");
435
+ }
436
+ };
437
+
438
+ // src/utils/encoding/decodeRlp.ts
439
+ function decodeRlp(value, to) {
440
+ const bytes = parse2(value);
441
+ const [data, consumed] = rlpToBytes(bytes);
442
+ if (consumed < bytes.length)
443
+ throw new DataLengthTooLongError({
444
+ consumed,
445
+ length: bytes.length
446
+ });
447
+ return format2(data, to);
448
+ }
449
+ function parse2(value) {
450
+ if (typeof value === "string") {
451
+ if (value.length > 3 && value.length % 2 !== 0)
452
+ throw new InvalidHexValueError(value);
453
+ return hexToBytes(value);
454
+ }
455
+ return value;
456
+ }
457
+ function format2(bytes, to) {
458
+ if (Array.isArray(bytes))
459
+ return bytes.map((b) => format2(b, to));
460
+ return to === "hex" ? trim(bytesToHex(bytes)) : bytes;
461
+ }
462
+ function rlpToBytes(bytes, offset = 0) {
463
+ if (bytes.length === 0)
464
+ return [new Uint8Array([]), 0];
465
+ const prefix = bytes[offset];
466
+ if (prefix <= 127)
467
+ return [new Uint8Array([bytes[offset]]), 1];
468
+ if (prefix <= 183) {
469
+ const length2 = prefix - 128;
470
+ const offset_ = offset + 1;
471
+ if (offset_ + length2 > bytes.length)
472
+ throw new DataLengthTooShortError({
473
+ length: offset_ + length2,
474
+ dataLength: bytes.length
475
+ });
476
+ return [bytes.slice(offset_, offset_ + length2), 1 + length2];
477
+ }
478
+ if (prefix <= 191) {
479
+ const lengthOfLength2 = prefix - 183;
480
+ const offset_ = offset + 1;
481
+ const length2 = bytesToNumber(bytes.slice(offset_, offset_ + lengthOfLength2));
482
+ if (offset_ + lengthOfLength2 + length2 > bytes.length)
483
+ throw new DataLengthTooShortError({
484
+ length: lengthOfLength2 + length2,
485
+ dataLength: bytes.length - lengthOfLength2
486
+ });
487
+ return [
488
+ bytes.slice(offset_ + lengthOfLength2, offset_ + lengthOfLength2 + length2),
489
+ 1 + lengthOfLength2 + length2
490
+ ];
491
+ }
492
+ let lengthOfLength = 0;
493
+ let length = prefix - 192;
494
+ if (prefix > 247) {
495
+ lengthOfLength = prefix - 247;
496
+ length = bytesToNumber(bytes.slice(offset + 1, offset + 1 + lengthOfLength));
497
+ }
498
+ let nextOffset = offset + 1 + lengthOfLength;
499
+ if (nextOffset > bytes.length)
500
+ throw new DataLengthTooShortError({
501
+ length: nextOffset,
502
+ dataLength: bytes.length
503
+ });
504
+ let consumed = 1 + lengthOfLength + length;
505
+ let result = [];
506
+ while (nextOffset < offset + consumed) {
507
+ const decoded = rlpToBytes(bytes, nextOffset);
508
+ result.push(decoded[0]);
509
+ nextOffset += decoded[1];
510
+ if (nextOffset > offset + consumed)
511
+ throw new OffsetOutOfBoundsError({
512
+ nextOffset,
513
+ offset: offset + consumed
514
+ });
515
+ }
516
+ return [result, consumed];
517
+ }
518
+ var DataLengthTooLongError = class extends BaseError {
519
+ constructor({ consumed, length }) {
520
+ super(
521
+ `Consumed bytes (${consumed}) is shorter than data length (${length - 1}).`
522
+ );
523
+ __publicField(this, "name", "DataLengthTooLongError");
524
+ }
525
+ };
526
+ var DataLengthTooShortError = class extends BaseError {
527
+ constructor({ length, dataLength }) {
528
+ super(
529
+ `Data length (${dataLength - 1}) is shorter than prefix length (${length - 1}).`
530
+ );
531
+ __publicField(this, "name", "DataLengthTooShortError");
532
+ }
533
+ };
534
+ var InvalidHexValueError = class extends BaseError {
535
+ constructor(value) {
536
+ super(
537
+ `Hex value "${value}" is an odd length (${value.length}). It must be an even length.`
538
+ );
539
+ __publicField(this, "name", "InvalidHexValueError");
540
+ }
541
+ };
542
+ var OffsetOutOfBoundsError = class extends BaseError {
543
+ constructor({ nextOffset, offset }) {
544
+ super(
545
+ `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`
546
+ );
547
+ __publicField(this, "name", "OffsetOutOfBoundsError");
548
+ }
549
+ };
550
+
551
+ // src/utils/solidity.ts
552
+ var paramsRegex = /((function|event)\s)?(.*)(\((.*)\))/;
553
+ function extractFunctionParts(def) {
554
+ const parts = def.match(paramsRegex);
555
+ const type = parts?.[2] || void 0;
556
+ const name = parts?.[3];
557
+ const params = parts?.[5] || void 0;
558
+ return { type, name, params };
559
+ }
560
+ function extractFunctionName(def) {
561
+ return extractFunctionParts(def).name;
562
+ }
563
+ function extractFunctionParams(def) {
564
+ const params = extractFunctionParts(def).params;
565
+ const splitParams = params?.split(",").map((x) => x.trim().split(" "));
566
+ return splitParams?.map((param) => ({
567
+ type: param[0],
568
+ name: param[1] === "indexed" ? param[2] : param[1],
569
+ ...param[1] === "indexed" ? { indexed: true } : {}
570
+ }));
571
+ }
572
+ function extractFunctionType(def) {
573
+ return extractFunctionParts(def).type;
574
+ }
575
+
576
+ // src/utils/hash/keccak256.ts
577
+ import { keccak_256 } from "@noble/hashes/sha3";
578
+ function keccak256(value, to_) {
579
+ const to = to_ || "hex";
580
+ const bytes = keccak_256(value);
581
+ if (to === "bytes")
582
+ return bytes;
583
+ return encodeHex(bytes);
584
+ }
585
+
586
+ // src/utils/hash/hashFunction.ts
587
+ var hash = (value) => keccak256(encodeBytes(value));
588
+ function hashFunction(def) {
589
+ const name = extractFunctionName(def);
590
+ const params = extractFunctionParams(def);
591
+ if (!params || params.length === 0)
592
+ return hash(def.replace(/ /g, ""));
593
+ return hash(`${name}(${params.map(({ type }) => type).join(",")})`);
594
+ }
595
+
596
+ // src/utils/hash/getEventSignature.ts
597
+ var getEventSignature = (event) => hashFunction(event);
598
+
599
+ // src/utils/hash/getFunctionSignature.ts
600
+ var getFunctionSignature = (fn) => hashFunction(fn).slice(0, 10);
601
+
602
+ // src/utils/address/getAddress.ts
603
+ var addressRegex = /^(0x)?[a-fA-F0-9]{40}$/;
604
+ function checksumAddress(address_) {
605
+ const hexAddress = address_.substring(2).toLowerCase();
606
+ const hash2 = keccak256(stringToBytes(hexAddress), "bytes");
607
+ let address = hexAddress.split("");
608
+ for (let i = 0; i < 40; i += 2) {
609
+ if (hash2?.[i >> 1] >> 4 >= 8) {
610
+ address[i] = address[i].toUpperCase();
611
+ }
612
+ if ((hash2[i >> 1] & 15) >= 8) {
613
+ address[i + 1] = address[i + 1].toUpperCase();
614
+ }
615
+ }
616
+ return `0x${address.join("")}`;
617
+ }
618
+ function getAddress(address) {
619
+ if (!addressRegex.test(address))
620
+ throw new InvalidAddressError({ address });
621
+ return checksumAddress(address);
622
+ }
623
+ var InvalidAddressError = class extends BaseError {
624
+ constructor({ address }) {
625
+ super(`Address "${address}" is invalid.`);
626
+ __publicField(this, "name", "InvalidAddressError");
627
+ }
628
+ };
629
+
630
+ // src/utils/address/getContractAddress.ts
631
+ function getContractAddress(opts) {
632
+ if (opts.opcode === "CREATE2")
633
+ return getCreate2Address(opts);
634
+ return getCreateAddress(opts);
635
+ }
636
+ function getCreateAddress(opts) {
637
+ const from = encodeBytes(getAddress(opts.from));
638
+ let nonce = encodeBytes(opts.nonce);
639
+ if (nonce[0] === 0)
640
+ nonce = new Uint8Array([]);
641
+ return getAddress(
642
+ "0x" + keccak256(encodeRlp([from, nonce], "bytes")).slice(26)
643
+ );
644
+ }
645
+ function getCreate2Address(opts) {
646
+ const from = encodeBytes(getAddress(opts.from));
647
+ const salt = pad(
648
+ isBytes(opts.salt) ? opts.salt : encodeBytes(opts.salt),
649
+ { size: 32 }
650
+ );
651
+ const bytecodeHash = encodeBytes(
652
+ keccak256(
653
+ isBytes(opts.bytecode) ? opts.bytecode : encodeBytes(opts.bytecode)
654
+ )
655
+ );
656
+ return getAddress(
657
+ slice(
658
+ keccak256(concat([encodeBytes("0xff"), from, salt, bytecodeHash])),
659
+ 12
660
+ )
661
+ );
662
+ }
663
+
664
+ // src/utils/address/isAddress.ts
665
+ function isAddress(address) {
666
+ try {
667
+ return Boolean(getAddress(address));
668
+ } catch {
669
+ return false;
670
+ }
671
+ }
672
+
673
+ // src/utils/address/isAddressEqual.ts
674
+ function isAddressEqual(a, b) {
675
+ return getAddress(a) === getAddress(b);
676
+ }
677
+
678
+ // src/utils/buildRequest.ts
679
+ function buildRequest(request) {
680
+ return async (args) => {
681
+ try {
682
+ return await request(args);
683
+ } catch (err_) {
684
+ let err = err_;
685
+ if (err.code === -32700)
686
+ throw new ParseRpcError(err);
687
+ if (err.code === -32600)
688
+ throw new InvalidRequestRpcError(err);
689
+ if (err.code === -32601)
690
+ throw new MethodNotFoundRpcError(err);
691
+ if (err.code === -32602)
692
+ throw new InvalidParamsRpcError(err);
693
+ if (err.code === -32603)
694
+ throw new InternalRpcError(err);
695
+ if (err.code === -32e3)
696
+ throw new InvalidInputRpcError(err);
697
+ if (err.code === -32001)
698
+ throw new ResourceNotFoundRpcError(err);
699
+ if (err.code === -32002)
700
+ throw new ResourceUnavailableRpcError(err);
701
+ if (err.code === -32003)
702
+ throw new TransactionRejectedRpcError(err);
703
+ if (err.code === -32004)
704
+ throw new MethodNotSupportedRpcError(err);
705
+ if (err.code === -32005)
706
+ throw new LimitExceededRpcError(err);
707
+ if (err.code === -32006)
708
+ throw new JsonRpcVersionUnsupportedError(err);
709
+ if (err_ instanceof BaseError)
710
+ throw err_;
711
+ throw new UnknownRpcError(err);
712
+ }
713
+ };
714
+ }
715
+ var RequestError = class extends BaseError {
716
+ constructor(err, { docsPath, humanMessage }) {
717
+ super(humanMessage, {
718
+ cause: err,
719
+ docsPath
720
+ });
721
+ this.name = err.name;
722
+ }
723
+ };
724
+ var RpcRequestError = class extends RequestError {
725
+ constructor(err, { docsPath, humanMessage }) {
726
+ super(err, { docsPath, humanMessage });
727
+ __publicField(this, "code");
728
+ this.code = err.code;
729
+ this.name = err.name;
730
+ }
731
+ };
732
+ var ParseRpcError = class extends RpcRequestError {
733
+ constructor(err) {
734
+ super(err, {
735
+ humanMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
736
+ });
737
+ __publicField(this, "name", "ParseRpcError");
738
+ __publicField(this, "code", -32700);
739
+ }
740
+ };
741
+ var InvalidRequestRpcError = class extends RpcRequestError {
742
+ constructor(err) {
743
+ super(err, { humanMessage: "JSON is not a valid request object." });
744
+ __publicField(this, "name", "InvalidRequestRpcError");
745
+ __publicField(this, "code", -32600);
746
+ }
747
+ };
748
+ var MethodNotFoundRpcError = class extends RpcRequestError {
749
+ constructor(err) {
750
+ super(err, {
751
+ humanMessage: "The method does not exist / is not available."
752
+ });
753
+ __publicField(this, "name", "MethodNotFoundRpcError");
754
+ __publicField(this, "code", -32601);
755
+ }
756
+ };
757
+ var InvalidParamsRpcError = class extends RpcRequestError {
758
+ constructor(err) {
759
+ super(err, {
760
+ humanMessage: [
761
+ "Invalid parameters were provided to the RPC method.",
762
+ "Double check you have provided the correct parameters."
763
+ ].join("\n")
764
+ });
765
+ __publicField(this, "name", "InvalidParamsRpcError");
766
+ __publicField(this, "code", -32602);
767
+ }
768
+ };
769
+ var InternalRpcError = class extends RpcRequestError {
770
+ constructor(err) {
771
+ super(err, { humanMessage: "An internal error was received." });
772
+ __publicField(this, "name", "InternalRpcError");
773
+ __publicField(this, "code", -32603);
774
+ }
775
+ };
776
+ var InvalidInputRpcError = class extends RpcRequestError {
777
+ constructor(err) {
778
+ super(err, {
779
+ humanMessage: [
780
+ "Missing or invalid parameters.",
781
+ "Double check you have provided the correct parameters."
782
+ ].join("\n")
783
+ });
784
+ __publicField(this, "name", "InvalidInputRpcError");
785
+ __publicField(this, "code", -32e3);
786
+ }
787
+ };
788
+ var ResourceNotFoundRpcError = class extends RpcRequestError {
789
+ constructor(err) {
790
+ super(err, { humanMessage: "Requested resource not found." });
791
+ __publicField(this, "name", "ResourceNotFoundRpcError");
792
+ __publicField(this, "code", -32001);
793
+ }
794
+ };
795
+ var ResourceUnavailableRpcError = class extends RpcRequestError {
796
+ constructor(err) {
797
+ super(err, { humanMessage: "Requested resource not available." });
798
+ __publicField(this, "name", "ResourceUnavailableRpcError");
799
+ __publicField(this, "code", -32002);
800
+ }
801
+ };
802
+ var TransactionRejectedRpcError = class extends RpcRequestError {
803
+ constructor(err) {
804
+ super(err, { humanMessage: "Transaction creation failed." });
805
+ __publicField(this, "name", "TransactionRejectedRpcError");
806
+ __publicField(this, "code", -32003);
807
+ }
808
+ };
809
+ var MethodNotSupportedRpcError = class extends RpcRequestError {
810
+ constructor(err) {
811
+ super(err, { humanMessage: "Method is not implemented." });
812
+ __publicField(this, "name", "MethodNotSupportedRpcError");
813
+ __publicField(this, "code", -32004);
814
+ }
815
+ };
816
+ var LimitExceededRpcError = class extends RpcRequestError {
817
+ constructor(err) {
818
+ super(err, { humanMessage: "Request exceeds defined limit." });
819
+ __publicField(this, "name", "LimitExceededRpcError");
820
+ __publicField(this, "code", -32005);
821
+ }
822
+ };
823
+ var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
824
+ constructor(err) {
825
+ super(err, {
826
+ humanMessage: "Version of JSON-RPC protocol is not supported."
827
+ });
828
+ __publicField(this, "name", "JsonRpcVersionUnsupportedError");
829
+ __publicField(this, "code", -32006);
830
+ }
831
+ };
832
+ var UnknownRpcError = class extends RequestError {
833
+ constructor(err) {
834
+ super(err, {
835
+ humanMessage: "An unknown RPC error occurred."
836
+ });
837
+ __publicField(this, "name", "UnknownRpcError");
838
+ }
839
+ };
840
+
841
+ // src/constants.ts
842
+ var etherUnits = {
843
+ gwei: 9,
844
+ wei: 18
845
+ };
846
+ var gweiUnits = {
847
+ ether: -9,
848
+ wei: 9
849
+ };
850
+ var weiUnits = {
851
+ ether: -18,
852
+ gwei: -9
853
+ };
854
+ var transactionType = {
855
+ "0x0": "legacy",
856
+ "0x1": "eip2930",
857
+ "0x2": "eip1559"
858
+ };
859
+
860
+ // src/utils/formatters/transaction.ts
861
+ function formatTransaction(transaction) {
862
+ const transaction_ = {
863
+ ...transaction,
864
+ blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
865
+ gas: transaction.gas ? BigInt(transaction.gas) : void 0,
866
+ gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
867
+ maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
868
+ maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
869
+ nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
870
+ transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
871
+ type: transaction.type ? transactionType[transaction.type] : void 0,
872
+ value: transaction.value ? BigInt(transaction.value) : void 0,
873
+ v: transaction.v ? BigInt(transaction.v) : void 0
874
+ };
875
+ if (transaction_.type === "legacy") {
876
+ delete transaction_["accessList"];
877
+ delete transaction_["maxFeePerGas"];
878
+ delete transaction_["maxPriorityFeePerGas"];
879
+ }
880
+ if (transaction_.type === "eip2930") {
881
+ delete transaction_["maxFeePerGas"];
882
+ delete transaction_["maxPriorityFeePerGas"];
883
+ }
884
+ return transaction_;
885
+ }
886
+
887
+ // src/utils/formatters/block.ts
888
+ function formatBlock(block) {
889
+ const transactions = block.transactions?.map((transaction) => {
890
+ if (typeof transaction === "string")
891
+ return transaction;
892
+ return formatTransaction(transaction);
893
+ });
894
+ return {
895
+ ...block,
896
+ baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
897
+ difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
898
+ gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
899
+ gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
900
+ number: block.number ? BigInt(block.number) : null,
901
+ size: block.size ? BigInt(block.size) : void 0,
902
+ timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
903
+ transactions,
904
+ totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
905
+ };
906
+ }
907
+
908
+ // src/utils/formatters/feeHistory.ts
909
+ function formatFeeHistory(feeHistory) {
910
+ return {
911
+ baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),
912
+ gasUsedRatio: feeHistory.gasUsedRatio,
913
+ oldestBlock: BigInt(feeHistory.oldestBlock),
914
+ reward: feeHistory.reward?.map(
915
+ (reward) => reward.map((value) => BigInt(value))
916
+ )
917
+ };
918
+ }
919
+
920
+ // src/utils/formatters/format.ts
921
+ function format3(data, { formatter }) {
922
+ return formatter(data);
923
+ }
924
+
925
+ // src/utils/formatters/log.ts
926
+ function formatLog(log) {
927
+ return {
928
+ ...log,
929
+ blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
930
+ logIndex: log.logIndex ? BigInt(log.logIndex) : null,
931
+ transactionIndex: log.transactionIndex ? BigInt(log.transactionIndex) : null
932
+ };
933
+ }
934
+
935
+ // src/utils/formatters/transactionReceipt.ts
936
+ var statuses = {
937
+ "0x0": "reverted",
938
+ "0x1": "success"
939
+ };
940
+ function formatTransactionReceipt(transactionReceipt) {
941
+ return {
942
+ ...transactionReceipt,
943
+ blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null,
944
+ cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
945
+ effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
946
+ gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
947
+ logs: transactionReceipt.logs ? transactionReceipt.logs.map(formatLog) : null,
948
+ transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
949
+ status: transactionReceipt.status ? statuses[transactionReceipt.status] : null,
950
+ type: transactionReceipt.type ? transactionType[transactionReceipt.type] : null
951
+ };
952
+ }
953
+
954
+ // src/utils/formatters/transactionRequest.ts
955
+ function formatTransactionRequest(transactionRequest) {
956
+ return {
957
+ ...transactionRequest,
958
+ gas: typeof transactionRequest.gas !== "undefined" ? numberToHex(transactionRequest.gas) : void 0,
959
+ gasPrice: typeof transactionRequest.gasPrice !== "undefined" ? numberToHex(transactionRequest.gasPrice) : void 0,
960
+ maxFeePerGas: typeof transactionRequest.maxFeePerGas !== "undefined" ? numberToHex(transactionRequest.maxFeePerGas) : void 0,
961
+ maxPriorityFeePerGas: typeof transactionRequest.maxPriorityFeePerGas !== "undefined" ? numberToHex(transactionRequest.maxPriorityFeePerGas) : void 0,
962
+ nonce: typeof transactionRequest.nonce !== "undefined" ? numberToHex(transactionRequest.nonce) : void 0,
963
+ value: typeof transactionRequest.value !== "undefined" ? numberToHex(transactionRequest.value) : void 0
964
+ };
965
+ }
966
+
967
+ // src/utils/promise/withCache.ts
968
+ var promiseCache = /* @__PURE__ */ new Map();
969
+ var responseCache = /* @__PURE__ */ new Map();
970
+ function getCache(cacheKey) {
971
+ const buildCache = (cacheKey2, cache) => ({
972
+ clear: () => cache.delete(cacheKey2),
973
+ get: () => cache.get(cacheKey2),
974
+ set: (data) => cache.set(cacheKey2, data)
975
+ });
976
+ const promise = buildCache(cacheKey, promiseCache);
977
+ const response = buildCache(
978
+ cacheKey,
979
+ responseCache
980
+ );
981
+ return {
982
+ clear: () => {
983
+ promise.clear();
984
+ response.clear();
985
+ },
986
+ promise,
987
+ response
988
+ };
989
+ }
990
+ async function withCache(fn, { cacheKey, maxAge = Infinity }) {
991
+ const cache = getCache(cacheKey);
992
+ const response = cache.response.get();
993
+ if (response && maxAge > 0) {
994
+ const age = new Date().getTime() - response.created.getTime();
995
+ if (age < maxAge)
996
+ return response.data;
997
+ }
998
+ let promise = cache.promise.get();
999
+ if (!promise) {
1000
+ promise = fn();
1001
+ cache.promise.set(promise);
1002
+ }
1003
+ const data = await promise;
1004
+ cache.promise.clear();
1005
+ cache.response.set({ created: new Date(), data });
1006
+ return data;
1007
+ }
1008
+
1009
+ // src/utils/wait.ts
1010
+ async function wait(time) {
1011
+ return new Promise((res) => setTimeout(res, time));
1012
+ }
1013
+
1014
+ // src/utils/promise/withRetry.ts
1015
+ function withRetry(fn, {
1016
+ delay: delay_ = 100,
1017
+ retryCount = 2,
1018
+ shouldRetryOnResponse = () => false,
1019
+ shouldRetryOnError = () => false
1020
+ } = {}) {
1021
+ return new Promise((resolve, reject) => {
1022
+ const attemptRetry = async ({ count = 0 } = {}) => {
1023
+ const retry = async ({ data } = {}) => {
1024
+ const delay = typeof delay_ === "function" ? delay_({ count, data }) : delay_;
1025
+ if (delay)
1026
+ await wait(delay);
1027
+ attemptRetry({ count: count + 1 });
1028
+ };
1029
+ try {
1030
+ const data = await fn();
1031
+ if (count < retryCount && await shouldRetryOnResponse({ count, data }))
1032
+ return retry({ data });
1033
+ resolve(data);
1034
+ } catch (err) {
1035
+ if (count < retryCount && await shouldRetryOnError({ count, error: err }))
1036
+ return retry();
1037
+ reject(err);
1038
+ }
1039
+ };
1040
+ attemptRetry();
1041
+ });
1042
+ }
1043
+
1044
+ // src/utils/promise/withTimeout.ts
1045
+ function withTimeout(fn, {
1046
+ errorInstance,
1047
+ timeout,
1048
+ signal
1049
+ }) {
1050
+ return new Promise((resolve, reject) => {
1051
+ ;
1052
+ (async () => {
1053
+ let timeoutId;
1054
+ try {
1055
+ const controller = new AbortController();
1056
+ if (timeout > 0) {
1057
+ timeoutId = setTimeout(() => {
1058
+ if (signal) {
1059
+ controller.abort();
1060
+ } else {
1061
+ reject(errorInstance);
1062
+ }
1063
+ }, timeout);
1064
+ }
1065
+ resolve(await fn({ signal: controller?.signal }));
1066
+ } catch (err) {
1067
+ if (err.name === "AbortError")
1068
+ reject(errorInstance);
1069
+ reject(err);
1070
+ } finally {
1071
+ clearTimeout(timeoutId);
1072
+ }
1073
+ })();
1074
+ });
1075
+ }
1076
+
1077
+ // src/utils/rpc.ts
1078
+ var id = 0;
1079
+ async function http(url, {
1080
+ body,
1081
+ retryDelay = 100,
1082
+ retryCount = 2,
1083
+ timeout = 0
1084
+ }) {
1085
+ const response = await withRetry(
1086
+ () => withTimeout(
1087
+ async ({ signal }) => {
1088
+ const response2 = await fetch(url, {
1089
+ headers: {
1090
+ "Content-Type": "application/json"
1091
+ },
1092
+ method: "POST",
1093
+ body: JSON.stringify({ jsonrpc: "2.0", id: id++, ...body }),
1094
+ signal: timeout > 0 ? signal : void 0
1095
+ });
1096
+ return response2;
1097
+ },
1098
+ {
1099
+ errorInstance: new TimeoutError({ body, url }),
1100
+ timeout,
1101
+ signal: true
1102
+ }
1103
+ ),
1104
+ {
1105
+ delay: ({ count, data: data2 }) => {
1106
+ const retryAfter = data2?.headers.get("Retry-After");
1107
+ if (retryAfter?.match(/\d/))
1108
+ return parseInt(retryAfter) * 1e3;
1109
+ return ~~((Math.random() + 0.5) * (1 << count)) * retryDelay;
1110
+ },
1111
+ retryCount,
1112
+ shouldRetryOnResponse: async ({ data: data2 }) => {
1113
+ if (data2.status >= 500)
1114
+ return true;
1115
+ if ([408, 413, 429].includes(data2.status))
1116
+ return true;
1117
+ return false;
1118
+ }
1119
+ }
1120
+ );
1121
+ let data;
1122
+ if (response.headers.get("Content-Type")?.startsWith("application/json")) {
1123
+ data = await response.json();
1124
+ } else {
1125
+ data = await response.text();
1126
+ }
1127
+ if (!response.ok) {
1128
+ throw new HttpRequestError({
1129
+ body,
1130
+ details: JSON.stringify(data.error) || response.statusText,
1131
+ status: response.status,
1132
+ url
1133
+ });
1134
+ }
1135
+ if (data.error) {
1136
+ throw new RpcError({ body, error: data.error, url });
1137
+ }
1138
+ return data;
1139
+ }
1140
+ var sockets = /* @__PURE__ */ new Map();
1141
+ async function getSocket(url_) {
1142
+ const url = new URL(url_);
1143
+ const urlKey = url.toString();
1144
+ let socket = sockets.get(urlKey);
1145
+ if (socket)
1146
+ return socket;
1147
+ const webSocket2 = new WebSocket(url);
1148
+ const requests = /* @__PURE__ */ new Map();
1149
+ const subscriptions = /* @__PURE__ */ new Map();
1150
+ const onMessage = ({ data }) => {
1151
+ const message = JSON.parse(data);
1152
+ const isSubscription = message.method === "eth_subscription";
1153
+ const id2 = isSubscription ? message.params.subscription : message.id;
1154
+ const cache = isSubscription ? subscriptions : requests;
1155
+ const callback = cache.get(id2);
1156
+ if (callback)
1157
+ callback({ data });
1158
+ if (!isSubscription)
1159
+ cache.delete(id2);
1160
+ };
1161
+ const onClose = () => {
1162
+ sockets.delete(urlKey);
1163
+ webSocket2.removeEventListener("close", onClose);
1164
+ webSocket2.removeEventListener("message", onMessage);
1165
+ };
1166
+ webSocket2.addEventListener("close", onClose);
1167
+ webSocket2.addEventListener("message", onMessage);
1168
+ if (webSocket2.readyState === WebSocket.CONNECTING) {
1169
+ await new Promise((resolve, reject) => {
1170
+ if (!webSocket2)
1171
+ return;
1172
+ webSocket2.onopen = resolve;
1173
+ webSocket2.onerror = reject;
1174
+ });
1175
+ }
1176
+ socket = Object.assign(webSocket2, {
1177
+ requests,
1178
+ subscriptions
1179
+ });
1180
+ sockets.set(urlKey, socket);
1181
+ return socket;
1182
+ }
1183
+ function webSocket(socket, {
1184
+ body,
1185
+ onData,
1186
+ onError
1187
+ }) {
1188
+ if (socket.readyState === socket.CLOSED || socket.readyState === socket.CLOSING)
1189
+ throw new WebSocketRequestError({
1190
+ body,
1191
+ url: socket.url,
1192
+ details: "Socket is closed."
1193
+ });
1194
+ const id_ = id++;
1195
+ const callback = ({ data }) => {
1196
+ const message = JSON.parse(data);
1197
+ if (typeof message.id === "number" && id_ !== message.id)
1198
+ return;
1199
+ if (message.error) {
1200
+ onError?.(new RpcError({ body, error: message.error, url: socket.url }));
1201
+ } else {
1202
+ onData?.(message);
1203
+ }
1204
+ if (body.method === "eth_subscribe" && typeof message.result === "string") {
1205
+ socket.subscriptions.set(message.result, callback);
1206
+ }
1207
+ if (body.method === "eth_unsubscribe") {
1208
+ socket.subscriptions.delete(body.params?.[0]);
1209
+ }
1210
+ };
1211
+ socket.requests.set(id_, callback);
1212
+ socket.send(JSON.stringify({ jsonrpc: "2.0", ...body, id: id_ }));
1213
+ return socket;
1214
+ }
1215
+ async function webSocketAsync(socket, {
1216
+ body,
1217
+ timeout = 0
1218
+ }) {
1219
+ return withTimeout(
1220
+ () => new Promise(
1221
+ (onData, onError) => rpc.webSocket(socket, {
1222
+ body,
1223
+ onData,
1224
+ onError
1225
+ })
1226
+ ),
1227
+ {
1228
+ errorInstance: new TimeoutError({ body, url: socket.url }),
1229
+ timeout
1230
+ }
1231
+ );
1232
+ }
1233
+ var rpc = {
1234
+ http,
1235
+ webSocket,
1236
+ webSocketAsync
1237
+ };
1238
+ var HttpRequestError = class extends BaseError {
1239
+ constructor({
1240
+ body,
1241
+ details,
1242
+ status,
1243
+ url
1244
+ }) {
1245
+ super(
1246
+ [
1247
+ "HTTP request failed.",
1248
+ "",
1249
+ `Status: ${status}`,
1250
+ `URL: ${url}`,
1251
+ `Request body: ${JSON.stringify(body)}`
1252
+ ].join("\n"),
1253
+ {
1254
+ details
1255
+ }
1256
+ );
1257
+ __publicField(this, "name", "HttpRequestError");
1258
+ __publicField(this, "status");
1259
+ this.status = status;
1260
+ }
1261
+ };
1262
+ var WebSocketRequestError = class extends BaseError {
1263
+ constructor({
1264
+ body,
1265
+ details,
1266
+ url
1267
+ }) {
1268
+ super(
1269
+ [
1270
+ "WebSocket request failed.",
1271
+ "",
1272
+ `URL: ${url}`,
1273
+ `Request body: ${JSON.stringify(body)}`
1274
+ ].join("\n"),
1275
+ {
1276
+ details
1277
+ }
1278
+ );
1279
+ __publicField(this, "name", "WebSocketRequestError");
1280
+ }
1281
+ };
1282
+ var RpcError = class extends BaseError {
1283
+ constructor({
1284
+ body,
1285
+ error,
1286
+ url
1287
+ }) {
1288
+ super(
1289
+ [
1290
+ "RPC Request failed.",
1291
+ "",
1292
+ `URL: ${url}`,
1293
+ `Request body: ${JSON.stringify(body)}`
1294
+ ].join("\n"),
1295
+ {
1296
+ cause: error,
1297
+ details: error.message
1298
+ }
1299
+ );
1300
+ __publicField(this, "code");
1301
+ __publicField(this, "name", "RpcError");
1302
+ this.code = error.code;
1303
+ }
1304
+ };
1305
+ var TimeoutError = class extends BaseError {
1306
+ constructor({
1307
+ body,
1308
+ url
1309
+ }) {
1310
+ super(
1311
+ [
1312
+ "The request took too long to respond.",
1313
+ "",
1314
+ `URL: ${url}`,
1315
+ `Request body: ${JSON.stringify(body)}`
1316
+ ].join("\n"),
1317
+ {
1318
+ details: "The request timed out."
1319
+ }
1320
+ );
1321
+ __publicField(this, "name", "TimeoutError");
1322
+ }
1323
+ };
1324
+
1325
+ // src/utils/unit/formatUnit.ts
1326
+ function formatUnit(value, decimals) {
1327
+ let display = value.toString();
1328
+ const negative = display.startsWith("-");
1329
+ if (negative)
1330
+ display = display.slice(1);
1331
+ let [integer, fraction] = [
1332
+ display.slice(0, display.length - decimals),
1333
+ display.slice(display.length - decimals)
1334
+ ];
1335
+ fraction = fraction.padStart(decimals, "0");
1336
+ fraction = fraction.replace(/(0+)$/, "");
1337
+ return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
1338
+ }
1339
+
1340
+ // src/utils/unit/formatEther.ts
1341
+ function formatEther(wei, unit = "wei") {
1342
+ return formatUnit(wei, etherUnits[unit]);
1343
+ }
1344
+
1345
+ // src/utils/unit/formatGwei.ts
1346
+ function formatGwei(wei, unit = "wei") {
1347
+ return formatUnit(wei, gweiUnits[unit]);
1348
+ }
1349
+
1350
+ // src/utils/unit/parseUnit.ts
1351
+ function parseUnit(value, decimals) {
1352
+ let [integer, fraction = "0"] = value.split(".");
1353
+ const negative = integer.startsWith("-");
1354
+ if (negative)
1355
+ integer = integer.slice(1);
1356
+ fraction = fraction.replace(/(0+)$/, "");
1357
+ if (decimals === 0) {
1358
+ integer = `${Math.round(Number(`${integer}.${fraction}`))}`;
1359
+ fraction = "";
1360
+ } else if (fraction.length > decimals) {
1361
+ const [before, after] = [
1362
+ fraction.slice(0, decimals),
1363
+ fraction.slice(decimals)
1364
+ ];
1365
+ fraction = `${/^0+$/.test(before) ? before.slice(0, before.length - 1) : ""}${Math.round(Number(`${before}.${after}`))}`;
1366
+ } else {
1367
+ fraction = fraction.padEnd(decimals, "0");
1368
+ }
1369
+ return BigInt(`${negative ? "-" : ""}${integer}${fraction}`);
1370
+ }
1371
+
1372
+ // src/utils/unit/parseEther.ts
1373
+ function parseEther(ether, unit = "wei") {
1374
+ return parseUnit(ether, etherUnits[unit]);
1375
+ }
1376
+
1377
+ // src/utils/unit/parseGwei.ts
1378
+ function parseGwei(ether, unit = "wei") {
1379
+ return parseUnit(ether, gweiUnits[unit]);
1380
+ }
1381
+
1382
+ export {
1383
+ __publicField,
1384
+ BaseError,
1385
+ isBytes,
1386
+ isHex,
1387
+ pad,
1388
+ padHex,
1389
+ padBytes,
1390
+ trim,
1391
+ size,
1392
+ slice,
1393
+ sliceBytes,
1394
+ sliceHex,
1395
+ boolToHex,
1396
+ bytesToHex,
1397
+ encodeHex,
1398
+ numberToHex,
1399
+ stringToHex,
1400
+ boolToBytes,
1401
+ encodeBytes,
1402
+ hexToBytes,
1403
+ numberToBytes,
1404
+ stringToBytes,
1405
+ encodeRlp,
1406
+ decodeHex,
1407
+ hexToBigInt,
1408
+ hexToBool,
1409
+ hexToNumber,
1410
+ hexToString,
1411
+ decodeBytes,
1412
+ bytesToBigint,
1413
+ bytesToBool,
1414
+ bytesToNumber,
1415
+ bytesToString,
1416
+ decodeRlp,
1417
+ extractFunctionName,
1418
+ extractFunctionParams,
1419
+ extractFunctionType,
1420
+ keccak256,
1421
+ getEventSignature,
1422
+ getFunctionSignature,
1423
+ checksumAddress,
1424
+ getAddress,
1425
+ getContractAddress,
1426
+ getCreateAddress,
1427
+ getCreate2Address,
1428
+ isAddress,
1429
+ isAddressEqual,
1430
+ buildRequest,
1431
+ RpcRequestError,
1432
+ ParseRpcError,
1433
+ InvalidRequestRpcError,
1434
+ MethodNotFoundRpcError,
1435
+ InvalidParamsRpcError,
1436
+ InternalRpcError,
1437
+ InvalidInputRpcError,
1438
+ ResourceNotFoundRpcError,
1439
+ ResourceUnavailableRpcError,
1440
+ TransactionRejectedRpcError,
1441
+ MethodNotSupportedRpcError,
1442
+ LimitExceededRpcError,
1443
+ JsonRpcVersionUnsupportedError,
1444
+ etherUnits,
1445
+ gweiUnits,
1446
+ weiUnits,
1447
+ transactionType,
1448
+ formatTransaction,
1449
+ formatBlock,
1450
+ formatFeeHistory,
1451
+ format3 as format,
1452
+ formatLog,
1453
+ formatTransactionReceipt,
1454
+ formatTransactionRequest,
1455
+ getCache,
1456
+ withCache,
1457
+ wait,
1458
+ getSocket,
1459
+ rpc,
1460
+ HttpRequestError,
1461
+ RpcError,
1462
+ TimeoutError,
1463
+ formatUnit,
1464
+ formatEther,
1465
+ formatGwei,
1466
+ parseUnit,
1467
+ parseEther,
1468
+ parseGwei
1469
+ };