Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fromWei() parsing of large numbers > 10^20 #6882

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/web3-utils/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,9 @@ Documentation:

- replaced our eventEmitter to EventEmitter3 to support react native builds (#6253)

## [Unreleased]
## [Unreleased]

### Fixed

- fixed erroneous parsing of big numbers in the `fromWei(...)` function (#6880)

7 changes: 7 additions & 0 deletions packages/web3-utils/src/converters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,13 @@ export const toHex = (
*/
export const toNumber = (value: Numbers): number | bigint => {
if (typeof value === 'number') {
if (value > 1e+20) {
// JavaScript converts numbers >= 10^21 to scientific notation when coerced to strings,
// leading to potential parsing errors and incorrect representations.
// For instance, String(10000000000000000000000) yields '1e+22'.
// Using BigInt prevents this
return BigInt(value);
}
return value;
}

Expand Down
5 changes: 4 additions & 1 deletion packages/web3-utils/test/fixtures/converters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,10 @@ const conversionBaseData: [[Numbers, EtherUnits], string][] = [

export const fromWeiValidData: [[Numbers, EtherUnits], string][] = [
...conversionBaseData,
[['0xff', 'wei'], '255'],
[['0xff', 'wei'], '255'],
[[1e+22, 'ether'], '10000'],
[[19999999999999991611392, 'ether'], '19999.999999999991611392'],
[[1.9999999999999991611392e+22, 'ether'], '19999.999999999991611392'],
];

export const toWeiValidData: [[Numbers, EtherUnits], string][] = [
Expand Down
Loading