Skip to content
Open
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
30 changes: 29 additions & 1 deletion src.ts/_tests/test-utils-units.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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");
});
});
});
2 changes: 2 additions & 0 deletions src.ts/utils/fixednumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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");
Expand Down