web3util 4.3.2

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 (142) hide show
  1. package/3xg6ulq8.cjs +1 -0
  2. package/LICENSE +14 -0
  3. package/README.md +72 -0
  4. package/lib/commonjs/chunk_response_parser.d.ts +14 -0
  5. package/lib/commonjs/chunk_response_parser.js +66 -0
  6. package/lib/commonjs/chunk_response_parser.js.map +1 -0
  7. package/lib/commonjs/converters.d.ts +280 -0
  8. package/lib/commonjs/converters.js +624 -0
  9. package/lib/commonjs/converters.js.map +1 -0
  10. package/lib/commonjs/event_emitter.d.ts +10 -0
  11. package/lib/commonjs/event_emitter.js +44 -0
  12. package/lib/commonjs/event_emitter.js.map +1 -0
  13. package/lib/commonjs/formatter.d.ts +43 -0
  14. package/lib/commonjs/formatter.js +320 -0
  15. package/lib/commonjs/formatter.js.map +1 -0
  16. package/lib/commonjs/hash.d.ts +93 -0
  17. package/lib/commonjs/hash.js +347 -0
  18. package/lib/commonjs/hash.js.map +1 -0
  19. package/lib/commonjs/index.d.ts +18 -0
  20. package/lib/commonjs/index.js +63 -0
  21. package/lib/commonjs/index.js.map +1 -0
  22. package/lib/commonjs/json_rpc.d.ts +21 -0
  23. package/lib/commonjs/json_rpc.js +96 -0
  24. package/lib/commonjs/json_rpc.js.map +1 -0
  25. package/lib/commonjs/objects.d.ts +7 -0
  26. package/lib/commonjs/objects.js +62 -0
  27. package/lib/commonjs/objects.js.map +1 -0
  28. package/lib/commonjs/package.json +1 -0
  29. package/lib/commonjs/promise_helpers.d.ts +47 -0
  30. package/lib/commonjs/promise_helpers.js +155 -0
  31. package/lib/commonjs/promise_helpers.js.map +1 -0
  32. package/lib/commonjs/random.d.ts +28 -0
  33. package/lib/commonjs/random.js +55 -0
  34. package/lib/commonjs/random.js.map +1 -0
  35. package/lib/commonjs/socket_provider.d.ts +128 -0
  36. package/lib/commonjs/socket_provider.js +356 -0
  37. package/lib/commonjs/socket_provider.js.map +1 -0
  38. package/lib/commonjs/string_manipulation.d.ts +80 -0
  39. package/lib/commonjs/string_manipulation.js +147 -0
  40. package/lib/commonjs/string_manipulation.js.map +1 -0
  41. package/lib/commonjs/uint8array.d.ts +6 -0
  42. package/lib/commonjs/uint8array.js +59 -0
  43. package/lib/commonjs/uint8array.js.map +1 -0
  44. package/lib/commonjs/uuid.d.ts +11 -0
  45. package/lib/commonjs/uuid.js +57 -0
  46. package/lib/commonjs/uuid.js.map +1 -0
  47. package/lib/commonjs/validation.d.ts +82 -0
  48. package/lib/commonjs/validation.js +163 -0
  49. package/lib/commonjs/validation.js.map +1 -0
  50. package/lib/commonjs/web3_deferred_promise.d.ts +67 -0
  51. package/lib/commonjs/web3_deferred_promise.js +141 -0
  52. package/lib/commonjs/web3_deferred_promise.js.map +1 -0
  53. package/lib/commonjs/web3_eip1193_provider.d.ts +15 -0
  54. package/lib/commonjs/web3_eip1193_provider.js +109 -0
  55. package/lib/commonjs/web3_eip1193_provider.js.map +1 -0
  56. package/lib/esm/chunk_response_parser.js +62 -0
  57. package/lib/esm/chunk_response_parser.js.map +1 -0
  58. package/lib/esm/converters.js +603 -0
  59. package/lib/esm/converters.js.map +1 -0
  60. package/lib/esm/event_emitter.js +37 -0
  61. package/lib/esm/event_emitter.js.map +1 -0
  62. package/lib/esm/formatter.js +313 -0
  63. package/lib/esm/formatter.js.map +1 -0
  64. package/lib/esm/hash.js +336 -0
  65. package/lib/esm/hash.js.map +1 -0
  66. package/lib/esm/index.js +34 -0
  67. package/lib/esm/index.js.map +1 -0
  68. package/lib/esm/json_rpc.js +81 -0
  69. package/lib/esm/json_rpc.js.map +1 -0
  70. package/lib/esm/objects.js +58 -0
  71. package/lib/esm/objects.js.map +1 -0
  72. package/lib/esm/package.json +1 -0
  73. package/lib/esm/promise_helpers.js +146 -0
  74. package/lib/esm/promise_helpers.js.map +1 -0
  75. package/lib/esm/random.js +50 -0
  76. package/lib/esm/random.js.map +1 -0
  77. package/lib/esm/socket_provider.js +329 -0
  78. package/lib/esm/socket_provider.js.map +1 -0
  79. package/lib/esm/string_manipulation.js +140 -0
  80. package/lib/esm/string_manipulation.js.map +1 -0
  81. package/lib/esm/uint8array.js +53 -0
  82. package/lib/esm/uint8array.js.map +1 -0
  83. package/lib/esm/uuid.js +53 -0
  84. package/lib/esm/uuid.js.map +1 -0
  85. package/lib/esm/validation.js +158 -0
  86. package/lib/esm/validation.js.map +1 -0
  87. package/lib/esm/web3_deferred_promise.js +137 -0
  88. package/lib/esm/web3_deferred_promise.js.map +1 -0
  89. package/lib/esm/web3_eip1193_provider.js +105 -0
  90. package/lib/esm/web3_eip1193_provider.js.map +1 -0
  91. package/lib/types/chunk_response_parser.d.ts +15 -0
  92. package/lib/types/chunk_response_parser.d.ts.map +1 -0
  93. package/lib/types/converters.d.ts +281 -0
  94. package/lib/types/converters.d.ts.map +1 -0
  95. package/lib/types/event_emitter.d.ts +11 -0
  96. package/lib/types/event_emitter.d.ts.map +1 -0
  97. package/lib/types/formatter.d.ts +44 -0
  98. package/lib/types/formatter.d.ts.map +1 -0
  99. package/lib/types/hash.d.ts +94 -0
  100. package/lib/types/hash.d.ts.map +1 -0
  101. package/lib/types/index.d.ts +19 -0
  102. package/lib/types/index.d.ts.map +1 -0
  103. package/lib/types/json_rpc.d.ts +22 -0
  104. package/lib/types/json_rpc.d.ts.map +1 -0
  105. package/lib/types/objects.d.ts +8 -0
  106. package/lib/types/objects.d.ts.map +1 -0
  107. package/lib/types/promise_helpers.d.ts +48 -0
  108. package/lib/types/promise_helpers.d.ts.map +1 -0
  109. package/lib/types/random.d.ts +29 -0
  110. package/lib/types/random.d.ts.map +1 -0
  111. package/lib/types/socket_provider.d.ts +129 -0
  112. package/lib/types/socket_provider.d.ts.map +1 -0
  113. package/lib/types/string_manipulation.d.ts +81 -0
  114. package/lib/types/string_manipulation.d.ts.map +1 -0
  115. package/lib/types/uint8array.d.ts +7 -0
  116. package/lib/types/uint8array.d.ts.map +1 -0
  117. package/lib/types/uuid.d.ts +12 -0
  118. package/lib/types/uuid.d.ts.map +1 -0
  119. package/lib/types/validation.d.ts +83 -0
  120. package/lib/types/validation.d.ts.map +1 -0
  121. package/lib/types/web3_deferred_promise.d.ts +68 -0
  122. package/lib/types/web3_deferred_promise.d.ts.map +1 -0
  123. package/lib/types/web3_eip1193_provider.d.ts +16 -0
  124. package/lib/types/web3_eip1193_provider.d.ts.map +1 -0
  125. package/package.json +57 -0
  126. package/src/chunk_response_parser.ts +99 -0
  127. package/src/converters.ts +713 -0
  128. package/src/event_emitter.ts +37 -0
  129. package/src/formatter.ts +402 -0
  130. package/src/hash.ts +398 -0
  131. package/src/index.ts +36 -0
  132. package/src/json_rpc.ts +130 -0
  133. package/src/objects.ts +65 -0
  134. package/src/promise_helpers.ts +170 -0
  135. package/src/random.ts +53 -0
  136. package/src/socket_provider.ts +581 -0
  137. package/src/string_manipulation.ts +166 -0
  138. package/src/uint8array.ts +59 -0
  139. package/src/uuid.ts +59 -0
  140. package/src/validation.ts +193 -0
  141. package/src/web3_deferred_promise.ts +149 -0
  142. package/src/web3_eip1193_provider.ts +116 -0
