From e96ed94f4b4ab4121be60a1c94ffeaecdba171e9 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Tue, 9 Oct 2018 11:12:49 +0200 Subject: [PATCH] injectExtrinsics into Method (use for decoding) (#227) * injectExtrinsics into Method (use for decoding) * Comment typos --- packages/api-observable/src/Base.ts | 2 ++ packages/api/src/index.ts | 23 ++++++++++-- packages/types/src/Extrinsic.spec.js | 7 ++++ packages/types/src/Method.ts | 48 +++++++++++++++++++++----- packages/types/src/codec/Struct.ts | 25 ++++++++------ packages/types/src/codec/Tuple.spec.js | 20 +++++++++++ packages/types/src/codec/Tuple.ts | 30 ++++++++++++++-- 7 files changed, 133 insertions(+), 22 deletions(-) diff --git a/packages/api-observable/src/Base.ts b/packages/api-observable/src/Base.ts index a7b8e1b130..c2ba81d75b 100644 --- a/packages/api-observable/src/Base.ts +++ b/packages/api-observable/src/Base.ts @@ -51,6 +51,8 @@ export default class ApiBase { } try { + // FIXME This now gets done in api-core/rpc-core as well, cleanup as soon as we + // have apis based on api-rx & api-promise (For now a bit of inefficiency) const meta = await this._api.state.getMetadata().toPromise(); this._genesisHash = await this._api.chain.getBlockHash(0).toPromise(); diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 7912a850a2..4a2c161630 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -6,9 +6,10 @@ import { ProviderInterface, ProviderInterface$Callback } from '@polkadot/api-pro import { RpcSection, RpcMethod } from '@polkadot/jsonrpc/types'; import { ApiInterface, ApiInterface$Section, ApiInterface$Section$Method } from './types'; -import { Base, Vector, createType } from '@polkadot/types/codec'; -import { StorageChangeSet, StorageKey } from '@polkadot/types/index'; import interfaces from '@polkadot/jsonrpc/index'; +import extrinsicsFromMeta from '@polkadot/extrinsics/fromMetadata'; +import { Base, Vector, createType } from '@polkadot/types/codec'; +import { Method, StorageChangeSet, StorageKey } from '@polkadot/types/index'; import assert from '@polkadot/util/assert'; import ExtError from '@polkadot/util/ext/error'; import isFunction from '@polkadot/util/is/function'; @@ -49,6 +50,8 @@ export default class Api implements ApiInterface { this.chain = this.createInterface(interfaces.chain); this.state = this.createInterface(interfaces.state); this.system = this.createInterface(interfaces.system); + + this.init(); } /** @@ -74,6 +77,22 @@ export default class Api implements ApiInterface { return `${method} (${inputs}): ${type}`; } + private init (): void { + // load metadata and and setup the Method static so we are able to use + // decoding at any point going forward. This is not great, but the best + // we can come up with for now + this.state + .getMetadata() + .then((metadata) => { + Method.injectExtrinsics( + extrinsicsFromMeta(metadata) + ); + }) + .catch((error) => { + console.error('Unable to retrieve metadata', error); + }); + } + private createInterface ({ methods, section }: RpcSection): ApiInterface$Section { return Object .keys(methods) diff --git a/packages/types/src/Extrinsic.spec.js b/packages/types/src/Extrinsic.spec.js index 4ee44310db..ceb53d9fa3 100644 --- a/packages/types/src/Extrinsic.spec.js +++ b/packages/types/src/Extrinsic.spec.js @@ -2,9 +2,16 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import extrinsics from '@polkadot/extrinsics/static'; + import Extrinsic from './Extrinsic'; +import Method from './Method'; describe('Extrinsic', () => { + beforeEach(() => { + Method.injectExtrinsics(extrinsics); + }); + it('decodes a non-signed properly via fromJSON', () => { const extrinsic = new Extrinsic().fromJSON('0x010200ea51b75b00000000'); diff --git a/packages/types/src/Method.ts b/packages/types/src/Method.ts index 2084c117bb..7f5b138c3e 100644 --- a/packages/types/src/Method.ts +++ b/packages/types/src/Method.ts @@ -4,6 +4,7 @@ import { AnyU8a } from './types'; +import { ExtrinsicFunction, Extrinsics } from '@polkadot/extrinsics/types'; import u8aConcat from '@polkadot/util/u8a/concat'; import createType from './codec/createType'; @@ -11,6 +12,13 @@ import Base from './codec/Base'; import MethodIndex from './MethodIndex'; import { FunctionMetadata, FunctionArgumentMetadata } from './Metadata'; +const FN_UNKNOWN = { + method: 'unknown', + section: 'unknown' +} as ExtrinsicFunction; + +const extrinsicFns: { [index: string]: ExtrinsicFunction } = {}; + /** * Extrinsic function descriptor, as defined in * {@link https://github.com/paritytech/wiki/blob/master/Extrinsic.md#the-extrinsic-format-for-node}. @@ -20,15 +28,15 @@ export default class Method extends MethodIndex { protected _data: Uint8Array; protected _meta: FunctionMetadata; - constructor (index: Method | AnyU8a, meta: FunctionMetadata, args: Array) { + constructor (index: Method | AnyU8a, meta?: FunctionMetadata, args?: Array) { super(index); if (index instanceof Method) { this._args = args || index.args; this._meta = meta || index.meta; } else { - this._args = args; - this._meta = meta; + this._args = args || []; + this._meta = meta || Method.findFunction(this.callIndex).meta; } this._data = Method.encode(this._meta, this._args); @@ -64,6 +72,27 @@ export default class Method extends MethodIndex { : []; } + // We could only inject the meta (see injectExtrinsics below) and then do a + // meta-only lookup via + // + // metadata.modules[callIndex[0]].module.call.functions[callIndex[1]] + // + // As a convenience helper though, we return the full constructor function, + // which includes the meta, name, section & actual interface for calling + static findFunction (callIndex: Uint8Array): ExtrinsicFunction { + return extrinsicFns[callIndex.toString()] || FN_UNKNOWN; + } + + // This is called/injected by the API on init, allowing a snapshot of + // the available system extrinsics to be used in lookups + static injectExtrinsics (extrinsics: Extrinsics): void { + Object.values(extrinsics).forEach((methods) => + Object.values(methods).forEach((method) => + extrinsicFns[method.callIndex.toString()] = method + ) + ); + } + byteLength (): number { return super.byteLength() + this.data.length; } @@ -76,10 +105,6 @@ export default class Method extends MethodIndex { return this._data; } - get index (): Uint8Array { - return this.raw; - } - get meta (): FunctionMetadata { return this._meta; } @@ -87,7 +112,14 @@ export default class Method extends MethodIndex { fromU8a (input: Uint8Array): Method { super.fromU8a(input); - this._data = input.subarray(super.byteLength()); + const startData = super.byteLength(); + + this._meta = Method.findFunction(this.callIndex).meta; + this._args = Method.decode(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; } diff --git a/packages/types/src/codec/Struct.ts b/packages/types/src/codec/Struct.ts index d2d2a76dbb..a8663808a5 100644 --- a/packages/types/src/codec/Struct.ts +++ b/packages/types/src/codec/Struct.ts @@ -27,9 +27,9 @@ export default class Struct < protected _jsonMap: Map; protected _Types: E; - constructor (Types: S, value: V | Array = {} as V, jsonMap: Map = new Map(), isTuple: boolean = false) { + constructor (Types: S, value: V | Array = {} as V, jsonMap: Map = new Map()) { super( - Struct.decode(Types, value, isTuple) + Struct.decode(Types, value) ); this._jsonMap = jsonMap; @@ -43,22 +43,22 @@ export default class Struct < }, {} as E); } - static decode (Types: S, value: V | Array, isTuple: boolean): T { + static decode (Types: S, value: V | Array): T { // l.debug(() => ['Struct.decode', { Types, value }]); return Object .keys(Types) .reduce((raw: T, key, index) => { - // @ts-ignore FIXME Ok, something weird is going on here or I just don't get it... + // 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 // the [key in keyof T] was added, the idea is to provide better checks, which // does backfire here, but works externally.) - raw[key] = new Types[key]( - isTuple && Array.isArray(value) - ? value[index] - // @ts-ignore as above - : value[key] - ); + // @ts-ignore + raw[key] = value[key] instanceof Types[key] + // @ts-ignore + ? value[key] + // @ts-ignore + : new Types[key](value[key]); return raw; }, {} as T); @@ -89,6 +89,11 @@ export default class Struct < return this.fromU8a(u8aToU8a(input)); } + // null & undefined yields empty + if (!input) { + input = {}; + } + Object.keys(this.raw).forEach((key) => { const jsonKey = this._jsonMap.get(key as any) || key; diff --git a/packages/types/src/codec/Tuple.spec.js b/packages/types/src/codec/Tuple.spec.js index d8ffc76242..395d0d7405 100644 --- a/packages/types/src/codec/Tuple.spec.js +++ b/packages/types/src/codec/Tuple.spec.js @@ -2,14 +2,22 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import extrinsics from '@polkadot/extrinsics/static'; + import Text from '../Text'; import U32 from '../U32'; import Tuple from './Tuple'; +import BlockNumber from '../BlockNumber'; +import Method from '../Method'; +import Proposal from '../Proposal'; +import VoteThreshold from '../VoteThreshold'; describe('Tuple', () => { let tuple; beforeEach(() => { + Method.injectExtrinsics(extrinsics); + tuple = new Tuple({ foo: Text, bar: U32 @@ -42,4 +50,16 @@ describe('Tuple', () => { '' ]); }); + + it('creates properly via actual hex string', () => { + const test = new (Tuple.with({ + blockNumber: BlockNumber, + proposal: Proposal, + threshold: VoteThreshold + }))('0x62190000000000000003507b0a092230783432223a202230783433220a7d0a01'); + + expect(test.get(0).toNumber()).toEqual(6498); + expect(test.get(1).callIndex).toEqual(new Uint8Array([0, 3])); + expect(test.get(2).toNumber()).toEqual(1); + }); }); diff --git a/packages/types/src/codec/Tuple.ts b/packages/types/src/codec/Tuple.ts index 9556646c8d..8a35a2e91b 100644 --- a/packages/types/src/codec/Tuple.ts +++ b/packages/types/src/codec/Tuple.ts @@ -2,8 +2,13 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +import { AnyU8a } from '../types'; + import hexToU8a from '@polkadot/util/hex/toU8a'; import isHex from '@polkadot/util/is/hex'; +import isString from '@polkadot/util/is/string'; +import isU8a from '@polkadot/util/is/u8a'; +import toU8a from '@polkadot/util/u8a/toU8a'; import Base from './Base'; import Struct from './Struct'; @@ -17,8 +22,29 @@ export default class Tuple < T = { [K in keyof S]: Base }, V = { [K in keyof S]: any } > extends Struct { - constructor (Types: S, value?: V | Array, jsonMap?: Map) { - super(Types, value, jsonMap, true); + constructor (Types: S, value?: V | AnyU8a, jsonMap?: Map) { + super(Types, Tuple.decodeU8a(Types, value), jsonMap); + } + + static decodeU8a (Types: S, _value: V | AnyU8a): V { + if (!isU8a(_value) && !isString(_value) && !Array.isArray(_value)) { + return _value as V; + } + + const value = toU8a(_value); + let offset = 0; + + return Object + .keys(Types) + .reduce((result: V, key) => { + // @ts-ignore + result[key] = new Types[key]().fromU8a(value.subarray(offset)); + + // @ts-ignore + offset += result[key].byteLength(); + + return result; + }, {} as V); } static with <