Shortcuts for Compact/Number instantiation (#4939)
* Shortcuts for Compact/Number instantiation * Move/combine isHex/isString
This commit is contained in:
@@ -25,15 +25,21 @@ function toPercentage (value: BN, divisor: BN): string {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array>, isNegative: boolean): string {
|
||||
if (isBn(value)) {
|
||||
return value.toString();
|
||||
} else if (isHex(value, -1, true)) {
|
||||
return hexToBn(value, { isLe: false, isNegative }).toString();
|
||||
} else if (isNumber(value)) {
|
||||
function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array>, isNegative: boolean): string | number {
|
||||
if (isNumber(value)) {
|
||||
assert(value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER && Number.isInteger(value), 'Number needs to be an integer <= Number.MAX_SAFE_INTEGER, i.e. 2 ^ 53 - 1');
|
||||
|
||||
return value;
|
||||
} else if (isString(value)) {
|
||||
if (isHex(value, -1, true)) {
|
||||
return hexToBn(value, { isLe: false, isNegative }).toString();
|
||||
}
|
||||
|
||||
assert(!(value.includes('.') || value.includes(',') || value.includes('e')), 'String should not contain decimal points or scientific notation');
|
||||
|
||||
return value;
|
||||
} else if (isBn(value)) {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
return bnToBn(value).toString();
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, AnyNumber, CodecClass, ICompact, Inspect, INumber, IU8a, Registry } from '../types';
|
||||
|
||||
import { compactFromU8a, compactToU8a, isU8a } from '@polkadot/util';
|
||||
import { compactFromU8a, compactFromU8aLim, compactToU8a, isU8a } from '@polkadot/util';
|
||||
|
||||
import { typeToConstructor } from '../utils';
|
||||
|
||||
@@ -64,11 +64,15 @@ export class Compact<T extends INumber> implements ICompact<T> {
|
||||
/** @internal */
|
||||
public static decodeCompact<T extends INumber> (registry: Registry, Type: CodecClass<T>, value: Compact<T> | AnyNumber): [T, number] {
|
||||
if (isU8a(value)) {
|
||||
const [decodedLength, bn] = compactFromU8a(value);
|
||||
const [decodedLength, bn] = (value[0] & 0b11) < 0b11
|
||||
? compactFromU8aLim(value)
|
||||
: compactFromU8a(value);
|
||||
|
||||
return [new Type(registry, bn), decodedLength];
|
||||
} else if (value instanceof Compact) {
|
||||
return [new Type(registry, value.#raw), 0];
|
||||
return value.#raw instanceof Type
|
||||
? [value.#raw, 0]
|
||||
: [new Type(registry, value.#raw), 0];
|
||||
} else if (value instanceof Type) {
|
||||
return [value, 0];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user