diff --git a/packages/api/src/promise/index.ts b/packages/api/src/promise/index.ts index 8cf7c6a1b7..c704ba904e 100644 --- a/packages/api/src/promise/index.ts +++ b/packages/api/src/promise/index.ts @@ -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): Promise => { + const decorated: any = (...args: Array): Promise => { 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 = []) => + (result: Array = []) => args[args.length - 1](result[0]) ); }; diff --git a/packages/api/src/rx/index.ts b/packages/api/src/rx/index.ts index a010361485..96fd8cfdb4 100644 --- a/packages/api/src/rx/index.ts +++ b/packages/api/src/rx/index.ts @@ -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 => { + const decorated: any = (arg: any): Observable => { let observable; try { @@ -242,7 +242,7 @@ export default class ApiRx extends ApiBase = []): Base | null | undefined => + map((result: Array = []): Codec | null | undefined => result[0] ) ); diff --git a/packages/rpc-core/src/index.ts b/packages/rpc-core/src/index.ts index 5d13350a31..8823505067 100644 --- a/packages/rpc-core/src/index.ts +++ b/packages/rpc-core/src/index.ts @@ -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): Array { + private formatInputs (method: RpcMethod, inputs: Array): Array { 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, result?: any): Base | Array { + private formatOutput (method: RpcMethod, params: Array, result?: any): Codec | Array { 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); + }, [] as Array); } return base; diff --git a/packages/rpc-provider/src/mock/index.ts b/packages/rpc-provider/src/mock/index.ts index 9cf73c4e52..6b8be13ccf 100644 --- a/packages/rpc-provider/src/mock/index.ts +++ b/packages/rpc-provider/src/mock/index.ts @@ -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) { + private updateSubs (method: string, value: Codec) { this.subscriptions[method].lastValue = value; Object diff --git a/packages/type-storage/src/fromMetadata.ts b/packages/type-storage/src/fromMetadata.ts index 06f0b6bc0d..7ff87d4118 100644 --- a/packages/type-storage/src/fromMetadata.ts +++ b/packages/type-storage/src/fromMetadata.ts @@ -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; diff --git a/packages/types/src/Bool.ts b/packages/types/src/Bool.ts index 962258fc2d..ae67cbc3f7 100644 --- a/packages/types/src/Bool.ts +++ b/packages/types/src/Bool.ts @@ -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 { diff --git a/packages/types/src/Bytes.ts b/packages/types/src/Bytes.ts index 8de81787d7..5a57335a85 100644 --- a/packages/types/src/Bytes.ts +++ b/packages/types/src/Bytes.ts @@ -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 diff --git a/packages/types/src/Extrinsic.ts b/packages/types/src/Extrinsic.ts index 0f86dd6077..5d2e373990 100644 --- a/packages/types/src/Extrinsic.ts +++ b/packages/types/src/Extrinsic.ts @@ -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 { + get args (): Array { return this.method.args; } diff --git a/packages/types/src/ExtrinsicSignature.ts b/packages/types/src/ExtrinsicSignature.ts index 7eb274b3c7..121e72bc37 100644 --- a/packages/types/src/ExtrinsicSignature.ts +++ b/packages/types/src/ExtrinsicSignature.ts @@ -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]; diff --git a/packages/types/src/Header.ts b/packages/types/src/Header.ts index 8c9e1bb7de..9718a4f824 100644 --- a/packages/types/src/Header.ts +++ b/packages/types/src/Header.ts @@ -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 { diff --git a/packages/types/src/KeyValue.spec.ts b/packages/types/src/KeyValue.spec.ts index c083cbac9b..15a25d0ab8 100644 --- a/packages/types/src/KeyValue.spec.ts +++ b/packages/types/src/KeyValue.spec.ts @@ -55,6 +55,6 @@ describe('KeyValueOption', () => { }); expect(kv.key.toHex()).toEqual('0x11223344'); - expect(kv.value.isEmpty).toEqual(true); + expect(kv.value.isNone).toEqual(true); }); }); diff --git a/packages/types/src/Metadata.ts b/packages/types/src/Metadata.ts index 68b1a3d357..4fbe9661df 100644 --- a/packages/types/src/Metadata.ts +++ b/packages/types/src/Metadata.ts @@ -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).raw; + return this.value as StorageFunctionType$Map; } get asType (): Type { - return (this.raw as Base).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).value; - - return value - ? value.raw - : value; + get storage (): Option { + return this.get('storage') as Option; } } @@ -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) => diff --git a/packages/types/src/Method.ts b/packages/types/src/Method.ts index 0a7feb837f..27eaafe108 100644 --- a/packages/types/src/Method.ts +++ b/packages/types/src/Method.ts @@ -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; + [index: string]: Constructor; } interface DecodeMethodInput { @@ -166,7 +165,7 @@ export default class Method extends Struct { ); } - get args (): Array { + get args (): Array { // FIXME This should return a Struct instead of an Array return [...(this.get('args') as Struct).values()]; } diff --git a/packages/types/src/Null.ts b/packages/types/src/Null.ts index 51a603764a..d5ae46dd59 100644 --- a/packages/types/src/Null.ts +++ b/packages/types/src/Null.ts @@ -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 { - constructor () { - super(null); - } - +export default class Null implements Codec { get encodedLength (): number { return 0; } + toHex (): string { + return '0x'; + } + toJSON (): any { return null; } diff --git a/packages/types/src/Origin.ts b/packages/types/src/Origin.ts index c7a89d61b7..17d2f238f2 100644 --- a/packages/types/src/Origin.ts +++ b/packages/types/src/Origin.ts @@ -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'); } } diff --git a/packages/types/src/Text.ts b/packages/types/src/Text.ts index 447ad700c5..28b3101b30 100644 --- a/packages/types/src/Text.ts +++ b/packages/types/src/Text.ts @@ -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 { diff --git a/packages/types/src/codec/Base.spec.js b/packages/types/src/codec/Base.spec.js deleted file mode 100644 index f2c41339c9..0000000000 --- a/packages/types/src/codec/Base.spec.js +++ /dev/null @@ -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/); - }); - }); -}); diff --git a/packages/types/src/codec/Base.ts b/packages/types/src/codec/Base.ts index 1cd0d51651..a92d67ef56 100644 --- a/packages/types/src/codec/Base.ts +++ b/packages/types/src/codec/Base.ts @@ -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 { - 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'); - } } diff --git a/packages/types/src/codec/Compact.ts b/packages/types/src/codec/Compact.ts index d8e57301ef..772204fde5 100644 --- a/packages/types/src/codec/Compact.ts +++ b/packages/types/src/codec/Compact.ts @@ -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 { +export default class Compact extends Base implements Codec { constructor (Type: Constructor, value: AnyNumber = 0) { super(Compact.decodeCompact(Type, value)); } @@ -126,7 +126,7 @@ export default class Compact extends Base { return this.toU8a().length; } - toBn (): any { + toBn (): BN { return this.raw.toBn(); } diff --git a/packages/types/src/codec/Enum.ts b/packages/types/src/codec/Enum.ts index 53582ed55e..2ddc55c00a 100644 --- a/packages/types/src/codec/Enum.ts +++ b/packages/types/src/codec/Enum.ts @@ -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 { +export default class Enum extends Base implements Codec { private _enum: EnumDef; constructor (def: EnumDef, value: Enum | Uint8Array | number = 0) { @@ -42,6 +43,10 @@ export default class Enum extends Base { return 1; } + toHex (): string { + return u8aToHex(this.toU8a()); + } + toJSON (): any { return this.raw; } diff --git a/packages/types/src/codec/EnumType.spec.js b/packages/types/src/codec/EnumType.spec.js index 415b49467a..4e8ea4d672 100644 --- a/packages/types/src/codec/EnumType.spec.js +++ b/packages/types/src/codec/EnumType.spec.js @@ -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); + }); }); diff --git a/packages/types/src/codec/EnumType.ts b/packages/types/src/codec/EnumType.ts index 56cace92ba..46d7fadf54 100644 --- a/packages/types/src/codec/EnumType.ts +++ b/packages/types/src/codec/EnumType.ts @@ -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>; +type TypesArray = Array; type TypesDef = { - [index: number]: Constructor + [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 extends Base> { +export default class EnumType extends Base implements Codec { private _Types: TypesArray; private _index: number; private _indexes: Array; @@ -87,7 +86,7 @@ export default class EnumType extends Base> { return this._Types[this._index].name; } - get value (): Base { + get value (): Codec { return this.raw; } @@ -95,21 +94,8 @@ export default class EnumType extends Base> { return 1 + this.raw.encodedLength; } - setValue (index?: | EnumType | 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 { diff --git a/packages/types/src/codec/Option.spec.js b/packages/types/src/codec/Option.spec.js index 576cafb402..8dc08b6f69 100644 --- a/packages/types/src/codec/Option.spec.js +++ b/packages/types/src/codec/Option.spec.js @@ -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])); diff --git a/packages/types/src/codec/Option.ts b/packages/types/src/codec/Option.ts index b5d07e5fc6..352c213d7e 100644 --- a/packages/types/src/codec/Option.ts +++ b/packages/types/src/codec/Option.ts @@ -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 extends Base> { - private _isEmpty: boolean; - - constructor (Type: Constructor>, value?: any) { +export default class Option extends Base implements Codec { + constructor (Type: Constructor, value?: any) { super( Option.decodeOption(Type, value) ); - - this._isEmpty = isNull(value) || isUndefined(value); } - static decodeOption (Type: Constructor>, value?: any): Base { + static decodeOption (Type: Constructor, value?: any): Codec { if (isU8a(value)) { if (value[0] === 0) { return new Null(); @@ -32,14 +28,13 @@ export default class Option extends Base> { 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 (Type: Constructor>): Constructor> { + static with (Type: Constructor): Constructor> { return class extends Option { constructor (value?: any) { super(Type, value); @@ -47,28 +42,28 @@ export default class Option extends Base> { }; } - get isEmpty (): boolean { - return this._isEmpty; + get isNone (): boolean { + return this.raw instanceof Null; } - get value (): Base | 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 extends Base> { 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 extends Base> { } 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; } } diff --git a/packages/types/src/codec/Set.ts b/packages/types/src/codec/Set.ts index bc56361bca..bc8b388fc2 100644 --- a/packages/types/src/codec/Set.ts +++ b/packages/types/src/codec/Set.ts @@ -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> { +export default class Set extends Base> implements Codec { private _setValues: SetValues; constructor (setValues: SetValues, value?: Array | Uint8Array | number) { @@ -78,6 +79,10 @@ export default class Set extends Base> { return Set.encodeSet(this._setValues, this.raw); } + toHex (): string { + return u8aToHex(this.toU8a()); + } + toJSON (): any { return this.values; } diff --git a/packages/types/src/codec/Struct.ts b/packages/types/src/codec/Struct.ts index f2144d6a18..dc30348e9f 100644 --- a/packages/types/src/codec/Struct.ts +++ b/packages/types/src/codec/Struct.ts @@ -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 values. It removes -// a lot of repetition from the actual coding, define a structure type, pass it the key/Base +// 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 implements Codec { - public raw: Map; // FIXME Remove this once we convert all types out of Base + > extends Map implements Codec { protected _jsonMap: Map; 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): 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 { + toArray (): Array { return [...this.values()]; } diff --git a/packages/types/src/codec/Tuple.ts b/packages/types/src/codec/Tuple.ts index 9c199d26de..2e35adc7be 100644 --- a/packages/types/src/codec/Tuple.ts +++ b/packages/types/src/codec/Tuple.ts @@ -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 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 }, - T extends { [K in keyof S]: Base } = { [K in keyof S]: Base }, + S extends ConstructorDef = { [index: string]: Constructor }, + 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 { + > extends Struct { static with< - S extends ConstructorDef = { [index: string]: Constructor } - > (Types: S): Constructor> { + S extends ConstructorDef = { [index: string]: Constructor } + > (Types: S): Constructor> { return class extends Tuple { constructor (value?: any) { super(Types, value); diff --git a/packages/types/src/codec/U8a.ts b/packages/types/src/codec/U8a.ts index 91e2399ff6..fd5406a3a8 100644 --- a/packages/types/src/codec/U8a.ts +++ b/packages/types/src/codec/U8a.ts @@ -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 { diff --git a/packages/types/src/codec/UInt.ts b/packages/types/src/codec/UInt.ts index 32bf703fb0..2640009bfe 100644 --- a/packages/types/src/codec/UInt.ts +++ b/packages/types/src/codec/UInt.ts @@ -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 { diff --git a/packages/types/src/codec/Vector.ts b/packages/types/src/codec/Vector.ts index b8d2d02232..7e3f369ff7 100644 --- a/packages/types/src/codec/Vector.ts +++ b/packages/types/src/codec/Vector.ts @@ -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> { + T extends Codec + > extends Base> implements Codec { private _Type: Constructor; constructor (Type: Constructor, value: Vector | Uint8Array | string | Array = [] as Array) { @@ -26,7 +26,7 @@ export default class Vector< this._Type = Type; } - static decodeVector (Type: Constructor, value: Vector | Uint8Array | string | Array): Array { + static decodeVector (Type: Constructor, value: Vector | Uint8Array | string | Array): Array { if (Array.isArray(value)) { return value.map((entry) => entry instanceof Type @@ -54,7 +54,7 @@ export default class Vector< return result; } - static with (Type: Constructor): Constructor> { + static with (Type: Constructor): Constructor> { return class extends Vector { constructor (value?: Array) { 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() diff --git a/packages/types/src/codec/createType.ts b/packages/types/src/codec/createType.ts index 9cf81d95f6..be3522d6d8 100644 --- a/packages/types/src/codec/createType.ts +++ b/packages/types/src/codec/createType.ts @@ -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( diff --git a/packages/types/src/codec/index.ts b/packages/types/src/codec/index.ts index b8a03c6949..35845471e3 100644 --- a/packages/types/src/codec/index.ts +++ b/packages/types/src/codec/index.ts @@ -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'; diff --git a/packages/types/src/scripts/MetadataMd.ts b/packages/types/src/scripts/MetadataMd.ts index 0fe51f6475..4b3913c3d1 100644 --- a/packages/types/src/scripts/MetadataMd.ts +++ b/packages/types/src/scripts/MetadataMd.ts @@ -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()); diff --git a/packages/types/src/types.d.ts b/packages/types/src/types.d.ts index 9779261ee2..4ed1c49098 100644 --- a/packages/types/src/types.d.ts +++ b/packages/types/src/types.d.ts @@ -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 = { new(value?: any): T }; +export type Constructor = { new(value?: any): T }; -export type ConstructorDef = { [index: string]: Constructor }; +export type ConstructorDef = { [index: string]: Constructor }; -export type TypeDef = { [index: string]: Base }; +export type TypeDef = { [index: string]: Codec };