diff --git a/src.ts/_tests/test-utils-units.ts b/src.ts/_tests/test-utils-units.ts index d5089a45a1..ccd737ab85 100644 --- a/src.ts/_tests/test-utils-units.ts +++ b/src.ts/_tests/test-utils-units.ts @@ -2,7 +2,7 @@ import assert from "assert"; import { loadTests } from "./utils.js"; -import { formatEther, formatUnits, parseEther, parseUnits } from "../index.js"; +import { FixedNumber, formatEther, formatUnits, parseEther, parseUnits } from "../index.js"; import type { TestCaseUnit } from "./types.js"; @@ -70,4 +70,32 @@ describe("Tests bad unit conversion", function() { return error.message.startsWith("invalid unit"); }); }); + + it("correctly fails to convert negative decimal counts", function() { + assert.throws(() => { + formatUnits(123n, -1); + }, (error: any) => { + return error.message.startsWith("invalid FixedNumber decimals"); + }); + + assert.throws(() => { + parseUnits("1.23", -1); + }, (error: any) => { + return error.message.startsWith("invalid FixedNumber decimals"); + }); + }); + + it("correctly fails to create FixedNumber values with negative decimals", function() { + assert.throws(() => { + FixedNumber.fromValue(1, -1); + }, (error: any) => { + return error.message.startsWith("invalid FixedNumber decimals"); + }); + + assert.throws(() => { + FixedNumber.fromString("1.23", { decimals: -1, width: 128 }); + }, (error: any) => { + return error.message.startsWith("invalid FixedNumber decimals"); + }); + }); }); diff --git a/src.ts/utils/fixednumber.ts b/src.ts/utils/fixednumber.ts index cc364af742..76f70f0e74 100644 --- a/src.ts/utils/fixednumber.ts +++ b/src.ts/utils/fixednumber.ts @@ -146,6 +146,7 @@ function getFormat(value?: FixedFormat): _FixedFormat { } assertArgument((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width); + assertArgument(decimals >= 0, "invalid FixedNumber decimals (negative)", "format.decimals", decimals); assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals); const name = (signed ? "": "u") + "fixed" + String(width) + "x" + String(decimals); @@ -567,6 +568,7 @@ export class FixedNumber { */ static fromValue(_value: BigNumberish, _decimals?: Numeric, _format?: FixedFormat): FixedNumber { const decimals = (_decimals == null) ? 0: getNumber(_decimals); + assertArgument(decimals >= 0, "invalid FixedNumber decimals (negative)", "decimals", decimals); const format = getFormat(_format); let value = getBigInt(_value, "value");