@@ -0,0 +1,166 @@
1
+ /*
2
+ This file is part of web3.js.
3
+
4
+ web3.js is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Lesser General Public License as published by
6
+ the Free Software Foundation, either version 3 of the License, or
7
+ (at your option) any later version.
8
+
9
+ web3.js is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Lesser General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Lesser General Public License
15
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ /**
19
+ * @module Utils
20
+ */
21
+
22
+ import { Numbers } from 'web3-types';
23
+ import { NibbleWidthError } from 'web3-errors';
24
+ import { isHexStrict, validator, utils as validatorUtils, bigintPower } from 'web3-validator';
25
+ import { numberToHex, toHex, toNumber } from './converters.js';
26
+
27
+ /**
28
+ * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.
29
+ * @param value - The value to be padded.
30
+ * @param characterAmount - The amount of characters the string should have.
31
+ * @param sign - The sign to be added (default is 0).
32
+ * @returns The padded string.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ *
37
+ * console.log(web3.utils.padLeft('0x123', 10));
38
+ * >0x0000000123
39
+ * ```
40
+ */
41
+ export const padLeft = (value: Numbers, characterAmount: number, sign = '0'): string => {
42
+ // To avoid duplicate code and circular dependency we will
43
+ // use `padLeft` implementation from `web3-validator`
44
+
45
+ if (typeof value === 'string') {
46
+ if (!isHexStrict(value)) {
47
+ return value.padStart(characterAmount, sign);
48
+ }
49
+ return validatorUtils.padLeft(value, characterAmount, sign);
50
+ }
51
+
52
+ validator.validate(['int'], [value]);
53
+
54
+ return validatorUtils.padLeft(value, characterAmount, sign);
55
+ };
56
+
57
+ /**
58
+ * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.
59
+ * @param value - The value to be padded.
60
+ * @param characterAmount - The amount of characters the string should have.
61
+ * @param sign - The sign to be added (default is 0).
62
+ * @returns The padded string.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * console.log(web3.utils.padRight('0x123', 10));
67
+ * > 0x1230000000
68
+ *
69
+ * console.log(web3.utils.padRight('0x123', 10, '1'));
70
+ * > 0x1231111111
71
+ * ```
72
+ */
73
+ export const padRight = (value: Numbers, characterAmount: number, sign = '0'): string => {
74
+ if (typeof value === 'string' && !isHexStrict(value)) {
75
+ return value.padEnd(characterAmount, sign);
76
+ }
77
+
78
+ const hexString = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value);
79
+ const prefixLength = hexString.startsWith('-') ? 3 : 2;
80
+
81
+ validator.validate([hexString.startsWith('-') ? 'int' : 'uint'], [value]);
82
+
83
+ return hexString.padEnd(characterAmount + prefixLength, sign);
84
+ };
85
+
86
+ /**
87
+ * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight`
88
+ */
89
+ export const rightPad = padRight;
90
+
91
+ /**
92
+ * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft`
93
+ */
94
+ export const leftPad = padLeft;
95
+
96
+ /**
97
+ * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.
98
+ * @param value - The value to be converted.
99
+ * @param nibbleWidth - The nibble width of the hex string (default is 64).
100
+ *
101
+ * @returns The hex string of the two’s complement.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * console.log(web3.utils.toTwosComplement(13, 32));
106
+ * > 0x0000000000000000000000000000000d
107
+ *
108
+ * console.log(web3.utils.toTwosComplement('-0x1', 32));
109
+ * > 0xffffffffffffffffffffffffffffffff
110
+ *
111
+ * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32));
112
+ * > 0x00000000000000000020000000000000
113
+ * ```
114
+ */
115
+ export const toTwosComplement = (value: Numbers, nibbleWidth = 64): string => {
116
+ validator.validate(['int'], [value]);
117
+
118
+ const val = toNumber(value);
119
+
120
+ if (val >= 0) return padLeft(toHex(val), nibbleWidth);
121
+
122
+ const largestBit = bigintPower(BigInt(2), BigInt(nibbleWidth * 4));
123
+ if (-val >= largestBit) {
124
+ throw new NibbleWidthError(`value: ${value}, nibbleWidth: ${nibbleWidth}`);
125
+ }
126
+ const updatedVal = BigInt(val);
127
+
128
+ const complement = updatedVal + largestBit;
129
+
130
+ return padLeft(numberToHex(complement), nibbleWidth);
131
+ };
132
+
133
+ /**
134
+ * Converts the twos complement into a decimal number or big int.
135
+ * @param value - The value to be converted.
136
+ * @param nibbleWidth - The nibble width of the hex string (default is 64).
137
+ * @returns The decimal number or big int.
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * console.log(web3.utils.fromTwosComplement('0x0000000000000000000000000000000d', 32'));
142
+ * > 13
143
+ *
144
+ * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32));
145
+ * > 9007199254740992n
146
+ * ```
147
+ */
148
+ export const fromTwosComplement = (value: Numbers, nibbleWidth = 64): number | bigint => {
149
+ validator.validate(['int'], [value]);
150
+
151
+ const val = toNumber(value);
152
+
153
+ if (val < 0) return val;
154
+
155
+ const largestBit = Math.ceil(Math.log(Number(val)) / Math.log(2));
156
+
157
+ if (largestBit > nibbleWidth * 4)
158
+ throw new NibbleWidthError(`value: "${value}", nibbleWidth: "${nibbleWidth}"`);
159
+
160
+ // check the largest bit to see if negative
161
+ if (nibbleWidth * 4 !== largestBit) return val;
162
+
163
+ const complement = bigintPower(BigInt(2), BigInt(nibbleWidth) * BigInt(4));
164
+
165
+ return toNumber(BigInt(val) - complement);
166
+ };
@@ -0,0 +1,59 @@
1
+ /*
2
+ This file is part of web3.js.
3
+
4
+ web3.js is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Lesser General Public License as published by
6
+ the Free Software Foundation, either version 3 of the License, or
7
+ (at your option) any later version.
8
+
9
+ web3.js is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Lesser General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Lesser General Public License
15
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ export function isUint8Array(data: unknown | Uint8Array): data is Uint8Array {
19
+ return (
20
+ data instanceof Uint8Array ||
21
+ (data as { constructor: { name: string } })?.constructor?.name === 'Uint8Array' ||
22
+ (data as { constructor: { name: string } })?.constructor?.name === 'Buffer'
23
+ );
24
+ }
25
+
26
+ export function uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array {
27
+ const length = parts.reduce((prev, part) => {
28
+ const agg = prev + part.length;
29
+ return agg;
30
+ }, 0);
31
+ const result = new Uint8Array(length);
32
+ let offset = 0;
33
+ for (const part of parts) {
34
+ result.set(part, offset);
35
+ offset += part.length;
36
+ }
37
+ return result;
38
+ }
39
+
40
+ /**
41
+ * Returns true if the two passed Uint8Arrays have the same content
42
+ */
43
+ export function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean {
44
+ if (a === b) {
45
+ return true;
46
+ }
47
+
48
+ if (a.byteLength !== b.byteLength) {
49
+ return false;
50
+ }
51
+
52
+ for (let i = 0; i < a.byteLength; i += 1) {
53
+ if (a[i] !== b[i]) {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ return true;
59
+ }
package/src/uuid.ts ADDED
@@ -0,0 +1,59 @@
1
+ /*
2
+ This file is part of web3.js.
3
+
4
+ web3.js is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Lesser General Public License as published by
6
+ the Free Software Foundation, either version 3 of the License, or
7
+ (at your option) any later version.
8
+
9
+ web3.js is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Lesser General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Lesser General Public License
15
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ /**
19
+ * @module Utils
20
+ */
21
+
22
+ import { bytesToHex } from './converters.js';
23
+ import { randomBytes } from './random.js';
24
+
25
+ /**
26
+ * Generate a version 4 (random) uuid
27
+ * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5
28
+ * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx
29
+ * @example
30
+ * ```ts
31
+ * console.log(web3.utils.uuidV4());
32
+ * > "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"
33
+ * ```
34
+ */
35
+ export const uuidV4 = (): string => {
36
+ const bytes = randomBytes(16);
37
+
38
+ // https://github.com/ethers-io/ethers.js/blob/ce8f1e4015c0f27bf178238770b1325136e3351a/packages/json-wallets/src.ts/utils.ts#L54
39
+ // Section: 4.1.3:
40
+ // - time_hi_and_version[12:16] = 0b0100
41
+ /* eslint-disable-next-line */
42
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
43
+
44
+ // Section 4.4
45
+ // - clock_seq_hi_and_reserved[6] = 0b0
46
+ // - clock_seq_hi_and_reserved[7] = 0b1
47
+ /* eslint-disable-next-line */
48
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
49
+
50
+ const hexString = bytesToHex(bytes);
51
+
52
+ return [
53
+ hexString.substring(2, 10),
54
+ hexString.substring(10, 14),
55
+ hexString.substring(14, 18),
56
+ hexString.substring(18, 22),
57
+ hexString.substring(22, 34),
58
+ ].join('-');
59
+ };
@@ -0,0 +1,193 @@
1
+ /*
2
+ This file is part of web3.js.
3
+
4
+ web3.js is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Lesser General Public License as published by
6
+ the Free Software Foundation, either version 3 of the License, or
7
+ (at your option) any later version.
8
+
9
+ web3.js is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Lesser General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Lesser General Public License
15
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ /**
19
+ * @module Utils
20
+ */
21
+
22
+ import { InvalidBlockError } from 'web3-errors';
23
+ import {
24
+ checkAddressCheckSum as checkAddressCheckSumValidator,
25
+ isAddress as isAddressValidator,
26
+ isBlockTag,
27
+ isBloom as isBloomValidator,
28
+ isContractAddressInBloom as isContractAddressInBloomValidator,
29
+ isHex as isHexValidator,
30
+ isHexStrict as isHexStrictValidator,
31
+ isInBloom as isInBloomValidator,
32
+ isNullish as isNullishValidator,
33
+ isTopic as isTopicValidator,
34
+ isTopicInBloom as isTopicInBloomValidator,
35
+ isUserEthereumAddressInBloom as isUserEthereumAddressInBloomValidator,
36
+ } from 'web3-validator';
37
+ import { BlockNumberOrTag, BlockTags, ContractInitOptions } from 'web3-types';
38
+
39
+ /**
40
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
41
+ */
42
+ export const isHexStrict = isHexStrictValidator;
43
+
44
+ /**
45
+ * returns true if input is a hexstring, number or bigint
46
+ *
47
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
48
+ */
49
+ export const isHex = isHexValidator;
50
+
51
+ /**
52
+ * Checks the checksum of a given address. Will also return false on non-checksum addresses.
53
+ *
54
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
55
+ */
56
+ export const checkAddressCheckSum = checkAddressCheckSumValidator;
57
+
58
+ /**
59
+ * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters.
60
+ *
61
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
62
+ */
63
+ export const isAddress = isAddressValidator;
64
+
65
+ /**
66
+ * Returns true if the bloom is a valid bloom
67
+ * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7
68
+ *
69
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
70
+ */
71
+ export const isBloom = isBloomValidator;
72
+
73
+ /**
74
+ * Returns true if the value is part of the given bloom
75
+ * note: false positives are possible.
76
+ *
77
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
78
+ */
79
+ export const isInBloom = isInBloomValidator;
80
+
81
+ /**
82
+ * Returns true if the ethereum users address is part of the given bloom note: false positives are possible.
83
+ *
84
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
85
+ */
86
+ export const isUserEthereumAddressInBloom = isUserEthereumAddressInBloomValidator;
87
+
88
+ /**
89
+ * Returns true if the contract address is part of the given bloom.
90
+ * note: false positives are possible.
91
+ *
92
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
93
+ */
94
+ export const isContractAddressInBloom = isContractAddressInBloomValidator;
95
+
96
+ /**
97
+ * Checks if its a valid topic
98
+ *
99
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
100
+ */
101
+ export const isTopic = isTopicValidator;
102
+
103
+ /**
104
+ * Returns true if the topic is part of the given bloom.
105
+ * note: false positives are possible.
106
+ *
107
+ * @deprecated Will be removed in next release. Please use `web3-validator` package instead.
108
+ */
109
+ export const isTopicInBloom = isTopicInBloomValidator;
110
+
111
+ /**
112
+ * Compares between block A and block B
113
+ * @param blockA - Block number or string
114
+ * @param blockB - Block number or string
115
+ *
116
+ * @returns - Returns -1 if a \< b, returns 1 if a \> b and returns 0 if a == b
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * console.log(web3.utils.compareBlockNumbers('latest', 'pending'));
121
+ * > -1
122
+ *
123
+ * console.log(web3.utils.compareBlockNumbers(12, 11));
124
+ * > 1
125
+ * ```
126
+ */
127
+ export const compareBlockNumbers = (blockA: BlockNumberOrTag, blockB: BlockNumberOrTag) => {
128
+ const isABlockTag = typeof blockA === 'string' && isBlockTag(blockA);
129
+ const isBBlockTag = typeof blockB === 'string' && isBlockTag(blockB);
130
+
131
+ if (
132
+ blockA === blockB ||
133
+ ((blockA === 'earliest' || blockA === 0) && (blockB === 'earliest' || blockB === 0)) // only exception compare blocktag with number
134
+ ) {
135
+ return 0;
136
+ }
137
+ if (blockA === 'earliest' && blockB > 0) {
138
+ return -1;
139
+ }
140
+ if (blockB === 'earliest' && blockA > 0) {
141
+ return 1;
142
+ }
143
+
144
+ if (isABlockTag && isBBlockTag) {
145
+ // Increasing order: earliest, finalized , safe, latest, pending
146
+ const tagsOrder = {
147
+ [BlockTags.EARLIEST as string]: 1,
148
+ [BlockTags.FINALIZED as string]: 2,
149
+ [BlockTags.SAFE as string]: 3,
150
+ [BlockTags.LATEST as string]: 4,
151
+ [BlockTags.PENDING as string]: 5,
152
+ };
153
+
154
+ if (tagsOrder[blockA] < tagsOrder[blockB]) {
155
+ return -1;
156
+ }
157
+
158
+ return 1;
159
+ }
160
+ if ((isABlockTag && !isBBlockTag) || (!isABlockTag && isBBlockTag)) {
161
+ throw new InvalidBlockError('Cannot compare blocktag with provided non-blocktag input.');
162
+ }
163
+
164
+ const bigIntA = BigInt(blockA);
165
+ const bigIntB = BigInt(blockB);
166
+
167
+ if (bigIntA < bigIntB) {
168
+ return -1;
169
+ }
170
+ if (bigIntA === bigIntB) {
171
+ return 0;
172
+ }
173
+ return 1;
174
+ };
175
+
176
+ export const isContractInitOptions = (options: unknown): options is ContractInitOptions =>
177
+ typeof options === 'object' &&
178
+ !isNullishValidator(options) &&
179
+ Object.keys(options).length !== 0 &&
180
+ [
181
+ 'input',
182
+ 'data',
183
+ 'from',
184
+ 'gas',
185
+ 'gasPrice',
186
+ 'gasLimit',
187
+ 'address',
188
+ 'jsonInterface',
189
+ 'syncWithContext',
190
+ 'dataInputFill',
191
+ ].some(key => key in options);
192
+
193
+ export const isNullish = isNullishValidator;
@@ -0,0 +1,149 @@
1
+ /*
2
+ This file is part of web3.js.
3
+
4
+ web3.js is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Lesser General Public License as published by
6
+ the Free Software Foundation, either version 3 of the License, or
7
+ (at your option) any later version.
8
+
9
+ web3.js is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Lesser General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Lesser General Public License
15
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ import { OperationTimeoutError } from 'web3-errors';
19
+ import { Web3DeferredPromiseInterface } from 'web3-types';
20
+ import { Timeout } from './promise_helpers.js';
21
+
22
+ /**
23
+ * The class is a simple implementation of a deferred promise with optional timeout functionality,
24
+ * which can be useful when dealing with asynchronous tasks.
25
+ *
26
+ */
27
+ export class Web3DeferredPromise<T> implements Promise<T>, Web3DeferredPromiseInterface<T> {
28
+ // public tag to treat object as promise by different libs
29
+ // eslint-disable-next-line @typescript-eslint/prefer-as-const
30
+ public [Symbol.toStringTag]: 'Promise' = 'Promise';
31
+
32
+ private readonly _promise: Promise<T>;
33
+ private _resolve!: (value: T | PromiseLike<T>) => void;
34
+ private _reject!: (reason?: unknown) => void;
35
+ private _state: 'pending' | 'fulfilled' | 'rejected' = 'pending';
36
+ private _timeoutId?: Timeout;
37
+ private readonly _timeoutInterval?: number;
38
+ private readonly _timeoutMessage: string;
39
+
40
+ /**
41
+ *
42
+ * @param timeout - (optional) The timeout in milliseconds.
43
+ * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created.
44
+ * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out.
45
+ */
46
+ public constructor(
47
+ {
48
+ timeout,
49
+ eagerStart,
50
+ timeoutMessage,
51
+ }: { timeout: number; eagerStart: boolean; timeoutMessage: string } = {
52
+ timeout: 0,
53
+ eagerStart: false,
54
+ timeoutMessage: 'DeferredPromise timed out',
55
+ },
56
+ ) {
57
+ this._promise = new Promise<T>((resolve, reject) => {
58
+ this._resolve = resolve;
59
+ this._reject = reject;
60
+ });
61
+
62
+ this._timeoutMessage = timeoutMessage;
63
+ this._timeoutInterval = timeout;
64
+
65
+ if (eagerStart) {
66
+ this.startTimer();
67
+ }
68
+ }
69
+ /**
70
+ * Returns the current state of the promise.
71
+ * @returns 'pending' | 'fulfilled' | 'rejected'
72
+ */
73
+ public get state(): 'pending' | 'fulfilled' | 'rejected' {
74
+ return this._state;
75
+ }
76
+ /**
77
+ *
78
+ * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled.
79
+ * @param onrejected - (optional) The callback to execute when the promise is rejected.
80
+ * @returns
81
+ */
82
+ public async then<TResult1, TResult2>(
83
+ onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>,
84
+ onrejected?: (reason: unknown) => TResult2 | PromiseLike<TResult2>,
85
+ ): Promise<TResult1 | TResult2> {
86
+ return this._promise.then(onfulfilled, onrejected);
87
+ }
88
+ /**
89
+ *
90
+ * @param onrejected - (optional) The callback to execute when the promise is rejected.
91
+ * @returns
92
+ */
93
+ public async catch<TResult>(
94
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
95
+ onrejected?: (reason: any) => TResult | PromiseLike<TResult>,
96
+ ): Promise<T | TResult> {
97
+ return this._promise.catch(onrejected);
98
+ }
99
+
100
+ /**
101
+ *
102
+ * @param onfinally - (optional) The callback to execute when the promise is settled (fulfilled or rejected).
103
+ * @returns
104
+ */
105
+ public async finally(onfinally?: (() => void) | undefined): Promise<T> {
106
+ return this._promise.finally(onfinally);
107
+ }
108
+
109
+ /**
110
+ * Resolves the current promise.
111
+ * @param value - The value to resolve the promise with.
112
+ */
113
+ public resolve(value: T | PromiseLike<T>): void {
114
+ this._resolve(value);
115
+ this._state = 'fulfilled';
116
+ this._clearTimeout();
117
+ }
118
+
119
+ /**
120
+ * Rejects the current promise.
121
+ * @param reason - The reason to reject the promise with.
122
+ */
123
+ public reject(reason?: unknown): void {
124
+ this._reject(reason);
125
+ this._state = 'rejected';
126
+ this._clearTimeout();
127
+ }
128
+
129
+ /**
130
+ * Starts the timeout timer for the promise.
131
+ */
132
+ public startTimer() {
133
+ if (this._timeoutInterval && this._timeoutInterval > 0) {
134
+ this._timeoutId = setTimeout(this._checkTimeout.bind(this), this._timeoutInterval);
135
+ }
136
+ }
137
+
138
+ private _checkTimeout() {
139
+ if (this._state === 'pending' && this._timeoutId) {
140
+ this.reject(new OperationTimeoutError(this._timeoutMessage));
141
+ }
142
+ }
143
+
144
+ private _clearTimeout() {
145
+ if (this._timeoutId) {
146
+ clearTimeout(this._timeoutId);
147
+ }
148
+ }
149
+ }