From 5ca32863d0f71a771c01a6b3f81a2d7d89f508f3 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Thu, 13 Jun 2019 15:46:47 +0200 Subject: [PATCH] Allow for contract Vec, Option and Tuple arg/return (#997) * Allow for contract Vec & Option arg/return * Support nesting, fixed vecs and tuples * Support Result * Update CHANGELOG * Add additional types added to CHANGELOG (& re-order) * Add metadata entry (ready to go) --- CHANGELOG.md | 8 +- packages/api/test/data/flipper.json | 23 +++- packages/types/src/ContractAbi.spec.ts | 82 ++++++++++++++ packages/types/src/ContractAbi.ts | 73 ++++++++++--- packages/types/test/abi/types.json | 142 +++++++++++++++++++++++++ 5 files changed, 311 insertions(+), 17 deletions(-) create mode 100644 packages/types/src/ContractAbi.spec.ts create mode 100644 packages/types/test/abi/types.json diff --git a/CHANGELOG.md b/CHANGELOG.md index eb35f1fcae..9f6454d5fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,16 @@ # 0.82.1 +- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it - Update `HeaderExtended` to retrieve author information from substrate 2.x (new `PreRuntime` digests) - `createType` allows for the creation of `[u8; ]` types (opening the door for contract support) - `api.derive.staking.info` now returns the `rewardDestination` - Fix for disconnection when default providers (non-specified) are used -- Update `ContractInfo` to match substrate master -- Additional examples for subscriptions using multi - Don't console.log type decoding errors and then throw, only re-throw with additional info +- Support latest substrate 2.x v5 metadata +- Add `ApprovalFlag`, `SetIndex`, `VoterInfo` types for council as per substrate +- Update `ContractInfo` to match substrate master +- Cater for `Vec`, `Option`, `Result`, tuples and fixed vectors for contracts ABIs +- Additional examples for subscriptions using multi # 0.81.1 diff --git a/packages/api/test/data/flipper.json b/packages/api/test/data/flipper.json index 6019350ee5..d425563a0c 100644 --- a/packages/api/test/data/flipper.json +++ b/packages/api/test/data/flipper.json @@ -1 +1,22 @@ -{"name":"Flipper","deploy":{"args":[]},"messages":[{"name":"flip","selector":970692492,"mutates":true,"args":[],"return_type":null},{"name":"get","selector":4266279973,"mutates":false,"args":[],"return_type":"bool"}]} \ No newline at end of file +{ + "name": "Flipper", + "deploy": { + "args": [] + }, + "messages": [ + { + "name": "flip", + "selector": 970692492, + "mutates": true, + "args": [], + "return_type": null + }, + { + "name": "get", + "selector": 4266279973, + "mutates": false, + "args": [], + "return_type": "bool" + } + ] +} diff --git a/packages/types/src/ContractAbi.spec.ts b/packages/types/src/ContractAbi.spec.ts new file mode 100644 index 0000000000..348c3945aa --- /dev/null +++ b/packages/types/src/ContractAbi.spec.ts @@ -0,0 +1,82 @@ +// Copyright 2017-2019 @polkadot/types authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +import TypesAbi from '../test/abi/types.json'; + +import ContractAbi, { ContractABIFn$Arg } from './ContractAbi'; + +describe('ContractAbi', () => { + let abi: ContractAbi; + + beforeAll(() => { + abi = new ContractAbi(TypesAbi); + }); + + function check (method: string, args: Array, type: string | null): void { + const fn = abi.messages[method]; + + expect(fn.args).toEqual(args); + expect(fn.type).toEqual(type); + } + + it('has the primitive method with args & return', () => { + check( + 'primitive', + [ + { name: 'bool', type: 'bool' }, + { name: 'u32', type: 'u32' } + ], + 'bool' + ); + }); + + it('has the vector method with args & return', () => { + check( + 'vector', + [ + { name: 'vecU8', type: 'Vec' }, + { name: 'vecU32', type: 'Vec' } + ], + 'Vec' + ); + }); + + it('has the vector_fixed method with args & return', () => { + check( + 'vectorFixed', + [ + { name: 'vecU8Length32', type: '[u8;32]' } + ], + '[u32;8]' + ); + }); + + it('has the option method with args & return', () => { + check( + 'option', + [ + { name: 'optionU32', type: 'Option' } + ], + 'Option' + ); + }); + + it('has the result method with return (empty)', () => { + check( + 'result', + [], + '()' + ); + }); + + it('allows for nested args', () => { + check( + 'nested', + [ + { name: 'optionVec', type: 'Option>' } + ], + 'Vec<(u32,u64)>' + ); + }); +}); diff --git a/packages/types/src/ContractAbi.ts b/packages/types/src/ContractAbi.ts index 884db0c440..2aff586092 100644 --- a/packages/types/src/ContractAbi.ts +++ b/packages/types/src/ContractAbi.ts @@ -4,25 +4,44 @@ import { CodecArg, Constructor } from './types'; -import { assert, isNumber, isNull, isString, isUndefined, stringCamelCase } from '@polkadot/util'; +import { assert, isNumber, isNull, isString, isUndefined, stringCamelCase, isObject } from '@polkadot/util'; import Compact from './codec/Compact'; import { createClass } from './codec/createType'; -export type ContractABIArgs = Array<{ +export type ContractABITypes$Struct = { + 'Option'?: { + T: ContractABITypes + }, + 'Result'?: { + T: ContractABITypes, + E: ContractABITypes + }, + 'Vec'?: { + T: ContractABITypes + }, + '[T;n]'?: { + T: ContractABITypes, + n: number + } +}; + +export type ContractABITypes = string | ContractABITypes$Struct | Array; + +export type ContractABIArg = { name: string, - type: string -}>; + type: ContractABITypes +}; export type ContractABIMethodBase = { - args: ContractABIArgs + args: Array }; export type ContractABIMethod = ContractABIMethodBase & { mutates?: boolean, name: string, selector: number, - return_type: string | null + return_type: ContractABITypes | null }; export type ContractABI = { @@ -31,9 +50,14 @@ export type ContractABI = { name: string }; +export interface ContractABIFn$Arg { + name: string; + type: string; +} + export interface ContractABIFn { (...args: Array): Uint8Array; - args: ContractABIArgs; + args: Array; isConstant: boolean; type: string | null; } @@ -46,14 +70,15 @@ export interface Contract { }; } -export function validateArgs (name: string, args: ContractABIArgs): void { +export function validateArgs (name: string, args: Array): void { assert(Array.isArray(args), `Expected 'args' to exist on ${name}`); args.forEach((arg) => { const unknownKeys = Object.keys(arg).filter((key) => !['name', 'type'].includes(key)); assert(unknownKeys.length === 0, `Unknown keys ${unknownKeys.join(', ')} found in ABI args for ${name}`); - assert(isString(arg.name) && isString(arg.type), `${name} args should have valid name & type values`); + assert(isString(arg.name), `${name} args should have valid name `); + assert(isString(arg.type) || isObject(arg.type), `${name} args should have valid type`); }); } @@ -70,7 +95,9 @@ export function validateMethods ({ messages }: ContractABI): void { const unknownKeys = Object.keys(method).filter((key) => !['args', 'mutates', 'name', 'selector', 'return_type'].includes(key)); assert(unknownKeys.length === 0, `Unknown keys ${unknownKeys.join(', ')} found in ABI args for messages.${method.name}`); - assert(isString(method.name) && isNumber(method.selector) && (isNull(method.return_type) || isString(method.return_type)), `Expected name, selector & return_type specified for messages.${method.name}`); + assert(isString(method.name), `Expected name for messages.${method.name}`); + assert(isNumber(method.selector), `Expected selector for messages.${method.name}`); + assert(isNull(method.return_type) || isString(method.return_type) || isObject(method.return_type), `Expected return_type for messages.${method.name}`); validateArgs(`messages.${method.name}`, method.args); }); @@ -104,7 +131,25 @@ export default class ContractAbi implements Contract { }); } - private _createClazz (args: ContractABIArgs, baseDef: { [index: string]: string }): Constructor { + private _convertType (type: ContractABITypes): string { + if (isString(type)) { + return type; + } else if (Array.isArray(type)) { + return `(${type.map((type) => this._convertType(type)).join(',')})`; + } else if (type['Option']) { + return `Option<${this._convertType(type['Option'].T)}>`; + } else if (type['Result']) { + return `()`; // Result is not supported, but only applicable for returns + } else if (type['Vec']) { + return `Vec<${this._convertType(type['Vec'].T)}>`; + } else if (type['[T;n]']) { + return `[${this._convertType(type['[T;n]'].T)};${type['[T;n]'].n}]`; + } + + throw new Error(`Unknown type specified ${JSON.stringify(type)}`); + } + + private _createClazz (args: Array, baseDef: { [index: string]: string }): Constructor { return createClass( JSON.stringify( args.reduce((base: { [index: string]: string }, { name, type }) => { @@ -117,9 +162,9 @@ export default class ContractAbi implements Contract { } private _createEncoded (name: string, method: Partial & ContractABIMethodBase): ContractABIFn { - const args = method.args.map(({ name, type }) => ({ + const args: Array = method.args.map(({ name, type }) => ({ name: stringCamelCase(name), - type + type: this._convertType(type) })); const Clazz = this._createClazz(args, isUndefined(method.selector) ? {} : { __selector: 'u32' }); const baseStruct: { [index: string]: any } = { __selector: method.selector }; @@ -141,7 +186,7 @@ export default class ContractAbi implements Contract { fn.args = args; fn.isConstant = !(method.mutates || false); - fn.type = method.return_type || null; + fn.type = method.return_type ? this._convertType(method.return_type) : null; return fn; } diff --git a/packages/types/test/abi/types.json b/packages/types/test/abi/types.json new file mode 100644 index 0000000000..f74cb8a6e1 --- /dev/null +++ b/packages/types/test/abi/types.json @@ -0,0 +1,142 @@ +{ + "name": "Types", + "deploy": { + "args": [] + }, + "messages": [ + { + "name": "primitive", + "selector": 1111, + "mutates": true, + "args": [ + { + "name": "bool", + "type": "bool" + }, + { + "name": "u32", + "type": "u32" + } + ], + "return_type": "bool" + }, + { + "name": "vector", + "selector": 2222, + "mutates": false, + "args": [ + { + "name": "Vec_u8", + "type": { + "Vec": { + "T": "u8" + } + } + }, + { + "name": "Vec_u32", + "type": { + "Vec": { + "T": "u32" + } + } + } + ], + "return_type": { + "Vec": { + "T": "bool" + } + } + }, + { + "name": "vector_fixed", + "selector": 3333, + "mutates": false, + "args": [ + { + "name": "vec_u8_length_32", + "type": { + "[T;n]": { + "T": "u8", + "n": 32 + } + } + } + ], + "return_type": { + "[T;n]": { + "T": "u32", + "n": 8 + } + } + }, + { + "name": "option", + "selector": 4444, + "mutates": false, + "args": [ + { + "name": "Option_u32", + "type": { + "Option": { + "T": "u32" + } + } + } + ], + "return_type": { + "Option": { + "T": "bool" + } + } + }, + { + "name": "tuple", + "selector": 5555, + "mutates": false, + "args": [ + { + "name": "Tuple_u32_u64", + "type": ["u32", "u64"] + } + ], + "return_type": ["bool"] + }, + { + "name": "result", + "selector": 666, + "mutates": false, + "args": [], + "return_type": { + "Result": { + "T": "u32", + "E": "u32" + } + } + }, + { + "name": "nested", + "selector": 987654321, + "mutates": false, + "args": [ + { + "name": "option_vec", + "type": { + "Option": { + "T": { + "Vec": { + "T": "u32" + } + } + } + } + } + ], + "return_type": { + "Vec": { + "T": ["u32", "u64"] + } + } + } + ] +}