createType allows multiple params (#1207)

This commit is contained in:
Jaco Greeff
2019-07-27 08:05:11 +02:00
committed by GitHub
parent d56905d1b5
commit 99368a6d4d
19 changed files with 71 additions and 70 deletions
+1 -1
View File
@@ -32,6 +32,6 @@
"@polkadot/types": "^0.82.0-beta.96"
},
"devDependencies": {
"@polkadot/keyring": "^0.94.1"
"@polkadot/keyring": "^0.95.0-beta.1"
}
}
+3 -3
View File
@@ -28,10 +28,10 @@
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/types": "^0.82.0-beta.96",
"@polkadot/util": "^0.94.1",
"@polkadot/util-crypto": "^0.94.1"
"@polkadot/util": "^0.95.0-beta.1",
"@polkadot/util-crypto": "^0.95.0-beta.1"
},
"devDependencies": {
"@polkadot/keyring": "^0.94.1"
"@polkadot/keyring": "^0.95.0-beta.1"
}
}
@@ -23,7 +23,7 @@ export default function fromMetadata (metadata: Metadata): Constants {
// For access, we change the index names, i.e. Democracy.EnactmentPeriod -> democracy.enactmentPeriod
result[stringCamelCase(name.toString())] = moduleMetadata.constants.reduce((newModule, meta): ModuleConstants => {
const codec = createTypeUnsafe(meta.type.toString(), meta.value);
const codec = createTypeUnsafe(meta.type.toString(), [meta.value]);
// This is not a perfect idea, however as it stands with number-only constants on the metadata
// does not have any effect. However, this could become problematic in cases where items are
@@ -6,7 +6,7 @@ import { Method } from '@polkadot/types/interfaces';
import { FunctionMetadata } from '@polkadot/types/Metadata/v7/Calls';
import { MethodFunction } from '@polkadot/types/primitive/Generic/Method';
import { ClassOf } from '@polkadot/types';
import { createType } from '@polkadot/types';
import { assert, stringCamelCase } from '@polkadot/util';
/**
@@ -33,7 +33,7 @@ export default function createDescriptor (
`Extrinsic ${section}.${funcName} expects ${expectedArgs.length.valueOf()} arguments, got ${args.length}.`
);
return new (ClassOf('Method'))({
return createType('Method', {
args,
callIndex
}, callMetadata);
@@ -70,9 +70,9 @@ export default function createFunction ({ meta, method, prefix, section }: Creat
const [key1, key2] = arg as [CreateArgType, CreateArgType];
const type1 = meta.type.asDoubleMap.key1.toString();
const type2 = meta.type.asDoubleMap.key2.toString();
const param1Encoded = u8aConcat(key, createTypeUnsafe(type1, key1).toU8a(true));
const param1Encoded = u8aConcat(key, createTypeUnsafe(type1, [key1]).toU8a(true));
const param1Hashed = hasher(param1Encoded);
const param2Hashed = key2Hasher(createTypeUnsafe(type2, key2).toU8a(true));
const param2Hashed = key2Hasher(createTypeUnsafe(type2, [key2]).toU8a(true));
return Compact.addLengthPrefix(u8aConcat(param1Hashed, param2Hashed));
}
@@ -81,7 +81,7 @@ export default function createFunction ({ meta, method, prefix, section }: Creat
assert(!isUndefined(arg) && !isNull(arg), `${meta.name} expects one argument`);
const type = meta.type.asMap.key.toString();
const param = createTypeUnsafe(type, arg).toU8a();
const param = createTypeUnsafe(type, [arg]).toU8a();
key = u8aConcat(key, param);
}
+2 -2
View File
@@ -32,9 +32,9 @@
"@polkadot/rpc-core": "^0.82.0-beta.96",
"@polkadot/rpc-provider": "^0.82.0-beta.96",
"@polkadot/types": "^0.82.0-beta.96",
"@polkadot/util-crypto": "^0.94.1"
"@polkadot/util-crypto": "^0.95.0-beta.1"
},
"devDependencies": {
"@polkadot/keyring": "^0.94.1"
"@polkadot/keyring": "^0.95.0-beta.1"
}
}
+2 -2
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import { createType, ClassOf, GenericMethod } from '@polkadot/types';
import { createType, GenericMethod } from '@polkadot/types';
import SignerPayload from './SignerPayload';
@@ -66,7 +66,7 @@ describe('SignerPayload', (): void => {
it('can be used as a feed to ExtrinsicPayload', (): void => {
const signer = new SignerPayload(TEST).toPayload();
const payload = new (ClassOf('ExtrinsicPayload'))(signer, { version: signer.version });
const payload = createType('ExtrinsicPayload', signer, { version: signer.version });
expect(payload.era.toHex()).toEqual(TEST.era);
expect(payload.method.toHex()).toEqual(TEST.method);
+2 -2
View File
@@ -9,7 +9,7 @@ import { ApiInterfaceRx, ApiTypes } from './types';
import BN from 'bn.js';
import { Observable, combineLatest, of } from 'rxjs';
import { first, map, mergeMap, switchMap, tap } from 'rxjs/operators';
import { createType, ClassOf, Vec } from '@polkadot/types';
import { createType, Vec } from '@polkadot/types';
import { isBn, isFunction, isNumber, isUndefined } from '@polkadot/util';
import filterEvents from './util/filterEvents';
@@ -113,7 +113,7 @@ export default function createSubmittableExtrinsic<ApiType> (
extrinsic: Method | Uint8Array | string,
trackingCb?: Callback<ISubmittableResult>
): SubmittableExtrinsic<ApiType> {
const _extrinsic = new (ClassOf('Extrinsic'))(extrinsic, { version: api.extrinsicType }) as unknown as SubmittableExtrinsic<ApiType>;
const _extrinsic = createType('Extrinsic', extrinsic, { version: api.extrinsicType }) as unknown as SubmittableExtrinsic<ApiType>;
const _noStatusCb = type === 'rxjs';
function updateSigner (updateId: number, status: Hash | ISubmittableResult): void {
+3 -2
View File
@@ -99,7 +99,8 @@ export default async function test (): Promise<void> {
const compact = createType('Compact<u32>', 2);
// const random = createType('RandomType', 2); // This one should deliberately show a TS error
const gasUnsafe = createTypeUnsafe('Gas', 2);
const overriddenUnsafe = createTypeUnsafe<Header>('Gas', 2);
const gasUnsafe = createTypeUnsafe('Gas', [2]);
const overriddenUnsafe = createTypeUnsafe<Header>('Gas', [2]);
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
}
@@ -5,7 +5,7 @@
import { Signer, SignerPayload, SignerResult } from '@polkadot/api/types';
import { KeyringPair } from '@polkadot/keyring/types';
import { ClassOf } from '@polkadot/types';
import { createType } from '@polkadot/types';
let id = 0;
@@ -41,7 +41,7 @@ export default class SingleAccountSigner implements Signer {
return new Promise((resolve): void => {
setTimeout((): void => {
const signed = new (ClassOf('ExtrinsicPayload'))(payload, { version: payload.version }).sign(this.keyringPair);
const signed = createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.keyringPair);
const result: SignerResult = { id: ++id, ...signed };
resolve(result);
+1 -1
View File
@@ -30,7 +30,7 @@
"@polkadot/jsonrpc": "^0.82.0-beta.96",
"@polkadot/rpc-provider": "^0.82.0-beta.96",
"@polkadot/types": "^0.82.0-beta.96",
"@polkadot/util": "^0.94.1",
"@polkadot/util": "^0.95.0-beta.1",
"rxjs": "^6.5.2"
}
}
+6 -6
View File
@@ -262,12 +262,12 @@ export default class Rpc implements RpcInterface {
assert(inputs.length >= reqArgCount && inputs.length <= method.params.length, `Expected ${method.params.length} parameters${optText}, ${inputs.length} found instead`);
return inputs.map((input, index): Codec =>
createTypeUnsafe(method.params[index].type, input)
createTypeUnsafe(method.params[index].type, [input])
);
}
private formatOutput (method: RpcMethod, params: Codec[], result?: any): Codec | (Codec | null | undefined)[] {
const base = createTypeUnsafe(method.type as string, result);
const base = createTypeUnsafe(method.type as string, [result]);
if (method.type === 'StorageData') {
const key = params[0] as StorageKey;
@@ -310,11 +310,11 @@ export default class Rpc implements RpcInterface {
if (meta.modifier.isOptional) {
return new Option(
createClass(type),
isNull ? null : createTypeUnsafe(type, base, true)
isNull ? null : createTypeUnsafe(type, [base], true)
);
}
return createTypeUnsafe(type, isNull ? meta.fallback : base, true);
return createTypeUnsafe(type, [isNull ? meta.fallback : base], true);
}
private formatStorageSet (key: StorageKey, base: StorageChangeSet): Codec {
@@ -337,10 +337,10 @@ export default class Rpc implements RpcInterface {
if (meta.modifier.isOptional) {
return new Option(
createClass(type),
value.isNone ? null : createTypeUnsafe(type, value.unwrap(), true)
value.isNone ? null : createTypeUnsafe(type, [value.unwrap()], true)
);
}
return createTypeUnsafe(type, value.unwrapOr(meta.fallback), true);
return createTypeUnsafe(type, [value.unwrapOr(meta.fallback)], true);
}
}
+3 -3
View File
@@ -28,15 +28,15 @@
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/api-metadata": "^0.82.0-beta.96",
"@polkadot/util": "^0.94.1",
"@polkadot/util-crypto": "^0.94.1",
"@polkadot/util": "^0.95.0-beta.1",
"@polkadot/util-crypto": "^0.95.0-beta.1",
"@types/nock": "^10.0.3",
"eventemitter3": "^4.0.0",
"isomorphic-fetch": "^2.2.1",
"websocket": "^1.0.29"
},
"devDependencies": {
"@polkadot/keyring": "^0.94.1",
"@polkadot/keyring": "^0.95.0-beta.1",
"mock-socket": "^8.0.5",
"nock": "^10.0.4"
}
+3 -3
View File
@@ -27,12 +27,12 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^0.94.1",
"@polkadot/util-crypto": "^0.94.1",
"@polkadot/util": "^0.95.0-beta.1",
"@polkadot/util-crypto": "^0.95.0-beta.1",
"@types/memoizee": "^0.4.2",
"memoizee": "^0.4.14"
},
"devDependencies": {
"@polkadot/keyring": "^0.94.1"
"@polkadot/keyring": "^0.95.0-beta.1"
}
}
+1 -1
View File
@@ -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 => createTypeUnsafe(type.toString(), fallback)
(): Codec => createTypeUnsafe(type.toString(), [fallback])
).not.toThrow();
});
});
+2 -2
View File
@@ -53,9 +53,9 @@ describe('Vec', (): void => {
});
it.skip('decodes a complex type via construction', (): void => {
const test = createTypeUnsafe('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;
expect((first[0] as PropIndex).toNumber()).toEqual(10);
+11 -11
View File
@@ -225,10 +225,10 @@ describe('createClass', (): void => {
describe('createType', (): void => {
it('allows creation of a Struct', (): void => {
expect(
createTypeUnsafe('{"balance":"Balance","index":"u32"}', {
createTypeUnsafe('{"balance":"Balance","index":"u32"}', [{
balance: 1234,
index: '0x10'
}).toJSON()
}]).toJSON()
).toEqual({
balance: 1234,
index: 16
@@ -237,31 +237,31 @@ describe('createType', (): void => {
it('allows creation of a Enum (simple)', (): void => {
expect(
createTypeUnsafe('{"_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(
createTypeUnsafe('{"_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(
createTypeUnsafe<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(
createTypeUnsafe('[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(
createTypeUnsafe('[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]));
});
@@ -269,7 +269,7 @@ describe('createType', (): void => {
const base = createType('StorageData', null);
expect(
(): Codec => createTypeUnsafe('DoubleMap<Vec<(BlockNumber,EventIndex)>>', base, true)
(): Codec => createTypeUnsafe('DoubleMap<Vec<(BlockNumber,EventIndex)>>', [base], true)
).toThrow(/ Input doesn't match output, received 0x, created 0x00/);
});
@@ -277,7 +277,7 @@ describe('createType', (): void => {
const base = createType('StorageData', null);
expect(
(): Codec => createTypeUnsafe('Vec<(BlockNumber,EventIndex)>', base, true)
(): Codec => createTypeUnsafe('Vec<(BlockNumber,EventIndex)>', [base], true)
).toThrow(/Input doesn't match output, received 0x, created 0x00/);
});
@@ -298,12 +298,12 @@ describe('createType', (): void => {
it('instanceof should work (complex type)', (): void => {
const complexType = '{"balance":"Balance","account_id":"AccountId","log":"(u64, u32)","fromSrml":"Gas"}';
const value = createTypeUnsafe(complexType, {
const value = createTypeUnsafe(complexType, [{
balance: 123,
accountId: '',
log: [456, 789],
fromSrml: 0
});
}]);
const ComplexType = createClass(complexType);
expect(value instanceof ComplexType).toBe(true);
+8 -8
View File
@@ -328,9 +328,10 @@ export function getTypeClass<T extends Codec = Codec> (value: TypeDef, Fallback?
throw new Error(`Unable to determine type from ${JSON.stringify(value)}`);
}
function initType<T extends Codec = Codec, K extends string = string> (Type: Constructor<FromReg<T, K>>, value?: any, isPedantic?: boolean): FromReg<T, K> {
function initType<T extends Codec = Codec, K extends string = string> (Type: Constructor<FromReg<T, K>>, params: any[] = [], isPedantic?: boolean): FromReg<T, K> {
try {
const created = new Type(value);
const created = new Type(...params);
const [value] = params;
// in pedantic mode, actually check that the encoding matches that supplied - this
// is much slower, but ensures that we have a 100% grasp on the actual provided value
@@ -352,7 +353,7 @@ function initType<T extends Codec = Codec, K extends string = string> (Type: Con
return created;
} catch (error) {
if (Type.Fallback) {
return initType(Type.Fallback as Constructor<FromReg<T, K>>, value, isPedantic);
return initType(Type.Fallback as Constructor<FromReg<T, K>>, params, isPedantic);
}
throw error;
@@ -364,11 +365,11 @@ function initType<T extends Codec = Codec, K extends string = string> (Type: Con
// runtime error.
export function createTypeUnsafe<T extends Codec = Codec, K extends string = string> (
type: K,
value?: any,
params: any[] = [],
isPedantic?: boolean
): FromReg<T, K> {
try {
return initType(createClass<T, K>(type), value, isPedantic);
return initType(createClass<T, K>(type), params, isPedantic);
} catch (error) {
throw new Error(`createType(${type}):: ${error.message}`);
}
@@ -385,8 +386,7 @@ export function createTypeUnsafe<T extends Codec = Codec, K extends string = str
*/
export default function createType<K extends keyof InterfaceRegistry> (
type: K,
value?: any,
isPedantic?: boolean
...params: any[]
): InterfaceRegistry[K] {
return createTypeUnsafe<Codec, K>(type, value, isPedantic) as InterfaceRegistry[K];
return createTypeUnsafe<Codec, K>(type, params) as InterfaceRegistry[K];
}