From 6f22e00488dc1ffeb5ff3400465fdefef978ad99 Mon Sep 17 00:00:00 2001 From: Tien Nguyen Khac Date: Wed, 22 Jun 2022 12:05:34 +1200 Subject: [PATCH] Fix `Decimal` can be constructed with a negative atomics --- packages/math/src/decimal.spec.ts | 4 ++++ packages/math/src/decimal.ts | 8 +++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/math/src/decimal.spec.ts b/packages/math/src/decimal.spec.ts index 52b876f7..446c8ce1 100644 --- a/packages/math/src/decimal.spec.ts +++ b/packages/math/src/decimal.spec.ts @@ -31,6 +31,10 @@ describe("Decimal", () => { expect(Decimal.fromAtomics("44", 3).toString()).toEqual("0.044"); expect(Decimal.fromAtomics("44", 4).toString()).toEqual("0.0044"); }); + + it("throws for atomics that are not non-negative", () => { + expect(() => Decimal.fromAtomics("-1", 0)).toThrowError(/atomics must not be negative/i); + }); }); describe("fromUserInput", () => { diff --git a/packages/math/src/decimal.ts b/packages/math/src/decimal.ts index 91ec2cc1..a0012a2e 100644 --- a/packages/math/src/decimal.ts +++ b/packages/math/src/decimal.ts @@ -107,8 +107,14 @@ export class Decimal { }; private constructor(atomics: string, fractionalDigits: number) { + const _atomics = new BN(atomics); + + if (_atomics.isNeg()) { + throw new Error("Atomics must not be negative"); + } + this.data = { - atomics: new BN(atomics), + atomics: _atomics, fractionalDigits: fractionalDigits, }; }