Contracts attachment (#818)

* WIP... just getting ti to work

* Export ContractAbi from types

* e2e testing

* Add selector encoding (calls)

* Linting

* Exapnd e2e tests

* TODO comments

* Add ABI types & isConstant flag

* Updated with actual steps (progress)

* Linting

* Cleanup event code

* Bump deps

* Bump deps (keyring mnemonic fix)
This commit is contained in:
Jaco Greeff
2019-04-02 21:21:00 +02:00
committed by GitHub
parent b9227c084f
commit 8e6c5f693d
19 changed files with 415 additions and 53 deletions
+1
View File
@@ -1,5 +1,6 @@
# 0.76.1
- Experimental contract API
- Update @polkadot/keyring to enable Alice's stash account on dev chains
- Update @polkadot/util-crypto with smaller footprint
+1 -1
View File
@@ -36,6 +36,6 @@
"@polkadot/rpc-rx": "^0.76.0-beta.2",
"@polkadot/storage": "^0.76.0-beta.2",
"@polkadot/types": "^0.76.0-beta.2",
"@polkadot/util-crypto": "^0.76.0-beta.4"
"@polkadot/util-crypto": "^0.76.0-beta.6"
}
}
+4 -5
View File
@@ -9,8 +9,7 @@ import { RxResult } from './rx/types';
import {
ApiBaseInterface, ApiInterface$Rx, ApiInterface$Events, ApiOptions, ApiType,
DecoratedRpc, DecoratedRpc$Method, DecoratedRpc$Section,
Derive, DeriveSection,
HashResult, U64Result,
Derive, DeriveSection, HashResult, U64Result,
OnCallDefinition, OnCallFunction,
QueryableModuleStorage, QueryableStorage, QueryableStorageFunction,
SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics, Signer
@@ -31,7 +30,7 @@ import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { assert, compactStripLength, isFunction, isObject, isUndefined, logger, u8aToHex } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { createSubmittableExtrinsic, SubmittableExtrinsic } from './SubmittableExtrinsic';
import createSubmittable, { SubmittableExtrinsic } from './SubmittableExtrinsic';
type MetaDecoration = {
callIndex?: Uint8Array,
@@ -68,8 +67,8 @@ function rxOnCall (
}
export default abstract class ApiBase<CodecResult, SubscriptionResult> implements ApiBaseInterface<CodecResult, SubscriptionResult> {
private _eventemitter: EventEmitter;
private _derive?: Derive<CodecResult, SubscriptionResult>;
private _eventemitter: EventEmitter;
private _extrinsics?: SubmittableExtrinsics<CodecResult, SubscriptionResult>;
private _genesisHash?: Hash;
private _isReady: boolean = false;
@@ -474,7 +473,7 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
private decorateExtrinsicEntry<C, S> (method: MethodFunction, onCall: OnCallDefinition<C, S>): SubmittableExtrinsicFunction<C, S> {
const decorated: any = (...params: Array<CodecArg>): SubmittableExtrinsic<C, S> =>
createSubmittableExtrinsic(this.type, this._rx as ApiInterface$Rx, onCall, method(...params));
createSubmittable(this.type, this._rx as ApiInterface$Rx, onCall, method(...params));
return this.decorateFunctionMeta(method, decorated) as SubmittableExtrinsicFunction<C, S>;
}
+24 -13
View File
@@ -46,6 +46,15 @@ export class SubmittableResult extends Struct {
get status (): ExtrinsicStatus {
return this.get('status') as ExtrinsicStatus;
}
/**
* @description Finds an EventRecord for the specified method & section
*/
findRecord (section: string, method: string): EventRecord | undefined {
return this.events.find(({ event }) =>
event.section === section && event.method === method
);
}
}
export interface SubmittableExtrinsic<CodecResult, SubscriptionResult> extends IExtrinsic {
@@ -60,7 +69,7 @@ export interface SubmittableExtrinsic<CodecResult, SubscriptionResult> extends I
signAndSend (account: KeyringPair | string | AccountId | Address, statusCb: StatusCb): SumbitableResultSubscription<CodecResult, SubscriptionResult>;
}
export function createSubmittableExtrinsic<CodecResult, SubscriptionResult> (type: ApiType, api: ApiInterface$Rx, onCall: OnCallDefinition<CodecResult, SubscriptionResult>, extrinsic: Method): SubmittableExtrinsic<CodecResult, SubscriptionResult> {
export default function createSubmittableExtrinsic<CodecResult, SubscriptionResult> (type: ApiType, api: ApiInterface$Rx, onCall: OnCallDefinition<CodecResult, SubscriptionResult>, extrinsic: Method, trackingCb?: (result: SubmittableResult) => any): SubmittableExtrinsic<CodecResult, SubscriptionResult> {
const _extrinsic = new (getTypeRegistry().getOrThrow('Extrinsic'))(extrinsic) as SubmittableExtrinsic<CodecResult, SubscriptionResult>;
const _noStatusCb = type === 'rxjs';
@@ -72,12 +81,11 @@ export function createSubmittableExtrinsic<CodecResult, SubscriptionResult> (typ
function statusObservable (status: ExtrinsicStatus): Observable<SubmittableResult> {
if (!status.isFinalized) {
return of(
new SubmittableResult({
status,
type: status.type
})
);
const result = new SubmittableResult({ status });
trackingCb && trackingCb(result);
return of(result);
}
const blockHash = status.asFinalized;
@@ -86,13 +94,16 @@ export function createSubmittableExtrinsic<CodecResult, SubscriptionResult> (typ
api.rpc.chain.getBlock(blockHash) as Observable<SignedBlock>,
api.query.system.events.at(blockHash) as Observable<Vector<EventRecord>>
).pipe(
map(([signedBlock, allEvents]) =>
new SubmittableResult({
map(([signedBlock, allEvents]) => {
const result = new SubmittableResult({
events: filterEvents(_extrinsic.hash, signedBlock, allEvents),
status,
type: status.type
})
)
status
});
trackingCb && trackingCb(result);
return result;
})
);
}
+1 -7
View File
@@ -7,13 +7,7 @@ import { DeriveCustom } from '@polkadot/api-derive';
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { RpcRxInterface$Events } from '@polkadot/rpc-rx/types';
import { Hash, Metadata, RuntimeVersion, u64 as U64 } from '@polkadot/types';
import {
CodecArg,
CodecCallback,
IExtrinsic,
RegistryTypes,
SignatureOptions
} from '@polkadot/types/types';
import { CodecArg, CodecCallback, IExtrinsic, RegistryTypes, SignatureOptions } from '@polkadot/types/types';
import { MethodFunction } from '@polkadot/types/primitive/Method';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
+1 -1
View File
@@ -22,6 +22,6 @@ export default function filterEvents (extHash: U8a, { block: { extrinsics, heade
return allEvents.filter(({ phase }) =>
// only ApplyExtrinsic has the extrinsic index
phase.type === 'ApplyExtrinsic' && phase.asApplyExtrinsic.eqn(index)
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eqn(index)
);
}
+100
View File
@@ -0,0 +1,100 @@
{
"name": "Erc20",
"deploy": {
"args": [
{
"name": "init_value",
"type": "Balance"
}
]
},
"messages": [
{
"name": "total_supply",
"selector": 949181842,
"mutates": false,
"args": [],
"return_type": "Balance"
},
{
"name": "balance_of",
"selector": 3827153702,
"mutates": false,
"args": [
{
"name": "owner",
"type": "Address"
}
],
"return_type": "Balance"
},
{
"name": "allowance",
"selector": 3057219184,
"mutates": false,
"args": [
{
"name": "owner",
"type": "Address"
},
{
"name": "spender",
"type": "Address"
}
],
"return_type": "Balance"
},
{
"name": "transfer",
"selector": 3374842663,
"mutates": true,
"args": [
{
"name": "to",
"type": "Address"
},
{
"name": "value",
"type": "Balance"
}
],
"return_type": "bool"
},
{
"name": "approve",
"selector": 431186122,
"mutates": true,
"args": [
{
"name": "spender",
"type": "Address"
},
{
"name": "value",
"type": "Balance"
}
],
"return_type": "bool"
},
{
"name": "transfer_from",
"selector": 197482595,
"mutates": true,
"args": [
{
"name": "from",
"type": "Address"
},
{
"name": "to",
"type": "Address"
},
{
"name": "value",
"type": "Balance"
}
],
"return_type": "bool"
}
]
}
Binary file not shown.
@@ -0,0 +1,92 @@
// Copyright 2017-2019 @polkadot/api 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 fs from 'fs';
import path from 'path';
import { ContractAbi } from '@polkadot/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import json from '../data/erc20.json';
import Api from '../../src/promise';
describe.skip('e2e contracts', () => {
let address;
let codeHash;
let keyring;
let abi;
let api;
beforeEach(async (done) => {
if (!api) {
api = await Api.create();
abi = new ContractAbi(json);
keyring = testingPairs({ type: 'sr25519' });
}
jest.setTimeout(10000);
done();
});
it('has the attached methods', () => {
expect(Object.keys(abi.messages)).toEqual(
['totalSupply', 'balanceOf', 'allowance', 'transfer', 'approve', 'transferFrom']
);
});
it('allows putCode', (done) => {
const code = fs.readFileSync(path.join(__dirname, '../data/erc20.wasm')).toString('hex');
api.tx.contract
.putCode(200000, `0x${code}`)
.signAndSend(keyring.eve, (result) => {
console.error('putCode', JSON.stringify(result));
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
codeHash = record.event.data[0];
done();
}
}
});
});
it('allows contract create', (done) => {
expect(codeHash).toBeDefined();
api.tx.contract
.create(1234, 12345, codeHash, abi.deploy(12345))
.signAndSend(keyring.bob, (result) => {
console.error('create', JSON.stringify(result));
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'Instantiated');
if (record) {
address = record.event.data[1];
done();
}
}
});
});
it('allows contract call', (done) => {
expect(address).toBeDefined();
api.tx.contract
.call(address, 123, 12345, abi.messages.balanceOf(keyring.alice.address()))
.signAndSend(keyring.bob, (result) => {
console.error('call', JSON.stringify(result));
if (result.status.isFinalized && result.findRecord('system', 'ExtrinsicSuccess')) {
done();
}
});
});
});
+1 -1
View File
@@ -33,6 +33,6 @@
"@polkadot/jsonrpc": "^0.76.0-beta.2",
"@polkadot/rpc-provider": "^0.76.0-beta.2",
"@polkadot/types": "^0.76.0-beta.2",
"@polkadot/util": "^0.76.0-beta.4"
"@polkadot/util": "^0.76.0-beta.6"
}
}
+3 -3
View File
@@ -30,10 +30,10 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": {
"@babel/runtime": "^7.4.2",
"@polkadot/keyring": "^0.76.0-beta.4",
"@polkadot/keyring": "^0.76.0-beta.6",
"@polkadot/storage": "^0.76.0-beta.2",
"@polkadot/util": "^0.76.0-beta.4",
"@polkadot/util-crypto": "^0.76.0-beta.4",
"@polkadot/util": "^0.76.0-beta.6",
"@polkadot/util-crypto": "^0.76.0-beta.6",
"@types/nock": "^9.3.1",
"eventemitter3": "^3.1.0",
"isomorphic-fetch": "^2.2.1",
+1 -1
View File
@@ -12,6 +12,6 @@
"dependencies": {
"@babel/runtime": "^7.4.2",
"@polkadot/types": "^0.76.0-beta.2",
"@polkadot/util": "^0.76.0-beta.4"
"@polkadot/util": "^0.76.0-beta.6"
}
}
+3 -3
View File
@@ -30,9 +30,9 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-storage#readme",
"dependencies": {
"@babel/runtime": "^7.4.2",
"@polkadot/keyring": "^0.76.0-beta.4",
"@polkadot/keyring": "^0.76.0-beta.6",
"@polkadot/types": "^0.76.0-beta.2",
"@polkadot/util": "^0.76.0-beta.4",
"@polkadot/util-crypto": "^0.76.0-beta.4"
"@polkadot/util": "^0.76.0-beta.6",
"@polkadot/util-crypto": "^0.76.0-beta.6"
}
}
+2 -2
View File
@@ -30,7 +30,7 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.4.2",
"@polkadot/keyring": "^0.76.0-beta.4",
"@polkadot/util": "^0.76.0-beta.4"
"@polkadot/keyring": "^0.76.0-beta.6",
"@polkadot/util": "^0.76.0-beta.6"
}
}
+148
View File
@@ -0,0 +1,148 @@
// 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 { CodecArg, Constructor } from './types';
import { assert, isNumber, isNull, isString, isUndefined, stringCamelCase } from '@polkadot/util';
import Compact from './codec/Compact';
import { createClass } from './codec/createType';
export type ContractABIArgs = Array<{
name: string,
type: string
}>;
export type ContractABIMethodBase = {
args: ContractABIArgs
};
export type ContractABIMethod = ContractABIMethodBase & {
mutates?: boolean,
name: string,
selector: number,
return_type: string | null
};
export type ContractABI = {
deploy: ContractABIMethodBase,
messages: Array<ContractABIMethod>,
name: string
};
export interface ContractABIFn {
(...args: Array<CodecArg>): Uint8Array;
args: ContractABIArgs;
isConstant: boolean;
type: string | null;
}
export interface Contract {
abi: ContractABI;
deploy: ContractABIFn;
messages: {
[index: string]: ContractABIFn
};
}
export function validateArgs (name: string, args: ContractABIArgs): 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`);
});
}
export function validateDeploy ({ deploy }: ContractABI): void {
const unknownKeys = Object.keys(deploy).filter((key) => !['args'].includes(key));
assert(unknownKeys.length === 0, `Unknown keys ${unknownKeys.join(', ')} found in ABI deploy`);
validateArgs('deploy', deploy.args);
}
export function validateMethods ({ messages }: ContractABI): void {
messages.forEach((method) => {
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.${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}`);
validateArgs(`messages.${method.name}`, method.args);
});
}
export function validateAbi (abi: ContractABI): void {
const unknownKeys = Object.keys(abi).filter((key) => !['deploy', 'messages', 'name'].includes(key));
assert(unknownKeys.length === 0, `Unknown fields ${unknownKeys.join(', ')} found in ABI`);
assert(abi.deploy && abi.messages && isString(abi.name), 'ABI should have deploy, messages & name sections');
validateDeploy(abi);
validateMethods(abi);
}
export default class ContractAbi implements Contract {
abi: ContractABI;
deploy: ContractABIFn;
messages: { [index: string]: ContractABIFn } = {};
constructor (abi: ContractABI) {
validateAbi(abi);
this.abi = abi;
this.deploy = this._createEncoded('deploy', abi.deploy);
abi.messages.forEach((method) => {
const name = stringCamelCase(method.name);
this.messages[name] = this._createEncoded(`messages.${name}`, method);
});
}
private _createClazz (args: ContractABIArgs, isDeploy: boolean): Constructor {
return createClass(
JSON.stringify(
args.reduce((base: { [index: string]: string }, { name, type }) => {
base[name] = type;
return base;
}, isDeploy ? {} : { __selector: 'u32' })
)
);
}
private _createEncoded (name: string, method: Partial<ContractABIMethod> & ContractABIMethodBase): ContractABIFn {
const args = method.args.map(({ name, type }) => ({
name: stringCamelCase(name),
type
}));
const Clazz = this._createClazz(args, isUndefined(method.selector));
const base: { [index: string]: any } = { __selector: method.selector };
const encoder = (...params: Array<CodecArg>): Uint8Array => {
assert(params.length === args.length, `Expected ${args.length} arguments to contract ${name}, found ${params.length}`);
return Compact.addLengthPrefix(
new Clazz(
args.reduce((mapped, { name }, index) => {
mapped[name] = params[index];
return mapped;
}, { ...base })
).toU8a()
);
};
const fn = (encoder as ContractABIFn);
fn.args = args;
fn.isConstant = !(method.mutates || false);
fn.type = method.return_type || null;
return fn;
}
}
+3 -1
View File
@@ -143,9 +143,11 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
// Returns the type Class for construction
export function getTypeClass (value: TypeDef): Constructor {
const Type = getRegistry().get(value.type);
if (Type) {
return Type;
}
switch (value.info) {
case TypeDefInfo.Compact:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Compact');
@@ -201,7 +203,7 @@ export function getTypeClass (value: TypeDef): Constructor {
throw new Error(`Unable to determine type from '${value.type}'`);
}
export function createClass (type: Text | string, value?: any): Constructor {
export function createClass (type: Text | string): Constructor {
return getTypeClass(
getTypeDef(type)
);
+1
View File
@@ -9,5 +9,6 @@ import { assertSingletonPackage } from '@polkadot/util';
assertSingletonPackage('@polkadot/types');
export { default as ContractAbi } from './ContractAbi';
export * from './codec';
export * from './index.types';
+14
View File
@@ -50,6 +50,20 @@ export class Phase extends EnumType<ApplyExtrinsic | Finalization> {
get asFinalization (): Finalization {
return this.value as Finalization;
}
/**
* @description true when this is a ApplyExtrinsic
*/
get isApplyExtrinsic (): boolean {
return this.type === 'ApplyExtrinsic';
}
/**
* @description true when this is a ApplyExtrinsic
*/
get isFinalization (): boolean {
return this.type === 'Finalization';
}
}
/**
+15 -15
View File
@@ -1630,14 +1630,14 @@
typescript "^3.4.1"
vuepress "^1.0.0-alpha.44"
"@polkadot/keyring@^0.76.0-beta.4":
version "0.76.0-beta.4"
resolved "https://registry.yarnpkg.com/@polkadot/keyring/-/keyring-0.76.0-beta.4.tgz#9942c60a9a5e9795b40280b6b0a08d5f463c33dd"
integrity sha512-VeunqSVe/JPKC7/WQGOTdLfOV0Fv3B+IinBE7zdxqaEOP74VJ4+uXAynjcF1FPiUoJwzlvj+Wu20eRX8fozapg==
"@polkadot/keyring@^0.76.0-beta.6":
version "0.76.0-beta.6"
resolved "https://registry.yarnpkg.com/@polkadot/keyring/-/keyring-0.76.0-beta.6.tgz#55cff504896340dcdfce9758dedd78275b08e402"
integrity sha512-v+TqsxlxfwWdbDjkyWpl3l3z9khJtfH0G0e4NFOmRL+Ym4FHqWmp/e9aRYFEztPe2WlP1htO6+f7teUQlroBKA==
dependencies:
"@babel/runtime" "^7.4.2"
"@polkadot/util" "^0.76.0-beta.4"
"@polkadot/util-crypto" "^0.76.0-beta.4"
"@polkadot/util" "^0.76.0-beta.6"
"@polkadot/util-crypto" "^0.76.0-beta.6"
"@types/bs58" "^4.0.0"
bs58 "^4.0.1"
@@ -1646,13 +1646,13 @@
resolved "https://registry.yarnpkg.com/@polkadot/ts/-/ts-0.1.56.tgz#ffd6e9c95704a7fb90b918193b9dc5c440114b27"
integrity sha512-wnt4zXxZXyz6WaubTO/I+nUElwV2DogFzdl6CrKfVn2PTWp8uHN06W9s40FH57ORtmQfDr9rLRP8Nq+oIyElbg==
"@polkadot/util-crypto@^0.76.0-beta.4":
version "0.76.0-beta.4"
resolved "https://registry.yarnpkg.com/@polkadot/util-crypto/-/util-crypto-0.76.0-beta.4.tgz#dc96bd4d76ddbe4edf2ddad9b4e330ba45b29831"
integrity sha512-pPjrSoT1HZm7LYLCgYP0rfGoZU13DfohyQVztMl1dWZG7c8KEXkE6hkIslt279sv2rnros4TAISHnOOMVBp2Vg==
"@polkadot/util-crypto@^0.76.0-beta.6":
version "0.76.0-beta.6"
resolved "https://registry.yarnpkg.com/@polkadot/util-crypto/-/util-crypto-0.76.0-beta.6.tgz#b7d72b1b9e895c7e81287daf3a149aba1d9ef68f"
integrity sha512-GLY+GL8U/9AhFk2wCUhMynDVH2U1ozVcS9hgzWyw/OWM/5O6Lr1f+zFFhF+GYEyj1Xy2iqBQ8qJAdSHaLJJS3A==
dependencies:
"@babel/runtime" "^7.4.2"
"@polkadot/util" "^0.76.0-beta.4"
"@polkadot/util" "^0.76.0-beta.6"
"@polkadot/wasm-crypto" "^0.8.1"
"@types/bip39" "^2.4.2"
"@types/pbkdf2" "^3.0.0"
@@ -1666,10 +1666,10 @@
tweetnacl "^1.0.1"
xxhashjs "^0.2.2"
"@polkadot/util@^0.76.0-beta.4":
version "0.76.0-beta.4"
resolved "https://registry.yarnpkg.com/@polkadot/util/-/util-0.76.0-beta.4.tgz#7186f63206ece1c8b5b4e4d87666cf92be04ae60"
integrity sha512-azVxRClnSXEqwqLL+VnddAq5LhZa4lU1mKVxLVrg0OhLiT5HzodG6e64m5/y0T+BRrLC0lNVkH+Y8CMCaw5XmQ==
"@polkadot/util@^0.76.0-beta.6":
version "0.76.0-beta.6"
resolved "https://registry.yarnpkg.com/@polkadot/util/-/util-0.76.0-beta.6.tgz#bcb83810dc9c0f9b6316844b888e1c115a3e7541"
integrity sha512-kTPsF3QGFkgtxF1X/LjXQ04gRGMgaYLYopdy80C7Bcm/eSUkidgxw928FC6v319ZGaFYGiwwxHsKTlmFDWKBJQ==
dependencies:
"@babel/runtime" "^7.4.2"
"@types/bn.js" "^4.11.4"