Simplify Base (#403)
* Convert Base to a wrapper * Remove isEmpty * Fix bug with storage * Fix lint * Fix imports * Protected raw * Remove useless imports * Remove test for Base * Use unwrap on Option * Storage unwrap * Use isNone * Add test for accessing values * Remove comment * toU8a always return Uint8Array
This commit is contained in:
@@ -8,7 +8,7 @@ import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import Rpc from '@polkadot/rpc-core/index';
|
||||
import { Extrinsics, ExtrinsicFunction } from '@polkadot/extrinsics/types';
|
||||
import { Storage } from '@polkadot/storage/types';
|
||||
import { Base } from '@polkadot/types/codec';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { StorageFunction } from '@polkadot/types/StorageKey';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
@@ -226,14 +226,14 @@ export default class ApiPromise extends ApiBase<Rpc, QueryableStorage, Submittab
|
||||
}
|
||||
|
||||
private decorateStorageEntry (method: StorageFunction): QueryableStorageFunction {
|
||||
const decorated: any = (...args: Array<any>): Promise<Base | null | undefined> => {
|
||||
const decorated: any = (...args: Array<any>): Promise<Codec | null | undefined> => {
|
||||
if (args.length === 0 || !isFunction(args[args.length - 1])) {
|
||||
return this.rpc.state.getStorage([method, args[0]]);
|
||||
}
|
||||
|
||||
return this.rpc.state.subscribeStorage(
|
||||
[[method, args.length === 1 ? undefined : args[0]]],
|
||||
(result: Array<Base | null | undefined> = []) =>
|
||||
(result: Array<Codec | null | undefined> = []) =>
|
||||
args[args.length - 1](result[0])
|
||||
);
|
||||
};
|
||||
|
||||
@@ -11,7 +11,7 @@ import Rpc from '@polkadot/rpc-core/index';
|
||||
import RpcRx from '@polkadot/rpc-rx/index';
|
||||
import { Extrinsics, ExtrinsicFunction } from '@polkadot/extrinsics/types';
|
||||
import { Storage } from '@polkadot/storage/types';
|
||||
import { Base } from '@polkadot/types/codec';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { logger } from '@polkadot/util';
|
||||
|
||||
import ApiBase from '../Base';
|
||||
@@ -227,7 +227,7 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE
|
||||
}
|
||||
|
||||
private decorateStorageEntry (method: StorageFunction): QueryableStorageFunction {
|
||||
const decorated: any = (arg: any): Observable<Base | null | undefined> => {
|
||||
const decorated: any = (arg: any): Observable<Codec | null | undefined> => {
|
||||
let observable;
|
||||
|
||||
try {
|
||||
@@ -242,7 +242,7 @@ export default class ApiRx extends ApiBase<RpcRx, QueryableStorage, SubmittableE
|
||||
// a single entry, we pull that from the array and return it as-is
|
||||
return observable.pipe(
|
||||
defaultIfEmpty([]),
|
||||
map((result: Array<Base | null | undefined> = []): Base | null | undefined =>
|
||||
map((result: Array<Codec | null | undefined> = []): Codec | null | undefined =>
|
||||
result[0]
|
||||
)
|
||||
);
|
||||
|
||||
@@ -8,7 +8,8 @@ import { RpcInterface, RpcInterface$Section, RpcInterface$Section$Method } from
|
||||
|
||||
import interfaces from '@polkadot/jsonrpc/index';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { Base, Vector, createType } from '@polkadot/types/codec';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Vector, createType } from '@polkadot/types/codec';
|
||||
import { StorageChangeSet, StorageKey } from '@polkadot/types/index';
|
||||
import { ExtError, assert, isFunction } from '@polkadot/util';
|
||||
|
||||
@@ -161,7 +162,7 @@ export default class Rpc implements RpcInterface {
|
||||
return call;
|
||||
}
|
||||
|
||||
private formatInputs (method: RpcMethod, inputs: Array<any>): Array<Base> {
|
||||
private formatInputs (method: RpcMethod, inputs: Array<any>): Array<Codec> {
|
||||
const reqArgCount = method.params.filter(({ isOptional }) => !isOptional).length;
|
||||
const optText = reqArgCount === method.params.length
|
||||
? ''
|
||||
@@ -174,7 +175,7 @@ export default class Rpc implements RpcInterface {
|
||||
);
|
||||
}
|
||||
|
||||
private formatOutput (method: RpcMethod, params: Array<Base>, result?: any): Base | Array<Base | null | undefined> {
|
||||
private formatOutput (method: RpcMethod, params: Array<Codec>, result?: any): Codec | Array<Codec | null | undefined> {
|
||||
const base = createType(method.type as string, result);
|
||||
|
||||
if (method.type === 'StorageData') {
|
||||
@@ -205,14 +206,14 @@ export default class Rpc implements RpcInterface {
|
||||
!item
|
||||
? undefined
|
||||
: (
|
||||
item.value.isEmpty
|
||||
item.value.isNone
|
||||
? null
|
||||
: createType(type, item.value.value)
|
||||
)
|
||||
);
|
||||
|
||||
return result;
|
||||
}, [] as Array<Base | null | undefined>);
|
||||
}, [] as Array<Codec | null | undefined>);
|
||||
}
|
||||
|
||||
return base;
|
||||
|
||||
@@ -10,7 +10,7 @@ import EventEmitter from 'eventemitter3';
|
||||
import interfaces from '@polkadot/jsonrpc/index';
|
||||
import testKeyring from '@polkadot/keyring/testing';
|
||||
import storage from '@polkadot/storage/static';
|
||||
import { Base } from '@polkadot/types/codec';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Header } from '@polkadot/types/index';
|
||||
import { bnToU8a, logger, u8aToHex } from '@polkadot/util';
|
||||
import { randomAsU8a } from '@polkadot/util-crypto';
|
||||
@@ -174,7 +174,7 @@ export default class Mock implements ProviderInterface {
|
||||
this.db[u8aToHex(key)] = bnToU8a(value, 64, true);
|
||||
}
|
||||
|
||||
private updateSubs (method: string, value: Base<any>) {
|
||||
private updateSubs (method: string, value: Codec) {
|
||||
this.subscriptions[method].lastValue = value;
|
||||
|
||||
Object
|
||||
|
||||
@@ -25,14 +25,14 @@ export default function fromMetadata (metadata: Metadata): Storage {
|
||||
}, {} as Storage);
|
||||
|
||||
return metadata.modules.reduce((result, moduleMetadata) => {
|
||||
if (!moduleMetadata.storage) {
|
||||
if (moduleMetadata.storage.isNone) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const prefix = moduleMetadata.storage.prefix;
|
||||
const prefix = moduleMetadata.storage.unwrap().prefix;
|
||||
|
||||
// For access, we change the index names, i.e. Balances.FreeBalance -> balances.freeBalance
|
||||
result[stringLowerFirst(prefix.toString())] = moduleMetadata.storage.functions.reduce((newModule, func) => {
|
||||
result[stringLowerFirst(prefix.toString())] = moduleMetadata.storage.unwrap().functions.reduce((newModule, func) => {
|
||||
newModule[stringLowerFirst(func.name.toString())] = createFunction(prefix, func.name, func);
|
||||
|
||||
return newModule;
|
||||
|
||||
@@ -7,14 +7,10 @@ import { isU8a, u8aToHex } from '@polkadot/util';
|
||||
import { Codec } from './types';
|
||||
|
||||
export default class Bool extends Boolean implements Codec {
|
||||
public raw: Boolean; // FIXME Remove this once we convert all types out of Base
|
||||
|
||||
constructor (value: Bool | Boolean | Uint8Array | boolean | number = false) {
|
||||
super(
|
||||
Bool.decodeBool(value)
|
||||
);
|
||||
|
||||
this.raw = this;
|
||||
}
|
||||
|
||||
private static decodeBool (value: any): boolean {
|
||||
|
||||
@@ -46,7 +46,7 @@ export default class Bytes extends U8a {
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
return isBare
|
||||
? this
|
||||
? super.toU8a(isBare)
|
||||
: u8aConcat(
|
||||
Compact.encodeU8a(this.length, DEFAULT_LENGTH_BITS),
|
||||
this
|
||||
|
||||
@@ -3,12 +3,11 @@
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { KeyringPair } from '@polkadot/keyring/types';
|
||||
import { AnyNumber, AnyU8a } from './types';
|
||||
import { AnyNumber, AnyU8a, Codec } from './types';
|
||||
|
||||
import { hexToU8a, isHex, isU8a, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { blake2AsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import Base from './codec/Base';
|
||||
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
|
||||
import Struct from './codec/Struct';
|
||||
import ExtrinsicSignature from './ExtrinsicSignature';
|
||||
@@ -42,8 +41,6 @@ export default class Extrinsic extends Struct {
|
||||
static decodeExtrinsic (value?: ExtrinsicValue | AnyU8a): object | Uint8Array {
|
||||
if (!value) {
|
||||
return {};
|
||||
} else if (value instanceof Extrinsic) {
|
||||
return value.raw;
|
||||
} else if (isHex(value)) {
|
||||
// FIXME We manually add the length prefix for hex for now
|
||||
// https://github.com/paritytech/substrate/issues/889
|
||||
@@ -67,7 +64,7 @@ export default class Extrinsic extends Struct {
|
||||
}
|
||||
|
||||
// expose args so it is compatible with Method (as constructor value)
|
||||
get args (): Array<Base> {
|
||||
get args (): Array<Codec> {
|
||||
return this.method.args;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,8 +46,6 @@ export default class ExtrinsicSignature extends Struct {
|
||||
static decodeExtrinsicSignature (value: ExtrinsicSignature | ExtrinsicSignatureValue | AnyU8a | undefined): object | Uint8Array {
|
||||
if (!value) {
|
||||
return {};
|
||||
} else if (value instanceof Struct) {
|
||||
return value.raw;
|
||||
} else if (isU8a(value)) {
|
||||
const version = value[0];
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ export default class Header extends Struct {
|
||||
}
|
||||
|
||||
get blockNumber (): BlockNumber {
|
||||
return (this.get('number') as Compact).raw as BlockNumber;
|
||||
return (this.get('number') as Compact).toBn() as BlockNumber;
|
||||
}
|
||||
|
||||
get digest (): Digest {
|
||||
|
||||
@@ -55,6 +55,6 @@ describe('KeyValueOption', () => {
|
||||
});
|
||||
|
||||
expect(kv.key.toHex()).toEqual('0x11223344');
|
||||
expect(kv.value.isEmpty).toEqual(true);
|
||||
expect(kv.value.isNone).toEqual(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,6 @@ import { AnyNumber } from './types';
|
||||
|
||||
import { hexToU8a, isHex, isU8a } from '@polkadot/util';
|
||||
|
||||
import Base from './codec/Base';
|
||||
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
|
||||
import Enum from './codec/Enum';
|
||||
import EnumType from './codec/EnumType';
|
||||
@@ -231,11 +230,11 @@ export class StorageFunctionType extends EnumType<Type | StorageFunctionType$Map
|
||||
}
|
||||
|
||||
get asMap (): StorageFunctionType$Map {
|
||||
return (this.raw as Base<StorageFunctionType$Map>).raw;
|
||||
return this.value as StorageFunctionType$Map;
|
||||
}
|
||||
|
||||
get asType (): Type {
|
||||
return (this.raw as Base<Type>).raw;
|
||||
return this.value as Type;
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
@@ -313,12 +312,8 @@ export class RuntimeModuleMetadata extends Struct {
|
||||
return this.get('prefix') as Text;
|
||||
}
|
||||
|
||||
get storage (): StorageMetadata | undefined {
|
||||
const value = (this.get('storage') as Option<StorageMetadata>).value;
|
||||
|
||||
return value
|
||||
? value.raw
|
||||
: value;
|
||||
get storage (): Option<StorageMetadata> {
|
||||
return this.get('storage') as Option<StorageMetadata>;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,15 +387,17 @@ export default class RuntimeMetadata extends Struct {
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const storages = this.modules.map((module) =>
|
||||
module.storage
|
||||
? module.storage.functions.map((fn) =>
|
||||
module.storage.isSome
|
||||
? module.storage.unwrap().functions.map((fn) =>
|
||||
fn.type.isMap
|
||||
? [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()]
|
||||
: [fn.type.asType.toString()]
|
||||
)
|
||||
: []
|
||||
);
|
||||
|
||||
const args = this.modules.map((module) =>
|
||||
module.module.call.functions.map((fn) =>
|
||||
fn.arguments.map((argument) =>
|
||||
|
||||
@@ -5,8 +5,7 @@
|
||||
import { ExtrinsicFunction, Extrinsics } from '@polkadot/extrinsics/types';
|
||||
import { assert, isHex, isObject, isU8a } from '@polkadot/util';
|
||||
|
||||
import Base from './codec/Base';
|
||||
import { AnyU8a, Constructor } from './types';
|
||||
import { AnyU8a, Codec, Constructor } from './types';
|
||||
import { FunctionMetadata, FunctionArgumentMetadata } from './Metadata';
|
||||
import { getTypeDef, getTypeClass } from './codec/createType';
|
||||
import Struct from './codec/Struct';
|
||||
@@ -18,7 +17,7 @@ const FN_UNKNOWN = {
|
||||
} as ExtrinsicFunction;
|
||||
|
||||
interface ArgsDef {
|
||||
[index: string]: Constructor<Base>;
|
||||
[index: string]: Constructor;
|
||||
}
|
||||
|
||||
interface DecodeMethodInput {
|
||||
@@ -166,7 +165,7 @@ export default class Method extends Struct {
|
||||
);
|
||||
}
|
||||
|
||||
get args (): Array<Base> {
|
||||
get args (): Array<Codec> {
|
||||
// FIXME This should return a Struct instead of an Array
|
||||
return [...(this.get('args') as Struct).values()];
|
||||
}
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './codec/Base';
|
||||
import { Codec } from './types';
|
||||
|
||||
// Implements a type that does not contain anything (apart from `null`)
|
||||
export default class Null extends Base<null> {
|
||||
constructor () {
|
||||
super(null);
|
||||
}
|
||||
|
||||
export default class Null implements Codec {
|
||||
get encodedLength (): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return '0x';
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2,13 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Base from './codec/Base';
|
||||
|
||||
// Where Origin occurs, it should be ignored, so it should never actually be constructed
|
||||
export default class Origin extends Base {
|
||||
export default class Origin {
|
||||
constructor () {
|
||||
super();
|
||||
|
||||
throw new Error('Origin should not be constructed, it is only a placeholder for compatibility');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,13 +16,10 @@ import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
|
||||
// wraps the `Balance`, `T::AccountId`, etc. The reasoning - with a "TypeString"
|
||||
// we can nicely strip types down like "T::AcountId" -> "AccountId"
|
||||
export default class Text extends String implements Codec {
|
||||
public raw: String; // FIXME Remove this once we convert all types out of Base
|
||||
constructor (value: Text | string | AnyU8a | { toString: () => string } = '') {
|
||||
super(
|
||||
Text.decodeText(value)
|
||||
);
|
||||
|
||||
this.raw = this;
|
||||
}
|
||||
|
||||
private static decodeText (value: Text | string | AnyU8a | { toString: () => string }): string {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
// 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 Base from './Base';
|
||||
|
||||
describe('Base', () => {
|
||||
it('has the contructor value on raw', () => {
|
||||
expect(new Base('foo-bar').raw).toEqual('foo-bar');
|
||||
});
|
||||
|
||||
['encodedLength', 'toJSON', 'toString', 'toU8a'].forEach((method) => {
|
||||
it(`has abstract (?) impl for ${method}`, () => {
|
||||
expect(
|
||||
() => new Base()[method]()
|
||||
).toThrow(/unimplemented/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,39 +2,13 @@
|
||||
// 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';
|
||||
|
||||
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)
|
||||
//
|
||||
// TODO
|
||||
// - This could probably be abstract, as long as we have the functions abstract as well
|
||||
// - Not convinced about abstratc - there are a number of extensions to this class that
|
||||
// don't provide some implementations (e.g. Length, good example and should not be
|
||||
// used-as-is). In those case it just relies in the throw in here.
|
||||
/**
|
||||
* A type extends the Base class, when it holds a value
|
||||
*/
|
||||
export default class Base<T = any> {
|
||||
raw: T;
|
||||
protected raw: T;
|
||||
|
||||
constructor (value?: any) {
|
||||
this.raw = value;
|
||||
}
|
||||
|
||||
get encodedLength (): number {
|
||||
throw new Error('Base::encodedLength: unimplemented');
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
throw new Error('Base::toJSON: unimplemented');
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
throw new Error('Base::toString: unimplemented');
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
throw new Error('Base::toU8a: unimplemented');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import BN from 'bn.js';
|
||||
import { bnToBn, bnToU8a, hexToBn, isBn, isHex, isNumber, isString, isU8a, u8aToBn, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { AnyNumber, Constructor } from '../types';
|
||||
import { AnyNumber, Codec, Constructor } from '../types';
|
||||
import Base from './Base';
|
||||
import UInt, { UIntBitLength } from './UInt';
|
||||
import Moment from '../Moment';
|
||||
@@ -31,7 +31,7 @@ const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1);
|
||||
// nn nn nn 11 [ / zz zz zz zz ]{4 + n}
|
||||
//
|
||||
// Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key.
|
||||
export default class Compact extends Base<UInt | Moment> {
|
||||
export default class Compact extends Base<UInt | Moment> implements Codec {
|
||||
constructor (Type: Constructor<UInt | Moment>, value: AnyNumber = 0) {
|
||||
super(Compact.decodeCompact(Type, value));
|
||||
}
|
||||
@@ -126,7 +126,7 @@ export default class Compact extends Base<UInt | Moment> {
|
||||
return this.toU8a().length;
|
||||
}
|
||||
|
||||
toBn (): any {
|
||||
toBn (): BN {
|
||||
return this.raw.toBn();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { isU8a } from '@polkadot/util';
|
||||
import { isU8a, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { Codec } from '../types';
|
||||
import Base from './Base';
|
||||
|
||||
type EnumDef = {
|
||||
@@ -17,7 +18,7 @@ type EnumDef = {
|
||||
//
|
||||
// TODO:
|
||||
// - It would be great if this could actually wrap actual TS enums
|
||||
export default class Enum extends Base<number> {
|
||||
export default class Enum extends Base<number> implements Codec {
|
||||
private _enum: EnumDef;
|
||||
|
||||
constructor (def: EnumDef, value: Enum | Uint8Array | number = 0) {
|
||||
@@ -42,6 +43,10 @@ export default class Enum extends Base<number> {
|
||||
return 1;
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
@@ -33,4 +33,15 @@ describe('Struct', () => {
|
||||
).toString()
|
||||
).toEqual('Text');
|
||||
});
|
||||
|
||||
it('allows accessing the type and value', () => {
|
||||
const text = new Text('foo');
|
||||
const enumType = new EnumType(
|
||||
[Text, U32],
|
||||
{ Text: text }
|
||||
);
|
||||
|
||||
expect(enumType.type).toBe('Text');
|
||||
expect(enumType.value).toEqual(text);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { isNumber, isObject, isU8a, isUndefined, u8aConcat } from '@polkadot/util';
|
||||
import { isNumber, isObject, isU8a, isUndefined, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import Base from './Base';
|
||||
import Null from '../Null';
|
||||
import { Constructor } from '../types';
|
||||
import { Codec, Constructor } from '../types';
|
||||
|
||||
type TypesArray = Array<Constructor<Base>>;
|
||||
type TypesArray = Array<Constructor>;
|
||||
type TypesDef = {
|
||||
[index: number]: Constructor<Base>
|
||||
[index: number]: Constructor
|
||||
} | TypesArray;
|
||||
|
||||
// This implements an enum, that based on the value wraps a different type. It is effectively an
|
||||
@@ -19,8 +19,7 @@ type TypesDef = {
|
||||
// TODO:
|
||||
// - As per Enum, actually use TS enum
|
||||
// - It should rather probably extend Enum instead of copying code
|
||||
// - There doesn't actually seem to be a way to get to the actual determined/wrapped value
|
||||
export default class EnumType<T> extends Base<Base<T>> {
|
||||
export default class EnumType<T> extends Base<Codec> implements Codec {
|
||||
private _Types: TypesArray;
|
||||
private _index: number;
|
||||
private _indexes: Array<number>;
|
||||
@@ -87,7 +86,7 @@ export default class EnumType<T> extends Base<Base<T>> {
|
||||
return this._Types[this._index].name;
|
||||
}
|
||||
|
||||
get value (): Base<T> {
|
||||
get value (): Codec {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
@@ -95,21 +94,8 @@ export default class EnumType<T> extends Base<Base<T>> {
|
||||
return 1 + this.raw.encodedLength;
|
||||
}
|
||||
|
||||
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) {
|
||||
this._index = this._indexes[0];
|
||||
}
|
||||
|
||||
this.raw = new this._Types[this._index](value);
|
||||
toHex (): string {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
|
||||
@@ -5,12 +5,12 @@
|
||||
import Option from './Option';
|
||||
import Text from '../Text';
|
||||
|
||||
const testDecode = (type, input, expected, testLength = true) =>
|
||||
const testDecode = (type, input, expected) =>
|
||||
it(`can decode from ${type}`, () => {
|
||||
const o = new Option(Text, input);
|
||||
|
||||
expect(o.toString()).toBe(expected);
|
||||
expect(o.isEmpty).toBe(testLength && !expected.length);
|
||||
expect(o.isNone).toBe(!expected.length);
|
||||
});
|
||||
|
||||
const testEncode = (to, expected) =>
|
||||
@@ -22,9 +22,9 @@ const testEncode = (to, expected) =>
|
||||
|
||||
describe('Option', () => {
|
||||
it('converts undefined/null to empty', () => {
|
||||
expect(new Option(Text, undefined).isEmpty).toBe(true);
|
||||
expect(new Option(Text, null).isEmpty).toBe(true);
|
||||
expect(new Option(Text, 'test').isEmpty).toBe(false);
|
||||
expect(new Option(Text, undefined).isNone).toBe(true);
|
||||
expect(new Option(Text, null).isNone).toBe(true);
|
||||
expect(new Option(Text, 'test').isNone).toBe(false);
|
||||
});
|
||||
|
||||
testDecode('string (with)', 'foo', 'foo');
|
||||
@@ -32,7 +32,7 @@ describe('Option', () => {
|
||||
testDecode('Uint8Array (with)', Uint8Array.from([1, 12, 102, 111, 111]), 'foo');
|
||||
testDecode('Uint8Array (without)', Uint8Array.from([0]), '', false);
|
||||
|
||||
// testEncode('toHex', '0x010c666f6f'); // FIXME Add this
|
||||
testEncode('toHex', '0x010c666f6f');
|
||||
testEncode('toString', 'foo');
|
||||
testEncode('toU8a', Uint8Array.from([1, 12, 102, 111, 111]));
|
||||
|
||||
|
||||
@@ -2,28 +2,24 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { isNull, isU8a, isUndefined } from '@polkadot/util';
|
||||
import { isNull, isU8a, isUndefined, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import Base from './Base';
|
||||
import { Constructor } from '../types';
|
||||
import { Codec, Constructor } from '../types';
|
||||
import Null from '../Null';
|
||||
|
||||
// An Option is an optional field. Basically the first byte indicates that there is
|
||||
// is value to follow. If the byte is `1` there is an actual value. So the Option
|
||||
// implements that - decodes, checks for optionality and wraps the required structure
|
||||
// with a value if/as required/found.
|
||||
export default class Option<T> extends Base<Base<T>> {
|
||||
private _isEmpty: boolean;
|
||||
|
||||
constructor (Type: Constructor<Base<T>>, value?: any) {
|
||||
export default class Option<T extends Codec> extends Base<T> implements Codec {
|
||||
constructor (Type: Constructor, value?: any) {
|
||||
super(
|
||||
Option.decodeOption(Type, value)
|
||||
);
|
||||
|
||||
this._isEmpty = isNull(value) || isUndefined(value);
|
||||
}
|
||||
|
||||
static decodeOption<O> (Type: Constructor<Base<O>>, value?: any): Base {
|
||||
static decodeOption<O> (Type: Constructor, value?: any): Codec {
|
||||
if (isU8a(value)) {
|
||||
if (value[0] === 0) {
|
||||
return new Null();
|
||||
@@ -32,14 +28,13 @@ export default class Option<T> extends Base<Base<T>> {
|
||||
return new Type(value.subarray(1));
|
||||
}
|
||||
|
||||
return new Type(
|
||||
isNull(value) || isUndefined(value)
|
||||
? undefined
|
||||
: value
|
||||
);
|
||||
return isNull(value) || isUndefined(value) || value instanceof Null
|
||||
? new Null()
|
||||
: new Type(value);
|
||||
|
||||
}
|
||||
|
||||
static with<O> (Type: Constructor<Base<O>>): Constructor<Option<O>> {
|
||||
static with<O extends Codec> (Type: Constructor): Constructor<Option<O>> {
|
||||
return class extends Option<O> {
|
||||
constructor (value?: any) {
|
||||
super(Type, value);
|
||||
@@ -47,28 +42,28 @@ export default class Option<T> extends Base<Base<T>> {
|
||||
};
|
||||
}
|
||||
|
||||
get isEmpty (): boolean {
|
||||
return this._isEmpty;
|
||||
get isNone (): boolean {
|
||||
return this.raw instanceof Null;
|
||||
}
|
||||
|
||||
get value (): Base<T> | undefined {
|
||||
return this._isEmpty
|
||||
? undefined
|
||||
: this.raw;
|
||||
get isSome (): boolean {
|
||||
return !this.isNone;
|
||||
}
|
||||
|
||||
get value (): Codec {
|
||||
return this.raw;
|
||||
}
|
||||
|
||||
get encodedLength (): number {
|
||||
const childLength = this._isEmpty
|
||||
? 0
|
||||
: this.raw.encodedLength;
|
||||
return 1 + this.raw.encodedLength;
|
||||
}
|
||||
|
||||
return 1 + childLength;
|
||||
toHex (): string {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this._isEmpty
|
||||
? undefined
|
||||
: this.raw.toJSON();
|
||||
this.raw.toJSON();
|
||||
}
|
||||
|
||||
toU8a (isBare?: boolean): Uint8Array {
|
||||
@@ -78,7 +73,7 @@ export default class Option<T> extends Base<Base<T>> {
|
||||
|
||||
const u8a = new Uint8Array(this.encodedLength);
|
||||
|
||||
if (!this._isEmpty) {
|
||||
if (this.isSome) {
|
||||
u8a.set([1]);
|
||||
u8a.set(this.raw.toU8a(), 1);
|
||||
}
|
||||
@@ -87,8 +82,13 @@ export default class Option<T> extends Base<Base<T>> {
|
||||
}
|
||||
|
||||
toString (): string {
|
||||
return this._isEmpty
|
||||
? ''
|
||||
: this.raw.toString();
|
||||
return this.raw.toString();
|
||||
}
|
||||
|
||||
unwrap (): T {
|
||||
if (this.isNone) {
|
||||
throw new Error('Option: unwrapping a None value');
|
||||
}
|
||||
return this.raw;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { isU8a, isUndefined } from '@polkadot/util';
|
||||
import { isU8a, isUndefined, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import Base from './Base';
|
||||
import { Codec } from '../types';
|
||||
|
||||
type SetValues = {
|
||||
[index: string]: number
|
||||
@@ -14,7 +15,7 @@ type SetValues = {
|
||||
// a bitwise representation of the values.
|
||||
//
|
||||
// FIXME This is a prime candidate to potentially extend Set
|
||||
export default class Set extends Base<Array<string>> {
|
||||
export default class Set extends Base<Array<string>> implements Codec {
|
||||
private _setValues: SetValues;
|
||||
|
||||
constructor (setValues: SetValues, value?: Array<string> | Uint8Array | number) {
|
||||
@@ -78,6 +79,10 @@ export default class Set extends Base<Array<string>> {
|
||||
return Set.encodeSet(this._setValues, this.raw);
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.values;
|
||||
}
|
||||
|
||||
@@ -4,11 +4,10 @@
|
||||
|
||||
import { hexToU8a, isHex, isObject, isU8a, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import Base from './Base';
|
||||
import { Codec, Constructor, ConstructorDef } from '../types';
|
||||
|
||||
// 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>
|
||||
// A Struct defines an Object with key/values - where the values are Codec values. It removes
|
||||
// a lot of repetition from the actual coding, define a structure type, pass it the key/Codec
|
||||
// values in the constructor and it manages the decoding. It is important that the constructor
|
||||
// values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical,
|
||||
// it needs to decoded in the specific defined order.
|
||||
@@ -16,13 +15,12 @@ export default class Struct<
|
||||
// The actual Class structure, i.e. key -> Class
|
||||
S extends ConstructorDef = ConstructorDef,
|
||||
// internal type, instance of classes mapped by key
|
||||
T extends { [K in keyof S]: Base } = { [K in keyof S]: Base },
|
||||
T extends { [K in keyof S]: Codec } = { [K in keyof S]: Codec },
|
||||
// input values, mapped by key can be anything (construction)
|
||||
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 {
|
||||
public raw: Map<keyof S, Base>; // FIXME Remove this once we convert all types out of Base
|
||||
> extends Map<keyof S, Codec> implements Codec {
|
||||
protected _jsonMap: Map<keyof S, string>;
|
||||
protected _Types: E;
|
||||
|
||||
@@ -41,9 +39,6 @@ export default class Struct<
|
||||
|
||||
return result;
|
||||
}, {} as E);
|
||||
|
||||
// FIXME Remove this once we convert all types out of Base
|
||||
this.raw = this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,7 +59,7 @@ export default class Struct<
|
||||
private static decodeStruct<
|
||||
S extends ConstructorDef,
|
||||
_,
|
||||
T extends { [K in keyof S]: Base }
|
||||
T extends { [K in keyof S]: Codec }
|
||||
> (Types: S, value: any, jsonMap: Map<keyof S, string>): T {
|
||||
// l.debug(() => ['Struct.decode', { Types, value }]);
|
||||
|
||||
@@ -130,11 +125,11 @@ export default class Struct<
|
||||
}, 0);
|
||||
}
|
||||
|
||||
getAtIndex (index: number): Base {
|
||||
getAtIndex (index: number): Codec {
|
||||
return this.toArray()[index];
|
||||
}
|
||||
|
||||
toArray (): Array<Base> {
|
||||
toArray (): Array<Codec> {
|
||||
return [...this.values()];
|
||||
}
|
||||
|
||||
|
||||
@@ -2,22 +2,21 @@
|
||||
// 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 { Codec, Constructor, ConstructorDef } from '../types';
|
||||
import Struct from './Struct';
|
||||
|
||||
// A Tuple defines an anonymous Object with key/values - where the values are Base<T> values. It
|
||||
// A Tuple defines an anonymous Object with key/values - where the values are Codec values. It
|
||||
// is a specialization of the Struct type where the toJSON 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 documented there)
|
||||
S extends ConstructorDef = { [index: string]: Constructor<Base> },
|
||||
T extends { [K in keyof S]: Base } = { [K in keyof S]: Base },
|
||||
S extends ConstructorDef = { [index: string]: Constructor<Codec> },
|
||||
T extends { [K in keyof S]: Codec } = { [K in keyof S]: Codec },
|
||||
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<Codec> }
|
||||
> (Types: S): Constructor<Tuple<S>> {
|
||||
return class extends Tuple<S> {
|
||||
constructor (value?: any) {
|
||||
super(Types, value);
|
||||
|
||||
@@ -11,15 +11,10 @@ import { AnyU8a, Codec } from '../types';
|
||||
// consume the full u8a as passed to it in U8a. As such it is meant to be
|
||||
// subclassed where the wrapper takes care of the actual lengths.
|
||||
export default class U8a extends Uint8Array implements Codec {
|
||||
// FIXME Remove this once we convert all types out of Base
|
||||
public raw: Uint8Array;
|
||||
|
||||
constructor (value: AnyU8a) {
|
||||
super(
|
||||
U8a.decodeU8a(value)
|
||||
);
|
||||
|
||||
this.raw = this;
|
||||
}
|
||||
|
||||
private static decodeU8a (value: any): Uint8Array {
|
||||
|
||||
@@ -20,7 +20,6 @@ export const DEFAULT_UINT_BITS = 64;
|
||||
export default class UInt extends BN implements Codec {
|
||||
protected _bitLength: UIntBitLength;
|
||||
private _isHexJson: boolean;
|
||||
public raw: BN; // FIXME Remove this once we convert all types out of Base
|
||||
|
||||
constructor (value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = true) {
|
||||
super(
|
||||
@@ -29,7 +28,6 @@ export default class UInt extends BN implements Codec {
|
||||
|
||||
this._bitLength = bitLength;
|
||||
this._isHexJson = isHexJson;
|
||||
this.raw = this;
|
||||
}
|
||||
|
||||
static decodeUInt (value: AnyNumber, bitLength: UIntBitLength): string {
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aConcat, u8aToU8a, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import Base from './Base';
|
||||
import Compact, { DEFAULT_LENGTH_BITS } from './Compact';
|
||||
import { Constructor } from '../types';
|
||||
import { Codec, Constructor } from '../types';
|
||||
|
||||
// This manages codec arrays. Intrernally it keeps track of the length (as decoded) and allows
|
||||
// construction with the passed `Type` in the constructor. It aims to be an array-like structure,
|
||||
@@ -14,8 +14,8 @@ import { Constructor } from '../types';
|
||||
// to retrieve a specific item. Additionally the helper functions `map`, `filter`, `forEach` and
|
||||
// `reduce` is exposed on the interface.
|
||||
export default class Vector<
|
||||
T extends Base
|
||||
> extends Base<Array<T>> {
|
||||
T extends Codec
|
||||
> extends Base<Array<T>> implements Codec {
|
||||
private _Type: Constructor<T>;
|
||||
|
||||
constructor (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | Array<any> = [] as Array<any>) {
|
||||
@@ -26,7 +26,7 @@ export default class Vector<
|
||||
this._Type = Type;
|
||||
}
|
||||
|
||||
static decodeVector<T extends Base> (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | Array<any>): Array<T> {
|
||||
static decodeVector<T extends Codec> (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | Array<any>): Array<T> {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) =>
|
||||
entry instanceof Type
|
||||
@@ -54,7 +54,7 @@ export default class Vector<
|
||||
return result;
|
||||
}
|
||||
|
||||
static with<O extends Base> (Type: Constructor<O>): Constructor<Vector<O>> {
|
||||
static with<O extends Codec> (Type: Constructor<O>): Constructor<Vector<O>> {
|
||||
return class extends Vector<O> {
|
||||
constructor (value?: Array<any>) {
|
||||
super(Type, value);
|
||||
@@ -104,6 +104,10 @@ export default class Vector<
|
||||
return this.raw.reduce(fn, initial);
|
||||
}
|
||||
|
||||
toHex (): string {
|
||||
return u8aToHex(this.toU8a());
|
||||
}
|
||||
|
||||
toJSON (): any {
|
||||
return this.raw.map((entry) =>
|
||||
entry.toJSON()
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { Constructor } from '../types';
|
||||
import { Codec, Constructor } from '../types';
|
||||
import Text from '../Text';
|
||||
import Base from './Base';
|
||||
import Compact from './Compact';
|
||||
import Tuple from './Tuple';
|
||||
import UInt from './UInt';
|
||||
@@ -155,7 +154,7 @@ export function getTypeClass (value: TypeDef): Constructor {
|
||||
return Type;
|
||||
}
|
||||
|
||||
export default function createType (type: Text | string, value?: any): Base {
|
||||
export default function createType (type: Text | string, value?: any): Codec {
|
||||
// l.debug(() => ['createType', { type, value }]);
|
||||
|
||||
const Type = getTypeClass(
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
// others, so there _should_ not be need for direct use)
|
||||
|
||||
// These are the base codec types, generally used for construction
|
||||
export { default as Base } from './Base';
|
||||
export { default as Compact } from './Compact';
|
||||
export { default as Enum } from './Enum';
|
||||
export { default as EnumType } from './EnumType';
|
||||
|
||||
@@ -144,13 +144,13 @@ function addStorage (metadata: Metadata) {
|
||||
const renderAnchors = generateSectionLinks('storage', metadata);
|
||||
|
||||
return orderedSections.reduce((md: string, moduleMetadata: any) => {
|
||||
if (!moduleMetadata.storage) {
|
||||
if (moduleMetadata.storage.isNone) {
|
||||
return md;
|
||||
}
|
||||
|
||||
const sectionName = stringLowerFirst(moduleMetadata.storage.prefix.toString());
|
||||
const sectionName = stringLowerFirst(moduleMetadata.storage.unwrap().prefix.toString());
|
||||
const renderSection = generateSectionHeader(md, sectionName);
|
||||
const orderedMethods = moduleMetadata.storage.functions.map((i: any) => i).sort();
|
||||
const orderedMethods = moduleMetadata.storage.unwrap().functions.map((i: any) => i).sort();
|
||||
|
||||
return orderedMethods.reduce((md: string, func: any) => {
|
||||
const methodName = stringLowerFirst(func.name.toString());
|
||||
|
||||
Vendored
+3
-4
@@ -5,7 +5,6 @@
|
||||
import BN from 'bn.js';
|
||||
import * as Classes from './index';
|
||||
|
||||
import Base from './codec/Base';
|
||||
import { UInt } from './codec';
|
||||
|
||||
export type AnyNumber = UInt | BN | Uint8Array | number | string;
|
||||
@@ -26,8 +25,8 @@ export type CodecTo = 'toHex' | 'toJSON' | 'toString' | 'toU8a'
|
||||
|
||||
export type CodecTypes = keyof typeof Classes;
|
||||
|
||||
export type Constructor<T = Base> = { new(value?: any): T };
|
||||
export type Constructor<T = Codec> = { new(value?: any): T };
|
||||
|
||||
export type ConstructorDef<T = Base> = { [index: string]: Constructor<T> };
|
||||
export type ConstructorDef<T = Codec> = { [index: string]: Constructor<T> };
|
||||
|
||||
export type TypeDef<T = Base> = { [index: string]: Base<T> };
|
||||
export type TypeDef<T = Codec> = { [index: string]: Codec<T> };
|
||||
|
||||
Reference in New Issue
Block a user