Allow createType to create sets (#1191)

* Allow createType to create sets

* build:srmlTs generates types
This commit is contained in:
Jaco Greeff
2019-07-25 15:20:32 +02:00
committed by GitHub
parent ed6aad8265
commit 6d65095ee0
11 changed files with 126 additions and 90 deletions
+24 -5
View File
@@ -2,9 +2,9 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { assert, isU8a, isNumber, isUndefined, u8aToHex } from '@polkadot/util';
import { assert, isU8a, isNumber, isUndefined, stringCamelCase, stringUpperFirst, u8aToHex } from '@polkadot/util';
import { Codec } from '../types';
import { Codec, Constructor } from '../types';
import { compareArray } from './utils';
type SetValues = Record<string, number>;
@@ -20,9 +20,7 @@ export default class CodecSet extends Set<string> implements Codec {
private _setValues: SetValues;
public constructor (setValues: SetValues, value?: string[] | Set<string> | Uint8Array | number) {
super(
CodecSet.decodeSet(setValues, value)
);
super(CodecSet.decodeSet(setValues, value));
this._setValues = setValues;
}
@@ -65,6 +63,27 @@ export default class CodecSet extends Set<string> implements Codec {
}, 0);
}
public static with (values: SetValues): Constructor<CodecSet> {
return class extends CodecSet {
public constructor (value?: any) {
super(values, value);
Object.keys(values).forEach((_key): void => {
const name = stringUpperFirst(stringCamelCase(_key));
const iskey = `is${name}`;
// do not clobber existing properties on the object
if (isUndefined((this as any)[iskey])) {
Object.defineProperty(this, iskey, {
enumerable: true,
get: (): boolean => this.strings.includes(_key)
});
}
});
}
};
}
/**
* @description The length of the value when encoded as a Uint8Array
*/
@@ -8,6 +8,7 @@ import createType, { TypeDef, TypeDefInfo, createClass, getTypeClass, getTypeDef
import Balance from '../primitive/Balance';
import Text from '../primitive/Text';
import { injectDefinitions } from '../srml';
import CodecSet from './Set';
describe('typeSplit', (): void => {
it('splits simple types into an array', (): void => {
@@ -265,6 +266,12 @@ describe('createType', (): void => {
).toEqual({ B: 0 });
});
it('allows creation of a Set', (): void => {
expect(
createType<CodecSet>('{"_set": { "A": 1, "B": 2, "C": 4, "D": 8, "E": 16, "G": 32, "H": 64, "I": 128 } }', 1 + 4 + 16 + 64).strings
).toEqual(['A', 'C', 'E', 'H']);
});
it('allows creation of a [u8; 8]', (): void => {
expect(
createType('[u8; 8]', [0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67, 0x00]).toHex()
+61 -23
View File
@@ -13,6 +13,7 @@ import Compact from './Compact';
import Enum from './Enum';
import Linkage from './Linkage';
import Option from './Option';
import CodecSet from './Set';
import Struct from './Struct';
import Tuple from './Tuple';
import U8aFixed, { BitLength as U8aFixedBitLength } from './U8aFixed';
@@ -28,6 +29,7 @@ export enum TypeDefInfo {
Linkage,
Option,
Plain,
Set,
Struct,
Tuple,
Vector,
@@ -43,6 +45,7 @@ export interface TypeDefExtVecFixed {
export interface TypeDef {
info: TypeDefInfo;
index?: number;
ext?: TypeDefExtVecFixed; // add additional here as required
name?: string;
type: string;
@@ -97,6 +100,42 @@ export function typeSplit (type: string): string[] {
return result;
}
// decode an enum of either of the following forms
// { _enum: ['A', 'B', 'C'] }
// { _enum: { A: AccountId, B: Balance, C: u32 } }
function _decodeEnum (value: TypeDef, details: string[] | Record<string, string>): TypeDef {
value.info = TypeDefInfo.Enum;
// not as pretty, but remain compatible with oo7 for both struct and Array types
value.sub = Array.isArray(details)
? details.map((name): TypeDef => ({
info: TypeDefInfo.Plain,
name,
type: 'Null'
}))
: Object.entries(details).map(([name, type]): TypeDef => ({
info: TypeDefInfo.Plain,
name,
type: type || 'Null'
}));
return value;
}
// decode a set of the form
// { _set: { A: 0b0001, B: 0b0010, C: 0b0100 } }
function _decodeSet (value: TypeDef, details: Record<string, number>): TypeDef {
value.info = TypeDefInfo.Set;
value.sub = Object.entries(details).map(([name, index]): TypeDef => ({
index,
info: TypeDefInfo.Plain,
name,
type: name
}));
return value;
}
export function getTypeDef (_type: Text | string, name?: string): TypeDef {
const type = _type.toString().trim();
const value: TypeDef = {
@@ -136,21 +175,9 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
const keys = Object.keys(parsed);
if (keys.length === 1 && keys[0] === '_enum') {
const details = parsed[keys[0]];
// not as pretty, but remain compatible with oo7 for both struct and Array types
value.sub = Array.isArray(details)
? details.map((name): TypeDef => ({
info: TypeDefInfo.Plain,
name,
type: 'Null'
}))
: Object.keys(details).map((name): TypeDef => ({
info: TypeDefInfo.Plain,
name,
type: details[name] || 'Null'
}));
value.info = TypeDefInfo.Enum;
_decodeEnum(value, parsed[keys[0]]);
} else if (keys.length === 1 && keys[0] === '_set') {
_decodeSet(value, parsed[keys[0]]);
} else {
value.info = TypeDefInfo.Struct;
value.sub = keys.map((name): TypeDef => getTypeDef(parsed[name], name));
@@ -214,40 +241,50 @@ export function getTypeClass<T extends Codec = Codec> (value: TypeDef, Fallback?
switch (value.info) {
case TypeDefInfo.Compact:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Compact');
return Compact.with(
getTypeClass<UInt>(value.sub as TypeDef)
) as unknown as Constructor<T>;
case TypeDefInfo.Enum:
assert(value.sub && Array.isArray(value.sub), 'Expected subtype for Enum');
return Enum.with(
getTypeClassMap(value.sub as TypeDef[])
) as unknown as Constructor<T>;
case TypeDefInfo.Option:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Option');
return Option.with(
getTypeClass(value.sub as TypeDef)
) as unknown as Constructor<T>;
case TypeDefInfo.Set:
assert(Array.isArray(value.sub), 'Expected nested info for Set');
return CodecSet.with(
(value.sub as TypeDef[]).reduce((result, { name, index }): Record<string, number> => {
result[name as string] = index as number;
return result;
}, {} as unknown as Record<string, number>)
) as unknown as Constructor<T>;
case TypeDefInfo.Struct:
assert(Array.isArray(value.sub), 'Expected nested subtypes for Struct');
return Struct.with(
getTypeClassMap(value.sub as TypeDef[])
) as unknown as Constructor<T>;
case TypeDefInfo.Tuple:
assert(Array.isArray(value.sub), 'Expected nested subtypes for Tuple');
return Tuple.with(
(value.sub as TypeDef[]).map((Type): Constructor<Codec> => getTypeClass(Type))
) as unknown as Constructor<T>;
case TypeDefInfo.Vector:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Vector');
return Vector.with(
getTypeClass<Codec>(value.sub as TypeDef)
) as unknown as Constructor<T>;
case TypeDefInfo.VectorFixed:
assert(value.ext, 'Expected length & type information for fixed vector');
@@ -258,16 +295,17 @@ export function getTypeClass<T extends Codec = Codec> (value: TypeDef, Fallback?
? U8aFixed.with((ext.length * 8) as U8aFixedBitLength)
: VectorFixed.with(createClass<Codec>(ext.type), ext.length)
) as unknown as Constructor<T>;
case TypeDefInfo.Linkage:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Linkage');
return Linkage.withKey(
getTypeClass<Codec>(value.sub as TypeDef)
) as unknown as Constructor<T>;
case TypeDefInfo.DoubleMap:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for DoubleMap');
return getTypeClass(value.sub as TypeDef);
case TypeDefInfo.Null:
return Null as unknown as Constructor<T>;
}
+11
View File
@@ -163,6 +163,16 @@ function _tsStructGetterType (structName: string | undefined, { info, sub, type
}
}
function tsSet ({ name: setName, sub }: TypeDef, imports: TypeImports): string {
setImports(imports, ['Set']);
const types = (sub as TypeDef[]).map(({ name }): string =>
createGetter(`is${name}`, 'boolean')
);
return createInterface(setName, 'Set', types.join(''));
}
function tsStruct ({ name: structName, sub }: TypeDef, imports: TypeImports): string {
const keys = (sub as TypeDef[]).map((typedef): string => {
const [embedType, returnType] = _tsStructGetterType(structName, typedef, imports);
@@ -237,6 +247,7 @@ function generateTsDef (srmlName: string, { types }: { types: Record<string, any
[TypeDefInfo.Null]: errorUnhandled,
[TypeDefInfo.Option]: tsOption,
[TypeDefInfo.Plain]: tsPlain,
[TypeDefInfo.Set]: tsSet,
[TypeDefInfo.Struct]: tsStruct,
[TypeDefInfo.Tuple]: tsTuple,
[TypeDefInfo.Vector]: tsVector,
@@ -4,15 +4,23 @@
export default {
types: {
VestingSchedule: {
offset: 'Balance',
perBlock: 'Balance'
},
WithdrawReasons: {
_set: {
TransactionPayment: 0b00000001,
Transfer: 0b00000010,
Reserve: 0b00000100,
Fee: 0b00001000
}
},
BalanceLock: {
id: 'LockIdentifier',
amount: 'Balance',
until: 'BlockNumber',
reasons: 'WithdrawReasons'
},
VestingSchedule: {
offset: 'Balance',
perBlock: 'Balance'
}
}
};
+2 -1
View File
@@ -3,8 +3,9 @@
import { Struct } from '../../codec';
import { Balance } from '../../primitive';
import { BlockNumber, WithdrawReasons } from '../../type';
import { BlockNumber } from '../../type';
import { LockIdentifier } from '../runtime/types';
import { WithdrawReasons } from '../staking/types';
export interface BalanceLock extends Struct {
readonly id: LockIdentifier;
@@ -6,9 +6,7 @@ export default {
types: {
EraIndex: 'u32',
EraRewards: {
// Total number of points. Equals the sum of reward points for each validator.
total: 'u32',
// Reward at one index correspond to reward for validator in current_elected of this index. This this reward vec is only valid for one elected set.
rewards: 'Vec<u32>'
},
IndividualExposure: {
@@ -22,11 +20,8 @@ export default {
},
RewardDestination: {
_enum: [
// Pay into the stash account, increasing the amount at stake accordingly.
'Staked',
// Pay into the stash account, not increasing the amount at stake.
'Stash',
// Pay into the controller account.
'Controller'
]
},
+8 -1
View File
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-empty-interface */
// Auto-generated via `yarn build:srmlTs`, do not edit
import { Compact, Enum, Struct, Vector } from '../../codec';
import { Compact, Enum, Set, Struct, Vector } from '../../codec';
import { AccountId, Balance, u32 } from '../../primitive';
export interface EraIndex extends u32 {}
@@ -41,3 +41,10 @@ export interface ValidatorPrefs extends Struct {
readonly unstakeThreshold: Compact<u32>;
readonly validatorPayment: Compact<Balance>;
}
export interface WithdrawReasons extends Set {
readonly isTransactionPayment: boolean;
readonly isTransfer: boolean;
readonly isReserve: boolean;
readonly isFee: boolean;
}
@@ -1,49 +0,0 @@
// Copyright 2017-2019 @polkadot/types 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 Set from '../codec/Set';
/**
* @name WithdrawReasons
* @description
* The Substrate WithdrawReasons for staking
*/
export default class WithdrawReasons extends Set {
public constructor (value: any = []) {
super({
TransactionPayment: 0b00000001,
Transfer: 0b00000010,
Reserve: 0b00000100,
Fee: 0b00001000
}, value);
}
/**
* @description In order to reserve some funds for a later return or repatriation
*/
public get isReserve (): boolean {
return this.strings.includes('Reserve');
}
/**
* @description In order to pay for (system) transaction costs
*/
public get isTransactionPayment (): boolean {
return this.strings.includes('TransactionPayment');
}
/**
* @description In order to transfer ownership
*/
public get isTransfer (): boolean {
return this.strings.includes('Transfer');
}
/**
* @description /// In order to pay some other (higher-level) fees.
*/
public get isFee (): boolean {
return this.strings.includes('Fee');
}
}
-1
View File
@@ -19,4 +19,3 @@ export { default as Perbill } from './Perbill';
export { default as StakingLedger } from './StakingLedger';
export { default as UnlockChunk } from './UnlockChunk';
export { default as Vote } from './Vote';
export { default as WithdrawReasons } from './WithdrawReasons';
+1 -1
View File
@@ -106,7 +106,7 @@ export type ConstructorDef<T = Codec> = Record<string, Constructor<T>>;
export type TypeDef = Record<string, Codec>;
export type RegistryTypes = Record<string, Constructor | string | Record<string, string> | { _enum: string[] | Record<string, string> }>;
export type RegistryTypes = Record<string, Constructor | string | Record<string, string> | { _enum: string[] | Record<string, string> } | { _set: Record<string, number> }>;
export interface RuntimeVersionInterface {
// eslint-disable-next-line @typescript-eslint/no-explicit-any