API formatting for inputs & outputs (#171)

* API formatting for inputs & outputs

* Shorten naming

* getStorage (signle key) operational

* Remove api-format (not used in api anymore)

* Cleanup creation logic

* Cleanup linting

* Cleanup storage creation

* e2e state test

* Add code test

* Add isBare flag to toU8a

* Uppercase... wtill wrong though

* Update metadata json

* We are creating keys properly

* Cleanup tslint

* Type splitting,m handling Tuple & Vector

* StorageChangeSet results in-place

* Update deps

* Allow Tuples to have array constructors

* Test for uncloded vec/tuple

* Update deps
This commit is contained in:
Jaco Greeff
2018-09-28 15:42:23 +02:00
committed by GitHub
parent 8380455599
commit 74737b6367
70 changed files with 748 additions and 697 deletions
+1 -2
View File
@@ -30,10 +30,9 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.0.0",
"@polkadot/api-format": "^0.30.1",
"@polkadot/api-provider": "^0.30.1",
"@polkadot/jsonrpc": "^0.30.1",
"@polkadot/params": "^0.30.1",
"@polkadot/util": "^0.30.4"
"@polkadot/util": "^0.30.7"
}
}
@@ -2,17 +2,17 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import storage from '@polkadot/storage';
import storage from '@polkadot/storage/testing';
import Api from './index';
const ADDR_ONE = '5EhmTa7fL6SdjgKXo9g6hetR6nHnRAmrtisoGFWEESjzECtY';
const ADDR_TWO = '5FjbQAHSptRU4Q7Py6zDsRnE7UkpZikJVg5nm1tmu3WuZXKd';
const ENC_ONE = '0x11cf1094db4db43356b7787c3e59c39f';
const ENC_TWO = '0x924776c687da8e30afdd2ac87d2c67da';
const ENC_ONE = '0x24988a82b3bbaae58680bc9de5dea5aa';
const ENC_TWO = '0xdb190750267d8849c35316ec9d342111';
describe('formatResult', () => {
describe('formatting', () => {
let api;
let provider;
@@ -25,8 +25,8 @@ describe('formatResult', () => {
subscription(null, {
block: '0x1234',
changes: [
['0x11cf1094db4db43356b7787c3e59c39f', '0x0102'],
['0x924776c687da8e30afdd2ac87d2c67da', '0x0201']
[ENC_ONE, '0x0102'],
[ENC_TWO, '0x0201']
]
})
)
@@ -34,12 +34,11 @@ describe('formatResult', () => {
api = new Api(provider);
});
it.skip('encodes key (with params), decoding response', () => {
it('encodes key (with params), decoding response', () => {
return api.state
.getStorage([
// FIXME changed storage api
storage.staking.public.freeBalanceOf, ADDR_ONE
])
.getStorage(
[storage.balances.freeBalance, ADDR_ONE]
)
.then((value) => {
expect(
provider.send
@@ -51,15 +50,16 @@ describe('formatResult', () => {
});
});
it.skip('encodes multiple keys, decoding multiple results', (done) => {
it('encodes multiple keys, decoding multiple results', (done) => {
api.state
.storage(
[
// FIXME changed storage api
[storage.staking.public.freeBalanceOf, ADDR_ONE],
[storage.staking.public.freeBalanceOf, ADDR_TWO]
[storage.balances.freeBalance, ADDR_ONE],
[storage.balances.freeBalance, ADDR_TWO]
],
(error, value) => {
console.error(value);
expect(
provider.subscribe
).toHaveBeenCalledWith(
@@ -69,7 +69,9 @@ describe('formatResult', () => {
expect.anything()
);
expect(
value.map((bn) => bn.toNumber())
value.map((balance) =>
balance.toNumber()
)
).toEqual([513, 258]);
done(error);
+56 -33
View File
@@ -5,13 +5,11 @@
import { ProviderInterface, ProviderInterface$Callback } from '@polkadot/api-provider/types';
import { Interfaces, Interface$Sections } from '@polkadot/jsonrpc/types';
import { SectionItem } from '@polkadot/params/types';
import { Storages } from '@polkadot/storage/types';
import { ApiInterface, ApiInterface$Section, ApiInterface$Section$Method } from './types';
import formatInputs from '@polkadot/api-format/input';
import formatOutput from '@polkadot/api-format/output';
import { Base, Vector, createType } from '@polkadot/api-codec/codec';
import { StorageChangeSet, StorageKey } from '@polkadot/api-codec/index';
import interfaces from '@polkadot/jsonrpc/index';
import decodeParams from '@polkadot/params/decode';
import signature from '@polkadot/params/signature';
import assert from '@polkadot/util/assert';
import ExtError from '@polkadot/util/ext/error';
@@ -20,14 +18,11 @@ import isUndefined from '@polkadot/util/is/undefined';
/**
* @example
* ```javascript
*
* import Api from '@polkadot/api';
* import WsProvider from '@polkadot/api-provider/ws';
*
* const provider = new WsProvider('http://127.0.0.1:9944');
* const api = new Api(provider);
* ```
*/
export default class Api implements ApiInterface {
private _provider: ProviderInterface;
@@ -78,12 +73,17 @@ export default class Api implements ApiInterface {
const call = async (...values: Array<any>): Promise<any> => {
// TODO Warn on deprecated methods
try {
const params = formatInputs(method.params, values);
const result = await this._provider.send(rpcName, params);
const params = this.formatInputs(method, values);
const paramsJson = params.map((param) => param.toJSON());
const result = await this._provider.send(rpcName, paramsJson);
return this.formatResult(method, params, values, result);
return this.formatOutput(method, params, result);
} catch (error) {
throw new ExtError(`${signature(method)}:: ${error.message}`, (error as ExtError).code, undefined);
const message = `${signature(method)}:: ${error.message}`;
console.error(message, error);
throw new ExtError(message, (error as ExtError).code, undefined);
}
};
@@ -99,14 +99,19 @@ export default class Api implements ApiInterface {
assert(isFunction(cb), `Expected callback in last position of params`);
const params = formatInputs(method.params, values);
const params = this.formatInputs(method, values);
const paramsJson = params.map((param) => param.toJSON());
const update = (error: Error | null, result?: any) => {
cb(error, this.formatResult(method, params, values, result));
cb(error, this.formatOutput(method, params, result));
};
return this._provider.subscribe(rpcName, method.subscribe[0], params, update);
return this._provider.subscribe(rpcName, method.subscribe[0], paramsJson, update);
} catch (error) {
throw new ExtError(`${signature(method)}:: ${error.message}`, (error as ExtError).code, undefined);
const message = `${signature(method)}:: ${error.message}`;
console.error(message, error);
throw new ExtError(message, (error as ExtError).code, undefined);
}
};
@@ -117,29 +122,47 @@ export default class Api implements ApiInterface {
return call;
}
private formatResult (method: SectionItem<Interfaces>, params: Array<any>, inputs: Array<any>, result?: any): any {
if (method.type === 'StorageResult') {
return this.formatStorageOutput(inputs[0][0], result);
}
private formatInputs (method: SectionItem<Interfaces>, inputs: Array<any>): Array<Base> {
assert(method.params.length === inputs.length, `Expected ${method.params.length} parameters, ${inputs.length} found instead`);
if (method.type === 'StorageResultSet') {
return params[0].map((key: string, index: number) => {
const input = inputs[0][index][0];
const { changes = [] }: { block: string, changes: Array<[string, string]> } = result || {};
const value = changes.find(([_key]) => key === _key);
return method.params.map(({ type }, index) =>
createType(type as string, inputs[index])
);
}
if (!value) {
return undefined;
private formatOutput (method: SectionItem<Interfaces>, params: Array<Base>, result?: any): Base {
const base = createType(method.type as string, result);
if (method.type === 'StorageData') {
const type = (params[0] as StorageKey).outputType;
if (type) {
return createType(type, base.raw);
}
} else if (method.type === 'StorageChangeSet') {
return (params[0] as Vector<StorageKey>).reduce((vector, _key: StorageKey) => {
const type = _key.outputType;
if (!type) {
throw new Error('Cannot format StorageChangeSet, output type missing for key');
}
return this.formatStorageOutput(input, value[1]);
});
const key = _key.toHex();
const item = (base as StorageChangeSet).changes.find((item) =>
item.key.toHex() === key
);
if (!item) {
throw new Error('No result found for key in StorageChangeSet');
}
vector.push(createType(type, item.value.value));
return vector;
}, new (Vector.with(Base))());
}
return formatOutput(method.type, result);
}
private formatStorageOutput (key: SectionItem<Storages>, result?: any): any {
return decodeParams(key.type, result, 'latest', true).value;
return base;
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ describe('methodSend', () => {
const method = api.createMethodSend('test_bleh', methods.bleh);
return method(1).catch((error) => {
expect(error.message).toMatch(/no params expected, found 1 instead/);
expect(error.message).toMatch(/parameters, 1 found instead/);
});
});