From 5eeb2d6188469f2ad4f5377b37ef5d3f92017bdc Mon Sep 17 00:00:00 2001 From: whitemoshui <139415706+whitemoshui@users.noreply.github.com> Date: Tue, 19 Nov 2024 17:50:33 +0800 Subject: [PATCH] chore: fix 0 kwei bug (#7387) --- CHANGELOG.md | 4 ++++ packages/web3-utils/CHANGELOG.md | 4 ++++ packages/web3-utils/src/converters.ts | 2 +- packages/web3-utils/test/fixtures/converters.ts | 3 +++ 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c97c573755..7ea32551380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2809,3 +2809,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f #### web3 - Export Web3Account, Wallet and signature related types. (#7374) + +#### web3-utils + +- Make `fromWei` return "0" when input is `0` (#7387) diff --git a/packages/web3-utils/CHANGELOG.md b/packages/web3-utils/CHANGELOG.md index 940059963d8..b698fcf51ba 100644 --- a/packages/web3-utils/CHANGELOG.md +++ b/packages/web3-utils/CHANGELOG.md @@ -241,3 +241,7 @@ Documentation: - fix `padRight` validation failure on large `uint` (#7265) ## [Unreleased] + +### Fixed + +- Make `fromWei` return "0" when input is `0` (#7387) diff --git a/packages/web3-utils/src/converters.ts b/packages/web3-utils/src/converters.ts index 9c94a4332b0..dce6ce78871 100644 --- a/packages/web3-utils/src/converters.ts +++ b/packages/web3-utils/src/converters.ts @@ -546,7 +546,7 @@ export const fromWei = (number: Numbers, unit: EtherUnits | number): string => { const fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\.?0+$/, ''); if (integer === '') { - return `0.${fraction}`; + return fraction ? `0.${fraction}` : '0'; } if (fraction === '') { diff --git a/packages/web3-utils/test/fixtures/converters.ts b/packages/web3-utils/test/fixtures/converters.ts index cecb0b3fafb..025f9f7a987 100644 --- a/packages/web3-utils/test/fixtures/converters.ts +++ b/packages/web3-utils/test/fixtures/converters.ts @@ -328,6 +328,9 @@ export const fromWeiValidData: [[Numbers, EtherUnits | number], Numbers][] = [ [['1123', 'kwei'], '1.123'], [['1234100', 'kwei'], '1234.1'], [['3308685546611893', 'ether'], '0.003308685546611893'], + [['0', 'wei'], '0'], + [['0', 'kwei'], '0'], + [['0', 'ether'], '0'], ]; export const toWeiValidData: [[Numbers, EtherUnits | number], Numbers][] = [