From a83e9d57ffe318331e820d307afe6f179a759225 Mon Sep 17 00:00:00 2001 From: sgerodes Date: Mon, 25 Mar 2024 15:07:35 +0100 Subject: [PATCH] fix: fromWei() parsing of large numbers > 10^20 (#6882) * Fix scientific notation parsing for large numbers with BigInt Prevent automatic conversion to scientific notation for numbers >= 10^21 by using BigInt, ensuring accurate string representations and avoiding parsing errors in fromWei function. * Update Tests for scientific notation number parsing. * refactor: minor code cleaning * docs: Update changelog for #6882 * Update CHANGELOG.md --------- Co-authored-by: Alex Co-authored-by: Alex --- packages/web3-utils/CHANGELOG.md | 7 ++++++- packages/web3-utils/src/converters.ts | 7 +++++++ packages/web3-utils/test/fixtures/converters.ts | 5 ++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/web3-utils/CHANGELOG.md b/packages/web3-utils/CHANGELOG.md index 35301f35341..70e08ea813f 100644 --- a/packages/web3-utils/CHANGELOG.md +++ b/packages/web3-utils/CHANGELOG.md @@ -199,4 +199,9 @@ Documentation: - replaced our eventEmitter to EventEmitter3 to support react native builds (#6253) -## [Unreleased] \ No newline at end of file +## [Unreleased] + +### Fixed + +- fixed erroneous parsing of big numbers in the `fromWei(...)` function (#6880) + diff --git a/packages/web3-utils/src/converters.ts b/packages/web3-utils/src/converters.ts index 3d005ca3deb..862e9e31d53 100644 --- a/packages/web3-utils/src/converters.ts +++ b/packages/web3-utils/src/converters.ts @@ -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; } diff --git a/packages/web3-utils/test/fixtures/converters.ts b/packages/web3-utils/test/fixtures/converters.ts index 464c196b32d..0161c86cd6d 100644 --- a/packages/web3-utils/test/fixtures/converters.ts +++ b/packages/web3-utils/test/fixtures/converters.ts @@ -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][] = [