Skip to content

Commit

Permalink
fix(web3#7044): toWei trim strings with more than 20 decimal places
Browse files Browse the repository at this point in the history
  • Loading branch information
gordon-to committed May 17, 2024
1 parent 2f73aa5 commit 052b799
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions packages/web3-utils/src/converters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,21 +558,22 @@ export const toWei = (number: Numbers, unit: EtherUnits): string => {
if (!denomination) {
throw new InvalidUnitError(unit);
}
let parsedNumber = number;
if (typeof parsedNumber === 'number'){
if (parsedNumber < 1e-15){
let parsedNumber: string;
if (typeof number === 'number'){
if (number < 1e-15){
console.warn(PrecisionLossWarning)
}
if (parsedNumber > 1e+20) {
if (number > 1e+20) {
console.warn(PrecisionLossWarning)

parsedNumber = BigInt(parsedNumber);
parsedNumber = BigInt(number).toLocaleString('fullwide');
} else {
// in case there is a decimal point, we need to convert it to string
parsedNumber = parsedNumber.toLocaleString('fullwide', {useGrouping: false, maximumFractionDigits: 20})
}
parsedNumber = number.toLocaleString('fullwide', {useGrouping: false, maximumFractionDigits: 20})
}

}

// 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(
Expand All @@ -581,10 +582,17 @@ export const toWei = (number: Numbers, unit: EtherUnits): string => {
.split('.')
.concat('');

// if the number of decimal places is over 20 we need to trim the extra decimal places before multiplying by
// the denomination to avoid returning an invalid result
let trimmedFraction = fraction
if (fraction.length >= 20) {
console.warn(PrecisionLossWarning)
trimmedFraction = fraction.substring(0,20)
}

// join the value removing `.` from
// 24.56 -> 2456

const value = BigInt(`${integer}${fraction}`);
const value = BigInt(`${integer}${trimmedFraction}`);

// multiply value with denomination
// 2456 * 1000000 -> 2456000000
Expand Down

0 comments on commit 052b799

Please sign in to comment.