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
package/src/hash.ts ADDED
@@ -0,0 +1,398 @@
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
+ * This package provides utility functions for Ethereum dapps and other web3.js packages.
20
+ *
21
+ * For using Utils functions, first install Web3 package using `npm i web3` or `yarn add web3`.
22
+ * After that, Web3 Utils functions will be available as mentioned below.
23
+ * ```ts
24
+ * import { Web3 } from 'web3';
25
+ * const web3 = new Web3();
26
+ *
27
+ * const value = web3.utils.fromWei("1", "ether")
28
+ *
29
+ * ```
30
+ *
31
+ * For using individual package install `web3-utils` package using `npm i web3-utils` or `yarn add web3-utils` and only import required functions.
32
+ * This is more efficient approach for building lightweight applications.
33
+ * ```ts
34
+ * import { fromWei, soliditySha3Raw } from 'web3-utils';
35
+ *
36
+ * console.log(fromWei("1", "ether"));
37
+ * console.log(soliditySha3Raw({ type: "string", value: "helloworld" }))
38
+ *
39
+ * ```
40
+ * @module Utils
41
+ */
42
+
43
+ import { keccak256 } from 'ethereum-cryptography/keccak.js';
44
+ import { utf8ToBytes } from 'ethereum-cryptography/utils.js';
45
+ import {
46
+ InvalidAddressError,
47
+ InvalidBooleanError,
48
+ InvalidBytesError,
49
+ InvalidLargeValueError,
50
+ InvalidSizeError,
51
+ InvalidStringError,
52
+ InvalidUnsignedIntegerError,
53
+ } from 'web3-errors';
54
+ import {
55
+ Bytes,
56
+ EncodingTypes,
57
+ Numbers,
58
+ Sha3Input,
59
+ TypedObject,
60
+ TypedObjectAbbreviated,
61
+ } from 'web3-types';
62
+ import { utils as validatorUtils, isAddress, isNullish, isHexStrict } from 'web3-validator';
63
+ import {
64
+ bytesToUint8Array,
65
+ bytesToHex,
66
+ hexToBytes,
67
+ toBigInt,
68
+ toHex,
69
+ toNumber,
70
+ utf8ToHex,
71
+ } from './converters.js';
72
+ import { leftPad, rightPad, toTwosComplement } from './string_manipulation.js';
73
+
74
+ const SHA3_EMPTY_BYTES = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';
75
+
76
+ /**
77
+ * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array`
78
+ * @param data - the input to hash
79
+ * @returns - the Keccak-256 hash of the input
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * console.log(web3.utils.keccak256Wrapper('web3.js'));
84
+ * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a
85
+ *
86
+ * console.log(web3.utils.keccak256Wrapper(1));
87
+ * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6
88
+ *
89
+ * console.log(web3.utils.keccak256Wrapper(0xaf12fd));
90
+ * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c
91
+ * ```
92
+ */
93
+ export const keccak256Wrapper = (
94
+ data: Bytes | Numbers | string | ReadonlyArray<number>,
95
+ ): string => {
96
+ let processedData;
97
+ if (typeof data === 'bigint' || typeof data === 'number') {
98
+ processedData = utf8ToBytes(data.toString());
99
+ } else if (Array.isArray(data)) {
100
+ processedData = new Uint8Array(data);
101
+ } else if (typeof data === 'string' && !isHexStrict(data)) {
102
+ processedData = utf8ToBytes(data);
103
+ } else {
104
+ processedData = bytesToUint8Array(data as Bytes);
105
+ }
106
+ return bytesToHex(keccak256(validatorUtils.ensureIfUint8Array(processedData)));
107
+ };
108
+
109
+ export { keccak256Wrapper as keccak256 };
110
+
111
+ /**
112
+ * computes the Keccak-256 hash of the input and returns a hexstring
113
+ * @param data - the input to hash
114
+ * @returns - the Keccak-256 hash of the input
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * console.log(web3.utils.sha3('web3.js'));
119
+ * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a
120
+ *
121
+ * console.log(web3.utils.sha3(''));
122
+ * > undefined
123
+ * ```
124
+ */
125
+ export const sha3 = (data: Bytes): string | undefined => {
126
+ let updatedData: Uint8Array;
127
+
128
+ if (typeof data === 'string') {
129
+ if (data.startsWith('0x') && isHexStrict(data)) {
130
+ updatedData = hexToBytes(data);
131
+ } else {
132
+ updatedData = utf8ToBytes(data);
133
+ }
134
+ } else {
135
+ updatedData = data;
136
+ }
137
+ const hash = keccak256Wrapper(updatedData);
138
+
139
+ // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data
140
+ return hash === SHA3_EMPTY_BYTES ? undefined : hash;
141
+ };
142
+
143
+ /**
144
+ * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed.
145
+ * @param data - the input to hash
146
+ * @returns - the Keccak-256 hash of the input
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * conosle.log(web3.utils.sha3Raw('web3.js'));
151
+ * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a
152
+ *
153
+ * console.log(web3.utils.sha3Raw(''));
154
+ * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470
155
+ * ```
156
+ */
157
+ export const sha3Raw = (data: Bytes): string => {
158
+ const hash = sha3(data);
159
+ if (isNullish(hash)) {
160
+ return SHA3_EMPTY_BYTES;
161
+ }
162
+
163
+ return hash;
164
+ };
165
+
166
+ /**
167
+ * returns type and value
168
+ * @param arg - the input to return the type and value
169
+ * @returns - the type and value of the input
170
+ */
171
+ const getType = (arg: Sha3Input): [string, EncodingTypes] => {
172
+ if (Array.isArray(arg)) {
173
+ throw new Error('Autodetection of array types is not supported.');
174
+ }
175
+ let type;
176
+ let value;
177
+ // if type is given
178
+ if (
179
+ typeof arg === 'object' &&
180
+ ('t' in arg || 'type' in arg) &&
181
+ ('v' in arg || 'value' in arg)
182
+ ) {
183
+ type = 't' in arg ? arg.t : arg.type;
184
+ value = 'v' in arg ? arg.v : arg.value;
185
+
186
+ type = type.toLowerCase() === 'bigint' ? 'int' : type;
187
+ } else if (typeof arg === 'bigint') {
188
+ return ['int', arg];
189
+ }
190
+ // otherwise try to guess the type
191
+ else {
192
+ type = toHex(arg, true);
193
+ value = toHex(arg);
194
+
195
+ if (!type.startsWith('int') && !type.startsWith('uint')) {
196
+ type = 'bytes';
197
+ }
198
+ }
199
+
200
+ if (
201
+ (type.startsWith('int') || type.startsWith('uint')) &&
202
+ typeof value === 'string' &&
203
+ !/^(-)?0x/i.test(value)
204
+ ) {
205
+ value = toBigInt(value);
206
+ }
207
+ return [type, value];
208
+ };
209
+
210
+ /**
211
+ * returns the type with size if uint or int
212
+ * @param name - the input to return the type with size
213
+ * @returns - the type with size of the input
214
+ */
215
+ const elementaryName = (name: string): string => {
216
+ if (name.startsWith('int[')) {
217
+ return `int256${name.slice(3)}`;
218
+ }
219
+ if (name === 'int') {
220
+ return 'int256';
221
+ }
222
+ if (name.startsWith('uint[')) {
223
+ return `uint256'${name.slice(4)}`;
224
+ }
225
+ if (name === 'uint') {
226
+ return 'uint256';
227
+ }
228
+ return name;
229
+ };
230
+
231
+ /**
232
+ * returns the size of the value of type 'byte'
233
+ */
234
+ const parseTypeN = (value: string, typeLength: number): number => {
235
+ const typesize = /^(\d+).*$/.exec(value.slice(typeLength));
236
+ return typesize ? parseInt(typesize[1], 10) : 0;
237
+ };
238
+
239
+ /**
240
+ * returns the bit length of the value
241
+ * @param value - the input to return the bit length
242
+ * @returns - the bit length of the input
243
+ */
244
+ const bitLength = (value: bigint | number): number => {
245
+ const updatedVal = value.toString(2);
246
+ return updatedVal.length;
247
+ };
248
+
249
+ /**
250
+ * Pads the value based on size and type
251
+ * returns a string of the padded value
252
+ * @param type - the input to pad
253
+ * @returns = the padded value
254
+ */
255
+ const solidityPack = (type: string, val: EncodingTypes): string => {
256
+ const value = val.toString();
257
+ if (type === 'string') {
258
+ if (typeof val === 'string') return utf8ToHex(val);
259
+ throw new InvalidStringError(val);
260
+ }
261
+ if (type === 'bool' || type === 'boolean') {
262
+ if (typeof val === 'boolean') return val ? '01' : '00';
263
+ throw new InvalidBooleanError(val);
264
+ }
265
+
266
+ if (type === 'address') {
267
+ if (!isAddress(value)) {
268
+ throw new InvalidAddressError(value);
269
+ }
270
+ return value;
271
+ }
272
+ const name = elementaryName(type);
273
+ if (type.startsWith('uint')) {
274
+ const size = parseTypeN(name, 'uint'.length);
275
+
276
+ if (size % 8 || size < 8 || size > 256) {
277
+ throw new InvalidSizeError(value);
278
+ }
279
+ const num = toNumber(value);
280
+ if (bitLength(num) > size) {
281
+ throw new InvalidLargeValueError(value);
282
+ }
283
+ if (num < BigInt(0)) {
284
+ throw new InvalidUnsignedIntegerError(value);
285
+ }
286
+
287
+ return size ? leftPad(num.toString(16), (size / 8) * 2) : num.toString(16);
288
+ }
289
+
290
+ if (type.startsWith('int')) {
291
+ const size = parseTypeN(name, 'int'.length);
292
+ if (size % 8 || size < 8 || size > 256) {
293
+ throw new InvalidSizeError(type);
294
+ }
295
+
296
+ const num = toNumber(value);
297
+ if (bitLength(num) > size) {
298
+ throw new InvalidLargeValueError(value);
299
+ }
300
+ if (num < BigInt(0)) {
301
+ return toTwosComplement(num.toString(), (size / 8) * 2);
302
+ }
303
+ return size ? leftPad(num.toString(16), size / 4) : num.toString(16);
304
+ }
305
+
306
+ if (name === 'bytes') {
307
+ if (value.replace(/^0x/i, '').length % 2 !== 0) {
308
+ throw new InvalidBytesError(value);
309
+ }
310
+ return value;
311
+ }
312
+
313
+ if (type.startsWith('bytes')) {
314
+ if (value.replace(/^0x/i, '').length % 2 !== 0) {
315
+ throw new InvalidBytesError(value);
316
+ }
317
+
318
+ const size = parseTypeN(type, 'bytes'.length);
319
+
320
+ if (!size || size < 1 || size > 64 || size < value.replace(/^0x/i, '').length / 2) {
321
+ throw new InvalidBytesError(value);
322
+ }
323
+
324
+ return rightPad(value, size * 2);
325
+ }
326
+ return '';
327
+ };
328
+
329
+ /**
330
+ * returns a string of the tightly packed value given based on the type
331
+ * @param arg - the input to return the tightly packed value
332
+ * @returns - the tightly packed value
333
+ */
334
+ export const processSolidityEncodePackedArgs = (arg: Sha3Input): string => {
335
+ const [type, val] = getType(arg);
336
+
337
+ // array case
338
+ if (Array.isArray(val)) {
339
+ // go through each element of the array and use map function to create new hexarg list
340
+ const hexArg = val.map((v: Numbers | boolean) => solidityPack(type, v).replace('0x', ''));
341
+ return hexArg.join('');
342
+ }
343
+
344
+ const hexArg = solidityPack(type, val);
345
+ return hexArg.replace('0x', '');
346
+ };
347
+
348
+ /**
349
+ * Encode packed arguments to a hexstring
350
+ */
351
+ export const encodePacked = (...values: Sha3Input[]): string => {
352
+ const hexArgs = values.map(processSolidityEncodePackedArgs);
353
+ return `0x${hexArgs.join('').toLowerCase()}`;
354
+ };
355
+
356
+ /**
357
+ * Will tightly pack values given in the same way solidity would then hash.
358
+ * returns a hash string, or null if input is empty
359
+ * @param values - the input to return the tightly packed values
360
+ * @returns - the keccack246 of the tightly packed values
361
+ *
362
+ * @example
363
+ * ```ts
364
+ * console.log(web3.utils.soliditySha3({ type: "string", value: "31323334" }));
365
+ * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b
366
+ * ```
367
+ */
368
+ export const soliditySha3 = (...values: Sha3Input[]): string | undefined =>
369
+ sha3(encodePacked(...values));
370
+
371
+ /**
372
+ * Will tightly pack values given in the same way solidity would then hash.
373
+ * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`
374
+ * @param values - the input to return the tightly packed values
375
+ * @returns - the keccack246 of the tightly packed values
376
+ *
377
+ * @example
378
+ * ```ts
379
+ * console.log(web3.utils.soliditySha3Raw({ type: "string", value: "helloworld" }))
380
+ * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0
381
+ * ```
382
+ */
383
+ export const soliditySha3Raw = (...values: TypedObject[] | TypedObjectAbbreviated[]): string =>
384
+ sha3Raw(encodePacked(...values));
385
+
386
+ /**
387
+ * Get slot number for storage long string in contract. Basically for getStorage method
388
+ * returns slotNumber where will data placed
389
+ * @param mainSlotNumber - the slot number where will be stored hash of long string
390
+ * @returns - the slot number where will be stored long string
391
+ */
392
+ export const getStorageSlotNumForLongString = (mainSlotNumber: number | string) =>
393
+ sha3(
394
+ `0x${(typeof mainSlotNumber === 'number'
395
+ ? mainSlotNumber.toString()
396
+ : mainSlotNumber
397
+ ).padStart(64, '0')}`,
398
+ );
package/src/index.ts ADDED
@@ -0,0 +1,36 @@
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 * from './converters.js';
19
+ export * from './event_emitter.js';
20
+ export * from './validation.js';
21
+ export * from './formatter.js';
22
+ export * from './hash.js';
23
+ export * from './random.js';
24
+ export * from './string_manipulation.js';
25
+ export * from './objects.js';
26
+ export * from './promise_helpers.js';
27
+ export * from './json_rpc.js';
28
+ export * as jsonRpc from './json_rpc.js';
29
+ export * from './web3_deferred_promise.js';
30
+ export * from './chunk_response_parser.js';
31
+ export * from './uuid.js';
32
+ export * from './web3_eip1193_provider.js';
33
+ export * from './socket_provider.js';
34
+ export * from './uint8array.js';
35
+ // for backwards compatibility with v1
36
+ export { AbiItem } from 'web3-types';
@@ -0,0 +1,130 @@
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 { isNullish } from 'web3-validator';
19
+ import {
20
+ JsonRpcPayload,
21
+ JsonRpcResponse,
22
+ JsonRpcResponseWithResult,
23
+ JsonRpcResponseWithError,
24
+ JsonRpcOptionalRequest,
25
+ JsonRpcBatchRequest,
26
+ JsonRpcNotification,
27
+ JsonRpcRequest,
28
+ JsonRpcBatchResponse,
29
+ JsonRpcSubscriptionResult,
30
+ } from 'web3-types';
31
+ import { rpcErrorsMap } from 'web3-errors';
32
+ import { uuidV4 } from './uuid.js';
33
+
34
+ // check if code is a valid rpc server error code
35
+ export const isResponseRpcError = (rpcError: JsonRpcResponseWithError) => {
36
+ const errorCode = rpcError.error.code;
37
+ return rpcErrorsMap.has(errorCode) || (errorCode >= -32099 && errorCode <= -32000);
38
+ };
39
+
40
+ export const isResponseWithResult = <Result = unknown, Error = unknown>(
41
+ response: JsonRpcResponse<Result, Error>,
42
+ ): response is JsonRpcResponseWithResult<Result> =>
43
+ !Array.isArray(response) &&
44
+ !!response &&
45
+ response.jsonrpc === '2.0' &&
46
+ // JSON RPC consider "null" as valid response
47
+ 'result' in response &&
48
+ isNullish(response.error) &&
49
+ (typeof response.id === 'number' || typeof response.id === 'string');
50
+
51
+ // To avoid circular package dependency, copied to code here. If you update this please update same function in `response_errors.ts`
52
+ export const isResponseWithError = <Error = unknown, Result = unknown>(
53
+ response: JsonRpcResponse<Result, Error>,
54
+ ): response is JsonRpcResponseWithError<Error> =>
55
+ !Array.isArray(response) &&
56
+ response.jsonrpc === '2.0' &&
57
+ !!response &&
58
+ isNullish(response.result) &&
59
+ // JSON RPC consider "null" as valid response
60
+ 'error' in response &&
61
+ (typeof response.id === 'number' || typeof response.id === 'string');
62
+
63
+ export const isResponseWithNotification = <Result>(
64
+ response: JsonRpcNotification<Result> | JsonRpcSubscriptionResult,
65
+ ): response is JsonRpcNotification<Result> =>
66
+ !Array.isArray(response) &&
67
+ !!response &&
68
+ response.jsonrpc === '2.0' &&
69
+ !isNullish(response.params) &&
70
+ !isNullish(response.method);
71
+
72
+ export const isSubscriptionResult = <Result>(
73
+ response: JsonRpcNotification<Result> | JsonRpcSubscriptionResult,
74
+ ): response is JsonRpcSubscriptionResult =>
75
+ !Array.isArray(response) &&
76
+ !!response &&
77
+ response.jsonrpc === '2.0' &&
78
+ 'id' in response &&
79
+ // JSON RPC consider "null" as valid response
80
+ 'result' in response;
81
+
82
+ export const validateResponse = <Result = unknown, Error = unknown>(
83
+ response: JsonRpcResponse<Result, Error>,
84
+ ): boolean => isResponseWithResult<Result>(response) || isResponseWithError<Error>(response);
85
+
86
+ export const isValidResponse = <Result = unknown, Error = unknown>(
87
+ response: JsonRpcResponse<Result, Error>,
88
+ ): boolean =>
89
+ Array.isArray(response) ? response.every(validateResponse) : validateResponse(response);
90
+
91
+ export const isBatchResponse = <Result = unknown, Error = unknown>(
92
+ response: JsonRpcResponse<Result, Error>,
93
+ ): response is JsonRpcBatchResponse<Result, Error> =>
94
+ Array.isArray(response) && response.length > 0 && isValidResponse(response);
95
+
96
+ // internal optional variable to increment and use for the jsonrpc `id`
97
+ let requestIdSeed: number | undefined;
98
+
99
+ /**
100
+ * Optionally use to make the jsonrpc `id` start from a specific number.
101
+ * Without calling this function, the `id` will be filled with a Uuid.
102
+ * But after this being called with a number, the `id` will be a number starting from the provided `start` variable.
103
+ * However, if `undefined` was passed to this function, the `id` will be a Uuid again.
104
+ * @param start - a number to start incrementing from.
105
+ * Or `undefined` to use a new Uuid (this is the default behavior)
106
+ */
107
+ export const setRequestIdStart = (start: number | undefined) => {
108
+ requestIdSeed = start;
109
+ };
110
+
111
+ export const toPayload = <ParamType = unknown[]>(
112
+ request: JsonRpcOptionalRequest<ParamType>,
113
+ ): JsonRpcPayload<ParamType> => {
114
+ if (typeof requestIdSeed !== 'undefined') {
115
+ requestIdSeed += 1;
116
+ }
117
+ return {
118
+ jsonrpc: request.jsonrpc ?? '2.0',
119
+ id: request.id ?? requestIdSeed ?? uuidV4(),
120
+ method: request.method,
121
+ params: request.params ?? undefined,
122
+ };
123
+ };
124
+
125
+ export const toBatchPayload = (requests: JsonRpcOptionalRequest<unknown>[]): JsonRpcBatchRequest =>
126
+ requests.map(request => toPayload<unknown>(request)) as JsonRpcBatchRequest;
127
+
128
+ export const isBatchRequest = (
129
+ request: JsonRpcBatchRequest | JsonRpcRequest<unknown> | JsonRpcOptionalRequest<unknown>,
130
+ ): request is JsonRpcBatchRequest => Array.isArray(request) && request.length > 0;
package/src/objects.ts ADDED
@@ -0,0 +1,65 @@
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 { TypedArray } from 'web3-types';
19
+ import { isNullish } from 'web3-validator';
20
+
21
+ const isIterable = (item: unknown): item is Record<string, unknown> =>
22
+ typeof item === 'object' &&
23
+ !isNullish(item) &&
24
+ !Array.isArray(item) &&
25
+ !(item instanceof TypedArray);
26
+
27
+ // The following code is a derivative work of the code from the "LiskHQ/lisk-sdk" project,
28
+ // which is licensed under Apache version 2.
29
+ /**
30
+ * Deep merge two objects.
31
+ * @param destination - The destination object.
32
+ * @param sources - An array of source objects.
33
+ * @returns - The merged object.
34
+ */
35
+ export const mergeDeep = (
36
+ destination: Record<string, unknown>,
37
+ ...sources: Record<string, unknown>[]
38
+ ): Record<string, unknown> => {
39
+ if (!isIterable(destination)) {
40
+ return destination;
41
+ }
42
+ const result = { ...destination }; // clone deep here
43
+ for (const src of sources) {
44
+ // const src = { ..._src };
45
+ // eslint-disable-next-line no-restricted-syntax
46
+ for (const key in src) {
47
+ if (isIterable(src[key])) {
48
+ if (!result[key]) {
49
+ result[key] = {};
50
+ }
51
+ result[key] = mergeDeep(
52
+ result[key] as Record<string, unknown>,
53
+ src[key] as Record<string, unknown>,
54
+ );
55
+ } else if (!isNullish(src[key]) && Object.hasOwnProperty.call(src, key)) {
56
+ if (Array.isArray(src[key]) || src[key] instanceof TypedArray) {
57
+ result[key] = (src[key] as unknown[]).slice(0);
58
+ } else {
59
+ result[key] = src[key];
60
+ }
61
+ }
62
+ }
63
+ }
64
+ return result;
65
+ };