More ergonomic contracts interfaces (RxJs only initial) (#1015)

* More ergnomic contracts interfaces

* extend SubmittableResult

* Allow creation of contract from blueprint

* "decorate" Contract (just playing with interfaces)

* Make actual messages calls

* Rename to Rx{Blueprint, Cond, Contract}

* Add exports

* Support contract & contracts endpoints

* Remove unneeded ApiType generics (may return)

* Comment 2.x/1.x detection
This commit is contained in:
Jaco Greeff
2019-06-21 16:48:00 +02:00
committed by GitHub
parent 5e5bb9984b
commit f30c516099
10 changed files with 288 additions and 45 deletions
+3 -3
View File
@@ -2,17 +2,17 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ContractABI, ContractABIFn } from './types';
import { ContractABI, ContractABIFn, IAbi, IAbi$Messages } from './types';
import { stringCamelCase } from '@polkadot/util';
import { createMethod } from './method';
import { validateAbi } from './validation';
export default class ContractAbi {
export default class ContractAbi implements IAbi {
readonly abi: ContractABI;
readonly deploy: ContractABIFn;
readonly messages: { [index: string]: ContractABIFn } = {};
readonly messages: IAbi$Messages = {};
constructor (abi: ContractABI) {
validateAbi(abi);
-24
View File
@@ -1,24 +0,0 @@
// Copyright 2017-2019 @polkadot/api-contract 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 { ContractABI } from './types';
import { AccountId } from '@polkadot/types';
import Abi from './Abi';
export default class Contract {
readonly abi: Abi;
readonly address: AccountId;
// TODO This needs to be useful
// - pass API instance
// - expose calls here so we don't need to do the encoding manually
//
// Also, we need the same structure for managing code and deploying
constructor (address: string | AccountId, abi: ContractABI) {
this.abi = new Abi(abi);
this.address = new AccountId(address);
}
}
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2017-2019 @polkadot/api-contract 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 { SubmittableModuleExtrinsics } from '@polkadot/api/types';
import { ApiObject, ContractABI, IContractBase } from './types';
import { assert } from '@polkadot/util';
import Abi from './Abi';
// NOTE Experimental, POC, bound to change
export default abstract class RxBase implements IContractBase<'rxjs'> {
readonly abi: Abi;
readonly api: ApiObject<'rxjs'>;
readonly apiContracts: SubmittableModuleExtrinsics<'rxjs'>;
constructor (api: ApiObject<'rxjs'>, abi: ContractABI | Abi) {
this.abi = abi instanceof Abi
? abi
: new Abi(abi);
this.api = api;
// cater for substrate 2.x & 1.x (in order)
this.apiContracts = api.tx.contracts || api.tx.contract;
assert(this.apiContracts && this.apiContracts.putCode, `You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance`);
}
}
+69
View File
@@ -0,0 +1,69 @@
// Copyright 2017-2019 @polkadot/api-contract 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 { ISubmittableResult, SubmittableResult } from '@polkadot/api/SubmittableExtrinsic';
import { IKeyringPair } from '@polkadot/types/types';
import { ContractABI } from './types';
import BN from 'bn.js';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiRx } from '@polkadot/api';
import { AccountId, Address, Hash } from '@polkadot/types';
import Abi from './Abi';
import RxBase from './RxBase';
import RxContract from './RxContract';
type IBlueprintCreateResultSubscription = Observable<BlueprintCreateResult>;
export interface IBlueprintCreate {
signAndSend (account: IKeyringPair | string | AccountId | Address): IBlueprintCreateResultSubscription;
}
class BlueprintCreateResult extends SubmittableResult {
readonly contract?: RxContract;
constructor (result: ISubmittableResult, contract?: RxContract) {
super(result);
this.contract = contract;
}
}
// NOTE Experimental, POC, bound to change
export default class Blueprint extends RxBase {
readonly codeHash: Hash;
constructor (api: ApiRx, abi: ContractABI | Abi, codeHash: string | Hash) {
super(api, abi);
this.codeHash = new Hash(codeHash);
}
public deployContract (endowment: number | BN, maxGas: number | BN, ...params: Array<any>): IBlueprintCreate {
const signAndSend = (account: IKeyringPair | string | AccountId | Address): IBlueprintCreateResultSubscription => {
return this.apiContracts
.create(endowment, maxGas, this.codeHash, this.abi.deploy(...params))
.signAndSend(account)
.pipe(
map((result: SubmittableResult) => {
let contract: RxContract | undefined;
if (result.isFinalized) {
const record = result.findRecord('contract', 'Instantiated');
if (record) {
contract = new RxContract(this.api, this.abi, record.event.data[1] as Address);
}
}
return new BlueprintCreateResult(result, contract);
})
);
};
return { signAndSend };
}
}
+82
View File
@@ -0,0 +1,82 @@
// Copyright 2017-2019 @polkadot/api-contract 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 { ISubmittableResult, SubmittableResult } from '@polkadot/api/SubmittableExtrinsic';
import { IKeyringPair } from '@polkadot/types/types';
import { ContractABI } from './types';
import BN from 'bn.js';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiRx } from '@polkadot/api';
import { AccountId, Address, Hash } from '@polkadot/types';
import { compactAddLength, u8aToU8a } from '@polkadot/util';
import Abi from './Abi';
import RxBase from './RxBase';
import RxBlueprint from './RxBlueprint';
// Ok, tried, failed, eventually ... well, we are only trying with RxJs as a
// start, so take a big fat shortcut with this version, real intended version
// follows this and is commented out
type ICodePutCodeResultSubscription = Observable<CodePutCodeResult>;
// type ICodePutCodeResultSubscription<ApiType> =
// ApiType extends 'rxjs'
// ? Observable<CodePutCodeResult>
// : Promise<() => void>;
// unlike the ISubmittableExtrinsic, it doesn't extend IExtrinsic and only
// implements one var iant of signAndSend - this is purely done to see what
// is hanging where, with the bare-mainimum from a simplicity perspective
// Very obvious is that it supports only 1 version of signAndSend
// (we need to revisit this, but probably ok for initial?)
export interface ICodePutCode {
signAndSend (account: IKeyringPair | string | AccountId | Address): ICodePutCodeResultSubscription;
}
class CodePutCodeResult extends SubmittableResult {
readonly blueprint?: RxBlueprint;
constructor (result: ISubmittableResult, blueprint?: RxBlueprint) {
super(result);
this.blueprint = blueprint;
}
}
// NOTE Experimental, POC, bound to change
export default class RxCode extends RxBase {
readonly code: Uint8Array;
constructor (api: ApiRx, abi: ContractABI | Abi, wasm: string | Uint8Array) {
super(api, abi);
this.code = u8aToU8a(wasm);
}
public createBlueprint (maxGas: number | BN): ICodePutCode {
const signAndSend = (account: IKeyringPair | string | AccountId | Address): ICodePutCodeResultSubscription => {
return this.apiContracts
.putCode(maxGas, compactAddLength(this.code))
.signAndSend(account)
.pipe(
map((result: ISubmittableResult) => {
let blueprint: RxBlueprint | undefined;
if (result.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
blueprint = new RxBlueprint(this.api, this.abi, record.event.data[0] as Hash);
}
}
return new CodePutCodeResult(result, blueprint);
})
);
};
return { signAndSend };
}
}
+39
View File
@@ -0,0 +1,39 @@
// Copyright 2017-2019 @polkadot/api-contract 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 { ContractABI, ContractABIFn, IContract, IContract$Calls } from './types';
import { IKeyringPair } from '@polkadot/types/types';
import BN from 'bn.js';
import { Observable } from 'rxjs';
import { ApiRx } from '@polkadot/api';
import { SubmittableResult } from '@polkadot/api/SubmittableExtrinsic';
import { AccountId, Address } from '@polkadot/types';
import Abi from './Abi';
import RxBase from './RxBase';
export type IContractCallResultSubscription = Observable<SubmittableResult>;
export interface IContractCall {
signAndSend (account: IKeyringPair | string | AccountId | Address): IContractCallResultSubscription;
}
// NOTE Experimental, POC, bound to change
export default class RxContract extends RxBase implements IContract {
readonly address: Address;
readonly calls: IContract$Calls = {};
constructor (api: ApiRx, abi: ContractABI | Abi, address: string | AccountId | Address) {
super(api, abi);
this.address = new Address(address);
Object.entries(abi.messages).forEach(([name, fn]) => {
this.calls[name] = (fn: ContractABIFn) =>
(value: BN | number, maxGas: BN | number, ...params: Array<any>): IContractCall =>
this.apiContracts.call(this.address, value, maxGas, fn(...params));
});
}
}
+3 -1
View File
@@ -3,4 +3,6 @@
// of the Apache-2.0 license. See the LICENSE file for details.
export { default as Abi } from './Abi';
export { default as Contract } from './Contract';
export { default as RxBlueprint } from './RxBlueprint';
export { default as RxCode } from './RxCode';
export { default as RxContract } from './RxContract';
+38 -2
View File
@@ -2,8 +2,16 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { SubmittableModuleExtrinsics } from '@polkadot/api/types';
import { CodecArg } from '@polkadot/types/types';
import { ApiPromise, ApiRx } from '@polkadot/api';
import { Address } from '@polkadot/types';
export type ApiObject<ApiType> = ApiType extends 'rxjs'
? ApiRx
: ApiPromise;
export type ContractABITypes$Struct = {
'Option<T>'?: {
T: ContractABITypes
@@ -50,9 +58,37 @@ export interface ContractABIFn$Arg {
type: string;
}
export interface ContractABIFn {
(...args: Array<CodecArg>): Uint8Array;
export interface ContractABIFn$Meta {
args: Array<ContractABIFn$Arg>;
isConstant: boolean;
type: string | null;
}
export interface ContractABIFn extends ContractABIFn$Meta {
(...args: Array<CodecArg>): Uint8Array;
}
export interface IAbi$Messages {
[index: string]: ContractABIFn;
}
export interface IAbi {
readonly abi: ContractABI;
readonly deploy: ContractABIFn;
readonly messages: IAbi$Messages;
}
export interface IContractBase<ApiType> {
readonly abi: IAbi;
readonly api: ApiObject<ApiType>;
readonly apiContracts: SubmittableModuleExtrinsics<ApiType>;
}
export interface IContract$Calls {
[index: string]: Function;
}
export interface IContract {
readonly address: Address;
readonly calls: IContract$Calls;
}
+23 -13
View File
@@ -13,14 +13,24 @@ import { assert, isBn, isFunction, isNumber, isUndefined } from '@polkadot/util'
import ApiBase from './Base';
import filterEvents from './util/filterEvents';
type SumbitableResultResult<ApiType> =
export interface ISubmittableResult {
readonly events: Array<EventRecord>;
readonly status: ExtrinsicStatus;
readonly isCompleted: boolean;
readonly isError: boolean;
readonly isFinalized: boolean;
findRecord (section: string, method: string): EventRecord | undefined;
}
export type SumbitableResultResult<ApiType> =
ApiType extends 'rxjs'
? Observable<SubmittableResult>
? Observable<ISubmittableResult>
: Promise<Hash>;
type SumbitableResultSubscription<ApiType> =
export type SumbitableResultSubscription<ApiType> =
ApiType extends 'rxjs'
? Observable<SubmittableResult>
? Observable<ISubmittableResult>
: Promise<() => void>;
type SubmittableResultValue = {
@@ -28,7 +38,7 @@ type SubmittableResultValue = {
status: ExtrinsicStatus;
};
export class SubmittableResult {
export class SubmittableResult implements ISubmittableResult {
readonly events: Array<EventRecord>;
readonly status: ExtrinsicStatus;
@@ -62,13 +72,13 @@ export class SubmittableResult {
export interface SubmittableExtrinsic<ApiType> extends IExtrinsic {
send (): SumbitableResultResult<ApiType>;
send (statusCb: Callback<SubmittableResult>): SumbitableResultSubscription<ApiType>;
send (statusCb: Callback<ISubmittableResult>): SumbitableResultSubscription<ApiType>;
sign (account: IKeyringPair, _options: Partial<SignatureOptions>): this;
signAndSend (account: IKeyringPair | string | AccountId | Address, options?: Partial<Partial<SignatureOptions>>): SumbitableResultResult<ApiType>;
signAndSend (account: IKeyringPair | string | AccountId | Address, statusCb: Callback<SubmittableResult>): SumbitableResultSubscription<ApiType>;
signAndSend (account: IKeyringPair | string | AccountId | Address, statusCb: Callback<ISubmittableResult>): SumbitableResultSubscription<ApiType>;
}
export default function createSubmittableExtrinsic<ApiType> (
@@ -76,18 +86,18 @@ export default function createSubmittableExtrinsic<ApiType> (
api: ApiInterface$Rx,
decorateMethod: ApiBase<ApiType>['decorateMethod'],
extrinsic: Method | Uint8Array | string,
trackingCb?: Callback<SubmittableResult>
trackingCb?: Callback<ISubmittableResult>
): SubmittableExtrinsic<ApiType> {
const _extrinsic = new (getTypeRegistry().getOrThrow('Extrinsic'))(extrinsic) as SubmittableExtrinsic<ApiType>;
const _noStatusCb = type === 'rxjs';
function updateSigner (updateId: number, status: Hash | SubmittableResult): void {
function updateSigner (updateId: number, status: Hash | ISubmittableResult): void {
if ((updateId !== -1) && api.signer && api.signer.update) {
api.signer.update(updateId, status);
}
}
function statusObservable (status: ExtrinsicStatus): Observable<SubmittableResult> {
function statusObservable (status: ExtrinsicStatus): Observable<ISubmittableResult> {
if (!status.isFinalized) {
const result = new SubmittableResult({ status });
@@ -125,7 +135,7 @@ export default function createSubmittableExtrinsic<ApiType> (
);
}
function subscribeObservable (updateId: number = -1): Observable<SubmittableResult> {
function subscribeObservable (updateId: number = -1): Observable<ISubmittableResult> {
return (api.rpc.author
.submitAndWatchExtrinsic(_extrinsic) as Observable<ExtrinsicStatus>)
.pipe(
@@ -151,7 +161,7 @@ export default function createSubmittableExtrinsic<ApiType> (
_extrinsic,
{
send: {
value: function (statusCb?: Callback<SubmittableResult>): SumbitableResultResult<ApiType> | SumbitableResultSubscription<ApiType> {
value: function (statusCb?: Callback<ISubmittableResult>): SumbitableResultResult<ApiType> | SumbitableResultSubscription<ApiType> {
const isSubscription = _noStatusCb || !!statusCb;
return decorateMethod(isSubscription ? subscribeObservable : sendObservable)(statusCb);
@@ -171,7 +181,7 @@ export default function createSubmittableExtrinsic<ApiType> (
}
},
signAndSend: {
value: function (account: IKeyringPair | string | AccountId | Address, _options?: Partial<Partial<SignatureOptions>> | Callback<SubmittableResult>, statusCb?: Callback<SubmittableResult>): SumbitableResultResult<ApiType> | SumbitableResultSubscription<ApiType> {
value: function (account: IKeyringPair | string | AccountId | Address, _options?: Partial<Partial<SignatureOptions>> | Callback<ISubmittableResult>, statusCb?: Callback<ISubmittableResult>): SumbitableResultResult<ApiType> | SumbitableResultSubscription<ApiType> {
let options: Partial<Partial<SignatureOptions>> = {};
if (isFunction(_options)) {
+2 -2
View File
@@ -11,7 +11,7 @@ import { MethodFunction } from '@polkadot/types/primitive/Method';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import ApiBase from './Base';
import { SubmittableResult, SubmittableExtrinsic } from './SubmittableExtrinsic';
import { ISubmittableResult, SubmittableExtrinsic } from './SubmittableExtrinsic';
// Prepend an element V onto the beginning of a tuple T.
// Cons<1, [2,3,4]> is [1,2,3,4]
@@ -222,5 +222,5 @@ export interface Signer {
/**
* @description Receives an update for the extrinsic signed by a `signer.sign`
*/
update?: (id: number, status: Hash | SubmittableResult) => void;
update?: (id: number, status: Hash | ISubmittableResult) => void;
}