-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
converters.ts
643 lines (558 loc) · 16.5 KB
/
converters.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import { keccak256 } from 'ethereum-cryptography/keccak.js';
import { bytesToUtf8, utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js';
import { Address, Bytes, HexString, Numbers, ValueTypes } from 'web3-types';
import {
isAddress,
isHex,
isHexStrict,
isInt,
isNullish,
utils,
utils as validatorUtils,
validator,
} from 'web3-validator';
import {
HexProcessingError,
InvalidAddressError,
InvalidBooleanError,
InvalidBytesError,
InvalidNumberError,
InvalidUnitError,
} from 'web3-errors';
const base = BigInt(10);
const expo10 = (expo: number) => base ** BigInt(expo);
// Ref: https://ethdocs.org/en/latest/ether.html
/** @internal */
export const ethUnitMap = {
noether: BigInt('0'),
wei: BigInt(1),
kwei: expo10(3),
Kwei: expo10(3),
babbage: expo10(3),
femtoether: expo10(3),
mwei: expo10(6),
Mwei: expo10(6),
lovelace: expo10(6),
picoether: expo10(6),
gwei: expo10(9),
Gwei: expo10(9),
shannon: expo10(9),
nanoether: expo10(9),
nano: expo10(9),
szabo: expo10(12),
microether: expo10(12),
micro: expo10(12),
finney: expo10(15),
milliether: expo10(15),
milli: expo10(15),
ether: expo10(18),
kether: expo10(21),
grand: expo10(21),
mether: expo10(24),
gether: expo10(27),
tether: expo10(30),
};
export type EtherUnits = keyof typeof ethUnitMap;
/**
* Convert a value from bytes to Uint8Array
* @param data - Data to be converted
* @returns - The Uint8Array representation of the input data
*
* @example
* ```ts
* console.log(web3.utils.bytesToUint8Array("0xab")));
* > Uint8Array(1) [ 171 ]
* ```
*/
export const bytesToUint8Array = (data: Bytes): Uint8Array | never => {
validator.validate(['bytes'], [data]);
if (data instanceof Uint8Array) {
return data;
}
if (Array.isArray(data)) {
return new Uint8Array(data);
}
if (typeof data === 'string') {
return validatorUtils.hexToUint8Array(data);
}
throw new InvalidBytesError(data);
};
/**
* @internal
*/
const { uint8ArrayToHexString } = validatorUtils;
/**
* Convert a byte array to a hex string
* @param bytes - Byte array to be converted
* @returns - The hex string representation of the input byte array
*
* @example
* ```ts
* console.log(web3.utils.bytesToHex(new Uint8Array([72, 12])));
* > "0x480c"
*
*/
export const bytesToHex = (bytes: Bytes): HexString =>
uint8ArrayToHexString(bytesToUint8Array(bytes));
/**
* Convert a hex string to a byte array
* @param hex - Hex string to be converted
* @returns - The byte array representation of the input hex string
*
* @example
* ```ts
* console.log(web3.utils.hexToBytes('0x74657374'));
* > Uint8Array(4) [ 116, 101, 115, 116 ]
* ```
*/
export const hexToBytes = (bytes: HexString): Uint8Array => {
if (typeof bytes === 'string' && bytes.slice(0, 2).toLowerCase() !== '0x') {
return bytesToUint8Array(`0x${bytes}`);
}
return bytesToUint8Array(bytes);
};
/**
* Converts value to it's number representation
* @param value - Hex string to be converted
* @returns - The number representation of the input value
*
* @example
* ```ts
* conoslle.log(web3.utils.hexToNumber('0xa'));
* > 10
* ```
*/
export const hexToNumber = (value: HexString): bigint | number => {
validator.validate(['hex'], [value]);
// To avoid duplicate code and circular dependency we will
// use `hexToNumber` implementation from `web3-validator`
return validatorUtils.hexToNumber(value);
};
/**
* Converts value to it's number representation @alias `hexToNumber`
*/
export const toDecimal = hexToNumber;
/**
* Converts value to it's hex representation
* @param value - Value to be converted
* @param hexstrict - Add padding to converted value if odd, to make it hexstrict
* @returns - The hex representation of the input value
*
* @example
* ```ts
* console.log(web3.utils.numberToHex(10));
* > "0xa"
* ```
*/
export const numberToHex = (value: Numbers, hexstrict?: boolean): HexString => {
if (typeof value !== 'bigint') validator.validate(['int'], [value]);
// To avoid duplicate code and circular dependency we will
// use `numberToHex` implementation from `web3-validator`
let updatedValue = validatorUtils.numberToHex(value);
if (hexstrict) {
if (!updatedValue.startsWith('-') && updatedValue.length % 2 === 1) {
// To avoid duplicate a circular dependancy we will not be using the padLeft method
updatedValue = '0x0'.concat(updatedValue.slice(2));
} else if (updatedValue.length % 2 === 0 && updatedValue.startsWith('-'))
updatedValue = '-0x0'.concat(updatedValue.slice(3));
}
return updatedValue;
};
/**
* Converts value to it's hex representation @alias `numberToHex`
*
*/
export const fromDecimal = numberToHex;
/**
* Converts value to it's decimal representation in string
* @param value - Hex string to be converted
* @returns - The decimal representation of the input value
*
* @example
* ```ts
* console.log(web3.utils.hexToNumberString('0xa'));
* > "10"
* ```
*/
export const hexToNumberString = (data: HexString): string => hexToNumber(data).toString();
/**
* Should be called to get hex representation (prefixed by 0x) of utf8 string
* @param str - Utf8 string to be converted
* @returns - The hex representation of the input string
*
* @example
* ```ts
* console.log(utf8ToHex('web3.js'));
* > "0x776562332e6a73"
*
*/
export const utf8ToHex = (str: string): HexString => {
validator.validate(['string'], [str]);
// To be compatible with 1.x trim null character
// eslint-disable-next-line no-control-regex
let strWithoutNullCharacter = str.replace(/^(?:\u0000)/, '');
// eslint-disable-next-line no-control-regex
strWithoutNullCharacter = strWithoutNullCharacter.replace(/(?:\u0000)$/, '');
return bytesToHex(new TextEncoder().encode(strWithoutNullCharacter));
};
/**
* @alias utf8ToHex
*/
export const fromUtf8 = utf8ToHex;
/**
* @alias utf8ToHex
*/
export const stringToHex = utf8ToHex;
/**
* Should be called to get utf8 from it's hex representation
* @param str - Hex string to be converted
* @returns - Utf8 string
*
* @example
* ```ts
* console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64'));
* > Hello World
* ```
*/
export const hexToUtf8 = (str: HexString): string => bytesToUtf8(hexToBytes(str));
/**
* @alias hexToUtf8
*/
export const toUtf8 = (input: HexString | Uint8Array) => {
if (typeof input === 'string') {
return hexToUtf8(input);
}
validator.validate(['bytes'], [input]);
return bytesToUtf8(input);
};
export const utf8ToBytes = ecUtf8ToBytes;
/**
* @alias hexToUtf8
*/
export const hexToString = hexToUtf8;
/**
* Should be called to get hex representation (prefixed by 0x) of ascii string
* @param str - String to be converted to hex
* @returns - Hex string
*
* @example
* ```ts
* console.log(web3.utils.asciiToHex('Hello World'));
* > 0x48656c6c6f20576f726c64
* ```
*/
export const asciiToHex = (str: string): HexString => {
validator.validate(['string'], [str]);
let hexString = '';
for (let i = 0; i < str.length; i += 1) {
const hexCharCode = str.charCodeAt(i).toString(16);
// might need a leading 0
hexString += hexCharCode.length % 2 !== 0 ? `0${hexCharCode}` : hexCharCode;
}
return `0x${hexString}`;
};
/**
* @alias asciiToHex
*/
export const fromAscii = asciiToHex;
/**
* Should be called to get ascii from it's hex representation
* @param str - Hex string to be converted to ascii
* @returns - Ascii string
*
* @example
* ```ts
* console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64'));
* > Hello World
* ```
*/
export const hexToAscii = (str: HexString): string => {
const decoder = new TextDecoder('ascii');
return decoder.decode(hexToBytes(str));
};
/**
* @alias hexToAscii
*/
export const toAscii = hexToAscii;
/**
* Auto converts any given value into it's hex representation.
* @param value - Value to be converted to hex
* @param returnType - If true, it will return the type of the value
*
* @example
* ```ts
* console.log(web3.utils.toHex(10));
* > 0xa
*
* console.log(web3.utils.toHex('0x123', true));
* > bytes
*```
*/
export const toHex = (
value: Numbers | Bytes | Address | boolean | object,
returnType?: boolean,
): HexString | ValueTypes => {
if (typeof value === 'string' && isAddress(value)) {
return returnType ? 'address' : `0x${value.toLowerCase().replace(/^0x/i, '')}`;
}
if (typeof value === 'boolean') {
// eslint-disable-next-line no-nested-ternary
return returnType ? 'bool' : value ? '0x01' : '0x00';
}
if (typeof value === 'number') {
// eslint-disable-next-line no-nested-ternary
return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value);
}
if (typeof value === 'bigint') {
return returnType ? 'bigint' : numberToHex(value);
}
if (typeof value === 'object' && !!value) {
return returnType ? 'string' : utf8ToHex(JSON.stringify(value));
}
if (typeof value === 'string') {
if (value.startsWith('-0x') || value.startsWith('-0X')) {
return returnType ? 'int256' : numberToHex(value);
}
if (isHexStrict(value)) {
return returnType ? 'bytes' : value;
}
if (isHex(value) && !isInt(value)) {
return returnType ? 'bytes' : `0x${value}`;
}
if (!Number.isFinite(value)) {
return returnType ? 'string' : utf8ToHex(value);
}
}
throw new HexProcessingError(value);
};
/**
* Converts any given value into it's number representation, if possible, else into it's bigint representation.
* @param value - The value to convert
* @returns - Returns the value in number or bigint representation
*
* @example
* ```ts
* console.log(web3.utils.toNumber(1));
* > 1
* console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER));
* > 9007199254740991
*
* console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER)));
* > 9007199254740991
*
* console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)));
* > 9007199254740992n
*
* ```
*/
export const toNumber = (value: Numbers): number | bigint => {
if (typeof value === 'number') {
return value;
}
if (typeof value === 'bigint') {
return value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER
? Number(value)
: value;
}
if (typeof value === 'string' && isHexStrict(value)) {
return hexToNumber(value);
}
try {
return toNumber(BigInt(value));
} catch {
throw new InvalidNumberError(value);
}
};
/**
* Auto converts any given value into it's bigint representation
*
* @param value - The value to convert
* @returns - Returns the value in bigint representation
* @example
* ```ts
* console.log(web3.utils.toBigInt(1));
* > 1n
* ```
*/
export const toBigInt = (value: unknown): bigint => {
if (typeof value === 'number') {
return BigInt(value);
}
if (typeof value === 'bigint') {
return value;
}
// isHex passes for dec, too
if (typeof value === 'string' && isHex(value)) {
if (value.startsWith('-')) {
return -BigInt(value.substring(1));
}
return BigInt(value);
}
throw new InvalidNumberError(value);
};
/**
* Takes a number of wei and converts it to any other ether unit.
* @param number - The value in wei
* @param unit - The unit to convert to
* @returns - Returns the converted value in the given unit
*
* @example
* ```ts
* console.log(web3.utils.fromWei("1", "ether"));
* > 0.000000000000000001
*
* console.log(web3.utils.fromWei("1", "shannon"));
* > 0.000000001
* ```
*/
export const fromWei = (number: Numbers, unit: EtherUnits): string => {
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new InvalidUnitError(unit);
}
// value in wei would always be integer
// 13456789, 1234
const value = String(toNumber(number));
// count number of zeros in denomination
// 1000000 -> 6
const numberOfZerosInDenomination = denomination.toString().length - 1;
if (numberOfZerosInDenomination <= 0) {
return value.toString();
}
// pad the value with required zeros
// 13456789 -> 13456789, 1234 -> 001234
const zeroPaddedValue = value.padStart(numberOfZerosInDenomination, '0');
// get the integer part of value by counting number of zeros from start
// 13456789 -> '13'
// 001234 -> ''
const integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);
// get the fraction part of value by counting number of zeros backward
// 13456789 -> '456789'
// 001234 -> '001234'
const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, '');
if (integer === '') {
return `0.${fraction}`;
}
if (fraction === '') {
return integer;
}
return `${integer}.${fraction}`;
};
/**
* Takes a number of a unit and converts it to wei.
*
* @param number - The number to convert.
* @param unit - {@link EtherUnits} The unit of the number passed.
* @returns The number converted to wei.
*
* @example
* ```ts
* console.log(web3.utils.toWei("0.001", "ether"));
* > 1000000000000000 //(wei)
* ```
*/
// todo in 1.x unit defaults to 'ether'
export const toWei = (number: Numbers, unit: EtherUnits): string => {
validator.validate(['number'], [number]);
const denomination = ethUnitMap[unit];
if (!denomination) {
throw new InvalidUnitError(unit);
}
// if value is decimal e.g. 24.56 extract `integer` and `fraction` part
// to avoid `fraction` to be null use `concat` with empty string
const [integer, fraction] = String(
typeof number === 'string' && !isHexStrict(number) ? number : toNumber(number),
)
.split('.')
.concat('');
// join the value removing `.` from
// 24.56 -> 2456
const value = BigInt(`${integer}${fraction}`);
// multiply value with denomination
// 2456 * 1000000 -> 2456000000
const updatedValue = value * denomination;
// count number of zeros in denomination
const numberOfZerosInDenomination = denomination.toString().length - 1;
// check which either `fraction` or `denomination` have lower number of zeros
const decimals = Math.min(fraction.length, numberOfZerosInDenomination);
if (decimals === 0) {
return updatedValue.toString();
}
// Add zeros to make length equal to required decimal points
// If string is larger than decimal points required then remove last zeros
return updatedValue.toString().padStart(decimals, '0').slice(0, -decimals);
};
/**
* Will convert an upper or lowercase Ethereum address to a checksum address.
* @param address - An address string
* @returns The checksum address
* @example
* ```ts
* web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
* > "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"
* ```
*/
export const toChecksumAddress = (address: Address): string => {
if (!isAddress(address, false)) {
throw new InvalidAddressError(address);
}
const lowerCaseAddress = address.toLowerCase().replace(/^0x/i, '');
const hash = utils.uint8ArrayToHexString(keccak256(utf8ToBytes(lowerCaseAddress)));
if (
isNullish(hash) ||
hash === '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
)
return ''; // // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data
let checksumAddress = '0x';
const addressHash = hash.replace(/^0x/i, '');
for (let i = 0; i < lowerCaseAddress.length; i += 1) {
// If ith character is 8 to f then make it uppercase
if (parseInt(addressHash[i], 16) > 7) {
checksumAddress += lowerCaseAddress[i].toUpperCase();
} else {
checksumAddress += lowerCaseAddress[i];
}
}
return checksumAddress;
};
export const toBool = (value: boolean | string | number | unknown): boolean => {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number' && (value === 0 || value === 1)) {
return Boolean(value);
}
if (typeof value === 'bigint' && (value === BigInt(0) || value === BigInt(1))) {
return Boolean(value);
}
if (
typeof value === 'string' &&
!isHexStrict(value) &&
(value === '1' || value === '0' || value === 'false' || value === 'true')
) {
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
return Boolean(Number(value));
}
if (typeof value === 'string' && isHexStrict(value) && (value === '0x1' || value === '0x0')) {
return Boolean(toNumber(value));
}
throw new InvalidBooleanError(value);
};