Skip to content

Commit 1101826

Browse files
authored
Rename contract helpers (#2708)
* Rename contract helpers * Allow Buffer input for code * Parse json strings * Revert #typeDefs * Allow lookup on name * constsitent string ids * Read only via address * Move .json * Extract findMessage * Naming
1 parent fda1924 commit 1101826

File tree

11 files changed

+59
-61
lines changed

11 files changed

+59
-61
lines changed

packages/api-contract/src/Abi.spec.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
22
// SPDX-License-Identifier: Apache-2.0
33

4-
import { TypeRegistry } from '@polkadot/types';
5-
64
import Abi from './Abi';
75

86
import * as testContracts from '../test/contracts';
97

108
const abis: Record<string, any> = { ...testContracts };
119

12-
function compare (name: string, registry: TypeRegistry, messageIds: string[]): void {
10+
function compare (name: string, messageIds: string[]): void {
1311
try {
1412
const inkAbi = new Abi(abis[name]);
1513

@@ -23,18 +21,16 @@ function compare (name: string, registry: TypeRegistry, messageIds: string[]): v
2321

2422
describe('Abi', (): void => {
2523
describe('construction', (): void => {
26-
const registry = new TypeRegistry();
27-
2824
it('initializes from a contract ABI (flipper)', (): void => {
29-
compare('flipper', registry, ['flip', 'get']);
25+
compare('flipper', ['flip', 'get']);
3026
});
3127

3228
it('initializes from a contract ABI (incrementer)', (): void => {
33-
compare('incrementer', registry, ['inc', 'get']);
29+
compare('incrementer', ['inc', 'get']);
3430
});
3531

3632
it('initializes from a contract ABI (erc20)', (): void => {
37-
compare('erc20', registry, [
33+
compare('erc20', [
3834
'total_supply',
3935
'balance_of',
4036
'allowance',
@@ -45,15 +41,15 @@ describe('Abi', (): void => {
4541
});
4642

4743
it('initializes from a contract ABI (delegator)', (): void => {
48-
compare('delegator', registry, [
44+
compare('delegator', [
4945
'get',
5046
'change',
5147
'switch'
5248
]);
5349
});
5450

5551
it('initializes from a contract ABI (dns)', (): void => {
56-
compare('dns', registry, [
52+
compare('dns', [
5753
'register',
5854
'set_address',
5955
'transfer',
@@ -62,7 +58,7 @@ describe('Abi', (): void => {
6258
});
6359

6460
it('initializes from a contract ABI (erc721)', (): void => {
65-
compare('erc721', registry, [
61+
compare('erc721', [
6662
'balance_of',
6763
'owner_of',
6864
'get_approved',
@@ -77,7 +73,7 @@ describe('Abi', (): void => {
7773
});
7874

7975
it('initializes from a contract ABI (multisig_plain)', (): void => {
80-
compare('multisigPlain', registry, [
76+
compare('multisigPlain', [
8177
'add_owner',
8278
'remove_owner',
8379
'replace_owner',
@@ -91,4 +87,8 @@ describe('Abi', (): void => {
9187
]);
9288
});
9389
});
90+
91+
it('stores base project as JSON', (): void => {
92+
expect(new Abi(abis.dns).json).toEqual(abis.dns);
93+
});
9494
});

packages/api-contract/src/Abi.ts

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,39 @@ import { AnyJson } from '@polkadot/types/types';
55
import { InkConstructorSpec, InkMessageSpec } from '@polkadot/types/interfaces';
66
import { AbiConstructor, AbiMessage, AbiMessageParam } from './types';
77

8-
import { assert, isNumber, isObject, stringCamelCase } from '@polkadot/util';
8+
import { assert, isNumber, isObject, isString, stringCamelCase } from '@polkadot/util';
99

1010
import ContractRegistry from './ContractRegistry';
1111

12+
function findMessage <T extends AbiMessage> (list: T[], messageOrId: T | string | number): T {
13+
const message = isNumber(messageOrId)
14+
? list[messageOrId]
15+
: isString(messageOrId)
16+
? list.find(({ identifier }: T) => identifier === messageOrId.toString())
17+
: messageOrId;
18+
19+
assert(message, `Attempted to call an invalid contract interface, ${JSON.stringify(messageOrId)}`);
20+
21+
return message;
22+
}
23+
1224
export default class Abi extends ContractRegistry {
1325
public readonly constructors: AbiConstructor[];
1426

27+
public readonly json: AnyJson;
28+
1529
public readonly messages: AbiMessage[];
1630

17-
constructor (json: AnyJson) {
31+
constructor (abiJson: AnyJson) {
32+
const json = isString(abiJson)
33+
? JSON.parse(abiJson) as AnyJson
34+
: abiJson;
35+
36+
assert(isObject(json) && !Array.isArray(json) && json.metadataVersion && isObject(json.spec) && !Array.isArray(json.spec) && Array.isArray(json.spec.constructors) && Array.isArray(json.spec.messages), 'Invalid JSON ABI structure supplied, expected a recent metadata version');
37+
1838
super(json);
1939

40+
this.json = json;
2041
this.constructors = this.project.spec.constructors.map((spec: InkConstructorSpec, index) =>
2142
this._createBase(spec, index, {
2243
isConstructor: true
@@ -35,24 +56,12 @@ export default class Abi extends ContractRegistry {
3556
});
3657
}
3758

38-
public findConstructor (constructorOrIndex: AbiConstructor | number): AbiConstructor {
39-
const message = isNumber(constructorOrIndex)
40-
? this.constructors[constructorOrIndex]
41-
: constructorOrIndex;
42-
43-
assert(message, 'Attempted to call an invalid contract message');
44-
45-
return message;
59+
public findConstructor (constructorOrId: AbiConstructor | string | number): AbiConstructor {
60+
return findMessage(this.constructors, constructorOrId);
4661
}
4762

48-
public findMessage (messageOrIndex: AbiMessage | number): AbiMessage {
49-
const message = isNumber(messageOrIndex)
50-
? this.messages[messageOrIndex]
51-
: messageOrIndex;
52-
53-
assert(message, 'Attempted to call an invalid contract message');
54-
55-
return message;
63+
public findMessage (messageOrId: AbiMessage | string | number): AbiMessage {
64+
return findMessage(this.messages, messageOrId);
5665
}
5766

5867
private _createBase (spec: InkMessageSpec | InkConstructorSpec, index: number, add: Partial<AbiMessage> = {}): AbiMessage {

packages/api-contract/src/ContractRegistry.spec.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,5 @@ describe('ContractRegistry', (): void => {
5454
it('initializes from a contract ABI (multisig_plain)', (): void => {
5555
compare('multisigPlain');
5656
});
57-
58-
it('stores base project as JSON', (): void => {
59-
const inkRegistry = new ContractRegistry(abis.dns);
60-
61-
expect(inkRegistry.json).toEqual(abis.dns);
62-
});
6357
});
6458
});

packages/api-contract/src/ContractRegistry.ts

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import { InkProject, MtField, MtLookupTypeId, MtType, MtTypeDefArray, MtTypeDefVariant, MtTypeDefSequence, MtTypeDefTuple, MtVariant } from '@polkadot/types/interfaces';
55
import { AnyJson, Registry, TypeDef, TypeDefInfo } from '@polkadot/types/types';
66

7-
import { assert, isObject, isUndefined } from '@polkadot/util';
7+
import { assert, isUndefined } from '@polkadot/util';
88
import { TypeRegistry, withTypeString } from '@polkadot/types';
99

1010
// convert the offset into project-specific, index-1
@@ -13,19 +13,14 @@ export function getRegistryOffset (id: MtLookupTypeId): number {
1313
}
1414

1515
export default class ContractRegistry {
16-
public typeDefs: TypeDef[] = [];
16+
public readonly typeDefs: TypeDef[] = [];
1717

1818
public readonly registry: Registry;
1919

20-
public project: InkProject;
21-
22-
public json: AnyJson;
23-
24-
constructor (json: AnyJson) {
25-
assert(isObject(json) && !Array.isArray(json) && json.metadataVersion && isObject(json.spec) && !Array.isArray(json.spec) && Array.isArray(json.spec.constructors) && Array.isArray(json.spec.messages), 'Invalid JSON ABI structure supplied, expected a recent metadata version');
20+
public readonly project: InkProject;
2621

22+
constructor (json: Record<string, AnyJson>) {
2723
this.registry = new TypeRegistry();
28-
this.json = json;
2924
this.project = this.registry.createType('InkProject', json);
3025

3126
// Generate TypeDefs for each provided registry type

packages/api-contract/src/base/Blueprint.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ export default class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
3535
this.codeHash = this.registry.createType('Hash', codeHash);
3636
}
3737

38-
public createContract (constructorOrIndex: AbiConstructor | number, endowment: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> {
38+
public createContract (constructorOrId: AbiConstructor | string| number, endowment: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> {
3939
return this.api.tx.contracts
40-
.instantiate(endowment, gasLimit, this.codeHash, encodeMessage(this.registry, this.abi.findConstructor(constructorOrIndex), params))
40+
.instantiate(endowment, gasLimit, this.codeHash, encodeMessage(this.registry, this.abi.findConstructor(constructorOrId), params))
4141
.withResultTransform((result: ISubmittableResult) =>
4242
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', (record: EventRecord) =>
4343
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)

packages/api-contract/src/base/Code.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export class CodeSubmittableResult<ApiType extends ApiTypes> extends Submittable
2828
export default class Code<ApiType extends ApiTypes> extends Base<ApiType> {
2929
public readonly code: Uint8Array;
3030

31-
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string, decorateMethod: DecorateMethod<ApiType>) {
31+
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer, decorateMethod: DecorateMethod<ApiType>) {
3232
super(api, abi, decorateMethod);
3333

3434
this.code = u8aToU8a(wasm);

packages/api-contract/src/base/Contract.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,18 +47,18 @@ export default class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
4747
return isFunction(this.api.rx.rpc.contracts?.call);
4848
}
4949

50-
public exec (messageOrIndex: AbiMessage | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): SubmittableExtrinsic<ApiType> {
51-
return this.api.tx.contracts.call(this.address, value, gasLimit, encodeMessage(this.registry, this.abi.findMessage(messageOrIndex), params));
50+
public exec (messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): SubmittableExtrinsic<ApiType> {
51+
return this.api.tx.contracts.call(this.address, value, gasLimit, encodeMessage(this.registry, this.abi.findMessage(messageOrId), params));
5252
}
5353

54-
public read (messageOrIndex: AbiMessage | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): ContractRead<ApiType> {
54+
public read (messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): ContractRead<ApiType> {
5555
assert(this.hasRpcContractsCall, 'Your node does not support contract RPC read calls');
5656

57-
const message = this.abi.findMessage(messageOrIndex);
57+
const message = this.abi.findMessage(messageOrId);
5858

5959
return {
6060
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
61-
send: this._decorateMethod((account: IKeyringPair | string | AccountId): ContractCallResult<'rpc'> =>
61+
send: this._decorateMethod((account: string | AccountId | Uint8Array): ContractCallResult<'rpc'> =>
6262
this.api.rx.rpc.contracts.call({
6363
dest: this.address,
6464
gasLimit,

packages/api-contract/src/promise/PromiseCode.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import Abi from '../Abi';
99
import Code from '../base/Code';
1010

1111
export default class PromiseCode extends Code<'promise'> {
12-
constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: string | Uint8Array) {
12+
constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer) {
1313
super(api, abi, wasm, decorateMethod);
1414
}
1515
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
22
// SPDX-License-Identifier: Apache-2.0
33

4-
export { default as PromiseBlueprint } from './PromiseBlueprint';
5-
export { default as PromiseCode } from './PromiseCode';
6-
export { default as PromiseContract } from './PromiseContract';
4+
export { default as BlueprintPromise } from './PromiseBlueprint';
5+
export { default as CodePromise } from './PromiseCode';
6+
export { default as ContractPromise } from './PromiseContract';

packages/api-contract/src/rx/RxCode.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import Abi from '../Abi';
1010
import Code from '../base/Code';
1111

1212
export default class RxCode extends Code<'rxjs'> {
13-
constructor (api: ApiRx, abi: AnyJson | Abi, wasm: string | Uint8Array) {
13+
constructor (api: ApiRx, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer) {
1414
super(api, abi, wasm, decorateMethod);
1515
}
1616
}

0 commit comments

Comments
 (0)