CreateType is typed, add createTypeUnsafe just in case (#1199)

* Use unsafe internally

* Add comments

* Remove <> in createType

* Fix lint

* Fix classOf

* Remove createType from Text

* Fix lint

* Fix Fallback type

* Fix fallback in createType
This commit is contained in:
Amaury Martiny
2019-07-26 14:00:25 +02:00
committed by Jaco Greeff
parent ec0b9a84a3
commit 441148889d
24 changed files with 112 additions and 104 deletions
+2 -2
View File
@@ -6,7 +6,7 @@ import '../../injector';
import extrinsicsFromMeta from '@polkadot/api-metadata/extrinsics/fromMetadata';
import createType from '../../codec/createType';
import { createTypeUnsafe } from '../../codec/createType';
import Metadata from '../Metadata';
import Method from '../../primitive/Method';
import { MetadataInterface } from '../types';
@@ -62,7 +62,7 @@ export function defaultValues (rpcData: string): void {
mod.storage.unwrap().items.forEach(({ fallback, name, type }): void => {
it(`creates default types for ${mod.name}.${name}, type ${type}`, (): void => {
expect(
(): Codec => createType(type.toString(), fallback)
(): Codec => createTypeUnsafe(type.toString(), fallback)
).not.toThrow();
});
});
+3 -5
View File
@@ -4,8 +4,6 @@
import '../injector';
import { Balance, BlockNumber } from '../interfaces/runtime';
import BN from 'bn.js';
import createType, { ClassOf } from '../codec/createType';
@@ -66,7 +64,7 @@ describe('Compact', (): void => {
it('encondes a large balance', (): void => {
expect(
Compact.encodeU8a(createType<Balance>('Balance', '0x5af3107a4000'))
Compact.encodeU8a(createType('Balance', '0x5af3107a4000'))
).toEqual(
new Uint8Array([
3 + ((6 - 4) << 2),
@@ -111,13 +109,13 @@ describe('Compact', (): void => {
describe('constructor', (): void => {
it('has the correct bitLength for constructor values (BlockNumber)', (): void => {
expect(
new Compact(ClassOf<BlockNumber>('BlockNumber'), 0xfffffff9).bitLength()
new Compact(ClassOf('BlockNumber'), 0xfffffff9).bitLength()
).toEqual(64);
});
it('has the correct encodedLength for constructor values (BlockNumber)', (): void => {
expect(
new Compact(ClassOf<BlockNumber>('BlockNumber'), 0xfffffff9).encodedLength
new Compact(ClassOf('BlockNumber'), 0xfffffff9).encodedLength
).toEqual(5);
});
+2 -2
View File
@@ -10,7 +10,7 @@ import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import AccountId from '../primitive/AccountId';
import Method from '../primitive/Method';
import Text from '../primitive/Text';
import createType from './createType';
import { createTypeUnsafe } from './createType';
import Vec from './Vec';
import Tuple from './Tuple';
@@ -53,7 +53,7 @@ describe('Vec', (): void => {
});
it.skip('decodes a complex type via construction', (): void => {
const test = createType('Vec<(PropIndex, Proposal, AccountId)>', new Uint8Array([
const test = createTypeUnsafe('Vec<(PropIndex, Proposal, AccountId)>', new Uint8Array([
4, 10, 0, 0, 0, 0, 3, 80, 123, 10, 9, 34, 48, 120, 52, 50, 34, 58, 32, 34, 48, 120, 52, 51, 34, 10, 125, 10, 209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79
]));
const first = (test as Vec<Codec>)[0] as Tuple;
+10 -25
View File
@@ -6,8 +6,7 @@ import '../injector';
import { Codec, Constructor } from '../types';
import createType, { TypeDef, TypeDefInfo, createClass, getTypeClass, getTypeDef, typeSplit, ClassOf } from './createType';
import Text from '../primitive/Text';
import createType, { TypeDef, TypeDefInfo, createClass, createTypeUnsafe, getTypeClass, getTypeDef, typeSplit, ClassOf } from './createType';
import CodecSet from './Set';
describe('typeSplit', (): void => {
@@ -221,26 +220,12 @@ describe('createClass', (): void => {
expect(a).toBe(b);
});
it('should memoize from Text', (): void => {
const a = createClass(new Text('TrieId'));
const b = createClass(new Text('TrieId'));
expect(a).toBe(b);
});
it('should memoize from string/Text combo', (): void => {
const a = createClass(new Text('AuthorityWeight'));
const b = createClass('AuthorityWeight');
expect(a).toBe(b);
});
});
describe('createType', (): void => {
it('allows creation of a Struct', (): void => {
expect(
createType('{"balance":"Balance","index":"u32"}', {
createTypeUnsafe('{"balance":"Balance","index":"u32"}', {
balance: 1234,
index: '0x10'
}).toJSON()
@@ -252,31 +237,31 @@ describe('createType', (): void => {
it('allows creation of a Enum (simple)', (): void => {
expect(
createType('{"_enum": ["A", "B", "C"]}', 1).toJSON()
createTypeUnsafe('{"_enum": ["A", "B", "C"]}', 1).toJSON()
).toEqual({ B: null });
});
it('allows creation of a Enum (parametrised)', (): void => {
expect(
createType('{"_enum": {"A": null, "B": "u32", "C": null} }', 1).toJSON()
createTypeUnsafe('{"_enum": {"A": null, "B": "u32", "C": null} }', 1).toJSON()
).toEqual({ B: 0 });
});
it('allows creation of a Set', (): void => {
expect(
createType<CodecSet>('{"_set": { "A": 1, "B": 2, "C": 4, "D": 8, "E": 16, "G": 32, "H": 64, "I": 128 } }', 1 + 4 + 16 + 64).strings
createTypeUnsafe<CodecSet>('{"_set": { "A": 1, "B": 2, "C": 4, "D": 8, "E": 16, "G": 32, "H": 64, "I": 128 } }', 1 + 4 + 16 + 64).strings
).toEqual(['A', 'C', 'E', 'H']);
});
it('allows creation of a [u8; 8]', (): void => {
expect(
createType('[u8; 8]', [0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67, 0x00]).toHex()
createTypeUnsafe('[u8; 8]', [0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67, 0x00]).toHex()
).toEqual('0x1200230045006700');
});
it('allows creation of a [u16; 4]', (): void => {
expect(
createType('[u16; 4]', [0x1200, 0x2300, 0x4500, 0x6700]).toU8a()
createTypeUnsafe('[u16; 4]', [0x1200, 0x2300, 0x4500, 0x6700]).toU8a()
).toEqual(new Uint8Array([0x00, 0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67]));
});
@@ -284,7 +269,7 @@ describe('createType', (): void => {
const base = createType('StorageData', null);
expect(
(): Codec => createType('DoubleMap<Vec<(BlockNumber,EventIndex)>>', base, true)
(): Codec => createTypeUnsafe('DoubleMap<Vec<(BlockNumber,EventIndex)>>', base, true)
).toThrow(/ Input doesn't match output, received 0x, created 0x00/);
});
@@ -292,7 +277,7 @@ describe('createType', (): void => {
const base = createType('StorageData', null);
expect(
(): Codec => createType('Vec<(BlockNumber,EventIndex)>', base, true)
(): Codec => createTypeUnsafe('Vec<(BlockNumber,EventIndex)>', base, true)
).toThrow(/Input doesn't match output, received 0x, created 0x00/);
});
@@ -313,7 +298,7 @@ describe('createType', (): void => {
it('instanceof should work (complex type)', (): void => {
const complexType = '{"balance":"Balance","account_id":"AccountId","log":"(u64, u32)","fromSrml":"Gas"}';
const value = createType(complexType, {
const value = createTypeUnsafe(complexType, {
balance: 123,
accountId: '',
log: [456, 789],
+46 -23
View File
@@ -8,7 +8,6 @@ import { assert } from '@polkadot/util';
import { InterfaceRegistry } from '../interfaceRegistry';
import { Codec, Constructor } from '../types';
import Null from '../primitive/Null';
import Text from '../primitive/Text';
import Compact from './Compact';
import Enum from './Enum';
import Linkage from './Linkage';
@@ -22,6 +21,9 @@ import Vec from './Vec';
import VecFixed from './VecFixed';
import getRegistry from './typeRegistry';
// Type which says: if `K` is in the InterfaceRegistry, then return InterfaceRegistry[K], else fallback to T
type FromReg<T extends Codec, K extends string> = K extends keyof InterfaceRegistry ? InterfaceRegistry[K] : T
export enum TypeDefInfo {
Compact,
DoubleMap,
@@ -135,7 +137,7 @@ function _decodeSet (value: TypeDef, details: Record<string, number>): TypeDef {
return value;
}
export function getTypeDef (_type: Text | string, name?: string): TypeDef {
export function getTypeDef (_type: string, name?: string): TypeDef {
const type = _type.toString().trim();
const value: TypeDef = {
info: TypeDefInfo.Plain,
@@ -202,27 +204,33 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
}
// Memoized helper of the `createClass` function below
const memoizedCreateClass = memoizee(<T extends Codec = Codec, K extends Text | string = Text | string>(
const memoizedCreateClass = memoizee(<T extends Codec = Codec, K extends string = string>(
type: K
): Constructor<K extends keyof InterfaceRegistry ? InterfaceRegistry[K] : T> => {
): Constructor<FromReg<T, K>> => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return getTypeClass<K extends keyof InterfaceRegistry ? InterfaceRegistry[K] : T>(
return getTypeClass<FromReg<T, K>>(
getTypeDef(type)
);
}, {
length: 1,
// Normalize args so that different args that should be cached
// together are cached together.
// E.g.: `createClass('abc') === createClass(new Text('abc'));`
normalizer: JSON.stringify
});
}, { length: 1 });
export function createClass<T extends Codec = Codec, K extends Text | string = Text | string> (
export function createClass<T extends Codec = Codec, K extends string = string> (
type: K
): Constructor<K extends keyof InterfaceRegistry ? InterfaceRegistry[K] : T> {
): Constructor<FromReg<T, K>> {
return memoizedCreateClass(type);
}
// An unsafe version of the `createType` below. It's unsafe because the `type`
// argument here can be any string, which, if not parseable, will yield a
// runtime error.
export function ClassOfUnsafe<T extends Codec = Codec, K extends string = string> (name: K): Constructor<FromReg<T, K>> {
return createClass<T, K>(name);
}
// alias for createClass
export function ClassOf<K extends keyof InterfaceRegistry> (name: K): Constructor<InterfaceRegistry[K]> {
return ClassOfUnsafe<Codec, K>(name) as Constructor<InterfaceRegistry[K]>;
}
// create an array of constructors from the input
export function getTypeClassMap (defs: TypeDef[]): { [index: string]: Constructor } {
return defs.reduce((result, sub): Record<string, Constructor> => {
@@ -320,12 +328,7 @@ export function getTypeClass<T extends Codec = Codec> (value: TypeDef, Fallback?
throw new Error(`Unable to determine type from ${JSON.stringify(value)}`);
}
// alias for createClass
export function ClassOf<T extends Codec = Codec, K extends Text | string = Text | string> (name: string): Constructor<T> {
return createClass<T>(name);
}
function initType<T extends Codec = Codec, K extends Text | string = Text | string> (Type: Constructor<T>, value?: any, isPedantic?: boolean): T {
function initType<T extends Codec = Codec, K extends string = string> (Type: Constructor<FromReg<T, K>>, value?: any, isPedantic?: boolean): FromReg<T, K> {
try {
const created = new Type(value);
@@ -349,21 +352,41 @@ function initType<T extends Codec = Codec, K extends Text | string = Text | stri
return created;
} catch (error) {
if (Type.Fallback) {
return initType(Type.Fallback, value, isPedantic);
return initType(Type.Fallback as Constructor<FromReg<T, K>>, value, isPedantic);
}
throw error;
}
}
export default function createType<T extends Codec = Codec, K extends Text | string = Text | string> (
// An unsafe version of the `createType` below. It's unsafe because the `type`
// argument here can be any string, which, if not parseable, will yield a
// runtime error.
export function createTypeUnsafe<T extends Codec = Codec, K extends string = string> (
type: K,
value?: any,
isPedantic?: boolean
): K extends keyof InterfaceRegistry ? InterfaceRegistry[K] : T {
): FromReg<T, K> {
try {
return initType(createClass<T, K>(type), value, isPedantic);
} catch (error) {
throw new Error(`createType(${type}):: ${error.message}`);
}
}
/**
* Create an instance of a `type` with a given `value`.
* @param type - A recognizable string representing the type to create an
* instance from
* @param value - The value to instantiate the type with
* @param isPedantic - Double-check that the input's encoding matches the
* output's one. Slower, but ensures that we have a 100% grasp on the actual
* provided value
*/
export default function createType<K extends keyof InterfaceRegistry> (
type: K,
value?: any,
isPedantic?: boolean
): InterfaceRegistry[K] {
return createTypeUnsafe<Codec, K>(type, value, isPedantic) as InterfaceRegistry[K];
}
@@ -4,8 +4,6 @@
import '../../injector';
import { KeyValue } from './types';
import createType from '../../codec/createType';
describe('KeyValue', (): void => {
@@ -34,7 +32,7 @@ describe('KeyValue', (): void => {
});
it('exposes the properties for key/value', (): void => {
const [key, value] = createType<KeyValue>('KeyValue', ['0x11223344', '0x998877665544332211']);
const [key, value] = createType('KeyValue', ['0x11223344', '0x998877665544332211']);
expect(key.toHex()).toEqual('0x11223344');
expect(value.toHex()).toEqual('0x998877665544332211');
+1 -1
View File
@@ -119,7 +119,7 @@ export default class Event extends Struct {
section.events.unwrap().forEach((meta, methodIndex): void => {
const methodName = meta.name.toString();
const eventIndex = new Uint8Array([sectionIndex, methodIndex]);
const typeDef = meta.args.map((arg): TypeDef => getTypeDef(arg));
const typeDef = meta.args.map((arg): TypeDef => getTypeDef(arg.toString()));
const Types = typeDef.map((typeDef): Constructor<Codec> => getTypeClass(typeDef, Unconstructable.with(typeDef)));
EventTypes[eventIndex.toString()] = class extends EventData {
@@ -123,7 +123,7 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
era: era || IMMORTAL_ERA,
blockHash
});
const signature = createType<Signature>('Signature', payload.sign(account));
const signature = createType('Signature', payload.sign(account));
return this.injectSignature(signer, signature, payload);
}
@@ -128,7 +128,7 @@ export default class ExtrinsicSignatureV2 extends Struct implements IExtrinsicSi
nonce,
tip: tip || 0
});
const signature = createType<Signature>('Signature', payload.sign(account));
const signature = createType('Signature', payload.sign(account));
return this.injectSignature(signer, signature, payload);
}
+1 -1
View File
@@ -157,7 +157,7 @@ export default class Method extends Struct implements IMethod {
private static getArgsDef (meta: FunctionMetadataV7): ArgsDef {
return Method.filterOrigin(meta).reduce((result, { name, type }): ArgsDef => {
const Type = getTypeClass(
getTypeDef(type)
getTypeDef(type.toString())
);
result[name.toString()] = Type;
+2 -2
View File
@@ -32,7 +32,7 @@ export default class Vote extends U8a {
const conviction = decoded[0] & 0b01111111;
this._aye = new Bool(msb);
this._conviction = createType<Conviction>('Conviction', conviction);
this._conviction = createType('Conviction', conviction);
}
private static decodeVote (value?: any): Uint8Array {
@@ -48,7 +48,7 @@ export default class Vote extends U8a {
: new Uint8Array([0b0]);
} else if (isObject(value) && !isUndefined(value.aye) && !isUndefined(value.conviction)) {
const aye = new Bool(value.aye);
const convictionIndex = createType<Conviction>('Conviction', value.conviction).index;
const convictionIndex = createType('Conviction', value.conviction).index;
const result = convictionIndex | (aye.eq(true) ? 0b1 << 7 : 0b0);
+1 -1
View File
@@ -105,7 +105,7 @@ export interface IHash extends U8a { }
export type CodecTo = 'toHex' | 'toJSON' | 'toString' | 'toU8a';
export interface Constructor<T = Codec> {
Fallback?: Constructor<T>;
Fallback?: Constructor<Codec>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new(...value: any[]): T;