From 6b17bf5a7a5f23b3772edfdd855f06770fadfe90 Mon Sep 17 00:00:00 2001 From: Jaco Date: Sun, 23 Apr 2023 15:53:32 +0300 Subject: [PATCH] Default to hex-only when number bits > native Rust (#5611) * Default to hex-only when number bits > native Rust * CHANGELOG * Add test for > u128 case --- CHANGELOG.md | 7 +++++++ packages/types-codec/src/abstract/Int.ts | 6 +++--- packages/types-codec/src/base/UInt.spec.ts | 3 ++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 964a5089e7..146666cad0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # CHANGELOG +## master + +Changes: + +- Default to hex-only in `Int/Uint.toJSON` for > 128-bit values + + ## 10.4.1 Apr 22, 2023 Contributed: diff --git a/packages/types-codec/src/abstract/Int.ts b/packages/types-codec/src/abstract/Int.ts index c832b4c184..a58727f822 100644 --- a/packages/types-codec/src/abstract/Int.ts +++ b/packages/types-codec/src/abstract/Int.ts @@ -221,9 +221,9 @@ export abstract class AbstractInt extends BN implements INumber { public override toJSON (onlyHex = false): any { // FIXME this return type should by string | number, however BN returns string // Options here are - // - super.bitLength() - the actual used bits - // - this.#bitLength - the type bits (this should be used, however contracts RPC is problematic) - return onlyHex || (super.bitLength() > MAX_NUMBER_BITS) + // - super.bitLength() - the actual used bits, use hex when close to MAX_SAFE_INTEGER + // - this.#bitLength - the max used bits, use hex when larger than native Rust type + return onlyHex || (this.#bitLength > 128) || (super.bitLength() > MAX_NUMBER_BITS) ? this.toHex() : this.toNumber(); } diff --git a/packages/types-codec/src/base/UInt.spec.ts b/packages/types-codec/src/base/UInt.spec.ts index ecf3c06d02..874408a784 100644 --- a/packages/types-codec/src/base/UInt.spec.ts +++ b/packages/types-codec/src/base/UInt.spec.ts @@ -123,8 +123,9 @@ describe('UInt', (): void => { it('converts to JSON representation based on size', (): void => { expect(new UInt(registry, '0x12345678', 32).toJSON()).toEqual(0x12345678); - expect(new UInt(registry, '0x1234567890', 64).toJSON()).toEqual(78187493520); // '0x0000001234567890'); + expect(new UInt(registry, '0x1234567890', 64).toJSON()).toEqual(78187493520); expect(new UInt(registry, '0x1234567890abcdef', 64).toJSON()).toEqual('0x1234567890abcdef'); + expect(new UInt(registry, 1, 256).toJSON()).toEqual('0x0000000000000000000000000000000000000000000000000000000000000001'); }); it('has a sane inspect', (): void => {