From e1c8b99307e7451f75051152b9592110e7cf78eb Mon Sep 17 00:00:00 2001 From: Richard Moore Date: Wed, 30 Nov 2022 15:39:59 -0500 Subject: [PATCH] Fixed twos-complement issues. --- src.ts/abi/coders/number.ts | 7 +------ src.ts/hash/solidity.ts | 3 ++- src.ts/utils/fixednumber.ts | 6 +++--- src.ts/utils/units.ts | 2 +- 4 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src.ts/abi/coders/number.ts b/src.ts/abi/coders/number.ts index 13e1f0111..240351be0 100644 --- a/src.ts/abi/coders/number.ts +++ b/src.ts/abi/coders/number.ts @@ -42,16 +42,11 @@ export class NumberCoder extends Coder { if (value > bounds || value < -(bounds + BN_1)) { this._throwError("value out-of-bounds", _value); } + value = toTwos(value, 8 * WordSize); } else if (value < BN_0 || value > mask(maxUintValue, this.size * 8)) { this._throwError("value out-of-bounds", _value); } - value = mask(toTwos(value, this.size * 8), this.size * 8); - - if (this.signed) { - value = toTwos(fromTwos(value, this.size * 8), 8 * WordSize); - } - return writer.writeValue(value); } diff --git a/src.ts/hash/solidity.ts b/src.ts/hash/solidity.ts index ab699ade1..2f68f0faa 100644 --- a/src.ts/hash/solidity.ts +++ b/src.ts/hash/solidity.ts @@ -29,13 +29,14 @@ function _pack(type: string, value: any, isArray?: boolean): Uint8Array { let match = type.match(regexNumber); if (match) { + let signed = (match[1] === "int"); let size = parseInt(match[2] || "256") assertArgument((!match[2] || match[2] === String(size)) && (size % 8 === 0) && size !== 0 && size <= 256, "invalid number type", "type", type); if (isArray) { size = 256; } - value = toTwos(value, size); + if (signed) { value = toTwos(value, size); } return getBytes(zeroPadValue(toArray(value), size / 8)); } diff --git a/src.ts/utils/fixednumber.ts b/src.ts/utils/fixednumber.ts index a6d4f7611..ebf6313f2 100644 --- a/src.ts/utils/fixednumber.ts +++ b/src.ts/utils/fixednumber.ts @@ -162,10 +162,10 @@ function toString(val: bigint, decimals: number) { let str = val.toString(); // No decimal point for whole values - if (decimals === 0) { return str; } + if (decimals === 0) { return (negative + str); } - // Pad out to the whole component - while (str.length < decimals) { str = Zeros + str; } + // Pad out to the whole component (including a whole digit) + while (str.length <= decimals) { str = Zeros + str; } // Insert the decimal point const index = str.length - decimals; diff --git a/src.ts/utils/units.ts b/src.ts/utils/units.ts index 6fcc3f37a..ea7a8c412 100644 --- a/src.ts/utils/units.ts +++ b/src.ts/utils/units.ts @@ -52,7 +52,7 @@ export function formatUnits(value: BigNumberish, unit?: string | Numeric): strin decimals = getNumber(unit, "unit"); } - return FixedNumber.fromValue(value, decimals, "fixed256x80").toString(); + return FixedNumber.fromValue(value, decimals, { decimals }).toString(); } /**