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:
@@ -30,7 +30,7 @@
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-codec#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.0.0",
|
||||
"@polkadot/util": "^0.30.4",
|
||||
"@polkadot/util-keyring": "^0.30.4"
|
||||
"@polkadot/util": "^0.30.7",
|
||||
"@polkadot/util-keyring": "^0.30.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,10 +114,12 @@ export default class Address extends Base<AccountId | AccountIndex> {
|
||||
return this.raw.toString();
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
return u8aConcat(
|
||||
Address.writeLength(this.raw.byteLength()),
|
||||
this.raw.toU8a()
|
||||
);
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return isBare
|
||||
? this.raw.toU8a(true)
|
||||
: u8aConcat(
|
||||
Address.writeLength(this.raw.byteLength()),
|
||||
this.raw.toU8a(isBare)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ export default class Bool extends Base<boolean> {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return new Uint8Array([this.raw ? 1 : 0]);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,9 +48,9 @@ export default class Bytes extends U8a {
|
||||
return this;
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
this._length.toU8a(),
|
||||
this._length.toU8a(isBare),
|
||||
this.raw
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AnyU8a } from './types';
|
||||
|
||||
import Option from './codec/Option';
|
||||
import Struct from './codec/Struct';
|
||||
import Tuple from './codec/Tuple';
|
||||
import StorageData from './StorageData';
|
||||
import StorageKey from './StorageKey';
|
||||
|
||||
@@ -41,8 +42,9 @@ export type KeyValueOptionValue = {
|
||||
};
|
||||
|
||||
// A key/value change. This is similar to the KeyValue structure,
|
||||
// however in this case the value could be optional.
|
||||
export class KeyValueOption extends Struct {
|
||||
// however in this case the value could be optional. Here it extends
|
||||
// from a Tuple, indicating the use inside areas such as StorageChangeSet
|
||||
export class KeyValueOption extends Tuple {
|
||||
constructor (value?: KeyValueOptionValue) {
|
||||
super({
|
||||
key: StorageKey,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,6 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { AnyNumber } from './types';
|
||||
|
||||
import Vector from './codec/Vector';
|
||||
import Base from './codec/Base';
|
||||
import Enum from './codec/Enum';
|
||||
@@ -17,12 +19,12 @@ import U16 from './U16';
|
||||
// end and work up. (Just so we don't use before definition)
|
||||
|
||||
export class EventMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
arguments: Vector.with(Type),
|
||||
documentation: Vector.with(Text)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get arguments (): Vector<Type> {
|
||||
@@ -39,11 +41,11 @@ export class EventMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class OuterEventMetadataEvent extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
events: Vector.with(EventMetadata)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get events (): Vector<EventMetadata> {
|
||||
@@ -56,11 +58,11 @@ export class OuterEventMetadataEvent extends Struct {
|
||||
}
|
||||
|
||||
export class OuterEventMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
events: Vector.with(OuterEventMetadataEvent)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get events (): Vector<OuterEventMetadataEvent> {
|
||||
@@ -73,11 +75,11 @@ export class OuterEventMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class FunctionArgumentMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
type: Type
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get name (): Text {
|
||||
@@ -90,13 +92,13 @@ export class FunctionArgumentMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class FunctionMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
id: U16,
|
||||
name: Text,
|
||||
arguments: Vector.with(FunctionArgumentMetadata),
|
||||
documentation: Vector.with(Text)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get arguments (): Vector<FunctionArgumentMetadata> {
|
||||
@@ -117,11 +119,11 @@ export class FunctionMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class CallMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
functions: Vector.with(FunctionMetadata)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get functions (): Vector<FunctionMetadata> {
|
||||
@@ -134,11 +136,11 @@ export class CallMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class ModuleMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
name: Text,
|
||||
call: CallMetadata
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get call (): CallMetadata {
|
||||
@@ -151,17 +153,17 @@ export class ModuleMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class StorageFunctionModifier extends Enum {
|
||||
constructor () {
|
||||
super(['None', 'Default', 'Required']);
|
||||
constructor (value?: any) {
|
||||
super(['None', 'Default', 'Required'], value);
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageFunctionType$Map extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
key: Type,
|
||||
value: Type
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get key (): Type {
|
||||
@@ -192,16 +194,29 @@ export class StorageFunctionType extends EnumType<Type | StorageFunctionType$Map
|
||||
get asType (): Type {
|
||||
return (this.raw as Base<Type>).raw;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this.isMap
|
||||
? this.asMap.value.toString()
|
||||
: this.asType.toString();
|
||||
}
|
||||
}
|
||||
|
||||
type StorageFunctionMetadataValue = {
|
||||
name?: string | Text,
|
||||
modifier?: StorageFunctionModifier | AnyNumber,
|
||||
type?: StorageFunctionType,
|
||||
documentation?: Vector<Text> | Array<string>
|
||||
};
|
||||
|
||||
export class StorageFunctionMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: StorageFunctionMetadataValue) {
|
||||
super({
|
||||
name: Text,
|
||||
modifier: StorageFunctionModifier,
|
||||
type: StorageFunctionType,
|
||||
documentation: Vector.with(Text)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get documentation (): Vector<Text> {
|
||||
@@ -222,11 +237,11 @@ export class StorageFunctionMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class StorageMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
prefix: Text,
|
||||
functions: Vector.with(StorageFunctionMetadata)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get functions (): Vector<StorageFunctionMetadata> {
|
||||
@@ -239,12 +254,12 @@ export class StorageMetadata extends Struct {
|
||||
}
|
||||
|
||||
export class RuntimeModuleMetadata extends Struct {
|
||||
constructor () {
|
||||
constructor (value?: any) {
|
||||
super({
|
||||
prefix: Text,
|
||||
module: ModuleMetadata,
|
||||
storage: Option.with(StorageMetadata)
|
||||
});
|
||||
}, value);
|
||||
}
|
||||
|
||||
get module (): ModuleMetadata {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import BN from 'bn.js';
|
||||
import bnToBn from '@polkadot/util/bn/toBn';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import isU8a from '@polkadot/util/is/u8a';
|
||||
import u8aToBn from '@polkadot/util/u8a/toBn';
|
||||
|
||||
import Base from './codec/Base';
|
||||
@@ -16,8 +17,7 @@ const BITLENGTH = 64;
|
||||
// per-second. For any encoding/decoding the 1000 multiplier would be applied to
|
||||
// get it in line with JavaScript formats
|
||||
export default class Moment extends Base<Date> {
|
||||
// NOTE
|
||||
constructor (value: Moment | Date | number = 0) {
|
||||
constructor (value: Uint8Array | Moment | Date | number = 0) {
|
||||
super(
|
||||
value instanceof Date
|
||||
? new Date(Math.ceil(value.getTime() / 1000) * 1000)
|
||||
@@ -25,12 +25,16 @@ export default class Moment extends Base<Date> {
|
||||
);
|
||||
}
|
||||
|
||||
static decode (value: Moment | number | BN): Date {
|
||||
return value instanceof Moment
|
||||
? value.raw
|
||||
: new Date(
|
||||
bnToBn(value).toNumber() * 1000
|
||||
);
|
||||
static decode (value: Uint8Array | Moment | number | BN): Date {
|
||||
if (value instanceof Moment) {
|
||||
return value.raw;
|
||||
} if (isU8a(value)) {
|
||||
value = u8aToBn(value, true);
|
||||
}
|
||||
|
||||
return new Date(
|
||||
bnToBn(value).toNumber() * 1000
|
||||
);
|
||||
}
|
||||
|
||||
byteLength (): number {
|
||||
@@ -55,7 +59,7 @@ export default class Moment extends Base<Date> {
|
||||
return this.toNumber();
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this.toNumber(), BITLENGTH, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,62 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Bytes from './Bytes';
|
||||
import { AnyU8a } from './types';
|
||||
|
||||
// A representation of a storage key (typically hashed) in the system
|
||||
export default class StorageKey extends Bytes {
|
||||
import isFunction from '@polkadot/util/is/function';
|
||||
import toU8a from '@polkadot/util/u8a/toU8a';
|
||||
|
||||
import U8a from './codec/U8a';
|
||||
import Bytes from './Bytes';
|
||||
import { StorageFunctionMetadata } from './Metadata';
|
||||
|
||||
export interface StorageFunction {
|
||||
(arg?: any): Uint8Array;
|
||||
meta: StorageFunctionMetadata;
|
||||
}
|
||||
|
||||
// A representation of a storage key (typically hashed) in the system. It can be constructed
|
||||
// by passing in a raw key or a StorageFunction with (optional) arguments.
|
||||
export default class StorageKey extends Bytes {
|
||||
private _outputType: string | null;
|
||||
|
||||
constructor (value: AnyU8a | StorageKey | StorageFunction | [StorageFunction, any]) {
|
||||
super(StorageKey.encode(value));
|
||||
|
||||
this._outputType = StorageKey.getType(value as StorageKey);
|
||||
}
|
||||
|
||||
static encode (value: AnyU8a | StorageKey | StorageFunction | [StorageFunction, any]): Uint8Array {
|
||||
if (value instanceof StorageKey || value instanceof U8a) {
|
||||
return value.raw;
|
||||
} else if (isFunction(value)) {
|
||||
return value();
|
||||
} else if (Array.isArray(value)) {
|
||||
const [fn, arg] = value;
|
||||
|
||||
if (isFunction(fn)) {
|
||||
return fn(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return toU8a(value);
|
||||
}
|
||||
|
||||
static getType (value: StorageKey | StorageFunction | [StorageFunction, any]): string | null {
|
||||
if (value instanceof StorageKey) {
|
||||
return value.outputType;
|
||||
} else if (isFunction(value)) {
|
||||
return value.meta.type.toString();
|
||||
} else if (Array.isArray(value)) {
|
||||
const [fn] = value;
|
||||
|
||||
return fn.meta.type.toString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
get outputType (): string | null {
|
||||
return this._outputType;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,14 +66,14 @@ export default class Text extends Base<string> {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
// NOTE Since we trim in the fromU8a, here we re-calculate the actual length
|
||||
const encoded = u8aFromUtf8(this.raw);
|
||||
|
||||
this._length.setValue(encoded.length);
|
||||
|
||||
return u8aConcat(
|
||||
this._length.toU8a(),
|
||||
this._length.toU8a(isBare),
|
||||
encoded
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ export default class Type extends Text {
|
||||
// Note Since we are mangling what we get in beyond recognition, we really should
|
||||
// not allow the re-encoding. Additionally, this is probably more of a decoder-only
|
||||
// helper, so treat it as such.
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
throw new Error('Type::toU8a: unimplemented');
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
export const l = logger('codec');
|
||||
|
||||
// The actual base class for any type. As it stands, this should not be used on it's own,
|
||||
// so we expose the interface, but throw on anything. This allows subclasses to actaully
|
||||
// only implement part (things that are unused/unexpected should just error-out)
|
||||
@@ -38,7 +42,7 @@ export default class Base <T = any> {
|
||||
throw new Error('Base::toString: unimplemented');
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
throw new Error('Base::toU8a: unimplemented');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ export default class Enum extends Base<number> {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return new Uint8Array([this.raw]);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export default class EnumType <T> extends Base<Base<T>> {
|
||||
private _index: number;
|
||||
private _indexes: Array<number>;
|
||||
|
||||
constructor (def: TypesDef, index?: number, value?: any) {
|
||||
constructor (def: TypesDef, index?: number | EnumType<T>, value?: any) {
|
||||
super(
|
||||
new (Object.values(def)[0])()
|
||||
);
|
||||
@@ -52,7 +52,14 @@ export default class EnumType <T> extends Base<Base<T>> {
|
||||
return this;
|
||||
}
|
||||
|
||||
setValue (index?: number, value?: any): void {
|
||||
setValue (index?: | EnumType<T> | number, value?: any): void {
|
||||
if (index instanceof EnumType) {
|
||||
this._index = index._index;
|
||||
this.raw = new this._Types[this._index](index.raw);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this._index = this._indexes.indexOf(index || 0);
|
||||
|
||||
if (this._index === -1) {
|
||||
|
||||
@@ -95,8 +95,10 @@ export default class Length extends Base<BN> {
|
||||
return this.raw.toNumber();
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
return Length.encode(this.raw);
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return isBare
|
||||
? new Uint8Array()
|
||||
: Length.encode(this.raw);
|
||||
}
|
||||
|
||||
setValue (value: BN | number): void {
|
||||
|
||||
@@ -73,7 +73,11 @@ export default class Option <T> extends Base<Base<T>> {
|
||||
: this.raw.toJSON();
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
if (isBare) {
|
||||
return this.raw.toU8a(true);
|
||||
}
|
||||
|
||||
const u8a = new Uint8Array(this.byteLength());
|
||||
|
||||
if (!this._isEmpty) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
|
||||
import Base from './Base';
|
||||
import Base, { l } from './Base';
|
||||
|
||||
// A Struct defines an Object with key/values - where the values are Base<T> values. It removes
|
||||
// a lot of repetition from the actual coding, define a structure type, pass it the key/Base<T>
|
||||
@@ -24,19 +24,9 @@ export default class Struct <
|
||||
protected _jsonMap: Map<keyof S, string>;
|
||||
protected _Types: E;
|
||||
|
||||
constructor (Types: S, value: V = {} as V, jsonMap: Map<keyof S, string> = new Map()) {
|
||||
constructor (Types: S, value: V | Array<any> = {} as V, jsonMap: Map<keyof S, string> = new Map(), isTuple: boolean = false) {
|
||||
super(
|
||||
Object
|
||||
.keys(Types)
|
||||
.reduce((raw: T, key) => {
|
||||
// @ts-ignore FIXME Ok, something weird is going on here or I just don't get it...
|
||||
// it works, so ignore the checker, although it drives me batty. (It started when
|
||||
// the [key in keyof T] was added, the idea is to provide better checks, which
|
||||
// does backfire here, but works externally.)
|
||||
raw[key] = new Types[key](value[key]);
|
||||
|
||||
return raw;
|
||||
}, {} as T)
|
||||
Struct.decode(Types, value, isTuple)
|
||||
);
|
||||
|
||||
this._jsonMap = jsonMap;
|
||||
@@ -50,6 +40,27 @@ export default class Struct <
|
||||
}, {} as E);
|
||||
}
|
||||
|
||||
static decode <S, V, T> (Types: S, value: V | Array<any>, isTuple: boolean): T {
|
||||
l.debug(() => ['Struct.decode', { Types, value }]);
|
||||
|
||||
return Object
|
||||
.keys(Types)
|
||||
.reduce((raw: T, key, index) => {
|
||||
// @ts-ignore FIXME Ok, something weird is going on here or I just don't get it...
|
||||
// it works, so ignore the checker, although it drives me batty. (It started when
|
||||
// the [key in keyof T] was added, the idea is to provide better checks, which
|
||||
// does backfire here, but works externally.)
|
||||
raw[key] = new Types[key](
|
||||
isTuple && Array.isArray(value)
|
||||
? value[index]
|
||||
// @ts-ignore as above
|
||||
: value[key]
|
||||
);
|
||||
|
||||
return raw;
|
||||
}, {} as T);
|
||||
}
|
||||
|
||||
static with <
|
||||
S = { [index: string]: { new(value?: any): Base } }
|
||||
> (Types: S): { new(value?: any): Struct<S> } {
|
||||
@@ -106,10 +117,10 @@ export default class Struct <
|
||||
return Object.keys(this.raw);
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
...Object.values(this.raw).map((entry) =>
|
||||
entry.toU8a()
|
||||
entry.toU8a(isBare)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,10 +9,15 @@ import Struct from './Struct';
|
||||
// is a specialization of the Struct type where the toJSON/fromJSON operates on Array structures,
|
||||
// while the U8a encoding is handled in the same way as a Struct
|
||||
export default class Tuple <
|
||||
// S & T definitions maps to what we have in Struct (naming expanded there)
|
||||
// S & T definitions maps to what we have in Struct (naming documented there)
|
||||
S = { [index: string]: { new(value?: any): Base } },
|
||||
T = { [K in keyof S]: Base }
|
||||
> extends Struct<S, T> {
|
||||
T = { [K in keyof S]: Base },
|
||||
V = { [K in keyof S]: any }
|
||||
> extends Struct<S, T, V> {
|
||||
constructor (Types: S, value?: V | Array<any>, jsonMap?: Map<keyof S, string>) {
|
||||
super(Types, value, jsonMap, true);
|
||||
}
|
||||
|
||||
static with <
|
||||
S = { [index: string]: { new(value?: any): Base } }
|
||||
> (Types: S): { new(value?: any): Tuple<S> } {
|
||||
@@ -23,7 +28,7 @@ export default class Tuple <
|
||||
};
|
||||
}
|
||||
|
||||
fromJSON (input: any): Tuple<S, T> {
|
||||
fromJSON (input: any): Tuple<S, T, V> {
|
||||
Object.values(this.raw).forEach((entry, index) => {
|
||||
entry.fromJSON(input[index]);
|
||||
});
|
||||
|
||||
@@ -50,7 +50,7 @@ export default class U8a extends Base<Uint8Array> {
|
||||
return this.toHex();
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { AnyNumber } from '../types';
|
||||
import BN from 'bn.js';
|
||||
import isHex from '@polkadot/util/is/hex';
|
||||
import isString from '@polkadot/util/is/string';
|
||||
import isU8a from '@polkadot/util/is/u8a';
|
||||
import bnToBn from '@polkadot/util/bn/toBn';
|
||||
import bnToHex from '@polkadot/util/bn/toHex';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
@@ -39,6 +40,9 @@ export default class UInt extends Base<BN> {
|
||||
return value.raw;
|
||||
} else if (isHex(value)) {
|
||||
return hexToBn(value as string);
|
||||
} else if (isU8a(value)) {
|
||||
// NOTE When passing u8a in (typically from decoded data), it is always u8a
|
||||
return u8aToBn(value, true);
|
||||
} else if (isString(value)) {
|
||||
return new BN(value, 10);
|
||||
}
|
||||
@@ -70,7 +74,7 @@ export default class UInt extends Base<BN> {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return bnToU8a(this.raw, this._bitLength, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,11 +53,15 @@ export default class Vector <
|
||||
}, this._length.byteLength());
|
||||
}
|
||||
|
||||
filter (fn: (entry: T, index?: number) => any): Array<T> {
|
||||
filter (fn: (item: T, index?: number) => any): Array<T> {
|
||||
return this.raw.filter(fn);
|
||||
}
|
||||
|
||||
forEach (fn: (entry: T, index?: number) => any): any {
|
||||
find (fn: (item: T, index?: number) => any): T | undefined {
|
||||
return this.raw.find(fn);
|
||||
}
|
||||
|
||||
forEach (fn: (item: T, index?: number) => any): any {
|
||||
return this.raw.forEach(fn);
|
||||
}
|
||||
|
||||
@@ -90,11 +94,16 @@ export default class Vector <
|
||||
return this.raw[index];
|
||||
}
|
||||
|
||||
map <O> (fn: (entry: T, index?: number) => O): Array<O> {
|
||||
map <O> (fn: (item: T, index?: number) => O): Array<O> {
|
||||
return this.raw.map(fn);
|
||||
}
|
||||
|
||||
reduce <O> (fn: (result: O, entry: T, index?: number) => O, initial: O): O {
|
||||
push (item: T): void {
|
||||
this.raw.push(item);
|
||||
this._length.setValue(this.raw.length);
|
||||
}
|
||||
|
||||
reduce <O> (fn: (result: O, item: T, index?: number) => O, initial: O): O {
|
||||
return this.raw.reduce(fn, initial);
|
||||
}
|
||||
|
||||
@@ -104,11 +113,11 @@ export default class Vector <
|
||||
);
|
||||
}
|
||||
|
||||
toU8a (): Uint8Array {
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return u8aConcat(
|
||||
this._length.toU8a(),
|
||||
this._length.toU8a(isBare),
|
||||
...this.raw.map((entry) =>
|
||||
entry.toU8a()
|
||||
entry.toU8a(isBare)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2017-2018 @polkadot/api-codec authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { typeSplit, getType, getTupleType, getVectorType } from './createType';
|
||||
|
||||
describe('typeSplit', () => {
|
||||
it('splits simple types into an array', () => {
|
||||
expect(
|
||||
typeSplit('Text, u32, u64')
|
||||
).toEqual(['Text', 'u32', 'u64']);
|
||||
});
|
||||
|
||||
it('splits nested combinations', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32), Vec<u64>')
|
||||
).toEqual(['Text', '(u32)', 'Vec<u64>']);
|
||||
});
|
||||
|
||||
it('keeps nested tuples together', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32, u128), Vec<u64>')
|
||||
).toEqual(['Text', '(u32, u128)', 'Vec<u64>']);
|
||||
});
|
||||
|
||||
it('keeps nested vector tuples together', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32, u128), Vec<(u64, u32)>')
|
||||
).toEqual(['Text', '(u32, u128)', 'Vec<(u64, u32)>']);
|
||||
});
|
||||
|
||||
it('allows for deep nesting', () => {
|
||||
expect(
|
||||
typeSplit('Text, (u32, (u128, u8)), Vec<(u64, (u32, u32))>')
|
||||
).toEqual(['Text', '(u32, (u128, u8))', 'Vec<(u64, (u32, u32))>']);
|
||||
});
|
||||
|
||||
it('checks for unclosed vec', () => {
|
||||
expect(
|
||||
() => typeSplit('Text, Vec<u64')
|
||||
).toThrow(/Invalid Vector/);
|
||||
});
|
||||
|
||||
it('checks for unclosed tuple', () => {
|
||||
expect(
|
||||
() => typeSplit('Text, (u64, u32')
|
||||
).toThrow(/Invalid Tuple/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTupleType', () => {
|
||||
it('does not allow invalid tuples, end )', () => {
|
||||
expect(
|
||||
() => getTupleType('(u64, u32')
|
||||
).toThrow(/tuple wrapped/);
|
||||
});
|
||||
|
||||
it('does not allow invalid tuples, start (', () => {
|
||||
expect(
|
||||
() => getTupleType('u64, u32)')
|
||||
).toThrow(/tuple wrapped/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getVectorType', () => {
|
||||
it('does not allow invalid vectors, end >', () => {
|
||||
expect(
|
||||
() => getVectorType('Vec<u64')
|
||||
).toThrow(/Vec wrapped/);
|
||||
});
|
||||
|
||||
it('does not allow invalid vectors, start Vec<', () => {
|
||||
expect(
|
||||
() => getVectorType('u64>')
|
||||
).toThrow(/Vec wrapped/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getType', () => {
|
||||
it('does not allow invalid types', () => {
|
||||
expect(
|
||||
() => getType('SomethingInvalid')
|
||||
).toThrow(/determine type/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// Copyright 2017-2018 @polkadot/api-codec authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import assert from '@polkadot/util/assert';
|
||||
|
||||
import * as Types from '../index';
|
||||
import Base, { l } from './Base';
|
||||
import Tuple from './Tuple';
|
||||
import Vector from './Vector';
|
||||
|
||||
type Constructor = { new (value?: any): Base };
|
||||
|
||||
// safely split a string on ', ' while taking care of any nested occurences
|
||||
export function typeSplit (type: string): Array<string> {
|
||||
let tDepth = 0;
|
||||
let vDepth = 0;
|
||||
let start = 0;
|
||||
const result = [];
|
||||
|
||||
for (let index = 0; index < type.length; index++) {
|
||||
switch (type[index]) {
|
||||
case ',':
|
||||
// we are not nested, add the type
|
||||
if (tDepth === 0 && vDepth === 0) {
|
||||
result.push(type.substr(start, index - start).trim());
|
||||
start = index + 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case '(':
|
||||
// inc tuple depth
|
||||
tDepth++;
|
||||
break;
|
||||
|
||||
case ')':
|
||||
// dec tuple depth
|
||||
tDepth--;
|
||||
break;
|
||||
|
||||
case '<':
|
||||
// inc vec depth
|
||||
vDepth++;
|
||||
break;
|
||||
|
||||
case '>':
|
||||
// dec tuple depth
|
||||
vDepth--;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert(tDepth === 0, `Invalid Tuple in ${type}`);
|
||||
assert(vDepth === 0, `Invalid Vector in ${type}`);
|
||||
|
||||
// the final leg of the journey
|
||||
result.push(type.substr(start, type.length - start).trim());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Handle Vector types, i.e Vec<AccountId> or Vec<(AccountId, Balance)>
|
||||
export function getVectorType (type: string): Constructor {
|
||||
l.debug(() => ['getVectorType', { type }]);
|
||||
|
||||
assert(type.substr(0, 4) === 'Vec<' && type[type.length - 1] === '>', `Expected Vec wrapped with <>`);
|
||||
|
||||
// strip wrapping Vec<>
|
||||
const subType = type.substr(4, type.length - 5);
|
||||
|
||||
return Vector.with(
|
||||
getType(subType)
|
||||
);
|
||||
}
|
||||
|
||||
// Handle tuple types, (u32, String, AccountId). It could be nested and wrapped in other
|
||||
// types, i.e. (u32, Vec<(AccountId, Balance)>)
|
||||
export function getTupleType (type: string): Constructor {
|
||||
l.debug(() => ['getTupleType', { type }]);
|
||||
|
||||
assert(type[0] === '(' && type[type.length - 1] === ')', `Expected tuple wrapped with ()`);
|
||||
|
||||
// strip wrapping ()'s
|
||||
const innerTypes = typeSplit(type.substr(1, type.length - 2));
|
||||
|
||||
return Tuple.with(
|
||||
innerTypes.reduce((result, type, index) => {
|
||||
result[`entry${index}`] = getType(type);
|
||||
|
||||
return result;
|
||||
}, {} as { [index: string]: Constructor })
|
||||
);
|
||||
}
|
||||
|
||||
// Returns the type Class for construction
|
||||
export function getType (_type: string): Constructor {
|
||||
const type = _type.trim();
|
||||
|
||||
l.debug(() => ['getType', { type }]);
|
||||
|
||||
if (type[0] === '(') {
|
||||
return getTupleType(type);
|
||||
} else if (type.substr(0, 4) === 'Vec<') {
|
||||
return getVectorType(type);
|
||||
}
|
||||
|
||||
const Type = (Types as any)[type];
|
||||
|
||||
assert(Type, `Unable to determine type from '${type}'`);
|
||||
|
||||
return Type;
|
||||
}
|
||||
|
||||
export default function createType (type: string, value?: any): Base {
|
||||
l.debug(() => ['createType', { type, value }]);
|
||||
|
||||
const Type = getType(type);
|
||||
|
||||
return new Type(value);
|
||||
}
|
||||
@@ -11,3 +11,5 @@ export { default as Base } from './Base';
|
||||
export { default as Struct } from './Struct';
|
||||
export { default as Tuple } from './Tuple';
|
||||
export { default as Vector } from './Vector';
|
||||
|
||||
export { default as createType } from './createType';
|
||||
|
||||
@@ -52,12 +52,13 @@ export { default as StorageKey } from './StorageKey';
|
||||
export { default as Text } from './Text';
|
||||
// NOTE Type is currently only used internally (possibly in codec-related work)
|
||||
// export { default as Type } from './Type';
|
||||
export { default as U8 } from './U8';
|
||||
export { default as U16 } from './U16';
|
||||
export { default as U32 } from './U32';
|
||||
export { default as U64 } from './U64';
|
||||
export { default as U128 } from './U128';
|
||||
export { default as U256 } from './U256';
|
||||
// NOTE We are exporting the U* classes as lowercase, matching with Rust
|
||||
export { default as u8 } from './U8';
|
||||
export { default as u16 } from './U16';
|
||||
export { default as u32 } from './U32';
|
||||
export { default as u64 } from './U64';
|
||||
export { default as u128 } from './U128';
|
||||
export { default as u256 } from './U256';
|
||||
export { default as ValidatorPrefs } from './ValidatorPrefs';
|
||||
export { default as VoteThreshold } from './VoteThreshold';
|
||||
export { default as VoteIndex } from './VoteIndex';
|
||||
|
||||
Vendored
+1
-1
@@ -7,6 +7,6 @@ import BN from 'bn.js';
|
||||
import U8a from './codec/U8a';
|
||||
import UInt from './codec/UInt';
|
||||
|
||||
export type AnyNumber = UInt | BN | number | string;
|
||||
export type AnyNumber = UInt | BN | Uint8Array | number | string;
|
||||
|
||||
export type AnyU8a = U8a | Uint8Array | Array<number> | string;
|
||||
|
||||
Reference in New Issue
Block a user