diff --git a/.changeset/warn-precision-validation b/.changeset/warn-precision-validation new file mode 100644 index 00000000000..4b1ad2c4fe4 --- /dev/null +++ b/.changeset/warn-precision-validation @@ -0,0 +1,5 @@ +--- +"@fuel-ts/math": patch +--- + +feat: add warning for invalid precision in `BN` format method diff --git a/packages/math/src/bn.test.ts b/packages/math/src/bn.test.ts index 114487310a5..bd55ee5484d 100644 --- a/packages/math/src/bn.test.ts +++ b/packages/math/src/bn.test.ts @@ -541,4 +541,35 @@ describe('Math - BN', () => { it('should return significant figures even if it exceeds the precision', () => { expect(bn('4000000').format({ precision: 1 })).toEqual('0.004'); }); + + describe('precision validation', () => { + let consoleWarnSpy: MockInstance; + + beforeEach(() => { + consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(); + }); + + afterEach(() => { + consoleWarnSpy.mockRestore(); + }); + + it('should warn when precision is less than minPrecision', () => { + bn(123).format({ precision: 2, minPrecision: 4 }); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + 'Warning: precision (2) is less than minPrecision (4). ' + + 'This may lead to unexpected behavior. Consider setting precision >= minPrecision.' + ); + }); + + it('should not warn when precision equals minPrecision', () => { + bn(123).format({ precision: 4, minPrecision: 4 }); + expect(consoleWarnSpy).not.toHaveBeenCalled(); + }); + + it('should not warn when precision is greater than minPrecision', () => { + bn(123).format({ precision: 6, minPrecision: 4 }); + expect(consoleWarnSpy).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/math/src/bn.ts b/packages/math/src/bn.ts index fc66b89421e..45b2c554503 100644 --- a/packages/math/src/bn.ts +++ b/packages/math/src/bn.ts @@ -117,8 +117,15 @@ export class BN extends BnJs implements BNInputOverrides, BNHiddenTypes, BNHelpe return this.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } - // Adjust precision and minPrecision - // TODO: This really should throw an error because you can't have a precision less than the minPrecision but this would be a breaking change + // Warn if precision is less than minPrecision + if (initialPrecision < initialMinPrecision) { + console.warn( + `Warning: precision (${initialPrecision}) is less than minPrecision (${initialMinPrecision}). ` + + 'This may lead to unexpected behavior. Consider setting precision greater than or equal to minPrecision.' + ); + } + + // Adjust precision and minPrecision to maintain backward compatibility const minPrecision = initialMinPrecision > initialPrecision ? initialPrecision : initialMinPrecision; const precision =