essential-eth 0.11.2 → 0.13.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.
package/dist/index.js CHANGED
@@ -1,354 +1,9 @@
1
- // src/classes/utils/encode-decode-transaction.ts
2
- import { Keccak as Keccak2 } from "sha3";
3
-
4
- // src/shared/tiny-big/tiny-big.ts
5
- import Big from "big.js";
6
-
7
- // src/classes/utils/hex-to-decimal.ts
8
- function hexToDecimal(hex) {
9
- return BigInt(hex).toString();
10
- }
11
-
12
- // src/shared/tiny-big/helpers.ts
13
- function stripTrailingZeroes(numberString) {
14
- const isNegative = numberString.startsWith("-");
15
- numberString = numberString.replace("-", "");
16
- numberString = numberString.replace(
17
- /\.0*$/g,
18
- ""
19
- );
20
- numberString = numberString.replace(/^0+/, "");
21
- if (numberString.includes(".")) {
22
- numberString = numberString.replace(/0+$/, "");
23
- }
24
- if (numberString.startsWith(".")) {
25
- numberString = `0${numberString}`;
26
- }
27
- return `${isNegative ? "-" : ""}${numberString}`;
28
- }
29
- function scientificStrToDecimalStr(scientificString) {
30
- if (!scientificString.match(
31
- /e/i
32
- /* lowercase and uppercase E */
33
- )) {
34
- return stripTrailingZeroes(scientificString);
35
- }
36
- let [base, power] = scientificString.split(
37
- /e/i
38
- );
39
- const isNegative = Number(base) < 0;
40
- base = base.replace("-", "");
41
- base = stripTrailingZeroes(base);
42
- const [wholeNumber, fraction = ""] = base.split(".");
43
- if (Number(power) === 0) {
44
- return `${isNegative ? "-" : ""}${stripTrailingZeroes(base)}`;
45
- } else {
46
- const includesDecimal = base.includes(".");
47
- if (!includesDecimal) {
48
- base = `${base}.`;
49
- }
50
- base = base.replace(".", "");
51
- const baseLength = base.length;
52
- let splitPaddedNumber;
53
- if (Number(power) < 0) {
54
- if (wholeNumber.length < Math.abs(Number(power))) {
55
- base = base.padStart(
56
- baseLength + Math.abs(Number(power)) - wholeNumber.length,
57
- "0"
58
- );
59
- }
60
- splitPaddedNumber = base.split("");
61
- if (wholeNumber.length < Math.abs(Number(power))) {
62
- splitPaddedNumber = [".", ...splitPaddedNumber];
63
- } else {
64
- splitPaddedNumber.splice(
65
- splitPaddedNumber.length - Math.abs(Number(power)),
66
- 0,
67
- "."
68
- );
69
- }
70
- } else {
71
- if (fraction.length < Math.abs(Number(power))) {
72
- base = base.padEnd(
73
- baseLength + Math.abs(Number(power)) - fraction.length,
74
- "0"
75
- );
76
- }
77
- splitPaddedNumber = base.split("");
78
- if (fraction.length > Math.abs(Number(power))) {
79
- splitPaddedNumber.splice(
80
- splitPaddedNumber.length - Math.abs(Number(power)),
81
- 0,
82
- "."
83
- );
84
- }
85
- }
86
- const toReturn = stripTrailingZeroes(splitPaddedNumber.join(""));
87
- return `${isNegative ? "-" : ""}${toReturn}`;
88
- }
89
- }
90
-
91
- // src/shared/tiny-big/tiny-big.ts
92
- var TinyBig = class extends Big {
93
- constructor(value) {
94
- if (typeof value === "string" && value.startsWith("0x")) {
95
- value = hexToDecimal(value);
96
- }
97
- super(value);
98
- }
99
- /**
100
- * Used anytime you're passing in "value" to ethers or web3
101
- * For now, TypeScript will complain that `TinyBig` is not a `BigNumberish`. You can // @ts-ignore or call this
102
- *
103
- * @returns the TinyBig represented as a hex string
104
- * @example
105
- * ```javascript
106
- * tinyBig(293).toHexString();
107
- * // '0x125'
108
- * ```
109
- * @example
110
- * ```javascript
111
- * tinyBig(681365874).toHexString();
112
- * // '0x289cd172'
113
- */
114
- toHexString() {
115
- return `0x${BigInt(this.toString()).toString(16)}`;
116
- }
117
- toNumber() {
118
- return Number(scientificStrToDecimalStr(super.toString()));
119
- }
120
- toString() {
121
- if (this.toNumber() === 0) {
122
- return "0";
123
- }
124
- return scientificStrToDecimalStr(super.toString());
125
- }
126
- /**
127
- * Eithers pads or shortens a string to a specified length
128
- *
129
- * @param str the string to pad or chop
130
- * @param padChar the character to pad the string with
131
- * @param length the desired length of the given string
132
- * @returns a string of the desired length, either padded with the specified padChar or with the beginning of the string chopped off
133
- * @example
134
- * ```javascript
135
- * padAndChop('essential-eth', 'a', 8);
136
- * // 'tial-eth'
137
- * ```
138
- * @example
139
- * ```javascript
140
- * padAndChop('essential-eth', 'A', 20);
141
- * // 'AAAAAAAessential-eth'
142
- * ```
143
- */
144
- padAndChop = (str, padChar, length) => {
145
- return (Array(length).fill(padChar).join("") + str).slice(length * -1);
146
- };
147
- toTwos(bitCount) {
148
- let binaryStr;
149
- if (this.gte(0)) {
150
- const twosComp = this.toNumber().toString(2);
151
- binaryStr = this.padAndChop(twosComp, "0", bitCount || twosComp.length);
152
- } else {
153
- binaryStr = this.plus(Math.pow(2, bitCount)).toNumber().toString(2);
154
- if (Number(binaryStr) < 0) {
155
- throw new Error("Cannot calculate twos complement");
156
- }
157
- }
158
- const binary = `0b${binaryStr}`;
159
- const decimal = Number(binary);
160
- return tinyBig(decimal);
161
- }
162
- };
163
- function tinyBig(value) {
164
- return new TinyBig(value);
165
- }
166
-
167
- // src/utils/to-checksum-address.ts
168
- import { Keccak } from "sha3";
169
-
170
- // src/shared/validate-type.ts
171
- var validateType = (value, allowedTypes) => {
172
- if (!allowedTypes.includes(typeof value)) {
173
- throw new Error(
174
- `${allowedTypes.join(" or ")} required. Received ${typeof value}`
175
- );
176
- }
177
- };
178
-
179
- // src/utils/to-checksum-address.ts
180
- function toChecksumAddress(address) {
181
- validateType(address, ["string"]);
182
- if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
183
- throw new Error(`Invalid Ethereum address "${address}"`);
184
- }
185
- const _address = address.toLowerCase().replace(/^0x/i, "");
186
- const keccak = new Keccak(256);
187
- const addressHash = keccak.update(_address).digest("hex").replace(/^0x/i, "");
188
- let checksumAddress = "0x";
189
- for (let i = 0; i < _address.length; i++) {
190
- if (parseInt(addressHash[i], 16) > 7) {
191
- checksumAddress += _address[i].toUpperCase();
192
- } else {
193
- checksumAddress += _address[i];
194
- }
195
- }
196
- if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && checksumAddress !== address) {
197
- throw new Error(`Invalid Checksum address for "${address}"`);
198
- }
199
- return checksumAddress;
200
- }
201
-
202
- // src/classes/utils/encode-decode-transaction.ts
203
- var hexFalse = "0".repeat(64);
204
- var hexTrue = "0".repeat(63) + "1";
205
- function hexToUtf8(hex) {
206
- let str = "";
207
- let i = 0;
208
- const l = hex.length;
209
- if (hex.substring(0, 2) === "0x") {
210
- i = 2;
211
- }
212
- for (; i < l; i += 2) {
213
- const code = parseInt(hex.substr(i, 2), 16);
214
- if (code === 0) continue;
215
- str += String.fromCharCode(code);
216
- }
217
- try {
218
- return decodeURIComponent(escape(str));
219
- } catch (e) {
220
- return str;
221
- }
222
- }
223
- function expandType(type) {
224
- if (type === "uint[]") {
225
- return "uint256[]";
226
- }
227
- if (type === "int[]") {
228
- return "int256[]";
229
- }
230
- return type;
231
- }
232
- function encodeData(jsonABIArgument, args) {
233
- const hash = new Keccak2(256);
234
- const functionString = `${jsonABIArgument.name}(${jsonABIArgument.inputs.map(
235
- (input) => expandType(input.type)
236
- )})`;
237
- const functionHash = hash.update(functionString).digest("hex");
238
- const jsonABIInputsLength = jsonABIArgument.inputs.length;
239
- let shouldValidateInputLength = true;
240
- if (jsonABIArgument.inputs.find((input) => input.type.includes("["))) {
241
- shouldValidateInputLength = false;
242
- }
243
- if (shouldValidateInputLength && args.length !== jsonABIInputsLength) {
244
- throw new Error(
245
- `args inputs of "${args.length}" does not match expected length of "${jsonABIArgument.inputs.length}"`
246
- );
247
- }
248
- const argsWithTypes = (jsonABIArgument.inputs || []).reduce(
249
- (acc, input, i) => {
250
- if (input.type.includes("[")) {
251
- const basicType = /([^[]*)\[.*$/g.exec(input.type)?.[1];
252
- args.forEach((arg) => {
253
- acc = acc.concat([[arg, basicType]]);
254
- });
255
- return acc;
256
- } else {
257
- return acc.concat([[args[i], input.type]]);
258
- }
259
- },
260
- []
261
- );
262
- const encodedArgs = argsWithTypes.map(([arg, inputType]) => {
263
- let rawArg = arg;
264
- switch (inputType) {
265
- case "bool":
266
- return arg ? hexTrue : hexFalse;
267
- case "address":
268
- rawArg = arg.replace(/^0x/g, "").toLowerCase();
269
- break;
270
- default:
271
- if (inputType.startsWith("bytes")) {
272
- if (Array.isArray(arg)) {
273
- throw new Error(
274
- `essential-eth does not yet support "${inputType}[]" inputs. Make a PR today!"`
275
- );
276
- }
277
- const argEncoded2 = BigInt(arg).toString(16);
278
- const paddedEncodedArg2 = argEncoded2.padStart(64, "0");
279
- return paddedEncodedArg2;
280
- } else if (inputType === "uint256") {
281
- const argEncoded2 = BigInt(arg).toString(16);
282
- const paddedEncodedArg2 = argEncoded2.padStart(64, "0");
283
- return paddedEncodedArg2;
284
- } else if (inputType.startsWith("uint")) {
285
- break;
286
- } else {
287
- throw new Error(
288
- `essential-eth does not yet support "${inputType}" inputs. Make a PR today!"`
289
- );
290
- }
291
- }
292
- const argEncoded = rawArg.toString(16);
293
- const paddedEncodedArg = argEncoded.padStart(64, "0");
294
- return paddedEncodedArg;
295
- });
296
- const functionEncoded = functionHash.slice(0, 8);
297
- const data = `0x${functionEncoded}${encodedArgs.join("")}`;
298
- return data;
299
- }
300
- function decodeRPCResponse(jsonABIArgument, nodeResponse) {
301
- const rawOutputs = jsonABIArgument.outputs || [];
302
- const slicedResponse = nodeResponse.slice(2);
303
- if (rawOutputs.length === 1 && rawOutputs[0].type === "string") {
304
- const [hexOffset, responseData] = [
305
- slicedResponse.slice(0, 64),
306
- slicedResponse.slice(64)
307
- ];
308
- const decimalOffset = Number(hexToDecimal(`0x${hexOffset}`));
309
- const hexLength = responseData.slice(0, decimalOffset * 2);
310
- const decimalLength = Number(hexToDecimal(`0x${hexLength}`));
311
- const hexToDecode = responseData.slice(
312
- decimalOffset * 2,
313
- decimalOffset * 2 + decimalLength * 2
314
- );
315
- return hexToUtf8(hexToDecode);
316
- }
317
- const encodedOutputs = slicedResponse.match(/.{1,64}/g) || [];
318
- if (rawOutputs.length === 1 && rawOutputs[0].type === "address[]") {
319
- const unformattedAddresses = encodedOutputs.slice(2);
320
- return unformattedAddresses.map((unformattedAddress) => {
321
- return toChecksumAddress(`0x${unformattedAddress.slice(24)}`);
322
- });
323
- }
324
- if (rawOutputs?.length === 1 && rawOutputs[0].type === "uint256[]") {
325
- const outputs2 = encodedOutputs.slice(2);
326
- return outputs2.map((output) => {
327
- return tinyBig(hexToDecimal(`0x${output}`));
328
- });
329
- }
330
- const outputs = encodedOutputs.map((output, i) => {
331
- const outputType = rawOutputs[i].type;
332
- switch (outputType) {
333
- case "bool":
334
- return output === hexTrue;
335
- case "address":
336
- return toChecksumAddress(`0x${output.slice(24)}`);
337
- case "uint256":
338
- case "uint120":
339
- return tinyBig(hexToDecimal(`0x${output}`));
340
- case "bytes32":
341
- return `0x${output}`;
342
- case "uint8":
343
- return Number(hexToDecimal(`0x${output}`));
344
- default:
345
- throw new Error(
346
- `essential-eth does not yet support "${outputType}" outputs. Make a PR today!"`
347
- );
348
- }
349
- });
350
- return outputs.length === 1 ? outputs[0] : outputs;
351
- }
1
+ import { logger, encodeData, decodeRPCResponse, toChecksumAddress, hexlify } from './chunk-C4VOKUKQ.js';
2
+ export { arrayify, computeAddress, computePublicKey, concat, hashMessage, hexConcat, hexDataLength, hexDataSlice, hexStripZeros, hexValue, hexZeroPad, hexlify, isAddress, isBytes, isBytesLike, isHexString, keccak256, pack, solidityKeccak256, splitSignature, stripZeros, toChecksumAddress, toUtf8Bytes, zeroPad } from './chunk-C4VOKUKQ.js';
3
+ import { hexToDecimal, tinyBig, TinyBig } from './chunk-UXC5R4JE.js';
4
+ export { TinyBig, etherToGwei, etherToWei, gweiToEther, tinyBig, weiToEther } from './chunk-UXC5R4JE.js';
5
+ import unfetch from 'isomorphic-unfetch';
6
+ import Big from 'big.js';
352
7
 
353
8
  // src/classes/Contract.ts
354
9
  function estimateGas(txnData) {
@@ -547,9 +202,6 @@ function cleanTransactionReceipt(transactionReceipt) {
547
202
  cleanedTransactionReceipt.byzantium = cleanedTransactionReceipt.blockNumber >= 437e4;
548
203
  return cleanedTransactionReceipt;
549
204
  }
550
-
551
- // src/classes/utils/fetchers.ts
552
- import unfetch from "isomorphic-unfetch";
553
205
  function buildFetchInit(body) {
554
206
  return {
555
207
  method: "POST",
@@ -586,290 +238,6 @@ function buildRPCPostBody(method, params) {
586
238
  params
587
239
  };
588
240
  }
589
-
590
- // src/classes/utils/prepare-transaction.ts
591
- import Big2 from "big.js";
592
-
593
- // src/logger/package-version.ts
594
- var version = "0.11.2";
595
-
596
- // src/logger/logger.ts
597
- var Logger = class {
598
- packageVersion;
599
- constructor() {
600
- this.packageVersion = version;
601
- }
602
- throwError(message, args) {
603
- const argsLength = Object.keys(args).length;
604
- throw new Error(
605
- `${message} (${Object.entries(args).map(
606
- ([key, value], index) => `${key}=${value}${index < argsLength - 1 && ", "}`
607
- )}, version=essential-eth@${this.packageVersion})`
608
- );
609
- }
610
- throwArgumentError(message, arg, value) {
611
- throw new Error(
612
- `${message} (argument="${arg}" value=${value}, version=essential-eth@${this.packageVersion})`
613
- );
614
- }
615
- checkSafeUint53(value, message = "value not safe") {
616
- if (typeof value !== "number") {
617
- return;
618
- }
619
- if (value < 0 || value >= 9007199254740991) {
620
- this.throwError(message, {
621
- operation: "checkSafeInteger",
622
- fault: "out-of-safe-range",
623
- value
624
- });
625
- }
626
- if (value % 1) {
627
- this.throwError(message, {
628
- operation: "checkSafeInteger",
629
- fault: "non-integer",
630
- value
631
- });
632
- }
633
- }
634
- };
635
- var logger = new Logger();
636
-
637
- // src/utils/bytes.ts
638
- function isHexable(value) {
639
- return !!value.toHexString;
640
- }
641
- function isBytesLike(value) {
642
- return isHexString(value) && !(value.length % 2) || isBytes(value);
643
- }
644
- function isInteger(value) {
645
- return typeof value === "number" && value == value && value % 1 === 0;
646
- }
647
- function isBytes(value) {
648
- if (value == null) {
649
- return false;
650
- }
651
- if (value.constructor === Uint8Array) {
652
- return true;
653
- }
654
- if (typeof value === "string") {
655
- return false;
656
- }
657
- if (!isInteger(value.length) || value.length < 0) {
658
- return false;
659
- }
660
- for (let i = 0; i < value.length; i++) {
661
- const v = value[i];
662
- if (!isInteger(v) || v < 0 || v >= 256) {
663
- return false;
664
- }
665
- }
666
- return true;
667
- }
668
- function arrayify(value, options) {
669
- if (!options) {
670
- options = {};
671
- }
672
- if (typeof value === "number") {
673
- logger.checkSafeUint53(value, "invalid arrayify value");
674
- const result = [];
675
- while (value) {
676
- result.unshift(value & 255);
677
- value = parseInt(String(value / 256));
678
- }
679
- if (result.length === 0) {
680
- result.push(0);
681
- }
682
- return new Uint8Array(result);
683
- }
684
- if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") {
685
- value = "0x" + value;
686
- }
687
- if (isHexable(value)) {
688
- value = value.toHexString();
689
- }
690
- if (isHexString(value)) {
691
- let hex = value.substring(2);
692
- if (hex.length % 2) {
693
- if (options.hexPad === "left") {
694
- hex = "0" + hex;
695
- } else if (options.hexPad === "right") {
696
- hex += "0";
697
- } else {
698
- logger.throwArgumentError("hex data is odd-length", "value", value);
699
- }
700
- }
701
- const result = [];
702
- for (let i = 0; i < hex.length; i += 2) {
703
- result.push(parseInt(hex.substring(i, i + 2), 16));
704
- }
705
- return new Uint8Array(result);
706
- }
707
- if (isBytes(value)) {
708
- return new Uint8Array(value);
709
- }
710
- return logger.throwArgumentError("invalid arrayify value", "value", value);
711
- }
712
- function concat(arrayOfBytesLike) {
713
- const objects = arrayOfBytesLike.map((item) => arrayify(item));
714
- const length = objects.reduce((accum, item) => accum + item.length, 0);
715
- const result = new Uint8Array(length);
716
- objects.reduce((offset, object) => {
717
- result.set(object, offset);
718
- return offset + object.length;
719
- }, 0);
720
- return result;
721
- }
722
- function stripZeros(value) {
723
- let result = arrayify(value);
724
- if (result.length === 0) {
725
- return result;
726
- }
727
- let start = 0;
728
- while (start < result.length && result[start] === 0) {
729
- start++;
730
- }
731
- if (start) {
732
- result = result.slice(start);
733
- }
734
- return result;
735
- }
736
- function zeroPad(value, length) {
737
- value = arrayify(value);
738
- if (value.length > length) {
739
- logger.throwArgumentError("value out of range", "value", value);
740
- }
741
- const result = new Uint8Array(length);
742
- result.set(value, length - value.length);
743
- return result;
744
- }
745
- function isHexString(value, length) {
746
- if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
747
- return false;
748
- }
749
- if (length && value.length !== 2 + 2 * length) {
750
- return false;
751
- }
752
- return true;
753
- }
754
- var HexCharacters = "0123456789abcdef";
755
- function hexlify(value, options) {
756
- if (!options) {
757
- options = {};
758
- }
759
- if (typeof value === "number") {
760
- logger.checkSafeUint53(value, "invalid hexlify value");
761
- let hex = "";
762
- while (value) {
763
- hex = HexCharacters[value & 15] + hex;
764
- value = Math.floor(value / 16);
765
- }
766
- if (hex.length) {
767
- if (hex.length % 2) {
768
- hex = "0" + hex;
769
- }
770
- return "0x" + hex;
771
- }
772
- return "0x00";
773
- }
774
- if (typeof value === "bigint") {
775
- value = value.toString(16);
776
- if (value.length % 2) {
777
- return "0x0" + value;
778
- }
779
- return "0x" + value;
780
- }
781
- if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") {
782
- value = "0x" + value;
783
- }
784
- if (isHexable(value)) {
785
- return value.toHexString();
786
- }
787
- if (isHexString(value)) {
788
- if (value.length % 2) {
789
- if (options.hexPad === "left") {
790
- value = "0x0" + value.substring(2);
791
- } else if (options.hexPad === "right") {
792
- value += "0";
793
- } else {
794
- logger.throwArgumentError("hex data is odd-length", "value", value);
795
- }
796
- }
797
- return value.toLowerCase();
798
- }
799
- if (isBytes(value)) {
800
- let result = "0x";
801
- for (let i = 0; i < value.length; i++) {
802
- const v = value[i];
803
- result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15];
804
- }
805
- return result;
806
- }
807
- return logger.throwArgumentError("invalid hexlify value", "value", value);
808
- }
809
- function hexDataLength(data) {
810
- if (typeof data !== "string") {
811
- data = hexlify(data);
812
- } else if (!isHexString(data) || data.length % 2) {
813
- return null;
814
- }
815
- return (data.length - 2) / 2;
816
- }
817
- function hexDataSlice(data, offset, endOffset) {
818
- if (typeof data !== "string") {
819
- data = hexlify(data);
820
- } else if (!isHexString(data) || data.length % 2) {
821
- logger.throwArgumentError("invalid hexData", "value", data);
822
- }
823
- offset = 2 + 2 * offset;
824
- if (endOffset != null) {
825
- return "0x" + data.substring(offset, 2 + 2 * endOffset);
826
- }
827
- return "0x" + data.substring(offset);
828
- }
829
- function hexConcat(items) {
830
- let result = "0x";
831
- items.forEach((item) => {
832
- result += hexlify(item).substring(2);
833
- });
834
- return result;
835
- }
836
- function hexValue(value) {
837
- const trimmed = hexStripZeros(hexlify(value, { hexPad: "left" }));
838
- if (trimmed === "0x") {
839
- return "0x0";
840
- }
841
- return trimmed;
842
- }
843
- function hexStripZeros(value) {
844
- if (typeof value !== "string") {
845
- value = hexlify(value);
846
- }
847
- if (!isHexString(value)) {
848
- logger.throwArgumentError("invalid hex string", "value", value);
849
- }
850
- value = value.substring(2);
851
- let offset = 0;
852
- while (offset < value.length && value[offset] === "0") {
853
- offset++;
854
- }
855
- return "0x" + value.substring(offset);
856
- }
857
- function hexZeroPad(value, length) {
858
- if (typeof value !== "string") {
859
- value = hexlify(value);
860
- } else if (!isHexString(value)) {
861
- logger.throwArgumentError("invalid hex string", "value", value);
862
- }
863
- if (value.length > 2 * length + 2) {
864
- logger.throwError("value out of range", { value, length });
865
- }
866
- while (value.length < 2 * length + 2) {
867
- value = "0x0" + value.substring(2);
868
- }
869
- return value;
870
- }
871
-
872
- // src/classes/utils/prepare-transaction.ts
873
241
  function prepareTransaction(transaction) {
874
242
  const preparedTransaction = {
875
243
  ...transaction
@@ -886,7 +254,7 @@ function prepareTransaction(transaction) {
886
254
  const value = transaction[key];
887
255
  if (value instanceof TinyBig) {
888
256
  preparedTransaction[key] = value.toHexString();
889
- } else if (value instanceof Big2) {
257
+ } else if (value instanceof Big) {
890
258
  preparedTransaction[key] = `0x${BigInt(value.toString()).toString(
891
259
  16
892
260
  )}`;
@@ -1573,380 +941,4 @@ var FallthroughProvider = class extends BaseProvider {
1573
941
  };
1574
942
  };
1575
943
 
1576
- // src/utils/compute-public-key.ts
1577
- import { Point } from "@noble/secp256k1";
1578
- function computePublicKey(privKey) {
1579
- privKey = hexlify(privKey).slice(2);
1580
- return "0x" + Point.fromPrivateKey(privKey).toHex();
1581
- }
1582
-
1583
- // src/utils/keccak256.ts
1584
- import { Keccak as Keccak3 } from "sha3";
1585
- function keccak256(data) {
1586
- let bufferableData;
1587
- if (typeof data === "string") {
1588
- bufferableData = Buffer.from(data.replace(/^0x/, ""), "hex");
1589
- } else {
1590
- bufferableData = Buffer.from(data);
1591
- }
1592
- const keccak = new Keccak3(256);
1593
- const addressHash = "0x" + keccak.update(bufferableData).digest("hex");
1594
- return addressHash;
1595
- }
1596
-
1597
- // src/utils/compute-address.ts
1598
- function computeAddress(key) {
1599
- if (!key.startsWith("0x04") && !key.startsWith("0x03") && !key.startsWith("0x02")) {
1600
- key = computePublicKey(key);
1601
- }
1602
- return toChecksumAddress(hexDataSlice(keccak256(hexDataSlice(key, 1)), 12));
1603
- }
1604
-
1605
- // src/utils/ether-to-gwei.ts
1606
- function etherToGwei(etherQuantity) {
1607
- validateType(etherQuantity, ["string", "number", "object"]);
1608
- const result = tinyBig(etherQuantity).times("1000000000");
1609
- return tinyBig(result);
1610
- }
1611
-
1612
- // src/utils/ether-to-wei.ts
1613
- function etherToWei(etherQuantity) {
1614
- validateType(etherQuantity, ["string", "number", "object"]);
1615
- const result = tinyBig(etherQuantity).times("1000000000000000000");
1616
- return tinyBig(result);
1617
- }
1618
-
1619
- // src/utils/gwei-to-ether.ts
1620
- function gweiToEther(gweiQuantity) {
1621
- validateType(gweiQuantity, ["string", "number", "object"]);
1622
- const result = tinyBig(gweiQuantity).div("1000000000");
1623
- return tinyBig(result);
1624
- }
1625
-
1626
- // src/utils/to-utf8-bytes.ts
1627
- function toUtf8Bytes(data) {
1628
- return new Uint8Array(Buffer.from(data));
1629
- }
1630
-
1631
- // src/utils/hash-message.ts
1632
- var messagePrefix = "Ethereum Signed Message:\n";
1633
- function hashMessage(message) {
1634
- if (typeof message === "string") {
1635
- message = toUtf8Bytes(message);
1636
- }
1637
- return keccak256(
1638
- concat([
1639
- toUtf8Bytes(messagePrefix),
1640
- toUtf8Bytes(String(message.length)),
1641
- message
1642
- ])
1643
- );
1644
- }
1645
-
1646
- // src/utils/is-address.ts
1647
- function isAddress(address) {
1648
- validateType(address, ["string"]);
1649
- try {
1650
- toChecksumAddress(address);
1651
- return true;
1652
- } catch (error) {
1653
- return false;
1654
- }
1655
- }
1656
-
1657
- // src/utils/solidity-keccak256.ts
1658
- import { Buffer as Buffer2 } from "buffer";
1659
- var regexBytes = new RegExp("^bytes([0-9]+)$");
1660
- var regexNumber = new RegExp("^(u?int)([0-9]*)$");
1661
- var regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
1662
- function _pack(type, value, isArray) {
1663
- switch (type) {
1664
- case "address":
1665
- if (isArray) {
1666
- return zeroPad(value, 32);
1667
- }
1668
- return arrayify(value);
1669
- case "string":
1670
- return Buffer2.from(value);
1671
- case "bytes":
1672
- return arrayify(value);
1673
- case "bool":
1674
- value = value ? "0x01" : "0x00";
1675
- if (isArray) {
1676
- return zeroPad(value, 32);
1677
- }
1678
- return arrayify(value);
1679
- }
1680
- let match = type.match(regexNumber);
1681
- if (match) {
1682
- let size = parseInt(match[2] || "256");
1683
- if (match[2] && String(size) !== match[2] || size % 8 !== 0 || size === 0 || size > 256) {
1684
- logger.throwArgumentError("invalid number type", "type", type);
1685
- }
1686
- if (isArray) {
1687
- size = 256;
1688
- }
1689
- value = tinyBig(value).toTwos(size).toNumber();
1690
- const hexValue2 = hexlify(value);
1691
- return zeroPad(hexValue2, size / 8);
1692
- }
1693
- match = type.match(regexBytes);
1694
- if (match) {
1695
- const size = parseInt(match[1]);
1696
- if (String(size) !== match[1] || size === 0 || size > 32) {
1697
- logger.throwArgumentError("invalid bytes type", "type", type);
1698
- }
1699
- if (arrayify(value).byteLength !== size) {
1700
- logger.throwArgumentError(`invalid value for ${type}`, "value", value);
1701
- }
1702
- if (isArray) {
1703
- return arrayify((value + hexFalse).substring(0, 66));
1704
- }
1705
- return value;
1706
- }
1707
- match = type.match(regexArray);
1708
- if (match && Array.isArray(value)) {
1709
- const baseType = match[1];
1710
- const count = parseInt(match[2] || String(value.length));
1711
- if (count != value.length) {
1712
- logger.throwArgumentError(
1713
- `invalid array length for ${type}`,
1714
- "value",
1715
- value
1716
- );
1717
- }
1718
- const result = [];
1719
- value.forEach(function(value2) {
1720
- result.push(_pack(baseType, value2, true));
1721
- });
1722
- return concat(result);
1723
- }
1724
- return logger.throwArgumentError("invalid type", "type", type);
1725
- }
1726
- function pack(types, values) {
1727
- if (types.length != values.length) {
1728
- logger.throwArgumentError(
1729
- "wrong number of values; expected ${ types.length }",
1730
- "values",
1731
- values
1732
- );
1733
- }
1734
- const tight = [];
1735
- types.forEach(function(type, index) {
1736
- tight.push(_pack(type, values[index]));
1737
- });
1738
- return hexlify(concat(tight));
1739
- }
1740
- function solidityKeccak256(types, values) {
1741
- return keccak256(pack(types, values));
1742
- }
1743
-
1744
- // src/utils/split-signature.ts
1745
- function splitSignature(signature) {
1746
- const result = {
1747
- r: "0x",
1748
- s: "0x",
1749
- _vs: "0x",
1750
- recoveryParam: 0,
1751
- v: 0,
1752
- yParityAndS: "0x",
1753
- compact: "0x"
1754
- };
1755
- if (isBytesLike(signature)) {
1756
- const bytes = arrayify(signature);
1757
- if (bytes.length === 64) {
1758
- result.v = 27 + (bytes[32] >> 7);
1759
- bytes[32] &= 127;
1760
- result.r = hexlify(bytes.slice(0, 32));
1761
- result.s = hexlify(bytes.slice(32, 64));
1762
- } else if (bytes.length === 65) {
1763
- result.r = hexlify(bytes.slice(0, 32));
1764
- result.s = hexlify(bytes.slice(32, 64));
1765
- result.v = bytes[64];
1766
- } else {
1767
- logger.throwArgumentError(
1768
- "invalid signature string",
1769
- "signature",
1770
- signature
1771
- );
1772
- }
1773
- if (result.v < 27) {
1774
- if (result.v === 0 || result.v === 1) {
1775
- result.v += 27;
1776
- } else {
1777
- logger.throwArgumentError(
1778
- "signature invalid v byte",
1779
- "signature",
1780
- signature
1781
- );
1782
- }
1783
- }
1784
- result.recoveryParam = 1 - result.v % 2;
1785
- if (result.recoveryParam) {
1786
- bytes[32] |= 128;
1787
- }
1788
- result._vs = hexlify(bytes.slice(32, 64));
1789
- } else {
1790
- result.r = signature.r;
1791
- result.s = signature.s;
1792
- result.v = signature.v;
1793
- result.recoveryParam = signature.recoveryParam;
1794
- result._vs = signature._vs;
1795
- if (result._vs != null) {
1796
- const vs_1 = zeroPad(arrayify(result._vs), 32);
1797
- result._vs = hexlify(vs_1);
1798
- const recoveryParam = vs_1[0] >= 128 ? 1 : 0;
1799
- if (result.recoveryParam == null) {
1800
- result.recoveryParam = recoveryParam;
1801
- } else if (result.recoveryParam !== recoveryParam) {
1802
- logger.throwArgumentError(
1803
- "signature recoveryParam mismatch _vs",
1804
- "signature",
1805
- signature
1806
- );
1807
- }
1808
- vs_1[0] &= 127;
1809
- const s = hexlify(vs_1);
1810
- if (result.s == null) {
1811
- result.s = s;
1812
- } else if (result.s !== s) {
1813
- logger.throwArgumentError(
1814
- "signature v mismatch _vs",
1815
- "signature",
1816
- signature
1817
- );
1818
- }
1819
- }
1820
- if (result.recoveryParam == null) {
1821
- if (result.v == null) {
1822
- logger.throwArgumentError(
1823
- "signature missing v and recoveryParam",
1824
- "signature",
1825
- signature
1826
- );
1827
- } else if (result.v === 0 || result.v === 1) {
1828
- result.recoveryParam = result.v;
1829
- } else {
1830
- result.recoveryParam = 1 - result.v % 2;
1831
- }
1832
- } else {
1833
- if (result.v == null) {
1834
- result.v = 27 + result.recoveryParam;
1835
- } else {
1836
- const recId = result.v === 0 || result.v === 1 ? result.v : 1 - result.v % 2;
1837
- if (result.recoveryParam !== recId) {
1838
- logger.throwArgumentError(
1839
- "signature recoveryParam mismatch v",
1840
- "signature",
1841
- signature
1842
- );
1843
- }
1844
- }
1845
- }
1846
- if (result.r == null || !isHexString(result.r)) {
1847
- logger.throwArgumentError(
1848
- "signature missing or invalid r",
1849
- "signature",
1850
- signature
1851
- );
1852
- } else {
1853
- result.r = hexZeroPad(result.r, 32);
1854
- }
1855
- if (result.s == null || !isHexString(result.s)) {
1856
- logger.throwArgumentError(
1857
- "signature missing or invalid s",
1858
- "signature",
1859
- signature
1860
- );
1861
- } else {
1862
- result.s = hexZeroPad(result.s, 32);
1863
- }
1864
- const vs = arrayify(result.s);
1865
- if (vs[0] >= 128) {
1866
- logger.throwArgumentError(
1867
- "signature s out of range",
1868
- "signature",
1869
- signature
1870
- );
1871
- }
1872
- if (result.recoveryParam) {
1873
- vs[0] |= 128;
1874
- }
1875
- const _vs = hexlify(vs);
1876
- if (result._vs) {
1877
- if (!isHexString(result._vs)) {
1878
- logger.throwArgumentError(
1879
- "signature invalid _vs",
1880
- "signature",
1881
- signature
1882
- );
1883
- }
1884
- result._vs = hexZeroPad(result._vs, 32);
1885
- }
1886
- if (result._vs == null) {
1887
- result._vs = _vs;
1888
- } else if (result._vs !== _vs) {
1889
- logger.throwArgumentError(
1890
- "signature _vs mismatch v and s",
1891
- "signature",
1892
- signature
1893
- );
1894
- }
1895
- }
1896
- result.yParityAndS = result._vs;
1897
- result.compact = result.r + result.yParityAndS.substring(2);
1898
- return result;
1899
- }
1900
-
1901
- // src/utils/wei-to-ether.ts
1902
- function weiToEther(weiQuantity) {
1903
- validateType(weiQuantity, ["string", "number", "object"]);
1904
- try {
1905
- let _weiQuantity = weiQuantity;
1906
- if (typeof weiQuantity === "string" && weiQuantity.slice(0, 2) === "0x") {
1907
- _weiQuantity = BigInt(weiQuantity).toString();
1908
- }
1909
- const result = tinyBig(_weiQuantity).div("1000000000000000000");
1910
- return tinyBig(result);
1911
- } catch (error) {
1912
- throw error;
1913
- }
1914
- }
1915
- export {
1916
- AlchemyProvider,
1917
- BaseContract,
1918
- Contract,
1919
- FallthroughProvider,
1920
- JsonRpcProvider,
1921
- TinyBig,
1922
- arrayify,
1923
- computeAddress,
1924
- computePublicKey,
1925
- concat,
1926
- etherToGwei,
1927
- etherToWei,
1928
- gweiToEther,
1929
- hashMessage,
1930
- hexConcat,
1931
- hexDataLength,
1932
- hexDataSlice,
1933
- hexStripZeros,
1934
- hexValue,
1935
- hexZeroPad,
1936
- hexlify,
1937
- isAddress,
1938
- isBytes,
1939
- isBytesLike,
1940
- isHexString,
1941
- jsonRpcProvider,
1942
- keccak256,
1943
- pack,
1944
- solidityKeccak256,
1945
- splitSignature,
1946
- stripZeros,
1947
- tinyBig,
1948
- toChecksumAddress,
1949
- toUtf8Bytes,
1950
- weiToEther,
1951
- zeroPad
1952
- };
944
+ export { AlchemyProvider, BaseContract, Contract, FallthroughProvider, JsonRpcProvider, jsonRpcProvider };