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 @@
1
+ {"version":3,"file":"web3_eip1193_provider.js","sourceRoot":"","sources":["../../src/web3_eip1193_provider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;EAeE;AACF,2CAQoB;AACpB,iDAA6C;AAC7C,6CAAsD;AACtD,+CAA0C;AAE1C;;GAEG;AACH,MAAsB,eAEpB,SAAQ,6BAAqB;IAF/B;;QAGoB,kBAAa,GAAiB,IAAI,4BAAY,EAAE,CAAC;QAC5D,aAAQ,GAAc,EAAE,CAAC;QACzB,cAAS,GAAgB,EAAE,CAAC;IA8ErC,CAAC;IA5Ec,WAAW;;;YACxB,MAAM,IAAI,GAAG,MAAO,IAA8B,CAAC,OAAO,CAIzD,IAAA,uBAAS,EAAC;gBACT,MAAM,EAAE,aAAa;gBACrB,MAAM,EAAE,EAAE;aACV,CAA4C,CA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OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACpB,CAAC,CAAC;SACH,CAAC;aACA,IAAI,CAAC,GAAG,EAAE,CACV,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,SAAS,EAAE;YAClC,OAAO,EAAE,IAAI,CAAC,QAAQ;SACC,CAAC,CACzB;aACA,KAAK,CAAC,GAAG,CAAC,EAAE;YACZ,0BAA0B;YAC1B,sCAAsC;YACtC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACpB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,uDAAuD;IAC7C,aAAa,CAAC,IAAY,EAAE,IAAc;QACnD,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,qCAAuB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;IAChF,CAAC;IAEO,kBAAkB;QACzB,gCAAgC;QAChC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC;CACD;AAnFD,0CAmFC"}
@@ -0,0 +1,62 @@
1
+ import { InvalidResponseError } from 'web3-errors';
2
+ export class ChunkResponseParser {
3
+ constructor(eventEmitter, autoReconnect) {
4
+ this.eventEmitter = eventEmitter;
5
+ this.autoReconnect = autoReconnect;
6
+ this.chunkTimeout = 1000 * 15;
7
+ }
8
+ clearQueues() {
9
+ if (typeof this._clearQueues === 'function') {
10
+ this._clearQueues();
11
+ }
12
+ }
13
+ onError(clearQueues) {
14
+ this._clearQueues = clearQueues;
15
+ }
16
+ parseResponse(data) {
17
+ const returnValues = [];
18
+ // DE-CHUNKER
19
+ const dechunkedData = data
20
+ .replace(/\}[\n\r]?\{/g, '}|--|{') // }{
21
+ .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{
22
+ .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{
23
+ .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{
24
+ .split('|--|');
25
+ dechunkedData.forEach(_chunkData => {
26
+ // prepend the last chunk
27
+ let chunkData = _chunkData;
28
+ if (this.lastChunk) {
29
+ chunkData = this.lastChunk + chunkData;
30
+ }
31
+ let result;
32
+ try {
33
+ result = JSON.parse(chunkData);
34
+ }
35
+ catch (e) {
36
+ this.lastChunk = chunkData;
37
+ // start timeout to cancel all requests
38
+ if (this.lastChunkTimeout) {
39
+ clearTimeout(this.lastChunkTimeout);
40
+ }
41
+ this.lastChunkTimeout = setTimeout(() => {
42
+ if (this.autoReconnect)
43
+ return;
44
+ this.clearQueues();
45
+ this.eventEmitter.emit('error', new InvalidResponseError({
46
+ id: 1,
47
+ jsonrpc: '2.0',
48
+ error: { code: 2, message: 'Chunk timeout' },
49
+ }));
50
+ }, this.chunkTimeout);
51
+ return;
52
+ }
53
+ // cancel timeout and set chunk to null
54
+ clearTimeout(this.lastChunkTimeout);
55
+ this.lastChunk = undefined;
56
+ if (result)
57
+ returnValues.push(result);
58
+ });
59
+ return returnValues;
60
+ }
61
+ }
62
+ //# sourceMappingURL=chunk_response_parser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chunk_response_parser.js","sourceRoot":"","sources":["../../src/chunk_response_parser.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAInD,MAAM,OAAO,mBAAmB;IAQ/B,YAAmB,YAA0B,EAAE,aAAsB;QACpE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,IAAI,GAAG,EAAE,CAAC;IAC/B,CAAC;IACO,WAAW;QAClB,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,UAAU,EAAE;YAC5C,IAAI,CAAC,YAAY,EAAE,CAAC;SACpB;IACF,CAAC;IAEM,OAAO,CAAC,WAAwB;QACtC,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;I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AAC,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;gBACtB,OAAO;aACP;YAED,uCAAuC;YACvC,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YACpC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;YAE3B,IAAI,MAAM;gBAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;QAEH,OAAO,YAAY,CAAC;IACrB,CAAC;CACD"}
@@ -0,0 +1,603 @@
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
+ * @module Utils
19
+ */
20
+ import { keccak256 } from 'ethereum-cryptography/keccak.js';
21
+ import { bytesToUtf8, utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js';
22
+ import { isAddress, isHex, isHexStrict, isInt, isUInt, isNullish, utils, utils as validatorUtils, validator, bigintPower, } from 'web3-validator';
23
+ import { HexProcessingError, InvalidAddressError, InvalidBooleanError, InvalidBytesError, InvalidNumberError, InvalidUnitError, InvalidIntegerError, } from 'web3-errors';
24
+ import { isUint8Array } from './uint8array.js';
25
+ // Ref: https://ethdocs.org/en/latest/ether.html
26
+ // Note: this could be simplified using ** operator, but babel does not handle it well (https://github.com/babel/babel/issues/13109)
27
+ /** @internal */
28
+ export const ethUnitMap = {
29
+ noether: BigInt(0),
30
+ wei: BigInt(1),
31
+ kwei: BigInt(1000),
32
+ Kwei: BigInt(1000),
33
+ babbage: BigInt(1000),
34
+ femtoether: BigInt(1000),
35
+ mwei: BigInt(1000000),
36
+ Mwei: BigInt(1000000),
37
+ lovelace: BigInt(1000000),
38
+ picoether: BigInt(1000000),
39
+ gwei: BigInt(1000000000),
40
+ Gwei: BigInt(1000000000),
41
+ shannon: BigInt(1000000000),
42
+ nanoether: BigInt(1000000000),
43
+ nano: BigInt(1000000000),
44
+ szabo: BigInt(1000000000000),
45
+ microether: BigInt(1000000000000),
46
+ micro: BigInt(1000000000000),
47
+ finney: BigInt(1000000000000000),
48
+ milliether: BigInt(1000000000000000),
49
+ milli: BigInt(1000000000000000),
50
+ ether: BigInt('1000000000000000000'),
51
+ kether: BigInt('1000000000000000000000'),
52
+ grand: BigInt('1000000000000000000000'),
53
+ mether: BigInt('1000000000000000000000000'),
54
+ gether: BigInt('1000000000000000000000000000'),
55
+ tether: BigInt('1000000000000000000000000000000'),
56
+ };
57
+ const PrecisionLossWarning = 'Warning: Using type `number` with values that are large or contain many decimals may cause loss of precision, it is recommended to use type `string` or `BigInt` when using conversion methods';
58
+ /**
59
+ * Convert a value from bytes to Uint8Array
60
+ * @param data - Data to be converted
61
+ * @returns - The Uint8Array representation of the input data
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * console.log(web3.utils.bytesToUint8Array("0xab")));
66
+ * > Uint8Array(1) [ 171 ]
67
+ * ```
68
+ */
69
+ export const bytesToUint8Array = (data) => {
70
+ validator.validate(['bytes'], [data]);
71
+ if (isUint8Array(data)) {
72
+ return data;
73
+ }
74
+ if (Array.isArray(data)) {
75
+ return new Uint8Array(data);
76
+ }
77
+ if (typeof data === 'string') {
78
+ return validatorUtils.hexToUint8Array(data);
79
+ }
80
+ throw new InvalidBytesError(data);
81
+ };
82
+ /**
83
+ * @internal
84
+ */
85
+ const { uint8ArrayToHexString } = validatorUtils;
86
+ /**
87
+ * Convert a byte array to a hex string
88
+ * @param bytes - Byte array to be converted
89
+ * @returns - The hex string representation of the input byte array
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12])));
94
+ * > "0x480c"
95
+ *
96
+ */
97
+ export const bytesToHex = (bytes) => uint8ArrayToHexString(bytesToUint8Array(bytes));
98
+ /**
99
+ * Convert a hex string to a byte array
100
+ * @param hex - Hex string to be converted
101
+ * @returns - The byte array representation of the input hex string
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * console.log(web3.utils.hexToBytes('0x74657374'));
106
+ * > Uint8Array(4) [ 116, 101, 115, 116 ]
107
+ * ```
108
+ */
109
+ export const hexToBytes = (bytes) => {
110
+ if (typeof bytes === 'string' && bytes.slice(0, 2).toLowerCase() !== '0x') {
111
+ return bytesToUint8Array(`0x${bytes}`);
112
+ }
113
+ return bytesToUint8Array(bytes);
114
+ };
115
+ /**
116
+ * Converts value to it's number representation
117
+ * @param value - Hex string to be converted
118
+ * @returns - The number representation of the input value
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * conoslle.log(web3.utils.hexToNumber('0xa'));
123
+ * > 10
124
+ * ```
125
+ */
126
+ export const hexToNumber = (value) => {
127
+ validator.validate(['hex'], [value]);
128
+ // To avoid duplicate code and circular dependency we will
129
+ // use `hexToNumber` implementation from `web3-validator`
130
+ return validatorUtils.hexToNumber(value);
131
+ };
132
+ /**
133
+ * Converts value to it's number representation @alias `hexToNumber`
134
+ */
135
+ export const toDecimal = hexToNumber;
136
+ /**
137
+ * Converts value to it's hex representation
138
+ * @param value - Value to be converted
139
+ * @param hexstrict - Add padding to converted value if odd, to make it hexstrict
140
+ * @returns - The hex representation of the input value
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * console.log(web3.utils.numberToHex(10));
145
+ * > "0xa"
146
+ * ```
147
+ */
148
+ export const numberToHex = (value, hexstrict) => {
149
+ if (typeof value !== 'bigint')
150
+ validator.validate(['int'], [value]);
151
+ // To avoid duplicate code and circular dependency we will
152
+ // use `numberToHex` implementation from `web3-validator`
153
+ let updatedValue = validatorUtils.numberToHex(value);
154
+ if (hexstrict) {
155
+ if (!updatedValue.startsWith('-') && updatedValue.length % 2 === 1) {
156
+ // To avoid duplicate a circular dependency we will not be using the padLeft method
157
+ updatedValue = '0x0'.concat(updatedValue.slice(2));
158
+ }
159
+ else if (updatedValue.length % 2 === 0 && updatedValue.startsWith('-'))
160
+ updatedValue = '-0x0'.concat(updatedValue.slice(3));
161
+ }
162
+ return updatedValue;
163
+ };
164
+ /**
165
+ * Converts value to it's hex representation @alias `numberToHex`
166
+ *
167
+ */
168
+ export const fromDecimal = numberToHex;
169
+ /**
170
+ * Converts value to it's decimal representation in string
171
+ * @param value - Hex string to be converted
172
+ * @returns - The decimal representation of the input value
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * console.log(web3.utils.hexToNumberString('0xa'));
177
+ * > "10"
178
+ * ```
179
+ */
180
+ export const hexToNumberString = (data) => hexToNumber(data).toString();
181
+ /**
182
+ * Should be called to get hex representation (prefixed by 0x) of utf8 string
183
+ * @param str - Utf8 string to be converted
184
+ * @returns - The hex representation of the input string
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * console.log(utf8ToHex('web3.js'));
189
+ * > "0x776562332e6a73"
190
+ * ```
191
+ *
192
+ */
193
+ export const utf8ToHex = (str) => {
194
+ validator.validate(['string'], [str]);
195
+ // To be compatible with 1.x trim null character
196
+ // eslint-disable-next-line no-control-regex
197
+ let strWithoutNullCharacter = str.replace(/^(?:\u0000)/, '');
198
+ // eslint-disable-next-line no-control-regex
199
+ strWithoutNullCharacter = strWithoutNullCharacter.replace(/(?:\u0000)$/, '');
200
+ return bytesToHex(new TextEncoder().encode(strWithoutNullCharacter));
201
+ };
202
+ /**
203
+ * @alias utf8ToHex
204
+ */
205
+ export const fromUtf8 = utf8ToHex;
206
+ /**
207
+ * @alias utf8ToHex
208
+ */
209
+ export const stringToHex = utf8ToHex;
210
+ /**
211
+ * Should be called to get utf8 from it's hex representation
212
+ * @param str - Hex string to be converted
213
+ * @returns - Utf8 string
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64'));
218
+ * > Hello World
219
+ * ```
220
+ */
221
+ export const hexToUtf8 = (str) => bytesToUtf8(hexToBytes(str));
222
+ /**
223
+ * @alias hexToUtf8
224
+ */
225
+ export const toUtf8 = (input) => {
226
+ if (typeof input === 'string') {
227
+ return hexToUtf8(input);
228
+ }
229
+ validator.validate(['bytes'], [input]);
230
+ return bytesToUtf8(input);
231
+ };
232
+ export const utf8ToBytes = ecUtf8ToBytes;
233
+ /**
234
+ * @alias hexToUtf8
235
+ */
236
+ export const hexToString = hexToUtf8;
237
+ /**
238
+ * Should be called to get hex representation (prefixed by 0x) of ascii string
239
+ * @param str - String to be converted to hex
240
+ * @returns - Hex string
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * console.log(web3.utils.asciiToHex('Hello World'));
245
+ * > 0x48656c6c6f20576f726c64
246
+ * ```
247
+ */
248
+ export const asciiToHex = (str) => {
249
+ validator.validate(['string'], [str]);
250
+ let hexString = '';
251
+ for (let i = 0; i < str.length; i += 1) {
252
+ const hexCharCode = str.charCodeAt(i).toString(16);
253
+ // might need a leading 0
254
+ hexString += hexCharCode.length % 2 !== 0 ? `0${hexCharCode}` : hexCharCode;
255
+ }
256
+ return `0x${hexString}`;
257
+ };
258
+ /**
259
+ * @alias asciiToHex
260
+ */
261
+ export const fromAscii = asciiToHex;
262
+ /**
263
+ * Should be called to get ascii from it's hex representation
264
+ * @param str - Hex string to be converted to ascii
265
+ * @returns - Ascii string
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64'));
270
+ * > Hello World
271
+ * ```
272
+ */
273
+ export const hexToAscii = (str) => {
274
+ const decoder = new TextDecoder('ascii');
275
+ return decoder.decode(hexToBytes(str));
276
+ };
277
+ /**
278
+ * @alias hexToAscii
279
+ */
280
+ export const toAscii = hexToAscii;
281
+ /**
282
+ * Auto converts any given value into it's hex representation.
283
+ * @param value - Value to be converted to hex
284
+ * @param returnType - If true, it will return the type of the value
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * console.log(web3.utils.toHex(10));
289
+ * > 0xa
290
+ *
291
+ * console.log(web3.utils.toHex('0x123', true));
292
+ * > bytes
293
+ *```
294
+ */
295
+ export const toHex = (value, returnType) => {
296
+ if (typeof value === 'string' && isAddress(value)) {
297
+ return returnType ? 'address' : `0x${value.toLowerCase().replace(/^0x/i, '')}`;
298
+ }
299
+ if (typeof value === 'boolean') {
300
+ // eslint-disable-next-line no-nested-ternary
301
+ return returnType ? 'bool' : value ? '0x01' : '0x00';
302
+ }
303
+ if (typeof value === 'number') {
304
+ // eslint-disable-next-line no-nested-ternary
305
+ return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value);
306
+ }
307
+ if (typeof value === 'bigint') {
308
+ return returnType ? 'bigint' : numberToHex(value);
309
+ }
310
+ if (isUint8Array(value)) {
311
+ return returnType ? 'bytes' : bytesToHex(value);
312
+ }
313
+ if (typeof value === 'object' && !!value) {
314
+ return returnType ? 'string' : utf8ToHex(JSON.stringify(value));
315
+ }
316
+ if (typeof value === 'string') {
317
+ if (value.startsWith('-0x') || value.startsWith('-0X')) {
318
+ return returnType ? 'int256' : numberToHex(value);
319
+ }
320
+ if (isHexStrict(value)) {
321
+ return returnType ? 'bytes' : value;
322
+ }
323
+ if (isHex(value) && !isInt(value) && !isUInt(value)) {
324
+ return returnType ? 'bytes' : `0x${value}`;
325
+ }
326
+ if (isHex(value) && !isInt(value) && isUInt(value)) {
327
+ // This condition seems problematic because meeting
328
+ // both conditions `!isInt(value) && isUInt(value)` should be impossible.
329
+ // But a value pass for those conditions: "101611154195520776335741463917853444671577865378275924493376429267637792638729"
330
+ // Note that according to the docs: it is supposed to be treated as a string (https://docs.web3js.org/guides/web3_upgrade_guide/x/web3_utils_migration_guide#conversion-to-hex)
331
+ // In short, the strange is that isInt(value) is false but isUInt(value) is true for the value above.
332
+ // TODO: isUInt(value) should be investigated.
333
+ // However, if `toHex('101611154195520776335741463917853444671577865378275924493376429267637792638729', true)` is called, it will return `true`.
334
+ // But, if `toHex('101611154195520776335741463917853444671577865378275924493376429267637792638729')` is called, it will throw inside `numberToHex`.
335
+ return returnType ? 'uint' : numberToHex(value);
336
+ }
337
+ if (!Number.isFinite(value)) {
338
+ return returnType ? 'string' : utf8ToHex(value);
339
+ }
340
+ }
341
+ throw new HexProcessingError(value);
342
+ };
343
+ /**
344
+ * Converts any given value into it's number representation, if possible, else into it's bigint representation.
345
+ * @param value - The value to convert
346
+ * @returns - Returns the value in number or bigint representation
347
+ *
348
+ * @example
349
+ * ```ts
350
+ * console.log(web3.utils.toNumber(1));
351
+ * > 1
352
+ * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER));
353
+ * > 9007199254740991
354
+ *
355
+ * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER)));
356
+ * > 9007199254740991
357
+ *
358
+ * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)));
359
+ * > 9007199254740992n
360
+ *
361
+ * ```
362
+ */
363
+ export const toNumber = (value) => {
364
+ if (typeof value === 'number') {
365
+ if (value > 1e20) {
366
+ console.warn(PrecisionLossWarning);
367
+ // JavaScript converts numbers >= 10^21 to scientific notation when coerced to strings,
368
+ // leading to potential parsing errors and incorrect representations.
369
+ // For instance, String(10000000000000000000000) yields '1e+22'.
370
+ // Using BigInt prevents this
371
+ return BigInt(value);
372
+ }
373
+ return value;
374
+ }
375
+ if (typeof value === 'bigint') {
376
+ return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER
377
+ ? Number(value)
378
+ : value;
379
+ }
380
+ if (typeof value === 'string' && isHexStrict(value)) {
381
+ return hexToNumber(value);
382
+ }
383
+ try {
384
+ return toNumber(BigInt(value));
385
+ }
386
+ catch (_a) {
387
+ throw new InvalidNumberError(value);
388
+ }
389
+ };
390
+ /**
391
+ * Auto converts any given value into it's bigint representation
392
+ *
393
+ * @param value - The value to convert
394
+ * @returns - Returns the value in bigint representation
395
+
396
+ * @example
397
+ * ```ts
398
+ * console.log(web3.utils.toBigInt(1));
399
+ * > 1n
400
+ * ```
401
+ */
402
+ export const toBigInt = (value) => {
403
+ if (typeof value === 'number') {
404
+ return BigInt(value);
405
+ }
406
+ if (typeof value === 'bigint') {
407
+ return value;
408
+ }
409
+ // isHex passes for dec, too
410
+ if (typeof value === 'string' && isHex(value)) {
411
+ if (value.startsWith('-')) {
412
+ return -BigInt(value.substring(1));
413
+ }
414
+ return BigInt(value);
415
+ }
416
+ throw new InvalidNumberError(value);
417
+ };
418
+ /**
419
+ * Takes a number of wei and converts it to any other ether unit.
420
+ * @param number - The value in wei
421
+ * @param unit - The unit to convert to
422
+ * @returns - Returns the converted value in the given unit
423
+ *
424
+ * @example
425
+ * ```ts
426
+ * console.log(web3.utils.fromWei("1", "ether"));
427
+ * > 0.000000000000000001
428
+ *
429
+ * console.log(web3.utils.fromWei("1", "shannon"));
430
+ * > 0.000000001
431
+ * ```
432
+ */
433
+ export const fromWei = (number, unit) => {
434
+ let denomination;
435
+ if (typeof unit === 'string') {
436
+ denomination = ethUnitMap[unit];
437
+ if (!denomination) {
438
+ throw new InvalidUnitError(unit);
439
+ }
440
+ }
441
+ else {
442
+ if (unit < 0 || !Number.isInteger(unit)) {
443
+ throw new InvalidIntegerError(unit);
444
+ }
445
+ denomination = bigintPower(BigInt(10), BigInt(unit));
446
+ }
447
+ // value in wei would always be integer
448
+ // 13456789, 1234
449
+ const value = String(toNumber(number));
450
+ // count number of zeros in denomination
451
+ // 1000000 -> 6
452
+ const numberOfZerosInDenomination = denomination.toString().length - 1;
453
+ if (numberOfZerosInDenomination <= 0) {
454
+ return value.toString();
455
+ }
456
+ // pad the value with required zeros
457
+ // 13456789 -> 13456789, 1234 -> 001234
458
+ const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, '0');
459
+ // get the integer part of value by counting number of zeros from start
460
+ // 13456789 -> '13'
461
+ // 001234 -> ''
462
+ const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);
463
+ // get the fraction part of value by counting number of zeros backward
464
+ // 13456789 -> '456789'
465
+ // 001234 -> '001234'
466
+ const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, '');
467
+ if (integer === '') {
468
+ return `0.${fraction}`;
469
+ }
470
+ if (fraction === '') {
471
+ return integer;
472
+ }
473
+ const updatedValue = `${integer}.${fraction}`;
474
+ return updatedValue.slice(0, integer.length + numberOfZerosInDenomination + 1);
475
+ };
476
+ /**
477
+ * Takes a number of a unit and converts it to wei.
478
+ *
479
+ * @param number - The number to convert.
480
+ * @param unit - {@link EtherUnits} The unit of the number passed.
481
+ * @returns The number converted to wei.
482
+ *
483
+ * @example
484
+ * ```ts
485
+ * console.log(web3.utils.toWei("0.001", "ether"));
486
+ * > 1000000000000000 //(wei)
487
+ * ```
488
+ */
489
+ // todo in 1.x unit defaults to 'ether'
490
+ export const toWei = (number, unit) => {
491
+ validator.validate(['number'], [number]);
492
+ let denomination;
493
+ if (typeof unit === 'string') {
494
+ denomination = ethUnitMap[unit];
495
+ if (!denomination) {
496
+ throw new InvalidUnitError(unit);
497
+ }
498
+ }
499
+ else {
500
+ if (unit < 0 || !Number.isInteger(unit)) {
501
+ throw new InvalidIntegerError(unit);
502
+ }
503
+ denomination = bigintPower(BigInt(10), BigInt(unit));
504
+ }
505
+ let parsedNumber = number;
506
+ if (typeof parsedNumber === 'number') {
507
+ if (parsedNumber < 1e-15) {
508
+ console.warn(PrecisionLossWarning);
509
+ }
510
+ if (parsedNumber > 1e20) {
511
+ console.warn(PrecisionLossWarning);
512
+ parsedNumber = BigInt(parsedNumber);
513
+ }
514
+ else {
515
+ // in case there is a decimal point, we need to convert it to string
516
+ parsedNumber = parsedNumber.toLocaleString('fullwide', {
517
+ useGrouping: false,
518
+ maximumFractionDigits: 20,
519
+ });
520
+ }
521
+ }
522
+ // if value is decimal e.g. 24.56 extract `integer` and `fraction` part
523
+ // to avoid `fraction` to be null use `concat` with empty string
524
+ const [integer, fraction] = String(typeof parsedNumber === 'string' && !isHexStrict(parsedNumber)
525
+ ? parsedNumber
526
+ : toNumber(parsedNumber))
527
+ .split('.')
528
+ .concat('');
529
+ // join the value removing `.` from
530
+ // 24.56 -> 2456
531
+ const value = BigInt(`${integer}${fraction}`);
532
+ // multiply value with denomination
533
+ // 2456 * 1000000 -> 2456000000
534
+ const updatedValue = value * denomination;
535
+ // check if whole number was passed in
536
+ const decimals = fraction.length;
537
+ if (decimals === 0) {
538
+ return updatedValue.toString();
539
+ }
540
+ // trim the value to remove extra zeros
541
+ return updatedValue.toString().slice(0, -decimals);
542
+ };
543
+ /**
544
+ * Will convert an upper or lowercase Ethereum address to a checksum address.
545
+ * @param address - An address string
546
+ * @returns The checksum address
547
+ * @example
548
+ * ```ts
549
+ * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
550
+ * > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"
551
+ * ```
552
+ */
553
+ export const toChecksumAddress = (address) => {
554
+ if (!isAddress(address, false)) {
555
+ throw new InvalidAddressError(address);
556
+ }
557
+ const lowerCaseAddress = address.toLowerCase().replace(/^0x/i, '');
558
+ // calling `Uint8Array.from` because `noble-hashes` checks with `instanceof Uint8Array` that fails in some edge cases:
559
+ // https://github.com/paulmillr/noble-hashes/issues/25#issuecomment-1750106284
560
+ const hash = utils.uint8ArrayToHexString(keccak256(validatorUtils.ensureIfUint8Array(utf8ToBytes(lowerCaseAddress))));
561
+ if (isNullish(hash) ||
562
+ hash === '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470')
563
+ return ''; // // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data
564
+ let checksumAddress = '0x';
565
+ const addressHash = hash.replace(/^0x/i, '');
566
+ for (let i = 0; i < lowerCaseAddress.length; i += 1) {
567
+ // If ith character is 8 to f then make it uppercase
568
+ if (parseInt(addressHash[i], 16) > 7) {
569
+ checksumAddress += lowerCaseAddress[i].toUpperCase();
570
+ }
571
+ else {
572
+ checksumAddress += lowerCaseAddress[i];
573
+ }
574
+ }
575
+ return checksumAddress;
576
+ };
577
+ export const toBool = (value) => {
578
+ if (typeof value === 'boolean') {
579
+ return value;
580
+ }
581
+ if (typeof value === 'number' && (value === 0 || value === 1)) {
582
+ return Boolean(value);
583
+ }
584
+ if (typeof value === 'bigint' && (value === BigInt(0) || value === BigInt(1))) {
585
+ return Boolean(value);
586
+ }
587
+ if (typeof value === 'string' &&
588
+ !isHexStrict(value) &&
589
+ (value === '1' || value === '0' || value === 'false' || value === 'true')) {
590
+ if (value === 'true') {
591
+ return true;
592
+ }
593
+ if (value === 'false') {
594
+ return false;
595
+ }
596
+ return Boolean(Number(value));
597
+ }
598
+ if (typeof value === 'string' && isHexStrict(value) && (value === '0x1' || value === '0x0')) {
599
+ return Boolean(toNumber(value));
600
+ }
601
+ throw new InvalidBooleanError(value);
602
+ };
603
+ //# sourceMappingURL=converters.js.map