Split @polkadot/types-create (#4330)
* Split @polkadot/types-create * Remove floating Type class * Adjust * Adjust detectPackage * Fix types-known exports
This commit is contained in:
@@ -7,9 +7,11 @@ import rpcDefinitions from './interfaces/jsonrpc';
|
||||
export * from './codec';
|
||||
export * from './create';
|
||||
export * from './index.types';
|
||||
export * from './known';
|
||||
export * from './metadata';
|
||||
|
||||
export { TypeDefInfo } from './create/types';
|
||||
export { TypeDefInfo } from '@polkadot/types-create';
|
||||
|
||||
export { convertSiV0toV1 } from './metadata/PortableRegistry';
|
||||
export { packageInfo } from './packageInfo';
|
||||
export { unwrapStorageType } from './primitive/StorageKey';
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeDefInfo } from '../types';
|
||||
import { TypeDefInfo } from '@polkadot/types-create';
|
||||
|
||||
import { createClass, getTypeClass, TypeRegistry } from '.';
|
||||
|
||||
describe('createClass', (): void => {
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
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 { getTypeDef } from './getTypeDef';
|
||||
import { TypeDefInfo } from './types';
|
||||
|
||||
function getTypeDefType ({ lookupName, type }: TypeDef): string {
|
||||
return lookupName || type;
|
||||
}
|
||||
|
||||
function getSubDefArray (value: TypeDef): TypeDef[] {
|
||||
assert(value.sub && Array.isArray(value.sub), () => `Expected subtype as TypeDef[] in ${stringify(value)}`);
|
||||
|
||||
return value.sub;
|
||||
}
|
||||
|
||||
function getSubDef (value: TypeDef): TypeDef {
|
||||
assert(value.sub && !Array.isArray(value.sub), () => `Expected subtype as TypeDef in ${stringify(value)}`);
|
||||
|
||||
return value.sub;
|
||||
}
|
||||
|
||||
function getSubType (value: TypeDef): string {
|
||||
return getTypeDefType(getSubDef(value));
|
||||
}
|
||||
|
||||
// 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> = {};
|
||||
|
||||
for (let i = 0; i < subs.length; i++) {
|
||||
map[subs[i].name as string] = getTypeDefType(subs[i]);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
// 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): 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): CodecClass<Codec> {
|
||||
const [keyType, valueType] = getTypeClassArray(value);
|
||||
|
||||
return Clazz.with(keyType, valueType);
|
||||
}
|
||||
|
||||
function createWithSub (Clazz: { with: (t: string) => CodecClass<Codec> }, value: TypeDef): CodecClass<Codec> {
|
||||
return Clazz.with(getSubType(value));
|
||||
}
|
||||
|
||||
const infoMapping: Record<TypeDefInfo, (registry: CodecRegistry, value: TypeDef) => CodecClass<Codec>> = {
|
||||
[TypeDefInfo.BTreeMap]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createHashMap(BTreeMap, value),
|
||||
|
||||
[TypeDefInfo.BTreeSet]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(BTreeSet, value),
|
||||
|
||||
[TypeDefInfo.Compact]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(Compact, value),
|
||||
|
||||
[TypeDefInfo.DoNotConstruct]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
DoNotConstruct.with(value.displayName || value.type),
|
||||
|
||||
[TypeDefInfo.Enum]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> => {
|
||||
const subs = getSubDefArray(value);
|
||||
|
||||
return Enum.with(
|
||||
subs.every(({ type }) => type === 'Null')
|
||||
? subs.reduce<Record<string, number>>((out, { index, name }, count) => {
|
||||
out[name as string] = index || count;
|
||||
|
||||
return out;
|
||||
}, {})
|
||||
: getTypeClassMap(value)
|
||||
);
|
||||
},
|
||||
|
||||
[TypeDefInfo.HashMap]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createHashMap(HashMap, value),
|
||||
|
||||
[TypeDefInfo.Int]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createInt(Int, value),
|
||||
|
||||
// We have circular deps between Linkage & Struct
|
||||
[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);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
Clazz.prototype.toRawType = function (): string {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call
|
||||
return `Linkage<${this.next.toRawType(true)}>`;
|
||||
};
|
||||
|
||||
return Clazz;
|
||||
},
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Null]: (registry: CodecRegistry, _: TypeDef): CodecClass<Codec> =>
|
||||
Null,
|
||||
|
||||
[TypeDefInfo.Option]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(Option, value),
|
||||
|
||||
[TypeDefInfo.Plain]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
registry.getOrUnknown(value.type),
|
||||
|
||||
[TypeDefInfo.Range]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
(value.type.includes('RangeInclusive') ? RangeInclusive : Range).with(getSubType(value)),
|
||||
|
||||
[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: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
CodecSet.with(
|
||||
getSubDefArray(value).reduce<Record<string, number>>((result, { index, name }) => {
|
||||
result[name as string] = index as number;
|
||||
|
||||
return result;
|
||||
}, {}),
|
||||
value.length
|
||||
),
|
||||
|
||||
[TypeDefInfo.Si]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
getTypeClass(registry, (registry as LookupRegistry).lookup.getTypeDef(value.type)),
|
||||
|
||||
[TypeDefInfo.Struct]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
Struct.with(getTypeClassMap(value), value.alias),
|
||||
|
||||
[TypeDefInfo.Tuple]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
Tuple.with(getTypeClassArray(value)),
|
||||
|
||||
[TypeDefInfo.UInt]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createInt(UInt, value),
|
||||
|
||||
[TypeDefInfo.Vec]: (registry: CodecRegistry, { sub }: TypeDef): CodecClass<Codec> => {
|
||||
assert(sub && !Array.isArray(sub), 'Expected type information for vector');
|
||||
|
||||
return (
|
||||
sub.type === 'u8'
|
||||
? Bytes
|
||||
: Vec.with(getTypeDefType(sub))
|
||||
);
|
||||
},
|
||||
|
||||
[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 (
|
||||
sub.type === 'u8'
|
||||
? U8aFixed.with((length * 8) as U8aBitLength, displayName)
|
||||
: VecFixed.with(getTypeDefType(sub), length)
|
||||
);
|
||||
},
|
||||
|
||||
[TypeDefInfo.WrapperOpaque]: (registry: CodecRegistry, value: TypeDef): CodecClass<Codec> =>
|
||||
createWithSub(WrapperOpaque, value)
|
||||
};
|
||||
|
||||
export function constructTypeClass<T extends Codec = Codec> (registry: CodecRegistry, typeDef: TypeDef): CodecClass<T> {
|
||||
try {
|
||||
const Type = infoMapping[typeDef.info](registry, typeDef);
|
||||
|
||||
assert(Type, 'No class created');
|
||||
|
||||
// don't clobber any existing
|
||||
if (!Type.__fallbackType && typeDef.fallbackType) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore ...this is the only place we we actually assign this...
|
||||
Type.__fallbackType = typeDef.fallbackType;
|
||||
}
|
||||
|
||||
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: 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: 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 as LookupRegistry).lookup.getTypeDef(type)
|
||||
: getTypeDef(type)
|
||||
);
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
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 { createClass } from './createClass';
|
||||
|
||||
// With isPedantic, actually check that the encoding matches that supplied. This
|
||||
// is much slower, but verifies that we have the correct types defined
|
||||
function checkInstance (created: Codec, matcher: Uint8Array): void {
|
||||
const u8a = created.toU8a();
|
||||
const rawType = created.toRawType();
|
||||
const isOk = (
|
||||
// full match, all ok
|
||||
u8aEq(u8a, matcher) ||
|
||||
(
|
||||
// on a length-prefixed type, just check the actual length
|
||||
['Bytes', 'Text', 'Type'].includes(rawType) &&
|
||||
matcher.length === (created as Bytes).length
|
||||
) ||
|
||||
(
|
||||
// when the created is empty and matcher is also empty, let it slide...
|
||||
created.isEmpty &&
|
||||
matcher.every((v) => !v)
|
||||
)
|
||||
);
|
||||
|
||||
assert(isOk, () => `${rawType}:: Decoded input doesn't match input, received ${u8aToHex(matcher, 512)} (${matcher.length} bytes), created ${u8aToHex(u8a, 512)} (${u8a.length} bytes)`);
|
||||
}
|
||||
|
||||
function checkPedantic (created: Codec, [value]: unknown[], isPedantic = false): void {
|
||||
if (isPedantic) {
|
||||
if (isU8a(value)) {
|
||||
checkInstance(created, value);
|
||||
} else if (isHex(value)) {
|
||||
checkInstance(created, u8aToU8a(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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: CodecRegistry, Type: CodecClass, params: unknown[] = [], { blockHash, isOptional, isPedantic }: CreateOptions = {}): T {
|
||||
const created = new (isOptional ? Option.with(Type) : Type)(registry, ...params);
|
||||
|
||||
checkPedantic(created, params, isPedantic);
|
||||
|
||||
if (blockHash) {
|
||||
created.createdAtHash = createType(registry, 'Hash', blockHash);
|
||||
}
|
||||
|
||||
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: CodecRegistry, type: K, params: unknown[] = [], options: CreateOptions = {}): DetectCodec<T, K> {
|
||||
let Clazz: CodecClass | null = null;
|
||||
let firstError: Error | null = null;
|
||||
|
||||
try {
|
||||
Clazz = createClass(registry, type);
|
||||
|
||||
return initType(registry, Clazz, params, options);
|
||||
} catch (error) {
|
||||
firstError = new Error(`createType(${type}):: ${(error as Error).message}`);
|
||||
}
|
||||
|
||||
if (Clazz && Clazz.__fallbackType) {
|
||||
try {
|
||||
Clazz = createClass(registry, Clazz.__fallbackType as unknown as K);
|
||||
|
||||
return initType(registry, Clazz, params, options);
|
||||
} catch {
|
||||
// swallow, we will throw the first error again
|
||||
}
|
||||
}
|
||||
|
||||
throw firstError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of a `type` with a given `params`.
|
||||
* @param type - A recognizable string representing the type to create an
|
||||
* instance from
|
||||
* @param params - The value to instantiate the type with
|
||||
*/
|
||||
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,9 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { encodeTypeDef } from './encodeTypes';
|
||||
import { TypeDefInfo } from '@polkadot/types-create';
|
||||
|
||||
import { TypeRegistry } from './registry';
|
||||
import { TypeDefInfo } from './types';
|
||||
import { encodeTypeDef } from '.';
|
||||
|
||||
describe('encodeTypeDef', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { TypeDef } from './types';
|
||||
|
||||
import { assert, isNumber, isUndefined, objectSpread, stringify } from '@polkadot/util';
|
||||
|
||||
import { TypeDefInfo } from './types';
|
||||
|
||||
const stringIdentity = <T extends { toString: () => string }> (value: T): string => value.toString();
|
||||
|
||||
const INFO_WRAP = ['BTreeMap', 'BTreeSet', 'Compact', 'HashMap', 'Option', 'Result', 'Vec'];
|
||||
|
||||
export function paramsNotation <T> (outer: string, inner?: T | T[], transform: (_: T) => string = stringIdentity): string {
|
||||
return `${outer}${
|
||||
inner
|
||||
? `<${(Array.isArray(inner) ? inner : [inner]).map(transform).join(', ')}>`
|
||||
: ''
|
||||
}`;
|
||||
}
|
||||
|
||||
function encodeWithParams (CodecRegistry: CodecRegistry, typeDef: TypeDef, outer: string): string {
|
||||
const { info, sub } = typeDef;
|
||||
|
||||
switch (info) {
|
||||
case TypeDefInfo.BTreeMap:
|
||||
case TypeDefInfo.BTreeSet:
|
||||
case TypeDefInfo.Compact:
|
||||
case TypeDefInfo.HashMap:
|
||||
case TypeDefInfo.Linkage:
|
||||
case TypeDefInfo.Option:
|
||||
case TypeDefInfo.Result:
|
||||
case TypeDefInfo.Vec:
|
||||
case TypeDefInfo.WrapperOpaque:
|
||||
return paramsNotation(outer, sub, (p) => encodeTypeDef(CodecRegistry, p));
|
||||
}
|
||||
|
||||
throw new Error(`Unable to encode ${stringify(typeDef)} with params`);
|
||||
}
|
||||
|
||||
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(', ')}`);
|
||||
|
||||
const inner: Record<string, string> = objectSpread({}, extra);
|
||||
|
||||
for (let i = 0; i < sub.length; i++) {
|
||||
const def = sub[i];
|
||||
|
||||
inner[def.name as string] = encodeTypeDef(CodecRegistry, def);
|
||||
}
|
||||
|
||||
return stringify(
|
||||
asEnum
|
||||
? { _enum: inner }
|
||||
: inner
|
||||
);
|
||||
}
|
||||
|
||||
// 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, (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(CodecRegistry, sub, true);
|
||||
},
|
||||
[TypeDefInfo.HashMap]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'HashMap'),
|
||||
[TypeDefInfo.Int]: (CodecRegistry: CodecRegistry, { length = 32 }: TypeDef) =>
|
||||
`Int<${length}>`,
|
||||
[TypeDefInfo.Linkage]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Linkage'),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Null]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
'Null',
|
||||
[TypeDefInfo.Option]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'Option'),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Plain]: (CodecRegistry: CodecRegistry, { displayName, type }: TypeDef) =>
|
||||
displayName || type,
|
||||
[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]: (CodecRegistry: CodecRegistry, { length = 8, sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Set type');
|
||||
|
||||
return stringify({
|
||||
_set: sub.reduce((all, { index, name }, count) =>
|
||||
objectSpread(all, { [`${name || `Unknown${index || count}`}`]: index || count }),
|
||||
{ _bitLength: length || 8 })
|
||||
});
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
[TypeDefInfo.Si]: (CodecRegistry: CodecRegistry, { lookupName, type }: TypeDef) =>
|
||||
lookupName || type,
|
||||
[TypeDefInfo.Struct]: (CodecRegistry: CodecRegistry, { alias, sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Struct type');
|
||||
|
||||
return encodeSubTypes(CodecRegistry, sub, false,
|
||||
alias
|
||||
? {
|
||||
_alias: [...alias.entries()].reduce<Record<string, string>>((all, [k, v]) =>
|
||||
objectSpread(all, { [k]: v }), {}
|
||||
)
|
||||
}
|
||||
: {}
|
||||
);
|
||||
},
|
||||
[TypeDefInfo.Tuple]: (CodecRegistry: CodecRegistry, { sub }: TypeDef): string => {
|
||||
assert(sub && Array.isArray(sub), 'Unable to encode Tuple type');
|
||||
|
||||
return `(${sub.map((type) => encodeTypeDef(CodecRegistry, type)).join(',')})`;
|
||||
},
|
||||
[TypeDefInfo.UInt]: (CodecRegistry: CodecRegistry, { length = 32 }: TypeDef) =>
|
||||
`UInt<${length}>`,
|
||||
[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]: (CodecRegistry: CodecRegistry, typeDef: TypeDef) =>
|
||||
encodeWithParams(CodecRegistry, typeDef, 'WrapperOpaque')
|
||||
};
|
||||
|
||||
function encodeType (CodecRegistry: CodecRegistry, typeDef: TypeDef, withLookup = true): string {
|
||||
return withLookup && typeDef.lookupName
|
||||
? typeDef.lookupName
|
||||
: encoders[typeDef.info](CodecRegistry, typeDef);
|
||||
}
|
||||
|
||||
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(CodecRegistry, typeDef);
|
||||
}
|
||||
|
||||
export function withTypeString (CodecRegistry: CodecRegistry, typeDef: Omit<TypeDef, 'type'>): TypeDef {
|
||||
return objectSpread({}, typeDef, { type: encodeType(CodecRegistry, typeDef as TypeDef, false) });
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeDefInfo } from './types';
|
||||
import { TypeDefInfo } from '@polkadot/types-create';
|
||||
|
||||
import { getTypeDef, TypeRegistry } from '.';
|
||||
|
||||
describe('getTypeDef', (): void => {
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { TypeDef } from './types';
|
||||
|
||||
import { sanitize } from '@polkadot/types-codec';
|
||||
import { assert, isNumber, isString, objectSpread } from '@polkadot/util';
|
||||
|
||||
import { TypeDefInfo } from './types';
|
||||
import { typeSplit } from './typeSplit';
|
||||
|
||||
interface TypeDefOptions {
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
const MAX_NESTED = 64;
|
||||
const KNOWN_INTERNALS = ['_alias', '_fallback'];
|
||||
|
||||
function getTypeString (typeOrObj: any): string {
|
||||
return isString(typeOrObj)
|
||||
? typeOrObj.toString()
|
||||
: JSON.stringify(typeOrObj);
|
||||
}
|
||||
|
||||
function isRustEnum (details: Record<string, string> | Record<string, number>): details is Record<string, string> {
|
||||
const values = Object.values(details);
|
||||
|
||||
if (values.some((v) => isNumber(v))) {
|
||||
assert(values.every((v) => isNumber(v) && v >= 0 && v <= 255), 'Invalid number-indexed enum definition');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// decode an enum of either of the following forms
|
||||
// { _enum: ['A', 'B', 'C'] }
|
||||
// { _enum: { A: AccountId, B: Balance, C: u32 } }
|
||||
// { _enum: { A: 1, B: 2 } }
|
||||
function _decodeEnum (value: TypeDef, details: string[] | Record<string, string> | Record<string, number>, count: number): TypeDef {
|
||||
value.info = TypeDefInfo.Enum;
|
||||
|
||||
// not as pretty, but remain compatible with oo7 for both struct and Array types
|
||||
if (Array.isArray(details)) {
|
||||
value.sub = details.map((name, index): TypeDef => ({
|
||||
index,
|
||||
info: TypeDefInfo.Plain,
|
||||
name,
|
||||
type: 'Null'
|
||||
}));
|
||||
} else if (isRustEnum(details)) {
|
||||
value.sub = Object.entries(details).map(([name, typeOrObj], index): TypeDef =>
|
||||
objectSpread({}, getTypeDef(getTypeString(typeOrObj || 'Null'), { name }, count), { index })
|
||||
);
|
||||
} else {
|
||||
value.sub = Object.entries(details).map(([name, index]): TypeDef => ({
|
||||
index,
|
||||
info: TypeDefInfo.Plain,
|
||||
name,
|
||||
type: 'Null'
|
||||
}));
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// decode a set of the form
|
||||
// { _set: { A: 0b0001, B: 0b0010, C: 0b0100 } }
|
||||
function _decodeSet (value: TypeDef, details: Record<string, number>): TypeDef {
|
||||
value.info = TypeDefInfo.Set;
|
||||
value.length = details._bitLength;
|
||||
value.sub = Object
|
||||
.entries(details)
|
||||
.filter(([name]): boolean => !name.startsWith('_'))
|
||||
.map(([name, index]): TypeDef => ({
|
||||
index,
|
||||
info: TypeDefInfo.Plain,
|
||||
name,
|
||||
type: 'Null'
|
||||
}));
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// decode a struct, set or enum
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function _decodeStruct (value: TypeDef, type: string, _: string, count: number): TypeDef {
|
||||
const parsed = JSON.parse(type) as Record<string, unknown> & { _alias: string };
|
||||
const keys = Object.keys(parsed);
|
||||
|
||||
if (keys.length === 1 && keys[0] === '_enum') {
|
||||
return _decodeEnum(value, parsed[keys[0]] as string[], count);
|
||||
} else if (keys.length === 1 && keys[0] === '_set') {
|
||||
return _decodeSet(value, parsed[keys[0]] as Record<string, number>);
|
||||
}
|
||||
|
||||
value.alias = parsed._alias
|
||||
? new Map(Object.entries(parsed._alias))
|
||||
: undefined;
|
||||
value.fallbackType = parsed._fallback as string | undefined;
|
||||
value.sub = keys.filter((name) => !KNOWN_INTERNALS.includes(name)).map((name): TypeDef =>
|
||||
getTypeDef(getTypeString(parsed[name]), { name }, count)
|
||||
);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// decode a fixed vector, e.g. [u8;32]
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function _decodeFixedVec (value: TypeDef, type: string, _: string, count: number): TypeDef {
|
||||
const max = type.length - 1;
|
||||
let index = -1;
|
||||
let inner = 0;
|
||||
|
||||
for (let i = 1; (i < max) && (index === -1); i++) {
|
||||
if (type[i] === ';' && inner === 0) {
|
||||
index = i;
|
||||
} else if (['[', '(', '<'].includes(type[i])) {
|
||||
inner++;
|
||||
} else if ([']', ')', '>'].includes(type[i])) {
|
||||
inner--;
|
||||
}
|
||||
}
|
||||
|
||||
assert(index !== -1, () => `${type}: Unable to extract location of ';'`);
|
||||
|
||||
const vecType = type.substr(1, index - 1);
|
||||
const [strLength, displayName] = type.substr(index + 1, max - index - 1).split(';');
|
||||
const length = parseInt(strLength.trim(), 10);
|
||||
|
||||
// as a first round, only u8 via u8aFixed, we can add more support
|
||||
assert(length <= 256, () => `${type}: Only support for [Type; <length>], where length <= 256`);
|
||||
|
||||
value.displayName = displayName;
|
||||
value.length = length;
|
||||
value.sub = getTypeDef(vecType, {}, count);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function _decodeRange (value: TypeDef, _: string, subType: string): TypeDef {
|
||||
const Type = getTypeDef(subType);
|
||||
|
||||
value.sub = [Type, Type];
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// decode a tuple
|
||||
function _decodeTuple (value: TypeDef, _: string, subType: string, count: number): TypeDef {
|
||||
value.sub = subType.length === 0
|
||||
? []
|
||||
: typeSplit(subType).map((inner) => getTypeDef(inner, {}, count));
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// decode a Int/UInt<bitLength[, name]>
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function _decodeAnyInt (value: TypeDef, type: string, _: string, clazz: 'Int' | 'UInt'): TypeDef {
|
||||
const [strLength, displayName] = type.substr(clazz.length + 1, type.length - clazz.length - 1 - 1).split(',');
|
||||
const length = parseInt(strLength.trim(), 10);
|
||||
|
||||
// as a first round, only u8 via u8aFixed, we can add more support
|
||||
assert(length <= 8192 && (length % 8) === 0, () => `${type}: Only support for ${clazz}<bitLength>, where length <= 8192 and a power of 8, found ${length}`);
|
||||
|
||||
value.displayName = displayName;
|
||||
value.length = length;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function _decodeInt (value: TypeDef, type: string, subType: string): TypeDef {
|
||||
return _decodeAnyInt(value, type, subType, 'Int');
|
||||
}
|
||||
|
||||
function _decodeUInt (value: TypeDef, type: string, subType: string): TypeDef {
|
||||
return _decodeAnyInt(value, type, subType, 'UInt');
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function _decodeDoNotConstruct (value: TypeDef, type: string, _: string): TypeDef {
|
||||
const NAME_LENGTH = 'DoNotConstruct'.length;
|
||||
|
||||
value.displayName = type.substr(NAME_LENGTH + 1, type.length - NAME_LENGTH - 1 - 1);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function hasWrapper (type: string, [start, end]: [string, string, TypeDefInfo, any?]): boolean {
|
||||
return (type.substr(0, start.length) === start) && (type.substr(-1 * end.length) === end);
|
||||
}
|
||||
|
||||
const nestedExtraction: [string, string, TypeDefInfo, (value: TypeDef, type: string, subType: string, count: number) => TypeDef][] = [
|
||||
['[', ']', TypeDefInfo.VecFixed, _decodeFixedVec],
|
||||
['{', '}', TypeDefInfo.Struct, _decodeStruct],
|
||||
['(', ')', TypeDefInfo.Tuple, _decodeTuple],
|
||||
// the inner for these are the same as tuple, multiple values
|
||||
['BTreeMap<', '>', TypeDefInfo.BTreeMap, _decodeTuple],
|
||||
['HashMap<', '>', TypeDefInfo.HashMap, _decodeTuple],
|
||||
['Int<', '>', TypeDefInfo.Int, _decodeInt],
|
||||
// Not sure about these, have a specific implementation?
|
||||
['Range<', '>', TypeDefInfo.Tuple, _decodeRange],
|
||||
['RangeInclusive<', '>', TypeDefInfo.Tuple, _decodeRange],
|
||||
['Result<', '>', TypeDefInfo.Result, _decodeTuple],
|
||||
['UInt<', '>', TypeDefInfo.UInt, _decodeUInt],
|
||||
['DoNotConstruct<', '>', TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct]
|
||||
];
|
||||
|
||||
const wrappedExtraction: [string, string, TypeDefInfo][] = [
|
||||
['BTreeSet<', '>', TypeDefInfo.BTreeSet],
|
||||
['Compact<', '>', TypeDefInfo.Compact],
|
||||
['Linkage<', '>', TypeDefInfo.Linkage],
|
||||
['Option<', '>', TypeDefInfo.Option],
|
||||
['Vec<', '>', TypeDefInfo.Vec],
|
||||
['WrapperOpaque<', '>', TypeDefInfo.WrapperOpaque]
|
||||
];
|
||||
|
||||
function extractSubType (type: string, [start, end]: [string, string, TypeDefInfo, any?]): string {
|
||||
return type.substr(start.length, type.length - start.length - end.length);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export function getTypeDef (_type: String | string, { displayName, name }: TypeDefOptions = {}, count = 0): TypeDef {
|
||||
// create the type via Type, allowing types to be sanitized
|
||||
const type = sanitize(_type);
|
||||
const value: TypeDef = { displayName, info: TypeDefInfo.Plain, name, type };
|
||||
|
||||
assert(++count !== MAX_NESTED, 'getTypeDef: Maximum nested limit reached');
|
||||
|
||||
const nested = nestedExtraction.find((nested) => hasWrapper(type, nested));
|
||||
|
||||
if (nested) {
|
||||
value.info = nested[2];
|
||||
|
||||
return nested[3](value, type, extractSubType(type, nested), count);
|
||||
}
|
||||
|
||||
const wrapped = wrappedExtraction.find((wrapped) => hasWrapper(type, wrapped));
|
||||
|
||||
if (wrapped) {
|
||||
value.info = wrapped[2];
|
||||
value.sub = getTypeDef(extractSubType(type, wrapped), {}, count);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -1,10 +1,26 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './createClass';
|
||||
export * from './createType';
|
||||
export * from './encodeTypes';
|
||||
export * from './getTypeDef';
|
||||
import type { Codec, CodecClass, CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { DetectCodec } from '../types';
|
||||
|
||||
import { createClassUnsafe, createTypeUnsafe } from '@polkadot/types-create';
|
||||
|
||||
export * from '@polkadot/types-create';
|
||||
|
||||
export * from './lazy';
|
||||
export * from './registry';
|
||||
export * from './typeSplit';
|
||||
|
||||
export function createClass<T extends Codec = Codec, K extends string = string> (registry: CodecRegistry, type: K): CodecClass<DetectCodec<T, K>> {
|
||||
return createClassUnsafe(registry, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of a `type` with a given `params`.
|
||||
* @param type - A recognizable string representing the type to create an
|
||||
* instance from
|
||||
* @param params - The value to instantiate the type with
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Codec, CodecClass, CodecRegistry, IU8a } from '@polkadot/types-codec/types';
|
||||
import type { CreateOptions, TypeDef } from '@polkadot/types-create/types';
|
||||
import type { ExtDef } from '../extrinsic/signedExtensions/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 { constructTypeClass, createClassUnsafe, createTypeUnsafe } from '@polkadot/types-create';
|
||||
import { assert, assertReturn, BN_ZERO, formatBalance, isFunction, isString, isU8a, lazyMethod, logger, objectSpread, stringCamelCase, stringify } from '@polkadot/util';
|
||||
import { blake2AsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
@@ -19,8 +20,6 @@ import { decorateConstants, filterCallsSome, filterEventsSome } from '../metadat
|
||||
import { createCallFunction } from '../metadata/decorate/extrinsics';
|
||||
import { Metadata } from '../metadata/Metadata';
|
||||
import { PortableRegistry } from '../metadata/PortableRegistry';
|
||||
import { constructTypeClass, createClassUnsafe } from './createClass';
|
||||
import { createTypeUnsafe } from './createType';
|
||||
import { lazyVariants } from './lazy';
|
||||
|
||||
const l = logger('registry');
|
||||
@@ -266,8 +265,8 @@ export class TypeRegistry implements Registry {
|
||||
/**
|
||||
* @describe Creates an instance of the class
|
||||
*/
|
||||
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>;
|
||||
public createClass <T extends Codec = Codec, K extends string = string> (type: K): CodecClass<DetectCodec<T, K>> {
|
||||
return this.createClassUnsafe(type) as unknown as CodecClass<DetectCodec<T, K>>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,7 +279,7 @@ export class TypeRegistry implements Registry {
|
||||
/**
|
||||
* @description Creates an instance of a type as registered
|
||||
*/
|
||||
public createType <T extends Codec = Codec, K extends string = string, R = DetectCodec<T, K>> (type: K, ...params: unknown[]): R {
|
||||
public createType <T extends Codec = Codec, K extends string = string> (type: K, ...params: unknown[]): DetectCodec<T, K> {
|
||||
return this.createTypeUnsafe(type, params);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
function isNotNested (...counters: number[]): boolean {
|
||||
return !counters.some((counter): boolean => counter !== 0);
|
||||
}
|
||||
|
||||
// safely split a string on ', ' while taking care of any nested occurences
|
||||
export function typeSplit (type: string): string[] {
|
||||
let [cDepth, fDepth, sDepth, tDepth, start] = [0, 0, 0, 0, 0];
|
||||
const result = [];
|
||||
|
||||
const extract = (index: number): void => {
|
||||
if (isNotNested(cDepth, fDepth, sDepth, tDepth)) {
|
||||
result.push(type.substr(start, index - start).trim());
|
||||
start = index + 1;
|
||||
}
|
||||
};
|
||||
|
||||
for (let index = 0; index < type.length; index++) {
|
||||
switch (type[index]) {
|
||||
// if we are not nested, add the type
|
||||
case ',': extract(index); break;
|
||||
|
||||
// adjust compact/vec (and friends) depth
|
||||
case '<': cDepth++; break;
|
||||
case '>': cDepth--; break;
|
||||
|
||||
// adjust fixed vec depths
|
||||
case '[': fDepth++; break;
|
||||
case ']': fDepth--; break;
|
||||
|
||||
// adjust struct depth
|
||||
case '{': sDepth++; break;
|
||||
case '}': sDepth--; break;
|
||||
|
||||
// adjust tuple depth
|
||||
case '(': tDepth++; break;
|
||||
case ')': tDepth--; break;
|
||||
}
|
||||
}
|
||||
|
||||
assert(isNotNested(cDepth, fDepth, sDepth, tDepth), () => `Invalid definition (missing terminators) found in ${type}`);
|
||||
|
||||
// the final leg of the journey
|
||||
result.push(type.substr(start, type.length - start).trim());
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -2,46 +2,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export type { CodecCreateOptions as CreateOptions } from '@polkadot/types-codec/types';
|
||||
export type { TypeDef } from '@polkadot/types-create/types';
|
||||
|
||||
export enum TypeDefInfo {
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
Compact,
|
||||
DoNotConstruct,
|
||||
Enum,
|
||||
HashMap,
|
||||
Int,
|
||||
Linkage,
|
||||
Null,
|
||||
Option,
|
||||
Plain,
|
||||
Range,
|
||||
Result,
|
||||
Set,
|
||||
Si,
|
||||
Struct,
|
||||
Tuple,
|
||||
UInt,
|
||||
Vec,
|
||||
VecFixed,
|
||||
WrapperOpaque
|
||||
}
|
||||
|
||||
export interface TypeDef {
|
||||
alias?: Map<string, string>;
|
||||
displayName?: string;
|
||||
docs?: string[];
|
||||
fallbackType?: string;
|
||||
info: TypeDefInfo;
|
||||
index?: number;
|
||||
isFromSi?: boolean;
|
||||
length?: number;
|
||||
lookupIndex?: number;
|
||||
lookupName?: string;
|
||||
lookupNameRoot?: string;
|
||||
name?: string;
|
||||
namespace?: string;
|
||||
sub?: TypeDef | TypeDef[];
|
||||
type: string;
|
||||
typeName?: string;
|
||||
}
|
||||
export { TypeDefInfo } from '@polkadot/types-create';
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { packageInfo as codecInfo } from '@polkadot/types-codec';
|
||||
import { packageInfo as createInfo } from '@polkadot/types-create';
|
||||
import { detectPackage } from '@polkadot/util';
|
||||
|
||||
import { packageInfo } from './packageInfo';
|
||||
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [codecInfo]);
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [codecInfo, createInfo]);
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
// 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 { CreateRegistry, TypeDef } from '@polkadot/types-create/types';
|
||||
import type { EventMetadataLatest } from '../interfaces/metadata';
|
||||
import type { EventId } from '../interfaces/system';
|
||||
import type { IEvent, IEventData, InterfaceTypes, LookupRegistry } from '../types';
|
||||
import type { IEvent, IEventData, InterfaceTypes } from '../types';
|
||||
|
||||
import { Null, Struct, Tuple } from '@polkadot/types-codec';
|
||||
import { objectSpread } from '@polkadot/util';
|
||||
@@ -57,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 as LookupRegistry).lookup.getTypeDef(type));
|
||||
this.#typeDef = fields.map(({ type }) => (registry as CreateRegistry).lookup.getTypeDef(type));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types-known authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Text } from '@polkadot/types-codec';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { ExtDef } from '../extrinsic/signedExtensions/types';
|
||||
import type { Hash } from '../interfaces';
|
||||
import type { Text } from '../primitive';
|
||||
import type { ChainUpgradeVersion, CodecHasher, DefinitionRpc, DefinitionRpcSub, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '../types';
|
||||
|
||||
import { bnToBn, isNull, isUndefined, objectSpread } from '@polkadot/util';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// Copyright 2017-2021 @polkadot/types-known authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// We want predictive ordering (manually managed)
|
||||
|
||||
@@ -3,18 +3,15 @@
|
||||
|
||||
import type { Vec } from '@polkadot/types-codec';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { ILookup, TypeDef } from '@polkadot/types-create/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 { ILookup, TypeDef } from '../../types';
|
||||
|
||||
import { sanitize, Struct } from '@polkadot/types-codec';
|
||||
import { sanitize, Struct, u32 } from '@polkadot/types-codec';
|
||||
import { getTypeDef, TypeDefInfo, withTypeString } from '@polkadot/types-create';
|
||||
import { assert, isNumber, isString, objectSpread, stringCamelCase, stringify, stringPascalCase } from '@polkadot/util';
|
||||
|
||||
import { withTypeString } from '../../create/encodeTypes';
|
||||
import { getTypeDef } from '../../create/getTypeDef';
|
||||
import { u32 } from '../../primitive';
|
||||
import { TypeDefInfo } from '../../types';
|
||||
import { assertUnreachable } from './util';
|
||||
|
||||
// Just a placeholder for a type.unrwapOr()
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry, ICompact, INumber } from '@polkadot/types-codec/types';
|
||||
import type { CreateRegistry } from '@polkadot/types-create/types';
|
||||
import type { StorageEntryMetadataLatest, StorageHasher } from '../../../interfaces/metadata';
|
||||
import type { StorageEntry } from '../../../primitive/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';
|
||||
@@ -104,7 +104,7 @@ function createWStorageFn (registry: CodecRegistry, itemFn: CreateItemFn, option
|
||||
|
||||
return hashers.length === 1
|
||||
? createKey(registry, itemFn, { args, hashers, keys: [key] })
|
||||
: createKey(registry, itemFn, { args, hashers, keys: (registry as LookupRegistry).lookup.getSiType(key).def.asTuple });
|
||||
: createKey(registry, itemFn, { args, hashers, keys: (registry as CreateRegistry).lookup.getSiType(key).def.asTuple });
|
||||
};
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ function extendPrefixedMap (registry: CodecRegistry, itemFn: CreateItemFn, stora
|
||||
const { hashers, key } = type.asMap;
|
||||
const keysVec = hashers.length === 1
|
||||
? [key]
|
||||
: (registry as LookupRegistry).lookup.getSiType(key).def.asTuple;
|
||||
: (registry as CreateRegistry).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) }));
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { TypeDef } from '../../types';
|
||||
import type { TypeDef } from '@polkadot/types-create/types';
|
||||
|
||||
// we are attempting to avoid circular refs, hence the path import
|
||||
import { getTypeDef } from '../../create/getTypeDef';
|
||||
import { TypeDefInfo } from '../../create/types';
|
||||
import { getTypeDef, TypeDefInfo } from '@polkadot/types-create';
|
||||
|
||||
type Extracted = string | Extracted[];
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ILookup } from '@polkadot/types-create/types';
|
||||
import type { SiLookupTypeId } from '../../interfaces';
|
||||
import type { ILookup } from '../../types';
|
||||
|
||||
export function getSiName (lookup: ILookup, type: SiLookupTypeId): string {
|
||||
const typeDef = lookup.getTypeDef(type);
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Text } from '@polkadot/types-codec';
|
||||
import type { Text, Type } from '@polkadot/types-codec';
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
import type { ErrorMetadataV13, EventMetadataV13, ExtrinsicMetadataV13, ExtrinsicMetadataV14, FunctionMetadataV13, MetadataV13, MetadataV14, ModuleConstantMetadataV13, ModuleMetadataV13, PalletCallMetadataV14, PalletConstantMetadataV14, PalletErrorMetadataV14, PalletEventMetadataV14, PalletMetadataV14, PalletStorageMetadataV14, StorageEntryMetadataV14, StorageEntryTypeV14, StorageHasherV13, StorageMetadataV13 } from '../../interfaces/metadata';
|
||||
import type { SiVariant } from '../../interfaces/scaleInfo';
|
||||
import type { Type } from '../../primitive/Type';
|
||||
import type { OverrideModuleType, Registry } from '../../types';
|
||||
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AnyJson, AnyTuple, Codec, CodecRegistry, ICompact, INumber } from '@polkadot/types-codec/types';
|
||||
import type { CreateRegistry } from '@polkadot/types-create/types';
|
||||
import type { StorageEntryMetadataLatest, StorageEntryTypeLatest, StorageHasher } from '../interfaces/metadata';
|
||||
import type { AllHashers } from '../interfaces/metadata/definitions';
|
||||
import type { SiLookupTypeId } from '../interfaces/scaleInfo';
|
||||
import type { InterfaceTypes, IStorageKey, LookupRegistry } from '../types';
|
||||
import type { InterfaceTypes, IStorageKey } from '../types';
|
||||
import type { StorageEntry } from './types';
|
||||
|
||||
import { Bytes } from '@polkadot/types-codec';
|
||||
@@ -44,7 +45,7 @@ export function unwrapStorageSi (type: StorageEntryTypeLatest): SiLookupTypeId {
|
||||
|
||||
/** @internal */
|
||||
export function unwrapStorageType (registry: CodecRegistry, type: StorageEntryTypeLatest, isOptional?: boolean): keyof InterfaceTypes {
|
||||
const outputType = getSiName((registry as LookupRegistry).lookup, unwrapStorageSi(type));
|
||||
const outputType = getSiName((registry as CreateRegistry).lookup, unwrapStorageSi(type));
|
||||
|
||||
return isOptional
|
||||
? `Option<${outputType}>` as unknown as keyof InterfaceTypes
|
||||
@@ -118,7 +119,7 @@ function decodeArgsFromMeta <A extends AnyTuple> (registry: CodecRegistry, value
|
||||
const { hashers, key } = meta.type.asMap;
|
||||
const keys = hashers.length === 1
|
||||
? [key]
|
||||
: (registry as LookupRegistry).lookup.getSiType(key).def.asTuple;
|
||||
: (registry as CreateRegistry).lookup.getSiType(key).def.asTuple;
|
||||
|
||||
return decodeHashers(registry, value, hashers.map((h, i) => [h, keys[i]]));
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { CodecRegistry } from '@polkadot/types-codec/types';
|
||||
|
||||
import { sanitize, Text } from '@polkadot/types-codec';
|
||||
|
||||
/**
|
||||
* @name Type
|
||||
* @description
|
||||
* This is a extended version of Text, specifically to handle types. Here we rely fully
|
||||
* on what Text provides us, however we also adjust the types received from the runtime,
|
||||
* i.e. we remove the `T::` prefixes found in some types for consistency across implementation.
|
||||
*/
|
||||
export class Type extends Text {
|
||||
constructor (registry: CodecRegistry, value: Text | Uint8Array | string = '') {
|
||||
super(registry, value);
|
||||
|
||||
this.setOverride(sanitize(this.toString()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the base runtime type name for this instance
|
||||
*/
|
||||
public override toRawType (): string {
|
||||
return 'Type';
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
/**
|
||||
* @summary Type definitions that are used in the system
|
||||
*/
|
||||
export { BitVec, bool, Bool, Bytes, Type, i8, I8, i16, I16, i32, I32, i64, I64, i128, I128, i256, I256, Null, Text, u8, U8, u16, U16, u32, U32, u64, U64, u128, U128, u256, U256, usize, USize } from '@polkadot/types-codec';
|
||||
export { BitVec, bool, Bool, Bytes, i8, I8, i16, I16, i32, I32, i64, I64, i128, I128, i256, I256, Null, Text, Type, u8, U8, u16, U16, u32, U32, u64, U64, u128, U128, u256, U256, usize, USize } from '@polkadot/types-codec';
|
||||
|
||||
export { Data } from './Data';
|
||||
export { StorageKey } from './StorageKey';
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Observable } from 'rxjs';
|
||||
import type { CodecRegistry, ICompact, INumber, RegistryTypes } from '@polkadot/types-codec/types';
|
||||
import type { RegistryTypes } from '@polkadot/types-codec/types';
|
||||
import type { CreateRegistry, TypeDef } from '@polkadot/types-create/types';
|
||||
import type { BN } from '@polkadot/util';
|
||||
import type { TypeDef } from '../create/types';
|
||||
import type { ExtDef } from '../extrinsic/signedExtensions/types';
|
||||
import type { MetadataLatest } from '../interfaces/metadata';
|
||||
import type { SiField, SiLookupTypeId } from '../interfaces/scaleInfo';
|
||||
@@ -96,26 +96,8 @@ export interface RegisteredTypes {
|
||||
typesSpec?: Record<string, RegistryTypes>;
|
||||
}
|
||||
|
||||
export interface ILookup {
|
||||
getSiType (lookupId: ICompact<INumber> | string | number): {
|
||||
def: {
|
||||
asTuple: ICompact<INumber>[]
|
||||
}
|
||||
},
|
||||
getTypeDef (lookupId: ICompact<INumber> | string | number): TypeDef;
|
||||
}
|
||||
|
||||
export interface LookupRegistry extends CodecRegistry {
|
||||
lookup: ILookup;
|
||||
|
||||
createLookupType (lookupId: ICompact<INumber> | number): string;
|
||||
setLookup (lookup: ILookup): void;
|
||||
|
||||
getUnsafe <T extends Codec = Codec, K extends string = string> (name: K, withUnknown?: boolean, knownTypeDef?: TypeDef): CodecClass<T> | undefined;
|
||||
}
|
||||
|
||||
// Note the commented interfaces here are directly from CodecRegistry
|
||||
export interface Registry extends LookupRegistry {
|
||||
export interface Registry extends CreateRegistry {
|
||||
// readonly chainDecimals: number[];
|
||||
// readonly chainSS58: number | undefined;
|
||||
// readonly chainTokens: string[];
|
||||
|
||||
Reference in New Issue
Block a user