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
+117 -91
View File
@@ -5,8 +5,8 @@
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { AnyFunction, Codec, CodecArg, RegistryTypes } from '@polkadot/types/types';
import {
ApiInterface$Rx, ApiInterface$Events, ApiOptions, ApiTypes, DecorateMethodOptions,
DecoratedRpc, DecoratedRpc$Section,
ApiInterfaceRx, ApiInterfaceEvents, ApiOptions, ApiTypes, DecorateMethodOptions,
DecoratedRpc, DecoratedRpcSection,
QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs,
SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics, Signer
} from './types';
@@ -22,7 +22,7 @@ import { Storage } from '@polkadot/api-metadata/storage/types';
import storageFromMeta from '@polkadot/api-metadata/storage/fromMetadata';
import RpcCore from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
import { Event, getTypeRegistry, Hash, Metadata, Method, RuntimeVersion, Null } from '@polkadot/types';
import { Event, getTypeRegistry, Hash, Metadata, Method, RuntimeVersion, Null, U64 } from '@polkadot/types';
import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage';
import { MethodFunction, ModulesWithMethods } from '@polkadot/types/primitive/Method';
import * as srmlTypes from '@polkadot/types/srml/definitions';
@@ -34,20 +34,20 @@ import injectNodeCompat from './nodeCompat';
import createSubmittable, { SubmittableExtrinsic } from './SubmittableExtrinsic';
import { decorateSections } from './util/decorate';
type MetaDecoration = {
callIndex?: Uint8Array,
meta: any,
method: string,
section: string,
toJSON: () => any
};
interface MetaDecoration {
callIndex?: Uint8Array;
meta: any;
method: string;
section: string;
toJSON: () => any;
}
const INIT_ERROR = `Api needs to be initialised before using, listen on 'ready'`;
const KEEPALIVE_INTERVAL = 15000;
const l = logger('api/decorator');
let pkgJson: { name: string, version: string };
let pkgJson: { name: string; version: string };
try {
pkgJson = require('./package.json');
@@ -66,20 +66,35 @@ function rxDecorateMethod<Method extends AnyFunction> (method: Method): Method {
export default abstract class ApiBase<ApiType> {
private _consts?: Constants;
private _derive?: ReturnType<ApiBase<ApiType>['decorateDerive']>;
private _eventemitter: EventEmitter;
private _extrinsics?: SubmittableExtrinsics<ApiType>;
private _genesisHash?: Hash;
protected _isConnected: BehaviorSubject<boolean>;
private _isReady: boolean = false;
protected readonly _options: ApiOptions;
private _query?: QueryableStorage<ApiType>;
private _queryMulti: QueryableStorageMulti<ApiType>;
private _rpc: DecoratedRpc<ApiType>;
protected _rpcCore: RpcCore;
private _runtimeMetadata?: Metadata;
private _runtimeVersion?: RuntimeVersion;
private _rx: Partial<ApiInterface$Rx> = {};
private _rx: Partial<ApiInterfaceRx> = {};
private _type: ApiTypes;
/**
@@ -100,9 +115,9 @@ export default abstract class ApiBase<ApiType> {
* });
* ```
*/
constructor (provider: ApiOptions | ProviderInterface = {}, type: ApiTypes) {
public constructor (provider: ApiOptions | ProviderInterface = {}, type: ApiTypes) {
const options = isObject(provider) && isFunction((provider as ProviderInterface).send)
? { provider } as ApiOptions
? { provider } as unknown as ApiOptions
: provider as ApiOptions;
const thisProvider = options.source
? options.source._rpcCore.provider.clone()
@@ -125,7 +140,7 @@ export default abstract class ApiBase<ApiType> {
// we only re-register the types (global) if this is not a cloned instance
if (!options.source) {
// first register the definitions we have, i.e. those where there are no type classes
Object.values(srmlTypes).forEach(({ types }) =>
Object.values(srmlTypes).forEach(({ types }): void =>
this.registerTypes(types)
);
@@ -139,7 +154,7 @@ export default abstract class ApiBase<ApiType> {
/**
* @description Contains the genesis Hash of the attached chain. Apart from being useful to determine the actual chain, it can also be used to sign immortal transactions.
*/
get genesisHash (): Hash {
public get genesisHash (): Hash {
assert(!isUndefined(this._genesisHash), INIT_ERROR);
return this._genesisHash as Hash;
@@ -148,21 +163,21 @@ export default abstract class ApiBase<ApiType> {
/**
* @description `true` when subscriptions are supported
*/
get hasSubscriptions (): boolean {
public get hasSubscriptions (): boolean {
return this._rpcCore.provider.hasSubscriptions;
}
/**
* @description The library information name & version (from package.json)
*/
get libraryInfo (): string {
public get libraryInfo (): string {
return `${pkgJson.name} v${pkgJson.version}`;
}
/**
* @description Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.
*/
get runtimeMetadata (): Metadata {
public get runtimeMetadata (): Metadata {
assert(!isUndefined(this._runtimeMetadata), INIT_ERROR);
return this._runtimeMetadata as Metadata;
@@ -171,7 +186,7 @@ export default abstract class ApiBase<ApiType> {
/**
* @description Contains the version information for the current runtime.
*/
get runtimeVersion (): RuntimeVersion {
public get runtimeVersion (): RuntimeVersion {
assert(!isUndefined(this._runtimeVersion), INIT_ERROR);
return this._runtimeVersion as RuntimeVersion;
@@ -180,14 +195,14 @@ export default abstract class ApiBase<ApiType> {
/**
* @description The type of this API instance, either 'rxjs' or 'promise'
*/
get type (): ApiTypes {
public get type (): ApiTypes {
return this._type;
}
/**
* @description Set an external signer which will be used to sign extrinsic when account passed in is not KeyringPair
*/
setSigner (signer: Signer) {
public setSigner (signer: Signer): void {
this._rx.signer = signer;
}
@@ -203,7 +218,7 @@ export default abstract class ApiBase<ApiType> {
* });
* ```
*/
get derive (): ReturnType<ApiBase<ApiType>['decorateDerive']> {
public get derive (): ReturnType<ApiBase<ApiType>['decorateDerive']> {
assert(!isUndefined(this._derive), INIT_ERROR);
return this._derive as ReturnType<ApiBase<ApiType>['decorateDerive']>;
@@ -221,7 +236,7 @@ export default abstract class ApiBase<ApiType> {
* console.log(api.consts.democracy.enactmentPeriod.toString())
* ```
*/
get consts (): Constants {
public get consts (): Constants {
assert(!isUndefined(this._consts), INIT_ERROR);
return this._consts as Constants;
@@ -241,7 +256,7 @@ export default abstract class ApiBase<ApiType> {
* });
* ```
*/
get query (): QueryableStorage<ApiType> {
public get query (): QueryableStorage<ApiType> {
assert(!isUndefined(this._query), INIT_ERROR);
return this._query as QueryableStorage<ApiType>;
@@ -269,7 +284,7 @@ export default abstract class ApiBase<ApiType> {
* );
* ```
*/
get queryMulti (): QueryableStorageMulti<ApiType> {
public get queryMulti (): QueryableStorageMulti<ApiType> {
return this._queryMulti;
}
@@ -287,7 +302,7 @@ export default abstract class ApiBase<ApiType> {
* });
* ```
*/
get rpc (): DecoratedRpc<ApiType> {
public get rpc (): DecoratedRpc<ApiType> {
return this._rpc;
}
@@ -305,7 +320,7 @@ export default abstract class ApiBase<ApiType> {
* });
* ```
*/
get tx (): SubmittableExtrinsics<ApiType> {
public get tx (): SubmittableExtrinsics<ApiType> {
assert(!isUndefined(this._extrinsics), INIT_ERROR);
return this._extrinsics as SubmittableExtrinsics<ApiType>;
@@ -314,7 +329,7 @@ export default abstract class ApiBase<ApiType> {
/**
* @description Disconnect from the underlying provider, halting all comms
*/
disconnect (): void {
public disconnect (): void {
this._rpcCore.disconnect();
}
@@ -328,16 +343,16 @@ export default abstract class ApiBase<ApiType> {
* <BR>
*
* ```javascript
* api.on('connected', () => {
* api.on('connected', (): void => {
* console.log('API has been connected to the endpoint');
* });
*
* api.on('disconnected', () => {
* api.on('disconnected', (): void => {
* console.log('API has been disconnected from the endpoint');
* });
* ```
*/
on (type: ApiInterface$Events, handler: (...args: Array<any>) => any): this {
public on (type: ApiInterfaceEvents, handler: (...args: any[]) => any): this {
this._eventemitter.on(type, handler);
return this;
@@ -353,7 +368,7 @@ export default abstract class ApiBase<ApiType> {
* <BR>
*
* ```javascript
* const handler = () => {
* const handler = (): void => {
* console.log('Connected !);
* };
*
@@ -364,7 +379,7 @@ export default abstract class ApiBase<ApiType> {
* api.off('connected', handler);
* ```
*/
off (type: ApiInterface$Events, handler: (...args: Array<any>) => any): this {
public off (type: ApiInterfaceEvents, handler: (...args: any[]) => any): this {
this._eventemitter.removeListener(type, handler);
return this;
@@ -380,16 +395,16 @@ export default abstract class ApiBase<ApiType> {
* <BR>
*
* ```javascript
* api.once('connected', () => {
* api.once('connected', (): void => {
* console.log('API has been connected to the endpoint');
* });
*
* api.once('disconnected', () => {
* api.once('disconnected', (): void => {
* console.log('API has been disconnected from the endpoint');
* });
* ```
*/
once (type: ApiInterface$Events, handler: (...args: Array<any>) => any): this {
public once (type: ApiInterfaceEvents, handler: (...args: any[]) => any): this {
this._eventemitter.once(type, handler);
return this;
@@ -398,7 +413,7 @@ export default abstract class ApiBase<ApiType> {
/**
* @description Register additional user-defined of chain-specific types in the type registry
*/
registerTypes (types?: RegistryTypes): void {
public registerTypes (types?: RegistryTypes): void {
if (types) {
getTypeRegistry().register(types);
}
@@ -420,16 +435,16 @@ export default abstract class ApiBase<ApiType> {
* implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon
* via `deocrateMethod`.
*/
protected abstract decorateMethod (method: (...args: Array<any>) => Observable<any>, options?: DecorateMethodOptions): any;
protected abstract decorateMethod (method: (...args: any[]) => Observable<any>, options?: DecorateMethodOptions): any;
private emit (type: ApiInterface$Events, ...args: Array<any>): void {
private emit (type: ApiInterfaceEvents, ...args: any[]): void {
this._eventemitter.emit(type, ...args);
}
private init (): void {
let healthTimer: NodeJS.Timeout | null = null;
this._rpcCore.provider.on('disconnected', () => {
this._rpcCore.provider.on('disconnected', (): void => {
this.emit('disconnected');
this._isConnected.next(false);
@@ -439,11 +454,11 @@ export default abstract class ApiBase<ApiType> {
}
});
this._rpcCore.provider.on('error', (error) => {
this._rpcCore.provider.on('error', (error): void => {
this.emit('error', error);
});
this._rpcCore.provider.on('connected', async () => {
this._rpcCore.provider.on('connected', async (): Promise<void> => {
this.emit('connected');
this._isConnected.next(true);
@@ -459,8 +474,8 @@ export default abstract class ApiBase<ApiType> {
this.emit('ready', this);
}
healthTimer = setInterval(() => {
this._rpcCore.system.health().toPromise().catch(() => {
healthTimer = setInterval((): void => {
this._rpcCore.system.health().toPromise().catch((): void => {
// ignore
});
}, KEEPALIVE_INTERVAL);
@@ -514,7 +529,7 @@ export default abstract class ApiBase<ApiType> {
this._rx.tx = this.decorateExtrinsics(extrinsics, rxDecorateMethod);
this._rx.query = this.decorateStorage(storage, rxDecorateMethod);
this._rx.consts = constants;
this._derive = this.decorateDerive(this._rx as ApiInterface$Rx, this.decorateMethod);
this._derive = this.decorateDerive(this._rx as ApiInterfaceRx, this.decorateMethod);
// only inject if we are not a clone (global init)
if (!this._options.source) {
@@ -539,24 +554,24 @@ export default abstract class ApiBase<ApiType> {
}
private decorateRpc<ApiType> (rpc: RpcCore, decorateMethod: ApiBase<ApiType>['decorateMethod']): DecoratedRpc<ApiType> {
return ['author', 'chain', 'state', 'system'].reduce((result, _sectionName) => {
return ['author', 'chain', 'state', 'system'].reduce((result, _sectionName): DecoratedRpc<ApiType> => {
const sectionName = _sectionName as keyof DecoratedRpc<ApiType>;
result[sectionName] = Object.keys(rpc[sectionName]).reduce((section, methodName) => {
result[sectionName] = Object.keys(rpc[sectionName]).reduce((section, methodName): DecoratedRpcSection<ApiType> => {
const method = rpc[sectionName][methodName];
section[methodName] = decorateMethod(method, { methodName });
return section;
}, {} as DecoratedRpc$Section<ApiType>);
}, {} as unknown as DecoratedRpcSection<ApiType>);
return result;
}, {} as DecoratedRpc<ApiType>);
}, {} as unknown as DecoratedRpc<ApiType>);
}
private decorateMulti<ApiType> (decorateMethod: ApiBase<ApiType>['decorateMethod']): QueryableStorageMulti<ApiType> {
return decorateMethod(
(calls: QueryableStorageMultiArgs<ApiType>) => {
const mapped = calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Array<CodecArg>] =>
(calls: QueryableStorageMultiArgs<ApiType>): Observable<Codec[]> => {
const mapped = calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...CodecArg[]] =>
// the input is a QueryableStorageEntry, convert to StorageEntry
Array.isArray(arg)
? [arg[0].creator, ...arg.slice(1)]
@@ -569,49 +584,48 @@ export default abstract class ApiBase<ApiType> {
private decorateExtrinsics<ApiType> (extrinsics: ModulesWithMethods, decorateMethod: ApiBase<ApiType>['decorateMethod']): SubmittableExtrinsics<ApiType> {
const creator = (value: Uint8Array | string): SubmittableExtrinsic<ApiType> =>
createSubmittable(this.type, this._rx as ApiInterface$Rx, decorateMethod, value);
createSubmittable(this.type, this._rx as ApiInterfaceRx, decorateMethod, value);
return Object.keys(extrinsics).reduce((result, sectionName) => {
return Object.keys(extrinsics).reduce((result, sectionName): SubmittableExtrinsics<ApiType> => {
const section = extrinsics[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[sectionName] = Object.keys(section).reduce((result, methodName): SubmittableModuleExtrinsics<ApiType> => {
result[methodName] = this.decorateExtrinsicEntry(section[methodName], decorateMethod);
return result;
}, {} as SubmittableModuleExtrinsics<ApiType>);
}, {} as unknown as SubmittableModuleExtrinsics<ApiType>);
return result;
}, creator as SubmittableExtrinsics<ApiType>);
}, creator as unknown as SubmittableExtrinsics<ApiType>);
}
private decorateExtrinsicEntry<ApiType> (method: MethodFunction, decorateMethod: ApiBase<ApiType>['decorateMethod']): SubmittableExtrinsicFunction<ApiType> {
const decorated =
(...params: Array<CodecArg>): SubmittableExtrinsic<ApiType> =>
createSubmittable(this.type, this._rx as ApiInterface$Rx, decorateMethod, method(...params));
(...params: CodecArg[]): SubmittableExtrinsic<ApiType> =>
createSubmittable(this.type, this._rx as ApiInterfaceRx, decorateMethod, method(...params));
return this.decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
}
private decorateStorage<ApiType> (storage: Storage, decorateMethod: ApiBase<ApiType>['decorateMethod']): QueryableStorage<ApiType> {
return Object.keys(storage).reduce((result, sectionName) => {
return Object.keys(storage).reduce((result, sectionName): QueryableStorage<ApiType> => {
const section = storage[sectionName];
result[sectionName] = Object.keys(section).reduce((result, methodName) => {
result[sectionName] = Object.keys(section).reduce((result, methodName): QueryableModuleStorage<ApiType> => {
result[methodName] = this.decorateStorageEntry(section[methodName], decorateMethod);
return result;
}, {} as QueryableModuleStorage<ApiType>);
}, {} as unknown as QueryableModuleStorage<ApiType>);
return result;
}, {} as QueryableStorage<ApiType>);
}, {} as unknown as QueryableStorage<ApiType>);
}
private decorateStorageEntry<ApiType> (creator: StorageEntry, decorateMethod: ApiBase<ApiType>['decorateMethod']): QueryableStorageEntry<ApiType> {
const decorated = creator.headKey
? this.decorateStorageEntryLinked(creator, decorateMethod)
: decorateMethod(
(...args: Array<any>) => {
(...args: any[]): Observable<Codec> => {
return this._rpcCore.state
// Unfortunately for one-shot calls we also use .subscribeStorage here
.subscribeStorage([
@@ -621,7 +635,7 @@ export default abstract class ApiBase<ApiType> {
.pipe(
// state_storage returns an array of values, since we have just subscribed to
// a single entry, we pull that from the array and return it as-is
map((result: Array<Codec>): Codec =>
map((result: Codec[]): Codec =>
result[0]
)
);
@@ -632,18 +646,22 @@ export default abstract class ApiBase<ApiType> {
decorated.creator = creator;
decorated.at = decorateMethod(
(hash: Hash, arg1?: CodecArg, arg2?: CodecArg) => this._rpcCore.state.getStorage(
creator.meta.type.isDoubleMap
? [creator, [arg1, arg2]]
: [creator, arg1],
hash)
(hash: Hash, arg1?: CodecArg, arg2?: CodecArg): Observable<Codec> =>
this._rpcCore.state.getStorage(
creator.meta.type.isDoubleMap
? [creator, [arg1, arg2]]
: [creator, arg1],
hash
)
);
decorated.hash = decorateMethod(
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcCore.state.getStorageHash(
creator.meta.type.isDoubleMap
? [creator, [arg1, arg2]]
: [creator, arg1])
(arg1?: CodecArg, arg2?: CodecArg): Observable<Hash> =>
this._rpcCore.state.getStorageHash(
creator.meta.type.isDoubleMap
? [creator, [arg1, arg2]]
: [creator, arg1]
)
);
decorated.key = (arg1?: CodecArg, arg2?: CodecArg): string =>
@@ -651,16 +669,21 @@ export default abstract class ApiBase<ApiType> {
// When using double map storage function, user need to path double map key as an array
decorated.multi = decorateMethod(
(args: Array<CodecArg[] | CodecArg>) =>
(args: (CodecArg | CodecArg[])[]): Observable<Codec[]> =>
this._rpcCore.state
.subscribeStorage(args.map((arg: CodecArg[] | CodecArg) => [creator, arg]))
.subscribeStorage(
args.map((arg: CodecArg[] | CodecArg): [StorageEntry, CodecArg | CodecArg[]] =>
[creator, arg]
)
)
);
decorated.size = decorateMethod(
(arg1?: CodecArg, arg2?: CodecArg) => this._rpcCore.state.getStorageSize(
creator.meta.type.isDoubleMap
? [creator, [arg1, arg2]]
: [creator, arg1])
(arg1?: CodecArg, arg2?: CodecArg): Observable<U64> =>
this._rpcCore.state.getStorageSize(
creator.meta.type.isDoubleMap
? [creator, [arg1, arg2]]
: [creator, arg1])
);
return this.decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
@@ -677,7 +700,7 @@ export default abstract class ApiBase<ApiType> {
const getNext = (key: Codec): Observable<LinkageResult> => {
return this._rpcCore.state.subscribeStorage([[method, key]])
.pipe(
switchMap(([data]: [[Codec, Linkage<Codec>]]) => {
switchMap(([data]: [[Codec, Linkage<Codec>]]): Observable<LinkageResult> => {
const linkage = data[1];
result.set(key, data);
@@ -736,19 +759,22 @@ export default abstract class ApiBase<ApiType> {
// this handles the case where the head changes effectively, i.e. a new entry
// appears at the top of the list, the new getNext gets kicked off
return decorateMethod(
() => this._rpcCore.state
.subscribeStorage([method.headKey])
.pipe(
switchMap(([key]: Array<Codec>) => {
head = key;
(): Observable<LinkageResult> =>
this._rpcCore.state
.subscribeStorage([method.headKey])
.pipe(
switchMap(([key]: Codec[]): Observable<LinkageResult> => {
head = key;
return getNext(key);
})
)
return getNext(key);
})
)
);
}
private decorateDerive (apiRx: ApiInterface$Rx, decorateMethod: ApiBase<ApiType>['decorateMethod']) {
// FIXME I have no idea how to get this done
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
private decorateDerive (apiRx: ApiInterfaceRx, decorateMethod: ApiBase<ApiType>['decorateMethod']) {
// Pull in derive from api-derive
const derive = decorateDerive(apiRx, this._options.derives);
+25 -23
View File
@@ -4,7 +4,7 @@
import { AccountId, Address, ExtrinsicStatus, EventRecord, getTypeRegistry, Hash, Header, Index, Method, SignedBlock, Vector, ExtrinsicEra } from '@polkadot/types';
import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsic, IExtrinsicEra, IKeyringPair, SignatureOptions } from '@polkadot/types/types';
import { ApiInterface$Rx, ApiTypes } from './types';
import { ApiInterfaceRx, ApiTypes } from './types';
import BN from 'bn.js';
import { Observable, combineLatest, of } from 'rxjs';
@@ -14,8 +14,9 @@ import { isBn, isFunction, isNumber, isUndefined } from '@polkadot/util';
import ApiBase from './Base';
import filterEvents from './util/filterEvents';
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface ISubmittableResult {
readonly events: Array<EventRecord>;
readonly events: EventRecord[];
readonly status: ExtrinsicStatus;
readonly isCompleted: boolean;
readonly isError: boolean;
@@ -34,10 +35,10 @@ export type SumbitableResultSubscription<ApiType> =
? Observable<ISubmittableResult>
: Promise<() => void>;
type SubmittableResultValue = {
events?: Array<EventRecord>;
interface SubmittableResultValue {
events?: EventRecord[];
status: ExtrinsicStatus;
};
}
interface SignerOptions {
blockHash: AnyU8a;
@@ -50,31 +51,32 @@ const ONE_MINUTE = 15;
const DEFAULT_MORTAL_LENGTH = 5 * ONE_MINUTE;
export class SubmittableResult implements ISubmittableResult {
readonly events: Array<EventRecord>;
readonly status: ExtrinsicStatus;
public readonly events: EventRecord[];
constructor ({ events, status }: SubmittableResultValue) {
public readonly status: ExtrinsicStatus;
public constructor ({ events, status }: SubmittableResultValue) {
this.events = events || [];
this.status = status;
}
get isCompleted (): boolean {
public get isCompleted (): boolean {
return this.isError || this.isFinalized;
}
get isError (): boolean {
public get isError (): boolean {
return this.status.isDropped || this.status.isInvalid || this.status.isUsurped;
}
get isFinalized (): boolean {
public get isFinalized (): boolean {
return this.status.isFinalized;
}
/**
* @description Finds an EventRecord for the specified method & section
*/
findRecord (section: string, method: string): EventRecord | undefined {
return this.events.find(({ event }) =>
public findRecord (section: string, method: string): EventRecord | undefined {
return this.events.find(({ event }): boolean =>
event.section === section && event.method === method
);
}
@@ -96,7 +98,7 @@ export interface SubmittableExtrinsic<ApiType> extends IExtrinsic {
export default function createSubmittableExtrinsic<ApiType> (
type: ApiTypes,
api: ApiInterface$Rx,
api: ApiInterfaceRx,
decorateMethod: ApiBase<ApiType>['decorateMethod'],
extrinsic: Method | Uint8Array | string,
trackingCb?: Callback<ISubmittableResult>
@@ -125,7 +127,7 @@ export default function createSubmittableExtrinsic<ApiType> (
api.rpc.chain.getBlock(blockHash) as Observable<SignedBlock>,
api.query.system.events.at(blockHash) as Observable<Vector<EventRecord>>
]).pipe(
map(([signedBlock, allEvents]) => {
map(([signedBlock, allEvents]): SubmittableResult => {
const result = new SubmittableResult({
events: filterEvents(_extrinsic.hash, signedBlock, allEvents),
status
@@ -142,7 +144,7 @@ export default function createSubmittableExtrinsic<ApiType> (
return (api.rpc.author
.submitExtrinsic(_extrinsic) as Observable<Hash>)
.pipe(
tap((hash) => {
tap((hash): void => {
updateSigner(updateId, hash);
})
);
@@ -152,21 +154,21 @@ export default function createSubmittableExtrinsic<ApiType> (
return (api.rpc.author
.submitAndWatchExtrinsic(_extrinsic) as Observable<ExtrinsicStatus>)
.pipe(
switchMap((status) =>
switchMap((status): Observable<ISubmittableResult> =>
statusObservable(status)
),
tap((status) => {
tap((status): void => {
updateSigner(updateId, status);
})
);
}
function expandOptions (options: Partial<SignerOptions>): SignatureOptions {
return options = {
return {
blockHash: api.genesisHash,
version: api.runtimeVersion,
...options
} as SignatureOptions;
} as unknown as SignatureOptions;
}
function setupEraOptions (header: Header | null, options: Partial<SignerOptions>): Partial<SignatureOptions> {
@@ -233,7 +235,7 @@ export default function createSubmittableExtrinsic<ApiType> (
let updateId: number | undefined;
return decorateMethod(
() => ((
(): Observable<Codec> => ((
combineLatest([
// if we have a nonce already, don't retrieve the latest, use what is there
isUndefined(options.nonce)
@@ -247,7 +249,7 @@ export default function createSubmittableExtrinsic<ApiType> (
])
).pipe(
first(),
mergeMap(async ([nonce, header]) => {
mergeMap(async ([nonce, header]): Promise<void> => {
const eraOptions = setupEraOptions(header, options);
if (isKeyringPair) {
@@ -262,7 +264,7 @@ export default function createSubmittableExtrinsic<ApiType> (
throw new Error('no signer exists');
}
}),
switchMap(() => {
switchMap((): Observable<ISubmittableResult> | Observable<Hash> => {
return isSubscription
? subscribeObservable(updateId)
: sendObservable(updateId) as any; // ???
+9 -9
View File
@@ -12,7 +12,7 @@ import { Header, Nonce } from '@polkadot/types';
import { SubmittableResult } from './';
export default async function test () {
export default async function test (): Promise<void> {
const api = await ApiPromise.create();
const keyring = testKeyring();
@@ -23,29 +23,29 @@ export default async function test () {
const multiUnsub = await api.queryMulti([
[api.query.system.accountNonce, keyring.eve.address],
[api.query.system.accountNonce, keyring.bob.address]
], (balances) => {
], (balances): void => {
console.log('balances', balances);
multiUnsub();
});
await api.query.staking.intentions((intentions) => {
await api.query.staking.intentions((intentions): void => {
console.log('intentions:', intentions);
});
await api.rpc.chain.subscribeNewHead<Header>((header) => {
await api.rpc.chain.subscribeNewHead<Header>((header): void => {
console.log('current blockNumber:', header.blockNumber);
});
await api.rpc.chain.subscribeNewHead((header: Header) => {
await api.rpc.chain.subscribeNewHead((header: Header): void => {
console.log('current blockNumber:', header.blockNumber);
});
await api.derive.chain.subscribeNewHead((header: HeaderExtended) => {
await api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
console.log('current author:', header.author);
});
await api.derive.chain.subscribeNewHead((header: HeaderExtended) => {
await api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
console.log('current author:', header.author);
});
@@ -68,7 +68,7 @@ export default async function test () {
// just with the callback
const unsub = await api.tx.balances
.transfer(keyring.bob.address, 12345)
.signAndSend(keyring.alice, ({ status }: SubmittableResult) => {
.signAndSend(keyring.alice, ({ status }: SubmittableResult): void => {
console.log('transfer status:', status.type);
unsub();
@@ -78,7 +78,7 @@ export default async function test () {
const nonce2 = await api.query.system.accountNonce<Nonce>(keyring.alice.address);
const unsub2 = await api.tx.balances
.transfer(keyring.bob.address, 12345)
.signAndSend(keyring.alice, { nonce: nonce2 }, ({ status }: SubmittableResult) => {
.signAndSend(keyring.alice, { nonce: nonce2 }, ({ status }: SubmittableResult): void => {
console.log('transfer status:', status.type);
unsub2();
+2 -1
View File
@@ -2,11 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export { WsProvider } from '@polkadot/rpc-provider';
import { assertSingletonPackage } from '@polkadot/util';
assertSingletonPackage('@polkadot/api');
export { WsProvider } from '@polkadot/rpc-provider';
export { default as ApiPromise } from './promise';
export { default as ApiRx } from './rx';
export { default as SubmittableExtrinsic, SubmittableResult } from './SubmittableExtrinsic';
+12 -11
View File
@@ -1,24 +1,25 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Constructor } from '@polkadot/types/types';
import { EventRecord_0_76, RuntimeVersion, getTypeRegistry } from '@polkadot/types';
import { EventRecord0to76, RuntimeVersion, getTypeRegistry } from '@polkadot/types';
type Compat = {
interface Compat {
// an array of the spec-name and spec_version that denotes the first version that
// does not support this feature. i.e. for EventRecord between 0-76, the new version
// went live at 77 - hence the version here denotes 77
nodeSpecs: Array<[string, number]>,
nodeSpecs: [string, number][];
types: {
[index: string]: Constructor
}
};
[index: string]: Constructor;
};
}
const ANY_VERSION = 0xffffff;
const types: Array<Compat> = [
const types: Compat[] = [
{
nodeSpecs: [
['node', 77],
@@ -26,20 +27,20 @@ const types: Array<Compat> = [
['node-template', ANY_VERSION]
],
types: {
'EventRecord': EventRecord_0_76
EventRecord: EventRecord0to76
}
}
];
export default function injectNodeCompat ({ specName, specVersion }: RuntimeVersion): void {
types
.filter(({ nodeSpecs }) =>
nodeSpecs.some(([name, version]) =>
.filter(({ nodeSpecs }): boolean =>
nodeSpecs.some(([name, version]): boolean =>
specName.eq(name) &&
specVersion.ltn(version)
)
)
.forEach(({ types }) => {
.forEach(({ types }): void => {
getTypeRegistry().register(types);
});
}
+7 -8
View File
@@ -8,22 +8,22 @@ import Mock from '@polkadot/rpc-provider/mock/index';
import { ApiPromise } from './..';
import { ApiOptions } from './../types';
describe.skip('Metadata queries', () => {
describe.skip('Metadata queries', (): void => {
let mock: Mock;
beforeEach(() => {
beforeEach((): void => {
jest.setTimeout(3000000);
mock = new Mock();
});
it('Create API instance with metadata map and makes the runtime, rpc, state & extrinsics available', async () => {
const rpcData = await mock.send('state_getMetadata',[]);
const genesisHash = new Hash(await mock.send('chain_getBlockHash',[])).toHex();
it('Create API instance with metadata map and makes the runtime, rpc, state & extrinsics available', async (): Promise<void> => {
const rpcData = await mock.send('state_getMetadata', []);
const genesisHash = new Hash(await mock.send('chain_getBlockHash', [])).toHex();
const specVersion = 0;
const metadata: any = {};
const key = `${genesisHash}-${specVersion}`;
metadata[key] = rpcData;
const api = await ApiPromise.create({ provider: mock, metadata } as ApiOptions);
const api = await ApiPromise.create({ provider: mock, metadata } as unknown as ApiOptions);
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata.toJSON()).toEqual(new Metadata(rpcData).toJSON());
@@ -34,7 +34,7 @@ describe.skip('Metadata queries', () => {
expect(api.derive).toBeDefined();
});
it('Create API instance without metadata and makes the runtime, rpc, state & extrinsics available', async () => {
it('Create API instance without metadata and makes the runtime, rpc, state & extrinsics available', async (): Promise<void> => {
const metadata = {};
const api = await ApiPromise.create({
provider: mock, metadata
@@ -48,5 +48,4 @@ describe.skip('Metadata queries', () => {
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
});
+17 -17
View File
@@ -6,7 +6,7 @@ import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { AnyFunction, Callback, Codec } from '@polkadot/types/types';
import { ApiOptions, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise } from '../types';
import { EMPTY } from 'rxjs';
import { Observable, EMPTY } from 'rxjs';
import { catchError, first, tap } from 'rxjs/operators';
import { isFunction, assert } from '@polkadot/util';
@@ -120,7 +120,7 @@ export default class ApiPromise extends ApiBase<'promise'> {
* });
* ```
*/
static create (options: ApiOptions | ProviderInterface = {}): Promise<ApiPromise> {
public static create (options: ApiOptions | ProviderInterface = {}): Promise<ApiPromise> {
return new ApiPromise(options).isReady;
}
@@ -143,27 +143,27 @@ export default class ApiPromise extends ApiBase<'promise'> {
* });
* ```
*/
constructor (options?: ApiOptions | ProviderInterface) {
public constructor (options?: ApiOptions | ProviderInterface) {
super(options, 'promise');
this._isReadyPromise = new Promise((resolveReady) =>
super.once('ready', () =>
resolveReady(this)
)
);
this._isReadyPromise = new Promise((resolve): void => {
super.once('ready', (): void => {
resolve(this);
});
});
}
/**
* @description Promise that returns the first time we are connected and loaded
*/
get isReady (): Promise<ApiPromise> {
public get isReady (): Promise<ApiPromise> {
return this._isReadyPromise;
}
/**
* @description Returns a clone of this ApiPromise instance (new underlying provider connection)
*/
clone (): ApiPromise {
public clone (): ApiPromise {
return new ApiPromise({
...this._options,
source: this
@@ -190,7 +190,7 @@ export default class ApiPromise extends ApiBase<'promise'> {
* });
* ```
*/
async combineLatest (fns: Array<CombinatorFunction | [CombinatorFunction, ...Array<any>]>, callback: CombinatorCallback): UnsubscribePromise {
public async combineLatest (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback): UnsubscribePromise {
const combinator = new Combinator(fns, callback);
return (): void => {
@@ -201,9 +201,9 @@ export default class ApiPromise extends ApiBase<'promise'> {
protected decorateMethod<Method extends AnyFunction> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
return function (...args: any[]) {
return function (...args: any[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
let callback: Callback<Codec> | undefined;
let actualArgs = args.slice();
const actualArgs = args.slice();
// If the last arg is a function, we pop it, put it into callback.
// actualArgs will then hold the actual arguments to be passed to `method`
@@ -221,12 +221,12 @@ export default class ApiPromise extends ApiBase<'promise'> {
// FIXME TSLint shouts that type assertion is unnecessary, but tsc shouts
// when I remove it...
// tslint:disable-next-line
return new Promise((resolve, reject) => {
return new Promise((resolve, reject): void => {
let isCompleted = false;
const subscription = method(...actualArgs)
.pipe(
// if we find an error (invalid params, etc), reject the promise
catchError((error) => {
catchError((error): Observable<never> => {
if (!isCompleted) {
isCompleted = true;
@@ -237,11 +237,11 @@ export default class ApiPromise extends ApiBase<'promise'> {
return EMPTY;
}),
// upon the first result, resolve the with the unsub function
tap(() => {
tap((): void => {
if (!isCompleted) {
isCompleted = true;
resolve(() => subscription.unsubscribe());
resolve((): void => subscription.unsubscribe());
}
})
)
+22 -16
View File
@@ -7,23 +7,29 @@ import { UnsubscribePromise } from '../types';
import { isFunction } from '@polkadot/util';
export type CombinatorCallback = Callback<Array<any>>;
export type CombinatorFunction = {
(cb: Callback<any>): UnsubscribePromise
};
export type CombinatorCallback = Callback<any[]>;
export interface CombinatorFunction {
(cb: Callback<any>): UnsubscribePromise;
}
export default class Combinator {
protected _allHasFired: boolean = false;
protected _callback: CombinatorCallback;
protected _fired: Array<boolean> = [];
protected _fns: Array<CombinatorFunction> = [];
protected _isActive: boolean = true;
protected _results: Array<any> = [];
protected _subscriptions: Array<UnsubscribePromise> = [];
constructor (fns: Array<CombinatorFunction | [CombinatorFunction, ...Array<any>]>, callback: CombinatorCallback) {
protected _callback: CombinatorCallback;
protected _fired: boolean[] = [];
protected _fns: CombinatorFunction[] = [];
protected _isActive: boolean = true;
protected _results: any[] = [];
protected _subscriptions: UnsubscribePromise[] = [];
public constructor (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback) {
this._callback = callback;
this._subscriptions = fns.map(async (input, index) => {
this._subscriptions = fns.map(async (input, index): UnsubscribePromise => {
const [fn, ...args] = Array.isArray(input)
? input
: [input];
@@ -38,13 +44,13 @@ export default class Combinator {
protected allHasFired (): boolean {
if (!this._allHasFired) {
this._allHasFired = this._fired.filter((hasFired) => !hasFired).length === 0;
this._allHasFired = this._fired.filter((hasFired): boolean => !hasFired).length === 0;
}
return this._allHasFired;
}
protected createCallback (index: number) {
protected createCallback (index: number): (value: any) => void {
return (value: any): void => {
this._fired[index] = true;
this._results[index] = value;
@@ -65,14 +71,14 @@ export default class Combinator {
}
}
unsubscribe (): void {
public unsubscribe (): void {
if (!this._isActive) {
return;
}
this._isActive = false;
this._subscriptions.forEach(async (subscription) => {
this._subscriptions.forEach(async (subscription): Promise<void> => {
try {
const unsubscribe = await subscription;
+15 -14
View File
@@ -5,23 +5,23 @@
import { UnsubscribePromise } from '../types';
import Combinator from './Combinator';
describe('Combinator', () => {
let fns: Array<(value: any) => void> = [];
describe('Combinator', (): void => {
let fns: ((value: any) => void)[] = [];
const storeFn = async (cb: (value: any) => void): UnsubscribePromise => {
fns.push(cb);
return () => undefined;
return (): void => undefined;
};
beforeEach(() => {
beforeEach((): void => {
fns = [];
});
it('it triggers on all values', (done) => {
it('it triggers on all values', (done): void => {
let count = 0;
const combinator = new Combinator(
[storeFn],
(value: Array<any>) => {
(value: any[]): void => {
expect(value[0]).toEqual(`test${count}`);
count++;
@@ -39,10 +39,10 @@ describe('Combinator', () => {
expect(combinator).toBeDefined();
});
it('combines values from 2 sources, firing when it has all results', (done) => {
it('combines values from 2 sources, firing when it has all results', (done): void => {
const combinator = new Combinator(
[storeFn, storeFn],
(value: Array<any>) => {
(value: any[]): void => {
expect(value).toEqual(['test0', 'test1']);
done();
@@ -55,11 +55,11 @@ describe('Combinator', () => {
expect(combinator).toBeDefined();
});
it('combines values from 2 sources, allowing multiple updates', (done) => {
it('combines values from 2 sources, allowing multiple updates', (done): void => {
let count = 0;
const combinator = new Combinator(
[storeFn, storeFn],
(value: Array<any>) => {
(value: any[]): void => {
expect(value).toEqual(
count === 0
? ['test0', 'test1']
@@ -80,12 +80,13 @@ describe('Combinator', () => {
expect(combinator).toBeDefined();
});
it('unsubscribes as required', (done) => {
const mocker = async () => done;
it('unsubscribes as required', (done): void => {
const mocker = async (): Promise<any> => done;
const combinator = new Combinator([
mocker,
async () => () => void 0
], (value: Array<any>) => {
async (): UnsubscribePromise => (): void => void 0
// eslint-disable-next-line @typescript-eslint/no-unused-vars
], (value: any[]): void => {
// ignore
});
+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 ApiPromise } from './Api';
import ApiPromise from './Api';
export default ApiPromise;
+2 -2
View File
@@ -6,8 +6,8 @@ import { isObservable } from '@polkadot/util';
import ApiRx from './Api';
describe('ApiRx', () => {
it('has isConnected', () => {
describe('ApiRx', (): void => {
it('has isConnected', (): void => {
const api = new ApiRx();
expect(
+10 -10
View File
@@ -135,7 +135,7 @@ export default class ApiRx extends ApiBase<'rxjs'> {
* });
* ```
*/
static create (options?: ApiOptions | ProviderInterface): Observable<ApiRx> {
public static create (options?: ApiOptions | ProviderInterface): Observable<ApiRx> {
return new ApiRx(options).isReady;
}
@@ -161,37 +161,37 @@ export default class ApiRx extends ApiBase<'rxjs'> {
* });
* ```
*/
constructor (provider?: ApiOptions | ProviderInterface) {
public constructor (provider?: ApiOptions | ProviderInterface) {
super(provider, 'rxjs');
this._isReadyRx = from(
// convinced you can observable from an event, however my mind groks this form better
new Promise((resolveReady) =>
super.on('ready', () =>
resolveReady(this)
)
)
new Promise((resolve): void => {
super.on('ready', (): void => {
resolve(this);
});
})
) as Observable<ApiRx>;
}
/**
* @description Observable that carries the connected state for the provider. Results in a boolean flag that is true/false based on the connectivity.
*/
get isConnected (): Observable<boolean> {
public get isConnected (): Observable<boolean> {
return this._isConnected;
}
/**
* @description Observable that returns the first time we are connected and loaded
*/
get isReady (): Observable<ApiRx> {
public get isReady (): Observable<ApiRx> {
return this._isReadyRx;
}
/**
* @description Returns a clone of this ApiRx instance (new underlying provider connection)
*/
clone (): ApiRx {
public clone (): ApiRx {
return new ApiRx({
...this._options,
source: this
+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 ApiRx } from './Api';
import ApiRx from './Api';
export default ApiRx;
+38 -32
View File
@@ -6,7 +6,7 @@ import BN from 'bn.js';
import { Observable } from 'rxjs';
import { DeriveCustom } from '@polkadot/api-derive';
import { Constants } from '@polkadot/api-metadata/consts/fromMetadata/types';
import { ProviderInterface, ProviderInterface$Emitted } from '@polkadot/rpc-provider/types';
import { ProviderInterface, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
import { Hash, RuntimeVersion, u64 as U64 } from '@polkadot/types';
import { AnyFunction, Callback, Codec, CodecArg, IExtrinsic, RegistryTypes, SignatureOptions } from '@polkadot/types/types';
import { MethodFunction } from '@polkadot/types/primitive/Method';
@@ -20,15 +20,20 @@ import { ISubmittableResult, SubmittableExtrinsic } from './SubmittableExtrinsic
type Cons<V, T extends any[]> = ((v: V, ...t: T) => void) extends ((...r: infer R) => void)
? R
: never;
// Append an element V onto the end of a tuple T
// Push<[1,2,3],4> is [1,2,3,4]
// note that this DOES NOT PRESERVE optionality/readonly in tuples.
// So unfortunately Push<[1, 2?, 3?], 4> is [1,2|undefined,3|undefined,4]
type Push<T extends any[], V> = (Cons<any, Required<T>> extends infer R
? { [K in keyof R]: K extends keyof T ? T[K] : V }
: never) extends infer P
type Push<T extends any[], V> = (
(
Cons<any, Required<T>> extends infer R
? { [K in keyof R]: K extends keyof T ? T[K] : V }
: never
) extends infer P
? P extends any[] ? P : never
: never;
: never
);
// Returns the inner type of an Observable
export type ObsInnerType<O extends Observable<any>> = O extends Observable<infer U> ? U : never;
@@ -37,9 +42,9 @@ export type UnsubscribePromise = Promise<() => void>;
// In the abstract `decorateMethod` in Base.ts, we can also pass in some meta-
// information. This describes it.
export type DecorateMethodOptions = {
methodName?: string
};
export interface DecorateMethodOptions {
methodName?: string;
}
// Here are the return types of these parts of the api:
// - api.query.*.*: no exact typings
@@ -50,19 +55,22 @@ export type DecorateMethodOptions = {
// These are the types that don't lose type information (used for api.derive.*)
// Also use these for api.rpc.* https://github.com/polkadot-js/api/issues/1009
export type RxResult<F extends AnyFunction> = (...args: Parameters<F>) => Observable<ObsInnerType<ReturnType<F>>>;
// eslint-disable-next-line @typescript-eslint/prefer-interface
export type PromiseResult<F extends AnyFunction> = {
(...args: Parameters<F>): Promise<ObsInnerType<ReturnType<F>>>,
(...args: Push<Parameters<F>, Callback<ObsInnerType<ReturnType<F>>>>): UnsubscribePromise
(...args: Parameters<F>): Promise<ObsInnerType<ReturnType<F>>>;
(...args: Push<Parameters<F>, Callback<ObsInnerType<ReturnType<F>>>>): UnsubscribePromise;
};
// FIXME The day TS has higher-kinded types, we can remove this hardcoded stuff
export type MethodResult<ApiType, F extends AnyFunction> = ApiType extends 'rxjs'
? RxResult<F>
: PromiseResult<F>;
type DecoratedRpc$Method<ApiType> = ApiType extends 'rxjs'
type DecoratedRpcMethod<ApiType> = ApiType extends 'rxjs'
? {
(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Observable<Codec>
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Observable<T>
(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Observable<Codec>;
<T extends Codec>(arg1?: CodecArg, arg2?: CodecArg, arg3?: CodecArg): Observable<T>;
}
: {
// These signatures are allowed and exposed here (bit or a stoopid way, but checked
@@ -77,16 +85,16 @@ type DecoratedRpc$Method<ApiType> = ApiType extends 'rxjs'
};
// FIXME https://github.com/polkadot-js/api/issues/1009
export interface DecoratedRpc$Section<ApiType> {
[index: string]: DecoratedRpc$Method<ApiType>;
export interface DecoratedRpcSection<ApiType> {
[index: string]: DecoratedRpcMethod<ApiType>;
}
// FIXME https://github.com/polkadot-js/api/issues/1009
export interface DecoratedRpc<ApiType> {
author: DecoratedRpc$Section<ApiType>;
chain: DecoratedRpc$Section<ApiType>;
state: DecoratedRpc$Section<ApiType>;
system: DecoratedRpc$Section<ApiType>;
author: DecoratedRpcSection<ApiType>;
chain: DecoratedRpcSection<ApiType>;
state: DecoratedRpcSection<ApiType>;
system: DecoratedRpcSection<ApiType>;
}
export interface StorageEntryObservable {
@@ -96,7 +104,7 @@ export interface StorageEntryObservable {
creator: StorageEntry;
hash: (arg1?: CodecArg, arg2?: CodecArg) => Observable<Hash>;
key: (arg1?: CodecArg, arg2?: CodecArg) => string;
multi: <T extends Codec>(args: Array<CodecArg[] | CodecArg>) => Observable<Array<T>>;
multi: <T extends Codec>(args: (CodecArg[] | CodecArg)[]) => Observable<T[]>;
size: (arg1?: CodecArg, arg2?: CodecArg) => Observable<U64>;
}
@@ -109,8 +117,8 @@ export interface StorageEntryPromiseOverloads {
}
export interface StorageEntryPromiseMulti {
<T extends Codec>(args: Array<CodecArg[] | CodecArg>): Promise<Array<T>>;
<T extends Codec>(args: Array<CodecArg[] | CodecArg>, callback: Callback<Array<T>>): UnsubscribePromise;
<T extends Codec>(args: (CodecArg[] | CodecArg)[]): Promise<T[]>;
<T extends Codec>(args: (CodecArg[] | CodecArg)[], callback: Callback<T[]>): UnsubscribePromise;
}
export interface StorageEntryPromise extends StorageEntryPromiseOverloads {
@@ -133,16 +141,16 @@ export interface QueryableModuleStorage<ApiType> {
export type QueryableStorageMultiArg<ApiType> =
QueryableStorageEntry<ApiType> |
[QueryableStorageEntry<ApiType>, ...Array<CodecArg>];
[QueryableStorageEntry<ApiType>, ...CodecArg[]];
export type QueryableStorageMultiArgs<ApiType> = Array<QueryableStorageMultiArg<ApiType>>;
export type QueryableStorageMultiArgs<ApiType> = QueryableStorageMultiArg<ApiType>[];
export interface QueryableStorageMultiBase<ApiType> {
<T extends Codec>(calls: QueryableStorageMultiArgs<ApiType>): Observable<Array<T>>;
<T extends Codec>(calls: QueryableStorageMultiArgs<ApiType>): Observable<T[]>;
}
export interface QueryableStorageMultiPromise<ApiType> {
<T extends Codec>(calls: QueryableStorageMultiArgs<ApiType>, callback: Callback<Array<T>>): UnsubscribePromise;
<T extends Codec>(calls: QueryableStorageMultiArgs<ApiType>, callback: Callback<T[]>): UnsubscribePromise;
}
export type QueryableStorageMulti<ApiType> =
@@ -155,7 +163,7 @@ export interface QueryableStorage<ApiType> {
}
export interface SubmittableExtrinsicFunction<ApiType> extends MethodFunction {
(...params: Array<CodecArg>): SubmittableExtrinsic<ApiType>;
(...params: CodecArg[]): SubmittableExtrinsic<ApiType>;
}
export interface SubmittableModuleExtrinsics<ApiType> {
@@ -176,9 +184,7 @@ export interface ApiOptions {
* @description prebundles is a map of 'genesis hash and runtime spec version' as key to metadata's hex string
* if genesis hash and runtime spec version matches, then use metadata, else fetch it from chain
*/
metadata?: {
[key: string]: string
};
metadata?: Record<string, string>;
/**
* @description Transport Provider from rpc-provider. If not specified, it will default to
* connecting to a WsProvider connecting localhost with the default port, i.e. `ws://127.0.0.1:9944`
@@ -200,7 +206,7 @@ export interface ApiOptions {
}
// A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic
export interface ApiInterface$Rx {
export interface ApiInterfaceRx {
consts: Constants;
genesisHash: Hash;
hasSubscriptions: boolean;
@@ -213,7 +219,7 @@ export interface ApiInterface$Rx {
signer?: Signer;
}
export type ApiInterface$Events = ProviderInterface$Emitted | 'ready';
export type ApiInterfaceEvents = ProviderInterfaceEmitted | 'ready';
export type ApiTypes = 'promise' | 'rxjs';
+11 -9
View File
@@ -7,47 +7,49 @@ import { MethodResult } from '../types';
// A technically unsafe version of Object.keys(obj) that assumes that
// obj only has known properties of T
function keys<T extends object> (obj: T) {
return Object.keys(obj) as Array<keyof T>;
function keys<T extends object> (obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[];
}
function decorateMethods<ApiType, Section extends Record<keyof Section, (...args: Array<any>) => any>> (
// FIXME the return value typings here is horrible and not DRY
function decorateMethods<ApiType, Section extends Record<keyof Section, (...args: any[]) => any>> (
section: Section,
decorateMethod: <Method extends AnyFunction>(method: Method) => MethodResult<ApiType, Method>
) {
): { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> } {
return keys(section).reduce(
<MethodName extends keyof Section>(
acc: { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> },
methodName: MethodName
) => {
): { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> } => {
const method = section[methodName];
acc[methodName] = decorateMethod(method) as any;
return acc;
},
{} as { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> }
{} as unknown as { [MethodName in keyof Section]: MethodResult<ApiType, Section[MethodName]> }
);
}
/**
* This is a section decorator which keeps all type information.
*/
// FIXME the return value typings here is horrible and not DRY
export function decorateSections<ApiType, AllSections extends {
[SectionName in keyof AllSections]: Record<keyof AllSections[SectionName], (...args: any[]) => any>
}> (
allSections: AllSections,
decorateMethod: <Method extends AnyFunction>(method: Method) => MethodResult<ApiType, Method>
) {
): { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } } {
return keys(allSections).reduce(
<MethodName extends keyof AllSections>(
acc: { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } },
sectionName: MethodName
) => {
): { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } } => {
acc[sectionName] = decorateMethods(allSections[sectionName], decorateMethod);
return acc;
},
{} as { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } }
{} as unknown as { [SectionName in keyof AllSections]: { [MethodName in keyof AllSections[SectionName]]: MethodResult<ApiType, AllSections[SectionName][MethodName]> } }
);
}
+3 -3
View File
@@ -6,10 +6,10 @@ import { EventRecord, SignedBlock, U8a } from '@polkadot/types';
import l from './logging';
export default function filterEvents (extHash: U8a, { block: { extrinsics, header } }: SignedBlock, allEvents: Array<EventRecord>): Array<EventRecord> | undefined {
export default function filterEvents (extHash: U8a, { block: { extrinsics, header } }: SignedBlock, allEvents: EventRecord[]): EventRecord[] | undefined {
// extrinsics to hashes
const myHash = extHash.toHex();
const allHashes = extrinsics.map((ext) => ext.hash.toHex());
const allHashes = extrinsics.map((ext): string => ext.hash.toHex());
// find the index of our extrinsic in the block
const index = allHashes.indexOf(myHash);
@@ -20,7 +20,7 @@ export default function filterEvents (extHash: U8a, { block: { extrinsics, heade
return;
}
return allEvents.filter(({ phase }) =>
return allEvents.filter(({ phase }): boolean =>
// only ApplyExtrinsic has the extrinsic index
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eqn(index)
);
@@ -7,21 +7,21 @@ import { Extrinsic, SignedBlock } from '@polkadot/types';
import Api from './../../src/promise';
// To run these tests locally you need to run a Alexander full archive node locally
describe.skip('alex archive queries (local)', () => {
describe.skip('alex archive queries (local)', (): void => {
let api: Api;
beforeEach(() => {
beforeEach((): void => {
jest.setTimeout(30000);
});
beforeEach(async () => {
beforeEach(async (): Promise<Api> => {
api = await Api.create();
return api;
});
// https://github.com/polkadot-js/api/issues/845
it('retrieves block with no issues', async () => {
it('retrieves block with no issues', async (): Promise<boolean> => {
const metadata = await api.rpc.state.getMetadata('0x6f6f9bba0eed8e3ae9446c37eee763f93118b52a315a7b46090453ba6288da1f');
console.error(JSON.stringify(metadata, null, 2));
@@ -36,10 +36,10 @@ describe.skip('alex archive queries (local)', () => {
});
// https://github.com/polkadot-js/api/issues/846
it('handles toJSON with no issues', async (done) => {
it('handles toJSON with no issues', async (done): Promise<() => void> => {
return (
api.rpc.chain.getBlock('0x85c62b581f38cb81c3e443d34392672beb1fb877017fd7237cc87704113259dc', (result: SignedBlock) => {
const failed: Array<Extrinsic> = result.block.extrinsics.filter((extrinsic: Extrinsic) => {
api.rpc.chain.getBlock('0x85c62b581f38cb81c3e443d34392672beb1fb877017fd7237cc87704113259dc', (result: SignedBlock): void => {
const failed: Extrinsic[] = result.block.extrinsics.filter((extrinsic: Extrinsic): boolean => {
try {
const json = extrinsic.method.toJSON();
+17 -17
View File
@@ -10,14 +10,14 @@ import Api from './../../src/promise';
const WS_URL = 'wss://poc3-rpc.polkadot.io/';
// const WS_URL = 'wss://substrate-rpc.parity.io/';
describe.skip('alex queries', () => {
describe.skip('alex queries', (): void => {
let api: Api;
beforeEach(() => {
beforeEach((): void => {
jest.setTimeout(30000);
});
beforeEach(async () => {
beforeEach(async (): Promise<Api> => {
api = await Api.create({
provider: new WsProvider(WS_URL)
});
@@ -25,9 +25,9 @@ describe.skip('alex queries', () => {
return api;
});
it('retrieves the list of validators', (done) => {
it('retrieves the list of validators', (done): Promise<() => void> => {
return (
api.query.staking.validators((res) => {
api.query.staking.validators((res): void => {
console.error(res);
console.log('api.query.staking.validators():', res.toJSON());
@@ -36,10 +36,10 @@ describe.skip('alex queries', () => {
);
});
describe('retrieves a single value', () => {
it('retrieves the list of stash validators', (done) => {
describe('retrieves a single value', (): void => {
it('retrieves the list of stash validators', (done): Promise<() => void> => {
return (
api.query.staking.validators('5DuiZFa184E9iCwbh4WjXYvJ88NHvWJbS8SARY8Ev1YEqrri', (res) => {
api.query.staking.validators('5DuiZFa184E9iCwbh4WjXYvJ88NHvWJbS8SARY8Ev1YEqrri', (res): void => {
console.error(res);
console.log('api.query.staking.validators(id):', res.toJSON());
done();
@@ -47,18 +47,18 @@ describe.skip('alex queries', () => {
);
});
it('Gets the hash of the last finalized header', async (done) => {
it('Gets the hash of the last finalized header', async (done): Promise<() => void> => {
return (
api.rpc.chain.getFinalizedHead((head) => {
api.rpc.chain.getFinalizedHead((head): void => {
expect(head instanceof Hash).toBe(true);
done();
})
);
});
it('Subscribes to the best finalized header on ALEX', async (done) => {
it('Subscribes to the best finalized header on ALEX', async (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeFinalizedHeads((head) => {
api.rpc.chain.subscribeFinalizedHeads((head): void => {
expect(head instanceof Header).toBe(true);
done();
})
@@ -66,9 +66,9 @@ describe.skip('alex queries', () => {
});
});
it('derives a list of the controllers', (done) => {
it('derives a list of the controllers', (done): Promise<() => void> => {
return (
api.derive.staking.controllers((res: [Array<AccountId>, Array<Option<AccountId>>]) => {
api.derive.staking.controllers((res: [AccountId[], Option<AccountId>[]]): void => {
console.log('api.derive.staking.controllers:', JSON.stringify(res));
done();
@@ -76,15 +76,15 @@ describe.skip('alex queries', () => {
);
});
it('makes a query at a latest block (specified)', async () => {
it('makes a query at a latest block (specified)', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const events = await api.query.system.events.at(header.hash) as Vector<EventRecord>;
expect(events.length).not.toEqual(0);
});
it('subscribes to events', (done) => {
return api.query.system.events((events: Vector<EventRecord>) => {
it('subscribes to events', (done): Promise<() => void> => {
return api.query.system.events((events: Vector<EventRecord>): void => {
expect(events).not.toHaveLength(0);
done();
});
+4 -4
View File
@@ -6,20 +6,20 @@ import WsProvider from '@polkadot/rpc-provider/ws';
import { ApiPromise } from '@polkadot/api';
import { BlockNumber } from '@polkadot/types';
describe.skip('e2e consts', () => {
describe.skip('e2e consts', (): void => {
let api: ApiPromise;
beforeEach(() => {
beforeEach((): Promise<ApiPromise> => {
api = new ApiPromise(new WsProvider('ws://127.0.0.1:9944'));
return api.isReady;
});
beforeEach(() => {
beforeEach((): void => {
jest.setTimeout(30000);
});
it('democracy.cooloffPeriod parameter type', () => {
it('democracy.cooloffPeriod parameter type', (): void => {
expect(api.consts.democracy.cooloffPeriod).toBeInstanceOf(BlockNumber);
expect(api.consts.democracy.cooloffPeriod.eq(432000)).toBeTruthy();
});
+11 -11
View File
@@ -17,15 +17,15 @@ import { ApiPromise, SubmittableResult } from '../../src';
const flipperCode = fs.readFileSync(path.join(__dirname, '../../../api-contract/test/contracts/flipper-pruned.wasm')).toString('hex');
describe.skip('Promise e2e contracts', () => {
describe.skip('Promise e2e contracts', (): void => {
let address: Address;
let codeHash: Hash;
let keyring: {
[index: string]: KeyringPair
[index: string]: KeyringPair;
};
let api: ApiPromise;
beforeEach(async (done) => {
beforeEach(async (done): Promise<void> => {
if (!api) {
api = await ApiPromise.create();
@@ -36,19 +36,19 @@ describe.skip('Promise e2e contracts', () => {
done();
});
describe('flipper', () => {
describe('flipper', (): void => {
const MAX_GAS = 500000;
let abi: Abi;
beforeEach(() => {
beforeEach((): void => {
abi = new Abi(flipperAbi);
});
it('allows putCode', (done) => {
it('allows putCode', (done): Promise<() => void> => {
return (
api.tx.contracts
.putCode(MAX_GAS, `0x${flipperCode}`)
.signAndSend(keyring.eve, (result: SubmittableResult) => {
.signAndSend(keyring.eve, (result: SubmittableResult): void => {
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
@@ -61,13 +61,13 @@ describe.skip('Promise e2e contracts', () => {
);
});
it('allows contract create', (done) => {
it('allows contract create', (done): Promise<() => void> => {
expect(codeHash).toBeDefined();
return (
api.tx.contracts
.create(12345, MAX_GAS, codeHash, abi.deploy())
.signAndSend(keyring.bob, (result: SubmittableResult) => {
.signAndSend(keyring.bob, (result: SubmittableResult): void => {
console.error('create', JSON.stringify(result));
if (result.status.isFinalized) {
@@ -83,13 +83,13 @@ describe.skip('Promise e2e contracts', () => {
);
});
it('allows contract call', (done) => {
it('allows contract call', (done): Promise<() => void> => {
expect(address).toBeDefined();
return (
api.tx.contracts
.call(address, 12345, MAX_GAS, abi.messages.flip())
.signAndSend(keyring.bob, (result: SubmittableResult) => {
.signAndSend(keyring.bob, (result: SubmittableResult): void => {
console.error('call', JSON.stringify(result));
if (result.status.isFinalized && result.findRecord('system', 'ExtrinsicSuccess')) {
+63 -65
View File
@@ -17,11 +17,11 @@ const ZERO = new BN(0);
const WS_URL = 'ws://127.0.0.1:9944';
// const WS_URL = 'wss://poc3-rpc.polkadot.io/';
describe.skip('Promise e2e queries', () => {
describe.skip('Promise e2e queries', (): void => {
const keyring = testingPairs({ type: 'ed25519' });
let api: Api;
beforeEach(async (done) => {
beforeEach(async (done): Promise<void> => {
if (!api) {
api = await Api.create({
provider: new WsProvider(WS_URL)
@@ -32,7 +32,7 @@ describe.skip('Promise e2e queries', () => {
done();
});
it('makes the runtime, rpc, state & extrinsics available', () => {
it('makes the runtime, rpc, state & extrinsics available', (): void => {
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata).toBeDefined();
expect(api.runtimeVersion).toBeDefined();
@@ -42,31 +42,29 @@ describe.skip('Promise e2e queries', () => {
expect(api.derive).toBeDefined();
});
it('allows retrieval of an fallback entry (once-off query)', async () => {
it('allows retrieval of an fallback entry (once-off query)', async (): Promise<void> => {
const nonce = await api.query.system.accountNonce('5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
expect(nonce.toHex()).toEqual('0x0000000000000000');
});
it('allows retrieval of fallback when at query is made', async () => {
it('allows retrieval of fallback when at query is made', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const nonce = await api.query.system.accountNonce.at(header.hash, '5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
expect(nonce.toHex()).toEqual('0x0000000000000000');
});
it('queries state for a balance', async () => {
return (
api.query.balances.freeBalance(keyring.alice.address, (balance: Balance) => {
expect(balance).toBeInstanceOf(BN);
expect(balance.isZero()).toBe(false);
})
);
it('queries state for a balance', async (): Promise<() => void> => {
return api.query.balances.freeBalance(keyring.alice.address, (balance: Balance): void => {
expect(balance).toBeInstanceOf(BN);
expect(balance.isZero()).toBe(false);
});
});
it('subscribes to rpc', (done) => {
it('subscribes to rpc', (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeNewHead((header: Header) => {
api.rpc.chain.subscribeNewHead((header: Header): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
@@ -74,9 +72,9 @@ describe.skip('Promise e2e queries', () => {
);
});
it('subscribes to finalized', (done) => {
it('subscribes to finalized', (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeFinalizedHeads((header: Header) => {
api.rpc.chain.subscribeFinalizedHeads((header: Header): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
@@ -84,9 +82,9 @@ describe.skip('Promise e2e queries', () => {
);
});
it('subscribes to derive', (done) => {
it('subscribes to derive', (done): Promise<() => void> => {
return (
api.derive.chain.subscribeNewHead((header: HeaderExtended) => {
api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
@@ -94,9 +92,9 @@ describe.skip('Promise e2e queries', () => {
);
});
it('subscribes to queries', (done) => {
it('subscribes to queries', (done): Promise<() => void> => {
return (
api.query.system.accountNonce(keyring.ferdie.address, (nonce: Index) => {
api.query.system.accountNonce(keyring.ferdie.address, (nonce: Index): void => {
expect(nonce instanceof BN).toBe(true);
done();
@@ -104,9 +102,9 @@ describe.skip('Promise e2e queries', () => {
);
});
it.skip('subscribes to queries (default)', (done) => {
it.skip('subscribes to queries (default)', (done): Promise<() => void> => {
return (
api.query.staking.validators(keyring.ferdie.address, (prefs: ValidatorPrefs) => {
api.query.staking.validators(keyring.ferdie.address, (prefs: ValidatorPrefs): void => {
expect(prefs.unstakeThreshold.toNumber()).toBe(3);
done();
@@ -114,9 +112,9 @@ describe.skip('Promise e2e queries', () => {
);
});
it('subscribes to a linked map (staking.validators)', (done) => {
it('subscribes to a linked map (staking.validators)', (done): Promise<() => void> => {
return (
api.query.staking.validators((prefs: LinkageResult) => {
api.query.staking.validators((prefs: LinkageResult): void => {
expect(prefs instanceof LinkageResult).toBe(true);
done();
@@ -124,14 +122,14 @@ describe.skip('Promise e2e queries', () => {
);
});
it('subscribes to multiple results (freeBalance.multi)', (done) => {
it('subscribes to multiple results (freeBalance.multi)', (done): Promise<() => void> => {
return (
api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address,
'5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y',
keyring.ferdie.address
], (balances) => {
], (balances): void => {
expect(balances).toHaveLength(4);
done();
@@ -139,24 +137,24 @@ describe.skip('Promise e2e queries', () => {
);
});
it('subscribes to multiple results (api.queryMulti)', (done) => {
it('subscribes to multiple results (api.queryMulti)', (done): Promise<() => void> => {
return api.queryMulti([
[api.query.balances.freeBalance, keyring.alice.address],
[api.query.balances.freeBalance, keyring.bob.address],
[api.query.balances.freeBalance, '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y'],
[api.query.balances.freeBalance, keyring.ferdie.address]
], (balances: Array<Balance>) => {
], (balances: Balance[]): void => {
expect(balances).toHaveLength(4);
done();
});
});
it('subscribes to derived balances (balances.all)', (done) => {
it('subscribes to derived balances (balances.all)', (done): Promise<() => void> => {
return (
api.derive.balances.all(
keyring.alice.address,
(all: DerivedBalances) => {
(all: DerivedBalances): void => {
expect(all.accountId.toString()).toEqual(keyring.alice.address);
expect(all.freeBalance).toBeDefined();
@@ -172,61 +170,61 @@ describe.skip('Promise e2e queries', () => {
);
});
it('can retrive header by hash', async () => {
it('can retrive header by hash', async (): Promise<void> => {
const latest = await api.rpc.chain.getHeader() as Header;
const specific = await api.rpc.chain.getHeader(latest.hash) as Header;
expect(latest.hash).toEqual(specific.hash);
});
it('makes a query at a latest block (specified)', async () => {
it('makes a query at a latest block (specified)', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const events = await api.query.system.events.at(header.hash) as Vector<EventRecord>;
expect(events.length).not.toEqual(0);
events.forEach(({ event: { data, method, section }, phase, topics }: EventRecord) => {
events.forEach(({ event: { data, method, section }, phase, topics }: EventRecord): void => {
console.error(phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
});
it('subscribes to events', (done) => {
it('subscribes to events', (done): Promise<() => void> => {
return (
api.query.system.events((events) => {
api.query.system.events((events): void => {
expect(events).not.toHaveLength(0);
done();
})
);
});
describe('with plain type', () => {
it('queries a correct value', async () => {
describe('with plain type', (): void => {
it('queries a correct value', async (): Promise<void> => {
const sessionIndex = await api.query.session.currentIndex() as SessionIndex;
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
});
it('queries correct value at a specified block', async () => {
it('queries correct value at a specified block', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const sessionIndex = await api.query.session.currentIndex.at(header.hash) as SessionIndex;
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
});
it('subscribes to query and get correct result', (done) => {
return api.query.session.currentIndex((sessionIndex: SessionIndex) => {
it('subscribes to query and get correct result', (done): Promise<() => void> => {
return api.query.session.currentIndex((sessionIndex: SessionIndex): void => {
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
done();
});
});
it('queries correct hash', async () => {
it('queries correct hash', async (): Promise<void> => {
const hash: Hash = await api.query.session.currentIndex.hash();
expect(hash).toBeDefined();
});
it('gets correct key', async () => {
it('gets correct key', async (): Promise<void> => {
const key = api.query.session.currentIndex.key();
const sessionIndexData = await api.rpc.state.getStorage(key) as Option<any>;
const sessionIndexRPC = new SessionIndex(sessionIndexData.unwrapOr(undefined));
@@ -234,7 +232,7 @@ describe.skip('Promise e2e queries', () => {
expect(sessionIndexRPC.toNumber()).toBeGreaterThanOrEqual(0);
});
it('queries correct size', async () => {
it('queries correct size', async (): Promise<void> => {
const size = await api.query.session.currentIndex.size();
expect(size).not.toHaveLength(0);
@@ -242,14 +240,14 @@ describe.skip('Promise e2e queries', () => {
});
});
describe('with map type', () => {
it('queries correct value', async () => {
describe('with map type', (): void => {
it('queries correct value', async (): Promise<void> => {
const balance = await api.query.balances.freeBalance(keyring.alice.address) as Balance;
expect(balance.isZero()).toBe(false);
});
it('queries correct value at a specified block', async () => {
it('queries correct value at a specified block', async (): Promise<void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const balance = await api.query.balances.freeBalance(keyring.alice.address);
const header = await api.rpc.chain.getHeader() as Header;
@@ -259,24 +257,24 @@ describe.skip('Promise e2e queries', () => {
expect(balanceAt.toString()).toEqual(balance.toString());
});
it('subscribes to query and get correct result', async (done) => {
it('subscribes to query and get correct result', async (done): Promise<() => void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const balance = await api.query.balances.freeBalance(keyring.alice.address);
return api.query.balances.freeBalance(keyring.alice.address, (balanceSubscribed: Balance) => {
return api.query.balances.freeBalance(keyring.alice.address, (balanceSubscribed: Balance): void => {
expect(balanceSubscribed.isZero()).toBe(false);
expect(balanceSubscribed.toString()).toEqual(balance.toString());
done();
});
});
it('queries correct hash', async () => {
it('queries correct hash', async (): Promise<void> => {
const hash = await api.query.balances.freeBalance.hash(keyring.alice.address);
expect(hash).toBeDefined();
});
it('gets correct key', async () => {
it('gets correct key', async (): Promise<void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const key = api.query.balances.freeBalance.key(keyring.alice.address);
const balanceData = await api.rpc.state.getStorage(key) as Option<any>;
@@ -288,7 +286,7 @@ describe.skip('Promise e2e queries', () => {
expect(balanceRPC.toString()).toEqual(balance.toString());
});
it('queries multiple results', async () => {
it('queries multiple results', async (): Promise<void> => {
// assume the account Alice and Bob are only used in test(the balance of them do not change in this test case)
const balanceAlice = await api.query.balances.freeBalance(keyring.alice.address);
const balanceBob = await api.query.balances.freeBalance(keyring.bob.address);
@@ -303,7 +301,7 @@ describe.skip('Promise e2e queries', () => {
expect((balances as any)[1].toString()).toEqual(balanceBob.toString());
});
it('subscribes to multiple queries and get correct results', async (done) => {
it('subscribes to multiple queries and get correct results', async (done): Promise<() => void> => {
// assume the account Alice and Bob are only used in test(the balance of them do not change in this test case)
const balanceAlice = await api.query.balances.freeBalance(keyring.alice.address);
const balanceBob = await api.query.balances.freeBalance(keyring.bob.address);
@@ -311,7 +309,7 @@ describe.skip('Promise e2e queries', () => {
return api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address
], (balances) => {
], (balances): void => {
expect(balances).toHaveLength(2);
expect(balances[0].toString()).toEqual(balanceAlice.toString());
expect(balances[1].toString()).toEqual(balanceBob.toString());
@@ -319,7 +317,7 @@ describe.skip('Promise e2e queries', () => {
});
});
it('queries correct size', async () => {
it('queries correct size', async (): Promise<void> => {
const size = await api.query.balances.freeBalance.size(keyring.alice.address);
expect(size.toNumber()).not.toEqual(0);
@@ -327,16 +325,16 @@ describe.skip('Promise e2e queries', () => {
});
// TODO Update ['any', '0x1234'] to the key of a known event topic and update EXPECTED_VALUE to the expected value
describe('with double map type', () => {
describe('with double map type', (): void => {
const KEY1 = 'any';
const KEY2 = '0x1234';
it('queries correct value', async () => {
it('queries correct value', async (): Promise<void> => {
const eventTopics = await api.query.system.eventTopics(KEY1, KEY2);
expect(eventTopics.toJSON()).toEqual([]);
});
it('queries correct value at a specified block', async () => {
it('queries correct value at a specified block', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
// TODO check & fix: this will throw the error: Encoding for input doesn't match output, created 0x00 from 0x
@@ -347,27 +345,27 @@ describe.skip('Promise e2e queries', () => {
// expect(eventTopicsAt.toJSON()).toEqual([]);
});
it('subscribes to query and get correct result', async (done) => {
return api.query.system.eventTopics(KEY1, KEY2, (eventTopicsAt) => {
it('subscribes to query and get correct result', async (done): Promise<() => void> => {
return api.query.system.eventTopics(KEY1, KEY2, (eventTopicsAt): void => {
expect(eventTopicsAt.toJSON()).toEqual([]);
done();
});
});
it('queries correct hash', async () => {
it('queries correct hash', async (): Promise<void> => {
const hash = await api.query.system.eventTopics(KEY1, KEY2);
expect(hash).toBeDefined();
});
it('gets correct key', async () => {
it('gets correct key', async (): Promise<void> => {
const key = api.query.system.eventTopics.key(KEY1, KEY2);
const eventTopicsData = await api.rpc.state.getStorage(key) as Option<any>;
expect(eventTopicsData.unwrapOr(undefined)).toEqual(undefined);
});
it('queries multiple results', async () => {
it('queries multiple results', async (): Promise<void> => {
const eventTopicsList = await api.query.system.eventTopics.multi([
[KEY1, KEY2]
]);
@@ -376,17 +374,17 @@ describe.skip('Promise e2e queries', () => {
expect((eventTopicsList as any)[0].toJSON()).toEqual([]);
});
it('subscribes to multiple queries and get correct results', async (done) => {
it('subscribes to multiple queries and get correct results', async (done): Promise<() => void> => {
return api.query.system.eventTopics.multi([
[KEY1, KEY2]
], (eventTopicsList) => {
], (eventTopicsList): void => {
expect(eventTopicsList).toHaveLength(1);
expect(eventTopicsList[0].toJSON()).toEqual([]);
done();
});
});
it('queries correct size', async () => {
it('queries correct size', async (): Promise<void> => {
const size = await api.query.system.eventTopics.size(KEY1, KEY2);
expect(size.toNumber()).toEqual(0);
+27 -26
View File
@@ -14,15 +14,15 @@ import { Signer } from './../../src/types';
import Api from './../../src/promise';
// log all events for the transfare, calling done() when finalized
const logEvents = (done: () => {}) =>
({ events, status }: SubmittableResult) => {
const logEvents = (done: () => {}): (r: SubmittableResult) => void =>
({ events, status }: SubmittableResult): void => {
console.log('Transaction status:', status.type);
if (status.isFinalized) {
console.log('Completed at block hash', status.value.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }: EventRecord) => {
events.forEach(({ phase, event: { data, method, section } }: EventRecord): void => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
@@ -32,11 +32,11 @@ const logEvents = (done: () => {}) =>
}
};
describe.skip('Promise e2e transactions', () => {
describe.skip('Promise e2e transactions', (): void => {
const keyring = testingPairs({ type: 'ed25519' });
let api: Api;
beforeEach(async (done) => {
beforeEach(async (done): Promise<void> => {
if (!api) {
api = await Api.create({
provider: new WsProvider('ws://127.0.0.1:9944')
@@ -47,11 +47,11 @@ describe.skip('Promise e2e transactions', () => {
done();
});
afterEach(() => {
afterEach((): void => {
jest.setTimeout(5000);
});
it('can submit an extrinsic from hex', async (done) => {
it('can submit an extrinsic from hex', async (done): Promise<() => void> => {
const nonce = await api.query.system.accountNonce(keyring.dave.address) as Index;
const hex = api.tx.balances
.transfer(keyring.eve.address, 12345)
@@ -61,7 +61,7 @@ describe.skip('Promise e2e transactions', () => {
return api.tx(hex).send(logEvents(done));
});
it('makes a transfer (sign, then send)', async (done) => {
it('makes a transfer (sign, then send)', async (done): Promise<() => void> => {
const nonce = await api.query.system.accountNonce(keyring.dave.address) as Index;
return api.tx.balances
@@ -70,7 +70,7 @@ describe.skip('Promise e2e transactions', () => {
.send(logEvents(done));
});
it('makes a transfer (sign, then send - compat version)', async (done) => {
it('makes a transfer (sign, then send - compat version)', async (done): Promise<() => void> => {
const nonce = await api.query.system.accountNonce(keyring.dave.address) as Index;
return api.tx.balances
@@ -79,13 +79,13 @@ describe.skip('Promise e2e transactions', () => {
.send(logEvents(done));
});
it('makes a transfer (signAndSend, immortal)', async (done) => {
it('makes a transfer (signAndSend, immortal)', async (done): Promise<() => void> => {
return api.tx.balances
.transfer(keyring.eve.address, 12345)
.signAndSend(keyring.charlie, { era: 0 }, logEvents(done));
});
it('makes a transfer (signAndSend via Signer)', async (done) => {
it('makes a transfer (signAndSend via Signer)', async (done): Promise<() => void> => {
const signer = new SingleAccountSigner(keyring.charlie) as Signer;
api.setSigner(signer);
@@ -95,7 +95,7 @@ describe.skip('Promise e2e transactions', () => {
.signAndSend(keyring.charlie.address, logEvents(done));
});
it('makes a transfer (signAndSend via Signer) with undefined Signer', async () => {
it('makes a transfer (signAndSend via Signer) with undefined Signer', async (): Promise<void> => {
const signer: any = undefined;
// no signer
api.setSigner(signer);
@@ -105,7 +105,7 @@ describe.skip('Promise e2e transactions', () => {
.signAndSend(keyring.alice.address)).rejects.toThrow('no signer exists');
});
it('makes a transfer (signAndSend via Signer) with the wrong keyring pair', async () => {
it('makes a transfer (signAndSend via Signer) with the wrong keyring pair', async (): Promise<void> => {
const signer: Signer = new SingleAccountSigner(keyring.dave);
api.setSigner(signer);
@@ -116,14 +116,15 @@ describe.skip('Promise e2e transactions', () => {
.signAndSend(keyring.alice.address)).rejects.toThrow('does not have the keyringPair');
});
it('makes a transfer (signAndSend via Signer) with the wrong keyring pair with a callback', async () => {
it('makes a transfer (signAndSend via Signer) with the wrong keyring pair with a callback', async (): Promise<void> => {
// with callback
await expect(api.tx.balances
.transfer(keyring.eve.address, 12345)
.signAndSend(keyring.alice.address, (cb: any) => { /*do nothing */ })).rejects.toThrow('does not have the keyringPair');
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.signAndSend(keyring.alice.address, (cb: any): void => { /* do nothing */ })).rejects.toThrow('does not have the keyringPair');
});
it('makes a transfer (no callback)', async () => {
it('makes a transfer (no callback)', async (): Promise<void> => {
const hash = await api.tx.balances
.transfer(keyring.eve.address, 12345)
.signAndSend(keyring.dave);
@@ -131,7 +132,7 @@ describe.skip('Promise e2e transactions', () => {
expect(hash.toHex()).toHaveLength(66);
});
it('makes a proposal', async () => {
it('makes a proposal', async (): Promise<void> => {
// don't wait for status, just get hash. Here we generate a large-ish payload
// to ensure that we can sign with the hashed version as well (and have it accepted)
const hash: Hash = await api.tx.democracy
@@ -142,29 +143,29 @@ describe.skip('Promise e2e transactions', () => {
});
// this one is slightly difficult with the current testnet config - CantPay
it.skip('makes a transfer, and uses new balance to transfers to new', async (done) => {
it.skip('makes a transfer, and uses new balance to transfers to new', async (done): Promise<() => void> => {
const pair = new Keyring().addFromUri('testing123', {}, 'ed25519');
function doOne (cb: any) {
function doOne (cb: any): Promise<() => void> {
return api.tx.balances
.transfer(pair.address, 1234567)
.signAndSend(keyring.dave, logEvents(cb));
}
function doTwo (cb: any) {
function doTwo (cb: any): Promise<() => void> {
return api.tx.balances
.transfer(keyring.alice.address, 1111111)
.signAndSend(pair, logEvents(cb));
}
// return doTwo(done);
return doOne(() => {
return doOne((): Promise<() => void> => {
return doTwo(done);
});
});
describe('eras', () => {
it('makes a transfer (specified era)', async (done) => {
describe('eras', (): void => {
it('makes a transfer (specified era)', async (done): Promise<void> => {
const signedBlock = await api.rpc.chain.getBlock() as SignedBlock;
const currentHeight = signedBlock.block.header.number;
const exERA = new ExtrinsicEra({ current: currentHeight, period: 10 });
@@ -178,7 +179,7 @@ describe.skip('Promise e2e transactions', () => {
done();
});
it('makes a transfer with invalid time', async (done) => {
it('makes a transfer with invalid time', async (done): Promise<() => void> => {
const nonce = await api.query.system.accountNonce(keyring.alice.address) as Index;
const signedBlock = await api.rpc.chain.getBlock() as SignedBlock;
const currentHeight = signedBlock.block.header.number;
@@ -188,7 +189,7 @@ describe.skip('Promise e2e transactions', () => {
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
return (
api.rpc.chain.subscribeNewHead(async (header: Header) => {
api.rpc.chain.subscribeNewHead(async (header: Header): Promise<void> => {
if (header.blockNumber.toNumber() === eraDeath - 1) {
try {
await ex.signAndSend(keyring.alice, { blockHash, era: exERA, nonce } as any);
@@ -201,7 +202,7 @@ describe.skip('Promise e2e transactions', () => {
);
});
it('makes a transfer with custom numeric era', async (done) => {
it('makes a transfer with custom numeric era', async (done): Promise<void> => {
const hash = await api.tx.balances
.transfer(keyring.eve.address, 12345)
.signAndSend(keyring.charlie, { era: 2 });
+8 -8
View File
@@ -11,17 +11,17 @@ import testingPairs from '@polkadot/keyring/testingPairs';
import Api from '../../src/rx';
describe.skip('Rx e2e queries', () => {
describe.skip('Rx e2e queries', (): void => {
const keyring = testingPairs({ type: 'ed25519' });
let api: Api;
beforeEach(async (done) => {
beforeEach(async (done): Promise<void> => {
api = await Api.create().toPromise();
jest.setTimeout(3000000);
done();
});
it('makes the runtime, rpc, state & extrinsics available', () => {
it('makes the runtime, rpc, state & extrinsics available', (): void => {
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata).toBeDefined();
expect(api.runtimeVersion).toBeDefined();
@@ -31,22 +31,22 @@ describe.skip('Rx e2e queries', () => {
expect(api.derive).toBeDefined();
});
it('queries state for a balance', (done) => {
api.query.balances.freeBalance(keyring.alice.address).subscribe((balance) => {
it('queries state for a balance', (done): void => {
api.query.balances.freeBalance(keyring.alice.address).subscribe((balance): void => {
expect(balance).toBeInstanceOf(BN);
expect((balance as Balance).isZero()).toBe(false);
done();
});
});
it('makes a query at a specific block', (done) => {
it('makes a query at a specific block', (done): void => {
(api.rpc.chain.getHeader() as Observable<Header>)
.pipe(
switchMap(({ hash }: Header) =>
switchMap(({ hash }: Header): Observable<any> =>
api.query.system.events.at(hash)
)
)
.subscribe((events: any) => {
.subscribe((events: any): void => {
expect(events.length).not.toEqual(0);
done();
});
+9 -9
View File
@@ -11,50 +11,50 @@ import testingPairs from '@polkadot/keyring/testingPairs';
import Api from './../../src/rx';
import { SubmittableResult } from './../../src';
describe.skip('Rx e2e transactions', () => {
describe.skip('Rx e2e transactions', (): void => {
const keyring = testingPairs({ type: 'ed25519' });
let api: Api;
beforeEach(async (done) => {
beforeEach(async (done): Promise<void> => {
api = await Api.create().toPromise();
jest.setTimeout(30000);
done();
});
afterEach(() => {
afterEach((): void => {
jest.setTimeout(5000);
});
it('makes a transfer', (done) => {
it('makes a transfer', (done): void => {
(api.query.system.accountNonce(keyring.alice.address) as Observable<Index>)
.pipe(
first(),
switchMap((nonce: Index) =>
switchMap((nonce: Index): Observable<SubmittableResult> =>
api.tx.balances
.transfer(keyring.bob.address, 12345)
.sign(keyring.alice, { nonce })
.send()
)
)
.subscribe(({ status }: SubmittableResult) => {
.subscribe(({ status }: SubmittableResult): void => {
if (status.isFinalized) {
done();
}
});
});
it('makes a proposal', (done) => {
it('makes a proposal', (done): void => {
(api.query.system.accountNonce(keyring.alice.address) as Observable<Index>)
.pipe(
first(),
switchMap((nonce: Index) =>
switchMap((nonce: Index): Observable<SubmittableResult> =>
api.tx.democracy
.propose(api.tx.system.setCode('0xdeadbeef'), 10000)
.sign(keyring.alice, { nonce })
.send()
)
)
.subscribe(({ status }: SubmittableResult) => {
.subscribe(({ status }: SubmittableResult): void => {
if (status.isFinalized) {
done();
}
@@ -12,11 +12,11 @@ let id = 0;
export default class SingleAccountSigner {
private keyringPair: KeyringPair;
constructor (keyringPair: KeyringPair) {
public constructor (keyringPair: KeyringPair) {
this.keyringPair = keyringPair;
}
async sign (extrinsic: Extrinsic, address: string, options: SignatureOptions) {
public async sign (extrinsic: Extrinsic, address: string, options: SignatureOptions): Promise<number> {
if (!this.keyringPair || String(address) !== this.keyringPair.address) {
throw new Error('does not have the keyringPair');
}