Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Commit 884fa09

Browse files
committed
fix(#7044): toWei trim strings with more than 20 decimal places
1 parent 2f73aa5 commit 884fa09

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2480,6 +2480,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
24802480

24812481
#### web3-utils
24822482

2483+
- Fixed `toWei` to avoid returning wrong value when more than 20 decimals passed as string (#7044)
24832484

24842485
### Fixed
24852486

packages/web3-utils/src/converters.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -558,21 +558,22 @@ export const toWei = (number: Numbers, unit: EtherUnits): string => {
558558
if (!denomination) {
559559
throw new InvalidUnitError(unit);
560560
}
561-
let parsedNumber = number;
562-
if (typeof parsedNumber === 'number'){
563-
if (parsedNumber < 1e-15){
561+
let parsedNumber: string;
562+
if (typeof number === 'number'){
563+
if (number < 1e-15){
564564
console.warn(PrecisionLossWarning)
565565
}
566-
if (parsedNumber > 1e+20) {
566+
if (number > 1e+20) {
567567
console.warn(PrecisionLossWarning)
568568

569-
parsedNumber = BigInt(parsedNumber);
569+
parsedNumber = BigInt(number).toLocaleString('fullwide');
570570
} else {
571571
// in case there is a decimal point, we need to convert it to string
572-
parsedNumber = parsedNumber.toLocaleString('fullwide', {useGrouping: false, maximumFractionDigits: 20})
573-
}
572+
parsedNumber = number.toLocaleString('fullwide', {useGrouping: false, maximumFractionDigits: 20})
573+
}
574+
574575
}
575-
576+
576577
// if value is decimal e.g. 24.56 extract `integer` and `fraction` part
577578
// to avoid `fraction` to be null use `concat` with empty string
578579
const [integer, fraction] = String(
@@ -581,10 +582,17 @@ export const toWei = (number: Numbers, unit: EtherUnits): string => {
581582
.split('.')
582583
.concat('');
583584

585+
// if the number of decimal places is over 20 we need to trim the extra decimal places before multiplying by
586+
// the denomination to avoid returning an invalid result
587+
let trimmedFraction = fraction
588+
if (fraction.length >= 20) {
589+
console.warn(PrecisionLossWarning)
590+
trimmedFraction = fraction.substring(0,20)
591+
}
592+
584593
// join the value removing `.` from
585594
// 24.56 -> 2456
586-
587-
const value = BigInt(`${integer}${fraction}`);
595+
const value = BigInt(`${integer}${trimmedFraction}`);
588596

589597
// multiply value with denomination
590598
// 2456 * 1000000 -> 2456000000

0 commit comments

Comments
 (0)