Split codec into @polkadot/types-codec (#4329)
* Split codec into @polkadot/types-codec
* Additional (test cleanups next)
* Fix tests
* Imports from '@polkadot/types-codec
* All remaining codec imports (only exports left)
* Bytes -> types-codec
* Cleanups
* Bool, BitVec, Text movements
* sanitize move
* Adjust (first build fixes)
* Adjust
* Additional
* Adjust
* Adjustments
* linting
* Adjust, not working atm
* Move {U,I}{8,16,32...} to types-codec
* createTypeUnsafe
* Fix type-only exports
* Folder exports
* Split Lookup/Create on registry interfaces
* Clanup LookupRegistry & CreateRegistry
* Combine CreateRegistry into LookupRegistry
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecRegistry, IU8a, IVec } from '../types';
|
||||
|
||||
import { compactToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { compareArray } from '../utils/compareArray';
|
||||
|
||||
/**
|
||||
* @name AbstractArray
|
||||
* @description
|
||||
* This manages codec arrays. It is an extension to Array, providing
|
||||
* specific encoding/decoding on top of the base type.
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export abstract class AbstractArray<T extends Codec> extends Array<T> implements IVec<T> {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
protected constructor (registry: CodecRegistry, values: T[], initialU8aLength?: number) {
|
||||
super(values.length);
|
||||
|
||||
// explicitly set the values here - this removes the need for any extra allocations
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
this[i] = values[i];
|
||||
}
|
||||
|
||||
this.registry = registry;
|
||||
this.initialU8aLength = initialU8aLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
// We need to loop through all entries since they may have a variable length themselves,
|
||||
// e.g. when a Vec or Compact is contained withing, it has a variable length based on data
|
||||
let total = compactToU8a(this.length).length;
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
total += this[i].encodedLength;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value
|
||||
*/
|
||||
public override get length (): number {
|
||||
// only included here since we ignore inherited docs
|
||||
return super.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return compareArray(this, other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to an standard JavaScript Array
|
||||
*/
|
||||
public toArray (): T[] {
|
||||
return Array.from(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): AnyJson {
|
||||
const result = new Array<AnyJson>(this.length);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
result[i] = this[i].toHuman(isExtended);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
const result = new Array<AnyJson>(this.length);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
result[i] = this[i].toJSON();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
abstract toRawType (): string;
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
const result = new Array<string>(this.length);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
result[i] = this[i].toString();
|
||||
}
|
||||
|
||||
return `[${result.join(', ')}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
const encoded = new Array<Uint8Array>(this.length);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
encoded[i] = this[i].toU8a(isBare);
|
||||
}
|
||||
|
||||
return isBare
|
||||
? u8aConcat(...encoded)
|
||||
: u8aConcat(
|
||||
compactToU8a(this.length),
|
||||
...encoded
|
||||
);
|
||||
}
|
||||
|
||||
// Below are methods that we override. When we do a `new Vec(...).map()`,
|
||||
// we want it to return an Array. We only override the methods that return a
|
||||
// new instance.
|
||||
|
||||
/**
|
||||
* @description Concatenates two arrays
|
||||
*/
|
||||
public override concat (other: T[]): T[] {
|
||||
return this.toArray().concat(other instanceof AbstractArray ? other.toArray() : other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Filters the array with the callback
|
||||
*/
|
||||
public override filter (callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: unknown): T[] {
|
||||
return this.toArray().filter(callbackfn, thisArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Maps the array with the callback
|
||||
*/
|
||||
public override map<U> (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: unknown): U[] {
|
||||
return this.toArray().map(callbackfn, thisArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the array includes a specific value
|
||||
*/
|
||||
public override includes (check: unknown): boolean {
|
||||
return this.some((value: T) => value.eq(check));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a slice of an array
|
||||
*/
|
||||
public override slice (start?: number, end?: number): T[] {
|
||||
return this.toArray().slice(start, end);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyNumber, CodecRegistry, INumber, IU8a, UIntBitLength } from '../types';
|
||||
|
||||
import { assert, BN, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isBn, isHex, isU8a, u8aToBn } from '@polkadot/util';
|
||||
|
||||
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 = 52;
|
||||
const MUL_P = new BN(1_00_00);
|
||||
|
||||
const FORMATTERS: [string, BN][] = [
|
||||
['Perquintill', BN_QUINTILL],
|
||||
['Perbill', BN_BILLION],
|
||||
['Permill', BN_MILLION],
|
||||
['Percent', BN_HUNDRED]
|
||||
];
|
||||
|
||||
function toPercentage (value: BN, divisor: BN): string {
|
||||
return `${(value.mul(MUL_P).div(divisor).toNumber() / 100).toFixed(2)}%`;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeAbstractInt (value: AnyNumber, bitLength: UIntBitLength, isNegative: boolean): string {
|
||||
if (isU8a(value)) {
|
||||
return u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative }).toString();
|
||||
} else if (isBn(value)) {
|
||||
return value.toString();
|
||||
} else if (isHex(value, -1, true)) {
|
||||
return hexToBn(value, { isLe: false, isNegative }).toString();
|
||||
}
|
||||
|
||||
return bnToBn(value).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @name AbstractInt
|
||||
* @ignore
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export abstract class AbstractInt extends BN implements INumber {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly encodedLength: number;
|
||||
|
||||
readonly #bitLength: UIntBitLength;
|
||||
|
||||
readonly #isSigned: boolean;
|
||||
|
||||
constructor (registry: CodecRegistry, value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isSigned = false) {
|
||||
// Construct via a string, which will be passed in the BN constructor.
|
||||
// It would be ideal to actually return a BN, but there is an issue:
|
||||
// https://github.com/indutny/bn.js/issues/206
|
||||
super(
|
||||
// shortcut isU8a as used in SCALE decoding
|
||||
isU8a(value)
|
||||
? u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative: isSigned }).toString()
|
||||
: decodeAbstractInt(value, bitLength, isSigned)
|
||||
);
|
||||
|
||||
this.registry = registry;
|
||||
this.#bitLength = bitLength;
|
||||
this.encodedLength = this.#bitLength / 8;
|
||||
this.#isSigned = isSigned;
|
||||
|
||||
const isPositive = this.gte(BN_ZERO);
|
||||
const maxBits = bitLength - (isSigned && isPositive ? 1 : 0);
|
||||
|
||||
assert(isSigned || isPositive, () => `${this.toRawType()}: Negative number passed to unsigned type`);
|
||||
assert(super.bitLength() <= maxBits, () => `${this.toRawType()}: Input too large. Found input with ${super.bitLength()} bits, expected ${maxBits}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is a zero value (align elsewhere)
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.isZero();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an unsigned type
|
||||
*/
|
||||
public get isUnsigned (): boolean {
|
||||
return !this.#isSigned;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number of bits in the value
|
||||
*/
|
||||
public override bitLength (): number {
|
||||
return this.#bitLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
public override eq (other?: unknown): boolean {
|
||||
// Here we are actually overriding the built-in .eq to take care of both
|
||||
// number and BN inputs (no `.eqn` needed) - numbers will be converted
|
||||
return super.eq(
|
||||
isHex(other)
|
||||
? hexToBn(other.toString(), { isLe: false, isNegative: this.#isSigned })
|
||||
: bnToBn(other as string)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description True if this value is the max of the type
|
||||
*/
|
||||
public isMax (): boolean {
|
||||
const u8a = this.toU8a().filter((b) => b === 0xff);
|
||||
|
||||
return u8a.length === (this.#bitLength / 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a BigInt representation of the number
|
||||
*/
|
||||
public toBigInt (): bigint {
|
||||
return BigInt(this.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the BN representation of the number. (Compatibility)
|
||||
*/
|
||||
public toBn (): BN {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (isLe = false): HexString {
|
||||
// For display/JSON, this is BE, for compare, use isLe
|
||||
return bnToHex(this, {
|
||||
bitLength: this.bitLength(),
|
||||
isLe,
|
||||
isNegative: !this.isUnsigned
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toHuman (isExpanded?: boolean): string {
|
||||
const rawType = this.toRawType();
|
||||
|
||||
if (rawType === 'Balance') {
|
||||
return this.isMax()
|
||||
? 'everything'
|
||||
// FIXME In the case of multiples we need some way of detecting which instance this belongs
|
||||
// to. as it stands we will always format (incorrectly) against the first token defined
|
||||
: formatBalance(this, { decimals: this.registry.chainDecimals[0], withSi: true, withUnit: this.registry.chainTokens[0] });
|
||||
}
|
||||
|
||||
const [, divisor] = FORMATTERS.find(([type]) => type === rawType) || [];
|
||||
|
||||
return divisor
|
||||
? toPercentage(this, divisor)
|
||||
: formatNumber(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
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)
|
||||
? this.toHex()
|
||||
: this.toNumber();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
// NOTE In the case of balances, which have a special meaning on the UI
|
||||
// and can be interpreted differently, return a specific value for it so
|
||||
// underlying it always matches (no matter which length it actually is)
|
||||
return this instanceof this.registry.createClassUnsafe('Balance')
|
||||
? 'Balance'
|
||||
: `${this.isUnsigned ? 'u' : 'i'}${this.bitLength()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
* @param base The base to use for the conversion
|
||||
*/
|
||||
public override toString (base?: number): string {
|
||||
// only included here since we do not inherit docs
|
||||
return super.toString(base);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this, {
|
||||
bitLength: this.bitLength(),
|
||||
isLe: true,
|
||||
isNegative: !this.isUnsigned
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { AbstractArray } from './AbstractArray';
|
||||
export { AbstractInt } from './AbstractInt';
|
||||
@@ -0,0 +1,96 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, BareOpts, Codec, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
/**
|
||||
* @name Base
|
||||
* @description A type extends the Base class, when it holds a value
|
||||
*/
|
||||
export abstract class Base<T extends Codec> implements Codec {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
protected readonly _raw: T;
|
||||
|
||||
protected constructor (registry: CodecRegistry, value: T, initialU8aLength?: number) {
|
||||
this.registry = registry;
|
||||
this._raw = value;
|
||||
this.initialU8aLength = initialU8aLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return this.toU8a().length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this._raw.isEmpty;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return this._raw.eq(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
|
||||
*/
|
||||
public toHex (isLe?: boolean): HexString {
|
||||
return this._raw.toHex(isLe);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): AnyJson {
|
||||
return this._raw.toHuman(isExtended);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
return this._raw.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public toString (): string {
|
||||
return this._raw.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: BareOpts): Uint8Array {
|
||||
return this._raw.toU8a(isBare);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'Base';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, AnyNumber, CodecClass, CodecRegistry, ICompact, INumber, IU8a } from '../types';
|
||||
|
||||
import { compactFromU8a, compactToU8a, isBigInt, isBn, isNumber, isString } from '@polkadot/util';
|
||||
|
||||
import { typeToConstructor } from '../utils';
|
||||
|
||||
/**
|
||||
* @name Compact
|
||||
* @description
|
||||
* A compact length-encoding codec wrapper. It performs the same function as Length, however
|
||||
* differs in that it uses a variable number of bytes to do the actual encoding. This is mostly
|
||||
* used by other types to add length-prefixed encoding, or in the case of wrapped types, taking
|
||||
* a number and making the compact representation thereof
|
||||
*/
|
||||
export class Compact<T extends INumber> implements ICompact<T> {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #Type: CodecClass<T>;
|
||||
|
||||
readonly #raw: T;
|
||||
|
||||
constructor (registry: CodecRegistry, Type: CodecClass<T> | string, value: Compact<T> | AnyNumber = 0) {
|
||||
this.registry = registry;
|
||||
this.#Type = typeToConstructor(registry, Type);
|
||||
|
||||
const [raw, decodedLength] = Compact.decodeCompact<T>(registry, this.#Type, value);
|
||||
|
||||
this.initialU8aLength = decodedLength;
|
||||
this.#raw = raw;
|
||||
}
|
||||
|
||||
public static with<T extends INumber> (Type: CodecClass<T> | string): CodecClass<Compact<T>> {
|
||||
return class extends Compact<T> {
|
||||
constructor (registry: CodecRegistry, value?: Compact<T> | AnyNumber) {
|
||||
super(registry, Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
public static decodeCompact<T extends INumber> (registry: CodecRegistry, Type: CodecClass<T>, value: Compact<T> | AnyNumber): [T, number] {
|
||||
if (value instanceof Compact) {
|
||||
return [new Type(registry, value.#raw), 0];
|
||||
} else if (value instanceof Type) {
|
||||
return [value, 0];
|
||||
} else if (isString(value) || isNumber(value) || isBn(value) || isBigInt(value)) {
|
||||
return [new Type(registry, value), 0];
|
||||
}
|
||||
|
||||
const [decodedLength, bn] = compactFromU8a(value);
|
||||
|
||||
return [new Type(registry, bn), decodedLength];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return this.toU8a().length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.#raw.isEmpty;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number of bits in the value
|
||||
*/
|
||||
public bitLength (): number {
|
||||
return this.#raw.bitLength();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return this.#raw.eq(
|
||||
other instanceof Compact
|
||||
? other.#raw
|
||||
: other
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a BigInt representation of the number
|
||||
*/
|
||||
public toBigInt (): bigint {
|
||||
return this.#raw.toBigInt();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the BN representation of the number
|
||||
*/
|
||||
public toBn (): BN {
|
||||
return this.#raw.toBn();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
|
||||
*/
|
||||
public toHex (isLe?: boolean): HexString {
|
||||
return this.#raw.toHex(isLe);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): AnyJson {
|
||||
return this.#raw.toHuman(isExtended);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
return this.#raw.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number representation for the value
|
||||
*/
|
||||
public toNumber (): number {
|
||||
return this.#raw.toNumber();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return `Compact<${this.registry.getClassName(this.#Type) || this.#raw.toRawType()}>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public toString (): string {
|
||||
return this.#raw.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return compactToU8a(this.#raw.toBn());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the embedded [[UInt]] or [[Moment]] value
|
||||
*/
|
||||
public unwrap (): T {
|
||||
return this.#raw;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecClass, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
/**
|
||||
* @name DoNotConstruct
|
||||
* @description
|
||||
* An unknown type that fails on construction with the type info
|
||||
*/
|
||||
export class DoNotConstruct implements Codec {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
#neverError: Error;
|
||||
|
||||
constructor (registry: CodecRegistry, typeName = 'DoNotConstruct') {
|
||||
this.registry = registry;
|
||||
this.#neverError = new Error(`DoNotConstruct: Cannot construct unknown type ${typeName}`);
|
||||
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
public static with (typeName?: string): CodecClass {
|
||||
return class extends DoNotConstruct {
|
||||
constructor (registry: CodecRegistry) {
|
||||
super(registry, typeName);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value (always true)
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
eq (): boolean {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
toHex (): HexString {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
toHuman (): AnyJson {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
toJSON (): AnyJson {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
toRawType (): string {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
throw this.#neverError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecClass, CodecRegistry, IEnum, IU8a } from '../types';
|
||||
|
||||
import { assert, isHex, isNumber, isObject, isString, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { mapToTypeMap, typesToMap } from '../utils';
|
||||
import { Null } from './Null';
|
||||
|
||||
// export interface, this is used in Enum.with, so required as public by TS
|
||||
export interface EnumCodecClass<T = Codec> {
|
||||
new(registry: CodecRegistry, value?: any, index?: number): T;
|
||||
}
|
||||
|
||||
interface EntryDef {
|
||||
Type: CodecClass;
|
||||
index: number;
|
||||
}
|
||||
|
||||
type TypesDef = Record<string, EntryDef>;
|
||||
|
||||
interface Decoded {
|
||||
index: number;
|
||||
value: Codec;
|
||||
}
|
||||
|
||||
function isRustEnum (def: Record<string, string | CodecClass> | Record<string, number>): def is Record<string, string | CodecClass> {
|
||||
const defValues = Object.values(def);
|
||||
|
||||
if (defValues.some((v) => isNumber(v))) {
|
||||
assert(defValues.every((v) => isNumber(v) && v >= 0 && v <= 255), 'Invalid number-indexed enum definition');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function extractDef (registry: CodecRegistry, _def: Record<string, string | CodecClass> | Record<string, number> | string[]): { def: TypesDef; isBasic: boolean; isIndexed: boolean } {
|
||||
const def: TypesDef = {};
|
||||
let isBasic: boolean;
|
||||
let isIndexed: boolean;
|
||||
|
||||
if (Array.isArray(_def)) {
|
||||
for (let i = 0; i < _def.length; i++) {
|
||||
def[_def[i]] = { Type: Null, index: i };
|
||||
}
|
||||
|
||||
isBasic = true;
|
||||
isIndexed = false;
|
||||
} else if (isRustEnum(_def)) {
|
||||
const entries = Object.entries(mapToTypeMap(registry, _def));
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [key, Type] = entries[i];
|
||||
|
||||
def[key] = { Type, index: i };
|
||||
}
|
||||
|
||||
isBasic = !Object.values(def).some(({ Type }) => Type !== Null);
|
||||
isIndexed = false;
|
||||
} else {
|
||||
const entries = Object.entries(_def);
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [key, index] = entries[i];
|
||||
|
||||
def[key] = { Type: Null, index };
|
||||
}
|
||||
|
||||
isBasic = true;
|
||||
isIndexed = true;
|
||||
}
|
||||
|
||||
return {
|
||||
def,
|
||||
isBasic,
|
||||
isIndexed
|
||||
};
|
||||
}
|
||||
|
||||
function createFromValue (registry: CodecRegistry, def: TypesDef, index = 0, value?: unknown): Decoded {
|
||||
const entry = Object.values(def).find((e) => e.index === index);
|
||||
|
||||
assert(!isUndefined(entry), () => `Unable to create Enum via index ${index}, in ${Object.keys(def).join(', ')}`);
|
||||
|
||||
return {
|
||||
index,
|
||||
value: value instanceof entry.Type
|
||||
? value
|
||||
: new entry.Type(registry, value)
|
||||
};
|
||||
}
|
||||
|
||||
function decodeFromJSON (registry: CodecRegistry, def: TypesDef, key: string, value?: unknown): Decoded {
|
||||
// JSON comes in the form of { "<type (camelCase)>": "<value for type>" }, here we
|
||||
// additionally force to lower to ensure forward compat
|
||||
const keys = Object.keys(def).map((k) => k.toLowerCase());
|
||||
const keyLower = key.toLowerCase();
|
||||
const index = keys.indexOf(keyLower);
|
||||
|
||||
assert(index !== -1, () => `Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`);
|
||||
|
||||
try {
|
||||
return createFromValue(registry, def, Object.values(def)[index].index, value);
|
||||
} catch (error) {
|
||||
throw new Error(`Enum(${key}):: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function decodeEnum (registry: CodecRegistry, def: TypesDef, value?: unknown, index?: number): Decoded {
|
||||
// NOTE We check the index path first, before looking at values - this allows treating
|
||||
// the optional indexes before anything else, more-specific > less-specific
|
||||
if (isNumber(index)) {
|
||||
return createFromValue(registry, def, index, value);
|
||||
} else if (isU8a(value) || isHex(value)) {
|
||||
const u8a = u8aToU8a(value);
|
||||
|
||||
// nested, we don't want to match isObject below
|
||||
if (u8a.length) {
|
||||
return createFromValue(registry, def, u8a[0], u8a.subarray(1));
|
||||
}
|
||||
} else if (value instanceof Enum) {
|
||||
return createFromValue(registry, def, value.index, value.value);
|
||||
} else if (isNumber(value)) {
|
||||
return createFromValue(registry, def, value);
|
||||
} else if (isString(value)) {
|
||||
return decodeFromJSON(registry, def, value.toString());
|
||||
} else if (isObject(value)) {
|
||||
const key = Object.keys(value)[0];
|
||||
|
||||
return decodeFromJSON(registry, def, key, value[key]);
|
||||
}
|
||||
|
||||
// Worst-case scenario, return the first with default
|
||||
return createFromValue(registry, def, Object.values(def)[0].index);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Enum
|
||||
* @description
|
||||
* This implements an enum, that based on the value wraps a different type. It is effectively
|
||||
* an extension to enum where the value type is determined by the actual index.
|
||||
*/
|
||||
export class Enum implements IEnum {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly #def: TypesDef;
|
||||
|
||||
readonly #entryIndex: number;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #indexes: number[];
|
||||
|
||||
readonly #isBasic: boolean;
|
||||
|
||||
readonly #isIndexed: boolean;
|
||||
|
||||
readonly #raw: Codec;
|
||||
|
||||
constructor (registry: CodecRegistry, Types: Record<string, string | CodecClass> | Record<string, number> | string[], value?: unknown, index?: number) {
|
||||
const { def, isBasic, isIndexed } = extractDef(registry, Types);
|
||||
|
||||
// shortcut isU8a as used in SCALE decoding
|
||||
const decoded = isU8a(value) && value.length && !isNumber(index)
|
||||
? createFromValue(registry, def, value[0], value.subarray(1))
|
||||
: decodeEnum(registry, def, value, index);
|
||||
|
||||
this.registry = registry;
|
||||
this.#def = def;
|
||||
this.#isBasic = isBasic;
|
||||
this.#isIndexed = isIndexed;
|
||||
this.#indexes = Object.values(def).map(({ index }) => index);
|
||||
this.#entryIndex = this.#indexes.indexOf(decoded.index) || 0;
|
||||
this.#raw = decoded.value;
|
||||
|
||||
if (this.#raw.initialU8aLength) {
|
||||
this.initialU8aLength = 1 + this.#raw.initialU8aLength;
|
||||
}
|
||||
}
|
||||
|
||||
public static with (Types: Record<string, string | CodecClass> | Record<string, number> | string[]): EnumCodecClass<Enum> {
|
||||
const keys = Array.isArray(Types)
|
||||
? Types
|
||||
: Object.keys(Types);
|
||||
const asKeys = new Array<string>(keys.length);
|
||||
const isKeys = new Array<string>(keys.length);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const name = stringPascalCase(keys[i].replace(' ', '_'));
|
||||
|
||||
asKeys[i] = `as${name}`;
|
||||
isKeys[i] = `is${name}`;
|
||||
}
|
||||
|
||||
return class extends Enum {
|
||||
constructor (registry: CodecRegistry, value?: unknown, index?: number) {
|
||||
super(registry, Types, value, index);
|
||||
|
||||
objectProperties(this, isKeys, (_, i) => this.type === keys[i]);
|
||||
objectProperties(this, asKeys, (k, i): Codec => {
|
||||
assert(this[isKeys[i] as keyof this], () => `Cannot convert '${this.type}' via ${k}`);
|
||||
|
||||
return this.value;
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return 1 + this.#raw.encodedLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The index of the enum value
|
||||
*/
|
||||
public get index (): number {
|
||||
return this.#indexes[this.#entryIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description true if this is a basic enum (no values)
|
||||
*/
|
||||
public get isBasic (): boolean {
|
||||
return this.#isBasic;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.#raw.isEmpty;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Enum points to a [[Null]] type
|
||||
*/
|
||||
public get isNone (): boolean {
|
||||
return this.#raw instanceof Null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Enum points to a [[Null]] type
|
||||
* @deprecated use isNone
|
||||
*/
|
||||
public get isNull (): boolean {
|
||||
return this.#raw instanceof Null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The available keys for this enum
|
||||
*/
|
||||
public get defIndexes (): number[] {
|
||||
return this.#indexes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The available keys for this enum
|
||||
*/
|
||||
public get defKeys (): string[] {
|
||||
return Object.keys(this.#def);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The name of the type this enum value represents
|
||||
*/
|
||||
public get type (): string {
|
||||
return this.defKeys[this.#entryIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The value of the enum
|
||||
*/
|
||||
public get value (): Codec {
|
||||
return this.#raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
// cater for the case where we only pass the enum index
|
||||
if (isU8a(other)) {
|
||||
return !this.toU8a().some((entry, index) => entry !== other[index]);
|
||||
} else if (isNumber(other)) {
|
||||
return this.toNumber() === other;
|
||||
} else if (this.#isBasic && isString(other)) {
|
||||
return this.type === other;
|
||||
} else if (isHex(other)) {
|
||||
return this.toHex() === other;
|
||||
} else if (other instanceof Enum) {
|
||||
return this.index === other.index && this.value.eq(other.value);
|
||||
} else if (isObject(other)) {
|
||||
return this.value.eq(other[this.type]);
|
||||
}
|
||||
|
||||
// compare the actual wrapper value
|
||||
return this.value.eq(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): AnyJson {
|
||||
return this.#isBasic || this.isNone
|
||||
? this.type
|
||||
: { [this.type]: this.#raw.toHuman(isExtended) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
return this.#isBasic
|
||||
? this.type
|
||||
: { [stringCamelCase(this.type)]: this.#raw.toJSON() };
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number representation for the value
|
||||
*/
|
||||
public toNumber (): number {
|
||||
return this.index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a raw struct representation of the enum types
|
||||
*/
|
||||
protected _toRawStruct (): string[] | Record<string, string | number> {
|
||||
if (this.#isBasic) {
|
||||
return this.#isIndexed
|
||||
? this.defKeys.reduce((out: Record<string, number>, key, index): Record<string, number> => {
|
||||
out[key] = this.#indexes[index];
|
||||
|
||||
return out;
|
||||
}, {})
|
||||
: this.defKeys;
|
||||
}
|
||||
|
||||
const typeMap = Object
|
||||
.entries(this.#def)
|
||||
.reduce((out: Record<string, CodecClass>, [key, { Type }]) => {
|
||||
out[key] = Type;
|
||||
|
||||
return out;
|
||||
}, {});
|
||||
|
||||
return typesToMap(this.registry, typeMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return stringify({ _enum: this._toRawStruct() });
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public toString (): string {
|
||||
return this.isNull
|
||||
? this.type
|
||||
: stringify(this.toJSON());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
new Uint8Array(isBare ? [] : [this.index]),
|
||||
this.#raw.toU8a(isBare)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, CodecClass, CodecRegistry, UIntBitLength } from '../types';
|
||||
|
||||
import { AbstractInt } from '../abstract/AbstractInt';
|
||||
|
||||
/**
|
||||
* @name Int
|
||||
* @description
|
||||
* A generic signed integer codec. For Substrate all numbers are Little Endian encoded,
|
||||
* this handles the encoding and decoding of those numbers. Upon construction
|
||||
* the bitLength is provided and any additional use keeps the number to this
|
||||
* length. This extends `BN`, so all methods available on a normal `BN` object
|
||||
* is available here.
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class Int extends AbstractInt {
|
||||
constructor (registry: CodecRegistry, value: AnyNumber = 0, bitLength?: UIntBitLength) {
|
||||
super(registry, value, bitLength, true);
|
||||
}
|
||||
|
||||
public static with (bitLength: UIntBitLength, typeName?: string): CodecClass<Int> {
|
||||
return class extends Int {
|
||||
constructor (registry: CodecRegistry, value?: AnyNumber) {
|
||||
super(registry, value, bitLength);
|
||||
}
|
||||
|
||||
public override toRawType (): string {
|
||||
return typeName || super.toRawType();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
import { isNull } from '@polkadot/util';
|
||||
|
||||
/**
|
||||
* @name Null
|
||||
* @description
|
||||
* Implements a type that does not contain anything (apart from `null`)
|
||||
*/
|
||||
export class Null implements Codec {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
// Added for compatibility reasons, e.g. see Option
|
||||
public readonly initialU8aLength = 0;
|
||||
|
||||
constructor (registry: CodecRegistry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
throw new Error('.hash is not implemented on Null');
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value (always true)
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return other instanceof Null || isNull(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return '0x';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): null {
|
||||
return this.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'Null';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public toString (): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return new Uint8Array();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecClass, CodecRegistry, IOption, IU8a } from '../types';
|
||||
|
||||
import { assert, isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { typeToConstructor } from '../utils';
|
||||
import { Null } from './Null';
|
||||
|
||||
/** @internal */
|
||||
function decodeOption (registry: CodecRegistry, Type: CodecClass, value?: unknown): Codec {
|
||||
// In the case of an option, unwrap the inner
|
||||
if (value instanceof Option) {
|
||||
value = value.value;
|
||||
}
|
||||
|
||||
if (isNull(value) || isUndefined(value) || value instanceof Null || value === '0x') {
|
||||
return new Null(registry);
|
||||
} else if (value instanceof Type) {
|
||||
// don't re-create, use as it (which also caters for derived types)
|
||||
return value;
|
||||
} else if (isU8a(value)) {
|
||||
// the isU8a check happens last in the if-tree - since the wrapped value
|
||||
// may be an instance of it, so Type and Option checks go in first
|
||||
return !value.length || value[0] === 0
|
||||
? new Null(registry)
|
||||
: new Type(registry, value.subarray(1));
|
||||
}
|
||||
|
||||
return new Type(registry, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Option
|
||||
* @description
|
||||
* An Option is an optional field. Basically the first byte indicates that there is
|
||||
* is value to follow. If the byte is `1` there is an actual value. So the Option
|
||||
* implements that - decodes, checks for optionality and wraps the required structure
|
||||
* with a value if/as required/found.
|
||||
*/
|
||||
export class Option<T extends Codec> implements IOption<T> {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly #Type: CodecClass<T>;
|
||||
|
||||
readonly #initialU8aLength?: number;
|
||||
|
||||
readonly #raw: T;
|
||||
|
||||
constructor (registry: CodecRegistry, typeName: CodecClass<T> | string, value?: unknown) {
|
||||
const Type = typeToConstructor(registry, typeName);
|
||||
const decoded = isU8a(value) && value.length && !isCodec(value)
|
||||
? value[0] === 0
|
||||
? new Null(registry)
|
||||
: new Type(registry, value.subarray(1))
|
||||
: decodeOption(registry, Type, value);
|
||||
|
||||
this.registry = registry;
|
||||
this.#Type = Type;
|
||||
this.#raw = decoded as T;
|
||||
|
||||
if (decoded.initialU8aLength) {
|
||||
this.#initialU8aLength = 1 + decoded.initialU8aLength;
|
||||
}
|
||||
}
|
||||
|
||||
public static with<O extends Codec> (Type: CodecClass<O> | string): CodecClass<Option<O>> {
|
||||
return class extends Option<O> {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
// boolean byte (has value, doesn't have) along with wrapped length
|
||||
return 1 + this.#raw.encodedLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the initial encoded value (Only available when constructed from a Uint8Array)
|
||||
*/
|
||||
public get initialU8aLength (): number | undefined {
|
||||
return this.#initialU8aLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Option has no value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.isNone;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Option has no value
|
||||
*/
|
||||
public get isNone (): boolean {
|
||||
return this.#raw instanceof Null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Option has a value
|
||||
*/
|
||||
public get isSome (): boolean {
|
||||
return !this.isNone;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The actual value for the Option
|
||||
*/
|
||||
public get value (): Codec {
|
||||
return this.#raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
if (other instanceof Option) {
|
||||
return (this.isSome === other.isSome) && this.value.eq(other.value);
|
||||
}
|
||||
|
||||
return this.value.eq(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
// This attempts to align with the JSON encoding - actually in this case
|
||||
// the isSome value is correct, however the `isNone` may be problematic
|
||||
return this.isNone
|
||||
? '0x'
|
||||
: u8aToHex(this.toU8a().subarray(1));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): AnyJson {
|
||||
return this.#raw.toHuman(isExtended);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
return this.isNone
|
||||
? null
|
||||
: this.#raw.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (isBare?: boolean): string {
|
||||
const wrapped = this.registry.getClassName(this.#Type) || new this.#Type(this.registry).toRawType();
|
||||
|
||||
return isBare
|
||||
? wrapped
|
||||
: `Option<${wrapped}>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public toString (): string {
|
||||
return this.#raw.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
if (isBare) {
|
||||
return this.#raw.toU8a(true);
|
||||
}
|
||||
|
||||
const u8a = new Uint8Array(this.encodedLength);
|
||||
|
||||
if (this.isSome) {
|
||||
u8a.set([1]);
|
||||
u8a.set(this.#raw.toU8a(), 1);
|
||||
}
|
||||
|
||||
return u8a;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the value that the Option represents (if available), throws if null
|
||||
*/
|
||||
public unwrap (): T {
|
||||
assert(this.isSome, 'Option: unwrapping a None value');
|
||||
|
||||
return this.#raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the value that the Option represents (if available) or defaultValue if none
|
||||
* @param defaultValue The value to return if the option isNone
|
||||
*/
|
||||
public unwrapOr<O> (defaultValue: O): T | O {
|
||||
return this.isSome
|
||||
? this.unwrap()
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the value that the Option represents (if available) or defaultValue if none
|
||||
* @param defaultValue The value to return if the option isNone
|
||||
*/
|
||||
public unwrapOrDefault (): T {
|
||||
return this.isSome
|
||||
? this.unwrap()
|
||||
: new this.#Type(this.registry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry, IResult } from '../types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { Enum } from './Enum';
|
||||
|
||||
/**
|
||||
* @name Result
|
||||
* @description
|
||||
* A Result maps to the Rust Result type, that can either wrap a success or error value
|
||||
*/
|
||||
export class Result<O extends Codec, E extends Codec> extends Enum implements IResult<O, E> {
|
||||
constructor (registry: CodecRegistry, Ok: CodecClass<O> | string, Err: CodecClass<E> | string, value?: unknown) {
|
||||
// NOTE This is order-dependent, Ok (with index 0) needs to be first
|
||||
// eslint-disable-next-line sort-keys
|
||||
super(registry, { Ok, Err }, value);
|
||||
}
|
||||
|
||||
public static override with<O extends Codec, E extends Codec> (Types: { Ok: CodecClass<O> | string; Err: CodecClass<E> | string }): CodecClass<Result<O, E>> {
|
||||
return class extends Result<O, E> {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, Types.Ok, Types.Err, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the wrapper Err value (if isErr)
|
||||
*/
|
||||
public get asErr (): E {
|
||||
assert(this.isErr, 'Cannot extract Err value from Ok result, check isErr first');
|
||||
|
||||
return this.value as E;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use asErr
|
||||
*/
|
||||
public get asError (): E {
|
||||
return this.asErr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the wrapper Ok value (if isOk)
|
||||
*/
|
||||
public get asOk (): O {
|
||||
assert(this.isOk, 'Cannot extract Ok value from Err result, check isOk first');
|
||||
|
||||
return this.value as O;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Result has no value
|
||||
*/
|
||||
public override get isEmpty (): boolean {
|
||||
return this.isOk && this.value.isEmpty;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Result wraps an Err value
|
||||
*/
|
||||
public get isErr (): boolean {
|
||||
return !this.isOk;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use isErr
|
||||
*/
|
||||
public get isError (): boolean {
|
||||
return this.isErr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the Result wraps an Ok value
|
||||
*/
|
||||
public get isOk (): boolean {
|
||||
return this.index === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
const Types = this._toRawStruct() as { Ok: unknown; Err: unknown };
|
||||
|
||||
return `Result<${Types.Ok as string},${Types.Err as string}>`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyTupleValue, Codec, CodecClass, CodecRegistry, ITuple } from '../types';
|
||||
|
||||
import { isFunction, isHex, isString, isU8a, stringify, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from '../abstract/AbstractArray';
|
||||
import { decodeU8a, mapToTypeMap, typeToConstructor } from '../utils';
|
||||
|
||||
type TupleCodecClasss = CodecClass[] | {
|
||||
[index: string]: CodecClass;
|
||||
};
|
||||
|
||||
type TupleType = (CodecClass | string);
|
||||
|
||||
type TupleTypes = TupleType[] | {
|
||||
[index: string]: CodecClass | string;
|
||||
};
|
||||
|
||||
/** @internal */
|
||||
function decodeTuple (registry: CodecRegistry, Classes: TupleCodecClasss, value?: AnyTupleValue): [Codec[], number] {
|
||||
if (isU8a(value) || isHex(value)) {
|
||||
return decodeU8a(registry, u8aToU8a(value), Classes);
|
||||
}
|
||||
|
||||
const Types: CodecClass[] = Array.isArray(Classes)
|
||||
? Classes
|
||||
: Object.values(Classes);
|
||||
|
||||
return [
|
||||
Types.map((Type, index): Codec => {
|
||||
try {
|
||||
const entry = value?.[index];
|
||||
|
||||
if (entry instanceof Type) {
|
||||
return entry;
|
||||
}
|
||||
|
||||
return new Type(registry, entry);
|
||||
} catch (error) {
|
||||
throw new Error(`Tuple: failed on ${index}:: ${(error as Error).message}`);
|
||||
}
|
||||
}),
|
||||
0
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Tuple
|
||||
* @description
|
||||
* A Tuple defines an anonymous fixed-length array, where each element has its
|
||||
* own type. It extends the base JS `Array` object.
|
||||
*/
|
||||
export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
|
||||
#Types: TupleCodecClasss;
|
||||
|
||||
constructor (registry: CodecRegistry, Types: TupleTypes | TupleType, value?: AnyTupleValue) {
|
||||
const Classes = Array.isArray(Types)
|
||||
? Types.map((t) => typeToConstructor(registry, t))
|
||||
: isFunction(Types) || isString(Types)
|
||||
? [typeToConstructor(registry, Types)]
|
||||
: mapToTypeMap(registry, Types);
|
||||
const [values, decodedLength] = isU8a(value)
|
||||
? decodeU8a(registry, value, Classes)
|
||||
: decodeTuple(registry, Classes, value);
|
||||
|
||||
super(registry, values, decodedLength);
|
||||
|
||||
this.#Types = Classes;
|
||||
}
|
||||
|
||||
public static with (Types: TupleTypes | TupleType): CodecClass<Tuple> {
|
||||
return class extends Tuple {
|
||||
constructor (registry: CodecRegistry, value?: AnyTupleValue) {
|
||||
super(registry, Types, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public override get encodedLength (): number {
|
||||
let total = 0;
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
total += this[i].encodedLength;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The types definition of the tuple
|
||||
*/
|
||||
public get Types (): string[] {
|
||||
return Array.isArray(this.#Types)
|
||||
? this.#Types.map((T) => new T(this.registry).toRawType())
|
||||
: Object.keys(this.#Types);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
const types = (
|
||||
Array.isArray(this.#Types)
|
||||
? this.#Types
|
||||
: Object.values(this.#Types)
|
||||
).map((T) =>
|
||||
this.registry.getClassName(T) || new T(this.registry).toRawType()
|
||||
);
|
||||
|
||||
return `(${types.join(',')})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
// Overwrite the default toString representation of Array.
|
||||
return stringify(this.toJSON());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public override toU8a (isBare?: boolean): Uint8Array {
|
||||
const encoded = new Array<Uint8Array>(this.length);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
encoded[i] = this[i].toU8a(isBare);
|
||||
}
|
||||
|
||||
return u8aConcat(...encoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, CodecClass, CodecRegistry, UIntBitLength } from '../types';
|
||||
|
||||
import { AbstractInt } from '../abstract/AbstractInt';
|
||||
|
||||
/**
|
||||
* @name UInt
|
||||
* @description
|
||||
* A generic unsigned integer codec. For Substrate all numbers are Little Endian encoded,
|
||||
* this handles the encoding and decoding of those numbers. Upon construction
|
||||
* the bitLength is provided and any additional use keeps the number to this
|
||||
* length. This extends `BN`, so all methods available on a normal `BN` object
|
||||
* is available here.
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class UInt extends AbstractInt {
|
||||
public static with (bitLength: UIntBitLength, typeName?: string): CodecClass<UInt> {
|
||||
return class extends UInt {
|
||||
constructor (registry: CodecRegistry, value?: AnyNumber) {
|
||||
super(registry, value, bitLength);
|
||||
}
|
||||
|
||||
public override toRawType (): string {
|
||||
return typeName || super.toRawType();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { assert, compactFromU8a, logger, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from '../abstract/AbstractArray';
|
||||
import { decodeU8aVec, typeToConstructor } from '../utils';
|
||||
|
||||
const MAX_LENGTH = 64 * 1024;
|
||||
|
||||
const l = logger('Vec');
|
||||
|
||||
export function decodeVec<T extends Codec> (registry: CodecRegistry, Type: CodecClass<T>, value: Uint8Array | HexString | unknown[], length = -1): [T[], number, number] {
|
||||
if (Array.isArray(value)) {
|
||||
const result = new Array<T>(value.length);
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const entry = value[i];
|
||||
|
||||
try {
|
||||
result[i] = entry instanceof Type
|
||||
? entry
|
||||
: new Type(registry, entry);
|
||||
} catch (error) {
|
||||
l.error(`Unable to decode on index ${i}`, (error as Error).message);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return [result, 0, 0];
|
||||
}
|
||||
|
||||
const u8a = u8aToU8a(value);
|
||||
let offset = 0;
|
||||
|
||||
if (length === -1) {
|
||||
const [_offset, _length] = compactFromU8a(u8a);
|
||||
|
||||
assert(_length.lten(MAX_LENGTH), () => `Vec length ${_length.toString()} exceeds ${MAX_LENGTH}`);
|
||||
|
||||
length = _length.toNumber();
|
||||
offset = _offset;
|
||||
}
|
||||
|
||||
return decodeU8aVec(registry, u8a, offset, Type, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Vec
|
||||
* @description
|
||||
* This manages codec arrays. Internally it keeps track of the length (as decoded) and allows
|
||||
* construction with the passed `Type` in the constructor. It is an extension to Array, providing
|
||||
* specific encoding/decoding on top of the base type.
|
||||
*/
|
||||
export class Vec<T extends Codec> extends AbstractArray<T> {
|
||||
#Type: CodecClass<T>;
|
||||
|
||||
constructor (registry: CodecRegistry, Type: CodecClass<T> | string, value: Uint8Array | HexString | unknown[] = []) {
|
||||
const Clazz = typeToConstructor<T>(registry, Type);
|
||||
const [values, decodedLength] = decodeVec(registry, Clazz, value);
|
||||
|
||||
super(registry, values, decodedLength);
|
||||
|
||||
this.#Type = Clazz;
|
||||
}
|
||||
|
||||
public static with<O extends Codec> (Type: CodecClass<O> | string): CodecClass<Vec<O>> {
|
||||
return class extends Vec<O> {
|
||||
constructor (registry: CodecRegistry, value?: any[]) {
|
||||
super(registry, Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The type for the items
|
||||
*/
|
||||
public get Type (): string {
|
||||
return this.#Type.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Finds the index of the value in the array
|
||||
*/
|
||||
public override indexOf (_other?: unknown): number {
|
||||
// convert type first, this removes overhead from the eq
|
||||
const other = _other instanceof this.#Type
|
||||
? _other
|
||||
: new this.#Type(this.registry, _other);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
if (other.eq(this[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return `Vec<${this.registry.getClassName(this.#Type) || new this.#Type(this.registry).toRawType()}>`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec } from '../types';
|
||||
|
||||
import { AbstractArray } from '../abstract/AbstractArray';
|
||||
|
||||
/**
|
||||
* @name VecAny
|
||||
* @description
|
||||
* This manages codec arrays, assuming that the inputs are already of type Codec. Unlike
|
||||
* a vector, this can be used to manage array-like structures with variable arguments of
|
||||
* any types
|
||||
*/
|
||||
export class VecAny<T extends Codec> extends AbstractArray<T> {
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
// FIXME This is basically an any type, cannot instantiate via createType
|
||||
return 'Vec<Codec>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { assert, isU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from '../abstract/AbstractArray';
|
||||
import { decodeU8aVec, typeToConstructor } from '../utils';
|
||||
import { decodeVec } from './Vec';
|
||||
|
||||
/** @internal */
|
||||
function decodeVecFixed<T extends Codec> (registry: CodecRegistry, value: Uint8Array | HexString | unknown[], Type: CodecClass<T>, length: number): [T[], number, number] {
|
||||
const [values, decodedLength, decodedLengthNoOffset] = decodeVec(registry, Type, value, length);
|
||||
|
||||
while (values.length < length) {
|
||||
values.push(new Type(registry));
|
||||
}
|
||||
|
||||
assert(values.length === length, () => `Expected a length of exactly ${length} entries`);
|
||||
|
||||
return [values, decodedLength, decodedLengthNoOffset];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name VecFixed
|
||||
* @description
|
||||
* This manages codec arrays of a fixed length
|
||||
*/
|
||||
export class VecFixed<T extends Codec> extends AbstractArray<T> {
|
||||
#Type: CodecClass<T>;
|
||||
|
||||
constructor (registry: CodecRegistry, Type: CodecClass<T> | string, length: number, value: Uint8Array | HexString | unknown[] = [] as unknown[]) {
|
||||
const Clazz = typeToConstructor<T>(registry, Type);
|
||||
const [values,, decodedLengthNoOffset] = isU8a(value)
|
||||
? decodeU8aVec(registry, value, 0, Clazz, length)
|
||||
: decodeVecFixed(registry, value, Clazz, length);
|
||||
|
||||
super(registry, values, decodedLengthNoOffset);
|
||||
|
||||
this.#Type = Clazz;
|
||||
}
|
||||
|
||||
public static with<O extends Codec> (Type: CodecClass<O> | string, length: number): CodecClass<VecFixed<O>> {
|
||||
return class extends VecFixed<O> {
|
||||
constructor (registry: CodecRegistry, value?: any[]) {
|
||||
super(registry, Type, length, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The type for the items
|
||||
*/
|
||||
public get Type (): string {
|
||||
return new this.#Type(this.registry).toRawType();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public override get encodedLength (): number {
|
||||
let total = 0;
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
total += this[i].encodedLength;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
public override toU8a (): Uint8Array {
|
||||
// we override, we don't add the length prefix for ourselves, and at the same time we
|
||||
// ignore isBare on entries, since they should be properly encoded at all times
|
||||
const encoded = new Array<Uint8Array>(this.length);
|
||||
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
encoded[i] = this[i].toU8a();
|
||||
}
|
||||
|
||||
return encoded.length
|
||||
? u8aConcat(...encoded)
|
||||
: new Uint8Array([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return `[${this.Type};${this.length}]`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { Base } from './Base';
|
||||
export { Compact } from './Compact';
|
||||
export { DoNotConstruct } from './DoNotConstruct';
|
||||
export { Enum } from './Enum';
|
||||
export { Int } from './Int';
|
||||
export { Null } from './Null';
|
||||
export { Option } from './Option';
|
||||
export { Result } from './Result';
|
||||
export { Tuple } from './Tuple';
|
||||
export { UInt } from './UInt';
|
||||
export { Vec } from './Vec';
|
||||
export { VecAny } from './VecAny';
|
||||
export { VecFixed } from './VecFixed';
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
|
||||
export * from './abstract';
|
||||
export * from './base';
|
||||
export * from './extended';
|
||||
export * from './native';
|
||||
export * from './primitive';
|
||||
export * from './utils';
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { detectPackage } from '@polkadot/util';
|
||||
|
||||
import { packageInfo } from './packageInfo';
|
||||
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, []);
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { CodecMap } from './Map';
|
||||
|
||||
export class BTreeMap<K extends Codec = Codec, V extends Codec = Codec> extends CodecMap<K, V> {
|
||||
public static with<K extends Codec, V extends Codec> (keyType: CodecClass<K> | string, valType: CodecClass<V> | string): CodecClass<CodecMap<K, V>> {
|
||||
return class extends BTreeMap<K, V> {
|
||||
constructor (registry: CodecRegistry, value?: Uint8Array | string | Map<any, any>) {
|
||||
super(registry, keyType, valType, value, 'BTreeMap');
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecClass, CodecRegistry, ISet, IU8a } from '../types';
|
||||
|
||||
import { compactFromU8a, compactToU8a, isHex, isU8a, logger, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { compareSet, decodeU8aVec, sortSet, typeToConstructor } from '../utils';
|
||||
|
||||
const l = logger('BTreeSet');
|
||||
|
||||
/** @internal */
|
||||
function decodeSetFromU8a<V extends Codec> (registry: CodecRegistry, ValClass: CodecClass<V>, u8a: Uint8Array): [Set<V>, number] {
|
||||
const output = new Set<V>();
|
||||
const [offset, length] = compactFromU8a(u8a);
|
||||
const [values, decodedLength] = decodeU8aVec(registry, u8a, offset, ValClass, length.toNumber());
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
output.add(values[i]);
|
||||
}
|
||||
|
||||
return [output, decodedLength + offset];
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeSetFromSet<V extends Codec> (registry: CodecRegistry, ValClass: CodecClass<V>, value: Set<any> | string[]): [Set<V>, number] {
|
||||
const output = new Set<V>();
|
||||
|
||||
value.forEach((val: any) => {
|
||||
try {
|
||||
output.add((val instanceof ValClass) ? val : new ValClass(registry, val));
|
||||
} catch (error) {
|
||||
l.error('Failed to decode key or value:', (error as Error).message);
|
||||
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
return [output, 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode input to pass into constructor.
|
||||
*
|
||||
* @param ValClass - Type of the map value
|
||||
* @param value - Value to decode, one of:
|
||||
* - null
|
||||
* - undefined
|
||||
* - hex
|
||||
* - Uint8Array
|
||||
* - Set<any>, where both key and value types are either
|
||||
* constructors or decodeable values for their types.
|
||||
* @param jsonSet
|
||||
* @internal
|
||||
*/
|
||||
function decodeSet<V extends Codec> (registry: CodecRegistry, valType: CodecClass<V> | string, value?: Uint8Array | string | string[] | Set<any>): [Set<V>, number] {
|
||||
if (!value) {
|
||||
return [new Set<V>(), 0];
|
||||
}
|
||||
|
||||
const ValClass = typeToConstructor(registry, valType);
|
||||
|
||||
if (isU8a(value) || isHex(value)) {
|
||||
return decodeSetFromU8a<V>(registry, ValClass, u8aToU8a(value));
|
||||
} else if (Array.isArray(value) || value instanceof Set) {
|
||||
return decodeSetFromSet<V>(registry, ValClass, value);
|
||||
}
|
||||
|
||||
throw new Error('BTreeSet: cannot decode type');
|
||||
}
|
||||
|
||||
export class BTreeSet<V extends Codec = Codec> extends Set<V> implements ISet<V> {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #ValClass: CodecClass<V>;
|
||||
|
||||
constructor (registry: CodecRegistry, valType: CodecClass<V> | string, rawValue?: Uint8Array | string | string[] | Set<any>) {
|
||||
const [values, decodedLength] = decodeSet(registry, valType, rawValue);
|
||||
|
||||
super(sortSet(values));
|
||||
|
||||
this.registry = registry;
|
||||
this.initialU8aLength = decodedLength;
|
||||
this.#ValClass = typeToConstructor(registry, valType);
|
||||
}
|
||||
|
||||
public static with<V extends Codec> (valType: CodecClass<V> | string): CodecClass<BTreeSet<V>> {
|
||||
return class extends BTreeSet<V> {
|
||||
constructor (registry: CodecRegistry, value?: Uint8Array | string | Set<any>) {
|
||||
super(registry, valType, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
let len = compactToU8a(this.size).length;
|
||||
|
||||
for (const v of this.values()) {
|
||||
len += v.encodedLength;
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hash of the value
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.size === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The actual set values as a string[]
|
||||
*/
|
||||
public get strings (): string[] {
|
||||
return [...super.values()].map((v) => v.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return compareSet(this, other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): AnyJson {
|
||||
const json: AnyJson = [];
|
||||
|
||||
for (const v of this.values()) {
|
||||
json.push(v.toHuman(isExtended));
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): AnyJson {
|
||||
const json: AnyJson = [];
|
||||
|
||||
for (const v of this.values()) {
|
||||
json.push(v.toJSON());
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return `BTreeSet<${this.registry.getClassName(this.#ValClass) || new this.#ValClass(this.registry).toRawType()}>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return stringify(this.toJSON());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
const encoded = new Array<Uint8Array>();
|
||||
|
||||
if (!isBare) {
|
||||
encoded.push(compactToU8a(this.size));
|
||||
}
|
||||
|
||||
for (const v of this.values()) {
|
||||
encoded.push(v.toU8a(isBare));
|
||||
}
|
||||
|
||||
return u8aConcat(...encoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyU8a, CodecRegistry } from '../types';
|
||||
|
||||
import { assert, compactFromU8a, compactToU8a, isString, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Raw } from '../native/Raw';
|
||||
|
||||
/** @internal */
|
||||
function decodeBitVecU8a (value?: Uint8Array): [number, Uint8Array] {
|
||||
if (!value || !value.length) {
|
||||
return [0, new Uint8Array()];
|
||||
}
|
||||
|
||||
// handle all other Uint8Array inputs, these do have a length prefix which is the number of bits encoded
|
||||
const [offset, length] = compactFromU8a(value);
|
||||
const total = offset + Math.ceil(length.toNumber() / 8);
|
||||
|
||||
assert(total <= value.length, () => `BitVec: required length less than remainder, expected at least ${total}, found ${value.length}`);
|
||||
|
||||
return [length.toNumber(), value.subarray(offset, total)];
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeBitVec (value?: AnyU8a): [number, Uint8Array] {
|
||||
if (Array.isArray(value) || isString(value)) {
|
||||
const u8a = u8aToU8a(value);
|
||||
|
||||
return [u8a.length / 8, u8a];
|
||||
}
|
||||
|
||||
return decodeBitVecU8a(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name BitVec
|
||||
* @description
|
||||
* A BitVec that represents an array of bits. The bits are however stored encoded. The difference between this
|
||||
* and a normal Bytes would be that the length prefix indicates the number of bits encoded, not the bytes
|
||||
*/
|
||||
export class BitVec extends Raw {
|
||||
readonly #decodedLength: number;
|
||||
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
const [decodedLength, u8a] = decodeBitVec(value);
|
||||
|
||||
super(registry, u8a);
|
||||
|
||||
this.#decodedLength = decodedLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public override get encodedLength (): number {
|
||||
return this.length + compactToU8a(this.#decodedLength).length;
|
||||
}
|
||||
|
||||
public override toHuman (): string {
|
||||
return `0b${[...this.toU8a(true)].map((d) => `00000000${d.toString(2)}`.slice(-8)).join('_')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return 'BitVec';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public override toU8a (isBare?: boolean): Uint8Array {
|
||||
const bitVec = super.toU8a();
|
||||
|
||||
return isBare
|
||||
? bitVec
|
||||
: u8aConcat(compactToU8a(this.#decodedLength), bitVec);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyU8a, CodecRegistry } from '../types';
|
||||
|
||||
import { assert, compactAddLength, compactFromU8a, compactToU8a, isString, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Raw } from '../native/Raw';
|
||||
|
||||
// Bytes are used for things like on-chain code, so it has a healthy limit
|
||||
const MAX_LENGTH = 10 * 1024 * 1024;
|
||||
|
||||
/** @internal */
|
||||
function decodeBytesU8a (value: Uint8Array): [Uint8Array, number] {
|
||||
if (!value.length) {
|
||||
return [new Uint8Array(), 0];
|
||||
}
|
||||
|
||||
// handle all other Uint8Array inputs, these do have a length prefix
|
||||
const [offset, length] = compactFromU8a(value);
|
||||
const total = offset + length.toNumber();
|
||||
|
||||
assert(length.lten(MAX_LENGTH), () => `Bytes length ${length.toString()} exceeds ${MAX_LENGTH}`);
|
||||
assert(total <= value.length, () => `Bytes: required length less than remainder, expected at least ${total}, found ${value.length}`);
|
||||
|
||||
return [value.subarray(offset, total), total];
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeBytes (value?: AnyU8a): [Uint8Array | undefined, number] {
|
||||
if (Array.isArray(value) || isString(value)) {
|
||||
return [u8aToU8a(value), 0];
|
||||
} else if (!(value instanceof Raw) && isU8a(value)) {
|
||||
// We are ensuring we are not a Raw instance. In the case of a Raw we already have gotten
|
||||
// rid of the length, i.e. new Bytes(new Bytes(...)) will work as expected
|
||||
return decodeBytesU8a(value);
|
||||
}
|
||||
|
||||
return [value, 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Bytes
|
||||
* @description
|
||||
* A Bytes wrapper for Vec<u8>. The significant difference between this and a normal Uint8Array
|
||||
* is that this version allows for length-encoding. (i.e. it is a variable-item codec, the same
|
||||
* as what is found in [[Text]] and [[Vec]])
|
||||
*/
|
||||
export class Bytes extends Raw {
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
const [u8a, decodedLength] = decodeBytes(value);
|
||||
|
||||
super(registry, u8a, decodedLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public override get encodedLength (): number {
|
||||
return this.length + compactToU8a(this.length).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return 'Bytes';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public override toU8a (isBare?: boolean): Uint8Array {
|
||||
return isBare
|
||||
? super.toU8a(isBare)
|
||||
: compactAddLength(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { CodecMap } from './Map';
|
||||
|
||||
export class HashMap<K extends Codec = Codec, V extends Codec = Codec> extends CodecMap<K, V> {
|
||||
public static with<K extends Codec, V extends Codec> (keyType: CodecClass<K> | string, valType: CodecClass<V> | string): CodecClass<CodecMap<K, V>> {
|
||||
return class extends HashMap<K, V> {
|
||||
constructor (registry: CodecRegistry, value?: Uint8Array | string | Map<any, any>) {
|
||||
super(registry, keyType, valType, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { Option } from '../base/Option';
|
||||
import { Tuple } from '../base/Tuple';
|
||||
import { Vec } from '../base/Vec';
|
||||
import { Struct } from '../native/Struct';
|
||||
|
||||
type TypeWithValues = [CodecClass, any[]];
|
||||
|
||||
const EMPTY = new Uint8Array();
|
||||
|
||||
/**
|
||||
* @name Linkage
|
||||
* @description The wrapper for the result from a LinkedMap
|
||||
*/
|
||||
export class Linkage<T extends Codec> extends Struct {
|
||||
constructor (registry: CodecRegistry, Type: CodecClass | string, value?: unknown) {
|
||||
super(registry, {
|
||||
previous: Option.with(Type),
|
||||
// eslint-disable-next-line sort-keys
|
||||
next: Option.with(Type)
|
||||
}, value as HexString);
|
||||
}
|
||||
|
||||
public static withKey<O extends Codec> (Type: CodecClass | string): CodecClass<Linkage<O>> {
|
||||
return class extends Linkage<O> {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public get previous (): Option<T> {
|
||||
return this.get('previous') as Option<T>;
|
||||
}
|
||||
|
||||
public get next (): Option<T> {
|
||||
return this.get('next') as Option<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return `Linkage<${this.next.toRawType(true)}>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Custom toU8a which with bare mode does not return the linkage if empty
|
||||
*/
|
||||
public override toU8a (): Uint8Array {
|
||||
// As part of a storage query (where these appear), in the case of empty, the values
|
||||
// are NOT populated by the node - follow the same logic, leaving it empty
|
||||
return this.isEmpty
|
||||
? EMPTY
|
||||
: super.toU8a();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @name LinkageResult
|
||||
* @description A Linkage keys/Values tuple
|
||||
*/
|
||||
export class LinkageResult extends Tuple {
|
||||
constructor (registry: CodecRegistry, [TypeKey, keys]: TypeWithValues, [TypeValue, values]: TypeWithValues) {
|
||||
super(registry, {
|
||||
Keys: Vec.with(TypeKey),
|
||||
Values: Vec.with(TypeValue)
|
||||
}, [keys, values]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecClass, CodecRegistry, IMap, IU8a } from '../types';
|
||||
|
||||
import { compactFromU8a, compactToU8a, isHex, isObject, isU8a, logger, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from '../abstract/AbstractArray';
|
||||
import { Enum } from '../base/Enum';
|
||||
import { Struct } from '../native/Struct';
|
||||
import { compareMap, decodeU8a, sortMap, typeToConstructor } from '../utils';
|
||||
|
||||
const l = logger('Map');
|
||||
|
||||
/** @internal */
|
||||
function decodeMapFromU8a<K extends Codec, V extends Codec> (registry: CodecRegistry, KeyClass: CodecClass<K>, ValClass: CodecClass<V>, u8a: Uint8Array): [Map<K, V>, number] {
|
||||
const output = new Map<K, V>();
|
||||
const [offset, length] = compactFromU8a(u8a);
|
||||
const count = length.toNumber();
|
||||
const types = [];
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
types.push(KeyClass, ValClass);
|
||||
}
|
||||
|
||||
const [values, decodedLength] = decodeU8a(registry, u8a.subarray(offset), types);
|
||||
|
||||
for (let i = 0; i < values.length; i += 2) {
|
||||
output.set(values[i] as K, values[i + 1] as V);
|
||||
}
|
||||
|
||||
return [output, offset + decodedLength];
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeMapFromMap<K extends Codec, V extends Codec> (registry: CodecRegistry, KeyClass: CodecClass<K>, ValClass: CodecClass<V>, value: Map<any, any>): [Map<K, V>, number] {
|
||||
const output = new Map<K, V>();
|
||||
|
||||
for (const [key, val] of value.entries()) {
|
||||
const isComplex = KeyClass.prototype instanceof AbstractArray ||
|
||||
KeyClass.prototype instanceof Struct ||
|
||||
KeyClass.prototype instanceof Enum;
|
||||
|
||||
try {
|
||||
output.set(
|
||||
key instanceof KeyClass
|
||||
? key
|
||||
: new KeyClass(registry, isComplex ? JSON.parse(key as string) : key),
|
||||
val instanceof ValClass
|
||||
? val
|
||||
: new ValClass(registry, val)
|
||||
);
|
||||
} catch (error) {
|
||||
l.error('Failed to decode key or value:', (error as Error).message);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return [output, 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode input to pass into constructor.
|
||||
*
|
||||
* @param KeyClass - Type of the map key
|
||||
* @param ValClass - Type of the map value
|
||||
* @param value - Value to decode, one of:
|
||||
* - null
|
||||
* - undefined
|
||||
* - hex
|
||||
* - Uint8Array
|
||||
* - Map<any, any>, where both key and value types are either
|
||||
* constructors or decodeable values for their types.
|
||||
* @param jsonMap
|
||||
* @internal
|
||||
*/
|
||||
function decodeMap<K extends Codec, V extends Codec> (registry: CodecRegistry, keyType: CodecClass<K> | string, valType: CodecClass<V> | string, value?: Uint8Array | string | Map<any, any>): [Map<K, V>, number] {
|
||||
const KeyClass = typeToConstructor(registry, keyType);
|
||||
const ValClass = typeToConstructor(registry, valType);
|
||||
|
||||
if (!value) {
|
||||
return [new Map<K, V>(), 0];
|
||||
} else if (isU8a(value) || isHex(value)) {
|
||||
return decodeMapFromU8a<K, V>(registry, KeyClass, ValClass, u8aToU8a(value));
|
||||
} else if (value instanceof Map) {
|
||||
return decodeMapFromMap<K, V>(registry, KeyClass, ValClass, value);
|
||||
} else if (isObject(value)) {
|
||||
return decodeMapFromMap<K, V>(registry, KeyClass, ValClass, new Map(Object.entries(value)));
|
||||
}
|
||||
|
||||
throw new Error('Map: cannot decode type');
|
||||
}
|
||||
|
||||
export class CodecMap<K extends Codec = Codec, V extends Codec = Codec> extends Map<K, V> implements IMap<K, V> {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly #KeyClass: CodecClass<K>;
|
||||
|
||||
readonly #ValClass: CodecClass<V>;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #type: string;
|
||||
|
||||
constructor (registry: CodecRegistry, keyType: CodecClass<K> | string, valType: CodecClass<V> | string, rawValue: Uint8Array | string | Map<any, any> | undefined, type: 'BTreeMap' | 'HashMap' = 'HashMap') {
|
||||
const [decoded, decodedLength] = decodeMap(registry, keyType, valType, rawValue);
|
||||
|
||||
super(type === 'BTreeMap' ? sortMap(decoded) : decoded);
|
||||
|
||||
this.registry = registry;
|
||||
this.initialU8aLength = decodedLength;
|
||||
this.#KeyClass = typeToConstructor(registry, keyType);
|
||||
this.#ValClass = typeToConstructor(registry, valType);
|
||||
this.#type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
let len = compactToU8a(this.size).length;
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
len += v.encodedLength + k.encodedLength;
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hash of the value
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.size === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return compareMap(this, other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): Record<string, AnyJson> {
|
||||
const json: Record<string, AnyJson> = {};
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
json[k.toString()] = v.toHuman(isExtended);
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): Record<string, AnyJson> {
|
||||
const json: Record<string, AnyJson> = {};
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
json[k.toString()] = v.toJSON();
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return `${this.#type}<${this.registry.getClassName(this.#KeyClass) || new this.#KeyClass(this.registry).toRawType()},${this.registry.getClassName(this.#ValClass) || new this.#ValClass(this.registry).toRawType()}>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return stringify(this.toJSON());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
const encoded = new Array<Uint8Array>();
|
||||
|
||||
if (!isBare) {
|
||||
encoded.push(compactToU8a(this.size));
|
||||
}
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
encoded.push(k.toU8a(isBare), v.toU8a(isBare));
|
||||
}
|
||||
|
||||
return u8aConcat(...encoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyTuple, CodecClass, CodecRegistry, INumber } from '../types';
|
||||
|
||||
import { Tuple } from '../base/Tuple';
|
||||
|
||||
type RangeType = 'Range' | 'RangeInclusive';
|
||||
|
||||
/**
|
||||
* @name Range
|
||||
* @description
|
||||
* Rust `Range<T>` representation
|
||||
*/
|
||||
export class Range<T extends INumber> extends Tuple {
|
||||
#rangeName: RangeType;
|
||||
|
||||
constructor (registry: CodecRegistry, Type: CodecClass<T> | string, value?: AnyTuple, rangeName: RangeType = 'Range') {
|
||||
super(registry, { end: Type, start: Type }, value);
|
||||
|
||||
this.#rangeName = rangeName;
|
||||
}
|
||||
|
||||
public static override with <T extends INumber> (Types: CodecClass<T> | string): CodecClass<Range<T>> {
|
||||
return class extends Range<T> {
|
||||
constructor (registry: CodecRegistry, value?: AnyTuple) {
|
||||
super(registry, Types, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the starting range value
|
||||
*/
|
||||
public get start (): T {
|
||||
return this[0] as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the ending range value
|
||||
*/
|
||||
public get end (): T {
|
||||
return this[1] as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return `${this.#rangeName}<${this.start.toRawType()}>`;
|
||||
}
|
||||
}
|
||||
|
||||
export class RangeInclusive<T extends INumber = INumber> extends Range<T> {
|
||||
constructor (registry: CodecRegistry, type: CodecClass<T> | string, value?: AnyTuple) {
|
||||
super(registry, type, value, 'RangeInclusive');
|
||||
}
|
||||
|
||||
public static override with <T extends INumber> (Types: CodecClass<T> | string): CodecClass<RangeInclusive<T>> {
|
||||
return class extends RangeInclusive<T> {
|
||||
constructor (registry: CodecRegistry, value?: AnyTuple) {
|
||||
super(registry, Types, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '../types';
|
||||
|
||||
import { Text } from '../native/Text';
|
||||
import { sanitize } from '../utils';
|
||||
|
||||
/**
|
||||
* @name Type
|
||||
* @description
|
||||
* This is a extended version of Text, specifically to handle types. Here we rely fully
|
||||
* on what Text provides us, however we also adjust the types received from the runtime,
|
||||
* i.e. we remove the `T::` prefixes found in some types for consistency across implementation.
|
||||
*/
|
||||
export class Type extends Text {
|
||||
constructor (registry: CodecRegistry, value: Text | Uint8Array | string = '') {
|
||||
super(registry, value);
|
||||
|
||||
this.setOverride(sanitize(this.toString()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return 'Type';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyU8a, CodecClass, CodecRegistry, U8aBitLength } from '../types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Raw } from '../native/Raw';
|
||||
|
||||
/** @internal */
|
||||
function decodeU8aFixed (value: AnyU8a, bitLength: U8aBitLength): [AnyU8a, number] {
|
||||
const u8a = u8aToU8a(value);
|
||||
const byteLength = bitLength / 8;
|
||||
|
||||
if (!u8a.length) {
|
||||
return [new Uint8Array(byteLength), 0];
|
||||
}
|
||||
|
||||
assert(u8a.length >= byteLength, () => `Expected at least ${byteLength} bytes (${bitLength} bits), found ${u8a.length} bytes`);
|
||||
|
||||
return [u8a.subarray(0, byteLength), byteLength];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name U8aFixed
|
||||
* @description
|
||||
* A U8a that manages a a sequence of bytes up to the specified bitLength. Not meant
|
||||
* to be used directly, rather is should be subclassed with the specific lengths.
|
||||
*/
|
||||
export class U8aFixed extends Raw {
|
||||
constructor (registry: CodecRegistry, value: AnyU8a = new Uint8Array(), bitLength: U8aBitLength = 256) {
|
||||
const [u8a, decodedLength] = decodeU8aFixed(value, bitLength);
|
||||
|
||||
super(registry, u8a, decodedLength);
|
||||
}
|
||||
|
||||
public static with (bitLength: U8aBitLength, typeName?: string): CodecClass<U8aFixed> {
|
||||
return class extends U8aFixed {
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
super(registry, value, bitLength);
|
||||
}
|
||||
|
||||
public override toRawType (): string {
|
||||
return typeName || super.toRawType();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return `[u8;${this.length}]`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { compactAddLength, compactStripLength, isU8a } from '@polkadot/util';
|
||||
|
||||
import { Base } from '../base/Base';
|
||||
import { typeToConstructor } from '../utils';
|
||||
|
||||
function decodeRaw<T extends Codec> (registry: CodecRegistry, Type: CodecClass<T> | string, value?: unknown): T {
|
||||
const Clazz = typeToConstructor<T>(registry, Type);
|
||||
|
||||
if (isU8a(value)) {
|
||||
const [, u8a] = compactStripLength(value);
|
||||
|
||||
return new Clazz(registry, u8a);
|
||||
}
|
||||
|
||||
return new Clazz(registry, value);
|
||||
}
|
||||
|
||||
export class WrapperOpaque<T extends Codec> extends Base<T> {
|
||||
constructor (registry: CodecRegistry, Type: CodecClass<T> | string, value?: unknown) {
|
||||
super(registry, decodeRaw(registry, Type, value));
|
||||
}
|
||||
|
||||
public static with<T extends Codec> (Type: CodecClass<T> | string): CodecClass<WrapperOpaque<T>> {
|
||||
return class extends WrapperOpaque<T> {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return `WrapperOpaque<${this._raw.toRawType()}>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public override toU8a (isBare?: boolean): Uint8Array {
|
||||
const u8a = super.toU8a(isBare);
|
||||
|
||||
return isBare
|
||||
? u8a
|
||||
: compactAddLength(u8a);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Return the inner value for the wrapped type
|
||||
*/
|
||||
public unwrap (): T {
|
||||
return this._raw;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { BitVec } from './BitVec';
|
||||
export { BTreeMap } from './BTreeMap';
|
||||
export { BTreeSet } from './BTreeSet';
|
||||
export { Bytes } from './Bytes';
|
||||
export { HashMap } from './HashMap';
|
||||
export { Linkage } from './Linkage';
|
||||
export { CodecMap, CodecMap as Map } from './Map';
|
||||
export { Range, RangeInclusive } from './Range';
|
||||
export { Type } from './Type';
|
||||
export { U8aFixed } from './U8aFixed';
|
||||
export { WrapperOpaque } from './WrapperOpaque';
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import './detectPackage';
|
||||
|
||||
export * from './bundle';
|
||||
@@ -0,0 +1,127 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
import { isU8a, u8aToHex } from '@polkadot/util';
|
||||
|
||||
/** @internal */
|
||||
function decodeBool (value: any): boolean {
|
||||
if (isU8a(value)) {
|
||||
return value[0] === 1;
|
||||
} else if (value instanceof Boolean) {
|
||||
return value.valueOf();
|
||||
}
|
||||
|
||||
return !!value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @name bool
|
||||
* @description
|
||||
* Representation for a boolean value in the system. It extends the base JS `Boolean` class
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class bool extends Boolean implements Codec {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
constructor (registry: CodecRegistry, value: bool | Boolean | Uint8Array | boolean | number = false) {
|
||||
super(decodeBool(value));
|
||||
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value (true when it wraps false/default)
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.isFalse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value (always false)
|
||||
*/
|
||||
public get isFalse (): boolean {
|
||||
return !this.isTrue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value (always false)
|
||||
*/
|
||||
public get isTrue (): boolean {
|
||||
return this.valueOf();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return this.valueOf() === (
|
||||
other instanceof Boolean
|
||||
? other.valueOf()
|
||||
: other
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): boolean {
|
||||
return this.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): boolean {
|
||||
return this.valueOf();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'bool';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return this.toJSON().toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return new Uint8Array([this.valueOf() ? 1 : 0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyNumber, CodecRegistry, INumber, IU8a, UIntBitLength } from '../types';
|
||||
|
||||
import { BN, bnToBn, bnToHex, bnToU8a, isString, isU8a, u8aToBn } from '@polkadot/util';
|
||||
|
||||
const BITLENGTH: UIntBitLength = 64;
|
||||
|
||||
function decodeDate (value: CodecDate | Date | AnyNumber): Date {
|
||||
if (isU8a(value)) {
|
||||
value = u8aToBn(value.subarray(0, BITLENGTH / 8), true);
|
||||
} else if (value instanceof Date) {
|
||||
return value;
|
||||
} else if (isString(value)) {
|
||||
value = new BN(value.toString(), 10, 'le');
|
||||
}
|
||||
|
||||
return new Date(
|
||||
bnToBn(value as BN).toNumber() * 1000
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Date
|
||||
* @description
|
||||
* A wrapper around seconds/timestamps. Internally the representation only has
|
||||
* second precicion (aligning with Rust), so any numbers passed an/out are always
|
||||
* per-second. For any encoding/decoding the 1000 multiplier would be applied to
|
||||
* get it in line with JavaScript formats. It extends the base JS `Date` object
|
||||
* and has all the methods available that are applicable to any `Date`
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class CodecDate extends Date implements INumber {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
constructor (registry: CodecRegistry, value: CodecDate | Date | AnyNumber = 0) {
|
||||
super(decodeDate(value));
|
||||
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return BITLENGTH / 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.getTime() === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return decodeDate(other as AnyNumber).getTime() === this.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number of bits in the value
|
||||
*/
|
||||
public bitLength (): UIntBitLength {
|
||||
return BITLENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a BigInt representation of the number
|
||||
*/
|
||||
public toBigInt (): bigint {
|
||||
return BigInt(this.toNumber());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the BN representation of the timestamp
|
||||
*/
|
||||
public toBn (): BN {
|
||||
return new BN(this.toNumber());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (isLe = false): HexString {
|
||||
return bnToHex(this.toBn(), {
|
||||
bitLength: BITLENGTH,
|
||||
isLe,
|
||||
isNegative: false
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): string {
|
||||
return this.toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public override toJSON (): any {
|
||||
// FIXME Return type should be number, but conflicts with Date.toJSON()
|
||||
// which returns string
|
||||
return this.toNumber();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number representation for the timestamp
|
||||
*/
|
||||
public toNumber (): number {
|
||||
return Math.ceil(this.getTime() / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'Moment';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
// only included here since we do not inherit docs
|
||||
return super.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this.toNumber(), BITLENGTH, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, Codec, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
import { isFunction, objectProperties, stringify } from '@polkadot/util';
|
||||
|
||||
import { compareMap } from '../utils';
|
||||
|
||||
/** @internal */
|
||||
function decodeJson (value?: Record<string, unknown> | null): [string, any][] {
|
||||
return Object.entries(value || {});
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Json
|
||||
* @description
|
||||
* Wraps the a JSON structure retrieve via RPC. It extends the standard JS Map with. While it
|
||||
* implements a Codec, it is limited in that it can only be used with input objects via RPC,
|
||||
* i.e. no hex decoding. Unlike a struct, this waps a JSON object with unknown keys
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class Json extends Map<string, any> implements Codec {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
constructor (registry: CodecRegistry, value?: Record<string, unknown> | null) {
|
||||
const decoded = decodeJson(value);
|
||||
|
||||
super(decoded);
|
||||
|
||||
this.registry = registry;
|
||||
|
||||
objectProperties(this, decoded.map(([k]) => k), (k) => this.get(k));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Always 0, never encodes as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return [...this.keys()].length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return compareMap(this, other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Unimplemented, will throw
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
throw new Error('Unimplemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): Record<string, AnyJson> {
|
||||
return [...this.entries()].reduce<Record<string, AnyJson>>((json, [key, value]): Record<string, AnyJson> => {
|
||||
json[key] = isFunction((value as Codec).toHuman)
|
||||
? (value as Codec).toHuman()
|
||||
: value as AnyJson;
|
||||
|
||||
return json;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): Record<string, AnyJson> {
|
||||
return [...this.entries()].reduce<Record<string, AnyJson>>((json, [key, value]): Record<string, AnyJson> => {
|
||||
json[key] = value as AnyJson;
|
||||
|
||||
return json;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'Json';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return stringify(this.toJSON());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Unimplemented, will throw
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
throw new Error('Unimplemented');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, AnyU8a, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
import { assert, isAscii, isUndefined, isUtf8, u8aToHex, u8aToString, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
/**
|
||||
* @name Raw
|
||||
* @description
|
||||
* A basic wrapper around Uint8Array, with no frills and no fuss. It does differ
|
||||
* from other implementations where it will consume the full Uint8Array as passed to it.
|
||||
* As such it is meant to be subclassed where the wrapper takes care of the
|
||||
* actual lengths instead of used directly.
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class Raw extends Uint8Array implements IU8a {
|
||||
readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a, initialU8aLength?: number) {
|
||||
super(u8aToU8a(value));
|
||||
|
||||
this.registry = registry;
|
||||
this.initialU8aLength = initialU8aLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return this.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns true if the wrapped value contains only ASCII printable characters
|
||||
*/
|
||||
public get isAscii (): boolean {
|
||||
return isAscii(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns true if the type wraps an empty/default all-0 value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return !this.length || isUndefined(this.find((b) => !!b));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns true if the wrapped value contains only utf8 characters
|
||||
*/
|
||||
public get isUtf8 (): boolean {
|
||||
return isUtf8(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value
|
||||
*/
|
||||
public override get length (): number {
|
||||
// only included here since we ignore inherited docs
|
||||
return super.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the number of bits in the value
|
||||
*/
|
||||
public bitLength (): number {
|
||||
return this.length * 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
if (other instanceof Uint8Array) {
|
||||
return (this.length === other.length) &&
|
||||
!this.some((b, index) => b !== other[index]);
|
||||
}
|
||||
|
||||
return this.eq(u8aToU8a(other as string));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Create a new slice from the actual buffer. (compat)
|
||||
* @param start The position to start at
|
||||
* @param end The position to end at
|
||||
*/
|
||||
public override slice (start?: number, end?: number): Uint8Array {
|
||||
// Like subarray below, we have to follow this approach since we are extending the TypeArray.
|
||||
// This happens especially when it comes to further extensions, the length may be an override
|
||||
return Uint8Array.from(this).slice(start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Create a new subarray from the actual buffer. (compat)
|
||||
* @param begin The position to start at
|
||||
* @param end The position to end at
|
||||
*/
|
||||
public override subarray (begin?: number, end?: number): Uint8Array {
|
||||
return Uint8Array.from(this).subarray(begin, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): AnyJson {
|
||||
if (this.isAscii) {
|
||||
const text = this.toUtf8();
|
||||
|
||||
// ensure we didn't end up with multibyte codepoints
|
||||
if (isAscii(text)) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
return this.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): string {
|
||||
return this.toHex();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'Raw';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return this.toHex();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return Uint8Array.from(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the wrapped data as a UTF-8 string
|
||||
*/
|
||||
public toUtf8 (): string {
|
||||
assert(this.isUtf8, 'The character sequence is not a valid Utf8 string');
|
||||
|
||||
return u8aToString(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecClass, CodecRegistry, ISet, IU8a } from '../types';
|
||||
|
||||
import { assert, BN, bnToBn, bnToU8a, isBn, isNumber, isString, isU8a, isUndefined, objectProperties, stringify, stringPascalCase, u8aToBn, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { compareArray } from '../utils';
|
||||
|
||||
type SetValues = Record<string, number | BN>;
|
||||
|
||||
function encodeSet (setValues: SetValues, values: string[]): BN {
|
||||
const encoded = new BN(0);
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
encoded.ior(bnToBn(setValues[values[i]] || 0));
|
||||
}
|
||||
|
||||
return encoded;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeSetArray (setValues: SetValues, values: string[]): string[] {
|
||||
const result = new Array<string>(values.length);
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const key = values[i];
|
||||
|
||||
assert(!isUndefined(setValues[key]), () => `Set: Invalid key '${key}' passed to Set, allowed ${Object.keys(setValues).join(', ')}`);
|
||||
|
||||
result[i] = key;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeSetNumber (setValues: SetValues, _value: BN | number): string[] {
|
||||
const bn = bnToBn(_value);
|
||||
const keys = Object.keys(setValues);
|
||||
const result: string[] = [];
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
|
||||
if (bn.and(bnToBn(setValues[key])).eq(bnToBn(setValues[key]))) {
|
||||
result.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
const computed = encodeSet(setValues, result);
|
||||
|
||||
assert(bn.eq(computed), () => `Set: Mismatch decoding '${bn.toString()}', computed as '${computed.toString()}' with ${result.join(', ')}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeSet (setValues: SetValues, value: string[] | Set<string> | Uint8Array | BN | number | string = 0, bitLength: number): string[] {
|
||||
assert(bitLength % 8 === 0, () => `Expected valid bitLength, power of 8, found ${bitLength}`);
|
||||
|
||||
const byteLength = bitLength / 8;
|
||||
|
||||
if (isU8a(value)) {
|
||||
return value.length === 0
|
||||
? []
|
||||
: decodeSetNumber(setValues, u8aToBn(value.subarray(0, byteLength), { isLe: true }));
|
||||
} else if (isString(value)) {
|
||||
return decodeSet(setValues, u8aToU8a(value), byteLength);
|
||||
} else if (value instanceof Set || Array.isArray(value)) {
|
||||
const input = Array.isArray(value)
|
||||
? value
|
||||
: [...value.values()];
|
||||
|
||||
return decodeSetArray(setValues, input);
|
||||
}
|
||||
|
||||
return decodeSetNumber(setValues, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Set
|
||||
* @description
|
||||
* An Set is an array of string values, represented an an encoded type by
|
||||
* a bitwise representation of the values.
|
||||
*/
|
||||
export class CodecSet extends Set<string> implements ISet<string> {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly #allowed: SetValues;
|
||||
|
||||
readonly #byteLength: number;
|
||||
|
||||
constructor (registry: CodecRegistry, setValues: SetValues, value?: string[] | Set<string> | Uint8Array | BN | number | string, bitLength = 8) {
|
||||
super(decodeSet(setValues, value, bitLength));
|
||||
|
||||
this.registry = registry;
|
||||
this.#allowed = setValues;
|
||||
this.#byteLength = bitLength / 8;
|
||||
}
|
||||
|
||||
public static with (values: SetValues, bitLength?: number): CodecClass<CodecSet> {
|
||||
const keys = Object.keys(values);
|
||||
const isKeys = new Array<string>(keys.length);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
isKeys[i] = `is${stringPascalCase(keys[i])}`;
|
||||
}
|
||||
|
||||
return class extends CodecSet {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, values, value as undefined, bitLength);
|
||||
|
||||
objectProperties(this, isKeys, (_, i) => this.strings.includes(keys[i]));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return this.#byteLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description true is the Set contains no values
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.size === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The actual set values as a string[]
|
||||
*/
|
||||
public get strings (): string[] {
|
||||
return [...super.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The encoded value for the set members
|
||||
*/
|
||||
public get valueEncoded (): BN {
|
||||
return encodeSet(this.#allowed, this.strings);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description adds a value to the Set (extended to allow for validity checking)
|
||||
*/
|
||||
public override add = (key: string): this => {
|
||||
// ^^^ add = () property done to assign this instance's this, otherwise Set.add creates "some" chaos
|
||||
// we have the isUndefined(this._setValues) in here as well, add is used internally
|
||||
// in the Set constructor (so it is undefined at this point, and should allow)
|
||||
assert(isUndefined(this.#allowed) || !isUndefined(this.#allowed[key]), () => `Set: Invalid key '${key}' on add`);
|
||||
|
||||
super.add(key);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
if (Array.isArray(other)) {
|
||||
// we don't actually care about the order, sort the values
|
||||
return compareArray(this.strings.sort(), other.sort());
|
||||
} else if (other instanceof Set) {
|
||||
return this.eq([...other.values()]);
|
||||
} else if (isNumber(other) || isBn(other as string)) {
|
||||
return this.valueEncoded.eq(bnToBn(other as string));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): string[] {
|
||||
return this.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): string[] {
|
||||
return this.strings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The encoded value for the set members
|
||||
*/
|
||||
public toNumber (): number {
|
||||
return this.valueEncoded.toNumber();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return stringify({ _set: this.#allowed });
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return `[${this.strings.join(', ')}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this.valueEncoded, {
|
||||
bitLength: this.#byteLength * 8,
|
||||
isLe: true
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson, BareOpts, Codec, CodecClass, CodecClassDef, CodecRegistry, IStruct, IU8a } from '../types';
|
||||
|
||||
import { assert, isBoolean, isFunction, isHex, isObject, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { compareMap, decodeU8a, mapToTypeMap, typesToMap } from '../utils';
|
||||
|
||||
type TypesDef<T = Codec> = Record<string, string | CodecClass<T>>;
|
||||
|
||||
/** @internal */
|
||||
function decodeStructFromObject (registry: CodecRegistry, Types: CodecClassDef, value: any, jsonMap: Map<string, string>): [Iterable<[string, Codec]>, number] {
|
||||
let jsonObj: Record<string, unknown> | undefined;
|
||||
const inputKeys = Object.keys(Types);
|
||||
const typeofArray = Array.isArray(value);
|
||||
const typeofMap = value instanceof Map;
|
||||
|
||||
assert(typeofArray || typeofMap || isObject(value), () => `Struct: Cannot decode value ${stringify(value)} (typeof ${typeof value}), expected an input object, map or array`);
|
||||
assert(!typeofArray || value.length === inputKeys.length, () => `Struct: Unable to map ${stringify(value)} array to object with known keys ${inputKeys.join(', ')}`);
|
||||
|
||||
const raw = new Array<[string, Codec]>(inputKeys.length);
|
||||
|
||||
for (let i = 0; i < inputKeys.length; i++) {
|
||||
const key = inputKeys[i];
|
||||
const jsonKey = jsonMap.get(key) || key;
|
||||
const Type = Types[key];
|
||||
let assign: unknown;
|
||||
|
||||
try {
|
||||
if (typeofArray) {
|
||||
assign = value[i] as unknown;
|
||||
} else if (typeofMap) {
|
||||
assign = jsonKey && value.get(jsonKey);
|
||||
} else {
|
||||
assign = jsonKey && value[jsonKey] as unknown;
|
||||
|
||||
if (isUndefined(assign)) {
|
||||
if (isUndefined(jsonObj)) {
|
||||
const entries = Object.entries(value);
|
||||
|
||||
jsonObj = {};
|
||||
|
||||
for (let e = 0; e < entries.length; e++) {
|
||||
jsonObj[stringCamelCase(entries[e][0])] = entries[e][1];
|
||||
}
|
||||
}
|
||||
|
||||
assign = jsonKey && jsonObj[jsonKey];
|
||||
}
|
||||
}
|
||||
|
||||
raw[i] = [
|
||||
key,
|
||||
assign instanceof Type
|
||||
? assign
|
||||
: new Type(registry, assign)
|
||||
];
|
||||
} catch (error) {
|
||||
let type = Type.name;
|
||||
|
||||
try {
|
||||
type = new Type(registry).toRawType();
|
||||
} catch (error) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
throw new Error(`Struct: failed on ${jsonKey}: ${type}:: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return [raw, 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Struct
|
||||
* @description
|
||||
* A Struct defines an Object with key-value pairs - where the values are Codec values. It removes
|
||||
* a lot of repetition from the actual coding, define a structure type, pass it the key/Codec
|
||||
* values in the constructor and it manages the decoding. It is important that the constructor
|
||||
* values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical,
|
||||
* it needs to decoded in the specific defined order.
|
||||
* @noInheritDoc
|
||||
*/
|
||||
export class Struct<
|
||||
// The actual Class structure, i.e. key -> Class
|
||||
S extends TypesDef = TypesDef,
|
||||
// input values, mapped by key can be anything (construction)
|
||||
V extends { [K in keyof S]: any } = { [K in keyof S]: any },
|
||||
// type names, mapped by key, name of Class in S
|
||||
E extends { [K in keyof S]: string } = { [K in keyof S]: string }> extends Map<keyof S, Codec> implements IStruct<keyof S> {
|
||||
readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #jsonMap: Map<keyof S, string>;
|
||||
|
||||
readonly #Types: CodecClassDef;
|
||||
|
||||
constructor (registry: CodecRegistry, Types: S, value?: V | Map<unknown, unknown> | unknown[] | HexString | null, jsonMap = new Map<string, string>()) {
|
||||
const typeMap = mapToTypeMap(registry, Types);
|
||||
const [decoded, decodedLength] = isU8a(value)
|
||||
? decodeU8a<Codec, [string, Codec]>(registry, value, typeMap, true)
|
||||
: isHex(value)
|
||||
? decodeU8a<Codec, [string, Codec]>(registry, u8aToU8a(value), typeMap, true)
|
||||
: value instanceof Struct
|
||||
? [value as Iterable<[string, Codec]>, 0]
|
||||
: decodeStructFromObject(registry, typeMap, value || {}, jsonMap);
|
||||
|
||||
super(decoded);
|
||||
|
||||
this.registry = registry;
|
||||
this.initialU8aLength = decodedLength;
|
||||
this.#jsonMap = jsonMap;
|
||||
this.#Types = typeMap;
|
||||
}
|
||||
|
||||
public static with<S extends TypesDef> (Types: S, jsonMap?: Map<string, string>): CodecClass<Struct<S>> {
|
||||
const keys = Object.keys(Types);
|
||||
|
||||
return class extends Struct<S> {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, Types, value as HexString, jsonMap);
|
||||
|
||||
objectProperties(this, keys, (k) => this.get(k));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The available keys for this struct
|
||||
*/
|
||||
public get defKeys (): string[] {
|
||||
return Object.keys(this.#Types);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
for (const v of this.values()) {
|
||||
if (!v.isEmpty) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the Type description of the structure
|
||||
*/
|
||||
public get Type (): E {
|
||||
const result: Record<string, string> = {};
|
||||
const defs = Object.entries(this.#Types);
|
||||
|
||||
for (let i = 0; i < defs.length; i++) {
|
||||
const [key, Type] = defs[i];
|
||||
|
||||
result[key] = new Type(this.registry).toRawType();
|
||||
}
|
||||
|
||||
return result as E;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
let total = 0;
|
||||
|
||||
for (const v of this.values()) {
|
||||
total += v.encodedLength;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return compareMap(this, other);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a specific names entry in the structure
|
||||
* @param name The name of the entry to retrieve
|
||||
*/
|
||||
public override get (name: keyof S): Codec | undefined {
|
||||
return super.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the values of a member at a specific index (Rather use get(name) for performance)
|
||||
*/
|
||||
public getAtIndex (index: number): Codec {
|
||||
return this.toArray()[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to an standard JavaScript Array
|
||||
*/
|
||||
public toArray (): Codec[] {
|
||||
return [...this.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (isExtended?: boolean): Record<string, AnyJson> {
|
||||
const json: Record<string, AnyJson> = {};
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
json[k as string] = v && v.toHuman(isExtended);
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): Record<string, AnyJson> {
|
||||
const json: Record<string, AnyJson> = {};
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
const jsonKey = this.#jsonMap.get(k) || k;
|
||||
|
||||
json[jsonKey as string] = v && v.toJSON();
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return stringify(typesToMap(this.registry, this.#Types));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return stringify(this.toJSON());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: BareOpts): Uint8Array {
|
||||
const encoded: Uint8Array[] = [];
|
||||
|
||||
for (const [k, v] of this.entries()) {
|
||||
if (v && isFunction(v.toU8a)) {
|
||||
encoded.push(
|
||||
v.toU8a(
|
||||
!isBare || isBoolean(isBare)
|
||||
? isBare
|
||||
: isBare[k]
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return u8aConcat(...encoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyU8a, Codec, CodecRegistry, IU8a } from '../types';
|
||||
|
||||
import { assert, compactAddLength, compactFromU8a, hexToU8a, isHex, isString, isU8a, stringToU8a, u8aToHex, u8aToString } from '@polkadot/util';
|
||||
|
||||
import { Raw } from './Raw';
|
||||
|
||||
const MAX_LENGTH = 128 * 1024;
|
||||
|
||||
/** @internal */
|
||||
function decodeText (value?: null | Text | string | AnyU8a | { toString: () => string }): [string, number] {
|
||||
if (isU8a(value)) {
|
||||
if (!value.length) {
|
||||
return ['', 0];
|
||||
}
|
||||
|
||||
// for Raw, the internal buffer does not have an internal length
|
||||
// (the same applies in e.g. Bytes, where length is added at encoding-time)
|
||||
if (value instanceof Raw) {
|
||||
return [u8aToString(value), 0];
|
||||
}
|
||||
|
||||
const [offset, length] = compactFromU8a(value);
|
||||
const total = offset + length.toNumber();
|
||||
|
||||
assert(length.lten(MAX_LENGTH), () => `Text: length ${length.toString()} exceeds ${MAX_LENGTH}`);
|
||||
assert(total <= value.length, () => `Text: required length less than remainder, expected at least ${total}, found ${value.length}`);
|
||||
|
||||
return [u8aToString(value.subarray(offset, total)), total];
|
||||
} else if (isHex(value)) {
|
||||
return [u8aToString(hexToU8a(value)), 0];
|
||||
}
|
||||
|
||||
return [value ? value.toString() : '', 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name Text
|
||||
* @description
|
||||
* This is a string wrapper, along with the length. It is used both for strings as well
|
||||
* as items such as documentation. It simply extends the standard JS `String` built-in
|
||||
* object, inheriting all methods exposed from `String`.
|
||||
* @noInheritDoc
|
||||
*/
|
||||
// TODO
|
||||
// - Strings should probably be trimmed (docs do come through with extra padding)
|
||||
export class Text extends String implements Codec {
|
||||
public readonly registry: CodecRegistry;
|
||||
|
||||
public createdAtHash?: IU8a;
|
||||
|
||||
readonly #initialU8aLength?: number;
|
||||
|
||||
#override: string | null = null;
|
||||
|
||||
constructor (registry: CodecRegistry, value?: null | Text | string | AnyU8a | { toString: () => string }) {
|
||||
const [str, decodedLength] = decodeText(value);
|
||||
|
||||
super(str);
|
||||
|
||||
this.registry = registry;
|
||||
this.#initialU8aLength = decodedLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
public get encodedLength (): number {
|
||||
return this.toU8a().length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the initial encoded value (Only available when constructed from a Uint8Array)
|
||||
*/
|
||||
public get initialU8aLength (): number | undefined {
|
||||
return this.#initialU8aLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description returns a hash of the contents
|
||||
*/
|
||||
public get hash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
public get isEmpty (): boolean {
|
||||
return this.length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The length of the value
|
||||
*/
|
||||
public override get length (): number {
|
||||
// only included here since we ignore inherited docs
|
||||
return super.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
public eq (other?: unknown): boolean {
|
||||
return isString(other)
|
||||
? this.toString() === other.toString()
|
||||
: false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Set an override value for this
|
||||
*/
|
||||
public setOverride (override: string): void {
|
||||
this.#override = override;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (): HexString {
|
||||
// like with Vec<u8>, when we are encoding to hex, we don't actually add
|
||||
// the length prefix (it is already implied by the actual string length)
|
||||
return u8aToHex(this.toU8a(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
public toHuman (): string {
|
||||
return this.toJSON();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
public toJSON (): string {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public toRawType (): string {
|
||||
return 'Text';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
public override toString (): string {
|
||||
return this.#override || super.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
public toU8a (isBare?: boolean): Uint8Array {
|
||||
// NOTE Here we use the super toString (we are not taking overrides into account,
|
||||
// rather encoding the original value the string was constructed with)
|
||||
const encoded = stringToU8a(super.toString());
|
||||
|
||||
return isBare
|
||||
? encoded
|
||||
: compactAddLength(encoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { bool, bool as Bool } from './Bool';
|
||||
export { CodecDate, CodecDate as Date } from './Date';
|
||||
export { Json } from './Json';
|
||||
export { Raw } from './Raw';
|
||||
export { CodecSet, CodecSet as Set } from './Set';
|
||||
export { Struct } from './Struct';
|
||||
export { Text } from './Text';
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/types-codec', version: '6.12.2-1' };
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Int } from '../base/Int';
|
||||
|
||||
/**
|
||||
* @name i128
|
||||
* @description
|
||||
* A 128-bit signed integer
|
||||
*/
|
||||
export class i128 extends Int.with(128) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __IntType = 'i128';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Int } from '../base/Int';
|
||||
|
||||
/**
|
||||
* @name i16
|
||||
* @description
|
||||
* A 16-bit signed integer
|
||||
*/
|
||||
export class i16 extends Int.with(16) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __IntType = 'i16';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Int } from '../base/Int';
|
||||
|
||||
/**
|
||||
* @name i256
|
||||
* @description
|
||||
* A 256-bit signed integer
|
||||
*/
|
||||
export class i256 extends Int.with(256) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __IntType = 'i256';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Int } from '../base/Int';
|
||||
|
||||
/**
|
||||
* @name i32
|
||||
* @description
|
||||
* A 32-bit signed integer
|
||||
*/
|
||||
export class i32 extends Int.with(32) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __IntType = 'i32';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Int } from '../base/Int';
|
||||
|
||||
/**
|
||||
* @name i64
|
||||
* @description
|
||||
* A 64-bit signed integer
|
||||
*/
|
||||
export class i64 extends Int.with(64) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __IntType = 'i64';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Int } from '../base/Int';
|
||||
|
||||
/**
|
||||
* @name i8
|
||||
* @description
|
||||
* An 8-bit signed integer
|
||||
*/
|
||||
export class i8 extends Int.with(8) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __IntType = 'i8';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { UInt } from '../base/UInt';
|
||||
|
||||
/**
|
||||
* @name u128
|
||||
* @description
|
||||
* A 128-bit unsigned integer
|
||||
*/
|
||||
export class u128 extends UInt.with(128) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __UIntType = 'u128';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { UInt } from '../base/UInt';
|
||||
|
||||
/**
|
||||
* @name u16
|
||||
* @description
|
||||
* A 16-bit unsigned integer
|
||||
*/
|
||||
export class u16 extends UInt.with(16) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __UIntType = 'u16';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { UInt } from '../base/UInt';
|
||||
|
||||
/**
|
||||
* @name u256
|
||||
* @description
|
||||
* A 256-bit unsigned integer
|
||||
*/
|
||||
export class u256 extends UInt.with(256) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __UIntType = 'u256';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { UInt } from '../base/UInt';
|
||||
|
||||
/**
|
||||
* @name u32
|
||||
* @description
|
||||
* A 32-bit unsigned integer
|
||||
*/
|
||||
export class u32 extends UInt.with(32) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __UIntType = 'u32';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { UInt } from '../base/UInt';
|
||||
|
||||
/**
|
||||
* @name u64
|
||||
* @description
|
||||
* A 64-bit unsigned integer
|
||||
*/
|
||||
export class u64 extends UInt.with(64) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __UIntType = 'u64';
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { UInt } from '../base/UInt';
|
||||
|
||||
/**
|
||||
* @name u8
|
||||
* @description
|
||||
* An 8-bit unsigned integer
|
||||
*/
|
||||
export class u8 extends UInt.with(8) {
|
||||
// NOTE without this, we cannot properly determine extensions
|
||||
public readonly __UIntType = 'u8';
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '../types';
|
||||
|
||||
import { u32 } from './U32';
|
||||
|
||||
/**
|
||||
* @name USize
|
||||
* @description
|
||||
* A System default unsigned number, typically used in RPC to report non-consensus
|
||||
* data. It is a wrapper for [[U32]] as a WASM default (as generated by Rust bindings).
|
||||
* It is not to be used, since it created consensus mismatches.
|
||||
*/
|
||||
export class usize extends u32 {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, value);
|
||||
|
||||
throw new Error('The `usize` type should not be used. Since it is platform-specific, it creates incompatibilities between native (generally u64) and WASM (always u32) code. Use one of the `u32` or `u64` types explicitly.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { i8, i8 as I8 } from './I8';
|
||||
export { i16, i16 as I16 } from './I16';
|
||||
export { i32, i32 as I32 } from './I32';
|
||||
export { i64, i64 as I64 } from './I64';
|
||||
export { i128, i128 as I128 } from './I128';
|
||||
export { i256, i256 as I256 } from './I256';
|
||||
export { u8, u8 as U8 } from './U8';
|
||||
export { u16, u16 as U16 } from './U16';
|
||||
export { u32, u32 as U32 } from './U32';
|
||||
export { u64, u64 as U64 } from './U64';
|
||||
export { u128, u128 as U128 } from './U128';
|
||||
export { u256, u256 as U256 } from './U256';
|
||||
export { usize, usize as USize } from './USize';
|
||||
@@ -0,0 +1,101 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { AnyJson } from './helpers';
|
||||
import type { IU8a } from './interfaces';
|
||||
import type { CodecRegistry } from './registry';
|
||||
|
||||
export type BareOpts = boolean | Record<string, boolean>;
|
||||
|
||||
/**
|
||||
* @name Codec
|
||||
* @description
|
||||
* The base Codec interface. All types implement the interface provided here. Additionally
|
||||
* implementors can add their own specific interfaces and helpers with getters and functions.
|
||||
* The Codec Base is however required for operating as an encoding/decoding layer
|
||||
*/
|
||||
export interface Codec {
|
||||
/**
|
||||
* @description The length of the value when encoded as a Uint8Array
|
||||
*/
|
||||
readonly encodedLength: number;
|
||||
|
||||
/**
|
||||
* @description Returns a hash of the value
|
||||
*/
|
||||
readonly hash: IU8a;
|
||||
|
||||
/**
|
||||
* @description The length of the initial encoded value (Only available when constructed from a Uint8Array)
|
||||
*/
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
/**
|
||||
* @description Checks if the value is an empty value
|
||||
*/
|
||||
readonly isEmpty: boolean;
|
||||
|
||||
/**
|
||||
* @description The registry associated with this object
|
||||
*/
|
||||
readonly registry: CodecRegistry;
|
||||
|
||||
/**
|
||||
* @description The block at which this value was retrieved/created (set to non-empty when retrieved from storage)
|
||||
*/
|
||||
createdAtHash?: IU8a;
|
||||
|
||||
/**
|
||||
* @description Compares the value of the input to see if there is a match
|
||||
*/
|
||||
eq (other?: unknown): boolean;
|
||||
|
||||
/**
|
||||
* @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation
|
||||
*/
|
||||
toHex (isLe?: boolean): HexString;
|
||||
|
||||
/**
|
||||
* @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
|
||||
*/
|
||||
toHuman (isExtended?: boolean): AnyJson;
|
||||
|
||||
/**
|
||||
* @description Converts the Object to JSON, typically used for RPC transfers
|
||||
*/
|
||||
toJSON (): AnyJson;
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
toRawType (): string;
|
||||
|
||||
/**
|
||||
* @description Returns the string representation of the value
|
||||
*/
|
||||
toString (): string;
|
||||
|
||||
/**
|
||||
* @description Encodes the value as a Uint8Array as per the SCALE specifications
|
||||
* @param isBare true when the value has none of the type-specific prefixes (internal)
|
||||
*/
|
||||
toU8a (isBare?: BareOpts): Uint8Array;
|
||||
}
|
||||
|
||||
export interface CodecClass<T = Codec> {
|
||||
/**
|
||||
* @description An internal fallback type (previous generation) if encoding fails
|
||||
*/
|
||||
readonly __fallbackType?: string;
|
||||
|
||||
// NOTE: We need the any[] here, unknown[] does not work as expected
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
new(registry: CodecRegistry, ...args: any[]): T;
|
||||
}
|
||||
|
||||
export type CodecClassDef<T = Codec> = Record<string, CodecClass<T>>;
|
||||
|
||||
export type CodecTo = 'toHex' | 'toJSON' | 'toString' | 'toU8a';
|
||||
|
||||
export type ArgsDef = Record<string, CodecClass | string>;
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { Codec } from './codec';
|
||||
|
||||
export type AnyJson = string | number | boolean | null | undefined | AnyJson[] | { [index: string]: AnyJson };
|
||||
|
||||
export type AnyFunction = (...args: any[]) => any;
|
||||
|
||||
export type AnyNumber = BN | bigint | Uint8Array | number | string;
|
||||
|
||||
export type AnyString = string | string;
|
||||
|
||||
export type AnyTuple = Codec[];
|
||||
|
||||
export type AnyU8a = Uint8Array | number[] | string;
|
||||
|
||||
export type UIntBitLength = 8 | 16 | 32 | 64 | 128 | 256;
|
||||
|
||||
// The 520 here is a weird one - it is explicitly for a [u8; 65] as found as a EcdsaSignature,
|
||||
// and 264 here is explicity for a [u8; 33] as found as EcdsaPublic key.
|
||||
// Likewise 160 is for [u8; 20], which is also a H160, i.e. an Ethereum address. Both these are
|
||||
// as a result of the Polkadot claims module. (Technically we don't need the 520 in here)
|
||||
export type U8aBitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 264 | 512 | 520 | 1024 | 2048;
|
||||
|
||||
export type AnyTupleValue = AnyU8a | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[];
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './codec';
|
||||
export * from './helpers';
|
||||
export * from './interfaces';
|
||||
export * from './registry';
|
||||
@@ -0,0 +1,87 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// import type { SignOptions } from '@polkadot/keyring/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { ArgsDef, Codec } from './codec';
|
||||
import type { AnyTuple } from './helpers';
|
||||
|
||||
export interface ICompact<T extends INumber = INumber> extends Codec {
|
||||
toBigInt (): bigint;
|
||||
toBn (): BN;
|
||||
toNumber (): number;
|
||||
unwrap (): T;
|
||||
}
|
||||
|
||||
export interface IEnum extends Codec {
|
||||
readonly defIndexes: number[];
|
||||
readonly defKeys: string[];
|
||||
readonly index: number;
|
||||
readonly isBasic: boolean
|
||||
readonly type: string;
|
||||
readonly value: Codec;
|
||||
|
||||
toNumber (): number;
|
||||
}
|
||||
|
||||
export interface IMap<K extends Codec = Codec, V extends Codec = Codec> extends Map<K, V>, Codec {}
|
||||
|
||||
export interface INumber extends Codec {
|
||||
bitLength (): number;
|
||||
toBigInt (): bigint;
|
||||
toBn (): BN;
|
||||
toNumber (): number;
|
||||
}
|
||||
|
||||
export interface IOption<T extends Codec = Codec> extends Codec {
|
||||
readonly isNone: boolean;
|
||||
readonly isSome: boolean;
|
||||
readonly value: Codec;
|
||||
|
||||
unwrap (): T;
|
||||
unwrapOr <O>(other: O): T | O;
|
||||
unwrapOrDefault (): T;
|
||||
}
|
||||
|
||||
export interface IResult<O extends Codec = Codec, E extends Codec = Codec> extends IEnum {
|
||||
readonly asErr: E;
|
||||
readonly asOk: O;
|
||||
readonly isErr: boolean;
|
||||
readonly isOk: boolean;
|
||||
}
|
||||
|
||||
export interface ISet<K = string> extends Set<K>, Codec {
|
||||
readonly strings: string[];
|
||||
}
|
||||
|
||||
export interface IStruct<K = string, V extends Codec = Codec> extends Map<K, V>, Codec {
|
||||
readonly defKeys: string[];
|
||||
|
||||
getAtIndex (index: number): Codec
|
||||
toArray (): Codec[];
|
||||
}
|
||||
|
||||
export type ITuple<T extends AnyTuple = Codec[]> = T & Codec;
|
||||
|
||||
export interface IU8a extends Uint8Array, Codec {
|
||||
readonly isAscii: boolean;
|
||||
readonly isUtf8: boolean
|
||||
|
||||
bitLength (): number;
|
||||
toHuman (isExtended?: boolean): any;
|
||||
toJSON (): any;
|
||||
toUtf8 (): string;
|
||||
}
|
||||
|
||||
export interface IVec<T extends Codec = Codec> extends Array<T>, Codec {
|
||||
toArray (): T[];
|
||||
}
|
||||
|
||||
export interface IMethod<A extends AnyTuple = AnyTuple> extends Codec {
|
||||
readonly args: A;
|
||||
readonly argsDef: ArgsDef;
|
||||
readonly callIndex: Uint8Array;
|
||||
readonly data: Uint8Array;
|
||||
|
||||
is: (tx: IMethod<AnyTuple>) => tx is IMethod<A>;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { Codec, CodecClass } from './codec';
|
||||
import type { ICompact, IEnum, IMap, IMethod, INumber, IOption, IResult, ISet, IStruct, ITuple, IU8a, IVec } from './interfaces';
|
||||
|
||||
export type OnlyCodec<K, T, Types> =
|
||||
K extends keyof Types
|
||||
? Types[K]
|
||||
: T extends ICompact | IEnum | IMap | IMethod | INumber | IOption | IResult | ISet | IStruct | ITuple | IU8a | IVec
|
||||
? T
|
||||
: T extends Codec
|
||||
? T
|
||||
: never;
|
||||
|
||||
export type RegistryTypes =
|
||||
Record<string, CodecClass | string | Record<string, string> |
|
||||
{ _enum: string[] | Record<string, number> | Record<string, string | null> } |
|
||||
{ _set: Record<string, number> }>;
|
||||
|
||||
export interface CodecCreateOptions {
|
||||
blockHash?: Uint8Array | string | null;
|
||||
isOptional?: boolean;
|
||||
isPedantic?: boolean;
|
||||
}
|
||||
|
||||
export interface CodecRegistry {
|
||||
readonly chainDecimals: number[];
|
||||
readonly chainSS58: number | undefined;
|
||||
readonly chainTokens: string[];
|
||||
// readonly knownTypes: RegisteredTypes;
|
||||
// readonly lookup: PortableCodecRegistry;
|
||||
// readonly metadata: MetadataLatest;
|
||||
// readonly unknownTypes: string[];
|
||||
// readonly signedExtensions: string[];
|
||||
|
||||
createdAtHash?: IU8a;
|
||||
|
||||
findMetaCall (callIndex: Uint8Array): unknown;
|
||||
findMetaError (errorIndex: Uint8Array | { error: BN, index: BN }): unknown;
|
||||
findMetaEvent (eventIndex: Uint8Array): CodecClass<any>;
|
||||
|
||||
isLookupType (value: string): boolean;
|
||||
createLookupType (lookupId: ICompact<INumber> | number): string;
|
||||
|
||||
// createClass <T, K extends string = string, Types = Record<K, Codec>> (type: K): CodecClass<OnlyCodec<T, K, Types>>;
|
||||
createClassUnsafe <T extends Codec = Codec, K extends string = string> (type: K): CodecClass<T>;
|
||||
// createType <T, K extends string = string> (type: K, ...params: unknown[]): OnlyCodec<T, K, Types>;
|
||||
createTypeUnsafe <T extends Codec = Codec, K extends string = string> (type: K, params: unknown[], options?: CodecCreateOptions): T;
|
||||
|
||||
// get <T extends Codec = Codec, K extends string = string, R = T> (name: K, withUnknown?: boolean, knownTypeDef?: TypeDef): CodecClass<R> | undefined;
|
||||
// getChainProperties (): ChainProperties | undefined;
|
||||
getClassName (clazz: CodecClass): string | undefined;
|
||||
// getDefinition (typeName: string): string | undefined;
|
||||
// getModuleInstances (specName: string, moduleName: string): string[] | undefined;
|
||||
|
||||
getOrThrow <T extends Codec = Codec, K extends string = string> (name: K, msg?: string): CodecClass<T>;
|
||||
getOrUnknown <T extends Codec = Codec, K extends string = string> (name: K): CodecClass<T>;
|
||||
|
||||
// setKnownTypes (types: RegisteredTypes): void;
|
||||
getSignedExtensionExtra (): Record<string, string>;
|
||||
getSignedExtensionTypes (): Record<string, string>;
|
||||
|
||||
hasClass (name: string): boolean;
|
||||
hasDef (name: string): boolean;
|
||||
hasType (name: string): boolean;
|
||||
hash (data: Uint8Array): IU8a;
|
||||
// init (): CodecRegistry;
|
||||
register (type: CodecClass | RegistryTypes): void;
|
||||
register (name: string, type: CodecClass): void;
|
||||
register (arg1: string | CodecClass | RegistryTypes, arg2?: CodecClass): void;
|
||||
// setChainProperties (properties?: ChainProperties): void;
|
||||
// setHasher (hasher?: IU8aer | null): void;
|
||||
// setLookup (lookup: PortableCodecRegistry): void;
|
||||
setMetadata (metadata: unknown, signedExtensions?: string[], userExtensions?: unknown): void;
|
||||
// setSignedExtensions (signedExtensions?: string[], userExtensions?: ExtDef): void;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isUndefined } from '@polkadot/util';
|
||||
|
||||
import { hasEq } from './util';
|
||||
|
||||
// NOTE These are used internally and when comparing objects, expects that
|
||||
// when the second is an Codec[] that the first has to be as well
|
||||
export function compareArray (a: unknown[], b?: unknown): boolean {
|
||||
if (Array.isArray(b)) {
|
||||
return (a.length === b.length) && isUndefined(
|
||||
a.find((v, index): boolean =>
|
||||
hasEq(v)
|
||||
? !v.eq(b[index])
|
||||
: v !== b[index]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isObject, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { hasEq } from './util';
|
||||
|
||||
function hasMismatch (a?: unknown, b?: unknown): boolean {
|
||||
return isUndefined(a) || (
|
||||
hasEq(a)
|
||||
? !a.eq(b)
|
||||
: a !== b
|
||||
);
|
||||
}
|
||||
|
||||
function notEntry (value: unknown): boolean {
|
||||
return !Array.isArray(value) || value.length !== 2;
|
||||
}
|
||||
|
||||
function compareMapArray (a: Map<unknown, unknown>, b: [unknown, unknown][]): boolean {
|
||||
// equal number of entries and each entry in the array should match
|
||||
return (a.size === b.length) && !b.some((e) =>
|
||||
notEntry(e) ||
|
||||
hasMismatch(a.get(e[0]), e[1])
|
||||
);
|
||||
}
|
||||
|
||||
// NOTE These are used internally and when comparing objects, expects that
|
||||
// when the second is an Map<string, Codec> that the first has to be as well
|
||||
export function compareMap (a: Map<unknown, unknown>, b?: unknown): boolean {
|
||||
if (Array.isArray(b)) {
|
||||
return compareMapArray(a, b as [unknown, unknown][]);
|
||||
} else if (b instanceof Map) {
|
||||
return compareMapArray(a, [...b.entries()]);
|
||||
} else if (isObject(b)) {
|
||||
return compareMapArray(a, Object.entries(b));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isObject } from '@polkadot/util';
|
||||
|
||||
function compareSetArray (a: Set<unknown>, b: any[]): boolean {
|
||||
// equal number of entries and each entry in the array should match
|
||||
return (a.size === b.length) && !b.some((e) => !a.has(e));
|
||||
}
|
||||
|
||||
// NOTE These are used internally and when comparing objects, expects that
|
||||
// when the second is an Set<string, Codec> that the first has to be as well
|
||||
export function compareSet (a: Set<unknown>, b?: unknown): boolean {
|
||||
if (Array.isArray(b)) {
|
||||
return compareSetArray(a, b);
|
||||
} else if (b instanceof Set) {
|
||||
return compareSetArray(a, [...b.values()]);
|
||||
} else if (isObject(b)) {
|
||||
return compareSetArray(a, Object.values(b));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { u8aToHex } from '@polkadot/util';
|
||||
|
||||
function formatFailure (error: Error, type: string | null, u8a: Uint8Array, key?: string): string {
|
||||
return `decodeU8a: failed at ${u8aToHex(u8a)}…${key ? ` on ${key}` : ''}${type ? `: ${type}` : ''}:: ${error.message}`;
|
||||
}
|
||||
|
||||
function getRawType (registry: CodecRegistry, Type: CodecClass): string | null {
|
||||
try {
|
||||
return new Type(registry).toRawType();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an u8a, and an array of Type constructors, decode the u8a against the
|
||||
* types, and return an array of decoded values.
|
||||
*
|
||||
* @param u8a - The u8a to decode.
|
||||
* @param result - The result array (will be returned with values pushed)
|
||||
* @param types - The array of CodecClass to decode the U8a against.
|
||||
*/
|
||||
export function decodeU8a <T extends Codec = Codec, E = T> (registry: CodecRegistry, u8a: Uint8Array, types: CodecClass[] | { [index: string]: CodecClass }, withZip?: boolean): [E[], number] {
|
||||
const [Types, keys]: [CodecClass[], string[]] = Array.isArray(types)
|
||||
? [types, []]
|
||||
: [Object.values(types), Object.keys(types)];
|
||||
|
||||
const result = new Array<E>(Types.length);
|
||||
let offset = 0;
|
||||
|
||||
for (let i = 0; i < Types.length; i++) {
|
||||
try {
|
||||
const value = new Types[i](registry, u8a.subarray(offset));
|
||||
|
||||
offset += value.initialU8aLength || value.encodedLength;
|
||||
result[i] = withZip
|
||||
? [keys[i], value] as unknown as E
|
||||
: value as unknown as E;
|
||||
} catch (error) {
|
||||
throw new Error(formatFailure(
|
||||
error as Error,
|
||||
getRawType(registry, Types[i]),
|
||||
u8a.subarray(offset, offset + 16),
|
||||
keys[i]
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return [result, offset];
|
||||
}
|
||||
|
||||
// Split from decodeU8a since this is specialized to 1 instance ... yes duplication, but
|
||||
// since we have to do less checks (and these are intensive anyway), much faster
|
||||
export function decodeU8aVec <T extends Codec = Codec> (registry: CodecRegistry, u8a: Uint8Array, start: number, Type: CodecClass<T>, count: number): [T[], number, number] {
|
||||
const result = new Array<T>(count);
|
||||
let offset = start;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
try {
|
||||
const value = new Type(registry, u8a.subarray(offset));
|
||||
|
||||
offset += value.initialU8aLength || value.encodedLength;
|
||||
result[i] = value;
|
||||
} catch (error) {
|
||||
throw new Error(formatFailure(
|
||||
error as Error,
|
||||
getRawType(registry, Type),
|
||||
u8a.subarray(offset, offset + 16)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return [result, offset, offset - start];
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { compareArray } from './compareArray';
|
||||
export { compareMap } from './compareMap';
|
||||
export { compareSet } from './compareSet';
|
||||
export { decodeU8a, decodeU8aVec } from './decodeU8a';
|
||||
export { mapToTypeMap } from './mapToTypeMap';
|
||||
export { typeToConstructor } from './typeToConstructor';
|
||||
export { sanitize } from './sanitize';
|
||||
export { sortAsc, sortSet, sortMap } from './sortValues';
|
||||
export { typesToMap } from './typesToMap';
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { typeToConstructor } from './typeToConstructor';
|
||||
|
||||
/**
|
||||
* @description takes an input map of the form `{ [string]: string | CodecClass }` and returns a map of `{ [string]: CodecClass }`
|
||||
*/
|
||||
export function mapToTypeMap (registry: CodecRegistry, input: Record<string, string | CodecClass>): Record<string, CodecClass> {
|
||||
const entries = Object.entries(input);
|
||||
const output: Record<string, CodecClass> = {};
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
output[entries[i][0]] = typeToConstructor(registry, entries[i][1]);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { alias, flattenSingleTuple, removeColons, removeExtensions } from './sanitize';
|
||||
|
||||
describe('sanitize', (): void => {
|
||||
describe('alias', (): void => {
|
||||
const fn = alias('String', 'Text');
|
||||
|
||||
it('replaces all occurrences for types', (): void => {
|
||||
expect(fn('(String,Address,MasterString,String)')).toEqual(
|
||||
'(Text,Address,MasterString,Text)'
|
||||
);
|
||||
});
|
||||
|
||||
it('replaces actual types, but leaves struct names', (): void => {
|
||||
expect(fn('{"system":"String","versionString":"String"}')).toEqual(
|
||||
'{"system":"Text","versionString":"Text"}'
|
||||
);
|
||||
});
|
||||
|
||||
it('handles the preceding correctly', (): void => {
|
||||
// NOTE This type doesn't make sense
|
||||
expect(fn('String String (String,[String;32],String)"String<String>')).toEqual(
|
||||
'Text Text (Text,[Text;32],Text)"Text<Text>'
|
||||
);
|
||||
});
|
||||
|
||||
it('handles embedded Vec/Tuples', (): void => {
|
||||
const ann = alias('Announcement', 'ProxyAnnouncement');
|
||||
|
||||
expect(ann('(Vec<Announcement>,BalanceOf)')).toEqual(
|
||||
'(Vec<ProxyAnnouncement>,BalanceOf)'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeColons', (): void => {
|
||||
const fn = removeColons();
|
||||
|
||||
it('removes preceding ::Text -> Text', (): void => {
|
||||
expect(fn('::Text')).toEqual('Text');
|
||||
});
|
||||
|
||||
it('removes middle voting::TallyType -> TallyType', (): void => {
|
||||
expect(fn('voting::TallyType')).toEqual('TallyType');
|
||||
});
|
||||
|
||||
it('removes on embedded values (one)', (): void => {
|
||||
expect(fn('(T::AccountId, SpanIndex)')).toEqual('(AccountId, SpanIndex)');
|
||||
});
|
||||
|
||||
it('removes on embedded values (all)', (): void => {
|
||||
expect(fn('(T::AccountId, slashing::SpanIndex)')).toEqual('(AccountId, SpanIndex)');
|
||||
});
|
||||
|
||||
it('keeps with allowNamespaces', (): void => {
|
||||
expect(fn('::slashing::SpanIndex', { allowNamespaces: true })).toEqual('slashing::SpanIndex');
|
||||
});
|
||||
});
|
||||
|
||||
describe('bounded', (): void => {
|
||||
const fn = removeExtensions('Bounded', true);
|
||||
|
||||
it('correctly cleans up bounded values', (): void => {
|
||||
expect(fn('BoundedVec<u32, 256>')).toEqual('Vec<u32>');
|
||||
});
|
||||
|
||||
it('correctly cleans up nested bounded values', (): void => {
|
||||
expect(
|
||||
fn('BoundedBTreeMap<BoundedVec<BoundedVec<u32, 1>, 2>, BoundedBTreeSet<u32, BoundedVec<u64, 3>, 4>, 5>')
|
||||
).toEqual('BTreeMap<Vec<Vec<u32>>,BTreeSet<u32,Vec<u64>>>');
|
||||
});
|
||||
|
||||
it('cleans up values with trailing commas', (): void => {
|
||||
expect(
|
||||
flattenSingleTuple()(
|
||||
fn('(BoundedVec<Announcement<T::AccountId, CallHashOf<T>, T::BlockNumber>, T::MaxPending,>,BalanceOf<T>,)')
|
||||
)
|
||||
).toEqual('(Vec<Announcement<T::AccountId,CallHashOf<T>,T::BlockNumber>>,BalanceOf<T>)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('weak', (): void => {
|
||||
const fn = removeExtensions('Weak', false);
|
||||
|
||||
it('correctly cleans up weak values', (): void => {
|
||||
expect(fn('WeakVec<u32>')).toEqual('Vec<u32>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
interface SanitizeOptions {
|
||||
allowNamespaces?: boolean;
|
||||
}
|
||||
|
||||
type Mapper = (value: string, options?: SanitizeOptions) => string;
|
||||
|
||||
const BOUNDED = ['BTreeMap', 'BTreeSet', 'HashMap', 'Vec'];
|
||||
const ALLOWED_BOXES = BOUNDED.concat(['Compact', 'DoNotConstruct', 'Int', 'Linkage', 'Range', 'RangeInclusive', 'Result', 'Option', 'UInt', 'WrapperOpaque']);
|
||||
const BOX_PRECEDING = ['<', '(', '[', '"', ',', ' ']; // start of vec, tuple, fixed array, part of struct def or in tuple
|
||||
|
||||
const mappings: Mapper[] = [
|
||||
// alias <T::InherentOfflineReport as InherentOfflineReport>::Inherent -> InherentOfflineReport
|
||||
alias('<T::InherentOfflineReport as InherentOfflineReport>::Inherent', 'InherentOfflineReport', false),
|
||||
alias('VecDeque<', 'Vec<', false),
|
||||
// <T::Balance as HasCompact>
|
||||
cleanupCompact(),
|
||||
// Change BoundedVec<Type, Size> to Vec<Type>
|
||||
removeExtensions('Bounded', true),
|
||||
// Change WeakVec<Type> to Vec<Type>
|
||||
removeExtensions('Weak', false),
|
||||
// Remove all the trait prefixes
|
||||
removeTraits(),
|
||||
// remove PairOf<T> -> (T, T)
|
||||
removePairOf(),
|
||||
// remove boxing, `Box<Proposal>` -> `Proposal`
|
||||
removeWrap('Box<'),
|
||||
// remove generics, `MisbehaviorReport<Hash, BlockNumber>` -> `MisbehaviorReport`
|
||||
removeGenerics(),
|
||||
// alias String -> Text (compat with jsonrpc methods)
|
||||
alias('String', 'Text'),
|
||||
// alias Vec<u8> -> Bytes
|
||||
alias('Vec<u8>', 'Bytes'),
|
||||
alias('&\\[u8\\]', 'Bytes'),
|
||||
alias("&'static\\[u8\\]", 'Bytes'),
|
||||
// alias RawAddress -> Address
|
||||
alias('RawAddress', 'Address'),
|
||||
// lookups, mapped to Address/AccountId as appropriate in runtime
|
||||
alias('Lookup::Source', 'LookupSource'),
|
||||
alias('Lookup::Target', 'LookupTarget'),
|
||||
// HACK duplication between contracts & primitives, however contracts prefixed with exec
|
||||
alias('exec::StorageKey', 'ContractStorageKey'),
|
||||
// flattens tuples with one value, `(AccountId)` -> `AccountId`
|
||||
flattenSingleTuple(),
|
||||
// converts ::Type to Type, <T as Trait<I>>::Proposal -> Proposal
|
||||
removeColons()
|
||||
];
|
||||
|
||||
// given a starting index, find the closing >
|
||||
export function findClosing (value: string, start: number): number {
|
||||
let depth = 0;
|
||||
|
||||
for (let index = start; index < value.length; index++) {
|
||||
if (value[index] === '>') {
|
||||
if (!depth) {
|
||||
return index;
|
||||
}
|
||||
|
||||
depth--;
|
||||
} else if (value[index] === '<') {
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`);
|
||||
}
|
||||
|
||||
export function alias (src: string, dest: string, withChecks = true): Mapper {
|
||||
const from = new RegExp(`(^${src}|${BOX_PRECEDING.map((box) => `\\${box}${src}`).join('|')})`, 'g');
|
||||
|
||||
const to = (src: string): string => {
|
||||
from.lastIndex = 0;
|
||||
|
||||
return withChecks && BOX_PRECEDING.includes(src[0])
|
||||
? `${src[0]}${dest}`
|
||||
: dest;
|
||||
};
|
||||
|
||||
return (value: string): string =>
|
||||
value.replace(from, to);
|
||||
}
|
||||
|
||||
export function cleanupCompact (): Mapper {
|
||||
return (value: string): string => {
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
if (value[index] === '<') {
|
||||
const end = findClosing(value, index + 1) - 14;
|
||||
|
||||
if (value.substr(end, 14) === ' as HasCompact') {
|
||||
value = `Compact<${value.substr(index + 1, end - index - 1)}>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
export function flattenSingleTuple (): Mapper {
|
||||
const from1 = /,\)/g;
|
||||
const from2 = /\(([^,]+)\)/;
|
||||
|
||||
return (value: string) => {
|
||||
from1.lastIndex = 0;
|
||||
|
||||
return value
|
||||
// tuples may have trailing commas, e.g. (u32, BlockNumber, )
|
||||
.replace(from1, ')')
|
||||
// change (u32) -> u32
|
||||
.replace(from2, '$1');
|
||||
};
|
||||
}
|
||||
|
||||
function replaceTagWith (value: string, matcher: string, replacer: (inner: string) => string): string {
|
||||
let index = -1;
|
||||
|
||||
while (true) {
|
||||
index = value.indexOf(matcher, index + 1);
|
||||
|
||||
if (index === -1) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const start = index + matcher.length;
|
||||
const end = findClosing(value, start);
|
||||
|
||||
value = `${value.substr(0, index)}${replacer(value.substr(start, end - start))}${value.substr(end + 1)}`;
|
||||
}
|
||||
}
|
||||
|
||||
// remove the Bounded* or Weak* wrappers
|
||||
export function removeExtensions (type: string, isSized: boolean): Mapper {
|
||||
return (value: string) =>
|
||||
BOUNDED.reduce((value, tag) =>
|
||||
replaceTagWith(value, `${type}${tag}<`, (inner: string): string => {
|
||||
const parts = inner
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s);
|
||||
|
||||
if (isSized) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return `${tag}<${parts.join(',')}>`;
|
||||
}), value
|
||||
);
|
||||
}
|
||||
|
||||
export function removeColons (): Mapper {
|
||||
return (value: string, { allowNamespaces }: SanitizeOptions = {}): string => {
|
||||
let index = 0;
|
||||
|
||||
while (index !== -1) {
|
||||
index = value.indexOf('::');
|
||||
|
||||
if (index === 0) {
|
||||
value = value.substr(2);
|
||||
} else if (index !== -1) {
|
||||
if (allowNamespaces) {
|
||||
return value;
|
||||
}
|
||||
|
||||
let start = index;
|
||||
|
||||
while (start !== -1 && !BOX_PRECEDING.includes(value[start])) {
|
||||
start--;
|
||||
}
|
||||
|
||||
value = `${value.substr(0, start + 1)}${value.substr(index + 2)}`;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
export function removeGenerics (): Mapper {
|
||||
return (value: string): string => {
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
if (value[index] === '<') {
|
||||
// check against the allowed wrappers, be it Vec<..>, Option<...> ...
|
||||
const box = ALLOWED_BOXES.find((box): boolean => {
|
||||
const start = index - box.length;
|
||||
|
||||
return (start >= 0 && value.substr(start, box.length) === box) && (
|
||||
// make sure it is stand-alone, i.e. don't catch ElectionResult<...> as Result<...>
|
||||
start === 0 || BOX_PRECEDING.includes(value[start - 1])
|
||||
);
|
||||
});
|
||||
|
||||
// we have not found anything, unwrap generic innards
|
||||
if (!box) {
|
||||
const end = findClosing(value, index + 1);
|
||||
|
||||
value = `${value.substr(0, index)}${value.substr(end + 1)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
// remove the PairOf wrappers
|
||||
export function removePairOf (): Mapper {
|
||||
const replacer = (inner: string) => `(${inner},${inner})`;
|
||||
|
||||
return (value: string) =>
|
||||
replaceTagWith(value, 'PairOf<', replacer);
|
||||
}
|
||||
|
||||
// remove the type traits
|
||||
export function removeTraits (): Mapper {
|
||||
const from1 = /\s/g;
|
||||
const from2 = /(T|Self)::/g;
|
||||
const from3 = /<(T|Self)asTrait>::/g;
|
||||
const from4 = /<Tas[a-z]+::Trait>::/g;
|
||||
const from5 = /<LookupasStaticLookup>/g;
|
||||
const from6 = /::Type/g;
|
||||
|
||||
return (value: string): string => {
|
||||
from1.lastIndex = 0;
|
||||
from2.lastIndex = 0;
|
||||
from3.lastIndex = 0;
|
||||
from4.lastIndex = 0;
|
||||
from5.lastIndex = 0;
|
||||
from6.lastIndex = 0;
|
||||
|
||||
return value
|
||||
// remove all whitespaces
|
||||
.replace(from1, '')
|
||||
// anything `T::<type>` to end up as `<type>`
|
||||
.replace(from2, '')
|
||||
// replace `<T as Trait>::` (whitespaces were removed above)
|
||||
.replace(from3, '')
|
||||
// replace `<T as something::Trait>::` (whitespaces were removed above)
|
||||
.replace(from4, '')
|
||||
// replace <Lookup as StaticLookup>
|
||||
.replace(from5, 'Lookup')
|
||||
// replace `<...>::Type`
|
||||
.replace(from6, '');
|
||||
};
|
||||
}
|
||||
|
||||
// remove wrapping values, i.e. Box<Proposal> -> Proposal
|
||||
export function removeWrap (check: string): Mapper {
|
||||
const replacer = (inner: string) => inner;
|
||||
|
||||
return (value: string) =>
|
||||
replaceTagWith(value, check, replacer);
|
||||
}
|
||||
|
||||
const sanitizeMap = new Map<string, string>();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export function sanitize (value: String | string, options?: SanitizeOptions): string {
|
||||
let result = value.toString();
|
||||
|
||||
if (!options) {
|
||||
const memoized = sanitizeMap.get(result);
|
||||
|
||||
if (memoized) {
|
||||
return memoized;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < mappings.length; i++) {
|
||||
result = mappings[i](result, options);
|
||||
}
|
||||
|
||||
result = result.trim();
|
||||
|
||||
if (!options) {
|
||||
sanitizeMap.set(value.toString(), result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { Enum } from '../base/Enum';
|
||||
import type { Codec } from '../types';
|
||||
|
||||
import { bnToBn, isBigInt, isBn, isFunction, isNumber, stringify } from '@polkadot/util';
|
||||
|
||||
type SortArg = Codec | Codec[] | number[] | BN | bigint | number | Uint8Array;
|
||||
|
||||
/** @internal **/
|
||||
function isArrayLike (arg: SortArg): arg is Uint8Array | Codec[] | number[] {
|
||||
return arg instanceof Uint8Array || Array.isArray(arg);
|
||||
}
|
||||
|
||||
/** @internal **/
|
||||
function isCodec (arg: SortArg): arg is Codec {
|
||||
return isFunction(arg && (arg as Codec).toU8a);
|
||||
}
|
||||
|
||||
/** @internal **/
|
||||
function isEnum (arg: SortArg): arg is Enum {
|
||||
return isCodec(arg) && isNumber((arg as Enum).index) && isCodec((arg as Enum).value);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function isNumberLike (arg: SortArg): arg is BN | bigint | number {
|
||||
return isNumber(arg) || isBn(arg) || isBigInt(arg);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function sortArray (a: Uint8Array | Codec[] | number[], b: Uint8Array | Codec[] | number[]): number {
|
||||
// Vec, Tuple, Bytes etc.
|
||||
let sortRes = 0;
|
||||
const minLen = Math.min(a.length, b.length);
|
||||
|
||||
for (let i = 0; i < minLen; ++i) {
|
||||
sortRes = sortAsc(a[i], b[i]);
|
||||
|
||||
if (sortRes !== 0) {
|
||||
return sortRes;
|
||||
}
|
||||
}
|
||||
|
||||
return a.length - b.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort keys/values of BTreeSet/BTreeMap in ascending order for encoding compatibility with Rust's BTreeSet/BTreeMap
|
||||
* (https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html)
|
||||
* (https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html)
|
||||
*/
|
||||
export function sortAsc<V extends SortArg = Codec> (a: V, b: V): number {
|
||||
if (isNumberLike(a) && isNumberLike(b)) {
|
||||
return bnToBn(a).cmp(bnToBn(b));
|
||||
} else if (a instanceof Map && b instanceof Map) {
|
||||
return sortAsc(Array.from(a.values()), Array.from(b.values()));
|
||||
} else if (isEnum(a) && isEnum(b)) {
|
||||
return sortAsc(a.index, b.index) || sortAsc(a.value, b.value);
|
||||
} else if (isArrayLike(a) && isArrayLike(b)) {
|
||||
return sortArray(a, b);
|
||||
} else if (isCodec(a) && isCodec(b)) {
|
||||
// Text, Bool etc.
|
||||
return sortAsc(a.toU8a(true), b.toU8a(true));
|
||||
}
|
||||
|
||||
throw new Error(`Attempting to sort unrecognized values: ${stringify(a)} (typeof ${typeof a}) <-> ${stringify(b)} (typeof ${typeof b})`);
|
||||
}
|
||||
|
||||
export function sortSet<V extends Codec = Codec> (set: Set<V>): Set<V> {
|
||||
return new Set(Array.from(set).sort(sortAsc));
|
||||
}
|
||||
|
||||
export function sortMap<K extends Codec = Codec, V extends Codec = Codec> (map: Map<K, V>): Map<K, V> {
|
||||
return new Map(Array.from(map.entries()).sort(([keyA], [keyB]) => sortAsc(keyA, keyB)));
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
import { isString } from '@polkadot/util';
|
||||
|
||||
export function typeToConstructor <T extends Codec = Codec> (registry: CodecRegistry, type: string | CodecClass<T>): CodecClass<T> {
|
||||
return (
|
||||
isString(type)
|
||||
? registry.createClassUnsafe(type)
|
||||
: type
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecClass, CodecRegistry } from '../types';
|
||||
|
||||
export function typesToMap (registry: CodecRegistry, Types: Record<string, CodecClass>): Record<string, string> {
|
||||
const entries = Object.entries(Types);
|
||||
const result: Record<string, string> = {};
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [key, Type] = entries[i];
|
||||
|
||||
result[key] = registry.getClassName(Type) || new Type(registry).toRawType();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/types-codec authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
export function hasEq (o: unknown): o is { eq: (other: unknown) => boolean } {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
return isFunction((o as any).eq);
|
||||
}
|
||||
Reference in New Issue
Block a user