Add EventRecord & PairOf (#349)

* Fix metadata type output for storage

* Add EventRecord

* Add PairOf, rename .with to .with<Class>

* Revert .with changes, test for EventRecord

* ApplkyExtrinsic extends u32

* Log EnumType errors a tiny bit better
This commit is contained in:
Jaco Greeff
2018-10-25 21:21:19 +02:00
committed by GitHub
parent f54173c862
commit c42b71a6d8
13 changed files with 187 additions and 19 deletions
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2017-2018 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import createType from './codec/createType';
import Vector from './codec/Vector';
import json from './json/EventRecord.001.json';
import { EventRecord } from './index';
describe('EventRecord', () => {
it('decodes correctly', () => {
const records: Vector<EventRecord> = createType('Vec<EventRecord>', json.params.result.changes[0][1]) as any;
const er = records.get(0);
expect(er.phase.type).toEqual('ApplyExtrinsic');
});
});
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2017-2018 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import EnumType from './codec/EnumType';
import Struct from './codec/Struct';
import Null from './Null';
import U32 from './U32';
class ApplyExtrinsic extends U32 {
}
class Finalization extends Null {
}
class Phase extends EnumType<ApplyExtrinsic | Finalization> {
constructor (value: any, index?: number) {
super([
ApplyExtrinsic,
Finalization
], value, index);
}
}
// FIXME Once we have actual data from Events, have a look on how to decode them
class Event extends Null {
}
export default class EventRecord extends Struct {
constructor (value: any) {
super({
phase: Phase,
event: Event
}, value);
}
get event (): Event {
return this.get('event') as Event;
}
get phase (): Phase {
return this.get('phase') as Phase;
}
}
+1 -1
View File
@@ -393,7 +393,7 @@ export default class RuntimeMetadata extends Struct {
? module.storage.functions.map((fn) =>
fn.type.isMap
? [fn.type.asMap.key.raw, fn.type.asMap.value.raw]
: [fn.type.asType.raw]
: [fn.type.asType]
)
: []
);
+1 -1
View File
@@ -6,7 +6,7 @@ import Text from './Text';
type Mapper = (value: string) => string;
const ALLOWED_BOXES = ['Vec', 'Option'];
const ALLOWED_BOXES = ['Option', 'PairOf', 'Vec'];
// This is a extended version of String, specifically to handle types. Here we rely full on
// what string provides us, however we also "tweak" the types received from the runtime, i.e.
+5 -1
View File
@@ -65,7 +65,11 @@ export default class EnumType<T> extends Base<Base<T>> {
.find((k) => def[+k].name.toLowerCase() === lowerKey);
if (isUndefined(index)) {
throw new Error('Unable to reliably map input on JSON');
const message = 'Unable to reliably map input on JSON';
console.error(message, value, def);
throw new Error(message);
}
return { index: +index, value: new def[+index](value[key]) };
+36
View File
@@ -0,0 +1,36 @@
// Copyright 2017-2018 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { Constructor, ConstructorDef } from '../types';
import Base from './Base';
import Tuple from './Tuple';
// PairOf defines a general structure that creates a Tuple pair of a specific type. These values
// are accessible via the first & second getters
export default class PairOf<
T extends Base
> extends Tuple<{ first: Constructor<T>, second: Constructor<T> }> {
static with<
S extends ConstructorDef = { [index: string]: Constructor<Base> }
> (Type: S): Constructor<Tuple<S>>;
static with<T extends Base> (Type: Constructor<T>): Constructor<PairOf<T>> {
return class extends PairOf<T> {
constructor (value?: any) {
super({
first: Type,
second: Type
}, value);
}
};
}
get first (): T {
return this.get('first') as T;
}
get second (): T {
return this.get('second') as T;
}
}
+4 -3
View File
@@ -21,13 +21,14 @@ export default class Struct<
V extends { [K in keyof S]: any } = { [K in keyof S]: any },
// type names, mapped by key, name of Class in S
E extends { [K in keyof S]: string } = { [K in keyof S]: string }
> extends Map<keyof S, Base> implements Codec {
> extends Map<keyof S, Base> implements Codec {
public raw: Map<keyof S, Base>; // FIXME Remove this once we convert all types out of Base
protected _jsonMap: Map<keyof S, string>;
protected _Types: E;
constructor (Types: S, value: V | Array<any> = {} as V, jsonMap: Map<keyof S, string> = new Map()) {
const decoded = Struct.decodeStruct<S, V, T>(Types, value, jsonMap);
super(
Object.entries(decoded)
);
@@ -64,7 +65,7 @@ export default class Struct<
S extends ConstructorDef,
_,
T extends { [K in keyof S]: Base }
> (Types: S, value: any, jsonMap: Map<keyof S, string>): T {
> (Types: S, value: any, jsonMap: Map<keyof S, string>): T {
// l.debug(() => ['Struct.decode', { Types, value }]);
if (isHex(value)) {
@@ -111,7 +112,7 @@ export default class Struct<
static with<
S extends ConstructorDef
> (Types: S): Constructor<Struct<S>> {
> (Types: S): Constructor<Struct<S>> {
return class extends Struct<S> {
constructor (value?: any, jsonMap?: Map<keyof S, string>) {
super(Types, value, jsonMap);
+4 -4
View File
@@ -12,12 +12,12 @@ import Struct from './Struct';
export default class Tuple<
// S & T definitions maps to what we have in Struct (naming documented there)
S extends ConstructorDef = { [index: string]: Constructor<Base> },
T extends { [K in keyof S]: Base }= { [K in keyof S]: Base },
T extends { [K in keyof S]: Base } = { [K in keyof S]: Base },
V extends { [K in keyof S]: any } = { [K in keyof S]: any }
> extends Struct<S, T, V> {
> extends Struct<S, T, V> {
static with<
S extends ConstructorDef= { [index: string]: Constructor<Base> }
> (Types: S): Constructor<Tuple<S>> {
S extends ConstructorDef = { [index: string]: Constructor<Base> }
> (Types: S): Constructor<Tuple<S>> {
return class extends Tuple<S> {
constructor (value?: any) {
super(Types, value);
@@ -13,8 +13,8 @@ describe('typeSplit', () => {
it('splits nested combinations', () => {
expect(
typeSplit('Text, (u32), Vec<u64>')
).toEqual(['Text', '(u32)', 'Vec<u64>']);
typeSplit('Text, (u32), Vec<u64>, PairOf<u32>')
).toEqual(['Text', '(u32)', 'Vec<u64>', 'PairOf<u32>']);
});
it('keeps nested tuples together', () => {
@@ -61,12 +61,18 @@ describe('getTypeValue', () => {
).toThrow(/Vec wrapped/);
});
it('does not allow invalid Pairs, end >', () => {
expect(
() => getTypeDef('PairOf<u32')
).toThrow(/PairOf wrapped/);
});
it('returns a type structure', () => {
expect(
getTypeDef('(u32, Vec<u64>, (Text, Vec<(Bool, u128)>))')
getTypeDef('(u32, Vec<u64>, PairOf<u32>, (Text, Vec<(Bool, u128)>))')
).toEqual({
info: TypeDefInfo.Tuple,
type: '(u32, Vec<u64>, (Text, Vec<(Bool, u128)>))',
type: '(u32, Vec<u64>, PairOf<u32>, (Text, Vec<(Bool, u128)>))',
sub: [
{
info: TypeDefInfo.Plain,
@@ -80,6 +86,14 @@ describe('getTypeValue', () => {
type: 'u64'
}
},
{
info: TypeDefInfo.PairOf,
type: 'PairOf<u32>',
sub: {
info: TypeDefInfo.Plain,
type: 'u32'
}
},
{
info: TypeDefInfo.Tuple,
type: '(Text, Vec<(Bool, u128)>)',
@@ -143,7 +157,7 @@ describe('getTypeValue', () => {
describe('getTypeClass', () => {
it('does not allow invalid types', () => {
expect(
() => getTypeClass('SomethingInvalid')
() => getTypeClass('SomethingInvalid' as any)
).toThrow(/determine type/);
});
});
+23 -4
View File
@@ -7,10 +7,12 @@ import { assert } from '@polkadot/util';
import { Constructor } from '../types';
import Text from '../Text';
import Base from './Base';
import PairOf from './PairOf';
import Tuple from './Tuple';
import Vector from './Vector';
export enum TypeDefInfo {
PairOf,
Plain,
Tuple,
Vector
@@ -50,12 +52,12 @@ export function typeSplit (type: string): Array<string> {
break;
case '<':
// inc vec depth
// inc vec/pair depth
vDepth++;
break;
case '>':
// dec tuple depth
// dec vec/pair depth
vDepth--;
break;
@@ -84,7 +86,7 @@ export function getTypeDef (_type: Text | string): TypeDef {
assert(type[type.length - 1] === ')', `Expected tuple wrapped with ()`);
// strip wrapping ()'s
const innerTypes = typeSplit(type.substr(1, type.length - 2));
const innerTypes = typeSplit(type.substr(1, type.length - 1 - 1));
value.info = TypeDefInfo.Tuple;
value.sub = innerTypes.map((inner) =>
@@ -94,10 +96,18 @@ export function getTypeDef (_type: Text | string): TypeDef {
assert(type[type.length - 1] === '>', `Expected Vec wrapped with <>`);
// strip wrapping Vec<>
const subType = type.substr(4, type.length - 5);
const subType = type.substr(4, type.length - 4 - 1);
value.info = TypeDefInfo.Vector;
value.sub = getTypeDef(subType);
} else if (type.substr(0, 7) === 'PairOf<') {
assert(type[type.length - 1] === '>', `Expected PairOf wrapped with <>`);
// strip wrapping PairOf<>
const subType = type.substr(7, type.length - 7 - 1);
value.info = TypeDefInfo.PairOf;
value.sub = getTypeDef(subType);
}
return value;
@@ -125,6 +135,15 @@ export function getTypeClass (value: TypeDef): Constructor {
return Vector.with(
getTypeClass(value.sub)
);
} else if (value.info === TypeDefInfo.PairOf) {
if (!value.sub || Array.isArray(value.sub)) {
throw new Error(`Expected subtype for PairOf`);
}
// This is not too cool... because of the static overrides we have a small issue here
return PairOf.with<any>(
getTypeClass(value.sub)
);
}
// We are dynamically loading as to avoid circular dependencies
+1
View File
@@ -27,6 +27,7 @@ export { default as Compact256 } from './Compact256';
export { default as Data } from './Data';
// NOTE Only used internally,
// export { default as Digest } from './Digest';
export { default as EventRecord } from './EventRecord';
export { default as Extrinsic } from './Extrinsic';
export { default as ExtrinsicEra } from './ExtrinsicEra';
export { default as ExtrinsicSignature } from './ExtrinsicSignature';
@@ -0,0 +1,16 @@
{
"jsonrpc": "2.0",
"method": "state_storage",
"params": {
"result": {
"block": "0x4c51fb36c859f9d2554ef0dadf53351c343f2746221a963d630bfe396728842d",
"changes": [
[
"0xcc956bdb7605e3547539f321ac2bc95c",
"0x0400000000000000"
]
]
},
"subscription": 14
}
}
@@ -0,0 +1,16 @@
{
"jsonrpc": "2.0",
"method": "state_storage",
"params": {
"result": {
"block": "0xa7f1ac9f18dded8e5825205d3e5260cf53ba01f629d9ebc1b80601b45ed8c358",
"changes": [
[
"0xcc956bdb7605e3547539f321ac2bc95c",
"0x10000000000000000001000000010037e027d776cd005c12bcf6722421374a9037167a0ceaf918f341c4ad68d54e59070000000000010000000102d2de7394ae047a5502ad9adb9cc69ff6fe484033bfce874d775da947487cd83237e027d776cd005c12bcf6722421374a9037167a0ceaf918f341c4ad68d54e59e80300000000000000000000000000000000000000000000000000000000000000010000000000"
]
]
},
"subscription": 19
}
}