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

Commit a83e9d5

Browse files
sgerodesAlexluu-alex
authored
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 <alex.luu@mail.utoronto.ca> Co-authored-by: Alex <luu.alex98@gmail.com>
1 parent 1f81ff0 commit a83e9d5

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

packages/web3-utils/CHANGELOG.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,4 +199,9 @@ Documentation:
199199

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

202-
## [Unreleased]
202+
## [Unreleased]
203+
204+
### Fixed
205+
206+
- fixed erroneous parsing of big numbers in the `fromWei(...)` function (#6880)
207+

packages/web3-utils/src/converters.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,13 @@ export const toHex = (
411411
*/
412412
export const toNumber = (value: Numbers): number | bigint => {
413413
if (typeof value === 'number') {
414+
if (value > 1e+20) {
415+
// JavaScript converts numbers >= 10^21 to scientific notation when coerced to strings,
416+
// leading to potential parsing errors and incorrect representations.
417+
// For instance, String(10000000000000000000000) yields '1e+22'.
418+
// Using BigInt prevents this
419+
return BigInt(value);
420+
}
414421
return value;
415422
}
416423

packages/web3-utils/test/fixtures/converters.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,10 @@ const conversionBaseData: [[Numbers, EtherUnits], string][] = [
279279

280280
export const fromWeiValidData: [[Numbers, EtherUnits], string][] = [
281281
...conversionBaseData,
282-
[['0xff', 'wei'], '255'],
282+
[['0xff', 'wei'], '255'],
283+
[[1e+22, 'ether'], '10000'],
284+
[[19999999999999991611392, 'ether'], '19999.999999999991611392'],
285+
[[1.9999999999999991611392e+22, 'ether'], '19999.999999999991611392'],
283286
];
284287

285288
export const toWeiValidData: [[Numbers, EtherUnits], string][] = [

0 commit comments

Comments
 (0)