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:
@@ -1,197 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, Codec, IVec, Registry } 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
protected constructor (registry: Registry, 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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyNumber, INumber, Registry } from '../types';
|
||||
import type { 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly encodedLength: number;
|
||||
|
||||
readonly #bitLength: UIntBitLength;
|
||||
|
||||
readonly #isSigned: boolean;
|
||||
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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.createClass('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
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Constructor, Registry } 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: Constructor<K> | string, valType: Constructor<V> | string): Constructor<CodecMap<K, V>> {
|
||||
return class extends BTreeMap<K, V> {
|
||||
constructor (registry: Registry, value?: Uint8Array | string | Map<any, any>) {
|
||||
super(registry, keyType, valType, value, 'BTreeMap');
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,7 @@ import { TypeRegistry } from '../create';
|
||||
import { I32, Text, U32 } from '../primitive';
|
||||
import { Constructor } from '../types';
|
||||
import { ITuple } from '../types/interfaces';
|
||||
import { Enum } from './Enum';
|
||||
import { BTreeSet, Struct, Tuple } from '.';
|
||||
import { BTreeSet, Enum, Struct, Tuple } from '.';
|
||||
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, Codec, Constructor, ISet, Registry } 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: Registry, ValClass: Constructor<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: Registry, ValClass: Constructor<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: Registry, valType: Constructor<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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #ValClass: Constructor<V>;
|
||||
|
||||
constructor (registry: Registry, valType: Constructor<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: Constructor<V> | string): Constructor<BTreeSet<V>> {
|
||||
return class extends BTreeSet<V> {
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, BareOpts, Codec, Registry } 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
protected readonly _raw: T;
|
||||
|
||||
protected constructor (registry: Registry, 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 (): CodecHash {
|
||||
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';
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { CodecDate } from '@polkadot/types-codec';
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
import { TypeRegistry } from '../create';
|
||||
import { U32 } from '../primitive';
|
||||
import { CodecDate } from './Date';
|
||||
import { Compact } from '.';
|
||||
|
||||
describe('Compact', (): void => {
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces';
|
||||
import type { AnyJson, AnyNumber, Constructor, ICompact, INumber, Registry } 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #Type: Constructor<T>;
|
||||
|
||||
readonly #raw: T;
|
||||
|
||||
constructor (registry: Registry, Type: Constructor<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: Constructor<T> | string): Constructor<Compact<T>> {
|
||||
return class extends Compact<T> {
|
||||
constructor (registry: Registry, value?: Compact<T> | AnyNumber) {
|
||||
super(registry, Type, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
public static decodeCompact<T extends INumber> (registry: Registry, Type: Constructor<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 (): CodecHash {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,11 @@
|
||||
|
||||
import type { CodecTo } from '../types';
|
||||
|
||||
import { CodecDate } from '@polkadot/types-codec';
|
||||
import { BN } from '@polkadot/util';
|
||||
|
||||
import { TypeRegistry } from '../create';
|
||||
import { U64 } from '../primitive';
|
||||
import { CodecDate } from './Date';
|
||||
|
||||
describe('Date', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyNumber, INumber, Registry } from '../types';
|
||||
import type { 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, Codec, Constructor, Registry } from '../types';
|
||||
|
||||
/**
|
||||
* @name DoNotConstruct
|
||||
* @description
|
||||
* An unknown type that fails on construction with the type info
|
||||
*/
|
||||
export class DoNotConstruct implements Codec {
|
||||
public readonly registry: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
#neverError: Error;
|
||||
|
||||
constructor (registry: Registry, typeName = 'DoNotConstruct') {
|
||||
this.registry = registry;
|
||||
this.#neverError = new Error(`DoNotConstruct: Cannot construct unknown type ${typeName}`);
|
||||
|
||||
throw this.#neverError;
|
||||
}
|
||||
|
||||
public static with (typeName?: string): Constructor {
|
||||
return class extends DoNotConstruct {
|
||||
constructor (registry: Registry) {
|
||||
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 (): CodecHash {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { u8aToHex } from '@polkadot/util';
|
||||
|
||||
@@ -131,7 +131,7 @@ describe('Enum', (): void => {
|
||||
class B extends Null { }
|
||||
class C extends Null { }
|
||||
class Test extends Enum {
|
||||
constructor (registry: Registry, value?: string, index?: number) {
|
||||
constructor (registry: CodecRegistry, value?: string, index?: number) {
|
||||
super(registry, {
|
||||
a: A,
|
||||
b: B,
|
||||
@@ -356,11 +356,11 @@ describe('Enum', (): void => {
|
||||
});
|
||||
|
||||
it('re-creates via rawType (types)', (): void => {
|
||||
const type = new Enum(registry, { A: Text, B: U32, C: U32 }).toRawType() as 'Raw';
|
||||
const value = registry.createType(type, { B: 123 }) as unknown as { isB: true, asB: U32 };
|
||||
const type = new Enum(registry, { A: Text, B: U32, C: U32 }).toRawType();
|
||||
const value = registry.createType(type, { B: 123 });
|
||||
|
||||
expect(value.isB).toEqual(true);
|
||||
expect(value.asB.toNumber()).toEqual(123);
|
||||
expect((value as unknown as Record<string, unknown>).isB).toEqual(true);
|
||||
expect((value as unknown as Record<string, U32>).asB.toNumber()).toEqual(123);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,400 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces';
|
||||
import type { AnyJson, Codec, Constructor, IEnum, Registry } from '../types';
|
||||
|
||||
import { assert, isHex, isNumber, isObject, isString, isU8a, isUndefined, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Null } from '../primitive/Null';
|
||||
import { mapToTypeMap, typesToMap } from './utils';
|
||||
|
||||
// export interface, this is used in Enum.with, so required as public by TS
|
||||
export interface EnumConstructor<T = Codec> {
|
||||
new(registry: Registry, value?: any, index?: number): T;
|
||||
}
|
||||
|
||||
interface EntryDef {
|
||||
Type: Constructor;
|
||||
index: number;
|
||||
}
|
||||
|
||||
type TypesDef = Record<string, EntryDef>;
|
||||
|
||||
interface Decoded {
|
||||
index: number;
|
||||
value: Codec;
|
||||
}
|
||||
|
||||
function isRustEnum (def: Record<string, string | Constructor> | Record<string, number>): def is Record<string, string | Constructor> {
|
||||
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: Registry, _def: Record<string, string | Constructor> | 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: Registry, 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: Registry, 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: Registry, 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly #def: TypesDef;
|
||||
|
||||
readonly #entryIndex: number;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #indexes: number[];
|
||||
|
||||
readonly #isBasic: boolean;
|
||||
|
||||
readonly #isIndexed: boolean;
|
||||
|
||||
readonly #raw: Codec;
|
||||
|
||||
constructor (registry: Registry, Types: Record<string, string | Constructor> | 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 | Constructor> | Record<string, number> | string[]): EnumConstructor<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: Registry, 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 (): CodecHash {
|
||||
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, Constructor>, [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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Constructor, Registry } 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: Constructor<K> | string, valType: Constructor<V> | string): Constructor<CodecMap<K, V>> {
|
||||
return class extends HashMap<K, V> {
|
||||
constructor (registry: Registry, value?: Uint8Array | string | Map<any, any>) {
|
||||
super(registry, keyType, valType, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, Constructor, Registry } from '../types';
|
||||
import type { UIntBitLength } from './types';
|
||||
|
||||
import { AbstractInt } from './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: Registry, value: AnyNumber = 0, bitLength?: UIntBitLength) {
|
||||
super(registry, value, bitLength, true);
|
||||
}
|
||||
|
||||
public static with (bitLength: UIntBitLength, typeName?: string): Constructor<Int> {
|
||||
return class extends Int {
|
||||
constructor (registry: Registry, value?: AnyNumber) {
|
||||
super(registry, value, bitLength);
|
||||
}
|
||||
|
||||
public override toRawType (): string {
|
||||
return typeName || super.toRawType();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, Codec, Registry } 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, Constructor, Registry } from '../types';
|
||||
|
||||
import { Option } from './Option';
|
||||
import { Struct } from './Struct';
|
||||
import { Tuple } from './Tuple';
|
||||
import { Vec } from './Vec';
|
||||
|
||||
type TypeWithValues = [Constructor, 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: Registry, Type: Constructor | 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: Constructor | string): Constructor<Linkage<O>> {
|
||||
return class extends Linkage<O> {
|
||||
constructor (registry: Registry, 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: Registry, [TypeKey, keys]: TypeWithValues, [TypeValue, values]: TypeWithValues) {
|
||||
super(registry, {
|
||||
Keys: Vec.with(TypeKey),
|
||||
Values: Vec.with(TypeValue)
|
||||
}, [keys, values]);
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, Codec, Constructor, IMap, Registry } from '../types';
|
||||
|
||||
import { compactFromU8a, compactToU8a, isHex, isObject, isU8a, logger, stringify, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from './AbstractArray';
|
||||
import { Enum } from './Enum';
|
||||
import { Struct } from './Struct';
|
||||
import { compareMap, decodeU8a, sortMap, typeToConstructor } from './utils';
|
||||
|
||||
const l = logger('Map');
|
||||
|
||||
/** @internal */
|
||||
function decodeMapFromU8a<K extends Codec, V extends Codec> (registry: Registry, KeyClass: Constructor<K>, ValClass: Constructor<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: Registry, KeyClass: Constructor<K>, ValClass: Constructor<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: Registry, keyType: Constructor<K> | string, valType: Constructor<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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly #KeyClass: Constructor<K>;
|
||||
|
||||
readonly #ValClass: Constructor<V>;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #type: string;
|
||||
|
||||
constructor (registry: Registry, keyType: Constructor<K> | string, valType: Constructor<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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces';
|
||||
import type { AnyJson, Codec, Constructor, IOption, Registry } from '../types';
|
||||
|
||||
import { assert, isCodec, isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Null } from '../primitive/Null';
|
||||
import { typeToConstructor } from './utils';
|
||||
|
||||
/** @internal */
|
||||
function decodeOption (registry: Registry, Type: Constructor, 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly #Type: Constructor<T>;
|
||||
|
||||
readonly #initialU8aLength?: number;
|
||||
|
||||
readonly #raw: T;
|
||||
|
||||
constructor (registry: Registry, typeName: Constructor<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: Constructor<O> | string): Constructor<Option<O>> {
|
||||
return class extends Option<O> {
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyTuple, Constructor, INumber, Registry } from '../types';
|
||||
|
||||
import { Tuple } from '../codec/Tuple';
|
||||
|
||||
type RangeType = 'Range' | 'RangeInclusive';
|
||||
|
||||
/**
|
||||
* @name Range
|
||||
* @description
|
||||
* Rust `Range<T>` representation
|
||||
*/
|
||||
export class Range<T extends INumber> extends Tuple {
|
||||
#rangeName: RangeType;
|
||||
|
||||
constructor (registry: Registry, Type: Constructor<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: Constructor<T> | string): Constructor<Range<T>> {
|
||||
return class extends Range<T> {
|
||||
constructor (registry: Registry, 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: Registry, type: Constructor<T> | string, value?: AnyTuple) {
|
||||
super(registry, type, value, 'RangeInclusive');
|
||||
}
|
||||
|
||||
public static override with <T extends INumber> (Types: Constructor<T> | string): Constructor<RangeInclusive<T>> {
|
||||
return class extends RangeInclusive<T> {
|
||||
constructor (registry: Registry, value?: AnyTuple) {
|
||||
super(registry, Types, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, AnyU8a, IU8a, Registry } 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 {
|
||||
public readonly registry: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Constructor, IResult, Registry } 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: Registry, Ok: Constructor<O> | string, Err: Constructor<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: Constructor<O> | string; Err: Constructor<E> | string }): Constructor<Result<O, E>> {
|
||||
return class extends Result<O, E> {
|
||||
constructor (registry: Registry, 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}>`;
|
||||
}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { Constructor, ISet, Registry } 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: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly #allowed: SetValues;
|
||||
|
||||
readonly #byteLength: number;
|
||||
|
||||
constructor (registry: Registry, 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): Constructor<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: Registry, 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 (): CodecHash {
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { CodecHash, Hash } from '../interfaces/runtime';
|
||||
import type { AnyJson, BareOpts, Codec, Constructor, ConstructorDef, IStruct, Registry } 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 | Constructor<T>>;
|
||||
|
||||
/** @internal */
|
||||
function decodeStructFromObject (registry: Registry, Types: ConstructorDef, 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> {
|
||||
public readonly registry: Registry;
|
||||
|
||||
public createdAtHash?: Hash;
|
||||
|
||||
readonly initialU8aLength?: number;
|
||||
|
||||
readonly #jsonMap: Map<keyof S, string>;
|
||||
|
||||
readonly #Types: ConstructorDef;
|
||||
|
||||
constructor (registry: Registry, 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>): Constructor<Struct<S>> {
|
||||
const keys = Object.keys(Types);
|
||||
|
||||
return class extends Struct<S> {
|
||||
constructor (registry: Registry, 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 (): CodecHash {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyTupleValue } from '@polkadot/types-codec/types';
|
||||
import type { VoteThreshold } from '../interfaces/elections';
|
||||
import type { BlockNumber } from '../interfaces/runtime';
|
||||
import type { CodecTo } from '../types';
|
||||
import type { AnyTupleValue } from './Tuple';
|
||||
|
||||
import rpcMetadata from '@polkadot/types-support/metadata/static-substrate';
|
||||
|
||||
import { TypeRegistry } from '../create';
|
||||
import { Metadata } from '../metadata';
|
||||
import { Text, U32, u128 as U128 } from '../primitive';
|
||||
import { Text, U32, U128 } from '../primitive';
|
||||
import { Tuple } from '.';
|
||||
|
||||
describe('Tuple', (): void => {
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, AnyString, AnyU8a, Codec, Constructor, ITuple, Registry } from '../types';
|
||||
|
||||
import { isFunction, isHex, isString, isU8a, stringify, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from './AbstractArray';
|
||||
import { decodeU8a, mapToTypeMap, typeToConstructor } from './utils';
|
||||
|
||||
export type AnyTupleValue = AnyU8a | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[];
|
||||
|
||||
type TupleConstructors = Constructor[] | {
|
||||
[index: string]: Constructor;
|
||||
};
|
||||
|
||||
type TupleType = (Constructor | string);
|
||||
|
||||
type TupleTypes = TupleType[] | {
|
||||
[index: string]: Constructor | string;
|
||||
};
|
||||
|
||||
/** @internal */
|
||||
function decodeTuple (registry: Registry, Classes: TupleConstructors, value?: AnyTupleValue): [Codec[], number] {
|
||||
if (isU8a(value) || isHex(value)) {
|
||||
return decodeU8a(registry, u8aToU8a(value), Classes);
|
||||
}
|
||||
|
||||
const Types: Constructor[] = 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: TupleConstructors;
|
||||
|
||||
constructor (registry: Registry, 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): Constructor<Tuple> {
|
||||
return class extends Tuple {
|
||||
constructor (registry: Registry, 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);
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyU8a, Constructor, Registry } from '../types';
|
||||
import type { U8aBitLength } from './types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Raw } from './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: Registry, value: AnyU8a = new Uint8Array(), bitLength: U8aBitLength = 256) {
|
||||
const [u8a, decodedLength] = decodeU8aFixed(value, bitLength);
|
||||
|
||||
super(registry, u8a, decodedLength);
|
||||
}
|
||||
|
||||
public static with (bitLength: U8aBitLength, typeName?: string): Constructor<U8aFixed> {
|
||||
return class extends U8aFixed {
|
||||
constructor (registry: Registry, 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}]`;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import BNOrig from 'bn.js';
|
||||
|
||||
import { BN, BN_TWO, isBn } from '@polkadot/util';
|
||||
|
||||
import { TypeRegistry } from '../create';
|
||||
@@ -28,7 +26,7 @@ describe('UInt', (): void => {
|
||||
const test = new UInt(registry, 16);
|
||||
|
||||
expect(isBn(test)).toBe(true);
|
||||
expect(BNOrig.isBN(test)).toBe(true);
|
||||
expect(BN.isBN(test)).toBe(true);
|
||||
expect(test instanceof BN).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, Constructor, Registry } from '../types';
|
||||
import type { UIntBitLength } from './types';
|
||||
|
||||
import { AbstractInt } from './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): Constructor<UInt> {
|
||||
return class extends UInt {
|
||||
constructor (registry: Registry, value?: AnyNumber) {
|
||||
super(registry, value, bitLength);
|
||||
}
|
||||
|
||||
public override toRawType (): string {
|
||||
return typeName || super.toRawType();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, Constructor, Registry } from '../types';
|
||||
|
||||
import { assert, compactFromU8a, logger, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from './AbstractArray';
|
||||
import { decodeU8aVec, typeToConstructor } from './utils';
|
||||
|
||||
const MAX_LENGTH = 64 * 1024;
|
||||
|
||||
const l = logger('Vec');
|
||||
|
||||
export function decodeVec<T extends Codec> (registry: Registry, Type: Constructor<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: Constructor<T>;
|
||||
|
||||
constructor (registry: Registry, Type: Constructor<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: Constructor<O> | string): Constructor<Vec<O>> {
|
||||
return class extends Vec<O> {
|
||||
constructor (registry: Registry, 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()}>`;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec } from '../types';
|
||||
|
||||
import { AbstractArray } from './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>';
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Codec, Constructor, Registry } from '../types';
|
||||
|
||||
import { assert, isU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import { AbstractArray } from './AbstractArray';
|
||||
import { decodeU8aVec, typeToConstructor } from './utils';
|
||||
import { decodeVec } from './Vec';
|
||||
|
||||
/** @internal */
|
||||
function decodeVecFixed<T extends Codec> (registry: Registry, value: Uint8Array | HexString | unknown[], Type: Constructor<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: Constructor<T>;
|
||||
|
||||
constructor (registry: Registry, Type: Constructor<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: Constructor<O> | string, length: number): Constructor<VecFixed<O>> {
|
||||
return class extends VecFixed<O> {
|
||||
constructor (registry: Registry, 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}]`;
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Constructor, Registry } from '../types';
|
||||
|
||||
import { compactAddLength, compactStripLength, isU8a } from '@polkadot/util';
|
||||
|
||||
import { Base } from './Base';
|
||||
import { typeToConstructor } from './utils';
|
||||
|
||||
function decodeRaw<T extends Codec> (registry: Registry, Type: Constructor<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: Registry, Type: Constructor<T> | string, value?: unknown) {
|
||||
super(registry, decodeRaw(registry, Type, value));
|
||||
}
|
||||
|
||||
public static with<T extends Codec> (Type: Constructor<T> | string): Constructor<WrapperOpaque<T>> {
|
||||
return class extends WrapperOpaque<T> {
|
||||
constructor (registry: Registry, 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;
|
||||
}
|
||||
}
|
||||
@@ -6,28 +6,4 @@
|
||||
// expand with slight care (for instance, Length is really only used internally to
|
||||
// others, so there _should_ not be need for direct use)
|
||||
|
||||
// These are the base codec types, generally used for construction
|
||||
export { BTreeMap } from './BTreeMap';
|
||||
export { BTreeSet } from './BTreeSet';
|
||||
export { Compact } from './Compact';
|
||||
// export { CodecDate, CodecDate as Date } from './Date';
|
||||
export { DoNotConstruct } from './DoNotConstruct';
|
||||
export { Enum } from './Enum';
|
||||
export { HashMap } from './HashMap';
|
||||
export { Int } from './Int';
|
||||
export { Json } from './Json';
|
||||
export { Linkage } from './Linkage';
|
||||
export { CodecMap, CodecMap as Map } from './Map';
|
||||
export { Option } from './Option';
|
||||
export { Range, RangeInclusive } from './Range';
|
||||
export { Raw } from './Raw';
|
||||
export { Result } from './Result';
|
||||
export { CodecSet, CodecSet as Set } from './Set';
|
||||
export { Struct } from './Struct';
|
||||
export { Tuple } from './Tuple';
|
||||
export { UInt } from './UInt';
|
||||
export { U8aFixed } from './U8aFixed';
|
||||
export { Vec } from './Vec';
|
||||
// export { VecAny } from './VecAny';
|
||||
export { VecFixed } from './VecFixed';
|
||||
export { WrapperOpaque } from './WrapperOpaque';
|
||||
export { BTreeMap, BTreeSet, Compact, DoNotConstruct, Enum, HashMap, Int, Json, Linkage, CodecMap, Map, Option, Range, RangeInclusive, Raw, Result, CodecSet, Set, Struct, Tuple, UInt, U8aFixed, Vec, VecFixed, WrapperOpaque } from '@polkadot/types-codec';
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
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 { U8aBitLength, UIntBitLength } from '@polkadot/types-codec/types';
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeRegistry } from '../../create';
|
||||
import { U32 } from '../../primitive';
|
||||
import { compareArray } from '.';
|
||||
|
||||
describe('compareArray', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const a = [new U32(registry, 123), new U32(registry, 456), new U32(registry, 789)];
|
||||
|
||||
it('returns false when second param is a non-array', (): void => {
|
||||
expect(
|
||||
compareArray(a, 123)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('compares array of codec agains primitive', (): void => {
|
||||
expect(
|
||||
compareArray(a, [123, 456, 789])
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('compares array of codec agains codec', (): void => {
|
||||
expect(
|
||||
compareArray(a, [new U32(registry, 123), new U32(registry, 456), new U32(registry, 789)])
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('compares primitive against primitive', (): void => {
|
||||
expect(
|
||||
compareArray(
|
||||
[123, 456], [123, 456]
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when lengths are not matching', (): void => {
|
||||
expect(
|
||||
compareArray(a, [123])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when value mismatches', (): void => {
|
||||
expect(
|
||||
compareArray(a, [123, 456, 999])
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types 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;
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec } from '../../types';
|
||||
|
||||
import { TypeRegistry } from '../../create';
|
||||
import { U32 } from '../../primitive';
|
||||
import { compareMap } from '.';
|
||||
|
||||
describe('compareMap', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
const a = new Map<string, Codec>([
|
||||
['decimals', new U32(registry, 15)],
|
||||
['missing', new U32(registry, 10)],
|
||||
['foobar', new U32(registry, 5)]
|
||||
]);
|
||||
const b = new Map<string, any>([
|
||||
['decimals', 15],
|
||||
['missing', 10],
|
||||
['foobar', 5]
|
||||
]);
|
||||
const c = new Map<string, Codec>([
|
||||
['decimals', new U32(registry, 15)],
|
||||
['missing', new U32(registry, 10)],
|
||||
['foobar', new U32(registry, 5)]
|
||||
]);
|
||||
|
||||
it('compares Map<string, Codec> against Object', (): void => {
|
||||
expect(
|
||||
compareMap(a, {
|
||||
decimals: 15,
|
||||
foobar: 5,
|
||||
missing: 10
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('compares Map<string, any> against entries array', (): void => {
|
||||
expect(
|
||||
compareMap(b, [
|
||||
['missing', 10], ['decimals', 15], ['foobar', 5]
|
||||
])
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('compares between 2 maps', (): void => {
|
||||
expect(compareMap(a, b)).toBe(true);
|
||||
});
|
||||
|
||||
it('compares between 2 maps (both codec)', (): void => {
|
||||
expect(compareMap(a, c)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when second param is a non-map, non-array, non-object', (): void => {
|
||||
expect(
|
||||
compareMap(a, 123)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when second param is a array with non-entries', (): void => {
|
||||
expect(
|
||||
compareMap(a, [123, 456, 789])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when second param is a array with non-entries (only key)', (): void => {
|
||||
expect(
|
||||
compareMap(a, [[123], [456], [789]])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when properties are missing', (): void => {
|
||||
expect(
|
||||
compareMap(a, [['decimals', 15], ['wrong', 10], ['foobar', 5]])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when lengths do not match', (): void => {
|
||||
expect(
|
||||
compareMap(a, [['decimals', 15]])
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types 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;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types 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;
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Constructor, Registry } 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: Registry, Type: Constructor): 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 Constructor to decode the U8a against.
|
||||
*/
|
||||
export function decodeU8a <T extends Codec = Codec, E = T> (registry: Registry, u8a: Uint8Array, types: Constructor[] | { [index: string]: Constructor }, withZip?: boolean): [E[], number] {
|
||||
const [Types, keys]: [Constructor[], 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: Registry, u8a: Uint8Array, start: number, Type: Constructor<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];
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types 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 { sortAsc, sortSet, sortMap } from './sortValues';
|
||||
export { typesToMap } from './typesToMap';
|
||||
@@ -1,20 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Constructor, Registry } from '../../types';
|
||||
|
||||
import { typeToConstructor } from './typeToConstructor';
|
||||
|
||||
/**
|
||||
* @description takes an input map of the form `{ [string]: string | Constructor }` and returns a map of `{ [string]: Constructor }`
|
||||
*/
|
||||
export function mapToTypeMap (registry: Registry, input: Record<string, string | Constructor>): Record<string, Constructor> {
|
||||
const entries = Object.entries(input);
|
||||
const output: Record<string, Constructor> = {};
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
output[entries[i][0]] = typeToConstructor(registry, entries[i][1]);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { Codec } from '../../types';
|
||||
import type { Enum } from '../Enum';
|
||||
|
||||
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)));
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Constructor, Registry } from '../../types';
|
||||
|
||||
import { isString } from '@polkadot/util';
|
||||
|
||||
export function typeToConstructor <T extends Codec = Codec> (registry: Registry, type: string | Constructor<T>): Constructor<T> {
|
||||
return (
|
||||
isString(type)
|
||||
? registry.createClass(type)
|
||||
: type
|
||||
) as Constructor<T>;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Constructor, Registry } from '../../types';
|
||||
|
||||
export function typesToMap (registry: Registry, Types: Record<string, Constructor>): 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;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types 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);
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { U8aBitLength, UIntBitLength } from '../codec/types';
|
||||
import type { Codec, Constructor, DetectConstructor, Registry } from '../types';
|
||||
import type { Codec, CodecClass, CodecRegistry, U8aBitLength, UIntBitLength } from '@polkadot/types-codec/types';
|
||||
import type { DetectCodec, LookupRegistry } from '../types';
|
||||
import type { TypeDef } from './types';
|
||||
|
||||
import { BTreeMap, BTreeSet, Bytes, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Null, Option, Range, RangeInclusive, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed, WrapperOpaque } from '@polkadot/types-codec';
|
||||
import { assert, isNumber, stringify } from '@polkadot/util';
|
||||
|
||||
import { BTreeMap, BTreeSet, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Option, Range, RangeInclusive, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed, WrapperOpaque } from '../codec';
|
||||
import { Bytes, Null } from '../primitive';
|
||||
import { getTypeDef } from './getTypeDef';
|
||||
import { TypeDefInfo } from './types';
|
||||
|
||||
@@ -32,7 +31,7 @@ function getSubType (value: TypeDef): string {
|
||||
return getTypeDefType(getSubDef(value));
|
||||
}
|
||||
|
||||
// create a maps of type string constructors from the input
|
||||
// create a maps of type string CodecClasss from the input
|
||||
function getTypeClassMap (value: TypeDef): Record<string, string> {
|
||||
const subs = getSubDefArray(value);
|
||||
const map: Record<string, string> = {};
|
||||
@@ -44,41 +43,41 @@ function getTypeClassMap (value: TypeDef): Record<string, string> {
|
||||
return map;
|
||||
}
|
||||
|
||||
// create an array of type string constructors from the input
|
||||
// create an array of type string CodecClasss from the input
|
||||
function getTypeClassArray (value: TypeDef): string[] {
|
||||
return getSubDefArray(value).map(getTypeDefType);
|
||||
}
|
||||
|
||||
function createInt (Clazz: typeof Int | typeof UInt, { displayName, length }: TypeDef): Constructor<Codec> {
|
||||
function createInt (Clazz: typeof Int | typeof UInt, { displayName, length }: TypeDef): CodecClass<Codec> {
|
||||
assert(isNumber(length), () => `Expected bitLength information for ${displayName || Clazz.constructor.name}<bitLength>`);
|
||||
|
||||
return Clazz.with(length as UIntBitLength, displayName);
|
||||
}
|
||||
|
||||
function createHashMap (Clazz: typeof BTreeMap | typeof HashMap, value: TypeDef): Constructor<Codec> {
|
||||
function createHashMap (Clazz: typeof BTreeMap | typeof HashMap, value: TypeDef): CodecClass<Codec> {
|
||||
const [keyType, valueType] = getTypeClassArray(value);
|
||||
|
||||
return Clazz.with(keyType, valueType);
|
||||
}
|
||||
|
||||
function createWithSub (Clazz: { with: (t: string) => Constructor<Codec> }, value: TypeDef): Constructor<Codec> {
|
||||
function createWithSub (Clazz: { with: (t: string) => CodecClass<Codec> }, value: TypeDef): CodecClass<Codec> {
|
||||
return Clazz.with(getSubType(value));
|
||||
}
|
||||
|
||||
const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => Constructor<Codec>> = {
|
||||
[TypeDefInfo.BTreeMap]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
const infoMapping: Record<TypeDefInfo, (registry: CodecRegistry, value: TypeDef) => CodecClass<Codec>> = {
|
||||
[TypeDefInfo.BTreeMap]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createHashMap(BTreeMap, value),
|
||||
|
||||
[TypeDefInfo.BTreeSet]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.BTreeSet]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(BTreeSet, value),
|
||||
|
||||
[TypeDefInfo.Compact]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Compact]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(Compact, value),
|
||||
|
||||
[TypeDefInfo.DoNotConstruct]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.DoNotConstruct]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
DoNotConstruct.with(value.displayName || value.type),
|
||||
|
||||
[TypeDefInfo.Enum]: (registry: Registry, value: TypeDef): Constructor<Codec> => {
|
||||
[TypeDefInfo.Enum]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> => {
|
||||
const subs = getSubDefArray(value);
|
||||
|
||||
return Enum.with(
|
||||
@@ -92,14 +91,14 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
|
||||
);
|
||||
},
|
||||
|
||||
[TypeDefInfo.HashMap]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.HashMap]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createHashMap(HashMap, value),
|
||||
|
||||
[TypeDefInfo.Int]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Int]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createInt(Int, value),
|
||||
|
||||
// We have circular deps between Linkage & Struct
|
||||
[TypeDefInfo.Linkage]: (registry: Registry, value: TypeDef): Constructor<Codec> => {
|
||||
[TypeDefInfo.Linkage]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> => {
|
||||
const type = `Option<${getSubType(value)}>`;
|
||||
// eslint-disable-next-line sort-keys
|
||||
const Clazz = Struct.with({ previous: type, next: type } as any);
|
||||
@@ -114,26 +113,26 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
|
||||
},
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Null]: (registry: Registry, _: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Null]: (registry: CodecRegistry, _: TypeDef): CodecClass<Codec> =>
|
||||
Null,
|
||||
|
||||
[TypeDefInfo.Option]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Option]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(Option, value),
|
||||
|
||||
[TypeDefInfo.Plain]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Plain]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
registry.getOrUnknown(value.type),
|
||||
|
||||
[TypeDefInfo.Range]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Range]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
(value.type.includes('RangeInclusive') ? RangeInclusive : Range).with(getSubType(value)),
|
||||
|
||||
[TypeDefInfo.Result]: (registry: Registry, value: TypeDef): Constructor<Codec> => {
|
||||
[TypeDefInfo.Result]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> => {
|
||||
const [Ok, Err] = getTypeClassArray(value);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
return Result.with({ Err, Ok });
|
||||
},
|
||||
|
||||
[TypeDefInfo.Set]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Set]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
CodecSet.with(
|
||||
getSubDefArray(value).reduce<Record<string, number>>((result, { index, name }) => {
|
||||
result[name as string] = index as number;
|
||||
@@ -143,19 +142,19 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
|
||||
value.length
|
||||
),
|
||||
|
||||
[TypeDefInfo.Si]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
getTypeClass(registry, registry.lookup.getTypeDef(value.type)),
|
||||
[TypeDefInfo.Si]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
getTypeClass(registry, (registry as LookupRegistry).lookup.getTypeDef(value.type)),
|
||||
|
||||
[TypeDefInfo.Struct]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Struct]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
Struct.with(getTypeClassMap(value), value.alias),
|
||||
|
||||
[TypeDefInfo.Tuple]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.Tuple]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
Tuple.with(getTypeClassArray(value)),
|
||||
|
||||
[TypeDefInfo.UInt]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.UInt]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createInt(UInt, value),
|
||||
|
||||
[TypeDefInfo.Vec]: (registry: Registry, { sub }: TypeDef): Constructor<Codec> => {
|
||||
[TypeDefInfo.Vec]: (registry: CodecRegistry, { sub }: TypeDef): CodecClass<Codec> => {
|
||||
assert(sub && !Array.isArray(sub), 'Expected type information for vector');
|
||||
|
||||
return (
|
||||
@@ -165,7 +164,7 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
|
||||
);
|
||||
},
|
||||
|
||||
[TypeDefInfo.VecFixed]: (registry: Registry, { displayName, length, sub }: TypeDef): Constructor<Codec> => {
|
||||
[TypeDefInfo.VecFixed]: (registry: CodecRegistry, { displayName, length, sub }: TypeDef): CodecClass<Codec> => {
|
||||
assert(sub && isNumber(length) && !Array.isArray(sub), 'Expected length & type information for fixed vector');
|
||||
|
||||
return (
|
||||
@@ -175,11 +174,11 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
|
||||
);
|
||||
},
|
||||
|
||||
[TypeDefInfo.WrapperOpaque]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
|
||||
[TypeDefInfo.WrapperOpaque]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(WrapperOpaque, value)
|
||||
};
|
||||
|
||||
export function constructTypeClass<T extends Codec = Codec> (registry: Registry, typeDef: TypeDef): Constructor<T> {
|
||||
export function constructTypeClass<T extends Codec = Codec> (registry: CodecRegistry, typeDef: TypeDef): CodecClass<T> {
|
||||
try {
|
||||
const Type = infoMapping[typeDef.info](registry, typeDef);
|
||||
|
||||
@@ -192,22 +191,26 @@ export function constructTypeClass<T extends Codec = Codec> (registry: Registry,
|
||||
Type.__fallbackType = typeDef.fallbackType;
|
||||
}
|
||||
|
||||
return Type as Constructor<T>;
|
||||
return Type as CodecClass<T>;
|
||||
} catch (error) {
|
||||
throw new Error(`Unable to construct class from ${stringify(typeDef)}: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the type Class for construction
|
||||
export function getTypeClass<T extends Codec = Codec> (registry: Registry, typeDef: TypeDef): Constructor<T> {
|
||||
return registry.get(typeDef.type, false, typeDef) as Constructor<T>;
|
||||
export function getTypeClass<T extends Codec = Codec> (registry: CodecRegistry, typeDef: TypeDef): CodecClass<T> {
|
||||
return (registry as LookupRegistry).getUnsafe(typeDef.type, false, typeDef) as CodecClass<T>;
|
||||
}
|
||||
|
||||
export function createClass<T extends Codec = Codec, K extends string = string> (registry: Registry, type: K): DetectConstructor<T, K> {
|
||||
export function createClass<T extends Codec = Codec, K extends string = string> (registry: CodecRegistry, type: K): CodecClass<DetectCodec<T, K>> {
|
||||
return createClassUnsafe(registry, type);
|
||||
}
|
||||
|
||||
export function createClassUnsafe<T extends Codec = Codec, K extends string = string> (registry: CodecRegistry, type: K): CodecClass<T> {
|
||||
return getTypeClass(
|
||||
registry,
|
||||
registry.isLookupType(type)
|
||||
? registry.lookup.getTypeDef(type)
|
||||
? (registry as LookupRegistry).lookup.getTypeDef(type)
|
||||
: getTypeDef(type)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { CodecSet, Int } from '../codec';
|
||||
import { CodecSet, Int } from '@polkadot/types-codec';
|
||||
|
||||
import { createClass, TypeRegistry } from '.';
|
||||
|
||||
describe('createType', (): void => {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Bytes } from '../primitive/Bytes';
|
||||
import type { Codec, Constructor, DetectCodec, Registry } from '../types';
|
||||
import type { Codec, CodecClass, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { DetectCodec } from '../types';
|
||||
import type { CreateOptions } from './types';
|
||||
|
||||
import { Bytes, Option } from '@polkadot/types-codec';
|
||||
import { assert, isHex, isU8a, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Option } from '../codec/Option';
|
||||
import { createClass } from './createClass';
|
||||
|
||||
// With isPedantic, actually check that the encoding matches that supplied. This
|
||||
@@ -45,7 +45,7 @@ function checkPedantic (created: Codec, [value]: unknown[], isPedantic = false):
|
||||
|
||||
// Initializes a type with a value. This also checks for fallbacks and in the cases
|
||||
// where isPedantic is specified (storage decoding), also check the format/structure
|
||||
function initType<T extends Codec> (registry: Registry, Type: Constructor, params: unknown[] = [], { blockHash, isOptional, isPedantic }: CreateOptions = {}): T {
|
||||
function initType<T extends Codec> (registry: CodecRegistry, Type: CodecClass, params: unknown[] = [], { blockHash, isOptional, isPedantic }: CreateOptions = {}): T {
|
||||
const created = new (isOptional ? Option.with(Type) : Type)(registry, ...params);
|
||||
|
||||
checkPedantic(created, params, isPedantic);
|
||||
@@ -54,15 +54,14 @@ function initType<T extends Codec> (registry: Registry, Type: Constructor, param
|
||||
created.createdAtHash = createType(registry, 'Hash', blockHash);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return created as any;
|
||||
return created as T;
|
||||
}
|
||||
|
||||
// An unsafe version of the `createType` below. It's unsafe because the `type`
|
||||
// argument here can be any string, which, when it cannot parse, will yield a
|
||||
// runtime error.
|
||||
export function createTypeUnsafe<T extends Codec = Codec, K extends string = string> (registry: Registry, type: K, params: unknown[] = [], options: CreateOptions = {}): DetectCodec<T, K> {
|
||||
let Clazz: Constructor | null = null;
|
||||
export function createTypeUnsafe<T extends Codec = Codec, K extends string = string> (registry: CodecRegistry, type: K, params: unknown[] = [], options: CreateOptions = {}): DetectCodec<T, K> {
|
||||
let Clazz: CodecClass | null = null;
|
||||
let firstError: Error | null = null;
|
||||
|
||||
try {
|
||||
@@ -92,6 +91,6 @@ export function createTypeUnsafe<T extends Codec = Codec, K extends string = str
|
||||
* instance from
|
||||
* @param params - The value to instantiate the type with
|
||||
*/
|
||||
export function createType<T extends Codec = Codec, K extends string = string> (registry: Registry, type: K, ...params: unknown[]): DetectCodec<T, K> {
|
||||
export function createType<T extends Codec = Codec, K extends string = string> (registry: CodecRegistry, type: K, ...params: unknown[]): DetectCodec<T, K> {
|
||||
return createTypeUnsafe(registry, type, params);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Registry } from '../types/registry';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { TypeDef } from './types';
|
||||
|
||||
import { assert, isNumber, isUndefined, objectSpread, stringify } from '@polkadot/util';
|
||||
@@ -20,7 +20,7 @@ export function paramsNotation <T> (outer: string, inner?: T | T[], transform: (
|
||||
}`;
|
||||
}
|
||||
|
||||
function encodeWithParams (registry: Registry, typeDef: TypeDef, outer: string): string {
|
||||
function encodeWithParams (CodecRegistry: CodecRegistry, typeDef: TypeDef, outer: string): string {
|
||||
const { info, sub } = typeDef;
|
||||
|
||||
switch (info) {
|
||||
@@ -33,13 +33,13 @@ function encodeWithParams (registry: Registry, typeDef: TypeDef, outer: string):
|
||||
case TypeDefInfo.Result:
|
||||
case TypeDefInfo.Vec:
|
||||
case TypeDefInfo.WrapperOpaque:
|
||||
return paramsNotation(outer, sub, (p) => encodeTypeDef(registry, p));
|
||||
return paramsNotation(outer, sub, (p) => encodeTypeDef(CodecRegistry, p));
|
||||
}
|
||||
|
||||
throw new Error(`Unable to encode ${stringify(typeDef)} with params`);
|
||||
}
|
||||
|
||||
function encodeSubTypes (registry: Registry, sub: TypeDef[], asEnum?: boolean, extra?: Record<string, unknown>): string {
|
||||
function encodeSubTypes (CodecRegistry: CodecRegistry, sub: TypeDef[], asEnum?: boolean, extra?: Record<string, unknown>): string {
|
||||
const names = sub.map(({ name }) => name);
|
||||
|
||||
assert(names.every((n) => !!n), () => `Subtypes does not have consistent names, ${names.join(', ')}`);
|
||||
@@ -49,7 +49,7 @@ function encodeSubTypes (registry: Registry, sub: TypeDef[], asEnum?: boolean, e
|
||||
for (let i = 0; i < sub.length; i++) {
|
||||
const def = sub[i];
|
||||
|
||||
inner[def.name as string] = encodeTypeDef(registry, def);
|
||||
inner[def.name as string] = encodeTypeDef(CodecRegistry, def);
|
||||
}
|
||||
|
||||
return stringify(
|
||||
@@ -61,44 +61,44 @@ function encodeSubTypes (registry: Registry, sub: TypeDef[], asEnum?: boolean, e
|
||||
|
||||
// We setup a record here to ensure we have comprehensive coverage (any item not covered will result
|
||||
// in a compile-time error with the missing index)
|
||||
const encoders: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef) => string> = {
|
||||
[TypeDefInfo.BTreeMap]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'BTreeMap'),
|
||||
[TypeDefInfo.BTreeSet]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'BTreeSet'),
|
||||
[TypeDefInfo.Compact]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'Compact'),
|
||||
[TypeDefInfo.DoNotConstruct]: (registry: Registry, { displayName, lookupIndex, lookupName }: TypeDef) =>
|
||||
`DoNotConstruct<${lookupName || displayName || (isUndefined(lookupIndex) ? 'Unknown' : registry.createLookupType(lookupIndex))}>`,
|
||||
[TypeDefInfo.Enum]: (registry: Registry, { sub }: TypeDef): string => {
|
||||
const encoders: Record<TypeDefInfo, (CodecRegistry: CodecRegistry, typeDef: TypeDef) => string> = {
|
||||
[TypeDefInfo.BTreeMap]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'BTreeMap'),
|
||||
[TypeDefInfo.BTreeSet]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'BTreeSet'),
|
||||
[TypeDefInfo.Compact]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Compact'),
|
||||
[TypeDefInfo.DoNotConstruct]: (CodecRegistry: CodecRegistry, { displayName, lookupIndex, lookupName }: TypeDef) =>
|
||||
`DoNotConstruct<${lookupName || displayName || (isUndefined(lookupIndex) ? 'Unknown' : CodecRegistry.createLookupType(lookupIndex))}>`,
|
||||
[TypeDefInfo.Enum]: (CodecRegistry: CodecRegistry, { sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Enum type');
|
||||
|
||||
// c-like enums have all Null entries
|
||||
// TODO We need to take the disciminant into account and auto-add empty entries
|
||||
return sub.every(({ type }) => type === 'Null')
|
||||
? stringify({ _enum: sub.map(({ name }, index) => `${name || `Empty${index}`}`) })
|
||||
: encodeSubTypes(registry, sub, true);
|
||||
: encodeSubTypes(CodecRegistry, sub, true);
|
||||
},
|
||||
[TypeDefInfo.HashMap]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'HashMap'),
|
||||
[TypeDefInfo.Int]: (registry: Registry, { length = 32 }: TypeDef) =>
|
||||
[TypeDefInfo.HashMap]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'HashMap'),
|
||||
[TypeDefInfo.Int]: (CodecRegistry: CodecRegistry, { length = 32 }: TypeDef) =>
|
||||
`Int<${length}>`,
|
||||
[TypeDefInfo.Linkage]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'Linkage'),
|
||||
[TypeDefInfo.Linkage]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Linkage'),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Null]: (registry: Registry, typeDef: TypeDef) =>
|
||||
[TypeDefInfo.Null]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
'Null',
|
||||
[TypeDefInfo.Option]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'Option'),
|
||||
[TypeDefInfo.Option]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Option'),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Plain]: (registry: Registry, { displayName, type }: TypeDef) =>
|
||||
[TypeDefInfo.Plain]: (CodecRegistry: CodecRegistry, { displayName, type }: TypeDef) =>
|
||||
displayName || type,
|
||||
[TypeDefInfo.Range]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, typeDef.type.includes('RangeInclusive') ? 'RangeInclusive' : 'Range'),
|
||||
[TypeDefInfo.Result]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'Result'),
|
||||
[TypeDefInfo.Range]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, typeDef.type.includes('RangeInclusive') ? 'RangeInclusive' : 'Range'),
|
||||
[TypeDefInfo.Result]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Result'),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Set]: (registry: Registry, { length = 8, sub }: TypeDef): string => {
|
||||
[TypeDefInfo.Set]: (CodecRegistry: CodecRegistry, { length = 8, sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Set type');
|
||||
|
||||
return stringify({
|
||||
@@ -108,12 +108,12 @@ const encoders: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef) => st
|
||||
});
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Si]: (registry: Registry, { lookupName, type }: TypeDef) =>
|
||||
[TypeDefInfo.Si]: (CodecRegistry: CodecRegistry, { lookupName, type }: TypeDef) =>
|
||||
lookupName || type,
|
||||
[TypeDefInfo.Struct]: (registry: Registry, { alias, sub }: TypeDef): string => {
|
||||
[TypeDefInfo.Struct]: (CodecRegistry: CodecRegistry, { alias, sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Struct type');
|
||||
|
||||
return encodeSubTypes(registry, sub, false,
|
||||
return encodeSubTypes(CodecRegistry, sub, false,
|
||||
alias
|
||||
? {
|
||||
_alias: [...alias.entries()].reduce<Record<string, string>>((all, [k, v]) =>
|
||||
@@ -123,39 +123,39 @@ const encoders: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef) => st
|
||||
: {}
|
||||
);
|
||||
},
|
||||
[TypeDefInfo.Tuple]: (registry: Registry, { sub }: TypeDef): string => {
|
||||
[TypeDefInfo.Tuple]: (CodecRegistry: CodecRegistry, { sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Tuple type');
|
||||
|
||||
return `(${sub.map((type) => encodeTypeDef(registry, type)).join(',')})`;
|
||||
return `(${sub.map((type) => encodeTypeDef(CodecRegistry, type)).join(',')})`;
|
||||
},
|
||||
[TypeDefInfo.UInt]: (registry: Registry, { length = 32 }: TypeDef) =>
|
||||
[TypeDefInfo.UInt]: (CodecRegistry: CodecRegistry, { length = 32 }: TypeDef) =>
|
||||
`UInt<${length}>`,
|
||||
[TypeDefInfo.Vec]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'Vec'),
|
||||
[TypeDefInfo.VecFixed]: (registry: Registry, { length, sub }: TypeDef): string => {
|
||||
[TypeDefInfo.Vec]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Vec'),
|
||||
[TypeDefInfo.VecFixed]: (CodecRegistry: CodecRegistry, { length, sub }: TypeDef): string => {
|
||||
assert(isNumber(length) && !isUndefined(sub) && !Array.isArray(sub), 'Unable to encode VecFixed type');
|
||||
|
||||
return `[${sub.type};${length}]`;
|
||||
},
|
||||
[TypeDefInfo.WrapperOpaque]: (registry: Registry, typeDef: TypeDef) =>
|
||||
encodeWithParams(registry, typeDef, 'WrapperOpaque')
|
||||
[TypeDefInfo.WrapperOpaque]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'WrapperOpaque')
|
||||
};
|
||||
|
||||
function encodeType (registry: Registry, typeDef: TypeDef, withLookup = true): string {
|
||||
function encodeType (CodecRegistry: CodecRegistry, typeDef: TypeDef, withLookup = true): string {
|
||||
return withLookup && typeDef.lookupName
|
||||
? typeDef.lookupName
|
||||
: encoders[typeDef.info](registry, typeDef);
|
||||
: encoders[typeDef.info](CodecRegistry, typeDef);
|
||||
}
|
||||
|
||||
export function encodeTypeDef (registry: Registry, typeDef: TypeDef): string {
|
||||
export function encodeTypeDef (CodecRegistry: CodecRegistry, typeDef: TypeDef): string {
|
||||
// In the case of contracts we do have the unfortunate situation where the displayName would
|
||||
// refer to "Option" when it is an option. For these, string it out, only using when actually
|
||||
// not a top-level element to be used
|
||||
return (typeDef.displayName && !INFO_WRAP.some((i) => typeDef.displayName === i))
|
||||
? typeDef.displayName
|
||||
: encodeType(registry, typeDef);
|
||||
: encodeType(CodecRegistry, typeDef);
|
||||
}
|
||||
|
||||
export function withTypeString (registry: Registry, typeDef: Omit<TypeDef, 'type'>): TypeDef {
|
||||
return objectSpread({}, typeDef, { type: encodeType(registry, typeDef as TypeDef, false) });
|
||||
export function withTypeString (CodecRegistry: CodecRegistry, typeDef: Omit<TypeDef, 'type'>): TypeDef {
|
||||
return objectSpread({}, typeDef, { type: encodeType(CodecRegistry, typeDef as TypeDef, false) });
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
|
||||
import type { TypeDef } from './types';
|
||||
|
||||
import { sanitize } from '@polkadot/types-codec';
|
||||
import { assert, isNumber, isString, objectSpread } from '@polkadot/util';
|
||||
|
||||
import { sanitize } from './sanitize';
|
||||
import { TypeDefInfo } from './types';
|
||||
import { typeSplit } from './typeSplit';
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
import type { Codec, Constructor } from '../types';
|
||||
import type { Codec, CodecClass } from '@polkadot/types-codec/types';
|
||||
|
||||
import { DoNotConstruct, Struct } from '@polkadot/types-codec';
|
||||
import { isChildClass, u8aToU8a } from '@polkadot/util';
|
||||
import { keccakAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { DoNotConstruct, Struct } from '../codec';
|
||||
import { Text, U32 } from '../primitive';
|
||||
import { TypeRegistry } from '.';
|
||||
|
||||
@@ -20,8 +20,8 @@ describe('TypeRegistry', (): void => {
|
||||
});
|
||||
|
||||
it('throws on non-existent via getOrThrow', (): void => {
|
||||
expect((): Constructor<Codec> => registry.getOrThrow('non-exist')).toThrow('type non-exist not found');
|
||||
expect((): Constructor<Codec> => registry.getOrThrow('non-exist', 'foo bar blah')).toThrow('foo bar blah');
|
||||
expect((): CodecClass<Codec> => registry.getOrThrow('non-exist')).toThrow('type non-exist not found');
|
||||
expect((): CodecClass<Codec> => registry.getOrThrow('non-exist', 'foo bar blah')).toThrow('foo bar blah');
|
||||
});
|
||||
|
||||
it('handles non exist type as Unknown (via getOrUnknown)', (): void => {
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry, IU8a } from '@polkadot/types-codec/types';
|
||||
import type { ExtDef } from '../extrinsic/signedExtensions/types';
|
||||
import type { ChainProperties, CodecHash, DispatchErrorModule, Hash, MetadataLatest, SiField, SiLookupTypeId, SiVariant } from '../interfaces/types';
|
||||
import type { CallFunction, Codec, CodecHasher, Constructor, Definitions, DetectCodec, DetectConstructor, RegisteredTypes, Registry, RegistryError, RegistryTypes } from '../types';
|
||||
import type { ChainProperties, DispatchErrorModule, EventMetadataLatest, Hash, MetadataLatest, SiField, SiLookupTypeId, SiVariant } from '../interfaces/types';
|
||||
import type { CallFunction, CodecHasher, Definitions, DetectCodec, RegisteredTypes, Registry, RegistryError, RegistryTypes } from '../types';
|
||||
import type { CreateOptions, TypeDef } from './types';
|
||||
|
||||
import { DoNotConstruct, Json, Raw } from '@polkadot/types-codec';
|
||||
import { assert, assertReturn, BN_ZERO, formatBalance, isFunction, isString, isU8a, lazyMethod, logger, objectSpread, stringCamelCase, stringify } from '@polkadot/util';
|
||||
import { blake2AsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { DoNotConstruct } from '../codec/DoNotConstruct';
|
||||
import { Json } from '../codec/Json';
|
||||
import { Raw } from '../codec/Raw';
|
||||
import { expandExtensionTypes, fallbackExtensions, findUnknownExtensions } from '../extrinsic/signedExtensions';
|
||||
import { GenericEventData } from '../generic/Event';
|
||||
import * as baseTypes from '../index.types';
|
||||
@@ -20,7 +19,7 @@ import { decorateConstants, filterCallsSome, filterEventsSome } from '../metadat
|
||||
import { createCallFunction } from '../metadata/decorate/extrinsics';
|
||||
import { Metadata } from '../metadata/Metadata';
|
||||
import { PortableRegistry } from '../metadata/PortableRegistry';
|
||||
import { constructTypeClass, createClass } from './createClass';
|
||||
import { constructTypeClass, createClassUnsafe } from './createClass';
|
||||
import { createTypeUnsafe } from './createType';
|
||||
import { lazyVariants } from './lazy';
|
||||
|
||||
@@ -78,7 +77,7 @@ function injectErrors (_: Registry, { lookup, pallets }: MetadataLatest, version
|
||||
}
|
||||
|
||||
// create event classes from metadata
|
||||
function injectEvents (registry: Registry, { lookup, pallets }: MetadataLatest, version: number, result: Record<string, Record<string, Constructor<GenericEventData>>>): void {
|
||||
function injectEvents (registry: CodecRegistry, { lookup, pallets }: MetadataLatest, version: number, result: Record<string, Record<string, CodecClass<GenericEventData>>>): void {
|
||||
const filtered = pallets.filter(filterEventsSome);
|
||||
|
||||
clearRecord(result);
|
||||
@@ -87,11 +86,11 @@ function injectEvents (registry: Registry, { lookup, pallets }: MetadataLatest,
|
||||
const { events, index, name } = filtered[i];
|
||||
|
||||
lazyMethod(result, version >= 12 ? index.toNumber() : i, () =>
|
||||
lazyVariants(lookup, events.unwrap(), getVariantStringIdx, (variant: SiVariant): Constructor<GenericEventData> => {
|
||||
const meta = registry.createType('EventMetadataLatest', objectSpread({}, variant, { args: getFieldArgs(lookup, variant.fields) }));
|
||||
lazyVariants(lookup, events.unwrap(), getVariantStringIdx, (variant: SiVariant): CodecClass<GenericEventData> => {
|
||||
const meta = (registry as Registry).createType<EventMetadataLatest>('EventMetadataLatest', objectSpread({}, variant, { args: getFieldArgs(lookup, variant.fields) }));
|
||||
|
||||
return class extends GenericEventData {
|
||||
constructor (registry: Registry, value: Uint8Array) {
|
||||
constructor (registry: CodecRegistry, value: Uint8Array) {
|
||||
super(registry, value, meta, stringCamelCase(name), variant.name.toString());
|
||||
}
|
||||
};
|
||||
@@ -101,7 +100,7 @@ function injectEvents (registry: Registry, { lookup, pallets }: MetadataLatest,
|
||||
}
|
||||
|
||||
// create extrinsic mapping from metadata
|
||||
function injectExtrinsics (registry: Registry, { lookup, pallets }: MetadataLatest, version: number, result: Record<string, Record<string, CallFunction>>): void {
|
||||
function injectExtrinsics (registry: CodecRegistry, { lookup, pallets }: MetadataLatest, version: number, result: Record<string, Record<string, CallFunction>>): void {
|
||||
const filtered = pallets.filter(filterCallsSome);
|
||||
|
||||
clearRecord(result);
|
||||
@@ -119,8 +118,8 @@ function injectExtrinsics (registry: Registry, { lookup, pallets }: MetadataLate
|
||||
}
|
||||
|
||||
// extract additional properties from the metadata
|
||||
function extractProperties (registry: Registry, metadata: Metadata): ChainProperties | undefined {
|
||||
const original = registry.getChainProperties();
|
||||
function extractProperties (registry: CodecRegistry, metadata: Metadata): ChainProperties | undefined {
|
||||
const original = (registry as Registry).getChainProperties();
|
||||
const constants = decorateConstants(registry, metadata.asLatest, metadata.version);
|
||||
const ss58Format = constants.system && (constants.system.sS58Prefix || constants.system.ss58Prefix);
|
||||
|
||||
@@ -130,11 +129,11 @@ function extractProperties (registry: Registry, metadata: Metadata): ChainProper
|
||||
|
||||
const { tokenDecimals, tokenSymbol } = original || {};
|
||||
|
||||
return registry.createType('ChainProperties', { ss58Format, tokenDecimals, tokenSymbol });
|
||||
return (registry as Registry).createType('ChainProperties', { ss58Format, tokenDecimals, tokenSymbol });
|
||||
}
|
||||
|
||||
export class TypeRegistry implements Registry {
|
||||
#classes = new Map<string, Constructor>();
|
||||
#classes = new Map<string, CodecClass>();
|
||||
|
||||
#definitions = new Map<string, string>();
|
||||
|
||||
@@ -148,7 +147,7 @@ export class TypeRegistry implements Registry {
|
||||
|
||||
readonly #metadataErrors: Record<string, Record<string, RegistryError>> = {};
|
||||
|
||||
readonly #metadataEvents: Record<string, Record<string, Constructor<GenericEventData>>> = {};
|
||||
readonly #metadataEvents: Record<string, Record<string, CodecClass<GenericEventData>>> = {};
|
||||
|
||||
#unknownTypes = new Map<string, boolean>();
|
||||
|
||||
@@ -181,7 +180,7 @@ export class TypeRegistry implements Registry {
|
||||
|
||||
public init (): this {
|
||||
// start clean
|
||||
this.#classes = new Map<string, Constructor>();
|
||||
this.#classes = new Map<string, CodecClass>();
|
||||
this.#definitions = new Map<string, string>();
|
||||
this.#unknownTypes = new Map<string, boolean>();
|
||||
this.#knownTypes = {};
|
||||
@@ -267,22 +266,29 @@ export class TypeRegistry implements Registry {
|
||||
/**
|
||||
* @describe Creates an instance of the class
|
||||
*/
|
||||
public createClass <T extends Codec = Codec, K extends string = string> (type: K): DetectConstructor<T, K> {
|
||||
return createClass(this, type);
|
||||
public createClass <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (type: K): CodecClass<R> {
|
||||
return this.createClassUnsafe(type) as unknown as CodecClass<R>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @describe Creates an instance of the class
|
||||
*/
|
||||
public createClassUnsafe <T extends Codec = Codec, K extends string = string> (type: K): CodecClass<T> {
|
||||
return createClassUnsafe(this, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates an instance of a type as registered
|
||||
*/
|
||||
public createType <T extends Codec = Codec, K extends string = string> (type: K, ...params: unknown[]): DetectCodec<T, K> {
|
||||
public createType <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (type: K, ...params: unknown[]): R {
|
||||
return this.createTypeUnsafe(type, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates an instance of a type as registered
|
||||
*/
|
||||
public createTypeUnsafe <T extends Codec = Codec, K extends string = string> (type: K, params: unknown[], options?: CreateOptions): DetectCodec<T, K> {
|
||||
return createTypeUnsafe(this, type, params, options);
|
||||
public createTypeUnsafe <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (type: K, params: unknown[], options?: CreateOptions): R {
|
||||
return createTypeUnsafe(this, type, params, options) as unknown as R;
|
||||
}
|
||||
|
||||
// find a specific call
|
||||
@@ -307,7 +313,7 @@ export class TypeRegistry implements Registry {
|
||||
);
|
||||
}
|
||||
|
||||
public findMetaEvent (eventIndex: Uint8Array): Constructor<GenericEventData> {
|
||||
public findMetaEvent (eventIndex: Uint8Array): CodecClass<GenericEventData> {
|
||||
const [section, method] = [eventIndex[0], eventIndex[1]];
|
||||
|
||||
return assertReturn(
|
||||
@@ -316,17 +322,21 @@ export class TypeRegistry implements Registry {
|
||||
);
|
||||
}
|
||||
|
||||
public get <T extends Codec = Codec, K extends string = string> (name: K, withUnknown?: boolean, knownTypeDef?: TypeDef): DetectConstructor<T, K> | undefined {
|
||||
public get <T extends Codec = Codec, K extends string = string> (name: K, withUnknown?: boolean, knownTypeDef?: TypeDef): CodecClass<T> | undefined {
|
||||
return this.getUnsafe(name, withUnknown, knownTypeDef) as CodecClass<T>;
|
||||
}
|
||||
|
||||
public getUnsafe <T extends Codec = Codec, K extends string = string> (name: K, withUnknown?: boolean, knownTypeDef?: TypeDef): CodecClass<T> | undefined {
|
||||
let Type = this.#classes.get(name);
|
||||
|
||||
// we have not already created the type, attempt it
|
||||
if (!Type) {
|
||||
const definition = this.#definitions.get(name);
|
||||
let BaseType: Constructor | undefined;
|
||||
let BaseType: CodecClass | undefined;
|
||||
|
||||
// we have a definition, so create the class now (lazily)
|
||||
if (definition) {
|
||||
BaseType = createClass(this, definition);
|
||||
BaseType = createClassUnsafe(this, definition);
|
||||
} else if (knownTypeDef) {
|
||||
BaseType = constructTypeClass(this, knownTypeDef);
|
||||
} else if (withUnknown) {
|
||||
@@ -347,14 +357,14 @@ export class TypeRegistry implements Registry {
|
||||
}
|
||||
}
|
||||
|
||||
return Type as DetectConstructor<T, K>;
|
||||
return Type as unknown as CodecClass<T>;
|
||||
}
|
||||
|
||||
public getChainProperties (): ChainProperties | undefined {
|
||||
return this.#chainProperties;
|
||||
}
|
||||
|
||||
public getClassName (Type: Constructor): string | undefined {
|
||||
public getClassName (Type: CodecClass): string | undefined {
|
||||
// we cannot rely on export order (anymore, since babel/core 7.15.8), so in the case of
|
||||
// items such as u32 & U32, we get the lowercase versions here... not quite as optimal
|
||||
// (previously this used to be a simple find & return)
|
||||
@@ -382,16 +392,16 @@ export class TypeRegistry implements Registry {
|
||||
return this.#knownTypes?.typesBundle?.spec?.[specName]?.instances?.[moduleName];
|
||||
}
|
||||
|
||||
public getOrThrow <T extends Codec = Codec, K extends string = string> (name: K, msg?: string): DetectConstructor<T, K> {
|
||||
public getOrThrow <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (name: K, msg?: string): CodecClass<R> {
|
||||
const Clazz = this.get<T, K>(name);
|
||||
|
||||
assert(Clazz, msg || `type ${name} not found`);
|
||||
|
||||
return Clazz;
|
||||
return Clazz as unknown as CodecClass<R>;
|
||||
}
|
||||
|
||||
public getOrUnknown <T extends Codec = Codec, K extends string = string> (name: K): DetectConstructor<T, K> {
|
||||
return this.get<T, K>(name, true) as DetectConstructor<T, K>;
|
||||
public getOrUnknown <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (name: K): CodecClass<R> {
|
||||
return this.get<T, K>(name, true) as unknown as CodecClass<R>;
|
||||
}
|
||||
|
||||
public getSignedExtensionExtra (): Record<string, string> {
|
||||
@@ -414,17 +424,17 @@ export class TypeRegistry implements Registry {
|
||||
return !this.#unknownTypes.get(name) && (this.hasClass(name) || this.hasDef(name));
|
||||
}
|
||||
|
||||
public hash (data: Uint8Array): CodecHash {
|
||||
public hash (data: Uint8Array): IU8a {
|
||||
return this.createType('CodecHash', this.#hasher(data));
|
||||
}
|
||||
|
||||
public register (type: Constructor | RegistryTypes): void;
|
||||
public register (type: CodecClass | RegistryTypes): void;
|
||||
|
||||
// eslint-disable-next-line no-dupe-class-members
|
||||
public register (name: string, type: Constructor): void;
|
||||
public register (name: string, type: CodecClass): void;
|
||||
|
||||
// eslint-disable-next-line no-dupe-class-members
|
||||
public register (arg1: string | Constructor | RegistryTypes, arg2?: Constructor): void {
|
||||
public register (arg1: string | CodecClass | RegistryTypes, arg2?: CodecClass): void {
|
||||
// NOTE Constructors appear as functions here
|
||||
if (isFunction(arg1)) {
|
||||
this.#classes.set(arg1.name, arg1);
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
// 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>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,281 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types 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;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export type { CodecCreateOptions as CreateOptions } from '@polkadot/types-codec/types';
|
||||
|
||||
export enum TypeDefInfo {
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
@@ -43,9 +45,3 @@ export interface TypeDef {
|
||||
type: string;
|
||||
typeName?: string;
|
||||
}
|
||||
|
||||
export interface CreateOptions {
|
||||
blockHash?: Uint8Array | string | null;
|
||||
isOptional?: boolean;
|
||||
isPedantic?: boolean;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { packageInfo as codecInfo } from '@polkadot/types-codec';
|
||||
import { detectPackage } from '@polkadot/util';
|
||||
|
||||
import { packageInfo } from './packageInfo';
|
||||
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, []);
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [codecInfo]);
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
import { Raw } from '../codec/Raw';
|
||||
import { Raw } from '@polkadot/types-codec';
|
||||
|
||||
import { TypeRegistry } from '../create';
|
||||
import { GenericEthereumAccountId as AccountId } from './AccountId';
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyString, AnyU8a, Registry } from '../types';
|
||||
import type { AnyString, AnyU8a, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { U8aFixed } from '@polkadot/types-codec';
|
||||
import { hexToU8a, isHex, isString, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
import { ethereumEncode, isEthereumAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { U8aFixed } from '../codec/U8aFixed';
|
||||
|
||||
/** @internal */
|
||||
function decodeAccountId (value: AnyU8a | AnyString): AnyU8a {
|
||||
if (isU8a(value) || Array.isArray(value)) {
|
||||
@@ -29,7 +28,7 @@ function decodeAccountId (value: AnyU8a | AnyString): AnyU8a {
|
||||
* just a Uint8Array wrapper with a fixed length.
|
||||
*/
|
||||
export class GenericEthereumAccountId extends U8aFixed {
|
||||
constructor (registry: Registry, value: AnyU8a = new Uint8Array()) {
|
||||
constructor (registry: CodecRegistry, value: AnyU8a = new Uint8Array()) {
|
||||
super(registry, decodeAccountId(value), 160);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Registry } from '../types';
|
||||
|
||||
import { Base } from '@polkadot/types-codec';
|
||||
import { isBigInt, isBn, isHex, isNumber, isU8a, u8aConcat, u8aToBn, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { Base } from '../codec/Base';
|
||||
import { GenericAccountIndex } from '../generic/AccountIndex';
|
||||
import { GenericEthereumAccountId } from './AccountId';
|
||||
|
||||
@@ -18,27 +18,27 @@ type AnyAddress = bigint | BN | GenericEthereumLookupSource | GenericEthereumAcc
|
||||
export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]);
|
||||
|
||||
/** @internal */
|
||||
function decodeString (registry: Registry, value: string): GenericEthereumAccountId | GenericAccountIndex {
|
||||
function decodeString (registry: CodecRegistry, value: string): GenericEthereumAccountId | GenericAccountIndex {
|
||||
const decoded = decodeAddress(value);
|
||||
|
||||
return decoded.length === 20
|
||||
? registry.createType('EthereumAccountId', decoded)
|
||||
: registry.createType('AccountIndex', u8aToBn(decoded, true));
|
||||
? registry.createTypeUnsafe('EthereumAccountId', [decoded])
|
||||
: registry.createTypeUnsafe('AccountIndex', [u8aToBn(decoded, true)]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeU8a (registry: Registry, value: Uint8Array): GenericEthereumAccountId | GenericAccountIndex {
|
||||
function decodeU8a (registry: CodecRegistry, value: Uint8Array): GenericEthereumAccountId | GenericAccountIndex {
|
||||
// This allows us to instantiate an address with a raw publicKey. Do this first before
|
||||
// we checking the first byte, otherwise we may split an already-existent valid address
|
||||
if (value.length === 20) {
|
||||
return registry.createType('EthereumAccountId', value);
|
||||
return registry.createTypeUnsafe('EthereumAccountId', [value]);
|
||||
} else if (value[0] === 0xff) {
|
||||
return registry.createType('EthereumAccountId', value.subarray(1));
|
||||
return registry.createTypeUnsafe('EthereumAccountId', [value.subarray(1)]);
|
||||
}
|
||||
|
||||
const [offset, length] = GenericAccountIndex.readLength(value);
|
||||
|
||||
return registry.createType('AccountIndex', u8aToBn(value.subarray(offset, offset + length), true));
|
||||
return registry.createTypeUnsafe('AccountIndex', [u8aToBn(value.subarray(offset, offset + length), true)]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,12 +50,12 @@ function decodeU8a (registry: Registry, value: Uint8Array): GenericEthereumAccou
|
||||
* is encoded as `[ <prefix-byte>, ...publicKey/...bytes ]` as per spec
|
||||
*/
|
||||
export class GenericEthereumLookupSource extends Base<GenericEthereumAccountId | GenericAccountIndex> {
|
||||
constructor (registry: Registry, value: AnyAddress = new Uint8Array()) {
|
||||
constructor (registry: CodecRegistry, value: AnyAddress = new Uint8Array()) {
|
||||
super(registry, GenericEthereumLookupSource._decodeAddress(registry, value));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeAddress (registry: Registry, value: AnyAddress): GenericEthereumAccountId | GenericAccountIndex {
|
||||
private static _decodeAddress (registry: CodecRegistry, value: AnyAddress): GenericEthereumAccountId | GenericAccountIndex {
|
||||
return value instanceof GenericEthereumLookupSource
|
||||
? value._raw
|
||||
: value instanceof GenericEthereumAccountId || value instanceof GenericAccountIndex
|
||||
@@ -63,7 +63,7 @@ export class GenericEthereumLookupSource extends Base<GenericEthereumAccountId |
|
||||
: isU8a(value) || Array.isArray(value) || isHex(value)
|
||||
? decodeU8a(registry, u8aToU8a(value))
|
||||
: isBn(value) || isNumber(value) || isBigInt(value)
|
||||
? registry.createType('AccountIndex', value)
|
||||
? registry.createTypeUnsafe('AccountIndex', [value])
|
||||
: decodeString(registry, value);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Compact } from '@polkadot/types-codec';
|
||||
import type { CodecRegistry, IMethod } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Compact } from '../codec/Compact';
|
||||
import type { EcdsaSignature, Ed25519Signature, ExtrinsicUnknown, ExtrinsicV4, Sr25519Signature } from '../interfaces/extrinsics';
|
||||
import type { FunctionMetadataLatest } from '../interfaces/metadata';
|
||||
import type { Address, Balance, Call, CodecHash, Index } from '../interfaces/runtime';
|
||||
import type { AnyJson, AnyTuple, AnyU8a, ArgsDef, CallBase, ExtrinsicPayloadValue, IExtrinsic, IKeyringPair, IMethod, Registry, SignatureOptions } from '../types';
|
||||
import type { AnyJson, AnyTuple, AnyU8a, ArgsDef, CallBase, ExtrinsicPayloadValue, IExtrinsic, IKeyringPair, SignatureOptions } from '../types';
|
||||
import type { GenericExtrinsicEra } from './ExtrinsicEra';
|
||||
import type { ExtrinsicValueV4 } from './v4/Extrinsic';
|
||||
|
||||
import { Base } from '@polkadot/types-codec';
|
||||
import { assert, compactAddLength, compactFromU8a, isHex, isU8a, objectProperty, objectSpread, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Base } from '../codec/Base';
|
||||
import { BIT_SIGNED, BIT_UNSIGNED, DEFAULT_VERSION, UNMASK_VERSION } from './constants';
|
||||
|
||||
interface CreateOptions {
|
||||
@@ -36,7 +37,7 @@ const VERSIONS = [
|
||||
export { EXTRINSIC_VERSION as LATEST_EXTRINSIC_VERSION } from './v4/Extrinsic';
|
||||
|
||||
abstract class ExtrinsicBase<A extends AnyTuple> extends Base<ExtrinsicVx | ExtrinsicUnknown> {
|
||||
constructor (registry: Registry, value: ExtrinsicV4 | ExtrinsicUnknown, initialU8aLength?: number) {
|
||||
constructor (registry: CodecRegistry, value: ExtrinsicV4 | ExtrinsicUnknown, initialU8aLength?: number) {
|
||||
super(registry, value, initialU8aLength);
|
||||
|
||||
const signKeys = Object.keys(registry.getSignedExtensionTypes());
|
||||
@@ -184,12 +185,12 @@ abstract class ExtrinsicBase<A extends AnyTuple> extends Base<ExtrinsicVx | Extr
|
||||
export class GenericExtrinsic<A extends AnyTuple = AnyTuple> extends ExtrinsicBase<A> implements IExtrinsic<A> {
|
||||
#hashCache?: CodecHash;
|
||||
|
||||
constructor (registry: Registry, value?: GenericExtrinsic | ExtrinsicValue | AnyU8a | Call, { version }: CreateOptions = {}) {
|
||||
constructor (registry: CodecRegistry, value?: GenericExtrinsic | ExtrinsicValue | AnyU8a | Call, { version }: CreateOptions = {}) {
|
||||
super(registry, GenericExtrinsic._decodeExtrinsic(registry, value, version));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _newFromValue (registry: Registry, value: any, version: number): ExtrinsicVx | ExtrinsicUnknown {
|
||||
private static _newFromValue (registry: CodecRegistry, value: any, version: number): ExtrinsicVx | ExtrinsicUnknown {
|
||||
if (value instanceof GenericExtrinsic) {
|
||||
return value._raw;
|
||||
}
|
||||
@@ -199,14 +200,14 @@ export class GenericExtrinsic<A extends AnyTuple = AnyTuple> extends ExtrinsicBa
|
||||
|
||||
// we cast here since the VERSION definition is incredibly broad - we don't have a
|
||||
// slice for "only add extrinsic types", and more string definitions become unwieldy
|
||||
return registry.createType(type, value, { isSigned, version });
|
||||
return registry.createTypeUnsafe(type, [value, { isSigned, version }]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeExtrinsic (registry: Registry, value?: GenericExtrinsic | ExtrinsicValue | AnyU8a | Call, version: number = DEFAULT_VERSION): ExtrinsicVx | ExtrinsicUnknown {
|
||||
private static _decodeExtrinsic (registry: CodecRegistry, value?: GenericExtrinsic | ExtrinsicValue | AnyU8a | Call, version: number = DEFAULT_VERSION): ExtrinsicVx | ExtrinsicUnknown {
|
||||
if (isU8a(value) || Array.isArray(value) || isHex(value)) {
|
||||
return GenericExtrinsic._decodeU8a(registry, u8aToU8a(value), version);
|
||||
} else if (value instanceof registry.createClass('Call')) {
|
||||
} else if (value instanceof registry.createClassUnsafe('Call')) {
|
||||
return GenericExtrinsic._newFromValue(registry, { method: value }, version);
|
||||
}
|
||||
|
||||
@@ -214,7 +215,7 @@ export class GenericExtrinsic<A extends AnyTuple = AnyTuple> extends ExtrinsicBa
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeU8a (registry: Registry, value: Uint8Array, version: number): ExtrinsicVx | ExtrinsicUnknown {
|
||||
private static _decodeU8a (registry: CodecRegistry, value: Uint8Array, version: number): ExtrinsicVx | ExtrinsicUnknown {
|
||||
if (!value.length) {
|
||||
return GenericExtrinsic._newFromValue(registry, new Uint8Array(), version);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { AnyU8a, IExtrinsicEra, Registry } from '../types';
|
||||
import type { AnyU8a, IExtrinsicEra } from '../types';
|
||||
|
||||
import { Enum, Raw, Tuple, U64 } from '@polkadot/types-codec';
|
||||
import { assert, bnToBn, formatNumber, hexToU8a, isHex, isObject, isU8a, u8aToBn, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Enum } from '../codec/Enum';
|
||||
import { Raw } from '../codec/Raw';
|
||||
import { Tuple } from '../codec/Tuple';
|
||||
import { u64 as U64 } from '../primitive/U64';
|
||||
import { IMMORTAL_ERA } from './constants';
|
||||
|
||||
type MortalEraValue = [U64, U64];
|
||||
@@ -45,7 +43,7 @@ function getTrailingZeros (period: number): number {
|
||||
*/
|
||||
export class ImmortalEra extends Raw {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
constructor (registry: Registry, value?: AnyU8a) {
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
// For immortals, we always provide the known value (i.e. treated as a
|
||||
// constant no matter how it is constructed - it is a fixed structure)
|
||||
super(registry, IMMORTAL_ERA);
|
||||
@@ -58,7 +56,7 @@ export class ImmortalEra extends Raw {
|
||||
* The MortalEra for an extrinsic, indicating period and phase
|
||||
*/
|
||||
export class MortalEra extends Tuple {
|
||||
constructor (registry: Registry, value?: MortalMethod | Uint8Array | number[] | string) {
|
||||
constructor (registry: CodecRegistry, value?: MortalMethod | Uint8Array | number[] | string) {
|
||||
super(registry, {
|
||||
period: U64,
|
||||
phase: U64
|
||||
@@ -66,7 +64,7 @@ export class MortalEra extends Tuple {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeMortalEra (registry: Registry, value?: MortalMethod | Uint8Array | number[] | string): MortalEraValue {
|
||||
private static _decodeMortalEra (registry: CodecRegistry, value?: MortalMethod | Uint8Array | number[] | string): MortalEraValue {
|
||||
if (isU8a(value) || isHex(value) || Array.isArray(value)) {
|
||||
return MortalEra._decodeMortalU8a(registry, u8aToU8a(value));
|
||||
} else if (!value) {
|
||||
@@ -79,7 +77,7 @@ export class MortalEra extends Tuple {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeMortalObject (registry: Registry, value: MortalMethod): MortalEraValue {
|
||||
private static _decodeMortalObject (registry: CodecRegistry, value: MortalMethod): MortalEraValue {
|
||||
const { current, period } = value;
|
||||
let calPeriod = Math.pow(2, Math.ceil(Math.log2(period)));
|
||||
|
||||
@@ -93,7 +91,7 @@ export class MortalEra extends Tuple {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeMortalU8a (registry: Registry, value: Uint8Array): MortalEraValue {
|
||||
private static _decodeMortalU8a (registry: CodecRegistry, value: Uint8Array): MortalEraValue {
|
||||
if (value.length === 0) {
|
||||
return [new U64(registry), new U64(registry)];
|
||||
}
|
||||
@@ -198,7 +196,7 @@ export class MortalEra extends Tuple {
|
||||
* The era for an extrinsic, indicating either a mortal or immortal extrinsic
|
||||
*/
|
||||
export class GenericExtrinsicEra extends Enum implements IExtrinsicEra {
|
||||
constructor (registry: Registry, value?: unknown) {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, {
|
||||
ImmortalEra,
|
||||
MortalEra
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtrinsicPayloadV4 } from '../interfaces/extrinsics';
|
||||
import type { Balance, Hash, Index } from '../interfaces/runtime';
|
||||
import type { AnyJson, BareOpts, ExtrinsicPayloadValue, IKeyringPair, Registry } from '../types';
|
||||
import type { AnyJson, BareOpts, ExtrinsicPayloadValue, IKeyringPair } from '../types';
|
||||
|
||||
import { Base, Compact, Raw, u32 } from '@polkadot/types-codec';
|
||||
import { u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Base } from '../codec/Base';
|
||||
import { Compact } from '../codec/Compact';
|
||||
import { Raw } from '../codec/Raw';
|
||||
import { u32 } from '../primitive/U32';
|
||||
import { DEFAULT_VERSION } from './constants';
|
||||
import { GenericExtrinsicEra } from './ExtrinsicEra';
|
||||
|
||||
@@ -37,17 +35,17 @@ const VERSIONS = [
|
||||
* on the contents included
|
||||
*/
|
||||
export class GenericExtrinsicPayload extends Base<ExtrinsicPayloadVx> {
|
||||
constructor (registry: Registry, value?: Partial<ExtrinsicPayloadValue> | Uint8Array | string, { version }: ExtrinsicPayloadOptions = {}) {
|
||||
constructor (registry: CodecRegistry, value?: Partial<ExtrinsicPayloadValue> | Uint8Array | string, { version }: ExtrinsicPayloadOptions = {}) {
|
||||
super(registry, GenericExtrinsicPayload.decodeExtrinsicPayload(registry, value as ExtrinsicPayloadValue, version));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
public static decodeExtrinsicPayload (registry: Registry, value?: GenericExtrinsicPayload | ExtrinsicPayloadValue | Uint8Array | string, version: number = DEFAULT_VERSION): ExtrinsicPayloadVx {
|
||||
public static decodeExtrinsicPayload (registry: CodecRegistry, value?: GenericExtrinsicPayload | ExtrinsicPayloadValue | Uint8Array | string, version: number = DEFAULT_VERSION): ExtrinsicPayloadVx {
|
||||
if (value instanceof GenericExtrinsicPayload) {
|
||||
return value._raw;
|
||||
}
|
||||
|
||||
return registry.createType(VERSIONS[version] || VERSIONS[0], value, { version });
|
||||
return registry.createTypeUnsafe(VERSIONS[version] || VERSIONS[0], [value, { version }]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +67,7 @@ export class GenericExtrinsicPayload extends Base<ExtrinsicPayloadVx> {
|
||||
*/
|
||||
public get genesisHash (): Hash {
|
||||
// NOTE only v3+
|
||||
return this._raw.genesisHash || this.registry.createType('Hash');
|
||||
return this._raw.genesisHash || this.registry.createTypeUnsafe('Hash', []);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,7 +89,7 @@ export class GenericExtrinsicPayload extends Base<ExtrinsicPayloadVx> {
|
||||
*/
|
||||
public get specVersion (): u32 {
|
||||
// NOTE only v3+
|
||||
return this._raw.specVersion || this.registry.createType('u32');
|
||||
return this._raw.specVersion || this.registry.createTypeUnsafe('u32', []);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -99,7 +97,7 @@ export class GenericExtrinsicPayload extends Base<ExtrinsicPayloadVx> {
|
||||
*/
|
||||
public get tip (): Compact<Balance> {
|
||||
// NOTE from v2+
|
||||
return this._raw.tip || this.registry.createType('Compact<Balance>');
|
||||
return this._raw.tip || this.registry.createTypeUnsafe('Compact<Balance>', []);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,7 +105,7 @@ export class GenericExtrinsicPayload extends Base<ExtrinsicPayloadVx> {
|
||||
*/
|
||||
public get transactionVersion (): u32 {
|
||||
// NOTE only v4+
|
||||
return this._raw.transactionVersion || this.registry.createType('u32');
|
||||
return this._raw.transactionVersion || this.registry.createTypeUnsafe('u32', []);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { ExtrinsicPayloadOptions } from './types';
|
||||
|
||||
import { Struct } from '../codec/Struct';
|
||||
import { Struct } from '@polkadot/types-codec';
|
||||
|
||||
/**
|
||||
* @name GenericExtrinsicPayloadUnknown
|
||||
@@ -12,7 +12,7 @@ import { Struct } from '../codec/Struct';
|
||||
* A default handler for payloads where the version is not known (default throw)
|
||||
*/
|
||||
export class GenericExtrinsicPayloadUnknown extends Struct {
|
||||
constructor (registry: Registry, value?: unknown, { version = 0 }: Partial<ExtrinsicPayloadOptions> = {}) {
|
||||
constructor (registry: CodecRegistry, value?: unknown, { version = 0 }: Partial<ExtrinsicPayloadOptions> = {}) {
|
||||
super(registry, {});
|
||||
|
||||
throw new Error(`Unsupported extrinsic payload version ${version}`);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { ExtrinsicOptions } from './types';
|
||||
|
||||
import { Struct } from '../codec/Struct';
|
||||
import { Struct } from '@polkadot/types-codec';
|
||||
|
||||
import { UNMASK_VERSION } from './constants';
|
||||
|
||||
/**
|
||||
@@ -13,7 +14,7 @@ import { UNMASK_VERSION } from './constants';
|
||||
* A default handler for extrinsics where the version is not known (default throw)
|
||||
*/
|
||||
export class GenericExtrinsicUnknown extends Struct {
|
||||
constructor (registry: Registry, value?: unknown, { isSigned = false, version = 0 }: Partial<ExtrinsicOptions> = {}) {
|
||||
constructor (registry: CodecRegistry, value?: unknown, { isSigned = false, version = 0 }: Partial<ExtrinsicOptions> = {}) {
|
||||
super(registry, {});
|
||||
|
||||
throw new Error(`Unsupported ${isSigned ? '' : 'un'}signed extrinsic version ${version & UNMASK_VERSION}`);
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Address, Balance, BlockNumber, Call, ExtrinsicEra, Hash, Index, RuntimeVersion } from '../interfaces';
|
||||
import type { Codec, ISignerPayload, Registry, SignerPayloadJSON, SignerPayloadRaw } from '../types';
|
||||
import type { Codec, ISignerPayload, SignerPayloadJSON, SignerPayloadRaw } from '../types';
|
||||
|
||||
import { Compact, Option, Struct, Text, u8, Vec } from '@polkadot/types-codec';
|
||||
import { objectProperty, objectSpread, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Compact } from '../codec/Compact';
|
||||
import { Option } from '../codec/Option';
|
||||
import { Struct } from '../codec/Struct';
|
||||
import { Vec } from '../codec/Vec';
|
||||
import { Text } from '../primitive/Text';
|
||||
import { u8 } from '../primitive/U8';
|
||||
|
||||
export interface SignerPayloadType extends Codec {
|
||||
address: Address;
|
||||
blockHash: Hash;
|
||||
@@ -50,7 +45,7 @@ const knownTypes: Record<string, string> = {
|
||||
export class GenericSignerPayload extends Struct implements ISignerPayload, SignerPayloadType {
|
||||
readonly #extraTypes: Record<string, string>;
|
||||
|
||||
constructor (registry: Registry, value?: HexString | { [x: string]: unknown; } | Map<unknown, unknown> | unknown[]) {
|
||||
constructor (registry: CodecRegistry, value?: HexString | { [x: string]: unknown; } | Map<unknown, unknown> | unknown[]) {
|
||||
const extensionTypes = objectSpread<Record<string, string>>({}, registry.getSignedExtensionTypes(), registry.getSignedExtensionExtra());
|
||||
|
||||
super(registry, objectSpread<Record<string, string>>({}, extensionTypes, knownTypes), value);
|
||||
@@ -156,7 +151,7 @@ export class GenericSignerPayload extends Struct implements ISignerPayload, Sign
|
||||
const payload = this.toPayload();
|
||||
const data = u8aToHex(
|
||||
this.registry
|
||||
.createType('ExtrinsicPayload', payload, { version: payload.version })
|
||||
.createTypeUnsafe('ExtrinsicPayload', [payload, { version: payload.version }])
|
||||
// NOTE Explicitly pass the bare flag so the method is encoded un-prefixed (non-decodable, for signing only)
|
||||
.toU8a({ method: true })
|
||||
);
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { SignOptions } from '@polkadot/keyring/types';
|
||||
import type { IKeyringPair, Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { IKeyringPair } from '../types';
|
||||
|
||||
// a helper function for both types of payloads, Raw and metadata-known
|
||||
export function sign (registry: Registry, signerPair: IKeyringPair, u8a: Uint8Array, options?: SignOptions): Uint8Array {
|
||||
export function sign (registry: CodecRegistry, signerPair: IKeyringPair, u8a: Uint8Array, options?: SignOptions): Uint8Array {
|
||||
const encoded = u8a.length > 256
|
||||
? registry.hash(u8a)
|
||||
: u8a;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtrinsicSignatureV4 } from '../../interfaces/extrinsics';
|
||||
import type { Address, Call } from '../../interfaces/runtime';
|
||||
import type { ExtrinsicPayloadValue, IExtrinsicImpl, IKeyringPair, Registry, SignatureOptions } from '../../types';
|
||||
import type { ExtrinsicPayloadValue, IExtrinsicImpl, IKeyringPair, SignatureOptions } from '../../types';
|
||||
import type { ExtrinsicOptions } from '../types';
|
||||
|
||||
import { Struct } from '@polkadot/types-codec';
|
||||
import { isU8a } from '@polkadot/util';
|
||||
|
||||
import { Struct } from '../../codec/Struct';
|
||||
|
||||
export const EXTRINSIC_VERSION = 4;
|
||||
|
||||
export interface ExtrinsicValueV4 {
|
||||
@@ -24,7 +24,7 @@ export interface ExtrinsicValueV4 {
|
||||
* The third generation of compact extrinsics
|
||||
*/
|
||||
export class GenericExtrinsicV4 extends Struct implements IExtrinsicImpl {
|
||||
constructor (registry: Registry, value?: Uint8Array | ExtrinsicValueV4 | Call, { isSigned }: Partial<ExtrinsicOptions> = {}) {
|
||||
constructor (registry: CodecRegistry, value?: Uint8Array | ExtrinsicValueV4 | Call, { isSigned }: Partial<ExtrinsicOptions> = {}) {
|
||||
super(registry, {
|
||||
signature: 'ExtrinsicSignatureV4',
|
||||
// eslint-disable-next-line sort-keys
|
||||
@@ -33,15 +33,15 @@ export class GenericExtrinsicV4 extends Struct implements IExtrinsicImpl {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
public static decodeExtrinsic (registry: Registry, value?: Call | Uint8Array | ExtrinsicValueV4, isSigned = false): ExtrinsicValueV4 {
|
||||
public static decodeExtrinsic (registry: CodecRegistry, value?: Call | Uint8Array | ExtrinsicValueV4, isSigned = false): ExtrinsicValueV4 {
|
||||
if (value instanceof GenericExtrinsicV4) {
|
||||
return value;
|
||||
} else if (value instanceof registry.createClass('Call')) {
|
||||
return { method: value };
|
||||
} else if (value instanceof registry.createClassUnsafe('Call')) {
|
||||
return { method: value as Call };
|
||||
} else if (isU8a(value)) {
|
||||
// here we decode manually since we need to pull through the version information
|
||||
const signature = registry.createType('ExtrinsicSignatureV4', value, { isSigned });
|
||||
const method = registry.createType('Call', value.subarray(signature.encodedLength));
|
||||
const signature = registry.createTypeUnsafe<ExtrinsicSignatureV4>('ExtrinsicSignatureV4', [value, { isSigned }]);
|
||||
const method = registry.createTypeUnsafe<Call>('Call', [value.subarray(signature.encodedLength)]);
|
||||
|
||||
return {
|
||||
method,
|
||||
@@ -49,7 +49,7 @@ export class GenericExtrinsicV4 extends Struct implements IExtrinsicImpl {
|
||||
};
|
||||
}
|
||||
|
||||
return value || {};
|
||||
return (value as ExtrinsicValueV4) || {};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,19 +2,15 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { SignOptions } from '@polkadot/keyring/types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { ExtrinsicEra } from '../../interfaces/extrinsics';
|
||||
import type { AssetId, Balance, Hash, Index } from '../../interfaces/runtime';
|
||||
import type { ExtrinsicPayloadValue, IKeyringPair, Registry } from '../../types';
|
||||
import type { ExtrinsicPayloadValue, IKeyringPair } from '../../types';
|
||||
|
||||
import { Bytes, Compact, Enum, Option, Struct, u32 } from '@polkadot/types-codec';
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
|
||||
import { Compact } from '../../codec/Compact';
|
||||
import { Enum } from '../../codec/Enum';
|
||||
import { Option } from '../../codec/Option';
|
||||
import { Struct } from '../../codec/Struct';
|
||||
import { Bytes } from '../../primitive/Bytes';
|
||||
import { u32 } from '../../primitive/U32';
|
||||
import { sign } from '../util';
|
||||
|
||||
/**
|
||||
@@ -26,7 +22,7 @@ import { sign } from '../util';
|
||||
export class GenericExtrinsicPayloadV4 extends Struct {
|
||||
#signOptions: SignOptions;
|
||||
|
||||
constructor (registry: Registry, value?: ExtrinsicPayloadValue | Uint8Array | HexString) {
|
||||
constructor (registry: CodecRegistry, value?: ExtrinsicPayloadValue | Uint8Array | HexString) {
|
||||
super(registry, objectSpread(
|
||||
{ method: 'Bytes' },
|
||||
registry.getSignedExtensionTypes(),
|
||||
@@ -37,7 +33,7 @@ export class GenericExtrinsicPayloadV4 extends Struct {
|
||||
// this is an enum, in the case of AnySignature, this is a Hash only
|
||||
// (which may be 64 or 65 bytes)
|
||||
this.#signOptions = {
|
||||
withType: registry.createType('ExtrinsicSignature') instanceof Enum
|
||||
withType: registry.createTypeUnsafe('ExtrinsicSignature', []) instanceof Enum
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { EcdsaSignature, Ed25519Signature, ExtrinsicEra, ExtrinsicSignature, Sr25519Signature } from '../../interfaces/extrinsics';
|
||||
import type { Address, Balance, Call, Index } from '../../interfaces/runtime';
|
||||
import type { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, Registry, SignatureOptions } from '../../types';
|
||||
import type { ExtrinsicPayloadValue, IExtrinsicSignature, IKeyringPair, SignatureOptions } from '../../types';
|
||||
import type { ExtrinsicSignatureOptions } from '../types';
|
||||
|
||||
import { Compact, Struct } from '@polkadot/types-codec';
|
||||
import { assert, isU8a, isUndefined, objectProperties, objectSpread, stringify, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Compact } from '../../codec/Compact';
|
||||
import { Struct } from '../../codec/Struct';
|
||||
import { EMPTY_U8A, IMMORTAL_ERA } from '../constants';
|
||||
import { GenericExtrinsicPayloadV4 } from './ExtrinsicPayload';
|
||||
|
||||
// Ensure we have enough data for all types of signatures
|
||||
const FAKE_SIGNATURE = new Uint8Array(256).fill(1);
|
||||
|
||||
function toAddress (registry: Registry, address: Address | Uint8Array | string): Address {
|
||||
return registry.createType('Address', isU8a(address) ? u8aToHex(address) : address);
|
||||
function toAddress (registry: CodecRegistry, address: Address | Uint8Array | string): Address {
|
||||
return registry.createTypeUnsafe('Address', [isU8a(address) ? u8aToHex(address) : address]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,7 +29,7 @@ function toAddress (registry: Registry, address: Address | Uint8Array | string):
|
||||
export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSignature {
|
||||
#signKeys: string[];
|
||||
|
||||
constructor (registry: Registry, value?: GenericExtrinsicSignatureV4 | Uint8Array, { isSigned }: ExtrinsicSignatureOptions = {}) {
|
||||
constructor (registry: CodecRegistry, value?: GenericExtrinsicSignatureV4 | Uint8Array, { isSigned }: ExtrinsicSignatureOptions = {}) {
|
||||
const signTypes = registry.getSignedExtensionTypes();
|
||||
|
||||
super(
|
||||
@@ -143,7 +143,7 @@ export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSig
|
||||
public addSignature (signer: Address | Uint8Array | string, signature: Uint8Array | HexString, payload: ExtrinsicPayloadValue | Uint8Array | HexString): IExtrinsicSignature {
|
||||
return this._injectSignature(
|
||||
toAddress(this.registry, signer),
|
||||
this.registry.createType('ExtrinsicSignature', signature),
|
||||
this.registry.createTypeUnsafe('ExtrinsicSignature', [signature]),
|
||||
new GenericExtrinsicPayloadV4(this.registry, payload)
|
||||
);
|
||||
}
|
||||
@@ -168,11 +168,13 @@ export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSig
|
||||
public sign (method: Call, account: IKeyringPair, options: SignatureOptions): IExtrinsicSignature {
|
||||
assert(account && account.addressRaw, () => `Expected a valid keypair for signing, found ${stringify(account)}`);
|
||||
|
||||
const signer = toAddress(this.registry, account.addressRaw);
|
||||
const payload = this.createPayload(method, options);
|
||||
const signature = this.registry.createType('ExtrinsicSignature', payload.sign(account));
|
||||
|
||||
return this._injectSignature(signer, signature, payload);
|
||||
return this._injectSignature(
|
||||
toAddress(this.registry, account.addressRaw),
|
||||
this.registry.createTypeUnsafe('ExtrinsicSignature', [payload.sign(account)]),
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,11 +183,13 @@ export class GenericExtrinsicSignatureV4 extends Struct implements IExtrinsicSig
|
||||
public signFake (method: Call, address: Address | Uint8Array | string, options: SignatureOptions): IExtrinsicSignature {
|
||||
assert(address, () => `Expected a valid address for signing, found ${stringify(address)}`);
|
||||
|
||||
const signer = toAddress(this.registry, address);
|
||||
const payload = this.createPayload(method, options);
|
||||
const signature = this.registry.createType('ExtrinsicSignature', FAKE_SIGNATURE);
|
||||
|
||||
return this._injectSignature(signer, signature, payload);
|
||||
return this._injectSignature(
|
||||
toAddress(this.registry, address),
|
||||
this.registry.createTypeUnsafe('ExtrinsicSignature', [FAKE_SIGNATURE]),
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
import { Raw } from '@polkadot/types-codec';
|
||||
import jsonVec from '@polkadot/types-support/json/AccountIdVec.001.json';
|
||||
|
||||
import { Raw } from '../codec/Raw';
|
||||
import { TypeRegistry } from '../create';
|
||||
import { GenericAccountId as AccountId } from '.';
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyString, AnyU8a, Registry } from '../types';
|
||||
import type { AnyString, AnyU8a, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { U8aFixed } from '@polkadot/types-codec';
|
||||
import { assert, hexToU8a, isHex, isString, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { U8aFixed } from '../codec/U8aFixed';
|
||||
|
||||
/** @internal */
|
||||
function decodeAccountId (value?: AnyU8a | AnyString): Uint8Array {
|
||||
if (isU8a(value) || Array.isArray(value)) {
|
||||
@@ -31,7 +30,7 @@ function decodeAccountId (value?: AnyU8a | AnyString): Uint8Array {
|
||||
* just a Uint8Array wrapper with a fixed length.
|
||||
*/
|
||||
export class GenericAccountId extends U8aFixed {
|
||||
constructor (registry: Registry, value?: AnyU8a) {
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
const decoded = decodeAccountId(value);
|
||||
|
||||
// Part of stream containing >= 32 bytes or a all empty (defaults)
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, Registry } from '../types';
|
||||
import type { AnyNumber, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { u32 } from '@polkadot/types-codec';
|
||||
import { BN, bnToBn, isBigInt, isBn, isHex, isNumber, isU8a } from '@polkadot/util';
|
||||
import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { u32 } from '../primitive/U32';
|
||||
|
||||
const PREFIX_1BYTE = 0xef;
|
||||
const PREFIX_2BYTE = 0xfc;
|
||||
const PREFIX_4BYTE = 0xfd;
|
||||
@@ -37,7 +36,7 @@ function decodeAccountIndex (value: AnyNumber): BN | bigint | Uint8Array | numbe
|
||||
* for an Account. We extends from [[U32]] to provide the number-like properties.
|
||||
*/
|
||||
export class GenericAccountIndex extends u32 {
|
||||
constructor (registry: Registry, value: AnyNumber = new BN(0)) {
|
||||
constructor (registry: CodecRegistry, value: AnyNumber = new BN(0)) {
|
||||
super(registry, decodeAccountIndex(value));
|
||||
}
|
||||
|
||||
@@ -88,7 +87,7 @@ export class GenericAccountIndex extends u32 {
|
||||
}
|
||||
|
||||
// convert and compare
|
||||
return super.eq(this.registry.createType('AccountIndex', other));
|
||||
return super.eq(this.registry.createTypeUnsafe('AccountIndex', [other]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Vec } from '../codec/Vec';
|
||||
import type { Vec } from '@polkadot/types-codec';
|
||||
import type { CodecRegistry, IU8a } from '@polkadot/types-codec/types';
|
||||
import type { GenericExtrinsic } from '../extrinsic/Extrinsic';
|
||||
import type { CodecHash, Digest, DigestItem, Header } from '../interfaces/runtime';
|
||||
import type { AnyNumber, AnyU8a, Registry } from '../types';
|
||||
import type { Digest, DigestItem, Header } from '../interfaces/runtime';
|
||||
import type { AnyNumber, AnyU8a } from '../types';
|
||||
|
||||
import { Struct } from '../codec/Struct';
|
||||
import { Struct } from '@polkadot/types-codec';
|
||||
|
||||
export interface HeaderValue {
|
||||
digest?: Digest | { logs: DigestItem[] | string[] };
|
||||
@@ -27,7 +28,7 @@ export interface BlockValue {
|
||||
* A block encoded with header and extrinsics
|
||||
*/
|
||||
export class GenericBlock extends Struct {
|
||||
constructor (registry: Registry, value?: BlockValue | Uint8Array) {
|
||||
constructor (registry: CodecRegistry, value?: BlockValue | Uint8Array) {
|
||||
super(registry, {
|
||||
header: 'Header',
|
||||
// eslint-disable-next-line sort-keys
|
||||
@@ -38,7 +39,7 @@ export class GenericBlock extends Struct {
|
||||
/**
|
||||
* @description Encodes a content [[Hash]] for the block
|
||||
*/
|
||||
public get contentHash (): CodecHash {
|
||||
public get contentHash (): IU8a {
|
||||
return this.registry.hash(this.toU8a());
|
||||
}
|
||||
|
||||
@@ -52,7 +53,7 @@ export class GenericBlock extends Struct {
|
||||
/**
|
||||
* @description Block/header [[Hash]]
|
||||
*/
|
||||
public override get hash (): CodecHash {
|
||||
public override get hash (): IU8a {
|
||||
return this.header.hash;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry, IMethod } from '@polkadot/types-codec/types';
|
||||
import type { FunctionMetadataLatest } from '../interfaces/metadata';
|
||||
import type { AnyJson, AnyTuple, AnyU8a, ArgsDef, CallBase, CallFunction, Codec, IMethod, InterfaceTypes, Registry } from '../types';
|
||||
import type { AnyJson, AnyTuple, AnyU8a, ArgsDef, CallBase, CallFunction, Codec, InterfaceTypes, Registry } from '../types';
|
||||
|
||||
import { Struct, U8aFixed } from '@polkadot/types-codec';
|
||||
import { isHex, isObject, isU8a, objectSpread, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { Struct } from '../codec/Struct';
|
||||
import { U8aFixed } from '../codec/U8aFixed';
|
||||
|
||||
interface DecodeMethodInput {
|
||||
args: unknown;
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
@@ -27,7 +26,7 @@ interface DecodedMethod extends DecodeMethodInput {
|
||||
* @param meta - The function metadata used to get the definition.
|
||||
* @internal
|
||||
*/
|
||||
function getArgsDef (registry: Registry, meta: FunctionMetadataLatest): ArgsDef {
|
||||
function getArgsDef (registry: CodecRegistry, meta: FunctionMetadataLatest): ArgsDef {
|
||||
return meta.fields.reduce((result, { name, type }, index): ArgsDef => {
|
||||
result[name.unwrapOr(`param${index}`).toString()] = registry.createLookupType(type) as keyof InterfaceTypes;
|
||||
|
||||
@@ -36,7 +35,7 @@ function getArgsDef (registry: Registry, meta: FunctionMetadataLatest): ArgsDef
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeCallViaObject (registry: Registry, value: DecodedMethod, _meta?: FunctionMetadataLatest): DecodedMethod {
|
||||
function decodeCallViaObject (registry: CodecRegistry, value: DecodedMethod, _meta?: FunctionMetadataLatest): DecodedMethod {
|
||||
// we only pass args/methodsIndex out
|
||||
const { args, callIndex } = value;
|
||||
|
||||
@@ -47,7 +46,7 @@ function decodeCallViaObject (registry: Registry, value: DecodedMethod, _meta?:
|
||||
: callIndex;
|
||||
|
||||
// Find metadata with callIndex
|
||||
const meta = _meta || registry.findMetaCall(lookupIndex).meta;
|
||||
const meta = _meta || (registry as Registry).findMetaCall(lookupIndex).meta;
|
||||
|
||||
return {
|
||||
args,
|
||||
@@ -58,14 +57,14 @@ function decodeCallViaObject (registry: Registry, value: DecodedMethod, _meta?:
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeCallViaU8a (registry: Registry, value: Uint8Array, _meta?: FunctionMetadataLatest): DecodedMethod {
|
||||
function decodeCallViaU8a (registry: CodecRegistry, value: Uint8Array, _meta?: FunctionMetadataLatest): DecodedMethod {
|
||||
// We need 2 bytes for the callIndex
|
||||
const callIndex = new Uint8Array(2);
|
||||
|
||||
callIndex.set(value.subarray(0, 2), 0);
|
||||
|
||||
// Find metadata with callIndex
|
||||
const meta = _meta || registry.findMetaCall(callIndex).meta;
|
||||
const meta = _meta || (registry as Registry).findMetaCall(callIndex).meta;
|
||||
|
||||
return {
|
||||
args: value.subarray(2),
|
||||
@@ -86,7 +85,7 @@ function decodeCallViaU8a (registry: Registry, value: Uint8Array, _meta?: Functi
|
||||
* necessary.
|
||||
* @internal
|
||||
*/
|
||||
function decodeCall (registry: Registry, value: unknown | DecodedMethod | Uint8Array | string = new Uint8Array(), _meta?: FunctionMetadataLatest): DecodedMethod {
|
||||
function decodeCall (registry: CodecRegistry, value: unknown | DecodedMethod | Uint8Array | string = new Uint8Array(), _meta?: FunctionMetadataLatest): DecodedMethod {
|
||||
if (isU8a(value) || isHex(value)) {
|
||||
return decodeCallViaU8a(registry, u8aToU8a(value), _meta);
|
||||
} else if (isObject(value) && value.callIndex && value.args) {
|
||||
@@ -102,7 +101,7 @@ function decodeCall (registry: Registry, value: unknown | DecodedMethod | Uint8A
|
||||
* A wrapper around the `[sectionIndex, methodIndex]` value that uniquely identifies a method
|
||||
*/
|
||||
export class GenericCallIndex extends U8aFixed {
|
||||
constructor (registry: Registry, value?: AnyU8a) {
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
super(registry, value, 16);
|
||||
}
|
||||
}
|
||||
@@ -115,7 +114,7 @@ export class GenericCallIndex extends U8aFixed {
|
||||
export class GenericCall<A extends AnyTuple = AnyTuple> extends Struct implements CallBase<A> {
|
||||
protected _meta: FunctionMetadataLatest;
|
||||
|
||||
constructor (registry: Registry, value: unknown, meta?: FunctionMetadataLatest) {
|
||||
constructor (registry: CodecRegistry, value: unknown, meta?: FunctionMetadataLatest) {
|
||||
const decoded = decodeCall(registry, value, meta);
|
||||
|
||||
try {
|
||||
@@ -128,7 +127,7 @@ export class GenericCall<A extends AnyTuple = AnyTuple> extends Struct implement
|
||||
let method = 'unknown.unknown';
|
||||
|
||||
try {
|
||||
const c = registry.findMetaCall(decoded.callIndex);
|
||||
const c = (registry as Registry).findMetaCall(decoded.callIndex);
|
||||
|
||||
method = `${c.section}.${c.method}`;
|
||||
} catch (error) {
|
||||
@@ -187,14 +186,14 @@ export class GenericCall<A extends AnyTuple = AnyTuple> extends Struct implement
|
||||
* @description Returns the name of the method
|
||||
*/
|
||||
public get method (): string {
|
||||
return this.registry.findMetaCall(this.callIndex).method;
|
||||
return (this.registry as Registry).findMetaCall(this.callIndex).method;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the module containing the method
|
||||
*/
|
||||
public get section (): string {
|
||||
return this.registry.findMetaCall(this.callIndex).section;
|
||||
return (this.registry as Registry).findMetaCall(this.callIndex).section;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -211,7 +210,7 @@ export class GenericCall<A extends AnyTuple = AnyTuple> extends Struct implement
|
||||
let call: CallFunction | undefined;
|
||||
|
||||
try {
|
||||
call = this.registry.findMetaCall(this.callIndex);
|
||||
call = (this.registry as Registry).findMetaCall(this.callIndex);
|
||||
} catch (error) {
|
||||
// swallow
|
||||
}
|
||||
|
||||
@@ -1,35 +1,33 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { Codec } from '../types';
|
||||
|
||||
import { Json, Option, Text, u32, Vec } from '@polkadot/types-codec';
|
||||
import { isFunction, isNull, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { Json } from '../codec/Json';
|
||||
import { Option } from '../codec/Option';
|
||||
import { Vec } from '../codec/Vec';
|
||||
import { Text } from '../primitive/Text';
|
||||
import { u32 } from '../primitive/U32';
|
||||
|
||||
function createValue (registry: Registry, type: string, value: unknown, asArray = true): Option<Codec> {
|
||||
function createValue (registry: CodecRegistry, type: string, value: unknown, asArray = true): Option<Codec> {
|
||||
// We detect codec here as well - when found, generally this is constructed from itself
|
||||
if (value && isFunction((value as Option<Codec>).unwrapOrDefault)) {
|
||||
return value as Option<Codec>;
|
||||
}
|
||||
|
||||
return registry.createType(
|
||||
type as 'Option<u32>',
|
||||
asArray
|
||||
? isNull(value) || isUndefined(value)
|
||||
? null
|
||||
: Array.isArray(value)
|
||||
? value
|
||||
: [value]
|
||||
: value
|
||||
return registry.createTypeUnsafe<Option<u32>>(
|
||||
type,
|
||||
[
|
||||
asArray
|
||||
? isNull(value) || isUndefined(value)
|
||||
? null
|
||||
: Array.isArray(value)
|
||||
? value
|
||||
: [value]
|
||||
: value
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
function decodeValue (registry: Registry, key: string, value: unknown): unknown {
|
||||
function decodeValue (registry: CodecRegistry, key: string, value: unknown): unknown {
|
||||
return key === 'ss58Format'
|
||||
? createValue(registry, 'Option<u32>', value, false)
|
||||
: key === 'tokenDecimals'
|
||||
@@ -39,7 +37,7 @@ function decodeValue (registry: Registry, key: string, value: unknown): unknown
|
||||
: value;
|
||||
}
|
||||
|
||||
function decode (registry: Registry, value?: Map<string, unknown> | Record<string, unknown> | null): Record<string, unknown> {
|
||||
function decode (registry: CodecRegistry, value?: Map<string, unknown> | Record<string, unknown> | null): Record<string, unknown> {
|
||||
return (
|
||||
// allow decoding from a map as well (ourselves)
|
||||
value && isFunction((value as Map<string, unknown>).entries)
|
||||
@@ -50,14 +48,14 @@ function decode (registry: Registry, value?: Map<string, unknown> | Record<strin
|
||||
|
||||
return all;
|
||||
}, {
|
||||
ss58Format: registry.createType('Option<u32>'),
|
||||
tokenDecimals: registry.createType('Option<Vec<u32>>' as 'Vec<u32>'),
|
||||
tokenSymbol: registry.createType('Option<Vec<Text>>' as 'Vec<Text>')
|
||||
ss58Format: registry.createTypeUnsafe('Option<u32>', []),
|
||||
tokenDecimals: registry.createTypeUnsafe('Option<Vec<u32>>', []),
|
||||
tokenSymbol: registry.createTypeUnsafe('Option<Vec<Text>>', [])
|
||||
});
|
||||
}
|
||||
|
||||
export class GenericChainProperties extends Json {
|
||||
constructor (registry: Registry, value?: Map<string, unknown> | Record<string, unknown> | null) {
|
||||
constructor (registry: CodecRegistry, value?: Map<string, unknown> | Record<string, unknown> | null) {
|
||||
super(registry, decode(registry, value));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,39 +1,37 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AccountId } from '../interfaces/runtime';
|
||||
import type { AnyU8a, Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { AccountId, RawAuraPreDigest, RawBabePreDigestCompat } from '../interfaces';
|
||||
import type { AnyU8a } from '../types';
|
||||
|
||||
import { Bytes, U8aFixed, u32 } from '@polkadot/types-codec';
|
||||
import { BN, bnToU8a, isNumber, stringToU8a, u8aToHex, u8aToString } from '@polkadot/util';
|
||||
|
||||
import { U8aFixed } from '../codec/U8aFixed';
|
||||
import { Bytes } from '../primitive/Bytes';
|
||||
import { u32 } from '../primitive/U32';
|
||||
|
||||
export const CID_AURA = stringToU8a('aura');
|
||||
export const CID_BABE = stringToU8a('BABE');
|
||||
export const CID_GRPA = stringToU8a('FRNK');
|
||||
export const CID_POW = stringToU8a('pow_');
|
||||
|
||||
function getAuraAuthor (registry: Registry, bytes: Bytes, sessionValidators: AccountId[]): AccountId {
|
||||
function getAuraAuthor (registry: CodecRegistry, bytes: Bytes, sessionValidators: AccountId[]): AccountId {
|
||||
return sessionValidators[
|
||||
registry.createType('RawAuraPreDigest', bytes.toU8a(true))
|
||||
registry.createTypeUnsafe<RawAuraPreDigest>('RawAuraPreDigest', [bytes.toU8a(true)])
|
||||
.slotNumber
|
||||
.mod(new BN(sessionValidators.length))
|
||||
.toNumber()
|
||||
];
|
||||
}
|
||||
|
||||
function getBabeAuthor (registry: Registry, bytes: Bytes, sessionValidators: AccountId[]): AccountId {
|
||||
const digest = registry.createType('RawBabePreDigestCompat', bytes.toU8a(true));
|
||||
function getBabeAuthor (registry: CodecRegistry, bytes: Bytes, sessionValidators: AccountId[]): AccountId {
|
||||
const digest = registry.createTypeUnsafe<RawBabePreDigestCompat>('RawBabePreDigestCompat', [bytes.toU8a(true)]);
|
||||
|
||||
return sessionValidators[
|
||||
(digest.value as u32).toNumber()
|
||||
];
|
||||
}
|
||||
|
||||
function getBytesAsAuthor (registry: Registry, bytes: Bytes): AccountId {
|
||||
return registry.createType('AccountId', bytes);
|
||||
function getBytesAsAuthor (registry: CodecRegistry, bytes: Bytes): AccountId {
|
||||
return registry.createTypeUnsafe('AccountId', [bytes]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,7 +40,7 @@ function getBytesAsAuthor (registry: Registry, bytes: Bytes): AccountId {
|
||||
* A 4-byte identifier identifying the engine
|
||||
*/
|
||||
export class GenericConsensusEngineId extends U8aFixed {
|
||||
constructor (registry: Registry, value?: AnyU8a) {
|
||||
constructor (registry: CodecRegistry, value?: AnyU8a) {
|
||||
super(
|
||||
registry,
|
||||
isNumber(value)
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyJson, Codec, CodecClass, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { TypeDef } from '../create/types';
|
||||
import type { EventMetadataLatest } from '../interfaces/metadata';
|
||||
import type { EventId } from '../interfaces/system';
|
||||
import type { AnyJson, Codec, Constructor, IEvent, IEventData, InterfaceTypes, Registry } from '../types';
|
||||
import type { IEvent, IEventData, InterfaceTypes, LookupRegistry } from '../types';
|
||||
|
||||
import { Null, Struct, Tuple } from '@polkadot/types-codec';
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
|
||||
import { Struct } from '../codec/Struct';
|
||||
import { Tuple } from '../codec/Tuple';
|
||||
import { Null } from '../primitive/Null';
|
||||
|
||||
interface Decoded {
|
||||
DataType: Constructor<Null> | Constructor<GenericEventData>;
|
||||
DataType: CodecClass<Null> | CodecClass<GenericEventData>;
|
||||
value?: {
|
||||
index: Uint8Array;
|
||||
data: Uint8Array;
|
||||
@@ -21,7 +19,7 @@ interface Decoded {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeEvent (registry: Registry, value?: Uint8Array): Decoded {
|
||||
function decodeEvent (registry: CodecRegistry, value?: Uint8Array): Decoded {
|
||||
if (!value || !value.length) {
|
||||
return { DataType: Null };
|
||||
}
|
||||
@@ -51,7 +49,7 @@ export class GenericEventData extends Tuple implements IEventData {
|
||||
|
||||
readonly #typeDef: TypeDef[];
|
||||
|
||||
constructor (registry: Registry, value: Uint8Array, meta: EventMetadataLatest, section = '<unknown>', method = '<unknown>') {
|
||||
constructor (registry: CodecRegistry, value: Uint8Array, meta: EventMetadataLatest, section = '<unknown>', method = '<unknown>') {
|
||||
const fields = meta?.fields || [];
|
||||
|
||||
super(registry, fields.map(({ type }) => registry.createLookupType(type) as keyof InterfaceTypes), value);
|
||||
@@ -59,7 +57,7 @@ export class GenericEventData extends Tuple implements IEventData {
|
||||
this.#meta = meta;
|
||||
this.#method = method;
|
||||
this.#section = section;
|
||||
this.#typeDef = fields.map(({ type }) => registry.lookup.getTypeDef(type));
|
||||
this.#typeDef = fields.map(({ type }) => (registry as LookupRegistry).lookup.getTypeDef(type));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,7 +98,7 @@ export class GenericEventData extends Tuple implements IEventData {
|
||||
export class GenericEvent extends Struct implements IEvent<Codec[]> {
|
||||
// Currently we _only_ decode from Uint8Array, since we expect it to
|
||||
// be used via EventRecord
|
||||
constructor (registry: Registry, _value?: Uint8Array) {
|
||||
constructor (registry: CodecRegistry, _value?: Uint8Array) {
|
||||
const { DataType, value } = decodeEvent(registry, _value);
|
||||
|
||||
super(registry, {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Registry } from '../types';
|
||||
|
||||
import { Base } from '@polkadot/types-codec';
|
||||
import { isBigInt, isBn, isHex, isNumber, isU8a, u8aConcat, u8aToBn, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { Base } from '../codec/Base';
|
||||
import { GenericAccountId } from './AccountId';
|
||||
import { GenericAccountIndex } from './AccountIndex';
|
||||
|
||||
@@ -18,27 +18,27 @@ type AnyAddress = bigint | BN | GenericLookupSource | GenericAccountId | Generic
|
||||
export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]);
|
||||
|
||||
/** @internal */
|
||||
function decodeString (registry: Registry, value: string): GenericAccountId | GenericAccountIndex {
|
||||
function decodeString (registry: CodecRegistry, value: string): GenericAccountId | GenericAccountIndex {
|
||||
const decoded = decodeAddress(value);
|
||||
|
||||
return decoded.length === 32
|
||||
? registry.createType('AccountId', decoded)
|
||||
: registry.createType('AccountIndex', u8aToBn(decoded, true));
|
||||
? registry.createTypeUnsafe('AccountId', [decoded])
|
||||
: registry.createTypeUnsafe('AccountIndex', [u8aToBn(decoded, true)]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeU8a (registry: Registry, value: Uint8Array): GenericAccountId | GenericAccountIndex {
|
||||
function decodeU8a (registry: CodecRegistry, value: Uint8Array): GenericAccountId | GenericAccountIndex {
|
||||
// This allows us to instantiate an address with a raw publicKey. Do this first before
|
||||
// we checking the first byte, otherwise we may split an already-existent valid address
|
||||
if (value.length === 32) {
|
||||
return registry.createType('AccountId', value);
|
||||
return registry.createTypeUnsafe('AccountId', [value]);
|
||||
} else if (value[0] === 0xff) {
|
||||
return registry.createType('AccountId', value.subarray(1));
|
||||
return registry.createTypeUnsafe('AccountId', [value.subarray(1)]);
|
||||
}
|
||||
|
||||
const [offset, length] = GenericAccountIndex.readLength(value);
|
||||
|
||||
return registry.createType('AccountIndex', u8aToBn(value.subarray(offset, offset + length), true));
|
||||
return registry.createTypeUnsafe('AccountIndex', [u8aToBn(value.subarray(offset, offset + length), true)]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,18 +50,18 @@ function decodeU8a (registry: Registry, value: Uint8Array): GenericAccountId | G
|
||||
* is encoded as `[ <prefix-byte>, ...publicKey/...bytes ]` as per spec
|
||||
*/
|
||||
export class GenericLookupSource extends Base<GenericAccountId | GenericAccountIndex> {
|
||||
constructor (registry: Registry, value: AnyAddress = new Uint8Array()) {
|
||||
constructor (registry: CodecRegistry, value: AnyAddress = new Uint8Array()) {
|
||||
super(registry, GenericLookupSource._decodeAddress(registry, value));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
private static _decodeAddress (registry: Registry, value: AnyAddress): GenericAccountId | GenericAccountIndex {
|
||||
private static _decodeAddress (registry: CodecRegistry, value: AnyAddress): GenericAccountId | GenericAccountIndex {
|
||||
return value instanceof GenericLookupSource
|
||||
? value._raw
|
||||
: value instanceof GenericAccountId || value instanceof GenericAccountIndex
|
||||
? value
|
||||
: isBn(value) || isNumber(value) || isBigInt(value)
|
||||
? registry.createType('AccountIndex', value)
|
||||
? registry.createTypeUnsafe('AccountIndex', [value])
|
||||
: Array.isArray(value) || isHex(value) || isU8a(value)
|
||||
? decodeU8a(registry, u8aToU8a(value))
|
||||
: decodeString(registry, value);
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Registry } from '../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { Enum } from '@polkadot/types-codec';
|
||||
import { isBn, isNumber, isString, isU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { Enum } from '../codec/Enum';
|
||||
import { GenericAccountId } from './AccountId';
|
||||
import { GenericAccountIndex } from './AccountIndex';
|
||||
|
||||
function decodeU8a (registry: Registry, u8a: Uint8Array): unknown {
|
||||
function decodeU8a (registry: CodecRegistry, u8a: Uint8Array): unknown {
|
||||
if ([0, 32].includes(u8a.length)) {
|
||||
return { Id: u8a };
|
||||
} else if (u8a.length === 20) {
|
||||
return { Address20: u8a };
|
||||
} else if (u8a.length <= 8) {
|
||||
return { Index: registry.createType('AccountIndex', u8a).toNumber() };
|
||||
return { Index: registry.createTypeUnsafe<GenericAccountIndex>('AccountIndex', [u8a]).toNumber() };
|
||||
}
|
||||
|
||||
return u8a;
|
||||
}
|
||||
|
||||
function decodeMultiAny (registry: Registry, value?: unknown): unknown {
|
||||
function decodeMultiAny (registry: CodecRegistry, value?: unknown): unknown {
|
||||
if (value instanceof GenericAccountId) {
|
||||
return { Id: value };
|
||||
} else if (isU8a(value)) {
|
||||
@@ -40,7 +40,7 @@ function decodeMultiAny (registry: Registry, value?: unknown): unknown {
|
||||
}
|
||||
|
||||
export class GenericMultiAddress extends Enum {
|
||||
constructor (registry: Registry, value?: unknown) {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
super(registry, {
|
||||
Id: 'AccountId',
|
||||
Index: 'Compact<AccountIndex>',
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { Conviction } from '../interfaces/democracy';
|
||||
import type { AllConvictions } from '../interfaces/democracy/definitions';
|
||||
import type { AnyJson, ArrayElementType, Registry } from '../types';
|
||||
import type { AnyJson, ArrayElementType } from '../types';
|
||||
|
||||
import { Bool, U8aFixed } from '@polkadot/types-codec';
|
||||
import { isBoolean, isNumber, isU8a, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { U8aFixed } from '../codec/U8aFixed';
|
||||
import { bool as Bool } from '../primitive/Bool';
|
||||
|
||||
interface VoteType {
|
||||
aye: boolean;
|
||||
conviction?: number | ArrayElementType<typeof AllConvictions>;
|
||||
@@ -39,15 +38,19 @@ function decodeVoteU8a (value: Uint8Array): Uint8Array {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeVoteType (registry: Registry, value: VoteType): Uint8Array {
|
||||
const vote = new Bool(registry, value.aye).isTrue ? AYE_BITS : NAY_BITS;
|
||||
const conviction = registry.createType('Conviction', value.conviction || DEF_CONV);
|
||||
|
||||
return new Uint8Array([vote | conviction.index]);
|
||||
function decodeVoteType (registry: CodecRegistry, value: VoteType): Uint8Array {
|
||||
return new Uint8Array([
|
||||
(
|
||||
new Bool(registry, value.aye).isTrue
|
||||
? AYE_BITS
|
||||
: NAY_BITS
|
||||
) |
|
||||
registry.createTypeUnsafe<Conviction>('Conviction', [value.conviction || DEF_CONV]).index
|
||||
]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function decodeVote (registry: Registry, value?: InputTypes): Uint8Array {
|
||||
function decodeVote (registry: CodecRegistry, value?: InputTypes): Uint8Array {
|
||||
if (isU8a(value)) {
|
||||
return decodeVoteU8a(value);
|
||||
} else if (isUndefined(value) || value instanceof Boolean || isBoolean(value)) {
|
||||
@@ -69,7 +72,7 @@ export class GenericVote extends U8aFixed {
|
||||
|
||||
#conviction: Conviction;
|
||||
|
||||
constructor (registry: Registry, value?: InputTypes) {
|
||||
constructor (registry: CodecRegistry, value?: InputTypes) {
|
||||
// decoded is just 1 byte
|
||||
// Aye: Most Significant Bit
|
||||
// Conviction: 0000 - 0101
|
||||
@@ -78,7 +81,7 @@ export class GenericVote extends U8aFixed {
|
||||
super(registry, decoded, 8);
|
||||
|
||||
this.#aye = (decoded[0] & AYE_BITS) === AYE_BITS;
|
||||
this.#conviction = this.registry.createType('Conviction', decoded[0] & CON_MASK);
|
||||
this.#conviction = this.registry.createTypeUnsafe('Conviction', [decoded[0] & CON_MASK]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyNumber, Registry } from '../types';
|
||||
import type { AnyNumber, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { U32 } from '@polkadot/types-codec';
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { U32 } from '../primitive';
|
||||
|
||||
export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding
|
||||
|
||||
export class MagicNumber extends U32 {
|
||||
constructor (registry: Registry, value?: AnyNumber) {
|
||||
constructor (registry: CodecRegistry, value?: AnyNumber) {
|
||||
super(registry, value);
|
||||
|
||||
if (!this.isEmpty) {
|
||||
assert(this.eq(MAGIC_NUMBER), () => `MagicNumber mismatch: expected ${registry.createType('u32', MAGIC_NUMBER).toHex()}, found ${this.toHex()}`);
|
||||
assert(this.eq(MAGIC_NUMBER), () => `MagicNumber mismatch: expected ${registry.createTypeUnsafe('u32', [MAGIC_NUMBER]).toHex()}, found ${this.toHex()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Registry } from '../types';
|
||||
|
||||
import { isHex, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
@@ -22,7 +22,7 @@ function toU8a (value: Uint8Array | HexString): Uint8Array {
|
||||
: value;
|
||||
}
|
||||
|
||||
function decodeU8a (registry: Registry, value: Uint8Array): MetadataVersioned {
|
||||
function decodeU8a (registry: CodecRegistry, value: Uint8Array): MetadataVersioned {
|
||||
try {
|
||||
return new MetadataVersioned(registry, value);
|
||||
} catch (error) {
|
||||
@@ -45,7 +45,7 @@ function decodeU8a (registry: Registry, value: Uint8Array): MetadataVersioned {
|
||||
* The versioned runtime metadata as a decoded structure
|
||||
*/
|
||||
export class Metadata extends MetadataVersioned {
|
||||
constructor (registry: Registry, value?: Uint8Array | HexString | Map<string, unknown> | Record<string, unknown>) {
|
||||
constructor (registry: CodecRegistry, value?: Uint8Array | HexString | Map<string, unknown> | Record<string, unknown>) {
|
||||
super(
|
||||
registry,
|
||||
isU8a(value) || isHex(value)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11, MetadataV12, MetadataV13, MetadataV14 } from '../interfaces/metadata';
|
||||
import type { AnyJson, Registry } from '../types';
|
||||
import type { AnyJson } from '../types';
|
||||
|
||||
import { Struct } from '@polkadot/types-codec';
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { Struct } from '../codec';
|
||||
import { toV10 } from './v9/toV10';
|
||||
import { toV11 } from './v10/toV11';
|
||||
import { toV12 } from './v11/toV12';
|
||||
@@ -30,7 +31,7 @@ const LATEST_VERSION = 14;
|
||||
export class MetadataVersioned extends Struct {
|
||||
readonly #converted = new Map<MetaVersions, MetaMapped>();
|
||||
|
||||
constructor (registry: Registry, value?: unknown) {
|
||||
constructor (registry: CodecRegistry, value?: unknown) {
|
||||
// console.time('MetadataVersioned')
|
||||
|
||||
super(registry, {
|
||||
@@ -47,7 +48,7 @@ export class MetadataVersioned extends Struct {
|
||||
return this.version === version;
|
||||
};
|
||||
|
||||
#getVersion = <T extends MetaMapped, F extends MetaMapped>(version: MetaVersions, fromPrev: (registry: Registry, input: F, metaVersion: number) => T): T => {
|
||||
#getVersion = <T extends MetaMapped, F extends MetaMapped>(version: MetaVersions, fromPrev: (registry: CodecRegistry, input: F, metaVersion: number) => T): T => {
|
||||
const asCurr = `asV${version}` as MetaAsX;
|
||||
const asPrev = version === 'latest'
|
||||
? `asV${LATEST_VERSION}` as MetaAsX
|
||||
@@ -77,7 +78,7 @@ export class MetadataVersioned extends Struct {
|
||||
public get asCallsOnly (): MetadataVersioned {
|
||||
return new MetadataVersioned(this.registry, {
|
||||
magicNumber: this.magicNumber,
|
||||
metadata: this.registry.createType('MetadataAll', toCallsOnly(this.registry, this.asLatest), LATEST_VERSION)
|
||||
metadata: this.registry.createTypeUnsafe('MetadataAll', [toCallsOnly(this.registry, this.asLatest), LATEST_VERSION])
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Vec } from '../../codec';
|
||||
import type { Vec } from '@polkadot/types-codec';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { PortableType } from '../../interfaces/metadata';
|
||||
import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDefArray, SiTypeDefBitSequence, SiTypeDefCompact, SiTypeDefComposite, SiTypeDefSequence, SiTypeDefTuple, SiTypeDefVariant, SiTypeParameter, SiVariant } from '../../interfaces/scaleInfo';
|
||||
import type { Text, Type } from '../../primitive';
|
||||
import type { Registry, TypeDef } from '../../types';
|
||||
import type { ILookup, TypeDef } from '../../types';
|
||||
|
||||
import { sanitize, Struct } from '@polkadot/types-codec';
|
||||
import { assert, isNumber, isString, objectSpread, stringCamelCase, stringify, stringPascalCase } from '@polkadot/util';
|
||||
|
||||
import { Struct } from '../../codec/Struct';
|
||||
import { withTypeString } from '../../create/encodeTypes';
|
||||
import { getTypeDef } from '../../create/getTypeDef';
|
||||
import { sanitize } from '../../create/sanitize';
|
||||
import { u32 } from '../../primitive';
|
||||
import { TypeDefInfo } from '../../types';
|
||||
import { assertUnreachable } from './util';
|
||||
|
||||
@@ -324,12 +325,12 @@ function extractTypeInfo (lookup: PortableRegistry, portable: PortableType[]): [
|
||||
return [types, lookups, names, params];
|
||||
}
|
||||
|
||||
export class PortableRegistry extends Struct {
|
||||
export class PortableRegistry extends Struct implements ILookup {
|
||||
#names: Record<number, string>;
|
||||
#typeDefs: Record<number, TypeDef> = {};
|
||||
#types: Record<number, PortableType>;
|
||||
|
||||
constructor (registry: Registry, value?: Uint8Array) {
|
||||
constructor (registry: CodecRegistry, value?: Uint8Array) {
|
||||
// console.time('PortableRegistry')
|
||||
|
||||
super(registry, {
|
||||
@@ -559,7 +560,7 @@ export class PortableRegistry extends Struct {
|
||||
|
||||
return withTypeString(this.registry, {
|
||||
info: TypeDefInfo.Set,
|
||||
length: this.registry.createType(this.registry.createLookupType(fields[0].type) as 'u32').bitLength(),
|
||||
length: this.registry.createTypeUnsafe<u32>(this.registry.createLookupType(fields[0].type), []).bitLength(),
|
||||
sub: this.getSiType(params[0].type.unwrap()).def.asVariant.variants.map(({ index, name }): TypeDef => ({
|
||||
// This will be an issue > 2^53 - 1 ... don't have those (yet)
|
||||
index: index.toNumber(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { MetadataLatest, PalletConstantMetadataLatest } from '../../../interfaces';
|
||||
import type { Registry } from '../../../types';
|
||||
import type { ConstantCodec, Constants } from '../types';
|
||||
|
||||
import { hexToU8a, lazyMethod, lazyMethods, stringCamelCase } from '@polkadot/util';
|
||||
@@ -11,7 +11,7 @@ import { objectNameToCamel } from '../util';
|
||||
|
||||
/** @internal */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function decorateConstants (registry: Registry, { pallets }: MetadataLatest, _version: number): Constants {
|
||||
export function decorateConstants (registry: CodecRegistry, { pallets }: MetadataLatest, _version: number): Constants {
|
||||
const result: Constants = {};
|
||||
|
||||
for (let i = 0; i < pallets.length; i++) {
|
||||
@@ -23,11 +23,11 @@ export function decorateConstants (registry: Registry, { pallets }: MetadataLate
|
||||
{},
|
||||
constants,
|
||||
(constant: PalletConstantMetadataLatest): ConstantCodec => {
|
||||
const codec = registry.createTypeUnsafe(registry.createLookupType(constant.type), [hexToU8a(constant.value.toHex())]) as ConstantCodec;
|
||||
const codec = registry.createTypeUnsafe(registry.createLookupType(constant.type), [hexToU8a(constant.value.toHex())]);
|
||||
|
||||
(codec as unknown as Record<string, unknown>).meta = constant;
|
||||
|
||||
return codec;
|
||||
return codec as ConstantCodec;
|
||||
},
|
||||
objectNameToCamel
|
||||
)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Text } from '@polkadot/types-codec';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { DispatchErrorModule, MetadataLatest, SiField, SiVariant } from '../../../interfaces';
|
||||
import type { PortableRegistry } from '../../../metadata';
|
||||
import type { Text, u8 } from '../../../primitive';
|
||||
import type { Registry } from '../../../types';
|
||||
import type { u8 } from '../../../primitive';
|
||||
import type { Errors, IsError } from '../types';
|
||||
|
||||
import { lazyMethod, objectSpread, stringCamelCase } from '@polkadot/util';
|
||||
@@ -28,7 +29,7 @@ export function variantToMeta (lookup: PortableRegistry, variant: SiVariant): It
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function decorateErrors (registry: Registry, { lookup, pallets }: MetadataLatest, version: number): Errors {
|
||||
export function decorateErrors (registry: CodecRegistry, { lookup, pallets }: MetadataLatest, version: number): Errors {
|
||||
const result: Errors = {};
|
||||
|
||||
for (let i = 0; i < pallets.length; i++) {
|
||||
@@ -42,7 +43,7 @@ export function decorateErrors (registry: Registry, { lookup, pallets }: Metadat
|
||||
is: ({ error, index }: DispatchErrorModule) =>
|
||||
index.eq(sectionIndex) &&
|
||||
error.eq(variant.index),
|
||||
meta: registry.createType('ErrorMetadataLatest', variantToMeta(lookup, variant))
|
||||
meta: registry.createTypeUnsafe('ErrorMetadataLatest', [variantToMeta(lookup, variant)])
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { MetadataLatest, PalletMetadataLatest, SiVariant } from '../../../interfaces';
|
||||
import type { AnyTuple, IEvent, Registry } from '../../../types';
|
||||
import type { AnyTuple, IEvent } from '../../../types';
|
||||
import type { Events, IsEvent } from '../types';
|
||||
|
||||
import { lazyMethod, stringCamelCase } from '@polkadot/util';
|
||||
@@ -16,7 +17,7 @@ export function filterEventsSome ({ events }: PalletMetadataLatest): boolean {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function decorateEvents (registry: Registry, { lookup, pallets }: MetadataLatest, version: number): Events {
|
||||
export function decorateEvents (registry: CodecRegistry, { lookup, pallets }: MetadataLatest, version: number): Events {
|
||||
const result: Events = {};
|
||||
const filtered = pallets.filter(filterEventsSome);
|
||||
|
||||
@@ -29,7 +30,7 @@ export function decorateEvents (registry: Registry, { lookup, pallets }: Metadat
|
||||
is: <T extends AnyTuple> (eventRecord: IEvent<AnyTuple>): eventRecord is IEvent<T> =>
|
||||
sectionIndex === eventRecord.index[0] &&
|
||||
variant.index.eq(eventRecord.index[1]),
|
||||
meta: registry.createType('EventMetadataLatest', variantToMeta(lookup, variant))
|
||||
meta: registry.createTypeUnsafe('EventMetadataLatest', [variantToMeta(lookup, variant)])
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { Call, FunctionMetadataLatest } from '../../../interfaces';
|
||||
import type { AnyJson, AnyTuple, CallFunction, IMethod, Registry } from '../../../types';
|
||||
import type { AnyJson, AnyTuple, CallFunction, IMethod } from '../../../types';
|
||||
|
||||
import { assert, stringCamelCase } from '@polkadot/util';
|
||||
|
||||
@@ -11,14 +12,14 @@ function isTx <A extends AnyTuple> (tx: IMethod<AnyTuple>, callIndex: Uint8Array
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function createUnchecked (registry: Registry, section: string, callIndex: Uint8Array, callMetadata: FunctionMetadataLatest): CallFunction {
|
||||
export function createUnchecked (registry: CodecRegistry, section: string, callIndex: Uint8Array, callMetadata: FunctionMetadataLatest): CallFunction {
|
||||
const expectedArgs = callMetadata.fields;
|
||||
const funcName = stringCamelCase(callMetadata.name);
|
||||
|
||||
const extrinsicFn = (...args: any[]): Call => {
|
||||
assert(expectedArgs.length === args.length, () => `Extrinsic ${section}.${funcName} expects ${expectedArgs.length} arguments, got ${args.length}.`);
|
||||
|
||||
return registry.createType('Call', { args, callIndex }, callMetadata);
|
||||
return registry.createTypeUnsafe('Call', [{ args, callIndex }, callMetadata]);
|
||||
};
|
||||
|
||||
extrinsicFn.is = <A extends AnyTuple> (tx: IMethod<AnyTuple>): tx is IMethod<A> =>
|
||||
@@ -31,5 +32,5 @@ export function createUnchecked (registry: Registry, section: string, callIndex:
|
||||
extrinsicFn.toJSON = (): AnyJson =>
|
||||
callMetadata.toJSON();
|
||||
|
||||
return extrinsicFn as CallFunction;
|
||||
return extrinsicFn as unknown as CallFunction;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { MetadataLatest, PalletMetadataLatest, SiVariant } from '../../../interfaces';
|
||||
import type { PortableRegistry } from '../../../metadata';
|
||||
import type { CallFunction, Registry } from '../../../types';
|
||||
import type { CallFunction } from '../../../types';
|
||||
import type { Extrinsics } from '../types';
|
||||
|
||||
import { lazyMethod, objectSpread, stringCamelCase } from '@polkadot/util';
|
||||
@@ -17,7 +18,7 @@ export function filterCallsSome ({ calls }: PalletMetadataLatest): boolean {
|
||||
return calls.isSome;
|
||||
}
|
||||
|
||||
export function createCallFunction (registry: Registry, lookup: PortableRegistry, variant: SiVariant, sectionName: string, sectionIndex: number): CallFunction {
|
||||
export function createCallFunction (registry: CodecRegistry, lookup: PortableRegistry, variant: SiVariant, sectionName: string, sectionIndex: number): CallFunction {
|
||||
const { fields, index } = variant;
|
||||
const args = new Array<Record<string, unknown>>(fields.length);
|
||||
|
||||
@@ -39,12 +40,12 @@ export function createCallFunction (registry: Registry, lookup: PortableRegistry
|
||||
registry,
|
||||
sectionName,
|
||||
new Uint8Array([sectionIndex, index.toNumber()]),
|
||||
registry.createType('FunctionMetadataLatest', objectSpread({ args }, variant))
|
||||
registry.createTypeUnsafe('FunctionMetadataLatest', [objectSpread({ args }, variant)])
|
||||
);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function decorateExtrinsics (registry: Registry, { lookup, pallets }: MetadataLatest, version: number): Extrinsics {
|
||||
export function decorateExtrinsics (registry: CodecRegistry, { lookup, pallets }: MetadataLatest, version: number): Extrinsics {
|
||||
const result: Extrinsics = {};
|
||||
const filtered = pallets.filter(filterCallsSome);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Registry } from '../../types';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { DecoratedMeta } from './types';
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
@@ -16,7 +16,7 @@ import { decorateStorage } from './storage';
|
||||
/**
|
||||
* Expands the metadata by decoration into consts, query and tx sections
|
||||
*/
|
||||
export function expandMetadata (registry: Registry, metadata: Metadata): DecoratedMeta {
|
||||
export function expandMetadata (registry: CodecRegistry, metadata: Metadata): DecoratedMeta {
|
||||
assert(metadata instanceof Metadata, 'You need to pass a valid Metadata instance to Decorated');
|
||||
|
||||
const latest = metadata.asLatest;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry, ICompact, INumber } from '@polkadot/types-codec/types';
|
||||
import type { StorageEntryMetadataLatest, StorageHasher } from '../../../interfaces/metadata';
|
||||
import type { SiLookupTypeId } from '../../../interfaces/scaleInfo';
|
||||
import type { StorageEntry } from '../../../primitive/types';
|
||||
import type { Registry } from '../../../types';
|
||||
import type { LookupRegistry } from '../../../types';
|
||||
|
||||
import { Raw } from '@polkadot/types-codec';
|
||||
import { assert, compactAddLength, compactStripLength, isUndefined, objectSpread, stringCamelCase, stringLowerFirst, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
import { xxhashAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { Raw } from '../../../codec';
|
||||
import { StorageKey } from '../../../primitive';
|
||||
import { getHasher } from './getHasher';
|
||||
|
||||
@@ -36,7 +36,7 @@ interface IterFn {
|
||||
interface RawArgs {
|
||||
args: unknown[];
|
||||
hashers: StorageHasher[];
|
||||
keys: SiLookupTypeId[];
|
||||
keys: ICompact<INumber>[];
|
||||
}
|
||||
|
||||
export const NO_RAW_ARGS: RawArgs = {
|
||||
@@ -46,12 +46,12 @@ export const NO_RAW_ARGS: RawArgs = {
|
||||
};
|
||||
|
||||
/** @internal */
|
||||
export function createKeyRaw (registry: Registry, itemFn: CreateItemBase, { args, hashers, keys }: RawArgs): Uint8Array {
|
||||
export function createKeyRaw (registry: CodecRegistry, itemFn: CreateItemBase, { args, hashers, keys }: RawArgs): Uint8Array {
|
||||
const extra = new Array<Uint8Array>(keys.length);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
extra[i] = getHasher(hashers[i])(
|
||||
registry.createType(registry.createLookupType(keys[i]), args[i]).toU8a()
|
||||
registry.createTypeUnsafe(registry.createLookupType(keys[i]), [args[i]]).toU8a()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ function filterDefined (a: unknown): boolean {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function createKey (registry: Registry, itemFn: CreateItemFn, { args, hashers, keys }: RawArgs): Uint8Array {
|
||||
function createKey (registry: CodecRegistry, itemFn: CreateItemFn, { args, hashers, keys }: RawArgs): Uint8Array {
|
||||
const { method, section } = itemFn;
|
||||
|
||||
assert(Array.isArray(args), () => `Call to ${stringCamelCase(section || 'unknown')}.${stringCamelCase(method || 'unknown')} needs ${keys.length} arguments`);
|
||||
@@ -81,7 +81,7 @@ function createKey (registry: Registry, itemFn: CreateItemFn, { args, hashers, k
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function createWStorageFn (registry: Registry, itemFn: CreateItemFn, options: CreateItemOptions): (...args: unknown[]) => Uint8Array {
|
||||
function createWStorageFn (registry: CodecRegistry, itemFn: CreateItemFn, options: CreateItemOptions): (...args: unknown[]) => Uint8Array {
|
||||
const { meta: { type } } = itemFn;
|
||||
let cacheKey: Uint8Array | null = null;
|
||||
|
||||
@@ -104,12 +104,12 @@ function createWStorageFn (registry: Registry, itemFn: CreateItemFn, options: Cr
|
||||
|
||||
return hashers.length === 1
|
||||
? createKey(registry, itemFn, { args, hashers, keys: [key] })
|
||||
: createKey(registry, itemFn, { args, hashers, keys: registry.lookup.getSiType(key).def.asTuple });
|
||||
: createKey(registry, itemFn, { args, hashers, keys: (registry as LookupRegistry).lookup.getSiType(key).def.asTuple });
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function createWithMeta (registry: Registry, itemFn: CreateItemFn, options: CreateItemOptions): StorageEntry {
|
||||
function createWithMeta (registry: CodecRegistry, itemFn: CreateItemFn, options: CreateItemOptions): StorageEntry {
|
||||
const { meta, method, prefix, section } = itemFn;
|
||||
const storageFn = createWStorageFn(registry, itemFn, options) as StorageEntry;
|
||||
|
||||
@@ -126,26 +126,26 @@ function createWithMeta (registry: Registry, itemFn: CreateItemFn, options: Crea
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function extendHeadMeta (registry: Registry, { meta: { docs, name, type }, section }: CreateItemFn, { method }: StorageEntry, iterFn: (...args: unknown[]) => Raw): (...args: unknown[]) => StorageKey {
|
||||
function extendHeadMeta (registry: CodecRegistry, { meta: { docs, name, type }, section }: CreateItemFn, { method }: StorageEntry, iterFn: (...args: unknown[]) => Raw): (...args: unknown[]) => StorageKey {
|
||||
const outputType = registry.createLookupType(type.asMap.key);
|
||||
|
||||
// metadata with a fallback value using the type of the key, the normal
|
||||
// meta fallback only applies to actual entry values, create one for head
|
||||
(iterFn as IterFn).meta = registry.createType('StorageEntryMetadataLatest', {
|
||||
(iterFn as IterFn).meta = registry.createTypeUnsafe('StorageEntryMetadataLatest', [{
|
||||
docs,
|
||||
fallback: registry.createType('Bytes'),
|
||||
modifier: registry.createType('StorageEntryModifierLatest', 1), // required
|
||||
fallback: registry.createTypeUnsafe('Bytes', []),
|
||||
modifier: registry.createTypeUnsafe('StorageEntryModifierLatest', [1]), // required
|
||||
name,
|
||||
// FIXME???
|
||||
type: registry.createType('StorageEntryTypeLatest', outputType, 0)
|
||||
});
|
||||
type: registry.createTypeUnsafe('StorageEntryTypeLatest', [outputType, 0])
|
||||
}]);
|
||||
|
||||
return (...args: unknown[]) =>
|
||||
registry.createType('StorageKey', iterFn(...args), { method, section });
|
||||
registry.createTypeUnsafe('StorageKey', [iterFn(...args), { method, section }]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn: StorageEntry): StorageEntry {
|
||||
function extendPrefixedMap (registry: CodecRegistry, itemFn: CreateItemFn, storageFn: StorageEntry): StorageEntry {
|
||||
const { meta: { type }, method, section } = itemFn;
|
||||
|
||||
storageFn.iterKey = extendHeadMeta(registry, itemFn, storageFn, (...args: unknown[]): Raw => {
|
||||
@@ -162,7 +162,7 @@ function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn:
|
||||
const { hashers, key } = type.asMap;
|
||||
const keysVec = hashers.length === 1
|
||||
? [key]
|
||||
: registry.lookup.getSiType(key).def.asTuple;
|
||||
: (registry as LookupRegistry).lookup.getSiType(key).def.asTuple;
|
||||
|
||||
return new Raw(registry, createKeyRaw(registry, itemFn, { args, hashers: hashers.slice(0, args.length), keys: keysVec.slice(0, args.length) }));
|
||||
}
|
||||
@@ -175,7 +175,7 @@ function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn:
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function createFunction (registry: Registry, itemFn: CreateItemFn, options: CreateItemOptions): StorageEntry {
|
||||
export function createFunction (registry: CodecRegistry, itemFn: CreateItemFn, options: CreateItemOptions): StorageEntry {
|
||||
const { meta: { type } } = itemFn;
|
||||
const storageFn = createWithMeta(registry, itemFn, options);
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { StorageEntry } from '../../../primitive/types';
|
||||
import type { Registry } from '../../../types';
|
||||
import type { Storage } from '../types';
|
||||
|
||||
import { substrate } from './substrate';
|
||||
|
||||
/** @internal */
|
||||
export function getStorage (registry: Registry): Storage {
|
||||
export function getStorage (registry: CodecRegistry): Storage {
|
||||
const storage: Record<string, StorageEntry> = {};
|
||||
const entries = Object.entries(substrate);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { MetadataLatest, StorageEntryMetadataLatest } from '../../../interfaces';
|
||||
import type { Registry } from '../../../types';
|
||||
import type { Storage } from '../types';
|
||||
|
||||
import { lazyMethod, lazyMethods, stringCamelCase } from '@polkadot/util';
|
||||
@@ -18,7 +18,7 @@ const VERSION_DOCS = { docs: 'Returns the current pallet version from storage',
|
||||
|
||||
/** @internal */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function decorateStorage (registry: Registry, { pallets }: MetadataLatest, _metaVersion: number): Storage {
|
||||
export function decorateStorage (registry: CodecRegistry, { pallets }: MetadataLatest, _metaVersion: number): Storage {
|
||||
const result: Storage = getStorage(registry);
|
||||
|
||||
for (let i = 0; i < pallets.length; i++) {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { StorageEntry } from '../../../primitive/types';
|
||||
import type { Registry } from '../../../types';
|
||||
import type { ManualMetadata } from './util';
|
||||
|
||||
import { createRuntimeFunction } from './util';
|
||||
|
||||
type Creator = (registry: Registry) => StorageEntry;
|
||||
type Creator = (registry: CodecRegistry) => StorageEntry;
|
||||
|
||||
const prefix = 'Substrate';
|
||||
const section = 'substrate';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { PortableType } from '../../../interfaces';
|
||||
import type { StorageEntry } from '../../../primitive/types';
|
||||
import type { Registry } from '../../../types';
|
||||
@@ -60,16 +61,16 @@ function findSiType (registry: Registry, orig: string): PortableType | undefined
|
||||
|
||||
// Small helper function to factorize code on this page.
|
||||
/** @internal */
|
||||
export function createRuntimeFunction ({ method, prefix, section }: ManualDefinition, key: Uint8Array | string, { docs, type }: ManualMetadata): (registry: Registry) => StorageEntry {
|
||||
return (registry: Registry): StorageEntry =>
|
||||
export function createRuntimeFunction ({ method, prefix, section }: ManualDefinition, key: Uint8Array | string, { docs, type }: ManualMetadata): (registry: CodecRegistry) => StorageEntry {
|
||||
return (registry: CodecRegistry): StorageEntry =>
|
||||
createFunction(registry, {
|
||||
meta: registry.createType('StorageEntryMetadataLatest', {
|
||||
docs: registry.createType('Vec<Text>', [docs]),
|
||||
modifier: registry.createType('StorageEntryModifierLatest', 'Required'),
|
||||
name: registry.createType('Text', method),
|
||||
meta: registry.createTypeUnsafe('StorageEntryMetadataLatest', [{
|
||||
docs: registry.createTypeUnsafe('Vec<Text>', [[docs]]),
|
||||
modifier: registry.createTypeUnsafe('StorageEntryModifierLatest', ['Required']),
|
||||
name: registry.createTypeUnsafe('Text', [method]),
|
||||
toJSON: (): any => key,
|
||||
type: registry.createType('StorageEntryTypeLatest', { Plain: findSiType(registry, type)?.id || 0 })
|
||||
}),
|
||||
type: registry.createTypeUnsafe('StorageEntryTypeLatest', [{ Plain: findSiType(registry as Registry, type)?.id || 0 }])
|
||||
}]),
|
||||
method,
|
||||
prefix,
|
||||
section
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { DispatchErrorModule, ErrorMetadataLatest, EventMetadataLatest, PalletConstantMetadataLatest } from '../../interfaces';
|
||||
import type { StorageEntry } from '../../primitive/types';
|
||||
import type { AnyTuple, CallFunction, Codec, IEvent, Registry } from '../../types';
|
||||
import type { AnyTuple, CallFunction, Codec, IEvent } from '../../types';
|
||||
|
||||
export interface ConstantCodec extends Codec {
|
||||
readonly meta: PalletConstantMetadataLatest;
|
||||
@@ -46,6 +47,6 @@ export interface DecoratedMeta {
|
||||
readonly errors: Errors;
|
||||
readonly events: Events;
|
||||
readonly query: Storage;
|
||||
readonly registry: Registry;
|
||||
readonly registry: CodecRegistry;
|
||||
readonly tx: Extrinsics
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Vec } from '../codec';
|
||||
import type { Vec } from '@polkadot/types-codec';
|
||||
import type { Codec } from '../types';
|
||||
|
||||
export interface MetadataInterface<Modules extends Codec> extends Codec {
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { SiLookupTypeId } from '../../interfaces';
|
||||
import type { PortableRegistry } from '../../metadata';
|
||||
import type { ILookup } from '../../types';
|
||||
|
||||
export function getSiName (lookup: PortableRegistry, type: SiLookupTypeId): string {
|
||||
export function getSiName (lookup: ILookup, type: SiLookupTypeId): string {
|
||||
const typeDef = lookup.getTypeDef(type);
|
||||
|
||||
return typeDef.lookupName || typeDef.type;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user