Handle storage with optional modifiers (#717)

* Handle storage with optional modifiers

* Storage docs indicate Option

* Cleanup Option logic

* Convert Optional derive to use Option

* Bump version, update changelog

* Update CHANGELOG description

* Enum.spec.js -> Enum.spec.ts

* Add isEmpty to primitive types
This commit is contained in:
Jaco Greeff
2019-02-19 13:47:36 +01:00
committed by GitHub
parent 4f17047c77
commit f807a93e87
40 changed files with 259 additions and 96 deletions
@@ -2,6 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import storage from '@polkadot/storage/static';
import Api from './index';
@@ -13,8 +14,8 @@ const ENC_ONE = '0x24988a82b3bbaae58680bc9de5dea5aa';
const ENC_TWO = '0xdb190750267d8849c35316ec9d342111';
describe('formatting', () => {
let api;
let provider;
let api: Api;
let provider: any;
beforeEach(() => {
provider = {
@@ -51,30 +52,29 @@ describe('formatting', () => {
});
it('encodes multiple keys, decoding multiple results', (done) => {
api.state
.subscribeStorage(
[
[storage.balances.freeBalance, ADDR_ONE],
[storage.balances.freeBalance, ADDR_TWO]
],
(value) => {
console.error(value);
return api.state.subscribeStorage(
[
[storage.balances.freeBalance, ADDR_ONE],
[storage.balances.freeBalance, ADDR_TWO]
],
(value: any) => {
console.error(value);
expect(
provider.subscribe
).toHaveBeenCalledWith(
'state_storage',
'state_subscribeStorage',
[[ENC_ONE, ENC_TWO]],
expect.anything()
);
expect(
value.map((balance) =>
balance.toNumber()
)
).toEqual([513, 258]);
expect(
provider.subscribe
).toHaveBeenCalledWith(
'state_storage',
'state_subscribeStorage',
[[ENC_ONE, ENC_TWO]],
expect.anything()
);
expect(
value.map((balance: BN) =>
balance.toNumber()
)
).toEqual([513, 258]);
done();
});
done();
});
});
});
@@ -5,13 +5,13 @@
import Api from './index';
describe('Api', () => {
let api;
let provider;
let sendSpy;
let api: Api;
let provider: any;
let sendSpy: any;
beforeEach(() => {
provider = {
send: (method, params) => {
send: (method: any, params: Array<any>) => {
return Promise.resolve(params[0]);
}
};
@@ -25,7 +25,7 @@ describe('Api', () => {
it('requires a provider with a send method', () => {
expect(
() => new Api({})
() => new Api({} as any)
).toThrow(/Expected Provider/);
});
+23 -13
View File
@@ -9,8 +9,8 @@ import { RpcInterface, RpcInterface$Method, RpcInterface$Section } from './types
import interfaces from '@polkadot/jsonrpc/index';
import WsProvider from '@polkadot/rpc-provider/ws';
import { Codec } from '@polkadot/types/types';
import { StorageChangeSet, StorageKey, Vector, createType } from '@polkadot/types/index';
import { ExtError, assert, isFunction, logger } from '@polkadot/util';
import { Option, StorageChangeSet, StorageKey, Vector, createClass, createType } from '@polkadot/types/index';
import { ExtError, assert, isFunction, isNull, logger } from '@polkadot/util';
const l = logger('rpc-core');
@@ -189,24 +189,32 @@ export default class Rpc implements RpcInterface {
if (method.type === 'StorageData') {
// single return value (via state.getStorage), decode the value based on the
// outputType that we have specified. Fallback to Data on nothing
const type = (params[0] as StorageKey).outputType || 'Data';
const key = params[0] as StorageKey;
const type = key.outputType || 'Data';
const meta = key.meta || { default: undefined, modifier: { isOptional: true } };
const value = isNull(result)
? null
: base;
return createType(type, base);
return meta.modifier.isOptional
? new Option(createClass(type), value)
: createType(type, value);
} else if (method.type === 'StorageChangeSet') {
// multiple return values (via state.storage subscription), decode the values
// one at a time, all based on the query types. Three values can be returned -
// - Base - There is a valid value, non-empty
// - null - The storage key is empty (but in the resultset)
// - undefined - The storage value is not in the resultset
return (params[0] as Vector<StorageKey>).reduce((result, _key: StorageKey) => {
return (params[0] as Vector<StorageKey>).reduce((result, key: StorageKey) => {
// Fallback to Data (i.e. just the encoding) if we don't have a specific type
const type = _key.outputType || 'Data';
const type = key.outputType || 'Data';
// see if we have a result value for this specific key
const key = _key.toHex();
const hexKey = key.toHex();
const item = (base as StorageChangeSet).changes.find((item) =>
item.key.toHex() === key
item.key.toHex() === hexKey
);
const meta = key.meta || { default: undefined, modifier: { isOptional: true } };
// if we don't have a value, do not fill in the entry, it will be up to the
// caller to sort this out, either ignoring or having a cache for older values
@@ -214,11 +222,13 @@ export default class Rpc implements RpcInterface {
!item
? undefined
: (
// for `null` we fallback to the default value, or create an empty type,
// otherwise we return the actual value as retrieved
item.value.isNone
? createType(type, (_key.meta || { default: undefined }).default)
: createType(type, item.value.unwrap())
meta.modifier.isOptional
// create option either with the existing value, or empty when
// there is no value returned
? new Option(createClass(type), item.value.unwrapOr(null))
// for `null` we fallback to the default value, or create an empty type,
// otherwise we return the actual value as retrieved
: createType(type, item.value.unwrapOr(meta.default))
)
);
@@ -5,9 +5,9 @@
import Api from './index';
describe('methodSend', () => {
let api;
let methods;
let provider;
let api: Api;
let methods: any;
let provider: any;
beforeEach(() => {
methods = {
@@ -37,6 +37,7 @@ describe('methodSend', () => {
});
it('wraps errors with the call signature', () => {
// @ts-ignore private method
const method = api.createMethodSend(methods.blah);
return method().catch((error) => {
@@ -45,6 +46,7 @@ describe('methodSend', () => {
});
it('checks for mismatched parameters', () => {
// @ts-ignore private method
const method = api.createMethodSend(methods.bleh);
return method(1).catch((error) => {
@@ -53,6 +55,7 @@ describe('methodSend', () => {
});
it('calls the provider with the correct parameters', () => {
// @ts-ignore private method
const method = api.createMethodSend(methods.blah);
// Args are length-prefixed, because it's a Bytes