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: parseUnits bug with 0 units #3320

Merged
merged 3 commits into from
Oct 13, 2024
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
5 changes: 5 additions & 0 deletions .changeset/tidy-scissors-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fuel-ts/math": patch
---

fix: `parseUnits` bug with 0 units
4 changes: 4 additions & 0 deletions packages/math/src/bn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,10 @@ 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());
arboleya marked this conversation as resolved.
Show resolved Hide resolved
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);
Expand Down
5 changes: 5 additions & 0 deletions packages/math/src/bn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down