Rewrite Method (#308)

* Let Method extend Struct

* Fix Method

* Allow to pass array into Struct constructor

* Formatting

* Fix tests

* Add explicit function return type
This commit is contained in:
Amaury Martiny
2018-10-17 10:46:12 +02:00
committed by Jaco Greeff
parent 30b1b4fcc8
commit 471bfce769
5 changed files with 104 additions and 74 deletions
@@ -2,12 +2,18 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details. // of the ISC license. See the LICENSE file for details.
import Extrinsic from './SubmittableExtrinsic'; import extrinsics from '@polkadot/extrinsics/static';
import Extrinsic from '@polkadot/types/Extrinsic';
import Method from '@polkadot/types/Method';
import SubmittableExtrinsic from './SubmittableExtrinsic';
describe('SubmittableExtrinsic', () => { describe('SubmittableExtrinsic', () => {
let api; let api;
beforeEach(() => { beforeEach(() => {
Method.injectExtrinsics(extrinsics);
api = { api = {
rpc: { rpc: {
author: { author: {
@@ -19,13 +25,19 @@ describe('SubmittableExtrinsic', () => {
}); });
it('send calls submitAndWatchExtrinsic with statusCb', async () => { it('send calls submitAndWatchExtrinsic with statusCb', async () => {
const result = await new Extrinsic(api).send(() => {}); const result = await new SubmittableExtrinsic(
api,
new Extrinsic('0x010200ea51b75b00000000')
).send(() => { });
expect(result).toEqual('submitAndWatchExtrinsic'); expect(result).toEqual('submitAndWatchExtrinsic');
}); });
it('send calls submitExtrinsic without statusCb', async () => { it('send calls submitExtrinsic without statusCb', async () => {
const result = await new Extrinsic(api).send(); const result = await new SubmittableExtrinsic(
api,
new Extrinsic('0x010200ea51b75b00000000')
).send();
expect(result).toEqual('submitExtrinsic'); expect(result).toEqual('submitExtrinsic');
}); });
@@ -30,7 +30,10 @@ export default function createDescriptor (
} }
return new Extrinsic({ return new Extrinsic({
method: new Method(callIndex, meta, args) method: new Method({
methodIndex: callIndex,
args
}, meta)
}); });
}; };
+11
View File
@@ -0,0 +1,11 @@
// Copyright 2017-2018 @polkadot/extrinsics authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import Method from './Method';
describe('Metadata', () => {
it('throws when not decodable', () => {
expect(() => new Method('foo')).toThrowError(/Method: cannot decode value/);
});
});
+67 -67
View File
@@ -2,73 +2,77 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details. // of the ISC license. See the LICENSE file for details.
import { AnyU8a } from './types'; import assert from '@polkadot/util/assert';
import { ExtrinsicFunction, Extrinsics } from '@polkadot/extrinsics/types'; import { ExtrinsicFunction, Extrinsics } from '@polkadot/extrinsics/types';
import isObject from '@polkadot/util/is/object';
import isU8a from '@polkadot/util/is/u8a'; import isU8a from '@polkadot/util/is/u8a';
import u8aConcat from '@polkadot/util/u8a/concat';
import createType from './codec/createType'; import { AnyU8a, Constructor } from './types';
import Base from './codec/Base'; import Base from './codec/Base';
import MethodIndex from './MethodIndex';
import { FunctionMetadata, FunctionArgumentMetadata } from './Metadata'; import { FunctionMetadata, FunctionArgumentMetadata } from './Metadata';
import { getTypeDef, getTypeClass } from './codec/createType';
import MethodIndex from './MethodIndex';
import Struct from './codec/Struct';
import isHex from '@polkadot/util/is/hex';
const FN_UNKNOWN = { const FN_UNKNOWN = {
method: 'unknown', method: 'unknown',
section: 'unknown' section: 'unknown'
} as ExtrinsicFunction; } as ExtrinsicFunction;
interface ArgsDef {
[index: string]: Constructor<Base>;
}
interface DecodedMethod {
args: any;
argsDef: ArgsDef;
meta: FunctionMetadata;
methodIndex: MethodIndex | AnyU8a;
}
const extrinsicFns: { [index: string]: ExtrinsicFunction } = {}; const extrinsicFns: { [index: string]: ExtrinsicFunction } = {};
/** /**
* Extrinsic function descriptor, as defined in * Extrinsic function descriptor, as defined in
* {@link https://github.com/paritytech/wiki/blob/master/Extrinsic.md#the-extrinsic-format-for-node}. * {@link https://github.com/paritytech/wiki/blob/master/Extrinsic.md#the-extrinsic-format-for-node}.
* // FIXME This class should extend Struct({ callIndex, method })
*/ */
export default class Method extends MethodIndex { export default class Method extends Struct {
protected _args: Array<Base>;
protected _data: Uint8Array;
protected _meta: FunctionMetadata; protected _meta: FunctionMetadata;
constructor (index: Method | AnyU8a, meta?: FunctionMetadata, args?: Array<any>) { constructor (value: any, meta?: FunctionMetadata) {
super(index); const decoded = Method.decodeMethod(value, meta);
if (index instanceof Method) { super({
this._args = args || index.args; methodIndex: MethodIndex,
this._meta = meta || index.meta; args: Struct.with(decoded.argsDef)
} else { }, decoded);
this._args = args || [];
this._meta = meta || Method.findFunction(this.callIndex).meta;
}
this._data = Method.encode(this._meta, this._args);
// FIXME this is really not clean, we're saying that if the callIndex is
// longer than 2 bytes, then we need to decode the rest too.
if (isU8a(index) && index.length > 2) {
this.fromU8a(index);
}
this._meta = decoded.meta;
} }
static decodeMethod (meta: FunctionMetadata, data: Uint8Array): Array<Base> { static decodeMethod (value: Uint8Array | string | DecodedMethod, _meta?: FunctionMetadata): DecodedMethod {
let offset = 0; if (isHex(value)) {
return Method.decodeMethod(value, _meta);
} else if (isU8a(value)) {
// The first 2 bytes are the callIndex
const callIndex = value.subarray(0, 2);
return Method.filterOrigin(meta).map(({ type }) => { // Find metadata with callIndex
const base = createType(type, data.subarray(offset)); const meta = _meta || Method.findFunction(callIndex).meta;
offset += base.byteLength(); // Get Struct definition of the arguments
const argsDef = Method.getArgsDef(meta);
return base; return { args: value.subarray(2), argsDef, methodIndex: callIndex, meta };
}); } else if (isObject(value) && _meta && (value as any).methodIndex && (value as any).args) {
} // If we instantiate a Method with an object value, we require (for now)
// that `_meta` be specified.
const argsDef = Method.getArgsDef(_meta);
return { ...value, argsDef };
}
static encode (meta: FunctionMetadata, args: Array<any>): Uint8Array { throw new Error(`Method: cannot decode value "${value}".`);
const encoded = Method.filterOrigin(meta).map(({ type }, index) =>
createType(type, args[index]).toU8a()
);
return u8aConcat(...encoded);
} }
// If the extrinsic function has an argument of type `Origin`, we ignore it // If the extrinsic function has an argument of type `Origin`, we ignore it
@@ -89,9 +93,27 @@ export default class Method extends MethodIndex {
// As a convenience helper though, we return the full constructor function, // As a convenience helper though, we return the full constructor function,
// which includes the meta, name, section & actual interface for calling // which includes the meta, name, section & actual interface for calling
static findFunction (callIndex: Uint8Array): ExtrinsicFunction { static findFunction (callIndex: Uint8Array): ExtrinsicFunction {
assert(Object.keys(extrinsicFns).length > 0, 'Calling Method.findFunction before extrinsics have been injected.');
return extrinsicFns[callIndex.toString()] || FN_UNKNOWN; return extrinsicFns[callIndex.toString()] || FN_UNKNOWN;
} }
/**
* Get a mapping of `argument name -> argument type` for the function, from
* its metadata.
*
* @param meta - The function metadata used to get the definition.
*/
private static getArgsDef (meta: FunctionMetadata): ArgsDef {
return Method.filterOrigin(meta).reduce((result, { name, type }) => {
const Type = getTypeClass(
getTypeDef(type)
);
result[name.toString()] = Type;
return result;
}, {} as ArgsDef);
}
// This is called/injected by the API on init, allowing a snapshot of // This is called/injected by the API on init, allowing a snapshot of
// the available system extrinsics to be used in lookups // the available system extrinsics to be used in lookups
static injectExtrinsics (extrinsics: Extrinsics): void { static injectExtrinsics (extrinsics: Extrinsics): void {
@@ -102,41 +124,19 @@ export default class Method extends MethodIndex {
); );
} }
byteLength (): number { get args (): Array<Base> {
return super.byteLength() + this.data.length; return (this.get(1) as Struct<Base>).values();
} }
get args (): Array<any> { get callIndex (): Uint8Array {
return this._args; return (this.get(0) as MethodIndex).callIndex;
} }
get data (): Uint8Array { get data (): Uint8Array {
return this._data; return (this.get(1) as Struct<Base>).toU8a();
} }
get meta (): FunctionMetadata { get meta (): FunctionMetadata {
return this._meta; return this._meta;
} }
fromU8a (input: Uint8Array): Method {
super.fromU8a(input);
const startData = super.byteLength();
this._meta = Method.findFunction(this.callIndex).meta;
this._args = Method.decodeMethod(this._meta, input.subarray(startData));
const argsLength = this._args.reduce((length, arg) => length + arg.byteLength(), 0);
this._data = input.subarray(startData, startData + argsLength);
return this;
}
toU8a (isBare?: boolean): Uint8Array {
return u8aConcat(
super.toU8a(isBare),
this.data
);
}
} }
+7 -3
View File
@@ -51,8 +51,6 @@ export default class Struct<
if (isHex(value)) { if (isHex(value)) {
return Struct.decodeStruct(Types, hexToU8a(value as string), jsonMap); return Struct.decodeStruct(Types, hexToU8a(value as string), jsonMap);
} else if (Array.isArray(value)) {
return Struct.decodeStruct(Types, toU8a(value), jsonMap);
} else if (!value) { } else if (!value) {
return {} as T; return {} as T;
} }
@@ -63,7 +61,7 @@ export default class Struct<
return Object return Object
.keys(Types) .keys(Types)
.reduce((raw: T, key) => { .reduce((raw: T, key, index) => {
// The key in the JSON can be snake_case (or other cases), but in our // The key in the JSON can be snake_case (or other cases), but in our
// Types, result or any other maps, it's camelCase // Types, result or any other maps, it's camelCase
const jsonKey = (jsonMap.get(key as any) && !value[key]) ? jsonMap.get(key as any) : key; const jsonKey = (jsonMap.get(key as any) && !value[key]) ? jsonMap.get(key as any) : key;
@@ -83,6 +81,12 @@ export default class Struct<
} else if (value[jsonKey] instanceof Types[key]) { } else if (value[jsonKey] instanceof Types[key]) {
// @ts-ignore FIXME See below // @ts-ignore FIXME See below
raw[key] = value[jsonKey]; raw[key] = value[jsonKey];
} else if (Array.isArray(value) && value.length === Object.keys(Types).length) {
// @ts-ignore FIXME See below
raw[key] = new Types[key](
// @ts-ignore FIXME
value[index]
);
} else if (isObject(value)) { } else if (isObject(value)) {
// @ts-ignore FIXME Ok, something weird is going on here or I just don't get it... // @ts-ignore FIXME Ok, something weird is going on here or I just don't get it...
// it works, so ignore the checker, although it drives me batty. (It started when // it works, so ignore the checker, although it drives me batty. (It started when