eslint rules (#1099)

* Off to the races - 3760 problems (1794 errors, 1966 warnings)

* Convert Array<T> -> T[] (not all correct, eg. extends)

* () => { -> (): void  => {

* get is/as -> public get is/as

* public for getters, constructors & base Codec

* Some cleanups from previous overzealous search & replace

* Under 2k, 1874 problems (649 errors, 1225 warnings)

* ^^^ check that commit for details ;)

* Minor.

* rm config header

* Minor cleanups

* Default to tslint, eslint as option

* Trigger

* Update jsonrpc

* 1494 problems (433 errors, 1061 warnings)

* 1103 problems (135 errors, 968 warnings)

* 899 problems (9 errors, 890 warnings)

* 483 problems (9 errors, 474 warnings) (ignore any... for now)

* 366 problems (9 errors, 357 warnings)

* 336 problems (9 errors, 327 warnings)

* 148 problems (9 errors, 139 warnings)

* 31 problems (8 errors, 23 warnings)

* 0, 0
This commit is contained in:
Jaco Greeff
2019-07-14 12:15:14 +02:00
committed by GitHub
parent f770fb973f
commit 71c5920b1f
354 changed files with 3817 additions and 3632 deletions
@@ -4,12 +4,12 @@
import MagicNumber, { MAGIC_NUMBER } from './MagicNumber';
describe('MagicNumber', () => {
it('succeeds when the magic number matches', () => {
expect(() => new MagicNumber(MAGIC_NUMBER)).not.toThrow();
describe('MagicNumber', (): void => {
it('succeeds when the magic number matches', (): void => {
expect((): MagicNumber => new MagicNumber(MAGIC_NUMBER)).not.toThrow();
});
it('fails when the magic number missmatches', () => {
expect(() => new MagicNumber(0x12345)).toThrow(/MagicNumber/);
it('fails when the magic number missmatches', (): void => {
expect((): MagicNumber => new MagicNumber(0x12345)).toThrow(/MagicNumber/);
});
});
+1 -1
View File
@@ -9,7 +9,7 @@ import U32 from '../primitive/U32';
export const MAGIC_NUMBER = new U32(0x6174656d); // `meta`, reversed for Little Endian encoding
export default class MagicNumber extends U32 {
constructor (value?: any) {
public constructor (value?: any) {
super(value);
assert(this.eq(MAGIC_NUMBER), `MagicNumber mismatch: expected ${MAGIC_NUMBER.toHex()}, found ${this.toHex()}`);
+1 -1
View File
@@ -13,7 +13,7 @@ import MetadataVersioned from './MetadataVersioned';
* The versioned runtime metadata as a decoded structure
*/
export default class Metadata extends MetadataVersioned {
constructor (value?: Uint8Array | string) {
public constructor (value?: Uint8Array | string) {
super(Metadata.decodeMetadata(value));
}
@@ -22,7 +22,7 @@ import v4ToV5 from './v4/toV5';
import v5ToV6 from './v5/toV6';
class MetadataEnum extends Enum {
constructor (value?: any) {
public constructor (value?: any) {
super({
MetadataV0, // once rolled-out, can replace this with MetadataDeprecated
MetadataV1, // once rolled-out, can replace this with MetadataDeprecated
@@ -37,7 +37,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V0 object
*/
get asV0 (): MetadataV0 {
public get asV0 (): MetadataV0 {
assert(this.isV0, `Cannot convert '${this.type}' via asV0`);
return this.value as MetadataV0;
@@ -46,7 +46,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V1 object
*/
get asV1 (): MetadataV1 {
public get asV1 (): MetadataV1 {
assert(this.isV1, `Cannot convert '${this.type}' via asV1`);
return this.value as MetadataV1;
@@ -55,7 +55,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V2 object
*/
get asV2 (): MetadataV2 {
public get asV2 (): MetadataV2 {
assert(this.isV2, `Cannot convert '${this.type}' via asV2`);
return this.value as MetadataV2;
@@ -64,7 +64,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V3 object
*/
get asV3 (): MetadataV3 {
public get asV3 (): MetadataV3 {
assert(this.isV3, `Cannot convert '${this.type}' via asV3`);
return this.value as MetadataV3;
@@ -73,7 +73,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V4 object
*/
get asV4 (): MetadataV4 {
public get asV4 (): MetadataV4 {
assert(this.isV4, `Cannot convert '${this.type}' via asV4`);
return this.value as MetadataV4;
@@ -82,7 +82,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V5 object
*/
get asV5 (): MetadataV5 {
public get asV5 (): MetadataV5 {
assert(this.isV5, `Cannot convert '${this.type}' via asV5`);
return this.value as MetadataV5;
@@ -91,7 +91,7 @@ class MetadataEnum extends Enum {
/**
* @description Returns the wrapped values as a V6 object
*/
get asV6 (): MetadataV6 {
public get asV6 (): MetadataV6 {
assert(this.isV6, `Cannot convert '${this.type}' via asV6`);
return this.value as MetadataV6;
@@ -100,63 +100,63 @@ class MetadataEnum extends Enum {
/**
* @description `true` if Deprecated
*/
get isDeprecated (): boolean {
public get isDeprecated (): boolean {
return this.type === 'MetadataDeprectated';
}
/**
* @description `true` if V0
*/
get isV0 (): boolean {
public get isV0 (): boolean {
return this.type === 'MetadataV0';
}
/**
* @description `true` if V1
*/
get isV1 (): boolean {
public get isV1 (): boolean {
return this.type === 'MetadataV1';
}
/**
* @description `true` if V2
*/
get isV2 (): boolean {
public get isV2 (): boolean {
return this.type === 'MetadataV2';
}
/**
* @description `true` if V3
*/
get isV3 (): boolean {
public get isV3 (): boolean {
return this.type === 'MetadataV3';
}
/**
* @description `true` if V4
*/
get isV4 (): boolean {
public get isV4 (): boolean {
return this.type === 'MetadataV4';
}
/**
* @description `true` if V5
*/
get isV5 (): boolean {
public get isV5 (): boolean {
return this.type === 'MetadataV5';
}
/**
* @description `true` if V6
*/
get isV6 (): boolean {
public get isV6 (): boolean {
return this.type === 'MetadataV6';
}
/**
* @description The version this metadata represents
*/
get version (): number {
public get version (): number {
return this.index;
}
}
@@ -168,13 +168,18 @@ class MetadataEnum extends Enum {
*/
export default class MetadataVersioned extends Struct {
private _convertedV1?: MetadataV1;
private _convertedV2?: MetadataV2;
private _convertedV3?: MetadataV3;
private _convertedV4?: MetadataV4;
private _convertedV5?: MetadataV5;
private _convertedV6?: MetadataV6;
constructor (value?: any) {
public constructor (value?: any) {
super({
magicNumber: MagicNumber,
metadata: MetadataEnum
@@ -184,7 +189,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description
*/
get magicNumber (): MagicNumber {
public get magicNumber (): MagicNumber {
return this.get('magicNumber') as MagicNumber;
}
@@ -198,14 +203,14 @@ export default class MetadataVersioned extends Struct {
/**
* @description the metadata version this structure represents
*/
get version (): number {
public get version (): number {
return this.metadata.index;
}
/**
* @description Returns the wrapped metadata as a V0 object
*/
get asV0 (): MetadataV0 {
public get asV0 (): MetadataV0 {
assert(this.metadata.version === 0, `Cannot convert metadata from v${this.metadata.version} to v0`);
return this.metadata.asV0;
@@ -214,7 +219,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description Returns the wrapped values as a V1 object
*/
get asV1 (): MetadataV1 {
public get asV1 (): MetadataV1 {
assert(this.metadata.version <= 1, `Cannot convert metadata from v${this.metadata.version} to v1`);
if (this.metadata.version === 1) {
@@ -231,7 +236,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description Returns the wrapped values as a V2 object
*/
get asV2 (): MetadataV2 {
public get asV2 (): MetadataV2 {
assert(this.metadata.version <= 2, `Cannot convert metadata from v${this.metadata.version} to v2`);
if (this.metadata.version === 2) {
@@ -248,7 +253,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description Returns the wrapped values as a V3 object
*/
get asV3 (): MetadataV3 {
public get asV3 (): MetadataV3 {
assert(this.metadata.version <= 3, `Cannot convert metadata from v${this.metadata.version} to v3`);
if (this.metadata.version === 3) {
@@ -265,7 +270,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description Returns the wrapped values as a V4 object
*/
get asV4 (): MetadataV4 {
public get asV4 (): MetadataV4 {
assert(this.metadata.version <= 4, `Cannot convert metadata from v${this.metadata.version} to v4`);
if (this.metadata.version === 4) {
@@ -282,7 +287,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description Returns the wrapped values as a V5 object
*/
get asV5 (): MetadataV5 {
public get asV5 (): MetadataV5 {
assert(this.metadata.version <= 5, `Cannot convert metadata from v${this.metadata.version} to v5`);
if (this.metadata.version === 5) {
@@ -299,7 +304,7 @@ export default class MetadataVersioned extends Struct {
/**
* @description Returns the wrapped values as a V6 object
*/
get asV6 (): MetadataV6 {
public get asV6 (): MetadataV6 {
assert(this.metadata.version <= 6, `Cannot convert metadata from v${this.metadata.version} to v6`);
if (this.metadata.version === 6) {
@@ -313,7 +318,7 @@ export default class MetadataVersioned extends Struct {
return this._convertedV6;
}
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
return this.asV6.getUniqTypes(throwError);
}
}
+1 -1
View File
@@ -2,6 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as Metadata } from './Metadata';
import Metadata from './Metadata';
export default Metadata;
+1 -1
View File
@@ -7,5 +7,5 @@ import { Codec } from '../types';
export interface MetadataInterface<Modules extends Codec> extends Codec {
modules: Vector<Modules>;
getUniqTypes (throwError: boolean): Array<string>;
getUniqTypes (throwError: boolean): string[];
}
@@ -3,8 +3,8 @@
// of the Apache-2.0 license. See the LICENSE file for details.
// Quick and dirty flatten (.flat() not available)
export default function flattenUniq (list: Array<any>): Array<any> {
const flat = list.reduce((result, entry) => {
export default function flattenUniq (list: any[]): any[] {
const flat = list.reduce((result, entry): any[] => {
return result.concat(
Array.isArray(entry)
? flattenUniq(entry)
@@ -13,6 +13,6 @@ export default function flattenUniq (list: Array<any>): Array<any> {
}, []);
return [...new Set(flat)]
.filter((value: any) => value)
.filter((value: any): any => value)
.sort();
}
+15 -15
View File
@@ -12,8 +12,8 @@ import Method from '../../primitive/Method';
import { MetadataInterface } from '../types';
import { Codec } from '../../types';
function injectDefinitions () {
Object.values(srmlTypes).forEach(({ types }) =>
function injectDefinitions (): void {
Object.values(srmlTypes).forEach(({ types }): void =>
getTypeRegistry().register(types)
);
}
@@ -26,8 +26,8 @@ export function decodeLatestSubstrate<Modules extends Codec> (
version: number,
rpcData: string,
latestSubstrate: object
) {
it('decodes latest substrate properly', () => {
): void {
it('decodes latest substrate properly', (): void => {
injectDefinitions();
const metadata = new Metadata(rpcData);
@@ -44,8 +44,8 @@ export function decodeLatestSubstrate<Modules extends Codec> (
* Given a `version`, MetadataV6 and MetadataV{version} should output the same
* unique types.
*/
export function toV6<Modules extends Codec> (version: number, rpcData: string) {
it('converts to V6', () => {
export function toV6<Modules extends Codec> (version: number, rpcData: string): void {
it('converts to V6', (): void => {
injectDefinitions();
const metadata = new Metadata(rpcData)[`asV${version}` as keyof Metadata];
@@ -60,8 +60,8 @@ export function toV6<Modules extends Codec> (version: number, rpcData: string) {
/**
* Given a Metadata, no type should throw when given its fallback value.
*/
export function defaultValues (rpcData: string) {
describe('storage with default values', () => {
export function defaultValues (rpcData: string): void {
describe('storage with default values', (): void => {
injectDefinitions();
const metadata = new Metadata(rpcData);
@@ -69,15 +69,15 @@ export function defaultValues (rpcData: string) {
Method.injectMethods(extrinsicsFromMeta(metadata));
metadata.asV6.modules
.filter(({ storage }) => storage.isSome)
.map((mod) =>
mod.storage.unwrap().forEach(({ fallback, name, type }) => {
it(`creates default types for ${mod.prefix}.${name}, type ${type}`, () => {
.filter(({ storage }): boolean => storage.isSome)
.forEach((mod): void => {
mod.storage.unwrap().forEach(({ fallback, name, type }): void => {
it(`creates default types for ${mod.prefix}.${name}, type ${type}`, (): void => {
expect(
() => createType(type.toString(), fallback)
(): Codec => createType(type.toString(), fallback)
).not.toThrow();
});
})
);
});
});
});
}
@@ -8,9 +8,9 @@ import { getTypeDef, TypeDef, TypeDefInfo } from '../../codec/createType';
import flattenUniq from './flattenUniq';
import { getTypeRegistry } from '../../codec';
export default function validateTypes (types: Array<string>, throwError: boolean): void {
const extractTypes = (types: Array<string>): Array<any> => {
return types.map((type) => {
export default function validateTypes (types: string[], throwError: boolean): void {
const extractTypes = (types: string[]): any[] => {
return types.map((type): any => {
const decoded = getTypeDef(type);
switch (decoded.info) {
@@ -24,7 +24,7 @@ export default function validateTypes (types: Array<string>, throwError: boolean
case TypeDefInfo.Tuple:
return extractTypes(
(decoded.sub as Array<TypeDef>).map((sub) => sub.type)
(decoded.sub as TypeDef[]).map((sub): string => sub.type)
);
default:
@@ -34,7 +34,7 @@ export default function validateTypes (types: Array<string>, throwError: boolean
};
const typeRegistry = getTypeRegistry();
const missing = flattenUniq(extractTypes(types)).filter((type) =>
const missing = flattenUniq(extractTypes(types)).filter((type): boolean =>
isUndefined(typeRegistry.get(type))
);
+7 -7
View File
@@ -8,7 +8,7 @@ import Text from '../../primitive/Text';
import U16 from '../../primitive/U16';
export class OuterDispatchCall extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -19,27 +19,27 @@ export class OuterDispatchCall extends Struct {
/**
* @description The [[U16]] index for the call
*/
get index (): U16 {
public get index (): U16 {
return this.get('index') as U16;
}
/**
* @description The name for the call
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The call prefix (or section)
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
}
export class OuterDispatchMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
calls: Vector.with(OuterDispatchCall)
@@ -49,14 +49,14 @@ export class OuterDispatchMetadata extends Struct {
/**
* @description The [[OuterDispathCall]] wrapped
*/
get calls (): Vector<OuterDispatchCall> {
public get calls (): Vector<OuterDispatchCall> {
return this.get('calls') as Vector<OuterDispatchCall>;
}
/**
* @description The name for the dispatch
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
+12 -12
View File
@@ -9,7 +9,7 @@ import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
export class EventMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
args: Vector.with(Type),
@@ -20,7 +20,7 @@ export class EventMetadata extends Struct {
/**
* @description The arguments of [[Type]]
*/
get args (): Vector<Type> {
public get args (): Vector<Type> {
return this.get('args') as Vector<Type>;
}
@@ -28,14 +28,14 @@ export class EventMetadata extends Struct {
* @description The arguments of [[Type]]
* @deprecated Use `.args` instead
*/
get arguments (): Vector<Type> {
public get arguments (): Vector<Type> {
return this.args;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -43,20 +43,20 @@ export class EventMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The name for the event
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
export class OuterEventEventMetadata extends Tuple {
constructor (value?: any) {
public constructor (value?: any) {
super({
Text,
'Vec<EventMetadata>': Vector.with(EventMetadata)
@@ -66,20 +66,20 @@ export class OuterEventEventMetadata extends Tuple {
/**
* @description The [[EventMetadata]]
*/
get events (): Vector<EventMetadata> {
public get events (): Vector<EventMetadata> {
return this[1] as Vector<EventMetadata>;
}
/**
* @description The name of the section
*/
get name (): Text {
public get name (): Text {
return this[0] as Text;
}
}
export class OuterEventMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
events: Vector.with(OuterEventEventMetadata)
@@ -89,14 +89,14 @@ export class OuterEventMetadata extends Struct {
/**
* @description The [[OuterEventEventMetadata]]
*/
get events (): Vector<OuterEventEventMetadata> {
public get events (): Vector<OuterEventEventMetadata> {
return this.get('events') as Vector<OuterEventEventMetadata>;
}
/**
* @description The name of the event
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
@@ -8,15 +8,15 @@ import latestSubstrateV0 from './latest.substrate.v0.json';
import rpcData from './static';
import { defaultValues, toV6 } from '../util/testUtil';
describe('Metadata', () => {
it('works with fallback', () => {
describe('Metadata', (): void => {
it('works with fallback', (): void => {
const metadata = new Metadata(rpcData);
const metadataV0 = new MetadataV0(rpcData);
expect(metadata.asV0.toString()).toEqual(metadataV0.toString());
});
it('decodes latest substrate properly', () => {
it('decodes latest substrate properly', (): void => {
const metadata = new Metadata(rpcData);
const json = metadata.asV0.toJSON();
+17 -17
View File
@@ -22,7 +22,7 @@ import { RuntimeModuleMetadata } from './Modules';
* The runtime metadata as a decoded structure
*/
export default class MetadataV0 extends Struct implements MetadataInterface<RuntimeModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
outerEvent: OuterEventMetadata,
modules: Vector.with(RuntimeModuleMetadata),
@@ -30,7 +30,7 @@ export default class MetadataV0 extends Struct implements MetadataInterface<Runt
}, MetadataV0.decodeMetadata(value));
}
static decodeMetadata (value: string | Uint8Array | object): object | Uint8Array {
public static decodeMetadata (value: string | Uint8Array | object): object | Uint8Array {
if (isHex(value)) {
// We receive this as an hex in the JSON output from the Node.
// Convert to u8a and use the U8a version to do the actual parsing.
@@ -55,44 +55,44 @@ export default class MetadataV0 extends Struct implements MetadataInterface<Runt
/**
* @description Wrapped [[OuterDispatchCall]]
*/
get calls (): Vector<OuterDispatchCall> {
public get calls (): Vector<OuterDispatchCall> {
return (this.get('outerDispatch') as OuterDispatchMetadata).calls;
}
/**
* @description Wrapped [[OuterEventEventMetadata]]
*/
get events (): Vector<OuterEventEventMetadata> {
public get events (): Vector<OuterEventEventMetadata> {
return (this.get('outerEvent') as OuterEventMetadata).events;
}
/**
* @description Wrapped [[RuntimeModuleMetadata]]
*/
get modules (): Vector<RuntimeModuleMetadata> {
public get modules (): Vector<RuntimeModuleMetadata> {
return this.get('modules') as Vector<RuntimeModuleMetadata>;
}
private get argNames () {
return this.modules.map((modul) =>
modul.module.call.functions.map((fn) =>
fn.args.map((argument) => argument.type.toString())
private get argNames (): string[][][] {
return this.modules.map((modul): string[][] =>
modul.module.call.functions.map((fn): string[] =>
fn.args.map((argument): string => argument.type.toString())
)
);
}
private get eventNames () {
return this.events.map((modul) =>
modul.events.map((event) =>
event.args.map((argument) => argument.toString())
private get eventNames (): string[][][] {
return this.events.map((modul): string[][] =>
modul.events.map((event): string[] =>
event.args.map((argument): string => argument.toString())
)
);
}
private get storageNames () {
return this.modules.map((modul) =>
private get storageNames (): string[][][] {
return this.modules.map((modul): string[][] =>
modul.storage.isSome
? modul.storage.unwrap().functions.map((fn) =>
? modul.storage.unwrap().functions.map((fn): string[] =>
fn.type.isMap
? [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()]
: [fn.type.asType.toString()]
@@ -104,7 +104,7 @@ export default class MetadataV0 extends Struct implements MetadataInterface<Runt
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.argNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+20 -20
View File
@@ -12,7 +12,7 @@ import U16 from '../../primitive/U16';
import { StorageMetadata } from './Storage';
export class FunctionArgumentMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
type: Type
@@ -22,20 +22,20 @@ export class FunctionArgumentMetadata extends Struct {
/**
* @description The argument name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The [[Type]]
*/
get type (): Type {
public get type (): Type {
return this.get('type') as Type;
}
}
export class FunctionMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
id: U16,
name: Text,
@@ -47,7 +47,7 @@ export class FunctionMetadata extends Struct {
/**
* @description The arguments of [[Type]]
*/
get args (): Vector<FunctionArgumentMetadata> {
public get args (): Vector<FunctionArgumentMetadata> {
return this.get('args') as Vector<FunctionArgumentMetadata>;
}
@@ -55,14 +55,14 @@ export class FunctionMetadata extends Struct {
* @description The [[FunctionArgumentMetadata]] for arguments
* @deprecated Use `.args` instead
*/
get arguments (): Vector<FunctionArgumentMetadata> {
public get arguments (): Vector<FunctionArgumentMetadata> {
return this.get('arguments') as Vector<FunctionArgumentMetadata>;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -70,27 +70,27 @@ export class FunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The `[sectionIndex, methodIndex]` call id
*/
get id (): U16 {
public get id (): U16 {
return this.get('id') as U16;
}
/**
* @description The call name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
export class CallMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
functions: Vector.with(FunctionMetadata)
@@ -100,19 +100,19 @@ export class CallMetadata extends Struct {
/**
* @description The functions available as [[FunctionMetadata]]
*/
get functions (): Vector<FunctionMetadata> {
public get functions (): Vector<FunctionMetadata> {
return this.get('functions') as Vector<FunctionMetadata>;
}
/**
* @description The section name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
call: CallMetadata
@@ -122,20 +122,20 @@ export class ModuleMetadata extends Struct {
/**
* @description The calls as [[FunctionMetadata]]
*/
get call (): CallMetadata {
public get call (): CallMetadata {
return this.get('call') as CallMetadata;
}
/**
* @description The name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
export class RuntimeModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
prefix: Text,
module: ModuleMetadata,
@@ -146,21 +146,21 @@ export class RuntimeModuleMetadata extends Struct {
/**
* @description The [[ModuleMetadata]]
*/
get module (): ModuleMetadata {
public get module (): ModuleMetadata {
return this.get('module') as ModuleMetadata;
}
/**
* @description The prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description The optional [[StorageMetadata]]
*/
get storage (): Option<StorageMetadata> {
public get storage (): Option<StorageMetadata> {
return this.get('storage') as Option<StorageMetadata>;
}
}
+31 -31
View File
@@ -14,18 +14,18 @@ import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
export class StorageFunctionModifier extends Enum {
constructor (value?: any) {
public constructor (value?: any) {
super(['Optional', 'Default', 'Required'], value);
}
/**
* @description `true` if the storage entry is optional
*/
get isOptional (): boolean {
public get isOptional (): boolean {
return this.toNumber() === 0;
}
toJSON (): string {
public toJSON (): string {
// This looks prettier in the generated JSON
return this.toString();
}
@@ -34,7 +34,7 @@ export class StorageFunctionModifier extends Enum {
export class MapType extends Struct {
private _isLinked = false;
constructor (value?: any) {
public constructor (value?: any) {
super({
key: Type,
value: Type
@@ -48,21 +48,21 @@ export class MapType extends Struct {
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
public get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
public get value (): Type {
return this.get('value') as Type;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
public get isLinked (): boolean {
return this._isLinked;
}
}
@@ -71,7 +71,7 @@ export class PlainType extends Type {
}
export class StorageFunctionType extends Enum {
constructor (value?: any, index?: number) {
public constructor (value?: any, index?: number) {
super({
PlainType,
MapType
@@ -81,7 +81,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
public get asMap (): MapType {
assert(this.isMap, `Cannot convert '${this.type}' via asMap`);
return this.value as MapType;
@@ -90,7 +90,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
public get asType (): PlainType {
assert(this.isPlainType, `Cannot convert '${this.type}' via asType`);
return this.value as PlainType;
@@ -99,21 +99,21 @@ export class StorageFunctionType extends Enum {
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
public get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description `true` if the storage entry is a plain type
*/
get isPlainType (): boolean {
public get isPlainType (): boolean {
return this.toNumber() === 0;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
if (this.isMap) {
if (this.asMap.isLinked) {
return `(${this.asMap.value.toString()}, Linkage<${this.asMap.key.toString()}>)`;
@@ -126,16 +126,16 @@ export class StorageFunctionType extends Enum {
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
export interface StorageFunctionMetadataValue {
name: string | Text;
modifier: StorageFunctionModifier | AnyNumber;
type: StorageFunctionType;
fallback: Bytes;
documentation: Vector<Text> | string[];
}
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
public constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
@@ -149,21 +149,21 @@ export class StorageFunctionMetadata extends Struct {
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
public get default (): Bytes {
return this.fallback;
}
/**
* @description The default value of the storage function
*/
get fallback (): Bytes {
public get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -171,34 +171,34 @@ export class StorageFunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The key name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The modifier
*/
get modifier (): StorageFunctionModifier {
public get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
public get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
export class StorageMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
prefix: Text,
functions: Vector.with(StorageFunctionMetadata)
@@ -208,14 +208,14 @@ export class StorageMetadata extends Struct {
/**
* @description The [[StorageFunctionMetadata]] for the section
*/
get functions (): Vector<StorageFunctionMetadata> {
public get functions (): Vector<StorageFunctionMetadata> {
return this.get('functions') as Vector<StorageFunctionMetadata>;
}
/**
* @description The section prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
}
+1 -1
View File
@@ -2,6 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV0 } from './Metadata';
import MetadataV0 from './Metadata';
export default MetadataV0;
+5 -5
View File
@@ -14,21 +14,21 @@ import { EventMetadata } from '../v1/Events';
import MetadataV1, { ModuleMetadata } from '../v1/Metadata';
import { StorageFunctionMetadata } from '../v1/Storage';
function toV1Calls (modul: RuntimeModuleMetadata) {
function toV1Calls (modul: RuntimeModuleMetadata): Option<FunctionMetadata> {
return modul.module.call.functions.length === 0
? new Option(Vector.with(FunctionMetadata))
: new Option(Vector.with(FunctionMetadata), modul.module.call.functions);
}
function toV1Events (metadataV0: MetadataV0, prefix: Text) {
const events = metadataV0.events.find((event) => event.name.eq(prefix));
function toV1Events (metadataV0: MetadataV0, prefix: Text): Option<EventMetadata> {
const events = metadataV0.events.find((event): boolean => event.name.eq(prefix));
return events
? new Option(Vector.with(EventMetadata), events.events)
: new Option(Vector.with(EventMetadata));
}
function toV1Storage (modul: RuntimeModuleMetadata) {
function toV1Storage (modul: RuntimeModuleMetadata): Option<StorageFunctionMetadata> {
return modul.storage.isNone
? new Option(Vector.with(StorageFunctionMetadata))
: new Option(
@@ -42,7 +42,7 @@ function toV1Storage (modul: RuntimeModuleMetadata) {
*/
export default function toV1 (metadataV0: MetadataV0): MetadataV1 {
return new MetadataV1({
modules: metadataV0.modules.map((modul) => {
modules: metadataV0.modules.map((modul): ModuleMetadata => {
// The prefix of this module (capitalized)
const prefix = modul.storage.isSome
? modul.storage.unwrap().prefix.toString()
+8 -8
View File
@@ -8,7 +8,7 @@ import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
export class FunctionArgumentMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
type: Type
@@ -18,14 +18,14 @@ export class FunctionArgumentMetadata extends Struct {
/**
* @description The argument name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The [[Type]]
*/
get type (): Type {
public get type (): Type {
return this.get('type') as Type;
}
}
@@ -36,7 +36,7 @@ export class FunctionArgumentMetadata extends Struct {
* The definition of a call
*/
export class FunctionMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
args: Vector.with(FunctionArgumentMetadata),
@@ -47,14 +47,14 @@ export class FunctionMetadata extends Struct {
/**
* @description The [[FunctionArgumentMetadata]] for arguments
*/
get args (): Vector<FunctionArgumentMetadata> {
public get args (): Vector<FunctionArgumentMetadata> {
return this.get('args') as Vector<FunctionArgumentMetadata>;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -62,14 +62,14 @@ export class FunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The call name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
}
@@ -6,7 +6,7 @@ import latestSubstrate from './latest.substrate.v1.json';
import rpcData from './static';
import { decodeLatestSubstrate, defaultValues, toV6 } from '../util/testUtil';
describe('MetadataV1', () => {
describe('MetadataV1', (): void => {
decodeLatestSubstrate(1, rpcData, latestSubstrate);
toV6(1, rpcData);
+20 -20
View File
@@ -20,7 +20,7 @@ import { StorageFunctionMetadata } from './Storage';
* The definition of a module in the system
*/
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -33,35 +33,35 @@ export class ModuleMetadata extends Struct {
/**
* @description the module calls
*/
get calls (): Option<Vector<FunctionMetadata>> {
public get calls (): Option<Vector<FunctionMetadata>> {
return this.get('calls') as Option<Vector<FunctionMetadata>>;
}
/**
* @description the module events
*/
get events (): Option<Vector<EventMetadata>> {
public get events (): Option<Vector<EventMetadata>> {
return this.get('events') as Option<Vector<EventMetadata>>;
}
/**
* @description the module name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageFunctionMetadata>> {
public get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
@@ -72,7 +72,7 @@ export class ModuleMetadata extends Struct {
* The runtime metadata as a decoded structure
*/
export default class MetadataV1 extends Struct implements MetadataInterface<ModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
modules: Vector.with(ModuleMetadata)
}, value);
@@ -81,35 +81,35 @@ export default class MetadataV1 extends Struct implements MetadataInterface<Modu
/**
* @description The associated modules for this structure
*/
get modules (): Vector<ModuleMetadata> {
public get modules (): Vector<ModuleMetadata> {
return this.get('modules') as Vector<ModuleMetadata>;
}
private get callNames () {
return this.modules.map((mod) =>
private get callNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
: mod.calls.unwrap().map((fn): string[] =>
fn.args.map((arg): string => arg.type.toString())
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
private get eventNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
: mod.events.unwrap().map((event): string[] =>
event.args.map((arg): string => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
private get storageNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) =>
: mod.storage.unwrap().map((fn): string[] =>
fn.type.isMap
? [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()]
: [fn.type.asType.toString()]
@@ -120,7 +120,7 @@ export default class MetadataV1 extends Struct implements MetadataInterface<Modu
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.callNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+1 -1
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV1, ModuleMetadata as ModuleMetadataV1 } from './Metadata';
import MetadataV1, { ModuleMetadata as ModuleMetadataV1 } from './Metadata';
export default MetadataV1;
@@ -6,7 +6,7 @@ import latestSubstrate from './latest.substrate.v2.json';
import rpcData from './static';
import { decodeLatestSubstrate, defaultValues, toV6 } from '../util/testUtil';
describe('MetadataV2', () => {
describe('MetadataV2', (): void => {
decodeLatestSubstrate(2, rpcData, latestSubstrate);
toV6(2, rpcData);
+20 -20
View File
@@ -20,7 +20,7 @@ import { StorageFunctionMetadata } from './Storage';
* The definition of a module in the system
*/
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -33,35 +33,35 @@ export class ModuleMetadata extends Struct {
/**
* @description the module calls
*/
get calls (): Option<Vector<FunctionMetadata>> {
public get calls (): Option<Vector<FunctionMetadata>> {
return this.get('calls') as Option<Vector<FunctionMetadata>>;
}
/**
* @description the module events
*/
get events (): Option<Vector<EventMetadata>> {
public get events (): Option<Vector<EventMetadata>> {
return this.get('events') as Option<Vector<EventMetadata>>;
}
/**
* @description the module name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageFunctionMetadata>> {
public get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
@@ -72,7 +72,7 @@ export class ModuleMetadata extends Struct {
* The runtime metadata as a decoded structure
*/
export default class MetadataV2 extends Struct implements MetadataInterface<ModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
modules: Vector.with(ModuleMetadata)
}, value);
@@ -81,35 +81,35 @@ export default class MetadataV2 extends Struct implements MetadataInterface<Modu
/**
* @description The associated modules for this structure
*/
get modules (): Vector<ModuleMetadata> {
public get modules (): Vector<ModuleMetadata> {
return this.get('modules') as Vector<ModuleMetadata>;
}
private get callNames () {
return this.modules.map((mod) =>
private get callNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
: mod.calls.unwrap().map((fn): string[] =>
fn.args.map((arg): string => arg.type.toString())
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
private get eventNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
: mod.events.unwrap().map((event): string[] =>
event.args.map((arg): string => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
private get storageNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) =>
: mod.storage.unwrap().map((fn): string[] =>
fn.type.isMap
? [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()]
: [fn.type.asType.toString()]
@@ -120,7 +120,7 @@ export default class MetadataV2 extends Struct implements MetadataInterface<Modu
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.callNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+25 -25
View File
@@ -22,7 +22,7 @@ export {
};
export class MapType extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
key: Type,
value: Type,
@@ -33,27 +33,27 @@ export class MapType extends Struct {
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
public get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
public get value (): Type {
return this.get('value') as Type;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
public get isLinked (): boolean {
return (this.get('isLinked') as Bool).valueOf();
}
}
export class StorageFunctionType extends Enum {
constructor (value?: any, index?: number) {
public constructor (value?: any, index?: number) {
super({
PlainType,
MapType
@@ -63,7 +63,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
public get asMap (): MapType {
assert(this.isMap, `Cannot convert '${this.type}' via asMap`);
return this.value as MapType;
@@ -72,7 +72,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
public get asType (): PlainType {
assert(this.isPlainType, `Cannot convert '${this.type}' via asType`);
return this.value as PlainType;
@@ -81,21 +81,21 @@ export class StorageFunctionType extends Enum {
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
public get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description `true` if the storage entry is a plain type
*/
get isPlainType (): boolean {
public get isPlainType (): boolean {
return this.toNumber() === 0;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
if (this.isMap) {
if (this.asMap.isLinked) {
return `(${this.asMap.value.toString()}, Linkage<${this.asMap.key.toString()}>)`;
@@ -108,13 +108,13 @@ export class StorageFunctionType extends Enum {
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
export interface StorageFunctionMetadataValue {
name: string | Text;
modifier: StorageFunctionModifier | AnyNumber;
type: StorageFunctionType;
fallback: Bytes;
documentation: Vector<Text> | string[];
}
/**
* @name ModuleMetadata
@@ -122,7 +122,7 @@ export type StorageFunctionMetadataValue = {
* The definition of a storage function
*/
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
public constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
@@ -136,14 +136,14 @@ export class StorageFunctionMetadata extends Struct {
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
public get default (): Bytes {
return this.fallback;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -151,35 +151,35 @@ export class StorageFunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The [[Bytes]] fallback default
*/
get fallback (): Bytes {
public get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[MetadataArgument]] for arguments
*/
get modifier (): StorageFunctionModifier {
public get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The call name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
public get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV2, ModuleMetadata as ModuleMetadataV2 } from './Metadata';
import MetadataV2, { ModuleMetadata as ModuleMetadataV2 } from './Metadata';
export default MetadataV2;
@@ -6,7 +6,7 @@ import latestSubstrate from './latest.substrate.v3.json';
import rpcData from './static';
import { decodeLatestSubstrate, defaultValues, toV6 } from '../util/testUtil';
describe('MetadataV3', () => {
describe('MetadataV3', (): void => {
decodeLatestSubstrate(3, rpcData, latestSubstrate);
toV6(3, rpcData);
+20 -20
View File
@@ -20,7 +20,7 @@ import { StorageFunctionMetadata } from './Storage';
* The definition of a module in the system
*/
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -33,35 +33,35 @@ export class ModuleMetadata extends Struct {
/**
* @description the module calls
*/
get calls (): Option<Vector<FunctionMetadata>> {
public get calls (): Option<Vector<FunctionMetadata>> {
return this.get('calls') as Option<Vector<FunctionMetadata>>;
}
/**
* @description the module events
*/
get events (): Option<Vector<EventMetadata>> {
public get events (): Option<Vector<EventMetadata>> {
return this.get('events') as Option<Vector<EventMetadata>>;
}
/**
* @description the module name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageFunctionMetadata>> {
public get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
@@ -72,7 +72,7 @@ export class ModuleMetadata extends Struct {
* The runtime metadata as a decoded structure
*/
export default class MetadataV3 extends Struct implements MetadataInterface<ModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
modules: Vector.with(ModuleMetadata)
}, value);
@@ -81,35 +81,35 @@ export default class MetadataV3 extends Struct implements MetadataInterface<Modu
/**
* @description The associated modules for this structure
*/
get modules (): Vector<ModuleMetadata> {
public get modules (): Vector<ModuleMetadata> {
return this.get('modules') as Vector<ModuleMetadata>;
}
private get callNames () {
return this.modules.map((mod) =>
private get callNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
: mod.calls.unwrap().map((fn): string[] =>
fn.args.map((arg): string => arg.type.toString())
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
private get eventNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
: mod.events.unwrap().map((event): string[] =>
event.args.map((arg): string => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
private get storageNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) => {
: mod.storage.unwrap().map((fn): string[] => {
if (fn.type.isMap) {
return [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()];
} else if (fn.type.isDoubleMap) {
@@ -124,7 +124,7 @@ export default class MetadataV3 extends Struct implements MetadataInterface<Modu
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.callNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+28 -28
View File
@@ -26,7 +26,7 @@ export {
};
export class DoubleMapType extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
key1: Type,
key2: Type,
@@ -38,34 +38,34 @@ export class DoubleMapType extends Struct {
/**
* @description The mapped key as [[Type]]
*/
get key1 (): Type {
public get key1 (): Type {
return this.get('key1') as Type;
}
/**
* @description The mapped key as [[Type]]
*/
get key2 (): Type {
public get key2 (): Type {
return this.get('key2') as Type;
}
/**
* @description The hashing algorithm used to hash key2, as [[Text]]
*/
get key2Hasher (): Text {
public get key2Hasher (): Text {
return this.get('key2Hasher') as Text;
}
/**
* @description The mapped key as [[Type]]
*/
get value (): Type {
public get value (): Type {
return this.get('value') as Type;
}
}
export class StorageFunctionType extends Enum {
constructor (value?: any, index?: number) {
public constructor (value?: any, index?: number) {
super({
PlainType,
MapType,
@@ -76,7 +76,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asDoubleMap (): DoubleMapType {
public get asDoubleMap (): DoubleMapType {
assert(this.isDoubleMap, `Cannot convert '${this.type}' via asDoubleMap`);
return this.value as DoubleMapType;
@@ -85,7 +85,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
public get asMap (): MapType {
assert(this.isMap, `Cannot convert '${this.type}' via asMap`);
return this.value as MapType;
@@ -94,7 +94,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
public get asType (): PlainType {
assert(this.isPlainType, `Cannot convert '${this.type}' via asType`);
return this.value as PlainType;
@@ -103,28 +103,28 @@ export class StorageFunctionType extends Enum {
/**
* @description `true` if the storage entry is a doublemap
*/
get isDoubleMap (): boolean {
public get isDoubleMap (): boolean {
return this.toNumber() === 2;
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
public get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description `true` if the storage entry is a plain type
*/
get isPlainType (): boolean {
public get isPlainType (): boolean {
return this.toNumber() === 0;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
if (this.isDoubleMap) {
return `DoubleMap<${this.asDoubleMap.toString()}>`;
}
@@ -141,13 +141,13 @@ export class StorageFunctionType extends Enum {
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
export interface StorageFunctionMetadataValue {
name: string | Text;
modifier: StorageFunctionModifier | AnyNumber;
type: StorageFunctionType;
fallback: Bytes;
documentation: Vector<Text> | string[];
}
/**
* @name StorageFunctionMetadata
@@ -155,7 +155,7 @@ export type StorageFunctionMetadataValue = {
* The definition of a storage function
*/
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
public constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
@@ -169,14 +169,14 @@ export class StorageFunctionMetadata extends Struct {
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
public get default (): Bytes {
return this.fallback;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -184,35 +184,35 @@ export class StorageFunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The [[Bytes]] fallback default
*/
get fallback (): Bytes {
public get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[MetadataArgument]] for arguments
*/
get modifier (): StorageFunctionModifier {
public get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The call name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
public get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV3, ModuleMetadata as ModuleMetadataV3 } from './Metadata';
import MetadataV3, { ModuleMetadata as ModuleMetadataV3 } from './Metadata';
export default MetadataV3;
+2 -1
View File
@@ -50,7 +50,8 @@ function toV4StorageFunction (storageFn: StorageFunctionMetadataV3): StorageFunc
*/
export default function toV4 (metadataV3: MetadataV3): MetadataV4 {
return new MetadataV4({
modules: metadataV3.modules.map((modul) => {
// FIXME, this needs typing, not any
modules: metadataV3.modules.map((modul): any => {
return {
name: modul.name,
prefix: modul.prefix,
@@ -6,7 +6,7 @@ import latestSubstrate from './latest.substrate.v4.json';
import rpcData from './static';
import { decodeLatestSubstrate, defaultValues, toV6 } from '../util/testUtil';
describe('MetadataV4', () => {
describe('MetadataV4', (): void => {
decodeLatestSubstrate(4, rpcData, latestSubstrate);
toV6(4, rpcData);
+20 -20
View File
@@ -20,7 +20,7 @@ import { StorageFunctionMetadata } from './Storage';
* The definition of a module in the system
*/
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -33,35 +33,35 @@ export class ModuleMetadata extends Struct {
/**
* @description the module calls
*/
get calls (): Option<Vector<FunctionMetadata>> {
public get calls (): Option<Vector<FunctionMetadata>> {
return this.get('calls') as Option<Vector<FunctionMetadata>>;
}
/**
* @description the module events
*/
get events (): Option<Vector<EventMetadata>> {
public get events (): Option<Vector<EventMetadata>> {
return this.get('events') as Option<Vector<EventMetadata>>;
}
/**
* @description the module name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageFunctionMetadata>> {
public get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
@@ -72,7 +72,7 @@ export class ModuleMetadata extends Struct {
* The runtime metadata as a decoded structure
*/
export default class MetadataV4 extends Struct implements MetadataInterface<ModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
modules: Vector.with(ModuleMetadata)
}, value);
@@ -81,35 +81,35 @@ export default class MetadataV4 extends Struct implements MetadataInterface<Modu
/**
* @description The associated modules for this structure
*/
get modules (): Vector<ModuleMetadata> {
public get modules (): Vector<ModuleMetadata> {
return this.get('modules') as Vector<ModuleMetadata>;
}
private get callNames () {
return this.modules.map((mod) =>
private get callNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
: mod.calls.unwrap().map((fn): string[] =>
fn.args.map((arg): string => arg.type.toString())
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
private get eventNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
: mod.events.unwrap().map((event): string[] =>
event.args.map((arg): string => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
private get storageNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) => {
: mod.storage.unwrap().map((fn): string[] => {
if (fn.type.isMap) {
return [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()];
} else if (fn.type.isDoubleMap) {
@@ -124,7 +124,7 @@ export default class MetadataV4 extends Struct implements MetadataInterface<Modu
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.callNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+34 -34
View File
@@ -23,7 +23,7 @@ export {
};
export class MapType extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
hasher: StorageHasher,
key: Type,
@@ -35,34 +35,34 @@ export class MapType extends Struct {
/**
* @description The hash algorithm used to hash keys, as [[StorageHasher]]
*/
get hasher (): StorageHasher {
public get hasher (): StorageHasher {
return this.get('hasher') as StorageHasher;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
public get isLinked (): boolean {
return (this.get('isLinked') as Bool).valueOf();
}
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
public get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
public get value (): Type {
return this.get('value') as Type;
}
}
export class DoubleMapType extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
hasher: StorageHasher,
key1: Type,
@@ -75,41 +75,41 @@ export class DoubleMapType extends Struct {
/**
* @description The hashing algorithm used to hash keys, as [[StorageHasher]]
*/
get hasher (): StorageHasher {
public get hasher (): StorageHasher {
return this.get('hasher') as StorageHasher;
}
/**
* @description The mapped key as [[Type]]
*/
get key1 (): Type {
public get key1 (): Type {
return this.get('key1') as Type;
}
/**
* @description The mapped key as [[Type]]
*/
get key2 (): Type {
public get key2 (): Type {
return this.get('key2') as Type;
}
/**
* @description The hashing algorithm used to hash key2, as [[Text]]
*/
get key2Hasher (): Text {
public get key2Hasher (): Text {
return this.get('key2Hasher') as Text;
}
/**
* @description The mapped key as [[Type]]
*/
get value (): Type {
public get value (): Type {
return this.get('value') as Type;
}
}
export class StorageFunctionType extends Enum {
constructor (value?: any, index?: number) {
public constructor (value?: any, index?: number) {
super({
PlainType,
MapType,
@@ -120,7 +120,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asDoubleMap (): DoubleMapType {
public get asDoubleMap (): DoubleMapType {
assert(this.isDoubleMap, `Cannot convert '${this.type}' via asDoubleMap`);
return this.value as DoubleMapType;
@@ -129,7 +129,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
public get asMap (): MapType {
assert(this.isMap, `Cannot convert '${this.type}' via asMap`);
return this.value as MapType;
@@ -138,7 +138,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
public get asType (): PlainType {
assert(this.isPlainType, `Cannot convert '${this.type}' via asType`);
return this.value as PlainType;
@@ -147,28 +147,28 @@ export class StorageFunctionType extends Enum {
/**
* @description `true` if the storage entry is a doublemap
*/
get isDoubleMap (): boolean {
public get isDoubleMap (): boolean {
return this.toNumber() === 2;
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
public get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description `true` if the storage entry is a plain type
*/
get isPlainType (): boolean {
public get isPlainType (): boolean {
return this.toNumber() === 0;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
if (this.isDoubleMap) {
return `DoubleMap<${this.asDoubleMap.value.toString()}>`;
}
@@ -185,13 +185,13 @@ export class StorageFunctionType extends Enum {
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
export interface StorageFunctionMetadataValue {
name: string | Text;
modifier: StorageFunctionModifier | AnyNumber;
type: StorageFunctionType;
fallback: Bytes;
documentation: Vector<Text> | string[];
}
/**
* @name StorageFunctionMetadata
@@ -199,7 +199,7 @@ export type StorageFunctionMetadataValue = {
* The definition of a storage function
*/
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
public constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
@@ -213,21 +213,21 @@ export class StorageFunctionMetadata extends Struct {
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
public get default (): Bytes {
return this.fallback;
}
/**
* @description The default value of the storage function
*/
get fallback (): Bytes {
public get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -235,28 +235,28 @@ export class StorageFunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The key name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The modifier
*/
get modifier (): StorageFunctionModifier {
public get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
public get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV4, ModuleMetadata as ModuleMetadataV4 } from './Metadata';
import MetadataV4, { ModuleMetadata as ModuleMetadataV4 } from './Metadata';
export default MetadataV4;
+2 -1
View File
@@ -60,7 +60,8 @@ function toV5StorageFunction (storageFn: StorageFunctionMetadataV4): StorageFunc
*/
export default function toV5 (metadataV4: MetadataV4): MetadataV5 {
return new MetadataV5({
modules: metadataV4.modules.map((modul) => {
// FIXME, this needs typing, not any
modules: metadataV4.modules.map((modul): any => {
return {
name: modul.name,
prefix: modul.prefix,
@@ -8,7 +8,7 @@ import polkadotData from './static.polkadot';
import substrateData from './static';
import { decodeLatestSubstrate, defaultValues, toV6 } from '../util/testUtil';
describe('MetadataV5 (substrate)', () => {
describe('MetadataV5 (substrate)', (): void => {
decodeLatestSubstrate(5, substrateData, substrateJson);
toV6(5, substrateData);
@@ -16,7 +16,7 @@ describe('MetadataV5 (substrate)', () => {
defaultValues(substrateData);
});
describe('MetadataV5 (polkadot)', () => {
describe('MetadataV5 (polkadot)', (): void => {
decodeLatestSubstrate(5, polkadotData, polkadotJson);
toV6(5, polkadotData);
+20 -20
View File
@@ -20,7 +20,7 @@ import { StorageFunctionMetadata } from './Storage';
* The definition of a module in the system
*/
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -33,35 +33,35 @@ export class ModuleMetadata extends Struct {
/**
* @description the module calls
*/
get calls (): Option<Vector<FunctionMetadata>> {
public get calls (): Option<Vector<FunctionMetadata>> {
return this.get('calls') as Option<Vector<FunctionMetadata>>;
}
/**
* @description the module events
*/
get events (): Option<Vector<EventMetadata>> {
public get events (): Option<Vector<EventMetadata>> {
return this.get('events') as Option<Vector<EventMetadata>>;
}
/**
* @description the module name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageFunctionMetadata>> {
public get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
@@ -72,7 +72,7 @@ export class ModuleMetadata extends Struct {
* The runtime metadata as a decoded structure
*/
export default class MetadataV5 extends Struct implements MetadataInterface<ModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
modules: Vector.with(ModuleMetadata)
}, value);
@@ -81,35 +81,35 @@ export default class MetadataV5 extends Struct implements MetadataInterface<Modu
/**
* @description The associated modules for this structure
*/
get modules (): Vector<ModuleMetadata> {
public get modules (): Vector<ModuleMetadata> {
return this.get('modules') as Vector<ModuleMetadata>;
}
private get callNames () {
return this.modules.map((mod) =>
private get callNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
: mod.calls.unwrap().map((fn): string[] =>
fn.args.map((arg): string => arg.type.toString())
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
private get eventNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
: mod.events.unwrap().map((event): string[] =>
event.args.map((arg): string => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
private get storageNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) => {
: mod.storage.unwrap().map((fn): string[] => {
if (fn.type.isMap) {
return [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()];
} else if (fn.type.isDoubleMap) {
@@ -124,7 +124,7 @@ export default class MetadataV5 extends Struct implements MetadataInterface<Modu
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.callNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+29 -29
View File
@@ -23,7 +23,7 @@ export {
};
export class DoubleMapType extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
hasher: StorageHasher,
key1: Type,
@@ -36,41 +36,41 @@ export class DoubleMapType extends Struct {
/**
* @description The hashing algorithm used to hash keys, as [[StorageHasher]]
*/
get hasher (): StorageHasher {
public get hasher (): StorageHasher {
return this.get('hasher') as StorageHasher;
}
/**
* @description The mapped key as [[Type]]
*/
get key1 (): Type {
public get key1 (): Type {
return this.get('key1') as Type;
}
/**
* @description The mapped key as [[Type]]
*/
get key2 (): Type {
public get key2 (): Type {
return this.get('key2') as Type;
}
/**
* @description The hashing algorithm used to hash key2, as [[StorageHasher]]
*/
get key2Hasher (): StorageHasher {
public get key2Hasher (): StorageHasher {
return this.get('key2Hasher') as StorageHasher;
}
/**
* @description The mapped key as [[Type]]
*/
get value (): Type {
public get value (): Type {
return this.get('value') as Type;
}
}
export class StorageFunctionType extends Enum {
constructor (value?: any, index?: number) {
public constructor (value?: any, index?: number) {
super({
PlainType,
MapType,
@@ -81,7 +81,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asDoubleMap (): DoubleMapType {
public get asDoubleMap (): DoubleMapType {
assert(this.isDoubleMap, `Cannot convert '${this.type}' via asDoubleMap`);
return this.value as DoubleMapType;
@@ -90,7 +90,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
public get asMap (): MapType {
assert(this.isMap, `Cannot convert '${this.type}' via asMap`);
return this.value as MapType;
@@ -99,7 +99,7 @@ export class StorageFunctionType extends Enum {
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
public get asType (): PlainType {
assert(this.isPlainType, `Cannot convert '${this.type}' via asType`);
return this.value as PlainType;
@@ -108,28 +108,28 @@ export class StorageFunctionType extends Enum {
/**
* @description `true` if the storage entry is a doublemap
*/
get isDoubleMap (): boolean {
public get isDoubleMap (): boolean {
return this.toNumber() === 2;
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
public get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description `true` if the storage entry is a plain type
*/
get isPlainType (): boolean {
public get isPlainType (): boolean {
return this.toNumber() === 0;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
if (this.isDoubleMap) {
return `DoubleMap<${this.asDoubleMap.value.toString()}>`;
}
@@ -146,13 +146,13 @@ export class StorageFunctionType extends Enum {
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
export interface StorageFunctionMetadataValue {
name: string | Text;
modifier: StorageFunctionModifier | AnyNumber;
type: StorageFunctionType;
fallback: Bytes;
documentation: Vector<Text> | string[];
}
/**
* @name StorageFunctionMetadata
@@ -160,7 +160,7 @@ export type StorageFunctionMetadataValue = {
* The definition of a storage function
*/
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
public constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
@@ -174,21 +174,21 @@ export class StorageFunctionMetadata extends Struct {
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
public get default (): Bytes {
return this.fallback;
}
/**
* @description The default value of the storage function
*/
get fallback (): Bytes {
public get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
@@ -196,28 +196,28 @@ export class StorageFunctionMetadata extends Struct {
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
public get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The key name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The modifier
*/
get modifier (): StorageFunctionModifier {
public get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
public get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV5, ModuleMetadata as ModuleMetadataV5 } from './Metadata';
import MetadataV5, { ModuleMetadata as ModuleMetadataV5 } from './Metadata';
export default MetadataV5;
+2 -1
View File
@@ -11,7 +11,8 @@ import MetadataV6 from '../v6';
*/
export default function toV6 (metadataV5: MetadataV5): MetadataV6 {
return new MetadataV6({
modules: metadataV5.modules.map((modul) => {
// FIXME, this needs typing, not any
modules: metadataV5.modules.map((modul): any => {
return {
name: modul.name,
prefix: modul.prefix,
+5 -5
View File
@@ -9,7 +9,7 @@ import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
export class ModuleConstantMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
type: Type,
@@ -21,28 +21,28 @@ export class ModuleConstantMetadata extends Struct {
/**
* @description The argument name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description The [[Type]]
*/
get type (): Type {
public get type (): Type {
return this.get('type') as Type;
}
/**
* @description The value as [[Bytes]]
*/
get value (): Bytes {
public get value (): Bytes {
return this.get('value') as Bytes;
}
/**
* @description The documentation
*/
get documentation (): Vector<Text> {
public get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
}
@@ -6,7 +6,7 @@ import substrateJson from './latest.substrate.v6.json';
import substrateData from './static';
import { decodeLatestSubstrate, defaultValues, toV6 } from '../util/testUtil';
describe('MetadataV6 (substrate)', () => {
describe('MetadataV6 (substrate)', (): void => {
decodeLatestSubstrate(6, substrateData, substrateJson);
toV6(6, substrateData);
+24 -24
View File
@@ -21,7 +21,7 @@ import { StorageEntryMetadata } from './Storage';
* The definition of a module in the system
*/
export class ModuleMetadata extends Struct {
constructor (value?: any) {
public constructor (value?: any) {
super({
name: Text,
prefix: Text,
@@ -35,42 +35,42 @@ export class ModuleMetadata extends Struct {
/**
* @description the module calls
*/
get calls (): Option<Vector<FunctionMetadata>> {
public get calls (): Option<Vector<FunctionMetadata>> {
return this.get('calls') as Option<Vector<FunctionMetadata>>;
}
/**
* @description the module constants
*/
get constants (): Vector<ModuleConstantMetadata> {
public get constants (): Vector<ModuleConstantMetadata> {
return this.get('constants') as Vector<ModuleConstantMetadata>;
}
/**
* @description the module events
*/
get events (): Option<Vector<EventMetadata>> {
public get events (): Option<Vector<EventMetadata>> {
return this.get('events') as Option<Vector<EventMetadata>>;
}
/**
* @description the module name
*/
get name (): Text {
public get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
public get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageEntryMetadata>> {
public get storage (): Option<Vector<StorageEntryMetadata>> {
return this.get('storage') as Option<Vector<StorageEntryMetadata>>;
}
}
@@ -81,7 +81,7 @@ export class ModuleMetadata extends Struct {
* The runtime metadata as a decoded structure
*/
export default class MetadataV6 extends Struct implements MetadataInterface<ModuleMetadata> {
constructor (value?: any) {
public constructor (value?: any) {
super({
modules: Vector.with(ModuleMetadata)
}, value);
@@ -90,43 +90,43 @@ export default class MetadataV6 extends Struct implements MetadataInterface<Modu
/**
* @description The associated modules for this structure
*/
get modules (): Vector<ModuleMetadata> {
public get modules (): Vector<ModuleMetadata> {
return this.get('modules') as Vector<ModuleMetadata>;
}
private get callNames () {
return this.modules.map((mod) =>
private get callNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
: mod.calls.unwrap().map((fn): string[] =>
fn.args.map((arg): string => arg.type.toString())
)
);
}
private get constantNames () {
return this.modules.map((mod) =>
mod.constants.map((c) =>
private get constantNames (): string[][] {
return this.modules.map((mod): string[] =>
mod.constants.map((c): string =>
c.type.toString()
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
private get eventNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
: mod.events.unwrap().map((event): string[] =>
event.args.map((arg): string => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
private get storageNames (): string[][][] {
return this.modules.map((mod): string[][] =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) => {
: mod.storage.unwrap().map((fn): string[] => {
if (fn.type.isMap) {
return [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()];
} else if (fn.type.isDoubleMap) {
@@ -141,7 +141,7 @@ export default class MetadataV6 extends Struct implements MetadataInterface<Modu
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
public getUniqTypes (throwError: boolean): string[] {
const types = flattenUniq([this.callNames, this.constantNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
+1 -1
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { default as MetadataV6, ModuleMetadata as ModuleMetadataV6 } from './Metadata';
import MetadataV6, { ModuleMetadata as ModuleMetadataV6 } from './Metadata';
export default MetadataV6;
+16 -16
View File
@@ -5,7 +5,7 @@
import { u8aConcat, u8aToHex } from '@polkadot/util';
import Compact from './Compact';
import { AnyJsonArray, Codec } from '../types';
import { AnyJson, AnyJsonArray, Codec } from '../types';
import { compareArray } from './utils';
/**
@@ -19,15 +19,15 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
/**
* @description Checks if the value is an empty value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.length === 0;
}
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
return this.reduce((total, raw) => {
public get encodedLength (): number {
return this.reduce((total, raw): number => {
return total + raw.encodedLength;
}, Compact.encodeU8a(this.length).length);
}
@@ -35,7 +35,7 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
/**
* @description The length of the value
*/
get length (): number {
public get length (): number {
// only included here since we ignore inherited docs
return super.length;
}
@@ -43,29 +43,29 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return compareArray(this, other);
}
/**
* @description Converts the Object to an standard JavaScript Array
*/
toArray (): Array<T> {
public toArray (): T[] {
return Array.from(this);
}
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
return u8aToHex(this.toU8a());
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): AnyJsonArray {
return this.map((entry) =>
public toJSON (): AnyJsonArray {
return this.map((entry): AnyJson =>
entry.toJSON()
);
}
@@ -78,9 +78,9 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
// Overwrite the default toString representation of Array.
const data = this.map((entry) =>
const data = this.map((entry): string =>
entry.toString()
);
@@ -91,8 +91,8 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
const encoded = this.map((entry) =>
public toU8a (isBare?: boolean): Uint8Array {
const encoded = this.map((entry): Uint8Array =>
entry.toU8a(isBare)
);
@@ -113,7 +113,7 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
* @param callbackfn The filter function
* @param thisArg The `this` object to apply the result to
*/
filter (callbackfn: (value: T, index: number, array: Array<T>) => any, thisArg?: any): Array<T> {
public filter (callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[] {
return this.toArray().filter(callbackfn, thisArg);
}
@@ -122,7 +122,7 @@ export default abstract class AbstractArray<T extends Codec> extends Array<T> im
* @param callbackfn The mapping function
* @param thisArg The `this` onject to apply the result to
*/
map<U> (callbackfn: (value: T, index: number, array: Array<T>) => U, thisArg?: any): Array<U> {
public map<U> (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[] {
return this.toArray().map(callbackfn, thisArg);
}
}
+12 -9
View File
@@ -20,10 +20,12 @@ export const DEFAULT_UINT_BITS = 64;
// - Apart from encoding/decoding we don't actually keep check on the sizes, is this good enough?
export default abstract class AbstractInt extends BN implements Codec {
protected _bitLength: UIntBitLength;
private _isHexJson: boolean;
private _isNegative: boolean;
constructor (
public constructor (
isNegative: boolean,
value: AnyNumber = 0,
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = true) {
@@ -36,7 +38,7 @@ export default abstract class AbstractInt extends BN implements Codec {
this._isNegative = isNegative;
}
static decodeAbstracInt (value: AnyNumber, bitLength: UIntBitLength, isNegative: boolean): string {
public static decodeAbstracInt (value: AnyNumber, bitLength: UIntBitLength, isNegative: boolean): string {
// This function returns a string, which will be passed in the BN
// constructor. It would be ideal to actually return a BN, but there's a
// bug: https://github.com/indutny/bn.js/issues/206.
@@ -63,28 +65,29 @@ export default abstract class AbstractInt extends BN implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return this._bitLength / 8;
}
/**
* @description Checks if the value is a zero value (align elsewhere)
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.isZero();
}
/**
* @description Returns the number of bits in the value
*/
bitLength (): UIntBitLength {
public bitLength (): UIntBitLength {
return this._bitLength;
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public eq (other?: any): boolean {
// Here we are actually overriding the built-in .eq to take care of both
// number and BN inputs (no `.eqn` needed) - numbers will be converted
return super.eq(
@@ -97,7 +100,7 @@ export default abstract class AbstractInt extends BN implements Codec {
/**
* @description Returns the BN representation of the number. (Compatibility)
*/
toBn (): BN {
public toBn (): BN {
return this;
}
@@ -109,7 +112,7 @@ export default abstract class AbstractInt extends BN implements Codec {
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): any {
public toJSON (): any {
// FIXME this return type should by string | number, but BN's return type
// is string.
// Maximum allowed integer for JS is 2^53 - 1, set limit at 52
@@ -127,7 +130,7 @@ export default abstract class AbstractInt extends BN implements Codec {
* @description Returns the string representation of the value
* @param base The base to use for the conversion
*/
toString (base?: number): string {
public toString (base?: number): string {
// only included here since we do not inherit docs
return super.toString(base);
}
+1 -1
View File
@@ -9,7 +9,7 @@
export default class Base<T> {
protected raw: T;
constructor (value?: any) {
public constructor (value?: any) {
this.raw = value;
}
}
+27 -27
View File
@@ -11,9 +11,9 @@ import BlockNumber from '../type/BlockNumber';
import Compact from './Compact';
import UInt from './UInt';
describe('Compact', () => {
describe('encodeU8a', () => {
it('encodes short u8', () => {
describe('Compact', (): void => {
describe('encodeU8a', (): void => {
it('encodes short u8', (): void => {
expect(
Compact.encodeU8a(18)
).toEqual(
@@ -21,7 +21,7 @@ describe('Compact', () => {
);
});
it('encodes max u8 values', () => {
it('encodes max u8 values', (): void => {
expect(
Compact.encodeU8a(new UInt(63))
).toEqual(
@@ -29,7 +29,7 @@ describe('Compact', () => {
);
});
it('encodes basic u16 value', () => {
it('encodes basic u16 value', (): void => {
expect(
Compact.encodeU8a(511)
).toEqual(
@@ -37,7 +37,7 @@ describe('Compact', () => {
);
});
it('encodes basic ua6 (not at edge)', () => {
it('encodes basic ua6 (not at edge)', (): void => {
expect(
Compact.encodeU8a(111)
).toEqual(
@@ -45,7 +45,7 @@ describe('Compact', () => {
);
});
it('encodes basic u32 values (short)', () => {
it('encodes basic u32 values (short)', (): void => {
expect(
Compact.encodeU8a(0xffff)
).toEqual(
@@ -53,7 +53,7 @@ describe('Compact', () => {
);
});
it('encodes basic u32 values (full)', () => {
it('encodes basic u32 values (full)', (): void => {
expect(
Compact.encodeU8a(0xfffffff9)
).toEqual(
@@ -61,7 +61,7 @@ describe('Compact', () => {
);
});
it('encondes a large balance', () => {
it('encondes a large balance', (): void => {
expect(
Compact.encodeU8a(new Balance('0x5af3107a4000'))
).toEqual(
@@ -73,86 +73,86 @@ describe('Compact', () => {
});
});
describe('decodeU8a', () => {
it('decoded u8 value', () => {
describe('decodeU8a', (): void => {
it('decoded u8 value', (): void => {
expect(
Compact.decodeU8a(new Uint8Array([0b11111100]), 32)
).toEqual([1, new BN(63)]);
});
it('decodes from same u16 encoded value', () => {
it('decodes from same u16 encoded value', (): void => {
expect(
Compact.decodeU8a(new Uint8Array([0b11111101, 0b00000111]), 32)
).toEqual([2, new BN(511)]);
});
it('decodes from same u32 encoded value (short)', () => {
it('decodes from same u32 encoded value (short)', (): void => {
expect(
Compact.decodeU8a(new Uint8Array([254, 255, 3, 0]), 32)
).toEqual([4, new BN(0xffff)]);
});
it('decodes from same u32 encoded value (full)', () => {
it('decodes from same u32 encoded value (full)', (): void => {
expect(
Compact.decodeU8a(new Uint8Array([3, 249, 255, 255, 255]), 32)
).toEqual([5, new BN(0xfffffff9)]);
});
it('decodes from same u32 as u64 encoded value (full, default)', () => {
it('decodes from same u32 as u64 encoded value (full, default)', (): void => {
expect(
Compact.decodeU8a(new Uint8Array([3, 249, 255, 255, 255]), 64)
).toEqual([5, new BN(0xfffffff9)]);
});
});
describe('constructor', () => {
it('has the correct bitLength for constructor values (BlockNumber)', () => {
describe('constructor', (): void => {
it('has the correct bitLength for constructor values (BlockNumber)', (): void => {
expect(
new Compact(BlockNumber, 0xfffffff9).bitLength()
).toEqual(64);
});
it('has the correct encodedLength for constructor values (BlockNumber)', () => {
it('has the correct encodedLength for constructor values (BlockNumber)', (): void => {
expect(
new Compact(BlockNumber, 0xfffffff9).encodedLength
).toEqual(5);
});
it('has the correct encodedLength for constructor values (u32)', () => {
it('has the correct encodedLength for constructor values (u32)', (): void => {
expect(
new Compact(U32, 0xffff9).encodedLength
).toEqual(4);
});
it('constructs properly via U8a as U32', () => {
it('constructs properly via U8a as U32', (): void => {
expect(
new Compact(U32, new Uint8Array([254, 255, 3, 0])).toNumber()
).toEqual(new BN(0xffff).toNumber());
});
it('constructs properly via number as Moment', () => {
it('constructs properly via number as Moment', (): void => {
expect(
new Compact(Moment, 1537968546).toString().startsWith('Wed Sep 26 2018') // The time depends on the timezone this test is run in
).toBe(true);
});
});
describe('utils', () => {
it('compares against another Compact', () => {
describe('utils', (): void => {
it('compares against another Compact', (): void => {
expect(new Compact(U32, 12345).eq(new Compact(U32, 12345))).toBe(true);
});
it('compares against a primitive', () => {
it('compares against a primitive', (): void => {
expect(new Compact(U32, 12345).eq(12345)).toBe(true);
});
it('unwraps to the wrapped value', () => {
it('unwraps to the wrapped value', (): void => {
expect(new Compact(U32, 12345).unwrap() instanceof U32).toBe(true);
});
});
describe('helpers', () => {
it('correctly adds the length prefix', () => {
describe('helpers', (): void => {
it('correctly adds the length prefix', (): void => {
expect(
Compact.addLengthPrefix(Uint8Array.from([12, 13]))
).toEqual(Uint8Array.from([2 << 2, 12, 13]));
+23 -20
View File
@@ -21,13 +21,13 @@ import UInt from './UInt';
* a number and making the compact representation thereof
*/
export default class Compact extends Base<UInt | Moment> implements Codec {
constructor (Type: Constructor<UInt | Moment>, value: Compact | AnyNumber = 0) {
public constructor (Type: Constructor<UInt | Moment>, value: Compact | AnyNumber = 0) {
super(Compact.decodeCompact(Type, value));
}
static with (Type: Constructor<UInt | Moment>): Constructor<Compact> {
public static with (Type: Constructor<UInt | Moment>): Constructor<Compact> {
return class extends Compact {
constructor (value?: any) {
public constructor (value?: any) {
super(Type, value);
}
};
@@ -38,17 +38,19 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
*
* @param u8a - The Uint8Array to be prefixed
*/
static addLengthPrefix = compactAddLength;
static decodeU8a = compactFromU8a;
static encodeU8a = compactToU8a;
public static addLengthPrefix = compactAddLength;
static stripLengthPrefix (u8a: Uint8Array, bitLength: UIntBitLength = DEFAULT_BITLENGTH): Uint8Array {
public static decodeU8a = compactFromU8a;
public static encodeU8a = compactToU8a;
public static stripLengthPrefix (u8a: Uint8Array, bitLength: UIntBitLength = DEFAULT_BITLENGTH): Uint8Array {
const [, value] = compactStripLength(u8a, bitLength);
return value;
}
static decodeCompact (Type: Constructor<UInt | Moment>, value: Compact | AnyNumber): Moment | UInt {
public static decodeCompact (Type: Constructor<UInt | Moment>, value: Compact | AnyNumber): Moment | UInt {
if (value instanceof Compact) {
return new Type(value.raw);
} else if (isString(value)) {
@@ -69,28 +71,28 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return this.toU8a().length;
}
/**
* @description Checks if the value is an empty value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.raw.isEmpty;
}
/**
* @description Returns the number of bits in the value
*/
bitLength (): UIntBitLength {
public bitLength (): UIntBitLength {
return this.raw.bitLength();
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return this.raw.eq(
other instanceof Compact
? other.raw
@@ -101,42 +103,42 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
/**
* @description Returns the BN representation of the number
*/
toBn (): BN {
public toBn (): BN {
return this.raw.toBn();
}
/**
* @description Returns a hex string representation of the value
*/
toHex (isLe?: boolean): any {
public toHex (isLe?: boolean): any {
return this.raw.toHex(isLe);
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): string | number {
public toJSON (): string | number {
return this.raw.toJSON();
}
/**
* @description Returns the number representation for the value
*/
toNumber (): number {
public toNumber (): number {
return this.raw.toNumber();
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `Compact<${this.raw.toRawType()}>`;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return this.raw.toString();
}
@@ -144,14 +146,15 @@ export default class Compact extends Base<UInt | Moment> implements Codec {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
return Compact.encodeU8a(this.raw.toBn());
}
/**
* @description Returns the embedded [[UInt]] or [[Moment]] value
*/
unwrap (): UInt | Moment {
public unwrap (): UInt | Moment {
return this.raw;
}
}
+40 -40
View File
@@ -7,9 +7,9 @@ import Null from '../primitive/Null';
import Text from '../primitive/Text';
import U32 from '../primitive/U32';
describe('Enum', () => {
describe('typed enum (previously EnumType)', () => {
it('provides a clean toString() (value)', () => {
describe('Enum', (): void => {
describe('typed enum (previously EnumType)', (): void => {
it('provides a clean toString() (value)', (): void => {
expect(
new Enum(
{ Text, U32 },
@@ -18,7 +18,7 @@ describe('Enum', () => {
).toEqual('12');
});
it('provides a clean toString() (enum)', () => {
it('provides a clean toString() (enum)', (): void => {
expect(
new Enum(
{ Text, U32 },
@@ -27,16 +27,16 @@ describe('Enum', () => {
).toEqual('{"U32":3289352}');
});
it('decodes from a JSON input (lowercase)', () => {
it('decodes from a JSON input (lowercase)', (): void => {
expect(
new Enum(
{ Text, U32 },
{ 'text': 'some text value' }
{ text: 'some text value' }
).value.toString()
).toEqual('some text value');
});
it('decodes from hex', () => {
it('decodes from hex', (): void => {
expect(
new Enum(
{ Text, U32 },
@@ -45,16 +45,16 @@ describe('Enum', () => {
).toEqual('4660'); // 0x1234 in decimal
});
it('decodes from a JSON input (mixed case)', () => {
it('decodes from a JSON input (mixed case)', (): void => {
expect(
new Enum(
{ Text, U32 },
{ 'U32': 42 }
{ U32: 42 }
).value.toString()
).toEqual('42');
});
it('decodes from JSON string', () => {
it('decodes from JSON string', (): void => {
expect(
new Enum(
{ Null, U32 },
@@ -63,20 +63,20 @@ describe('Enum', () => {
).toEqual('Null');
});
it('has correct isXyz/asXyz (Enum.with)', () => {
const test = new (Enum.with({ First: Text, Second: U32, Third: U32 }))({ 'Second': 42 }) as any as { isSecond: boolean, asSecond: U32, asThird: never };
it('has correct isXyz/asXyz (Enum.with)', (): void => {
const test = new (Enum.with({ First: Text, Second: U32, Third: U32 }))({ Second: 42 }) as any as { isSecond: boolean; asSecond: U32; asThird: never };
expect(test.isSecond).toEqual(true);
expect(test.asSecond.toNumber()).toEqual(42);
expect(() => test.asThird).toThrow(/Cannot convert Second via asThird/);
expect((): never => test.asThird).toThrow(/Cannot convert Second via asThird/);
});
it('stringifies with custom types', () => {
it('stringifies with custom types', (): void => {
class A extends Null { }
class B extends Null { }
class C extends Null { }
class Test extends Enum {
constructor (value?: string, index?: number) {
public constructor (value?: string, index?: number) {
super({
a: A,
b: B,
@@ -88,7 +88,7 @@ describe('Enum', () => {
expect(new Test().toJSON()).toEqual({ a: null });
});
it('creates via with', () => {
it('creates via with', (): void => {
class A extends Null { }
class B extends U32 { }
class C extends Null { }
@@ -101,7 +101,7 @@ describe('Enum', () => {
// We are currently not using this approach, none of the types in Substrate currently
// have any overrides. Instead of trying to support it (just-in-case), rather have it
// removed to simplify the code - it can be pulled-back if needed
it.skip('allows checking against defined indexes', () => {
it.skip('allows checking against defined indexes', (): void => {
expect(
new Enum(
{ 1: Text, 5: U32 },
@@ -110,7 +110,7 @@ describe('Enum', () => {
).toEqual('Text');
});
it('allows accessing the type and value', () => {
it('allows accessing the type and value', (): void => {
const text = new Text('foo');
const enumType = new Enum(
{ Text, U32 },
@@ -121,19 +121,19 @@ describe('Enum', () => {
expect(enumType.value).toEqual(text);
});
describe('utils', () => {
describe('utils', (): void => {
const eqtest = new Enum(
{ U32, Text },
new Uint8Array([1, 3 << 2, 88, 89, 90])
);
it('compares against index', () => {
it('compares against index', (): void => {
expect(
eqtest.eq(1)
).toBe(true);
});
it('compares against values', () => {
it('compares against values', (): void => {
expect(
eqtest.eq('XYZ')
).toBe(true);
@@ -141,16 +141,16 @@ describe('Enum', () => {
});
});
describe('string-only construction (old Enum)', () => {
const testDecode = (type: string, input: any, expected: any) =>
it(`can decode from ${type}`, () => {
describe('string-only construction (old Enum)', (): void => {
const testDecode = (type: string, input: any, expected: any): void =>
it(`can decode from ${type}`, (): void => {
const e = new Enum(['foo', 'bar'], input);
expect(e.toString()).toBe(expected);
});
const testEncode = (to: 'toJSON' | 'toNumber' | 'toString' | 'toU8a', expected: any) =>
it(`can encode ${to}`, () => {
const testEncode = (to: 'toJSON' | 'toNumber' | 'toString' | 'toU8a', expected: any): void =>
it(`can encode ${to}`, (): void => {
const e = new Enum(['foo', 'bar'], 1);
expect(e[to]()).toEqual(expected);
@@ -169,56 +169,56 @@ describe('Enum', () => {
testEncode('toString', 'bar');
testEncode('toU8a', Uint8Array.from([1]));
it('provides a clean toString()', () => {
it('provides a clean toString()', (): void => {
expect(
new Enum(['foo', 'bar']).toString()
).toEqual('foo');
});
it('provides a clean toString() (enum)', () => {
it('provides a clean toString() (enum)', (): void => {
expect(
new Enum(['foo', 'bar'], new Enum(['foo', 'bar'], 1)).toNumber()
).toEqual(1);
});
it('converts to and from U8a', () => {
it('converts to and from U8a', (): void => {
expect(
new Enum(['foo', 'bar'], new Uint8Array([1])).toU8a()
).toEqual(new Uint8Array([1]));
});
it('converts from JSON', () => {
it('converts from JSON', (): void => {
expect(
new Enum(['foo', 'bar', 'baz', 'gaz', 'jaz'], 4).toNumber()
).toEqual(4);
});
it('has correct isXyz getters (Enum.with)', () => {
const test = new (Enum.with(['First', 'Second', 'Third']))('Second') as any as { isSecond: boolean, asSecond: never };
it('has correct isXyz getters (Enum.with)', (): void => {
const test = new (Enum.with(['First', 'Second', 'Third']))('Second') as any as { isSecond: boolean; asSecond: never };
expect(test.isSecond).toEqual(true);
});
describe('utils', () => {
it('compares agains the index value', () => {
describe('utils', (): void => {
it('compares agains the index value', (): void => {
expect(
new Enum(['foo', 'bar'], 1).eq(1)
).toBe(true);
});
it('compares agains the index value (false)', () => {
it('compares agains the index value (false)', (): void => {
expect(
new Enum(['foo', 'bar'], 1).eq(0)
).toBe(false);
});
it('compares agains the string value', () => {
it('compares agains the string value', (): void => {
expect(
new Enum(['foo', 'bar'], 1).eq('bar')
).toBe(true);
});
it('compares agains the string value (false)', () => {
it('compares agains the string value (false)', (): void => {
expect(
new Enum(['foo', 'bar'], 1).eq('foo')
).toBe(false);
@@ -226,14 +226,14 @@ describe('Enum', () => {
});
});
describe('toRawType', () => {
it('has a sane output for basic enums', () => {
describe('toRawType', (): void => {
it('has a sane output for basic enums', (): void => {
expect(
new Enum(['foo', 'bar']).toRawType()
).toEqual(JSON.stringify({ _enum: ['foo', 'bar'] }));
});
it('has a sane output for types enums', () => {
it('has a sane output for types enums', (): void => {
expect(
new Enum({ foo: Text, bar: U32 }).toRawType()
).toEqual(JSON.stringify({ _enum: { foo: 'Text', bar: 'u32' } }));
+40 -37
View File
@@ -9,16 +9,16 @@ import { assert, hexToU8a, isHex, isNumber, isObject, isString, isU8a, isUndefin
import Null from '../primitive/Null';
import Base from './Base';
type EnumConstructor<T = Codec> = { new(value?: any, index?: number): T };
interface EnumConstructor<T = Codec> {
new(value?: any, index?: number): T;
}
type TypesDef = {
[name: string]: Constructor
};
type TypesDef = Record<string, Constructor>;
type Decoded = {
index: number,
value: Codec
};
interface Decoded {
index: number;
value: Codec;
}
/**
* @name Enum
@@ -31,11 +31,14 @@ type Decoded = {
// - It should rather probably extend Enum instead of copying code
export default class Enum extends Base<Codec> implements Codec {
private _def: TypesDef;
private _index: number;
private _indexes: Array<number>;
private _indexes: number[];
private _isBasic: boolean;
constructor (def: TypesDef | Array<string>, value?: any, index?: number | Enum) {
public constructor (def: TypesDef | string[], value?: any, index?: number | Enum) {
const defInfo = Enum.extractDef(def);
const decoded = Enum.decodeEnum(defInfo.def, value, index);
@@ -43,11 +46,11 @@ export default class Enum extends Base<Codec> implements Codec {
this._def = defInfo.def;
this._isBasic = defInfo.isBasic;
this._indexes = Object.keys(defInfo.def).map((_, index) => index);
this._indexes = Object.keys(defInfo.def).map((_, index): number => index);
this._index = this._indexes.indexOf(decoded.index) || 0;
}
private static extractDef (def: TypesDef | Array<string>): { def: TypesDef, isBasic: boolean } {
private static extractDef (def: TypesDef | string[]): { def: TypesDef; isBasic: boolean } {
if (!Array.isArray(def)) {
return {
def,
@@ -56,11 +59,11 @@ export default class Enum extends Base<Codec> implements Codec {
}
return {
def: def.reduce((def, key) => {
def: def.reduce((def, key): TypesDef => {
def[key] = Null;
return def;
}, {} as TypesDef),
}, {} as unknown as TypesDef),
isBasic: true
};
}
@@ -100,10 +103,10 @@ export default class Enum extends Base<Codec> implements Codec {
return Enum.createValue(def, 0);
}
private static createViaJSON (def: TypesDef, key: string, value?: any) {
private static createViaJSON (def: TypesDef, key: string, value?: any): Decoded {
// JSON comes in the form of { "<type (lowercased)>": "<value for type>" }, here we
// additionally force to lower to ensure forward compat
const keys = Object.keys(def).map((k) => k.toLowerCase());
const keys = Object.keys(def).map((k): string => k.toLowerCase());
const keyLower = key.toLowerCase();
const index = keys.indexOf(keyLower);
@@ -123,12 +126,12 @@ export default class Enum extends Base<Codec> implements Codec {
};
}
static with (Types: TypesDef | Array<string>): EnumConstructor<Enum> {
public static with (Types: TypesDef | string[]): EnumConstructor<Enum> {
return class extends Enum {
constructor (value?: any, index?: number) {
public constructor (value?: any, index?: number) {
super(Types, value, index);
Object.keys(this._def).forEach((_key) => {
Object.keys(this._def).forEach((_key): void => {
const askey = `as${_key}`;
const iskey = `is${_key}`;
@@ -136,14 +139,14 @@ export default class Enum extends Base<Codec> implements Codec {
if (isUndefined((this as any)[iskey])) {
Object.defineProperty(this, iskey, {
enumerable: true,
get: () => this.type === _key
get: (): boolean => this.type === _key
});
}
if (isUndefined((this as any)[askey])) {
Object.defineProperty(this, askey, {
enumerable: true,
get: () => {
get: (): Codec => {
assert((this as any)[iskey], `Cannot convert ${this.type} via ${askey}`);
return this.value;
@@ -158,56 +161,56 @@ export default class Enum extends Base<Codec> implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return 1 + this.raw.encodedLength;
}
/**
* @description The index of the metadata value
*/
get index (): number {
public get index (): number {
return this._index;
}
/**
* @description Checks if the value is an empty value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.isEmpty;
}
/**
* @description Checks if the Enum points to a [[Null]] type
*/
get isNone (): boolean {
public get isNone (): boolean {
return this.isNull;
}
/**
* @description Checks if the Enum points to a [[Null]] type (deprecated, use isNone)
*/
get isNull (): boolean {
public get isNull (): boolean {
return this.raw instanceof Null;
}
/**
* @description The name of the type this enum value represents
*/
get type (): string {
public get type (): string {
return Object.keys(this._def)[this._index];
}
/**
* @description The value of the enum
*/
get value (): Codec {
public get value (): Codec {
return this.raw;
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
// cater for the case where we only pass the enum index
if (isNumber(other)) {
return this.toNumber() === other;
@@ -222,14 +225,14 @@ export default class Enum extends Base<Codec> implements Codec {
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
return u8aToHex(this.toU8a());
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): AnyJson {
public toJSON (): AnyJson {
return this._isBasic
? this._index
: { [this.type]: this.raw.toJSON() };
@@ -238,21 +241,21 @@ export default class Enum extends Base<Codec> implements Codec {
/**
* @description Returns the number representation for the value
*/
toNumber (): number {
public toNumber (): number {
return this._index;
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
const _enum = this._isBasic
? Object.keys(this._def)
: Object.entries(this._def).reduce((result, [key, Type]) => {
: Object.entries(this._def).reduce((result, [key, Type]): Record<string, string> => {
result[key] = new Type().toRawType();
return result;
}, {} as { [index: string]: string });
}, {} as unknown as Record<string, string>);
return JSON.stringify({ _enum });
}
@@ -260,7 +263,7 @@ export default class Enum extends Base<Codec> implements Codec {
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return this.isNull
? this.type
: JSON.stringify(this.toJSON());
@@ -270,7 +273,7 @@ export default class Enum extends Base<Codec> implements Codec {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
public toU8a (isBare?: boolean): Uint8Array {
const index = this._indexes[this._index];
return u8aConcat(
+8 -8
View File
@@ -4,39 +4,39 @@
import Int from './Int';
describe('Int', () => {
it('provides a toBn interface', () => {
describe('Int', (): void => {
it('provides a toBn interface', (): void => {
expect(
new Int(-1234).toBn().toNumber()
).toEqual(-1234);
});
it('provides a toNumber interface', () => {
it('provides a toNumber interface', (): void => {
expect(
new Int(-1234).toNumber()
).toEqual(-1234);
});
it('converts to Little Endian from the provided value', () => {
it('converts to Little Endian from the provided value', (): void => {
expect(
new Int(-1234).toU8a()
).toEqual(new Uint8Array([46, 251, 255, 255, 255, 255, 255, 255]));
});
it('converts to Little Endian from the provided value (bitLength)', () => {
it('converts to Little Endian from the provided value (bitLength)', (): void => {
expect(
new Int(-1234, 32).toU8a()
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
it('converts to hex/string', () => {
it('converts to hex/string', (): void => {
const i = new Int('0x12', 16);
expect(i.toHex()).toEqual('0x0012');
expect(i.toString()).toEqual('18');
});
it('converts to equivalents', () => {
it('converts to equivalents', (): void => {
const a = new Int('-123');
expect(
@@ -44,7 +44,7 @@ describe('Int', () => {
).toEqual(-123);
});
it('converts to JSON depending on flags', () => {
it('converts to JSON depending on flags', (): void => {
expect(new Int(0x12, 16).toJSON()).toEqual('0x0012');
expect(new Int(0x12, 16, false).toJSON()).toEqual(0x12);
});
+5 -4
View File
@@ -19,7 +19,7 @@ import AbstractInt, { DEFAULT_UINT_BITS, UIntBitLength } from './AbstractInt';
* @noInheritDoc
*/
export default class Int extends AbstractInt {
constructor (
public constructor (
value: AnyNumber = 0,
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = true) {
super(
@@ -33,7 +33,7 @@ export default class Int extends AbstractInt {
/**
* @description Returns a hex string representation of the value
*/
toHex (isLe: boolean = false): string {
public toHex (isLe: boolean = false): string {
return bnToHex(this, {
bitLength: this._bitLength,
isLe,
@@ -44,7 +44,7 @@ export default class Int extends AbstractInt {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `i${this._bitLength}`;
}
@@ -52,7 +52,8 @@ export default class Int extends AbstractInt {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
return bnToU8a(this, {
bitLength: this._bitLength,
isLe: true,
+7 -7
View File
@@ -5,35 +5,35 @@
import { Struct, Option, Tuple, Vector } from '.';
import { Constructor, Codec } from '../types';
type TypeWithValues = [Constructor, Array<any>];
type TypeWithValues = [Constructor, any[]];
export default class Linkage<T extends Codec> extends Struct {
constructor (Type: Constructor, value?: any) {
public constructor (Type: Constructor, value?: any) {
super({
previous: Option.with(Type),
next: Option.with(Type)
}, value);
}
static withKey<O extends Codec> (Type: Constructor): Constructor<Linkage<O>> {
public static withKey<O extends Codec> (Type: Constructor): Constructor<Linkage<O>> {
return class extends Linkage<O> {
constructor (value?: any) {
public constructor (value?: any) {
super(Type, value);
}
};
}
get previous (): Option<T> {
public get previous (): Option<T> {
return this.get('previous') as Option<T>;
}
get next (): Option<T> {
public get next (): Option<T> {
return this.get('next') as Option<T>;
}
}
export class LinkageResult extends Tuple {
constructor ([TypeKey, keys]: TypeWithValues, [TypeValue, values]: TypeWithValues) {
public constructor ([TypeKey, keys]: TypeWithValues, [TypeValue, values]: TypeWithValues) {
super({
Keys: Vector.with(TypeKey),
Values: Vector.with(TypeValue)
+18 -18
View File
@@ -7,35 +7,35 @@ import Bytes from '../primitive/Bytes';
import U32 from '../primitive/U32';
import Text from '../primitive/Text';
const testDecode = (type: string, input: any, expected: any) =>
it(`can decode from ${type}`, () => {
const testDecode = (type: string, input: any, expected: any): void =>
it(`can decode from ${type}`, (): void => {
const o = new Option(Text, input);
expect(o.toString()).toBe(expected);
expect(o.isNone).toBe(!expected.length);
});
const testEncode = (to: string, expected: any) =>
it(`can encode ${to}`, () => {
const testEncode = (to: string, expected: any): void =>
it(`can encode ${to}`, (): void => {
const e = new Option(Text, 'foo');
expect((e as any)[to]()).toEqual(expected);
});
describe('Option', () => {
it('converts undefined/null to empty', () => {
describe('Option', (): void => {
it('converts undefined/null to empty', (): void => {
expect(new Option(Text, undefined).isNone).toBe(true);
expect(new Option(Text, null).isNone).toBe(true);
expect(new Option(Text, 'test').isNone).toBe(false);
});
it('converts an option to an option', () => {
it('converts an option to an option', (): void => {
expect(
new Option(Text, new Option(Text, 'hello')).toString()
).toEqual('hello');
});
it('properly converts correctly toHex (Bytes)', () => {
it('properly converts correctly toHex (Bytes)', (): void => {
// Option<Bytes> for a parachain head, however, this is effectively an
// Option<Option<Bytes>> (hence the length, since it is from storage)
const HEX = '0x210100000000000000000000000000000000000000000000000000000000000000000000000000000000011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce';
@@ -44,7 +44,7 @@ describe('Option', () => {
).toEqual(HEX.substr(6));
});
it.only('properly converts correctly toHex (U64)', () => {
it.only('properly converts correctly toHex (U64)', (): void => {
const HEX = '0x12345678';
expect(
(new Option(U32, HEX).unwrap() as U32).toNumber()
@@ -60,46 +60,46 @@ describe('Option', () => {
testEncode('toString', 'foo');
testEncode('toU8a', Uint8Array.from([1, 12, 102, 111, 111]));
it('has empty toString() (undefined)', () => {
it('has empty toString() (undefined)', (): void => {
expect(
new Option(Text).toString()
).toEqual('');
});
it('has value toString() (provided)', () => {
it('has value toString() (provided)', (): void => {
expect(
new Option(Text, new Uint8Array([1, 4 << 2, 49, 50, 51, 52])).toString()
).toEqual('1234');
});
it('converts toU8a() with', () => {
it('converts toU8a() with', (): void => {
expect(
new Option(Text, '1234').toU8a()
).toEqual(new Uint8Array([1, 4 << 2, 49, 50, 51, 52]));
});
it('converts toU8a() without', () => {
it('converts toU8a() without', (): void => {
expect(
new Option(Text).toU8a()
).toEqual(new Uint8Array([0]));
});
describe('utils', () => {
describe('utils', (): void => {
const testeq = new Option(Text, '1234');
it('compares against other option', () => {
it('compares against other option', (): void => {
expect(testeq.eq(new Option(Text, '1234'))).toBe(true);
});
it('compares against raw value', () => {
it('compares against raw value', (): void => {
expect(testeq.eq('1234')).toBe(true);
});
it('unwraps to default if empty', () => {
it('unwraps to default if empty', (): void => {
expect(new Option(Text).unwrapOr('6789')).toBe('6789');
});
it('unwraps to value if non-empty', () => {
it('unwraps to value if non-empty', (): void => {
expect((new Option(Text, '1234').unwrapOr(null) as Text).toString()).toBe('1234');
});
});
+17 -17
View File
@@ -19,7 +19,7 @@ import Null from '../primitive/Null';
export default class Option<T extends Codec> extends Base<T> implements Codec {
private _Type: Constructor;
constructor (Type: Constructor, value?: any) {
public constructor (Type: Constructor, value?: any) {
super(
Option.decodeOption(Type, value)
);
@@ -27,7 +27,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
this._Type = Type;
}
static decodeOption (Type: Constructor, value?: any): Codec {
public static decodeOption (Type: Constructor, value?: any): Codec {
if (isNull(value) || isUndefined(value) || value instanceof Null) {
return new Null();
} else if (value instanceof Option) {
@@ -46,9 +46,9 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
return new Type(value);
}
static with<O extends Codec> (Type: Constructor): Constructor<Option<O>> {
public static with<O extends Codec> (Type: Constructor): Constructor<Option<O>> {
return class extends Option<O> {
constructor (value?: any) {
public constructor (value?: any) {
super(Type, value);
}
};
@@ -57,7 +57,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
// boolean byte (has value, doesn't have) along with wrapped length
return 1 + this.raw.encodedLength;
}
@@ -65,35 +65,35 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
/**
* @description Checks if the Option has no value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.isNone;
}
/**
* @description Checks if the Option has no value
*/
get isNone (): boolean {
public get isNone (): boolean {
return this.raw instanceof Null;
}
/**
* @description Checks if the Option has a value
*/
get isSome (): boolean {
public get isSome (): boolean {
return !this.isNone;
}
/**
* @description The actual value for the Option
*/
get value (): Codec {
public get value (): Codec {
return this.raw;
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
if (other instanceof Option) {
return (this.isSome === other.isSome) && this.value.eq(other.value);
}
@@ -104,7 +104,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
// This attempts to align with the JSON encoding - actually in this case
// the isSome value is correct, however the `isNone` may be problematic
return this.isNone
@@ -115,21 +115,21 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): AnyJson {
public toJSON (): AnyJson {
return this.raw.toJSON();
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `Option<${new this._Type().toRawType()}>`;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return this.raw.toString();
}
@@ -137,7 +137,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
public toU8a (isBare?: boolean): Uint8Array {
if (isBare) {
return this.raw.toU8a(true);
}
@@ -155,7 +155,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
/**
* @description Returns the value that the Option represents (if available), throws if null
*/
unwrap (): T {
public unwrap (): T {
if (this.isNone) {
throw new Error('Option: unwrapping a None value');
}
@@ -167,7 +167,7 @@ export default class Option<T extends Codec> extends Base<T> implements Codec {
* @description Returns the value that the Option represents (if available) or defaultValue if none
* @param defaultValue The value to return if the option isNone
*/
unwrapOr<O> (defaultValue: O): T | O {
public unwrapOr<O> (defaultValue: O): T | O {
return this.isSome
? this.unwrap()
: defaultValue;
+23 -23
View File
@@ -5,16 +5,16 @@
import Set from './Set';
const SET_FIELDS = {
header: 0b00000001,
body: 0b00000010,
receipt: 0b00000100,
messageQueue: 0b00001000,
header: 0b00000001,
body: 0b00000010,
receipt: 0b00000100,
messageQueue: 0b00001000,
justification: 0b00010000
};
const SET_ROLES = {
none: 0b00000000,
full: 0b00000001,
light: 0b00000010,
none: 0b00000000,
full: 0b00000001,
light: 0b00000010,
authority: 0b00000100
};
const SET_WITHDRAW = {
@@ -24,8 +24,8 @@ const SET_WITHDRAW = {
Fee: 0b00001000
};
describe('Set', () => {
it('constructs via an Array<string>', () => {
describe('Set', (): void => {
it('constructs via an string[]', (): void => {
const set = new Set(SET_ROLES, ['full', 'authority']);
expect(set.isEmpty).toEqual(false);
@@ -34,65 +34,65 @@ describe('Set', () => {
);
});
it('throws with invalid values', () => {
it('throws with invalid values', (): void => {
expect(
() => new Set(SET_ROLES, ['full', 'authority', 'invalid'])
(): Set => new Set(SET_ROLES, ['full', 'authority', 'invalid'])
).toThrow(/Invalid key 'invalid'/);
});
it('throws with add on invalid', () => {
it('throws with add on invalid', (): void => {
expect(
() => (new Set(SET_ROLES, [])).add('invalid')
(): Set => (new Set(SET_ROLES, [])).add('invalid')
).toThrow(/Invalid key 'invalid'/);
});
it('allows construction via number', () => {
it('allows construction via number', (): void => {
expect(
(new Set(SET_WITHDRAW, 15)).eq(['TransactionPayment', 'Transfer', 'Reserve', 'Fee'])
).toBe(true);
});
it('does not allow invalid number', () => {
it('does not allow invalid number', (): void => {
expect(
() => new Set(SET_WITHDRAW, 31)
(): Set => new Set(SET_WITHDRAW, 31)
).toThrow(/Mismatch decoding '31', computed as '15'/);
});
it('hash a valid encoding', () => {
it('hash a valid encoding', (): void => {
const set = new Set(SET_FIELDS, ['header', 'body', 'justification']);
expect(set.toU8a()).toEqual(new Uint8Array([19]));
});
describe('utils', () => {
describe('utils', (): void => {
const set = new Set(SET_ROLES, ['full', 'authority']);
it('compares against string array', () => {
it('compares against string array', (): void => {
expect(
set.eq(['authority', 'full'])
).toBe(true);
});
it('compares against number (encoded)', () => {
it('compares against number (encoded)', (): void => {
expect(
set.eq(SET_ROLES.full | SET_ROLES.authority)
).toBe(true);
});
it('compares against other sets', () => {
it('compares against other sets', (): void => {
expect(
set.eq(new Set(SET_ROLES, ['authority', 'full']))
).toBe(true);
});
it('returns false on other values', () => {
it('returns false on other values', (): void => {
expect(
set.eq('full')
).toBe(false);
});
});
it('has a sane toRawType representation', () => {
it('has a sane toRawType representation', (): void => {
expect(
new Set({ a: 1, b: 2, c: 345 }).toRawType()
).toEqual(JSON.stringify({
+23 -24
View File
@@ -7,9 +7,7 @@ import { assert, isU8a, isNumber, isUndefined, u8aToHex } from '@polkadot/util';
import { Codec } from '../types';
import { compareArray } from './utils';
type SetValues = {
[index: string]: number
};
type SetValues = Record<string, number>;
/**
* @name Set
@@ -21,7 +19,7 @@ type SetValues = {
export default class CodecSet extends Set<string> implements Codec {
private _setValues: SetValues;
constructor (setValues: SetValues, value?: Array<string> | Set<string> | Uint8Array | number) {
public constructor (setValues: SetValues, value?: string[] | Set<string> | Uint8Array | number) {
super(
CodecSet.decodeSet(setValues, value)
);
@@ -29,7 +27,7 @@ export default class CodecSet extends Set<string> implements Codec {
this._setValues = setValues;
}
static decodeSet (setValues: SetValues, value: Array<string> | Set<string> | Uint8Array | number = 0): Array<string> {
public static decodeSet (setValues: SetValues, value: string[] | Set<string> | Uint8Array | number = 0): string[] {
if (isU8a(value)) {
return value.length === 0
? []
@@ -37,22 +35,22 @@ export default class CodecSet extends Set<string> implements Codec {
} else if (value instanceof Set) {
return CodecSet.decodeSet(setValues, [...value.values()]);
} else if (Array.isArray(value)) {
return value.reduce((result, key) => {
return value.reduce((result, key): string[] => {
assert(!isUndefined(setValues[key]), `Set: Invalid key '${key}' passed to Set, allowed ${Object.keys(setValues).join(', ')}`);
result.push(key);
return result;
}, [] as Array<string>);
}, [] as string[]);
}
const result = Object.keys(setValues).reduce((result, key) => {
const result = Object.keys(setValues).reduce((result, key): string[] => {
if ((value & setValues[key]) === setValues[key]) {
result.push(key);
}
return result;
}, [] as Array<string>);
}, [] as string[]);
const computed = CodecSet.encodeSet(setValues, result);
@@ -61,8 +59,8 @@ export default class CodecSet extends Set<string> implements Codec {
return result;
}
static encodeSet (setValues: SetValues, value: Array<string>): number {
return value.reduce((result, value) => {
public static encodeSet (setValues: SetValues, value: string[]): number {
return value.reduce((result, value): number => {
return result | (setValues[value] || 0);
}, 0);
}
@@ -70,35 +68,35 @@ export default class CodecSet extends Set<string> implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return 1;
}
/**
* @description true is the Set contains no values
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.size === 0;
}
/**
* @description The actual set values as a Array<string>
* @description The actual set values as a string[]
*/
get strings (): Array<string> {
public get strings (): string[] {
return [...super.values()];
}
/**
* @description The encoded value for the set members
*/
get valueEncoded (): number {
public get valueEncoded (): number {
return CodecSet.encodeSet(this._setValues, this.strings);
}
/**
* @description adds a value to the Set (extended to allow for validity checking)
*/
add (key: string): this {
public add (key: string): this {
// we have the isUndefined(this._setValues) in here as well, add is used internally
// in the Set constructor (so it is undefined at this point, and should allow)
assert(isUndefined(this._setValues) || !isUndefined(this._setValues[key]), `Set: Invalid key '${key}' on add`);
@@ -111,7 +109,7 @@ export default class CodecSet extends Set<string> implements Codec {
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
if (Array.isArray(other)) {
// we don't actually care about the order, sort the values
return compareArray(this.strings.sort(), other.sort());
@@ -127,28 +125,28 @@ export default class CodecSet extends Set<string> implements Codec {
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
return u8aToHex(this.toU8a());
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): string[] {
public toJSON (): string[] {
return this.strings;
}
/**
* @description The encoded value for the set members
*/
toNumber (): number {
public toNumber (): number {
return this.valueEncoded;
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
// FIXME We don't cater for this in createType as of yet
return JSON.stringify({ _set: this._setValues });
}
@@ -156,7 +154,7 @@ export default class CodecSet extends Set<string> implements Codec {
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return `[${this.strings.join(', ')}]`;
}
@@ -164,7 +162,8 @@ export default class CodecSet extends Set<string> implements Codec {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array([this.valueEncoded]);
}
}
+23 -23
View File
@@ -13,17 +13,17 @@ import Option from './Option';
import Struct from './Struct';
import Vector from './Vector';
describe('Struct', () => {
describe('decoding', () => {
const testDecode = (type: string, input: any) =>
it(`can decode from ${type}`, () => {
describe('Struct', (): void => {
describe('decoding', (): void => {
const testDecode = (type: string, input: any): void =>
it(`can decode from ${type}`, (): void => {
const s = new Struct({
foo: Text,
bar: U32
}, input);
expect([...s.keys()]).toEqual(['foo', 'bar']);
expect(
[...s.values()].map((v) =>
[...s.values()].map((v): string =>
v.toString()
)
).toEqual(['bazzing', '69']);
@@ -35,9 +35,9 @@ describe('Struct', () => {
testDecode('Uint8Array', Uint8Array.from([28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]));
});
describe('encoding', () => {
const testEncode = (to: CodecTo, expected: any) =>
it(`can encode ${to}`, () => {
describe('encoding', (): void => {
const testEncode = (to: CodecTo, expected: any): void =>
it(`can encode ${to}`, (): void => {
const s = new Struct({
foo: Text,
bar: U32
@@ -51,7 +51,7 @@ describe('Struct', () => {
testEncode('toString', '{"foo":"bazzing","bar":69}');
});
it('decodes null', () => {
it('decodes null', (): void => {
expect(
new (
Struct.with({
@@ -62,7 +62,7 @@ describe('Struct', () => {
).toEqual('{}');
});
it('decodes a more complicated type', () => {
it('decodes a more complicated type', (): void => {
const s = new Struct({
foo: Vector.with(Struct.with({
bar: Text
@@ -71,7 +71,7 @@ describe('Struct', () => {
expect(s.toString()).toBe('{"foo":[{"bar":"1"},{"bar":"2"}]}');
});
it('decodes from a Map input', () => {
it('decodes from a Map input', (): void => {
const input = new Struct({
a: U32,
txt: Text
@@ -84,9 +84,9 @@ describe('Struct', () => {
expect(s.toString()).toEqual('{"txt":"fubar","foo":0,"bar":0}');
});
it('throws when it cannot decode', () => {
it('throws when it cannot decode', (): void => {
expect(
() => new (
(): Struct<any> => new (
Struct.with({
txt: Text,
u32: U32
@@ -95,7 +95,7 @@ describe('Struct', () => {
).toThrowError(/Struct: cannot decode type/);
});
it('provides a clean toString()', () => {
it('provides a clean toString()', (): void => {
expect(
new (
Struct.with({
@@ -106,7 +106,7 @@ describe('Struct', () => {
).toEqual('{"txt":"foo","u32":1193046}');
});
it('exposes the properties on the object', () => {
it('exposes the properties on the object', (): void => {
const struct = new (
Struct.with({
txt: Text,
@@ -118,7 +118,7 @@ describe('Struct', () => {
expect((struct as any).u32.toNumber()).toEqual(0x123456);
});
it('correctly encodes length', () => {
it('correctly encodes length', (): void => {
expect(
new (
Struct.with({
@@ -129,7 +129,7 @@ describe('Struct', () => {
).toEqual(5);
});
it('exposes the types', () => {
it('exposes the types', (): void => {
expect(
new Struct({
foo: Text,
@@ -147,7 +147,7 @@ describe('Struct', () => {
});
});
it('gets the value at a particular index', () => {
it('gets the value at a particular index', (): void => {
expect(
new (
Struct.with({
@@ -160,8 +160,8 @@ describe('Struct', () => {
).toEqual('1234');
});
describe('utils', () => {
it('compares against other objects', () => {
describe('utils', (): void => {
it('compares against other objects', (): void => {
const test = {
foo: 'foo',
bar: 'bar',
@@ -178,7 +178,7 @@ describe('Struct', () => {
});
});
it('allows toString with large numbers', () => {
it('allows toString with large numbers', (): void => {
// replicate https://github.com/polkadot-js/api/issues/640
expect(
new Struct({
@@ -187,7 +187,7 @@ describe('Struct', () => {
).toEqual('{"blockNumber":"0x1234567890abcdef"}');
});
it('generates sane toRawType', () => {
it('generates sane toRawType', (): void => {
expect(
new Struct({
accountId: AccountId,
@@ -209,7 +209,7 @@ describe('Struct', () => {
}));
});
it('generates sane toRawType (via with)', () => {
it('generates sane toRawType (via with)', (): void => {
const Type = Struct.with({
accountId: AccountId,
balance: Balance
+35 -33
View File
@@ -25,12 +25,12 @@ export default class Struct<
// 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, Codec> implements Codec {
E extends { [K in keyof S]: string } = { [K in keyof S]: string }> extends Map<keyof S, Codec> implements Codec {
protected _jsonMap: Map<keyof S, string>;
protected _Types: S;
constructor (Types: S, value: V | Map<any, any> | Array<any> = {} as V, jsonMap: Map<keyof S, string> = new Map()) {
public constructor (Types: S, value: V | Map<any, any> | any[] = {} as unknown as V, jsonMap: Map<keyof S, string> = new Map()) {
const decoded = Struct.decodeStruct<S, V, T>(Types, value, jsonMap);
super(
@@ -69,14 +69,14 @@ export default class Struct<
const values = decodeU8a(value, Object.values(Types));
// Transform array of values to {key: value} mapping
return Object.keys(Types).reduce((raw: T, key: keyof S, index) => {
return Object.keys(Types).reduce((raw: T, key: keyof S, index): T => {
// TS2322: Type 'Codec' is not assignable to type 'T[keyof S]'.
(raw as any)[key] = values[index];
return raw;
}, {} as T);
}, {} as unknown as T);
} else if (!value) {
return {} as T;
return {} as unknown as T;
}
// We assume from here that value is a JS object (Array, Map, Object)
@@ -88,7 +88,7 @@ export default class Struct<
_,
T extends { [K in keyof S]: Codec }
> (Types: S, value: any, jsonMap: Map<keyof S, string>): T {
return Object.keys(Types).reduce((raw: T, key: keyof S, index) => {
return Object.keys(Types).reduce((raw: T, key: keyof S, index): T => {
// The key in the JSON can be snake_case (or other cases), but in our
// Types, result or any other maps, it's camelCase
const jsonKey = (jsonMap.get(key as any) && !value[key]) ? jsonMap.get(key as any) : key;
@@ -117,17 +117,17 @@ export default class Struct<
}
return raw;
}, {} as T);
}, {} as unknown as T);
}
static with<
public static with<
S extends ConstructorDef
> (Types: S): Constructor<Struct<S>> {
return class extends Struct<S> {
constructor (value?: any, jsonMap?: Map<keyof S, string>) {
public constructor (value?: any, jsonMap?: Map<keyof S, string>) {
super(Types, value, jsonMap);
(Object.keys(Types) as Array<keyof S>).forEach((key) => {
(Object.keys(Types) as (keyof S)[]).forEach((key): void => {
// do not clobber existing properties on the object
if (!isUndefined((this as any)[key])) {
return;
@@ -135,7 +135,7 @@ export default class Struct<
Object.defineProperty(this, key, {
enumerable: true,
get: () => this.get(key)
get: (): Codec | undefined => this.get(key)
});
});
}
@@ -145,7 +145,7 @@ export default class Struct<
/**
* @description Checks if the value is an empty value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
const items = this.toArray();
for (let i = 0; i < items.length; i++) {
@@ -160,29 +160,31 @@ export default class Struct<
/**
* @description Returns the Type description to sthe structure
*/
get Type (): E {
public get Type (): E {
return (Object
.entries(this._Types) as Array<[keyof S, Constructor]>)
.reduce((result: E, [key, Type]) => {
.entries(this._Types) as [keyof S, Constructor][])
.reduce((result: E, [key, Type]): E => {
(result as any)[key] = Type.name;
return result;
}, {} as E);
}, {} as unknown as E);
}
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
return this.toArray().reduce((length, entry) => {
return length += entry.encodedLength;
public get encodedLength (): number {
return this.toArray().reduce((length, entry): number => {
length += entry.encodedLength;
return length;
}, 0);
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return compareMap(this, other);
}
@@ -190,38 +192,38 @@ export default class Struct<
* @description Returns a specific names entry in the structure
* @param name The name of the entry to retrieve
*/
get (name: keyof S): Codec | undefined {
public get (name: keyof S): Codec | undefined {
return super.get(name);
}
/**
* @description Returns the values of a member at a specific index (Rather use get(name) for performance)
*/
getAtIndex (index: number): Codec {
public getAtIndex (index: number): Codec {
return this.toArray()[index];
}
/**
* @description Converts the Object to an standard JavaScript Array
*/
toArray (): Array<Codec> {
public toArray (): Codec[] {
return [...this.values()];
}
/**
* @description Returns a hex string representation of the value
*/
toHex () {
public toHex (): string {
return u8aToHex(this.toU8a());
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): AnyJsonObject | string {
public toJSON (): AnyJsonObject | string {
// FIXME the return type string is only used by Extrinsic (extends Struct),
// but its toJSON is the hex value
return [...this.keys()].reduce((json, key) => {
return [...this.keys()].reduce((json, key): any => {
const jsonKey = this._jsonMap.get(key) || key;
const value = this.get(key);
@@ -234,20 +236,20 @@ export default class Struct<
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return JSON.stringify(
Object.entries(this._Types).reduce((result, [key, Type]) => {
Object.entries(this._Types).reduce((result, [key, Type]): Record<string, string> => {
result[key] = new Type().toRawType();
return result;
}, {} as { [index: string]: string })
}, {} as unknown as Record<string, string>)
);
}
/**
* @description Returns the string representation of the value
*/
toString () {
public toString (): string {
return JSON.stringify(this.toJSON());
}
@@ -255,9 +257,9 @@ export default class Struct<
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
public toU8a (isBare?: boolean): Uint8Array {
return u8aConcat(
...this.toArray().map((entry) =>
...this.toArray().map((entry): Uint8Array =>
entry.toU8a(isBare)
)
);
+14 -13
View File
@@ -17,13 +17,13 @@ import { compareMap } from './utils';
* @noInheritDoc
*/
export default class StructAny extends Map<string, any> implements Codec {
constructor (value?: { [index: string]: any } | null) {
public constructor (value?: { [index: string]: any } | null) {
const decoded = StructAny.decodeJson(value);
super(decoded);
// like we are doing with structs, add the keys as getters
decoded.forEach(([key]) => {
decoded.forEach(([key]): void => {
// do not clobber existing properties on the object
if (!isUndefined((this as any)[key])) {
return;
@@ -31,48 +31,48 @@ export default class StructAny extends Map<string, any> implements Codec {
Object.defineProperty(this, key, {
enumerable: true,
get: () => this.get(key)
get: (): Codec | undefined => this.get(key)
});
});
}
private static decodeJson (value?: { [index: string]: any } | null): Array<[string, any]> {
private static decodeJson (value?: { [index: string]: any } | null): [string, any][] {
return Object.entries(value || {});
}
/**
* @description Always 0, never encodes as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return 0;
}
/**
* @description Checks if the value is an empty value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return [...this.keys()].length === 0;
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return compareMap(this, other);
}
/**
* @description Unimplemented, will throw
*/
toHex (): string {
public toHex (): string {
throw new Error('Unimplemented');
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): AnyJsonObject {
return [...this.entries()].reduce((json, [key, value]) => {
public toJSON (): AnyJsonObject {
return [...this.entries()].reduce((json, [key, value]): AnyJsonObject => {
json[key] = value;
return json;
@@ -82,21 +82,22 @@ export default class StructAny extends Map<string, any> implements Codec {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'Json';
}
/**
* @description Returns the string representation of the value
*/
toString () {
public toString (): string {
return JSON.stringify(this.toJSON());
}
/**
* @description Unimplemented, will throw
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
throw new Error('Unimplemented');
}
}
+21 -21
View File
@@ -13,19 +13,19 @@ import Proposal from '../type/Proposal';
import VoteThreshold from '../type/VoteThreshold';
import Tuple from './Tuple';
describe('Tuple', () => {
describe('Tuple', (): void => {
let tuple: Tuple;
beforeEach(() => {
beforeEach((): void => {
tuple = new Tuple(
[Text, U32],
['bazzing', 69]
);
});
describe('decoding', () => {
const testDecode = (type: string, input: any) =>
it(`can decode from ${type}`, () => {
describe('decoding', (): void => {
const testDecode = (type: string, input: any): void =>
it(`can decode from ${type}`, (): void => {
const t = new Tuple([
Text,
U32
@@ -40,9 +40,9 @@ describe('Tuple', () => {
testDecode('Uint8Array', Uint8Array.from([28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]));
});
describe('encoding', () => {
const testEncode = (to: CodecTo | 'toArray', expected: any) =>
it(`can encode ${to}`, () => {
describe('encoding', (): void => {
const testEncode = (to: CodecTo | 'toArray', expected: any): void =>
it(`can encode ${to}`, (): void => {
expect(tuple[to]()).toEqual(expected);
});
@@ -52,7 +52,7 @@ describe('Tuple', () => {
testEncode('toString', '["bazzing",69]');
});
it.skip('creates properly via actual hex string', () => {
it.skip('creates properly via actual hex string', (): void => {
Method.injectMethods(extrinsics);
const test = new (Tuple.with([
@@ -65,11 +65,11 @@ describe('Tuple', () => {
expect((test[2] as VoteThreshold).toNumber()).toEqual(1);
});
it('exposes the Types', () => {
it('exposes the Types', (): void => {
expect(tuple.Types).toEqual(['Text', 'U32']);
});
it('exposes the Types (object creation)', () => {
it('exposes the Types (object creation)', (): void => {
const test = new Tuple({
BlockNumber, VoteThreshold
}, []);
@@ -77,32 +77,32 @@ describe('Tuple', () => {
expect(test.Types).toEqual(['BlockNumber', 'VoteThreshold']);
});
it('exposes filter', () => {
expect(tuple.filter((v) => v.toJSON() === 69)).toEqual([new U32(69)]);
it('exposes filter', (): void => {
expect(tuple.filter((v): boolean => v.toJSON() === 69)).toEqual([new U32(69)]);
});
it('exposes map', () => {
expect(tuple.map(v => v.toString())).toEqual(['bazzing', '69']);
it('exposes map', (): void => {
expect(tuple.map((v): string => v.toString())).toEqual(['bazzing', '69']);
});
describe('utils', () => {
it('compares against inputs', () => {
describe('utils', (): void => {
it('compares against inputs', (): void => {
expect(tuple.eq(['bazzing', 69])).toBe(true);
});
it('compares against inputs (mismatch)', () => {
it('compares against inputs (mismatch)', (): void => {
expect(tuple.eq(['bazzing', 72])).toBe(false);
});
});
describe('toRawType', () => {
it('generates sane value with array types', () => {
describe('toRawType', (): void => {
it('generates sane value with array types', (): void => {
expect(
new Tuple([U32, BlockNumber]).toRawType()
).toEqual('(u32,u64)');
});
it('generates sane value with object types', () => {
it('generates sane value with object types', (): void => {
expect(
new Tuple({ number: U32, blockNumber: BlockNumber }).toRawType()
).toEqual('(u32,u64)');
+20 -18
View File
@@ -8,8 +8,8 @@ import { AnyNumber, AnyU8a, AnyString, Codec, Constructor } from '../types';
import { decodeU8a } from './utils';
import AbstractArray from './AbstractArray';
type TupleConstructors = Array<Constructor> | {
[index: string]: Constructor
type TupleConstructors = Constructor[] | {
[index: string]: Constructor;
};
/**
@@ -21,7 +21,7 @@ type TupleConstructors = Array<Constructor> | {
export default class Tuple extends AbstractArray<Codec> {
private _Types: TupleConstructors;
constructor (Types: TupleConstructors, value?: any) {
public constructor (Types: TupleConstructors, value?: any) {
super(
...Tuple.decodeTuple(Types, value)
);
@@ -29,18 +29,18 @@ export default class Tuple extends AbstractArray<Codec> {
this._Types = Types;
}
private static decodeTuple (_Types: TupleConstructors, value: AnyU8a | string | Array<AnyU8a | AnyNumber | AnyString | undefined | null>): Array<Codec> {
private static decodeTuple (_Types: TupleConstructors, value: AnyU8a | string | (AnyU8a | AnyNumber | AnyString | undefined | null)[]): Codec[] {
if (isU8a(value)) {
return decodeU8a(value, _Types);
} else if (isHex(value)) {
return Tuple.decodeTuple(_Types, hexToU8a(value));
}
const Types: Array<Constructor> = Array.isArray(_Types)
const Types: Constructor[] = Array.isArray(_Types)
? _Types
: Object.values(_Types);
return Types.map((Type, index) => {
return Types.map((Type, index): Codec => {
try {
return new Type(value && value[index]);
} catch (error) {
@@ -49,9 +49,9 @@ export default class Tuple extends AbstractArray<Codec> {
});
}
static with (Types: TupleConstructors): Constructor<Tuple> {
public static with (Types: TupleConstructors): Constructor<Tuple> {
return class extends Tuple {
constructor (value?: any) {
public constructor (value?: any) {
super(Types, value);
}
};
@@ -60,30 +60,32 @@ export default class Tuple extends AbstractArray<Codec> {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
return this.reduce((length, entry) => {
return length += entry.encodedLength;
public get encodedLength (): number {
return this.reduce((length: number, entry: Codec): number => {
length += entry.encodedLength;
return length;
}, 0);
}
/**
* @description The types definition of the tuple
*/
get Types (): Array<string> {
public get Types (): string[] {
return Array.isArray(this._Types)
? this._Types.map(({ name }) => name)
? this._Types.map(({ name }): string => name)
: Object.keys(this._Types);
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
const types = (
Array.isArray(this._Types)
? this._Types
: Object.values(this._Types)
).map((Type) => new Type().toRawType());
).map((Type): string => new Type().toRawType());
return `(${types.join(',')})`;
}
@@ -91,7 +93,7 @@ export default class Tuple extends AbstractArray<Codec> {
/**
* @description Returns the string representation of the value
*/
toString () {
public toString (): string {
// Overwrite the default toString representation of Array.
return JSON.stringify(this.toJSON());
}
@@ -100,9 +102,9 @@ export default class Tuple extends AbstractArray<Codec> {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
public toU8a (isBare?: boolean): Uint8Array {
return u8aConcat(
...this.map((entry) =>
...this.map((entry): Uint8Array =>
entry.toU8a(isBare)
)
);
+14 -14
View File
@@ -6,49 +6,49 @@ import { TypeRegistry } from './typeRegistry';
import Text from '../primitive/Text';
import U32 from '../primitive/U32';
describe('TypeRegistry', () => {
describe('TypeRegistry', (): void => {
let registry: TypeRegistry;
beforeEach(() => {
beforeEach((): void => {
registry = new TypeRegistry();
});
it('handles non exist type', () => {
it('handles non exist type', (): void => {
expect(registry.get('non-exist')).toBeUndefined();
});
it('can register single type', () => {
it('can register single type', (): void => {
registry.register(Text);
expect(registry.get('Text')).toBe(Text);
});
it('can register type with a different name', () => {
it('can register type with a different name', (): void => {
registry.register('TextRenamed', Text);
expect(registry.get('TextRenamed')).toBe(Text);
});
describe('object registration', () => {
it('can register multiple types', () => {
describe('object registration', (): void => {
it('can register multiple types', (): void => {
registry.register({
Text,
'U32Renamed': U32
U32Renamed: U32
});
expect(registry.get('Text')).toBe(Text);
expect(registry.get('U32Renamed')).toBe(U32);
});
it('can create types from string', () => {
it('can create types from string', (): void => {
registry.register({
'U32Renamed': 'u32'
U32Renamed: 'u32'
});
expect(registry.get('U32Renamed')).toBe(U32);
});
it('can create structs via definition', () => {
it('can create structs via definition', (): void => {
registry.register({
'SomeStruct': {
'foo': 'u32',
'bar': 'Text'
SomeStruct: {
foo: 'u32',
bar: 'Text'
}
});
+17 -15
View File
@@ -5,22 +5,24 @@
import { CodecTo } from '../types';
import U8a from './U8a';
const testDecode = (type: string, input: any, expected: string) =>
it(`can decode from ${type}`, () => {
const testDecode = (type: string, input: any, expected: string): void =>
it(`can decode from ${type}`, (): void => {
const e = new U8a(input);
expect(e.toString()).toBe(expected);
});
const testEncode = (to: CodecTo, expected: any) =>
it(`can encode ${to}`, () => {
const testEncode = (to: CodecTo, expected: any): void =>
it(`can encode ${to}`, (): void => {
const e = new U8a([1, 2, 3, 4, 5]);
expect(e[to]()).toEqual(expected);
});
describe('U8a', () => {
describe('U8a', (): void => {
let u8a: U8a;
beforeEach(() => {
beforeEach((): void => {
u8a = new U8a([1, 2, 3, 4, 5]);
});
@@ -34,38 +36,38 @@ describe('U8a', () => {
testEncode('toString', '0x0102030405');
testEncode('toU8a', Uint8Array.from([1, 2, 3, 4, 5]));
it('contains the length of the elements', () => {
it('contains the length of the elements', (): void => {
expect(u8a.length).toEqual(5);
});
it('correctly encodes length', () => {
it('correctly encodes length', (): void => {
expect(u8a.encodedLength).toEqual(5);
});
it('allows wrapping of a pre-existing instance', () => {
it('allows wrapping of a pre-existing instance', (): void => {
expect(
new U8a(u8a).length
).toEqual(5);
});
it('implements subarray correctly', () => {
it('implements subarray correctly', (): void => {
expect(u8a.subarray(1, 3)).toEqual(Uint8Array.from([2, 3]));
});
describe('utils', () => {
it('compares against other U8a', () => {
describe('utils', (): void => {
it('compares against other U8a', (): void => {
expect(u8a.eq(new Uint8Array([1, 2, 3, 4, 5]))).toBe(true);
});
it('compares against other U8a (non-length)', () => {
it('compares against other U8a (non-length)', (): void => {
expect(u8a.eq(new Uint8Array([1, 2, 3, 4]))).toBe(false);
});
it('compares against other U8a (mismatch)', () => {
it('compares against other U8a (mismatch)', (): void => {
expect(u8a.eq(new Uint8Array([1, 2, 3, 4, 6]))).toBe(false);
});
it('compares against hex inputs', () => {
it('compares against hex inputs', (): void => {
expect(u8a.eq('0x0102030405')).toBe(true);
});
});
+14 -13
View File
@@ -16,7 +16,7 @@ import { AnyU8a, Codec } from '../types';
* @noInheritDoc
*/
export default class U8a extends Uint8Array implements Codec {
constructor (value?: AnyU8a) {
public constructor (value?: AnyU8a) {
super(
U8a.decodeU8a(value)
);
@@ -33,21 +33,21 @@ export default class U8a extends Uint8Array implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return this.length;
}
/**
* @description Returns true if the type wraps an empty/default all-0 value
*/
get isEmpty (): boolean {
return !this.length || isUndefined(this.find((value) => !!value));
public get isEmpty (): boolean {
return !this.length || isUndefined(this.find((value): boolean => !!value));
}
/**
* @description The length of the value
*/
get length (): number {
public get length (): number {
// only included here since we ignore inherited docs
return super.length;
}
@@ -55,10 +55,10 @@ export default class U8a extends Uint8Array implements Codec {
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
if (other instanceof Uint8Array) {
return (this.length === other.length) && isUndefined(
this.find((value, index) => value !== other[index])
this.find((value, index): boolean => value !== other[index])
);
}
@@ -70,35 +70,35 @@ export default class U8a extends Uint8Array implements Codec {
* @param begin The position to start at
* @param end The position to end at
*/
subarray (begin: number, end?: number): Uint8Array {
public subarray (begin: number, end?: number): Uint8Array {
return Uint8Array.from(this).subarray(begin, end);
}
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
return u8aToHex(this);
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): string {
public toJSON (): string {
return this.toHex();
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `Vec<u8>`;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return this.toHex();
}
@@ -106,7 +106,8 @@ export default class U8a extends Uint8Array implements Codec {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
return Uint8Array.from(this);
}
}
+7 -7
View File
@@ -4,34 +4,34 @@
import U8aFixed from './U8aFixed';
describe('U8aFixed', () => {
describe('U8aFixed', (): void => {
let u8a: U8aFixed;
beforeEach(() => {
beforeEach((): void => {
u8a = new U8aFixed([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 32);
});
it('limits the length', () => {
it('limits the length', (): void => {
expect(u8a.length).toEqual(4);
});
it('exposes the correct bitLength', () => {
it('exposes the correct bitLength', (): void => {
expect(u8a.bitLength()).toEqual(32);
});
it('allows wrapping of a pre-existing instance', () => {
it('allows wrapping of a pre-existing instance', (): void => {
expect(
u8a.toU8a()
).toEqual(new Uint8Array([1, 2, 3, 4]));
});
it('allows empty values', () => {
it('allows empty values', (): void => {
expect(
new U8aFixed().toHex()
).toEqual('0x0000000000000000000000000000000000000000000000000000000000000000');
});
it('allows construction via with', () => {
it('allows construction via with', (): void => {
expect(
new (U8aFixed.with(64))().bitLength()
).toEqual(64);
+5 -5
View File
@@ -17,7 +17,7 @@ export type BitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 512 | 1024 | 2048;
* to be used directly, rather is should be subclassed with the specific lengths.
*/
export default class U8aFixed extends U8a {
constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) {
public constructor (value: AnyU8a = new Uint8Array(), bitLength: BitLength = 256) {
super(
U8aFixed.decodeU8aFixed(value, bitLength)
);
@@ -46,9 +46,9 @@ export default class U8aFixed extends U8a {
return value;
}
static with (bitLength: BitLength): Constructor<U8aFixed> {
public static with (bitLength: BitLength): Constructor<U8aFixed> {
return class extends U8aFixed {
constructor (value?: any) {
public constructor (value?: any) {
super(value, bitLength);
}
};
@@ -57,14 +57,14 @@ export default class U8aFixed extends U8a {
/**
* @description Returns the number of bits in the value
*/
bitLength () {
public bitLength (): number {
return this.length * 8;
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
// FIEXME We don't cater for this in createType
return `[u8;${this.length}]`;
}
+12 -12
View File
@@ -6,39 +6,39 @@ import BN from 'bn.js';
import UInt from './UInt';
describe('UInt', () => {
it('provides a toBn interface', () => {
describe('UInt', (): void => {
it('provides a toBn interface', (): void => {
expect(
new UInt(987).toBn().toNumber()
).toEqual(987);
});
it('provides a toNumber interface', () => {
it('provides a toNumber interface', (): void => {
expect(
new UInt(4567).toNumber()
).toEqual(4567);
});
it('converts to Little Endian from the provided value', () => {
it('converts to Little Endian from the provided value', (): void => {
expect(
new UInt(1234567).toU8a()
).toEqual(new Uint8Array([135, 214, 18, 0, 0, 0, 0, 0]));
});
it('converts to Little Endian from the provided value (bitLength)', () => {
it('converts to Little Endian from the provided value (bitLength)', (): void => {
expect(
new UInt(1234567, 32).toU8a()
).toEqual(new Uint8Array([135, 214, 18, 0]));
});
it('converts to hex/string', () => {
it('converts to hex/string', (): void => {
const u = new UInt('0x12', 16);
expect(u.toHex()).toEqual('0x0012');
expect(u.toString()).toEqual('18');
});
it('converts to equivalents', () => {
it('converts to equivalents', (): void => {
const a = new UInt('123');
expect(
@@ -46,24 +46,24 @@ describe('UInt', () => {
).toEqual(123);
});
it('converts to JSON representation based on flags/size', () => {
it('converts to JSON representation based on flags/size', (): void => {
expect(new UInt('0x12345678', 64, true).toJSON()).toEqual('0x0000000012345678');
expect(new UInt('0x1234567890', 64, false).toJSON()).toEqual(0x1234567890);
expect(new UInt('0x1234567890abcdef', 64, false).toJSON()).toEqual('0x1234567890abcdef');
});
describe('eq', () => {
describe('eq', (): void => {
const test = new UInt(12345);
it('compares against other BN values', () => {
it('compares against other BN values', (): void => {
expect(test.eq(new BN(12345))).toBe(true);
});
it('compares against other number values', () => {
it('compares against other number values', (): void => {
expect(test.eq(12345)).toBe(true);
});
it('compares against hex values', () => {
it('compares against hex values', (): void => {
expect(test.eq('0x3039')).toBe(true);
});
});
+5 -4
View File
@@ -19,7 +19,7 @@ import AbstractInt, { DEFAULT_UINT_BITS, UIntBitLength } from './AbstractInt';
* @noInheritDoc
*/
export default class UInt extends AbstractInt {
constructor (
public constructor (
value: AnyNumber = 0,
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = false) {
super(
@@ -33,7 +33,7 @@ export default class UInt extends AbstractInt {
/**
* @description Returns a hex string representation of the value
*/
toHex (isLe: boolean = false): string {
public toHex (isLe: boolean = false): string {
// For display/JSON, this is BE, for compare, use isLe
return bnToHex(this, {
bitLength: this._bitLength,
@@ -45,7 +45,7 @@ export default class UInt extends AbstractInt {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `u${this._bitLength}`;
}
@@ -53,7 +53,8 @@ export default class UInt extends AbstractInt {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
return bnToU8a(this, {
bitLength: this._bitLength,
isLe: true,
+25 -25
View File
@@ -15,24 +15,24 @@ import createType from './createType';
import Vector from './Vector';
import Tuple from './Tuple';
describe('Vector', () => {
describe('Vector', (): void => {
let vector: Vector<Codec>;
beforeEach(() => {
beforeEach((): void => {
vector = new Vector(Text, ['1', '23', '345', '4567', new Text('56789')]);
Method.injectMethods(extrinsics);
});
it('wraps a sequence of values', () => {
it('wraps a sequence of values', (): void => {
expect(vector.length).toEqual(5); // eslint-disable-line
});
it('has a sane representation for toString', () => {
it('has a sane representation for toString', (): void => {
expect(vector.toString()).toEqual('[1, 23, 345, 4567, 56789]');
});
it('encodes with length prefix', () => {
it('encodes with length prefix', (): void => {
expect(vector.toU8a()).toEqual(new Uint8Array([
5 << 2,
1 << 2, 49,
@@ -43,17 +43,17 @@ describe('Vector', () => {
]));
});
it('allows contruction via JSON', () => {
it('allows contruction via JSON', (): void => {
expect(
new Vector(Text, ['6', '7']).toJSON()
).toEqual(['6', '7']);
});
it('exposes the type', () => {
it('exposes the type', (): void => {
expect(vector.Type).toEqual('Text');
});
it.skip('decodes a complex type via construction', () => {
it.skip('decodes a complex type via construction', (): void => {
const test = createType('Vec<(PropIndex, Proposal, AccountId)>', new Uint8Array([
4, 10, 0, 0, 0, 0, 3, 80, 123, 10, 9, 34, 48, 120, 52, 50, 34, 58, 32, 34, 48, 120, 52, 51, 34, 10, 125, 10, 209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79
]));
@@ -64,17 +64,17 @@ describe('Vector', () => {
expect((first[2] as AccountId).toString()).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ');
});
describe('vector-like functions', () => {
it('allows retrieval of a specific item', () => {
describe('vector-like functions', (): void => {
it('allows retrieval of a specific item', (): void => {
expect(
vector[2].toString()
).toEqual('345');
});
it('exposes a working forEach', () => {
it('exposes a working forEach', (): void => {
const result: { [index: number]: string } = {};
vector.forEach((e, i) => {
vector.forEach((e, i): void => {
result[i] = e.toString();
});
@@ -87,28 +87,28 @@ describe('Vector', () => {
});
});
it('exposes a working filter', () => {
it('exposes a working filter', (): void => {
expect(
vector.filter((e, i) => i >= 3).toString()
vector.filter((e, i): boolean => i >= 3).toString()
).toEqual('4567,56789');
});
it('exposes a working map', () => {
it('exposes a working map', (): void => {
expect(
vector.map((e) => e.toString().substr(0, 1))
vector.map((e): string => e.toString().substr(0, 1))
).toEqual(['1', '2', '3', '4', '5']);
});
it('exposes a working reduce', () => {
it('exposes a working reduce', (): void => {
expect(
vector.reduce((r, e) => `${r}${e}`, '')
vector.reduce((r, e): string => `${r}${e}`, '')
).toEqual('123345456756789');
});
});
describe('encode', () => {
const testEncode = (to: CodecTo, expected: any) =>
it(`can encode ${to}`, () => {
describe('encode', (): void => {
const testEncode = (to: CodecTo, expected: any): void =>
it(`can encode ${to}`, (): void => {
expect(vector[to]()).toEqual(expected);
});
@@ -118,18 +118,18 @@ describe('Vector', () => {
testEncode('toU8a', Uint8Array.from([20, 4, 49, 8, 50, 51, 12, 51, 52, 53, 16, 52, 53, 54, 55, 20, 53, 54, 55, 56, 57]));
});
describe('utils', () => {
describe('utils', (): void => {
const vec = new Vector(Text, ['123', '456']);
it('compares against codec types', () => {
it('compares against codec types', (): void => {
expect(vec.eq([new Text('123'), new Text('456')])).toBe(true);
});
it('compares against codec + primitive types', () => {
it('compares against codec + primitive types', (): void => {
expect(vec.eq(['123', new Text('456')])).toBe(true);
});
it('finds the index of an value', () => {
it('finds the index of an value', (): void => {
const myId = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const vec = new Vector(AccountId, [
'5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw', '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
+9 -9
View File
@@ -21,7 +21,7 @@ const MAX_LENGTH = 32768;
export default class Vector<T extends Codec> extends AbstractArray<T> {
private _Type: Constructor<T>;
constructor (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | Array<any> = [] as Array<any>) {
public constructor (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | any[] = [] as any[]) {
super(
...Vector.decodeVector(Type, value)
);
@@ -29,9 +29,9 @@ export default class Vector<T extends Codec> extends AbstractArray<T> {
this._Type = Type;
}
static decodeVector<T extends Codec> (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | Array<any>): Array<T> {
public static decodeVector<T extends Codec> (Type: Constructor<T>, value: Vector<any> | Uint8Array | string | any[]): T[] {
if (Array.isArray(value)) {
return value.map((entry, index) => {
return value.map((entry, index): T => {
try {
return entry instanceof Type
? entry
@@ -52,13 +52,13 @@ export default class Vector<T extends Codec> extends AbstractArray<T> {
return decodeU8a(u8a.subarray(offset), new Array(length.toNumber()).fill(Type)) as T[];
}
static with<O extends Codec> (Type: Constructor<O>): Constructor<Vector<O>> {
public static with<O extends Codec> (Type: Constructor<O>): Constructor<Vector<O>> {
return class extends Vector<O> {
constructor (value?: Array<any>) {
public constructor (value?: any[]) {
super(Type, value);
}
static Fallback = Type.Fallback
public static Fallback = Type.Fallback
? Vector.with(Type.Fallback)
: undefined;
};
@@ -67,14 +67,14 @@ export default class Vector<T extends Codec> extends AbstractArray<T> {
/**
* @description The type for the items
*/
get Type (): string {
public get Type (): string {
return this._Type.name;
}
/**
* @description Finds the index of the value in the array
*/
indexOf (_other?: any): number {
public indexOf (_other?: any): number {
// convert type first, this removes overhead from the eq
const other = _other instanceof this._Type
? _other
@@ -92,7 +92,7 @@ export default class Vector<T extends Codec> extends AbstractArray<T> {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `Vec<${new this._Type().toRawType()}>`;
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ export default class VectorAny<T extends Codec> extends AbstractArray<T> {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
// FIXME This is basically an any type, cannot instantiate via createType
return 'Vec<Codec>';
}
+8 -8
View File
@@ -17,7 +17,7 @@ import Vector from './Vector';
export default class VectorFixed<T extends Codec> extends AbstractArray<T> {
private _Type: Constructor<T>;
constructor (Type: Constructor<T>, length: number, value: VectorFixed<any> | Uint8Array | string | Array<any> = [] as Array<any>) {
public constructor (Type: Constructor<T>, length: number, value: VectorFixed<any> | Uint8Array | string | any[] = [] as any[]) {
super(
...VectorFixed.decodeVectorFixed(Type, length, value)
);
@@ -25,7 +25,7 @@ export default class VectorFixed<T extends Codec> extends AbstractArray<T> {
this._Type = Type;
}
static decodeVectorFixed<T extends Codec> (Type: Constructor<T>, allocLength: number, value: VectorFixed<any> | Uint8Array | string | Array<any>): Array<T> {
public static decodeVectorFixed<T extends Codec> (Type: Constructor<T>, allocLength: number, value: VectorFixed<any> | Uint8Array | string | any[]): T[] {
const values = Vector.decodeVector(
Type,
isU8a(value)
@@ -42,13 +42,13 @@ export default class VectorFixed<T extends Codec> extends AbstractArray<T> {
return values;
}
static with<O extends Codec> (Type: Constructor<O>, length: number): Constructor<VectorFixed<O>> {
public static with<O extends Codec> (Type: Constructor<O>, length: number): Constructor<VectorFixed<O>> {
return class extends VectorFixed<O> {
constructor (value?: Array<any>) {
public constructor (value?: any[]) {
super(Type, length, value);
}
static Fallback = Type.Fallback
public static Fallback = Type.Fallback
? VectorFixed.with(Type.Fallback, length)
: undefined;
};
@@ -57,18 +57,18 @@ export default class VectorFixed<T extends Codec> extends AbstractArray<T> {
/**
* @description The type for the items
*/
get Type (): string {
public get Type (): string {
return this._Type.name;
}
toU8a (): Uint8Array {
public toU8a (): Uint8Array {
return super.toU8a(true);
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return `[${new this._Type().toRawType()};${this.length}`;
}
}
+34 -32
View File
@@ -2,66 +2,68 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import createType, { TypeDefInfo, getTypeClass, getTypeDef, typeSplit } from './createType';
import { Codec, Constructor } from '../types';
describe('typeSplit', () => {
it('splits simple types into an array', () => {
import createType, { TypeDef, TypeDefInfo, getTypeClass, getTypeDef, typeSplit } from './createType';
describe('typeSplit', (): void => {
it('splits simple types into an array', (): void => {
expect(
typeSplit('Text, u32, u64')
).toEqual(['Text', 'u32', 'u64']);
});
it('splits nested combinations', () => {
it('splits nested combinations', (): void => {
expect(
typeSplit('Text, (u32), Vec<u64>')
).toEqual(['Text', '(u32)', 'Vec<u64>']);
});
it('keeps nested tuples together', () => {
it('keeps nested tuples together', (): void => {
expect(
typeSplit('Text, (u32, u128), Vec<u64>')
).toEqual(['Text', '(u32, u128)', 'Vec<u64>']);
});
it('keeps nested vector tuples together', () => {
it('keeps nested vector tuples together', (): void => {
expect(
typeSplit('Text, (u32, u128), Vec<(u64, u32)>')
).toEqual(['Text', '(u32, u128)', 'Vec<(u64, u32)>']);
});
it('allows for deep nesting', () => {
it('allows for deep nesting', (): void => {
expect(
typeSplit('Text, (u32, (u128, u8)), Vec<(u64, (u32, u32))>')
).toEqual(['Text', '(u32, (u128, u8))', 'Vec<(u64, (u32, u32))>']);
});
it('checks for unclosed vec', () => {
it('checks for unclosed vec', (): void => {
expect(
() => typeSplit('Text, Vec<u64')
(): string[] => typeSplit('Text, Vec<u64')
).toThrow(/Invalid defintion/);
});
it('checks for unclosed tuple', () => {
it('checks for unclosed tuple', (): void => {
expect(
() => typeSplit('Text, (u64, u32')
(): string[] => typeSplit('Text, (u64, u32')
).toThrow(/Invalid defintion/);
});
});
describe('getTypeValue', () => {
it('does not allow invalid tuples, end )', () => {
describe('getTypeValue', (): void => {
it('does not allow invalid tuples, end )', (): void => {
expect(
() => getTypeDef('(u64, u32')
(): TypeDef => getTypeDef('(u64, u32')
).toThrow(/Expected '\(' closing with '\)'/);
});
it('does not allow invalid vectors, end >', () => {
it('does not allow invalid vectors, end >', (): void => {
expect(
() => getTypeDef('Vec<u64')
(): TypeDef => getTypeDef('Vec<u64')
).toThrow(/Expected 'Vec<' closing with '>'/);
});
it('returns a type structure', () => {
it('returns a type structure', (): void => {
expect(
getTypeDef('(u32, Compact<u32>, Vec<u64>, Option<u128>, DoubleMap<u128>, (Text, Vec<(Bool, u128)>))')
).toEqual({
@@ -136,7 +138,7 @@ describe('getTypeValue', () => {
});
});
it('returns a type structure (actual)', () => {
it('returns a type structure (actual)', (): void => {
expect(
getTypeDef('Vec<(PropIndex, Proposal, AccountId)>')
).toEqual({
@@ -163,7 +165,7 @@ describe('getTypeValue', () => {
});
});
it('returns an actual Struct', () => {
it('returns an actual Struct', (): void => {
expect(
getTypeDef('{"balance":"Balance","account_id":"AccountId","log":"(u64, Signature)"}')
).toEqual({
@@ -200,16 +202,16 @@ describe('getTypeValue', () => {
});
});
describe('getTypeClass', () => {
it('does not allow invalid types', () => {
describe('getTypeClass', (): void => {
it('does not allow invalid types', (): void => {
expect(
() => getTypeClass('SomethingInvalid' as any)
(): Constructor<Codec> => getTypeClass('SomethingInvalid' as any)
).toThrow(/determine type/);
});
});
describe('createType', () => {
it('allows creation of a Struct', () => {
describe('createType', (): void => {
it('allows creation of a Struct', (): void => {
expect(
createType('{"balance":"Balance","index":"u32"}', {
balance: 1234,
@@ -221,43 +223,43 @@ describe('createType', () => {
});
});
it('allows creation of a Enum (simple)', () => {
it('allows creation of a Enum (simple)', (): void => {
expect(
createType('{"_enum": ["A", "B", "C"]}', 1).toJSON()
).toEqual({ B: null });
});
it('allows creation of a Enum (parametrised)', () => {
it('allows creation of a Enum (parametrised)', (): void => {
expect(
createType('{"_enum": {"A": null, "B": "u32", "C": null} }', 1).toJSON()
).toEqual({ B: 0 });
});
it('allows creation of a [u8; 8]', () => {
it('allows creation of a [u8; 8]', (): void => {
expect(
createType('[u8; 8]', [0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67, 0x00]).toHex()
).toEqual('0x1200230045006700');
});
it('allows creation of a [u16; 4]', () => {
it('allows creation of a [u16; 4]', (): void => {
expect(
createType('[u16; 4]', [0x1200, 0x2300, 0x4500, 0x6700]).toU8a()
).toEqual(new Uint8Array([0x00, 0x12, 0x00, 0x23, 0x00, 0x45, 0x00, 0x67]));
});
it('throw error when create base is a StorageData with null value and isPedantic is true', () => {
it('throw error when create base is a StorageData with null value and isPedantic is true', (): void => {
const base = createType('StorageData', null);
expect(
() => createType('DoubleMap<Vec<(BlockNumber,EventIndex)>>', base, true)
(): Codec => createType('DoubleMap<Vec<(BlockNumber,EventIndex)>>', base, true)
).toThrow(/ Input doesn't match output, received 0x, created 0x00/);
});
it('throw error when create base is a StorageData with null value and isPedantic is true', () => {
it('throw error when create base is a StorageData with null value and isPedantic is true', (): void => {
const base = createType('StorageData', null);
expect(
() => createType('Vec<(BlockNumber,EventIndex)>', base, true)
(): Codec => createType('Vec<(BlockNumber,EventIndex)>', base, true)
).toThrow(/Input doesn't match output, received 0x, created 0x00/);
});
});
+31 -29
View File
@@ -35,21 +35,21 @@ export enum TypeDefInfo {
Null
}
export type TypeDefExtVecFixed = {
length: number,
type: string
};
export interface TypeDefExtVecFixed {
length: number;
type: string;
}
export type TypeDef = {
info: TypeDefInfo,
ext?: TypeDefExtVecFixed, // add additional here as required
name?: string,
type: string,
sub?: TypeDef | Array<TypeDef>
};
export interface TypeDef {
info: TypeDefInfo;
ext?: TypeDefExtVecFixed; // add additional here as required
name?: string;
type: string;
sub?: TypeDef | TypeDef[];
}
// safely split a string on ', ' while taking care of any nested occurences
export function typeSplit (type: string): Array<string> {
export function typeSplit (type: string): string[] {
let cDepth = 0; // compact/doublemap/linkedmap/option/vector depth
let fDepth = 0; // vector (fixed) depth
let sDepth = 0; // struct depth
@@ -119,7 +119,7 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
if (startingWith(type, '(', ')')) {
value.info = TypeDefInfo.Tuple;
value.sub = typeSplit(subType).map((inner) => getTypeDef(inner));
value.sub = typeSplit(subType).map((inner): TypeDef => getTypeDef(inner));
} else if (startingWith(type, '[', ']')) {
// this handles e.g. [u8;32]
const [vecType, _vecLen] = type.substr(1, type.length - 2).split(';');
@@ -129,7 +129,7 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
assert(vecLen <= 256, `Only support for [Type; <length>], where length <= 256`);
value.info = TypeDefInfo.VectorFixed;
value.ext = { length: vecLen, type: vecType } as TypeDefExtVecFixed;
value.ext = { length: vecLen, type: vecType } as unknown as TypeDefExtVecFixed;
} else if (startingWith(type, '{', '}')) {
const parsed = JSON.parse(type);
const keys = Object.keys(parsed);
@@ -139,12 +139,12 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
// not as pretty, but remain compatible with oo7 for both struct and Array types
value.sub = Array.isArray(details)
? details.map((name) => ({
? details.map((name): TypeDef => ({
info: TypeDefInfo.Plain,
name,
type: 'Null'
}))
: Object.keys(details).map((name) => ({
: Object.keys(details).map((name): TypeDef => ({
info: TypeDefInfo.Plain,
name,
type: details[name] || 'Null'
@@ -152,7 +152,7 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
value.info = TypeDefInfo.Enum;
} else {
value.info = TypeDefInfo.Struct;
value.sub = keys.map((name) => getTypeDef(parsed[name], name));
value.sub = keys.map((name): TypeDef => getTypeDef(parsed[name], name));
}
} else if (startingWith(type, 'Compact<', '>')) {
value.info = TypeDefInfo.Compact;
@@ -174,13 +174,21 @@ export function getTypeDef (_type: Text | string, name?: string): TypeDef {
return value;
}
export function createClass (type: Text | string): Constructor {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return getTypeClass(
getTypeDef(type)
);
}
// create an array of constructors from the input
export function getTypeClassMap (defs: Array<TypeDef>): { [index: string]: Constructor } {
return defs.reduce((result, sub) => {
export function getTypeClassMap (defs: TypeDef[]): { [index: string]: Constructor } {
return defs.reduce((result, sub): Record<string, Constructor> => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
result[sub.name as string] = getTypeClass(sub);
return result;
}, {} as { [index: string]: Constructor });
}, {} as unknown as Record<string, Constructor>);
}
// Returns the type Class for construction
@@ -202,7 +210,7 @@ export function getTypeClass (value: TypeDef, Fallback?: Constructor): Construct
assert(value.sub && Array.isArray(value.sub), 'Expected subtype for Enum');
return Enum.with(
getTypeClassMap(value.sub as Array<TypeDef>)
getTypeClassMap(value.sub as TypeDef[])
);
case TypeDefInfo.Option:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Option');
@@ -214,13 +222,13 @@ export function getTypeClass (value: TypeDef, Fallback?: Constructor): Construct
assert(Array.isArray(value.sub), 'Expected nested subtypes for Struct');
return Struct.with(
getTypeClassMap(value.sub as Array<TypeDef>)
getTypeClassMap(value.sub as TypeDef[])
);
case TypeDefInfo.Tuple:
assert(Array.isArray(value.sub), 'Expected nested subtypes for Tuple');
return Tuple.with(
(value.sub as Array<TypeDef>).map((Type) => getTypeClass(Type))
(value.sub as TypeDef[]).map((Type): Constructor<Codec> => getTypeClass(Type))
);
case TypeDefInfo.Vector:
assert(value.sub && !Array.isArray(value.sub), 'Expected subtype for Vector');
@@ -257,12 +265,6 @@ export function getTypeClass (value: TypeDef, Fallback?: Constructor): Construct
throw new Error(`Unable to determine type from '${value.type}'`);
}
export function createClass (type: Text | string): Constructor {
return getTypeClass(
getTypeDef(type)
);
}
// alias for createClass
export function ClassOf (name: string): Constructor {
return createClass(name);
+14 -9
View File
@@ -8,13 +8,17 @@ import { Constructor, RegistryTypes } from '../types';
import { createClass } from './createType';
export class TypeRegistry {
static readonly defaultRegistry: TypeRegistry = new TypeRegistry();
public static readonly defaultRegistry: TypeRegistry = new TypeRegistry();
private _registry: Map<string, Constructor> = new Map();
register (type: Constructor | RegistryTypes): void;
register (name: string, type: Constructor): void;
register (arg1: string | Constructor | RegistryTypes, arg2?: Constructor): void {
public register (type: Constructor | RegistryTypes): void;
// eslint-disable-next-line no-dupe-class-members
public register (name: string, type: Constructor): void;
// eslint-disable-next-line no-dupe-class-members
public register (arg1: string | Constructor | RegistryTypes, arg2?: Constructor): void {
if (isString(arg1)) {
const name = arg1;
const type = arg2!;
@@ -30,8 +34,8 @@ export class TypeRegistry {
}
}
private registerObject (obj: RegistryTypes, overwrite: boolean = true) {
Object.entries(obj).forEach(([name, type]) => {
private registerObject (obj: RegistryTypes, overwrite: boolean = true): void {
Object.entries(obj).forEach(([name, type]): void => {
if (overwrite || !this.get(name)) {
if (isString(type)) {
this._registry.set(name, createClass(type));
@@ -45,11 +49,11 @@ export class TypeRegistry {
});
}
get (name: string): Constructor | undefined {
public get (name: string): Constructor | undefined {
return this._registry.get(name);
}
getOrThrow (name: string, msg?: string): Constructor {
public getOrThrow (name: string, msg?: string): Constructor {
const type = this.get(name);
if (isUndefined(type)) {
@@ -62,8 +66,9 @@ export class TypeRegistry {
let defaultRegistry: TypeRegistry;
export default function getDefaultRegistry () {
export default function getDefaultRegistry (): TypeRegistry {
if (!defaultRegistry) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const defaultTypes = require('../index.types');
defaultRegistry = new TypeRegistry();
@@ -5,28 +5,28 @@
import U32 from '../../primitive/U32';
import compareArray from './compareArray';
describe('compareArray', () => {
describe('compareArray', (): void => {
const a = [new U32(123), new U32(456), new U32(789)];
it('returns false when second param is a non-array', () => {
it('returns false when second param is a non-array', (): void => {
expect(
compareArray(a, 123)
).toBe(false);
});
it('compares array of codec agains primitive', () => {
it('compares array of codec agains primitive', (): void => {
expect(
compareArray(a, [123, 456, 789])
).toBe(true);
});
it('compares array of codec agains codec', () => {
it('compares array of codec agains codec', (): void => {
expect(
compareArray(a, [new U32(123), new U32(456), new U32(789)])
).toBe(true);
});
it('compares primitive against primitive', () => {
it('compares primitive against primitive', (): void => {
expect(
compareArray(
[123, 456], [123, 456]
@@ -34,13 +34,13 @@ describe('compareArray', () => {
).toBe(true);
});
it('returns false when lengths are not matching', () => {
it('returns false when lengths are not matching', (): void => {
expect(
compareArray(a, [123])
).toBe(false);
});
it('returns false when value mismatches', () => {
it('returns false when value mismatches', (): void => {
expect(
compareArray(a, [123, 456, 999])
).toBe(false);
@@ -5,11 +5,11 @@
import { isFunction, isUndefined } from '@polkadot/util';
// NOTE These are used internally and when comparing objects, expects that
// when the second is an Array<Codec> that the first has to be as well
export default function compareArray (a: Array<any>, b?: any): boolean {
// when the second is an Codec[] that the first has to be as well
export default function compareArray (a: any[], b?: any): boolean {
if (Array.isArray(b)) {
return (a.length === b.length) && isUndefined(
a.find((value, index) =>
a.find((value, index): boolean =>
isFunction(value.eq)
? !value.eq(b[index])
: value !== b[index]
@@ -6,7 +6,7 @@ import { Codec } from '../../types';
import U32 from '../../primitive/U32';
import compareMap from './compareMap';
describe('compareMap', () => {
describe('compareMap', (): void => {
const a = new Map<string, Codec>([
['decimals', new U32(15)],
['missing', new U32(10)],
@@ -23,7 +23,7 @@ describe('compareMap', () => {
['foobar', new U32(5)]
]);
it('compares Map<string, Codec> against Object', () => {
it('compares Map<string, Codec> against Object', (): void => {
expect(
compareMap(a, {
decimals: 15,
@@ -33,7 +33,7 @@ describe('compareMap', () => {
).toBe(true);
});
it('compares Map<string, any> against entries array', () => {
it('compares Map<string, any> against entries array', (): void => {
expect(
compareMap(b, [
['missing', 10], ['decimals', 15], ['foobar', 5]
@@ -41,39 +41,39 @@ describe('compareMap', () => {
).toBe(true);
});
it('compares between 2 maps', () => {
it('compares between 2 maps', (): void => {
expect(compareMap(a, b)).toBe(true);
});
it('compares between 2 maps (both codec)', () => {
it('compares between 2 maps (both codec)', (): void => {
expect(compareMap(a, c)).toBe(true);
});
it('returns false when second param is a non-map, non-array, non-object', () => {
it('returns false when second param is a non-map, non-array, non-object', (): void => {
expect(
compareMap(a, 123)
).toBe(false);
});
it('returns false when second param is a array with non-entries', () => {
it('returns false when second param is a array with non-entries', (): void => {
expect(
compareMap(a, [123, 456, 789])
).toBe(false);
});
it('returns false when second param is a array with non-entries (only key)', () => {
it('returns false when second param is a array with non-entries (only key)', (): void => {
expect(
compareMap(a, [[123], [456], [789]])
).toBe(false);
});
it('returns false when properties are missing', () => {
it('returns false when properties are missing', (): void => {
expect(
compareMap(a, [['decimals', 15], ['wrong', 10], ['foobar', 5]])
).toBe(false);
});
it('returns false when lengths do not match', () => {
it('returns false when lengths do not match', (): void => {
expect(
compareMap(a, [['decimals', 15]])
).toBe(false);
+1 -1
View File
@@ -9,7 +9,7 @@ import { isFunction, isObject, isUndefined } from '@polkadot/util';
export default function compareMap (a: Map<any, any>, b?: any): boolean {
if (Array.isArray(b)) {
return (a.size === b.length) && isUndefined(
b.find((entry) => {
b.find((entry): boolean => {
if (!Array.isArray(entry) || entry.length !== 2) {
return true;
}
+10 -10
View File
@@ -4,17 +4,17 @@
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import { Constructor } from './types';
import { Codec, Constructor } from './types';
import * as Classes from './index.types';
const Types = Classes as { [index: string]: Constructor };
const UNCONSTRUCTABLE = ['origin', 'usize', 'vote'];
describe('types', () => {
describe('default creation', () => {
Object.keys(Types).forEach((name) => {
it(`creates an empty ${name}`, () => {
const constructFn = () =>
describe('types', (): void => {
describe('default creation', (): void => {
Object.keys(Types).forEach((name): void => {
it(`creates an empty ${name}`, (): void => {
const constructFn = (): Codec =>
new Types[name]();
if (UNCONSTRUCTABLE.includes(name.toLowerCase())) {
@@ -26,12 +26,12 @@ describe('types', () => {
});
});
describe('default creation (empty bytes)', () => {
describe('default creation (empty bytes)', (): void => {
(Types.Method as any).injectMethods(extrinsics);
Object.keys(Types).forEach((name) => {
it(`creates an empty ${name} (from empty bytes)`, () => {
const constructFn = () =>
Object.keys(Types).forEach((name): void => {
it(`creates an empty ${name} (from empty bytes)`, (): void => {
const constructFn = (): Codec =>
new Types[name](new Types.Bytes());
if (UNCONSTRUCTABLE.includes(name.toLowerCase())) {
+15 -15
View File
@@ -10,26 +10,26 @@ import jsonVec from '../json/AccountIdVec.001.json';
import AccountId from './AccountId';
import StorageData from './StorageData';
describe('AccountId', () => {
describe('defaults', () => {
describe('AccountId', (): void => {
describe('defaults', (): void => {
const id = new AccountId();
it('has a 32-byte length', () => {
it('has a 32-byte length', (): void => {
expect(id).toHaveLength(32);
});
it('is empty by default', () => {
it('is empty by default', (): void => {
expect(id.isEmpty).toBe(true);
});
it('equals the empty address', () => {
it('equals the empty address', (): void => {
expect(id.eq('5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM')).toBe(true);
});
});
describe('decoding', () => {
const testDecode = (type: string, input: Uint8Array | string | AccountId, expected: string) =>
it(`can decode from ${type}`, () => {
describe('decoding', (): void => {
const testDecode = (type: string, input: Uint8Array | string | AccountId, expected: string): void =>
it(`can decode from ${type}`, (): void => {
const a = new AccountId(input);
expect(a.toString()).toBe(expected);
});
@@ -59,9 +59,9 @@ describe('AccountId', () => {
);
});
describe('encoding', () => {
const testEncode = (to: 'toHex' | 'toJSON' | 'toString' | 'toU8a', expected: Uint8Array | string, input: string = '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF') =>
it(`can encode ${to}`, () => {
describe('encoding', (): void => {
const testEncode = (to: 'toHex' | 'toJSON' | 'toString' | 'toU8a', expected: Uint8Array | string, input: string = '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF'): void =>
it(`can encode ${to}`, (): void => {
const a = new AccountId(input);
expect(a[to]()).toEqual(expected);
@@ -76,17 +76,17 @@ describe('AccountId', () => {
1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8
]));
it('decodes to a non-empty value', () => {
it('decodes to a non-empty value', (): void => {
expect(new AccountId('7qT1BvpawNbqb3BZaBTMFMMAKrpJKLPf1LmEHR1JyarWJdMX').isEmpty).toBe(false);
});
});
describe('storage decoding', () => {
it('has the correct entries', () => {
describe('storage decoding', (): void => {
it('has the correct entries', (): void => {
setAddressPrefix(68);
const data = new StorageData(jsonVec.params.result.changes[0][1]);
const list = new Vector(AccountId, data).map((accountId) => accountId.toString());
const list = new Vector(AccountId, data).map((accountId): string => accountId.toString());
expect(list).toEqual([
'7qVJujLF3EDbZt5WfQXWvueFedMS4Vfk2Hb4GyR8jwksTLup',
+7 -7
View File
@@ -17,14 +17,14 @@ import U8aFixed from '../codec/U8aFixed';
* just a Uint8Array wrapper with a fixed length.
*/
export default class AccountId extends U8aFixed {
constructor (value: AnyU8a = new Uint8Array()) {
public constructor (value: AnyU8a = new Uint8Array()) {
super(
AccountId.decodeAccountId(value),
256
);
}
static encode (value: Uint8Array): string {
public static encode (value: Uint8Array): string {
return encodeAddress(value);
}
@@ -34,7 +34,7 @@ export default class AccountId extends U8aFixed {
} else if (isHex(value)) {
return hexToU8a(value.toString());
} else if (isString(value)) {
return decodeAddress((value as String).toString());
return decodeAddress((value as string).toString());
}
return value;
@@ -43,28 +43,28 @@ export default class AccountId extends U8aFixed {
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return super.eq(AccountId.decodeAccountId(other));
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): string {
public toJSON (): string {
return this.toString();
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return AccountId.encode(this);
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'AccountId';
}
}
@@ -5,56 +5,57 @@
import BN from 'bn.js';
import AccountIndex from './AccountIndex';
describe('AccountIndex', () => {
it('creates a BN representation', () => {
describe('AccountIndex', (): void => {
it('creates a BN representation', (): void => {
expect(
new AccountIndex(new Uint8Array([17, 18, 19, 20])).toNumber()
).toEqual(336794129);
});
it('creates a BN representation (from ss-58)', () => {
it('creates a BN representation (from ss-58)', (): void => {
expect(
new AccountIndex('Mwz15xP2').toNumber()
).toEqual(336794129);
});
it('constructs 2-byte from number', () => {
it('constructs 2-byte from number', (): void => {
expect(
new AccountIndex(256 * 1).toString()
).toEqual('25GUyv');
});
it('constructs from number', () => {
it('constructs from number', (): void => {
expect(
new AccountIndex(new BN(336794129)).toString()
).toEqual('Mwz15xP2');
});
it('compares ss-58 values', () => {
it('compares ss-58 values', (): void => {
expect(new AccountIndex(256 * 1).eq('25GUyv')).toBe(true);
});
it('compares numbers', () => {
it('compares numbers', (): void => {
expect(new AccountIndex('2jpAFn').eq(256 * 1)).toBe(true);
});
describe('calcLength', () => {
const testLength = (value: number, length: number) =>
describe('calcLength', (): void => {
const testLength = (value: number, length: number): void => {
expect(AccountIndex.calcLength(value)).toEqual(length);
};
it('returns 1 for <= 0xef', () => {
it('returns 1 for <= 0xef', (): void => {
testLength(0xef, 1);
});
it('returns 2 for > 0xef', () => {
it('returns 2 for > 0xef', (): void => {
testLength(0xf0, 2);
});
it('returns 4 bytes for 32-bit inputs', () => {
it('returns 4 bytes for 32-bit inputs', (): void => {
testLength(0xffeeddcc, 4);
});
it('returns 8 bytes for larger inputs', () => {
it('returns 8 bytes for larger inputs', (): void => {
testLength(0x122334455, 8);
});
});
+9 -9
View File
@@ -27,13 +27,13 @@ const MAX_4BYTE = new BN(1).shln(32);
* for an Account. We extends from [[U32]] to provide the number-like properties.
*/
export default class AccountIndex extends U32 {
constructor (value: AnyNumber = new BN(0)) {
public constructor (value: AnyNumber = new BN(0)) {
super(
AccountIndex.decodeAccountIndex(value)
);
}
static decodeAccountIndex (value: AnyNumber): BN | Uint8Array | number | string {
public static decodeAccountIndex (value: AnyNumber): BN | Uint8Array | number | string {
if (value instanceof AccountIndex) {
// `value.toBn()` on AccountIndex returns a pure BN (i.e. not an
// AccountIndex), which has the initial `toString()` implementation.
@@ -45,7 +45,7 @@ export default class AccountIndex extends U32 {
return AccountIndex.decodeAccountIndex(decodeAddress(value));
}
static calcLength (_value: BN | number): number {
public static calcLength (_value: BN | number): number {
const value = bnToBn(_value);
if (value.lte(MAX_1BYTE)) {
@@ -59,7 +59,7 @@ export default class AccountIndex extends U32 {
return 8;
}
static readLength (input: Uint8Array): [number, number] {
public static readLength (input: Uint8Array): [number, number] {
const first = input[0];
if (first === PREFIX_2BYTE) {
@@ -73,7 +73,7 @@ export default class AccountIndex extends U32 {
return [0, 1];
}
static writeLength (input: Uint8Array): Uint8Array {
public static writeLength (input: Uint8Array): Uint8Array {
switch (input.length) {
case 2: return new Uint8Array([PREFIX_2BYTE]);
case 4: return new Uint8Array([PREFIX_4BYTE]);
@@ -85,7 +85,7 @@ export default class AccountIndex extends U32 {
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
// shortcut for BN or Number, don't create an object
if (isBn(other) || isNumber(other)) {
return super.eq(other);
@@ -98,14 +98,14 @@ export default class AccountIndex extends U32 {
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): string {
public toJSON (): string {
return this.toString();
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
const length = AccountIndex.calcLength(this);
return encodeAddress(this.toU8a().subarray(0, length));
@@ -114,7 +114,7 @@ export default class AccountIndex extends U32 {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'AccountIndex';
}
}
+3 -3
View File
@@ -12,7 +12,7 @@ import U64 from './U64';
* An Account information structure for contracts
*/
export default class AccountInfo extends Struct {
constructor (value: any) {
public constructor (value: any) {
super({
trieId: Bytes,
currentMemStored: U64
@@ -22,14 +22,14 @@ export default class AccountInfo extends Struct {
/**
* @description The size of stored value in octet
*/
get currentMemStored (): U64 {
public get currentMemStored (): U64 {
return this.get('currentMemStored') as U64;
}
/**
* @description Unique ID for the subtree encoded as a byte
*/
get trieId (): Bytes {
public get trieId (): Bytes {
return this.get('trieId') as Bytes;
}
}
+10 -10
View File
@@ -6,27 +6,27 @@ import AccountId from './AccountId';
import AccountIndex from './AccountIndex';
import Address from './Address';
describe('Address', () => {
const testDecode = (type: string, input: Address | AccountId | AccountIndex | Array<number> | Uint8Array, expected: string) =>
it(`can decode from ${type}`, () => {
describe('Address', (): void => {
const testDecode = (type: string, input: Address | AccountId | AccountIndex | number[] | Uint8Array, expected: string): void =>
it(`can decode from ${type}`, (): void => {
const a = new Address(input);
expect(a.toString()).toBe(expected);
});
describe('utility', () => {
it('equals on AccountId', () => {
describe('utility', (): void => {
it('equals on AccountId', (): void => {
const addr = '5DkQbYAExs3M2sZgT1Ec3mKfZnAQCL4Dt9beTCknkCUn5jzo';
expect(new Address(addr).eq(addr)).toBe(true);
});
it('equals on AccountIndex', () => {
it('equals on AccountIndex', (): void => {
// see the test below - these are equivalent (with different prefix encoding)
expect(new Address('2jpAFn').eq('25GUyv')).toBe(true);
});
});
describe('decoding', () => {
describe('decoding', (): void => {
testDecode(
'Address',
new Address('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF'),
@@ -91,9 +91,9 @@ describe('Address', () => {
// );
});
describe('encoding', () => {
const testEncode = (to: 'toHex' | 'toString' | 'toU8a', expected: string | Uint8Array) =>
it(`can encode ${to}`, () => {
describe('encoding', (): void => {
const testEncode = (to: 'toHex' | 'toString' | 'toU8a', expected: string | Uint8Array): void =>
it(`can encode ${to}`, (): void => {
const a = new Address('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF');
expect(a[to]()).toEqual(expected);
});
+12 -12
View File
@@ -12,7 +12,7 @@ import Base from '../codec/Base';
import AccountId from './AccountId';
import AccountIndex from './AccountIndex';
type AnyAddress = BN | Address | AccountId | AccountIndex | Array<number> | Uint8Array | number | string;
type AnyAddress = BN | Address | AccountId | AccountIndex | number[] | Uint8Array | number | string;
export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]);
@@ -25,13 +25,13 @@ export const ACCOUNT_ID_PREFIX = new Uint8Array([0xff]);
* is encoded as `[ <prefix-byte>, ...publicKey/...bytes ]` as per spec
*/
export default class Address extends Base<AccountId | AccountIndex> implements Codec {
constructor (value: AnyAddress = new Uint8Array()) {
public constructor (value: AnyAddress = new Uint8Array()) {
super(
Address.decodeAddress(value)
);
}
static decodeAddress (value: AnyAddress): AccountId | AccountIndex {
public static decodeAddress (value: AnyAddress): AccountId | AccountIndex {
if (value instanceof AccountId || value instanceof AccountIndex) {
return value;
} else if (isBn(value) || isNumber(value)) {
@@ -66,7 +66,7 @@ export default class Address extends Base<AccountId | AccountIndex> implements C
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
const rawLength = this.rawLength;
return rawLength + (
@@ -80,14 +80,14 @@ export default class Address extends Base<AccountId | AccountIndex> implements C
/**
* @description Checks if the value is an empty value
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return this.raw.isEmpty;
}
/**
* @description The length of the raw value, either AccountIndex or AccountId
*/
get rawLength (): number {
public get rawLength (): number {
return this.raw instanceof AccountIndex
? AccountIndex.calcLength(this.raw)
: this.raw.encodedLength;
@@ -96,35 +96,35 @@ export default class Address extends Base<AccountId | AccountIndex> implements C
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return this.raw.eq(other);
}
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
return u8aToHex(this.toU8a());
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): string {
public toJSON (): string {
return this.raw.toJSON();
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return this.raw.toString();
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'Address';
}
@@ -132,7 +132,7 @@ export default class Address extends Base<AccountId | AccountIndex> implements C
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
public toU8a (isBare?: boolean): Uint8Array {
const encoded = this.raw.toU8a().subarray(0, this.rawLength);
return isBare
+1 -1
View File
@@ -13,7 +13,7 @@ export default class Balance extends U128 {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
// NOTE Balance we treat as a special case, don't return the base u128 - there
// is typically special processing downstream, i.e. different inputs, it gets
// treated as a primitive in this case
+12 -11
View File
@@ -5,10 +5,11 @@
import Bool from './Bool';
import { CodecTo } from '../types';
describe('Bool', () => {
describe('decode', () => {
const testDecode = (type: string, input: Uint8Array | boolean | Boolean | Bool | number, expected: boolean) =>
it(`can decode from ${type}`, () => {
describe('Bool', (): void => {
describe('decode', (): void => {
// eslint-disable-next-line @typescript-eslint/ban-types
const testDecode = (type: string, input: Uint8Array | boolean | Boolean | Bool | number, expected: boolean): void =>
it(`can decode from ${type}`, (): void => {
expect(new Bool(input).toJSON()).toBe(expected);
});
@@ -19,9 +20,9 @@ describe('Bool', () => {
testDecode('Uint8Array', Uint8Array.from([1]), true);
});
describe('encode', () => {
const testEncode = (to: CodecTo, expected: string | Uint8Array | boolean, value: boolean) =>
it(`can encode ${to}`, () => {
describe('encode', (): void => {
const testEncode = (to: CodecTo, expected: string | Uint8Array | boolean, value: boolean): void =>
it(`can encode ${to}`, (): void => {
expect(new Bool(value)[to]()).toEqual(expected);
});
@@ -32,16 +33,16 @@ describe('Bool', () => {
testEncode('toU8a', Uint8Array.from([0]), false);
});
it('correctly encodes length', () => {
it('correctly encodes length', (): void => {
expect(new Bool(true).encodedLength).toEqual(1);
});
describe('utils', () => {
it('compares agains a boolean', () => {
describe('utils', (): void => {
it('compares agains a boolean', (): void => {
expect(new Bool(true).eq(true)).toBe(true);
});
it('compares agains a Bool', () => {
it('compares agains a Bool', (): void => {
expect(new Bool(false).eq(new Bool(false))).toBe(true);
});
});
+11 -9
View File
@@ -13,7 +13,8 @@ import { Codec } from '../types';
* @noInheritDoc
*/
export default class Bool extends Boolean implements Codec {
constructor (value: Bool | Boolean | Uint8Array | boolean | number = false) {
// eslint-disable-next-line @typescript-eslint/ban-types
public constructor (value: Bool | Boolean | Uint8Array | boolean | number = false) {
super(
Bool.decodeBool(value)
);
@@ -32,21 +33,21 @@ export default class Bool extends Boolean implements Codec {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return 1;
}
/**
* @description Checks if the value is an empty value (always false)
*/
get isEmpty (): boolean {
public get isEmpty (): boolean {
return false;
}
/**
* @description Compares the value of the input to see if there is a match
*/
eq (other?: any): boolean {
public eq (other?: any): boolean {
return this.valueOf() === (
other instanceof Boolean
? other.valueOf()
@@ -57,28 +58,28 @@ export default class Bool extends Boolean implements Codec {
/**
* @description Returns a hex string representation of the value
*/
toHex (): string {
public toHex (): string {
return u8aToHex(this.toU8a());
}
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
toJSON (): boolean {
public toJSON (): boolean {
return this.valueOf();
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'bool';
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
public toString (): string {
return `${this.toJSON()}`;
}
@@ -86,7 +87,8 @@ export default class Bool extends Boolean implements Codec {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
return new Uint8Array([this.valueOf() ? 1 : 0]);
}
}
+7 -7
View File
@@ -5,29 +5,29 @@
import Bytes from './Bytes';
import StorageData from './StorageData';
describe('Bytes', () => {
describe('Bytes', (): void => {
const CODE = new Uint8Array([0x14, 0x3a, 0x63, 0x6f, 0x64, 0x65]);
describe('construction', () => {
it('decodes when input is string', () => {
describe('construction', (): void => {
it('decodes when input is string', (): void => {
expect(
new Bytes(':code').toU8a()
).toEqual(CODE);
});
it('decodes when hex is not length prefixed', () => {
it('decodes when hex is not length prefixed', (): void => {
expect(
new Bytes('0x3a636f6465').toU8a()
).toEqual(CODE);
});
it('decodes from Array<number>', () => {
it('decodes from number[]', (): void => {
expect(
new Bytes([0x3a, 0x63, 0x6f, 0x64, 0x65]).toU8a()
).toEqual(CODE);
});
it('creates via storagedata (no prefix)', () => {
it('creates via storagedata (no prefix)', (): void => {
expect(
new Bytes(
new StorageData('0x3a636f6465')
@@ -35,7 +35,7 @@ describe('Bytes', () => {
).toEqual(CODE);
});
it('creates via storagedata (with length prefix)', () => {
it('creates via storagedata (with length prefix)', (): void => {
expect(
new Bytes(
new StorageData('0x143a636f6465')
+4 -4
View File
@@ -16,7 +16,7 @@ import U8a from '../codec/U8a';
* as what is found in [[Text]] and [[Vector]])
*/
export default class Bytes extends U8a {
constructor (value?: AnyU8a) {
public constructor (value?: AnyU8a) {
super(Bytes.decodeBytes(value));
}
@@ -65,14 +65,14 @@ export default class Bytes extends U8a {
/**
* @description The length of the value when encoded as a Uint8Array
*/
get encodedLength (): number {
public get encodedLength (): number {
return this.length + Compact.encodeU8a(this.length).length;
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'Bytes';
}
@@ -80,7 +80,7 @@ export default class Bytes extends U8a {
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
toU8a (isBare?: boolean): Uint8Array {
public toU8a (isBare?: boolean): Uint8Array {
return isBare
? super.toU8a(isBare)
: Compact.addLengthPrefix(this);
+1 -1
View File
@@ -13,7 +13,7 @@ export default class Data extends U8a {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'Data';
}
}
+29 -26
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Constructor } from '../types';
import { Constructor, Codec } from '../types';
import { assert, isUndefined, stringCamelCase, u8aToHex } from '@polkadot/util';
@@ -16,7 +16,7 @@ import Null from './Null';
import U32 from './U32';
import Unconstructable from './Unconstructable';
const EventTypes: { [index: string]: Constructor<EventData> } = {};
const EventTypes: Record<string, Constructor<EventData>> = {};
/**
* @name EventIndex
@@ -33,11 +33,14 @@ export class EventIndex extends U32 {
*/
export class EventData extends Tuple {
private _meta: EventMetadataV6;
private _method: string;
private _section: string;
private _typeDef: Array<TypeDef>;
constructor (Types: Array<Constructor>, value: Uint8Array, typeDef: Array<TypeDef>, meta: EventMetadataV6, section: string, method: string) {
private _method: string;
private _section: string;
private _typeDef: TypeDef[];
public constructor (Types: Constructor[], value: Uint8Array, typeDef: TypeDef[], meta: EventMetadataV6, section: string, method: string) {
super(Types, value);
this._meta = meta;
@@ -49,28 +52,28 @@ export class EventData extends Tuple {
/**
* @description The wrapped [[EventMetadata]]
*/
get meta (): EventMetadataV6 {
public get meta (): EventMetadataV6 {
return this._meta;
}
/**
* @description The method as a string
*/
get method (): string {
public get method (): string {
return this._method;
}
/**
* @description The section as a string
*/
get section (): string {
public get section (): string {
return this._section;
}
/**
* @description The [[TypeDef]] for this event
*/
get typeDef (): Array<TypeDef> {
public get typeDef (): TypeDef[] {
return this._typeDef;
}
}
@@ -82,7 +85,7 @@ export class EventData extends Tuple {
* that indicates the actual event fired
*/
export class EventId extends U8aFixed {
constructor (value?: any) {
public constructor (value?: any) {
super(value, 16);
}
}
@@ -96,7 +99,7 @@ export class EventId extends U8aFixed {
export default class Event extends Struct {
// Currently we _only_ decode from Uint8Array, since we expect it to
// be used via EventRecord
constructor (_value?: Uint8Array) {
public constructor (_value?: Uint8Array) {
const { DataType, value } = Event.decodeEvent(_value);
super({
@@ -105,7 +108,7 @@ export default class Event extends Struct {
}, value);
}
static decodeEvent (value: Uint8Array = new Uint8Array()) {
public static decodeEvent (value: Uint8Array = new Uint8Array()): { DataType: Constructor<Null> | Constructor<EventData>; value?: { index: Uint8Array; data: Uint8Array } } {
if (!value.length) {
return {
DataType: Null
@@ -128,20 +131,20 @@ export default class Event extends Struct {
// This is called/injected by the API on init, allowing a snapshot of
// the available system events to be used in lookups
static injectMetadata (metadata: Metadata): void {
public static injectMetadata (metadata: Metadata): void {
metadata.asV6.modules
.filter((section) => section.events.isSome)
.forEach((section, sectionIndex) => {
.filter((section): boolean => section.events.isSome)
.forEach((section, sectionIndex): void => {
const sectionName = stringCamelCase(section.name.toString());
section.events.unwrap().forEach((meta, methodIndex) => {
section.events.unwrap().forEach((meta, methodIndex): void => {
const methodName = meta.name.toString();
const eventIndex = new Uint8Array([sectionIndex, methodIndex]);
const typeDef = meta.args.map((arg) => getTypeDef(arg));
const Types = typeDef.map((typeDef) => getTypeClass(typeDef, Unconstructable.with(typeDef)));
const typeDef = meta.args.map((arg): TypeDef => getTypeDef(arg));
const Types = typeDef.map((typeDef): Constructor<Codec> => getTypeClass(typeDef, Unconstructable.with(typeDef)));
EventTypes[eventIndex.toString()] = class extends EventData {
constructor (value: Uint8Array) {
public constructor (value: Uint8Array) {
super(Types, value, typeDef, meta, sectionName, methodName);
}
};
@@ -152,42 +155,42 @@ export default class Event extends Struct {
/**
* @description The wrapped [[EventData]]
*/
get data (): EventData {
public get data (): EventData {
return this.get('data') as EventData;
}
/**
* @description The [[EventId]], identifying the raw event
*/
get index (): EventId {
public get index (): EventId {
return this.get('index') as EventId;
}
/**
* @description The [[EventMetadata]] with the documentation
*/
get meta (): EventMetadataV6 {
public get meta (): EventMetadataV6 {
return this.data.meta;
}
/**
* @description The method string identifying the event
*/
get method (): string {
public get method (): string {
return this.data.method;
}
/**
* @description The section string identifying the event
*/
get section (): string {
public get section (): string {
return this.data.section;
}
/**
* @description The [[TypeDef]] for the event
*/
get typeDef (): Array<TypeDef> {
public get typeDef (): TypeDef[] {
return this.data.typeDef;
}
}
@@ -12,15 +12,15 @@ import metadata from '../Metadata/static';
import Event from './Event';
import EventRecord from './EventRecord';
describe('EventRecord', () => {
describe('EventRecord_0_76', () => {
beforeEach(() => {
describe('EventRecord', (): void => {
describe('EventRecord_0_76', (): void => {
beforeEach((): void => {
Event.injectMetadata(
new Metadata(metadataV0)
);
});
it('decodes correctly', () => {
it('decodes correctly', (): void => {
const records: Vector<EventRecord> = createType('Vec<EventRecord>', json1.params.result.changes[0][1]) as any;
const er = records[0];
@@ -28,21 +28,21 @@ describe('EventRecord', () => {
});
});
describe('EventRecord (current)', () => {
beforeEach(() => {
describe('EventRecord (current)', (): void => {
beforeEach((): void => {
Event.injectMetadata(
new Metadata(metadata)
);
});
it('decodes older eventrecord correctly', () => {
it('decodes older eventrecord correctly', (): void => {
const records: Vector<EventRecord> = createType('Vec<EventRecord>', json1.params.result.changes[0][1], true) as any;
const er = records[0];
expect(er.phase.type).toEqual('ApplyExtrinsic');
});
it('decodes eventrecord with topics correctly', () => {
it('decodes eventrecord with topics correctly', (): void => {
const hex = json3.params.result.changes[0][1];
const records: Vector<EventRecord> = createType('Vec<EventRecord>', hex, true) as any;
const er = records[0];
+15 -16
View File
@@ -34,7 +34,7 @@ export class Finalization extends Null {
* An [[Enum]] that indicates the specific phase where the [[EventRecord]] was generated
*/
export class Phase extends Enum {
constructor (value: any, index?: number) {
public constructor (value: any, index?: number) {
super({
ApplyExtrinsic,
Finalization
@@ -44,7 +44,7 @@ export class Phase extends Enum {
/**
* @description Returns the item as a [[ApplyExtrinsic]]
*/
get asApplyExtrinsic (): ApplyExtrinsic {
public get asApplyExtrinsic (): ApplyExtrinsic {
assert(this.isApplyExtrinsic, `Cannot convert '${this.type}' via asApplyExtrinsic`);
return this.value as ApplyExtrinsic;
@@ -53,7 +53,7 @@ export class Phase extends Enum {
/**
* @description Returns the item as a [[Finalization]]
*/
get asFinalization (): Finalization {
public get asFinalization (): Finalization {
assert(this.isFinalization, `Cannot convert '${this.type}' via asFinalization`);
return this.value as Finalization;
@@ -62,14 +62,14 @@ export class Phase extends Enum {
/**
* @description true when this is a ApplyExtrinsic
*/
get isApplyExtrinsic (): boolean {
public get isApplyExtrinsic (): boolean {
return this.type === 'ApplyExtrinsic';
}
/**
* @description true when this is a ApplyExtrinsic
*/
get isFinalization (): boolean {
public get isFinalization (): boolean {
return this.type === 'Finalization';
}
}
@@ -80,9 +80,8 @@ export class Phase extends Enum {
* A record for an [[Event]] (as specified by [[Metadata]]) with the specific [[Phase]] of
* application.
*/
// tslint:disable-next-line
export class EventRecord_0_76 extends Struct {
constructor (value: any) {
export class EventRecord0to76 extends Struct {
public constructor (value: any) {
super({
phase: Phase,
event: Event
@@ -92,21 +91,21 @@ export class EventRecord_0_76 extends Struct {
/**
* @description The [[Event]] this record refers to
*/
get event (): Event {
public get event (): Event {
return this.get('event') as Event;
}
/**
* @description The [[Phase]] where the event was generated
*/
get phase (): Phase {
public get phase (): Phase {
return this.get('phase') as Phase;
}
/**
* @description The [[Hash]] topics for this event (empty, compat)
*/
get topics (): Vector<Hash> {
public get topics (): Vector<Hash> {
return new (Vector.with(Hash))();
}
}
@@ -118,7 +117,7 @@ export class EventRecord_0_76 extends Struct {
* application.
*/
export default class EventRecord extends Struct {
constructor (value: any) {
public constructor (value: any) {
super({
phase: Phase,
event: Event,
@@ -126,26 +125,26 @@ export default class EventRecord extends Struct {
}, value);
}
static Fallback = EventRecord_0_76;
public static Fallback = EventRecord0to76;
/**
* @description The [[Event]] this record refers to
*/
get event (): Event {
public get event (): Event {
return this.get('event') as Event;
}
/**
* @description The [[Phase]] where the event was generated
*/
get phase (): Phase {
public get phase (): Phase {
return this.get('phase') as Phase;
}
/**
* @description The [[Hash]] topics for this event
*/
get topics (): Vector<Hash> {
public get topics (): Vector<Hash> {
return this.get('topics') as Vector<Hash>;
}
}
+2 -2
View File
@@ -13,14 +13,14 @@ import U8aFixed from '../codec/U8aFixed';
* as a sane default for fixed-length hash representations.
*/
export default class H160 extends U8aFixed {
constructor (value?: AnyU8a) {
public constructor (value?: AnyU8a) {
super(value, 160);
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'H160';
}
}
+2 -2
View File
@@ -13,14 +13,14 @@ import U8aFixed from '../codec/U8aFixed';
* as a sane default for fixed-length hash representations.
*/
export default class H256 extends U8aFixed {
constructor (value?: AnyU8a) {
public constructor (value?: AnyU8a) {
super(value, 256);
}
/**
* @description Returns the base runtime type name for this instance
*/
toRawType (): string {
public toRawType (): string {
return 'H256';
}
}

Some files were not shown because too many files have changed in this diff Show More