Format <= 32 as number, > as hex (not used size) (#2978)

This commit is contained in:
Jaco Greeff
2020-12-22 17:21:42 +01:00
committed by GitHub
parent 5fdefa9e58
commit 1028e14761
4 changed files with 11 additions and 9 deletions
+6 -4
View File
@@ -11,6 +11,9 @@ import { assert, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber,
export const DEFAULT_UINT_BITS = 64;
// Maximum allowed integer for JS is 2^53 - 1, set limit at 52
// In this case however, we always print any >32 as hex
const MAX_NUMBER_BITS = 32;
const MUL_P = new BN(1_00_00);
const FORMATTERS: [string, BN][] = [
@@ -187,10 +190,9 @@ export abstract class AbstractInt extends BN implements Codec {
* @description Converts the Object to JSON, typically used for RPC transfers
*/
public toJSON (onlyHex = false): any {
// FIXME this return type should by string | number, but BN's return type
// is string.
// Maximum allowed integer for JS is 2^53 - 1, set limit at 52
return onlyHex || (super.bitLength() > 52)
// FIXME this return type should by string | number, however BN returns string
// Here if we want to have the actual used bits, it is super.bitLength()
return onlyHex || (this.#bitLength > MAX_NUMBER_BITS)
? this.toHex()
: this.toNumber();
}
+2 -2
View File
@@ -73,8 +73,8 @@ describe('UInt', (): void => {
});
it('converts to JSON representation based on size', (): void => {
expect(new UInt(registry, '0x12345678', 64).toJSON()).toEqual(0x12345678);
expect(new UInt(registry, '0x1234567890', 64).toJSON()).toEqual(0x1234567890);
expect(new UInt(registry, '0x12345678', 32).toJSON()).toEqual(0x12345678);
expect(new UInt(registry, '0x1234567890', 64).toJSON()).toEqual('0x0000001234567890');
expect(new UInt(registry, '0x1234567890abcdef', 64).toJSON()).toEqual('0x1234567890abcdef');
});
+2 -2
View File
@@ -33,7 +33,7 @@ describe('createType', (): void => {
}]);
expect(struct.toJSON()).toEqual({
balance: 1234,
balance: '0x000000000000000000000000000004d2',
index: 16
});
expect(struct.toRawType()).toEqual(raw);
@@ -78,7 +78,7 @@ describe('createType', (): void => {
it('allows creation of a Tuple', (): void => {
expect(
createTypeUnsafe(registry, '(Balance,u32)', [[1234, 5678]]).toJSON()
).toEqual([1234, 5678]);
).toEqual(['0x000000000000000000000000000004d2', 5678]);
});
it('allows creation for a UInt<bitLength>', (): void => {
@@ -17,7 +17,7 @@ describe('Registration', (): void => {
'039911039922039944039955039933000003996600'
).toJSON()
).toEqual({
deposit: 10000000000000,
deposit: '0x0000000000000000000009184e72a000',
info: {
additional: [],
display: { Raw: '0x9911' },