From b727cd943744bb00b4eadc4ddbfc5ef5708e3038 Mon Sep 17 00:00:00 2001 From: Dhaiwat Date: Sun, 13 Oct 2024 21:17:06 +0530 Subject: [PATCH 1/2] fix: `parseUnits` bug with 0 units --- .changeset/tidy-scissors-sip.md | 5 +++++ packages/math/src/bn.test.ts | 1 + packages/math/src/bn.ts | 5 +++++ 3 files changed, 11 insertions(+) create mode 100644 .changeset/tidy-scissors-sip.md diff --git a/.changeset/tidy-scissors-sip.md b/.changeset/tidy-scissors-sip.md new file mode 100644 index 00000000000..5dc64e0a33b --- /dev/null +++ b/.changeset/tidy-scissors-sip.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/math": patch +--- + +fix: `parseUnits` bug with 0 units diff --git a/packages/math/src/bn.test.ts b/packages/math/src/bn.test.ts index 02750d6cfc9..85ccb4242dc 100644 --- a/packages/math/src/bn.test.ts +++ b/packages/math/src/bn.test.ts @@ -475,6 +475,7 @@ describe('Math - BN', () => { expect(bn.parseUnits('100,100,100.00002', 5).toHex()).toEqual(bn('10010010000002').toHex()); expect(bn.parseUnits('.').toHex()).toEqual(bn('0').toHex()); expect(bn.parseUnits('.', 5).toHex()).toEqual(bn('0').toHex()); + expect(bn.parseUnits('1', 0).toHex()).toEqual(bn('1').toHex()); expect(() => { bn.parseUnits('100,100.000002', 5); diff --git a/packages/math/src/bn.ts b/packages/math/src/bn.ts index c849acf750c..3696df16844 100644 --- a/packages/math/src/bn.ts +++ b/packages/math/src/bn.ts @@ -322,6 +322,11 @@ bn.parseUnits = (value: string, units: number = DEFAULT_DECIMAL_UNITS): BN => { const [valueUnits = '0', valueDecimals = '0'] = valueToParse.split('.'); const length = valueDecimals.length; + if (units === 0) { + const valueWithoutDecimals = valueToParse.replace(',', '').split('.')[0]; + return bn(valueWithoutDecimals); + } + if (length > units) { throw new FuelError( ErrorCode.CONVERTING_FAILED, From 7805a5644ed245f0ba71bd0364b8f81a87a79952 Mon Sep 17 00:00:00 2001 From: Dhaiwat Date: Sun, 13 Oct 2024 23:28:21 +0530 Subject: [PATCH 2/2] add more test cases --- packages/math/src/bn.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/math/src/bn.test.ts b/packages/math/src/bn.test.ts index 85ccb4242dc..721fd762ece 100644 --- a/packages/math/src/bn.test.ts +++ b/packages/math/src/bn.test.ts @@ -476,6 +476,9 @@ describe('Math - BN', () => { expect(bn.parseUnits('.').toHex()).toEqual(bn('0').toHex()); expect(bn.parseUnits('.', 5).toHex()).toEqual(bn('0').toHex()); expect(bn.parseUnits('1', 0).toHex()).toEqual(bn('1').toHex()); + expect(bn.parseUnits('0.000000001', 0).toHex()).toEqual(bn('0').toHex()); + expect(bn.parseUnits('100.00002', 0).toHex()).toEqual(bn('100').toHex()); + expect(bn.parseUnits('100,100.00002', 0).toHex()).toEqual(bn('100100').toHex()); expect(() => { bn.parseUnits('100,100.000002', 5);