Typescript-eslint 2 (#1353)
* Make a start * More minor cleanups * Some more cleanups * Last round? * Exclude build folders
This commit is contained in:
@@ -32,6 +32,6 @@
|
||||
"@polkadot/types": "^0.91.0-beta.10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^1.1.1"
|
||||
"@polkadot/keyring": "^1.2.0-beta.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) =>
|
||||
// where rpc.chain.getHeader throws, we will land here - it can happen that
|
||||
// we supplied an invalid hash. (Due to defaults, storeage will have an
|
||||
// empty value, so only the RPC is affected). So return undefined
|
||||
of() as Observable<undefined>
|
||||
of()
|
||||
),
|
||||
drr()
|
||||
);
|
||||
|
||||
@@ -23,6 +23,7 @@ export function controllers (api: ApiInterfaceRx): () => Observable<[AccountId[]
|
||||
switchMap(([stashIds]): Observable<[AccountId[], Option<AccountId>[]]> =>
|
||||
combineLatest([
|
||||
of(stashIds),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
|
||||
api.query.staking.bonded.multi(stashIds) as Observable<Option<AccountId>[]>
|
||||
])
|
||||
),
|
||||
|
||||
@@ -8,8 +8,8 @@ import { AnyJsonObject, Constructor } from '@polkadot/types/types';
|
||||
import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
|
||||
import { Struct } from '@polkadot/types';
|
||||
|
||||
// @ts-ignore We can ignore the properties, added via Struct.with
|
||||
const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header);
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header as any) as any;
|
||||
|
||||
/**
|
||||
* @name HeaderExtended
|
||||
|
||||
@@ -9,8 +9,8 @@ import BN from 'bn.js';
|
||||
import democracyTypes from '@polkadot/types/interfaces/democracy/definitions';
|
||||
import { Struct, createType } from '@polkadot/types';
|
||||
|
||||
// @ts-ignore We can ignore the properties, added via Struct.with
|
||||
const _ReferendumInfo: Constructor<ReferendumInfo> = Struct.with(democracyTypes.types.ReferendumInfo);
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _ReferendumInfo: Constructor<ReferendumInfo> = Struct.with(democracyTypes.types.ReferendumInfo as any) as any;
|
||||
|
||||
/**
|
||||
* @name ReferendumInfoExtended
|
||||
|
||||
@@ -28,10 +28,10 @@
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.5.5",
|
||||
"@polkadot/types": "^0.91.0-beta.10",
|
||||
"@polkadot/util": "^1.1.1",
|
||||
"@polkadot/util-crypto": "^1.1.1"
|
||||
"@polkadot/util": "^1.2.0-beta.3",
|
||||
"@polkadot/util-crypto": "^1.2.0-beta.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^1.1.1"
|
||||
"@polkadot/keyring": "^1.2.0-beta.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,8 +70,8 @@ function createKeyDoubleMap ({ meta: { name, type } }: CreateItemFn, rawKey: Uin
|
||||
const param1Encoded = u8aConcat(rawKey, createTypeUnsafe(type1, [key1]).toU8a(true));
|
||||
const param1Hashed = hasher(param1Encoded);
|
||||
|
||||
// @ts-ignore If this fails it means the getHashers function failed - and we have much bigger issues
|
||||
const param2Hashed = key2Hasher(createTypeUnsafe(type2, [key2]).toU8a(true));
|
||||
// If this fails it means the getHashers function failed - and we have much bigger issues
|
||||
const param2Hashed = (key2Hasher as HasherFunction)(createTypeUnsafe(type2, [key2]).toU8a(true));
|
||||
|
||||
// as per createKey, always add the length prefix (underlying it is Bytes)
|
||||
return Compact.addLengthPrefix(u8aConcat(param1Hashed, param2Hashed));
|
||||
|
||||
@@ -32,9 +32,9 @@
|
||||
"@polkadot/rpc-core": "^0.91.0-beta.10",
|
||||
"@polkadot/rpc-provider": "^0.91.0-beta.10",
|
||||
"@polkadot/types": "^0.91.0-beta.10",
|
||||
"@polkadot/util-crypto": "^1.1.1"
|
||||
"@polkadot/util-crypto": "^1.2.0-beta.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^1.1.1"
|
||||
"@polkadot/keyring": "^1.2.0-beta.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export interface SignerPayloadType {
|
||||
}
|
||||
|
||||
// We explicitly cast the type here to get the actual TypeScript exports right
|
||||
// @ts-ignore We can ignore the properties, added via Struct.with
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _Payload: Constructor<SignerPayloadType> = Struct.with({
|
||||
address: 'Address',
|
||||
blockHash: 'Hash',
|
||||
@@ -34,7 +34,7 @@ const _Payload: Constructor<SignerPayloadType> = Struct.with({
|
||||
runtimeVersion: 'RuntimeVersion',
|
||||
tip: 'Compact<Balance>',
|
||||
version: u8
|
||||
});
|
||||
}) as any;
|
||||
|
||||
export default class Payload extends _Payload {
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
|
||||
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ModulesWithCalls } from '@polkadot/types/types';
|
||||
import { SubmittableExtrinsic } from '../submittable/types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethodOptions, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { BehaviorSubject, Observable } from 'rxjs';
|
||||
@@ -50,7 +50,7 @@ export default abstract class Decorate<ApiType> extends Events {
|
||||
|
||||
protected _isConnected: BehaviorSubject<boolean>;
|
||||
|
||||
protected _isReady: boolean = false;
|
||||
protected _isReady = false;
|
||||
|
||||
protected readonly _options: ApiOptions;
|
||||
|
||||
@@ -70,6 +70,24 @@ export default abstract class Decorate<ApiType> extends Events {
|
||||
|
||||
protected _type: ApiTypes;
|
||||
|
||||
/**
|
||||
* This is the one and only method concrete children classes need to implement.
|
||||
* It's a higher-order function, which takes one argument
|
||||
* `method: Method extends (...args: any[]) => Observable<any>`
|
||||
* (and one optional `options`), and should return the user facing method.
|
||||
* For example:
|
||||
* - For ApiRx, `decorateMethod` should just be identity, because the input
|
||||
* function is already an Observable
|
||||
* - For ApiPromise, `decorateMethod` should return a function that takes all
|
||||
* the parameters from `method`, adds an optional `callback` argument, and
|
||||
* returns a Promise.
|
||||
*
|
||||
* We could easily imagine other user-facing interfaces, which are simply
|
||||
* implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon
|
||||
* via `deocrateMethod`.
|
||||
*/
|
||||
protected decorateMethod: DecorateMethod;
|
||||
|
||||
/**
|
||||
* @description Create an instance of the class
|
||||
*
|
||||
@@ -88,37 +106,20 @@ export default abstract class Decorate<ApiType> extends Events {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public constructor (options: ApiOptions, type: ApiTypes) {
|
||||
public constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod) {
|
||||
super();
|
||||
|
||||
const thisProvider = options.source
|
||||
? options.source._rpcCore.provider.clone()
|
||||
: (options.provider || new WsProvider());
|
||||
|
||||
this.decorateMethod = decorateMethod;
|
||||
this._options = options;
|
||||
this._type = type;
|
||||
this._rpcCore = new RpcCore(thisProvider);
|
||||
this._isConnected = new BehaviorSubject(this._rpcCore.provider.isConnected());
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the one and only method concrete children classes need to implement.
|
||||
* It's a higher-order function, which takes one argument
|
||||
* `method: Method extends (...args: any[]) => Observable<any>`
|
||||
* (and one optional `options`), and should return the user facing method.
|
||||
* For example:
|
||||
* - For ApiRx, `decorateMethod` should just be identity, because the input
|
||||
* function is already an Observable
|
||||
* - For ApiPromise, `decorateMethod` should return a function that takes all
|
||||
* the parameters from `method`, adds an optional `callback` argument, and
|
||||
* returns a Promise.
|
||||
*
|
||||
* We could easily imagine other user-facing interfaces, which are simply
|
||||
* implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon
|
||||
* via `deocrateMethod`.
|
||||
*/
|
||||
protected abstract decorateMethod(method: (...args: any[]) => Observable<any>, options?: DecorateMethodOptions): any;
|
||||
|
||||
private decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
|
||||
output.meta = input.meta;
|
||||
output.method = input.method;
|
||||
@@ -136,10 +137,9 @@ export default abstract class Decorate<ApiType> extends Events {
|
||||
return ['author', 'chain', 'state', 'system'].reduce((out, _sectionName): DecoratedRpc<ApiType, RpcInterface> => {
|
||||
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
|
||||
|
||||
// @ts-ignore Hard to type these correctly, I don't understand the TS errors
|
||||
out[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
|
||||
// @ts-ignore
|
||||
section[methodName] = decorateMethod(method, { methodName });
|
||||
// out and section here are horrors to get right from a typing perspective :()
|
||||
(out as any)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
|
||||
(section as any)[methodName] = decorateMethod(method, { methodName });
|
||||
|
||||
return section;
|
||||
}, {} as unknown as DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]>);
|
||||
@@ -310,7 +310,7 @@ export default abstract class Decorate<ApiType> extends Events {
|
||||
* Put the `this.onCall` function of ApiRx here, because it is needed by
|
||||
* `api._rx`.
|
||||
*/
|
||||
protected rxDecorateMethod<Method extends AnyFunction> (method: Method): Method {
|
||||
protected rxDecorateMethod = <Method extends AnyFunction> (method: Method): Method => {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { RuntimeVersion, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import { SignedBlock } from '@polkadot/types/interfaces';
|
||||
import { RegistryTypes } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes } from '../types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod } from '../types';
|
||||
|
||||
import constantsFromMeta from '@polkadot/api-metadata/consts/fromMetadata';
|
||||
import extrinsicsFromMeta from '@polkadot/api-metadata/extrinsics/fromMetadata';
|
||||
@@ -46,8 +46,8 @@ const l = logger('api/decorator');
|
||||
export default abstract class Init<ApiType> extends Decorate<ApiType> {
|
||||
private _healthTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
public constructor (options: ApiOptions, type: ApiTypes) {
|
||||
super(options, type);
|
||||
public constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod) {
|
||||
super(options, type, decorateMethod);
|
||||
|
||||
assert(this._rpcCore.provider.hasSubscriptions, 'Api can only be used with a provider supporting subscriptions');
|
||||
|
||||
@@ -99,7 +99,7 @@ export default abstract class Init<ApiType> extends Decorate<ApiType> {
|
||||
SPEC_TYPES[this._runtimeVersion.specName.toString()]
|
||||
);
|
||||
|
||||
const metadataKey = `${this._genesisHash}-${(this._runtimeVersion as RuntimeVersion).specVersion}`;
|
||||
const metadataKey = `${this._genesisHash}-${this._runtimeVersion.specVersion}`;
|
||||
const metadata = metadataKey in optMetadata
|
||||
? new Metadata(optMetadata[metadataKey])
|
||||
: await this._rpcCore.state.getMetadata().toPromise();
|
||||
@@ -111,7 +111,7 @@ export default abstract class Init<ApiType> extends Decorate<ApiType> {
|
||||
}
|
||||
|
||||
private async initFromMeta (metadata: Metadata): Promise<boolean> {
|
||||
// HACK-ish Old EventRecord format for e.g. Alex, based on \metadata format
|
||||
// HACK-ish Old EventRecord format for e.g. Alex, based on metadata format
|
||||
if (metadata.version <= 3) {
|
||||
this.registerTypes(TYPES_SUBSTRATE_1);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,7 @@
|
||||
import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types';
|
||||
import { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { CallFunction, RegistryTypes } from '@polkadot/types/types';
|
||||
|
||||
import { ApiOptions, ApiTypes, DecoratedRpc, QueryableStorage, QueryableStorageMulti, SignerPayloadRawBase, SubmittableExtrinsics, Signer } from '../types';
|
||||
import { ApiOptions, ApiTypes, DecoratedRpc, DecorateMethod, QueryableStorage, QueryableStorageMulti, SignerPayloadRawBase, SubmittableExtrinsics, Signer } from '../types';
|
||||
|
||||
import { Constants } from '@polkadot/api-metadata/consts/types';
|
||||
import { GenericCall, Metadata, getTypeRegistry } from '@polkadot/types';
|
||||
@@ -52,8 +51,8 @@ export default abstract class ApiBase<ApiType> extends Init<ApiType> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
public constructor (options: ApiOptions = {}, type: ApiTypes) {
|
||||
super(options, type);
|
||||
public constructor (options: ApiOptions = {}, type: ApiTypes, decorateMethod: DecorateMethod) {
|
||||
super(options, type, decorateMethod);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,7 +15,7 @@ import { createType, createTypeUnsafe } from '@polkadot/types/codec';
|
||||
|
||||
import { SubmittableResult } from './';
|
||||
|
||||
async function consts (api: ApiPromise): Promise<void> {
|
||||
function consts (api: ApiPromise): void {
|
||||
// constants has actual value & metadata
|
||||
console.log(
|
||||
api.consts.balances.creationFee.toHex(),
|
||||
@@ -118,4 +118,5 @@ async function main (): Promise<void> {
|
||||
tx(api, keyring);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
main().catch(console.error);
|
||||
|
||||
@@ -57,6 +57,37 @@ function promiseTracker (resolve: (value: () => void) => void, reject: (value: E
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
|
||||
*/
|
||||
function decorateMethod<Method extends AnyFunction> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
|
||||
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
|
||||
|
||||
return function (...args: any[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
|
||||
const [actualArgs, callback] = extractArgs(args, !!needsCallback);
|
||||
|
||||
if (!callback) {
|
||||
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
const subscription = method(...actualArgs)
|
||||
.pipe(
|
||||
// if we find an error (invalid params, etc), reject the promise
|
||||
catchError((error): Observable<never> =>
|
||||
tracker.reject(error)
|
||||
),
|
||||
// upon the first result, resolve the with the unsub function
|
||||
tap((): void =>
|
||||
tracker.resolve((): void => subscription.unsubscribe())
|
||||
)
|
||||
)
|
||||
.subscribe(callback);
|
||||
}) as any; // ???
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
|
||||
/**
|
||||
* # @polkadot/api/promise
|
||||
*
|
||||
@@ -183,7 +214,7 @@ export default class ApiPromise extends ApiBase<'promise'> {
|
||||
* ```
|
||||
*/
|
||||
public constructor (options?: ApiOptions) {
|
||||
super(options, 'promise');
|
||||
super(options, 'promise', decorateMethod);
|
||||
|
||||
this._isReadyPromise = new Promise((resolve): void => {
|
||||
super.once('ready', (): void => {
|
||||
@@ -229,6 +260,7 @@ export default class ApiPromise extends ApiBase<'promise'> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async combineLatest (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback): UnsubscribePromise {
|
||||
const combinator = new Combinator(fns, callback);
|
||||
|
||||
@@ -236,35 +268,4 @@ export default class ApiPromise extends ApiBase<'promise'> {
|
||||
combinator.unsubscribe();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
|
||||
*/
|
||||
protected decorateMethod<Method extends AnyFunction> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
|
||||
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
|
||||
|
||||
return function (...args: any[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
|
||||
const [actualArgs, callback] = extractArgs(args, !!needsCallback);
|
||||
|
||||
if (!callback) {
|
||||
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
const subscription = method(...actualArgs)
|
||||
.pipe(
|
||||
// if we find an error (invalid params, etc), reject the promise
|
||||
catchError((error): Observable<never> =>
|
||||
tracker.reject(error)
|
||||
),
|
||||
// upon the first result, resolve the with the unsub function
|
||||
tap((): void =>
|
||||
tracker.resolve((): void => subscription.unsubscribe())
|
||||
)
|
||||
)
|
||||
.subscribe(callback);
|
||||
}) as UnsubscribePromise;
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface CombinatorFunction {
|
||||
}
|
||||
|
||||
export default class Combinator {
|
||||
protected _allHasFired: boolean = false;
|
||||
protected _allHasFired = false;
|
||||
|
||||
protected _callback: CombinatorCallback;
|
||||
|
||||
@@ -21,7 +21,7 @@ export default class Combinator {
|
||||
|
||||
protected _fns: CombinatorFunction[] = [];
|
||||
|
||||
protected _isActive: boolean = true;
|
||||
protected _isActive = true;
|
||||
|
||||
protected _results: any[] = [];
|
||||
|
||||
@@ -29,6 +29,8 @@ export default class Combinator {
|
||||
|
||||
public constructor (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback) {
|
||||
this._callback = callback;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
this._subscriptions = fns.map(async (input, index): UnsubscribePromise => {
|
||||
const [fn, ...args] = Array.isArray(input)
|
||||
? input
|
||||
@@ -37,8 +39,8 @@ export default class Combinator {
|
||||
this._fired.push(false);
|
||||
this._fns.push(fn);
|
||||
|
||||
// @ts-ignore Not quite 100% how to have a variable number at the front here
|
||||
return fn(...args, this.createCallback(index));
|
||||
// Not quite 100% how to have a variable number at the front here
|
||||
return (fn as Function)(...args, this.createCallback(index));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,6 +80,7 @@ export default class Combinator {
|
||||
|
||||
this._isActive = false;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
this._subscriptions.forEach(async (subscription): Promise<void> => {
|
||||
try {
|
||||
const unsubscribe = await subscription;
|
||||
|
||||
@@ -7,6 +7,8 @@ import Combinator from './Combinator';
|
||||
|
||||
describe('Combinator', (): void => {
|
||||
let fns: ((value: any) => void)[] = [];
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
const storeFn = async (cb: (value: any) => void): UnsubscribePromise => {
|
||||
fns.push(cb);
|
||||
|
||||
@@ -81,9 +83,11 @@ describe('Combinator', (): void => {
|
||||
});
|
||||
|
||||
it('unsubscribes as required', (done): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
const mocker = async (): Promise<any> => done;
|
||||
const combinator = new Combinator([
|
||||
mocker,
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
async (): UnsubscribePromise => (): void => {}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
], (value: any[]): void => {
|
||||
|
||||
@@ -9,6 +9,10 @@ import { from, Observable } from 'rxjs';
|
||||
|
||||
import ApiBase from '../base';
|
||||
|
||||
function decorateMethod <Method extends AnyFunction> (method: Method): Method {
|
||||
return method;
|
||||
}
|
||||
|
||||
/**
|
||||
* # @polkadot/api/rx
|
||||
*
|
||||
@@ -157,7 +161,7 @@ export default class ApiRx extends ApiBase<'rxjs'> {
|
||||
* ```
|
||||
*/
|
||||
public constructor (options?: ApiOptions) {
|
||||
super(options, 'rxjs');
|
||||
super(options, 'rxjs', decorateMethod);
|
||||
|
||||
this._isReadyRx = from(
|
||||
// You can create an observable from an event, however my mind groks this form better
|
||||
@@ -192,8 +196,4 @@ export default class ApiRx extends ApiBase<'rxjs'> {
|
||||
source: this
|
||||
});
|
||||
}
|
||||
|
||||
protected decorateMethod<Method extends AnyFunction> (method: Method): Method {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,7 +232,7 @@ class Submittable<ApiType> extends _Extrinsic implements SubmittableExtrinsic<Ap
|
||||
);
|
||||
}
|
||||
|
||||
private _sendObservable (updateId: number = -1): Observable<Hash> {
|
||||
private _sendObservable = (updateId = -1): Observable<Hash> => {
|
||||
return this._api.rpc.author
|
||||
.submitExtrinsic(this)
|
||||
.pipe(
|
||||
@@ -242,7 +242,7 @@ class Submittable<ApiType> extends _Extrinsic implements SubmittableExtrinsic<Ap
|
||||
);
|
||||
}
|
||||
|
||||
private _subscribeObservable (updateId: number = -1): Observable<SubmittableResultImpl> {
|
||||
private _subscribeObservable = (updateId = -1): Observable<SubmittableResultImpl> => {
|
||||
return this._api.rpc.author
|
||||
.submitAndWatchExtrinsic(this)
|
||||
.pipe(
|
||||
|
||||
@@ -50,6 +50,8 @@ export interface DecorateMethodOptions {
|
||||
methodName?: string;
|
||||
}
|
||||
|
||||
export type DecorateMethod = (method: (...args: any[]) => Observable<any>, options?: DecorateMethodOptions) => any;
|
||||
|
||||
// Here are the return types of these parts of the api:
|
||||
// - api.query.*.*: no exact typings
|
||||
// - api.tx.*.*: SubmittableExtrinsic<ApiType>
|
||||
|
||||
@@ -73,7 +73,7 @@ describeE2E({
|
||||
}
|
||||
|
||||
expect(info.accountId.eq(accountId)).toBe(true);
|
||||
expect(info.controllerId!.eq('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')).toBe(true);
|
||||
expect(info.controllerId.eq('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')).toBe(true);
|
||||
expect(info.stashId.eq(accountId)).toBe(true);
|
||||
expect(info.stashId.eq(info.stakingLedger.stash)).toBe(true);
|
||||
|
||||
@@ -142,17 +142,19 @@ describeE2E({
|
||||
let count = 0; // The # of times we got a callback response from api.derive.staking.info
|
||||
|
||||
// Subscribe to staking.info
|
||||
api.derive.staking.info(stashId, (result): void => {
|
||||
++count;
|
||||
api.derive.staking
|
||||
.info(stashId, (result): void => {
|
||||
++count;
|
||||
|
||||
console.error('***', count, JSON.stringify(result));
|
||||
console.error('***', count, JSON.stringify(result));
|
||||
|
||||
if (count >= 2 && result.rewardDestination!.toString() === 'Stash') {
|
||||
done();
|
||||
}
|
||||
}).catch(console.error);
|
||||
if (count >= 2 && result.rewardDestination!.toString() === 'Stash') {
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
// Wait a bit, and change reward destination
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
setTimeout(async (): Promise<void> => {
|
||||
await api.tx.staking
|
||||
.setPayee('Stash')
|
||||
|
||||
@@ -44,8 +44,7 @@ describeE2E({
|
||||
// (and it is assuming it sent at least 1 tx)
|
||||
describe('derive.accounts', (): void => {
|
||||
describe('idAndIndex', (): void => {
|
||||
it('looks up AccountId & AccountIndex from AccountId', async (done): Promise<void> => {
|
||||
// @ts-ignore silence warning until we have static types here
|
||||
it('looks up AccountId & AccountIndex from AccountId', (done): void => {
|
||||
api.derive.accounts.idAndIndex(ID).subscribe(([accountId, accountIndex]): void => {
|
||||
expect(accountId!.toString()).toEqual(ID);
|
||||
// The first emitted value for ix is undefined when passing the ID
|
||||
@@ -58,8 +57,7 @@ describeE2E({
|
||||
});
|
||||
});
|
||||
|
||||
it('looks up AccountId & AccountIndex from AccountIndex', async (done): Promise<void> => {
|
||||
// @ts-ignore silence warning until we have static types here
|
||||
it('looks up AccountId & AccountIndex from AccountIndex', (done): void => {
|
||||
api.derive.accounts.idAndIndex(IX).subscribe(([accountId, accountIndex]): void => {
|
||||
// The first emitted value for id is undefined when passing the IX
|
||||
if (accountId) {
|
||||
@@ -74,8 +72,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('indexToId', (): void => {
|
||||
it('looks up AccountId from AccountIndex', async (done): Promise<void> => {
|
||||
// @ts-ignore silence warning until we have static types here
|
||||
it('looks up AccountId from AccountIndex', (done): void => {
|
||||
api.derive.accounts.indexToId(IX).subscribe((accountId): void => {
|
||||
// The first emitted value for accountId is undefined when passing the IX
|
||||
if (accountId) {
|
||||
@@ -90,8 +87,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('idToIndex', (): void => {
|
||||
it('looks up AccountIndex from AccountId', async (done): Promise<void> => {
|
||||
// @ts-ignore silence warning until we have static types here
|
||||
it('looks up AccountIndex from AccountId', (done): void => {
|
||||
api.derive.accounts.idToIndex(ID).subscribe((accountIndex): void => {
|
||||
// The first emitted value for AccountIndex is undefined when passing the ID
|
||||
if (accountIndex) {
|
||||
@@ -106,8 +102,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('indexes', (): void => {
|
||||
it('looks up all AccountIndexes', async (done): Promise<void> => {
|
||||
// @ts-ignore silence warning until we have static types here
|
||||
it('looks up all AccountIndexes', (done): void => {
|
||||
api.derive.accounts.indexes().subscribe((accountIndexes): void => {
|
||||
// A local dev chain should have the AccountIndex of Alice
|
||||
expect(accountIndexes).toHaveProperty(
|
||||
@@ -124,7 +119,7 @@ describeE2E({
|
||||
// (and it is assuming it sent at least 1 tx)
|
||||
describe('derive.balances', (): void => {
|
||||
describe('all', (): void => {
|
||||
it('It returns an object with all relevant balance information of an account', async (done): Promise<void> => {
|
||||
it('It returns an object with all relevant balance information of an account', (done): void => {
|
||||
api.derive.balances.all(ID).subscribe((balances: DerivedBalances): void => {
|
||||
expect(balances).toEqual(expect.objectContaining({
|
||||
accountId: expect.any(ClassOf('AccountId')),
|
||||
@@ -142,7 +137,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('fees', (): void => {
|
||||
it('fees: It returns an object with all relevant fees of type BN', async (done): Promise<void> => {
|
||||
it('fees: It returns an object with all relevant fees of type BN', (done): void => {
|
||||
api.derive.balances.fees().subscribe((fees: DerivedFees): void => {
|
||||
expect(fees).toEqual(expect.objectContaining({
|
||||
creationFee: expect.any(BN),
|
||||
@@ -159,7 +154,7 @@ describeE2E({
|
||||
|
||||
describe('derive.chain', (): void => {
|
||||
describe('bestNumber', (): void => {
|
||||
it('Get the latest block number', async (done): Promise<void> => {
|
||||
it('Get the latest block number', (done): void => {
|
||||
api.derive.chain.bestNumber().subscribe((blockNumber: BlockNumber): void => {
|
||||
expect(blockNumber instanceof ClassOf('BlockNumber')).toBe(true);
|
||||
expect(blockNumber.gten(0)).toBe(true);
|
||||
@@ -169,7 +164,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('bestNumberFinalized', (): void => {
|
||||
it('Get the latest finalised block number', async (done): Promise<void> => {
|
||||
it('Get the latest finalised block number', (done): void => {
|
||||
api.derive.chain.bestNumberFinalized().subscribe((blockNumber: BlockNumber): void => {
|
||||
expect(blockNumber instanceof ClassOf('BlockNumber')).toBe(true);
|
||||
expect(blockNumber.gten(0)).toBe(true);
|
||||
@@ -179,7 +174,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('bestNumberLag', (): void => {
|
||||
it('lag between finalised head and best head', async (done): Promise<void> => {
|
||||
it('lag between finalised head and best head', (done): void => {
|
||||
api.derive.chain.bestNumberLag().subscribe((numberLag: BlockNumber): void => {
|
||||
expect(numberLag instanceof ClassOf('BlockNumber')).toBe(true);
|
||||
expect(numberLag.gten(0)).toBe(true);
|
||||
@@ -190,7 +185,7 @@ describeE2E({
|
||||
|
||||
// FIXME https://github.com/polkadot-js/api/issues/868
|
||||
describe('getHeader', (): void => {
|
||||
it('gets a specific block header and extended with it`s author', async (done): Promise<void> => {
|
||||
it('gets a specific block header and extended with it`s author', (done): void => {
|
||||
api.derive.chain.getHeader('TODO').subscribe((headerExtended: HeaderExtended | undefined): void => {
|
||||
// WIP
|
||||
expect(headerExtended).toEqual(expect.arrayContaining([]));
|
||||
@@ -200,7 +195,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('subscribeNewHeads', (): void => {
|
||||
it('gets an observable of the current block header and it\'s author', async (done): Promise<void> => {
|
||||
it('gets an observable of the current block header and it\'s author', (done): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
api.derive.chain.subscribeNewHeads().subscribe((headerExtended: HeaderExtended): void => {
|
||||
// WIP https://github.com/polkadot-js/api/issues/868
|
||||
@@ -212,7 +207,7 @@ describeE2E({
|
||||
|
||||
describe('derive.contracts', (): void => {
|
||||
describe('fees', (): void => {
|
||||
it('fees: It returns an object with all relevant constract fees of type Balance', async (done): Promise<void> => {
|
||||
it('fees: It returns an object with all relevant constract fees of type Balance', (done): void => {
|
||||
api.derive.contracts.fees().subscribe((fees: DerivedContractFees): void => {
|
||||
expect(fees).toEqual(expect.objectContaining({
|
||||
callBaseFee: expect.any(BN),
|
||||
@@ -234,7 +229,7 @@ describeE2E({
|
||||
|
||||
describe('derive.elections', (): void => {
|
||||
describe('info', (): void => {
|
||||
it('It returns an object with all relevant elections properties', async (done): Promise<void> => {
|
||||
it('It returns an object with all relevant elections properties', (done): void => {
|
||||
api.derive.elections.info().subscribe((info: DerivedElectionsInfo): void => {
|
||||
expect(info).toEqual(expect.objectContaining({
|
||||
members: expect.anything(),
|
||||
@@ -252,7 +247,7 @@ describeE2E({
|
||||
|
||||
describe('derive.session', (): void => {
|
||||
describe('sessionProgress', (): void => {
|
||||
it('derive.session.sessionProgress', async (done): Promise<void> => {
|
||||
it('derive.session.sessionProgress', (done): void => {
|
||||
api.derive.session.sessionProgress().subscribe((progress: BN): void => {
|
||||
expect(progress instanceof BN).toBe(true);
|
||||
done();
|
||||
@@ -261,7 +256,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('session.info', (): void => {
|
||||
it('retrieves all session info', async (done): Promise<void> => {
|
||||
it('retrieves all session info', (done): void => {
|
||||
api.derive.session.info().subscribe((info: DerivedSessionInfo): void => {
|
||||
expect(info).toEqual(expect.objectContaining({
|
||||
currentEra: expect.anything(),
|
||||
@@ -280,7 +275,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('session.eraLength', (): void => {
|
||||
it('derive.session.eraLength', async (done): Promise<void> => {
|
||||
it('derive.session.eraLength', (done): void => {
|
||||
api.derive.session.eraLength().subscribe((length: BN): void => {
|
||||
expect(length instanceof BN).toBe(true);
|
||||
done();
|
||||
@@ -289,7 +284,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('session.eraProgress', (): void => {
|
||||
it('derive.session.eraProgress', async (done): Promise<void> => {
|
||||
it('derive.session.eraProgress', (done): void => {
|
||||
api.derive.session.eraProgress().subscribe((progress: BN): void => {
|
||||
expect(progress instanceof BN).toBe(true);
|
||||
done();
|
||||
|
||||
@@ -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 { AccountId, EventRecord, Header } from '@polkadot/types/interfaces';
|
||||
import { AccountId, EventRecord } from '@polkadot/types/interfaces';
|
||||
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { ClassOf, Option, Vec } from '@polkadot/types';
|
||||
@@ -73,7 +73,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('makes a query at a latest block (specified)', async (): Promise<void> => {
|
||||
const header = await api.rpc.chain.getHeader() as Header;
|
||||
const header = await api.rpc.chain.getHeader();
|
||||
const events = await api.query.system.events.at(header.hash) as Vec<EventRecord>;
|
||||
|
||||
expect(events.length).not.toEqual(0);
|
||||
|
||||
@@ -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 { Balance, Header, Index } from '@polkadot/types/interfaces';
|
||||
import { Balance, Index } from '@polkadot/types/interfaces';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
@@ -40,7 +40,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('allows retrieval of fallback when at query is made', async (): Promise<void> => {
|
||||
const header = await api.rpc.chain.getHeader() as Header;
|
||||
const header = await api.rpc.chain.getHeader();
|
||||
const nonce = await api.query.system.accountNonce.at(header.hash, '5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
|
||||
|
||||
expect(nonce.toHex()).toEqual('0x0000000000000000');
|
||||
@@ -131,7 +131,7 @@ describeE2E({
|
||||
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_stash.address);
|
||||
const header = await api.rpc.chain.getHeader() as Header;
|
||||
const header = await api.rpc.chain.getHeader();
|
||||
const balanceAt = await api.query.balances.freeBalance.at(header.hash, keyring.alice_stash.address) as Balance;
|
||||
|
||||
expect(balanceAt.isZero()).toBe(false);
|
||||
|
||||
@@ -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 { Header, Keys } from '@polkadot/types/interfaces';
|
||||
import { Keys } from '@polkadot/types/interfaces';
|
||||
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
@@ -41,7 +41,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('queries correct value at a specified block', async (): Promise<void> => {
|
||||
const header = await api.rpc.chain.getHeader() as Header;
|
||||
const header = await api.rpc.chain.getHeader();
|
||||
|
||||
// TODO check & fix: this will throw the error: Encoding for input doesn't match output, created 0x00 from 0x
|
||||
const eventTopicsAt = await api.query.system.eventTopics.at(header.hash, KEY1, KEY2);
|
||||
@@ -98,7 +98,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
describe('session Keys', (): void => {
|
||||
it('sets a session key, retrieves the value', async (done): Promise<void> => {
|
||||
it('sets a session key, retrieves the value', (done): void => {
|
||||
const babe = encodeAddress(randomAsU8a());
|
||||
const grandpa = encodeAddress(randomAsU8a());
|
||||
const imOnline = encodeAddress(randomAsU8a());
|
||||
|
||||
@@ -72,14 +72,14 @@ describeE2E()('Promise e2e queries', (wsUrl: string): void => {
|
||||
});
|
||||
|
||||
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;
|
||||
const latest = await api.rpc.chain.getHeader();
|
||||
const specific = await api.rpc.chain.getHeader(latest.hash);
|
||||
|
||||
expect(latest.hash).toEqual(specific.hash);
|
||||
});
|
||||
|
||||
it('makes a query at a latest block (specified)', async (): Promise<void> => {
|
||||
const header = await api.rpc.chain.getHeader() as Header;
|
||||
const header = await api.rpc.chain.getHeader();
|
||||
const events = await api.query.system.events.at(header.hash) as Vec<EventRecord>;
|
||||
|
||||
expect(events.length).not.toEqual(0);
|
||||
@@ -106,7 +106,7 @@ describeE2E()('Promise e2e queries', (wsUrl: string): void => {
|
||||
});
|
||||
|
||||
it('queries correct value at a specified block', async (): Promise<void> => {
|
||||
const header = await api.rpc.chain.getHeader() as Header;
|
||||
const header = await api.rpc.chain.getHeader();
|
||||
const sessionIndex = await api.query.session.currentIndex.at(header.hash) as SessionIndex;
|
||||
|
||||
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import { EventRecord, Header, Index, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import { EventRecord, Header, Index } from '@polkadot/types/interfaces';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
import { SubmittableResult } from '../../../src';
|
||||
@@ -50,7 +50,7 @@ describeE2E({
|
||||
|
||||
describe('eras', (): void => {
|
||||
it('makes a transfer (specified era)', async (done): Promise<void> => {
|
||||
const signedBlock = await api.rpc.chain.getBlock() as SignedBlock;
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
|
||||
@@ -62,7 +62,7 @@ describeE2E({
|
||||
});
|
||||
|
||||
it('makes a transfer (specified era, previous block)', async (done): Promise<void> => {
|
||||
const signedBlock = await api.rpc.chain.getBlock() as SignedBlock;
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number.toBn().subn(1);
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 10 });
|
||||
const ex = api.tx.balances.transfer(keyring.eve.address, 12345);
|
||||
@@ -75,7 +75,7 @@ describeE2E({
|
||||
|
||||
it('fails on 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 signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const eraDeath = exERA.asMortalEra.death(currentHeight.toNumber());
|
||||
@@ -104,7 +104,7 @@ describeE2E({
|
||||
api.setSigner(signer);
|
||||
|
||||
const nonce = await api.query.system.accountNonce(keyring.bob_stash.address) as Index;
|
||||
const signedBlock = await api.rpc.chain.getBlock() as SignedBlock;
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const exERA = createType('ExtrinsicEra', { current: currentHeight, period: 4 });
|
||||
const eraDeath = exERA.asMortalEra.death(currentHeight.toNumber());
|
||||
|
||||
@@ -47,6 +47,7 @@ describeE2E({
|
||||
beforeAll(async (done): Promise<() => void> => {
|
||||
abi = new Abi(incrementerAbi);
|
||||
api = await ApiPromise.create({ provider: new WsProvider(wsUrl) });
|
||||
|
||||
return (
|
||||
api.tx.contracts
|
||||
.putCode(MAX_GAS, `0x${incrementerCode}`)
|
||||
@@ -62,7 +63,7 @@ describeE2E({
|
||||
);
|
||||
});
|
||||
|
||||
beforeEach(async (done): Promise<void> => {
|
||||
beforeEach((done): void => {
|
||||
rpc = new Rpc(new WsProvider(wsUrl));
|
||||
done();
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ export class SingleAccountSigner implements Signer {
|
||||
|
||||
private signDelay: number;
|
||||
|
||||
public constructor (keyringPair: KeyringPair, signDelay: number = 0) {
|
||||
public constructor (keyringPair: KeyringPair, signDelay = 0) {
|
||||
this.keyringPair = keyringPair;
|
||||
this.signDelay = signDelay;
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
"@polkadot/jsonrpc": "^0.91.0-beta.10",
|
||||
"@polkadot/rpc-provider": "^0.91.0-beta.10",
|
||||
"@polkadot/types": "^0.91.0-beta.10",
|
||||
"@polkadot/util": "^1.1.1",
|
||||
"@polkadot/util": "^1.2.0-beta.3",
|
||||
"rxjs": "^6.5.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,8 +63,8 @@ describe('Cached Observables', (): void => {
|
||||
});
|
||||
|
||||
it('creates different observables for different methods but same arguments', (): void => {
|
||||
// @ts-ignore
|
||||
const observable1 = rpc.chain.subscribeNewHeads([123]);
|
||||
// params do not match here
|
||||
const observable1 = (rpc.chain as any).subscribeNewHeads([123]);
|
||||
const observable2 = rpc.state.subscribeStorage([123]);
|
||||
|
||||
expect(observable2).not.toBe(observable1);
|
||||
|
||||
@@ -70,6 +70,7 @@ export default class Rpc implements RpcInterface {
|
||||
* @param {ProviderInterface} provider An API provider using HTTP or WebSocket
|
||||
*/
|
||||
public constructor (provider: ProviderInterface) {
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
assert(provider && isFunction(provider.send), 'Expected Provider to API create');
|
||||
|
||||
this.provider = provider;
|
||||
@@ -249,6 +250,7 @@ export default class Rpc implements RpcInterface {
|
||||
// Normalize args so that different args that should be cached
|
||||
// together are cached together.
|
||||
// E.g.: `query.my.method('abc') === query.my.method(createType('AccountId', 'abc'));`
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
normalizer: JSON.stringify
|
||||
});
|
||||
|
||||
|
||||
@@ -37,12 +37,12 @@ describe('methodSend', (): void => {
|
||||
});
|
||||
|
||||
it('wraps errors with the call signature', (done): void => {
|
||||
// @ts-ignore private method
|
||||
const method = rpc.createMethodSend(methods.blah);
|
||||
// private access
|
||||
const method = (rpc as any).createMethodSend(methods.blah);
|
||||
|
||||
method().subscribe(
|
||||
(): void => { /* noop */ },
|
||||
(error): void => {
|
||||
(): void => {},
|
||||
(error: Error): void => {
|
||||
expect(error.message).toMatch(/blah \(foo: Bytes\): Bytes/);
|
||||
done();
|
||||
}
|
||||
@@ -50,20 +50,20 @@ describe('methodSend', (): void => {
|
||||
});
|
||||
|
||||
it('checks for mismatched parameters', (done): void => {
|
||||
// @ts-ignore private method
|
||||
const method = rpc.createMethodSend(methods.bleh);
|
||||
// private method
|
||||
const method = (rpc as any).createMethodSend(methods.bleh);
|
||||
|
||||
method(1).subscribe(
|
||||
(): void => { /* noop */ },
|
||||
(error): void => {
|
||||
(): void => {},
|
||||
(error: Error): void => {
|
||||
expect(error.message).toMatch(/parameters, 1 found instead/);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls the provider with the correct parameters', (done): void => {
|
||||
// @ts-ignore private method
|
||||
const method = rpc.createMethodSend(methods.blah);
|
||||
// private method
|
||||
const method = (rpc as any).createMethodSend(methods.blah);
|
||||
|
||||
// Args are length-prefixed, because it's a Bytes
|
||||
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe((): void => {
|
||||
|
||||
@@ -15,12 +15,11 @@ describe('replay', (): void => {
|
||||
});
|
||||
|
||||
it('subscribes via the rpc section', (done): void => {
|
||||
// @ts-ignore
|
||||
rpc.chain.getBlockHash = jest.fn((): Observable<number> => of(1));
|
||||
|
||||
// @ts-ignore
|
||||
rpc.chain.getBlockHash(123, false).subscribe((): void => {
|
||||
// we don't honor types or number of params here
|
||||
(rpc.chain as any).getBlockHash = jest.fn((): Observable<number> => of(1));
|
||||
(rpc.chain as any).getBlockHash(123, false).subscribe((): void => {
|
||||
expect(
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
rpc.chain.getBlockHash
|
||||
).toHaveBeenCalledWith(123, false);
|
||||
|
||||
@@ -52,6 +51,7 @@ describe('replay', (): void => {
|
||||
});
|
||||
|
||||
it('unsubscribes as required', (done): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
rpc.provider.unsubscribe = jest.fn();
|
||||
|
||||
const subscription = rpc.chain.subscribeNewHeads().subscribe((): void => {
|
||||
@@ -59,6 +59,7 @@ describe('replay', (): void => {
|
||||
|
||||
// There's a promise inside .unsubscribe(), wait a bit
|
||||
setTimeout((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
expect(rpc.provider.unsubscribe).toHaveBeenCalled();
|
||||
done();
|
||||
}, 200);
|
||||
|
||||
@@ -28,15 +28,15 @@
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.5.5",
|
||||
"@polkadot/api-metadata": "^0.91.0-beta.10",
|
||||
"@polkadot/util": "^1.1.1",
|
||||
"@polkadot/util-crypto": "^1.1.1",
|
||||
"@polkadot/util": "^1.2.0-beta.3",
|
||||
"@polkadot/util-crypto": "^1.2.0-beta.3",
|
||||
"@types/nock": "^10.0.3",
|
||||
"eventemitter3": "^4.0.0",
|
||||
"isomorphic-fetch": "^2.2.1",
|
||||
"websocket": "^1.0.29"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^1.1.1",
|
||||
"@polkadot/keyring": "^1.2.0-beta.3",
|
||||
"mock-socket": "^9.0.0",
|
||||
"nock": "^10.0.4"
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBaseError } from '../ty
|
||||
import { assert, isUndefined, isNumber } from '@polkadot/util';
|
||||
|
||||
export default class RpcCoder {
|
||||
private id: number = 0;
|
||||
private id = 0;
|
||||
|
||||
public decodeResponse (response: JsonRpcResponse): any {
|
||||
assert(response, 'Empty response object received');
|
||||
|
||||
@@ -113,7 +113,7 @@ export default class HttpProvider implements ProviderInterface {
|
||||
/**
|
||||
* @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/require-await
|
||||
public async subscribe (types: string, method: string, params: any[], cb: ProviderInterfaceCallback): Promise<number> {
|
||||
l.error(ERROR_SUBSCRIBE);
|
||||
|
||||
@@ -123,7 +123,7 @@ export default class HttpProvider implements ProviderInterface {
|
||||
/**
|
||||
* @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/require-await
|
||||
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
l.error(ERROR_SUBSCRIBE);
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ export default class Mock implements ProviderInterface {
|
||||
|
||||
private emitter = new EventEmitter();
|
||||
|
||||
public isUpdating: boolean = true;
|
||||
public isUpdating = true;
|
||||
|
||||
private requests: Record<string, (...params: any[]) => string> = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
@@ -74,7 +74,7 @@ export default class Mock implements ProviderInterface {
|
||||
return subs;
|
||||
}, ({} as unknown as MockStateSubscriptions));
|
||||
|
||||
private subscriptionId: number = 0;
|
||||
private subscriptionId = 0;
|
||||
|
||||
private subscriptionMap: Record<number, string> = {};
|
||||
|
||||
@@ -102,6 +102,7 @@ export default class Mock implements ProviderInterface {
|
||||
this.emitter.on(type, sub);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async send (method: string, params: any[]): Promise<any> {
|
||||
if (!this.requests[method]) {
|
||||
throw new Error(`provider.send: Invalid method '${method}'`);
|
||||
@@ -110,6 +111,7 @@ export default class Mock implements ProviderInterface {
|
||||
return this.requests[method](this.db, params);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async subscribe (type: string, method: string, ...params: any[]): Promise<number> {
|
||||
l.debug((): any => ['subscribe', method, params]);
|
||||
|
||||
@@ -130,6 +132,7 @@ export default class Mock implements ProviderInterface {
|
||||
throw new Error(`provider.subscribe: Invalid method '${method}'`);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
const sub = this.subscriptionMap[id];
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ const l = logger('api-ws');
|
||||
export default class WsProvider implements WSProviderInterface {
|
||||
private _eventemitter: EventEmitter;
|
||||
|
||||
private _isConnected: boolean = false;
|
||||
private _isConnected = false;
|
||||
|
||||
private autoConnect: boolean;
|
||||
|
||||
@@ -89,7 +89,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @param {string} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`
|
||||
* @param {boolean} autoConnect Whether to connect automatically or not.
|
||||
*/
|
||||
public constructor (endpoint: string = defaults.WS_URL, autoConnect: boolean = true) {
|
||||
public constructor (endpoint: string = defaults.WS_URL, autoConnect = true) {
|
||||
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
|
||||
|
||||
this._eventemitter = new EventEmitter();
|
||||
@@ -376,6 +376,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
this.subscriptions = {};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
Object.keys(subscriptions).forEach(async (id): Promise<void> => {
|
||||
const { callback, method, params, type } = subscriptions[id];
|
||||
|
||||
@@ -397,8 +398,8 @@ export default class WsProvider implements WSProviderInterface {
|
||||
private sendQueue (): void {
|
||||
Object.keys(this.queued).forEach((id): void => {
|
||||
try {
|
||||
// @ts-ignore we have done the websocket check in onSocketOpen, if an issue, will catch it
|
||||
this.websocket.send(
|
||||
// we have done the websocket check in onSocketOpen, if an issue, will catch it
|
||||
(this.websocket as WebSocket).send(
|
||||
this.queued[id]
|
||||
);
|
||||
|
||||
|
||||
@@ -22,36 +22,31 @@ describe('onConnect', (): void => {
|
||||
it('Does not connect when autoConnect is false', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, false);
|
||||
// We need to access the private WsProvider property 'websocket' here which would otherwise trigger a tslint error.
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).toBeNull();
|
||||
expect((provider as any).websocket).toBeNull();
|
||||
});
|
||||
|
||||
it('Does connect when autoConnect is true', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, true);
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).not.toBeNull();
|
||||
|
||||
expect((provider as any).websocket).not.toBeNull();
|
||||
});
|
||||
|
||||
it('Creates a new WebSocket instance by calling the connect() method', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, false);
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).toBeNull();
|
||||
|
||||
expect((provider as any).websocket).toBeNull();
|
||||
|
||||
provider.connect();
|
||||
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).not.toBeNull();
|
||||
// @ts-ignore
|
||||
expect(provider.websocket instanceof WebSocket).toBe(true);
|
||||
expect((provider as any).websocket).not.toBeNull();
|
||||
expect((provider as any).websocket instanceof WebSocket).toBe(true);
|
||||
});
|
||||
|
||||
it('Creates the on handlers', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL);
|
||||
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).not.toBeNull();
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).toEqual(expect.objectContaining({
|
||||
expect((provider as any).websocket).not.toBeNull();
|
||||
expect((provider as any).websocket).toEqual(expect.objectContaining({
|
||||
listeners: expect.objectContaining({
|
||||
close: [expect.any(Function)],
|
||||
error: [expect.any(Function)],
|
||||
|
||||
@@ -13,8 +13,7 @@ describe('WsProvider', (): void => {
|
||||
|
||||
it('calls the handler when found', (done): void => {
|
||||
// We need to access the private WsProvider property 'handlers' here which otherwise trigger a tslint error..
|
||||
// @ts-ignore
|
||||
provider.handlers[5] = {
|
||||
(provider as any).handlers[5] = {
|
||||
callback: (_: any, result: any): void => {
|
||||
expect(result).toEqual('test');
|
||||
done();
|
||||
@@ -24,8 +23,7 @@ describe('WsProvider', (): void => {
|
||||
};
|
||||
|
||||
// We need to access the private WsProvider property 'onSocketMessage' here which would otherwise trigger a tslint error.
|
||||
// @ts-ignore
|
||||
provider.onSocketMessage(
|
||||
(provider as any).onSocketMessage(
|
||||
new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":5,"result":"test"}' })
|
||||
);
|
||||
});
|
||||
|
||||
@@ -13,8 +13,7 @@ describe('onMessageSubscribe', (): void => {
|
||||
|
||||
it('calls the subscriber with data', (done): void => {
|
||||
// We need to access the private WsProvider property 'handlers' here which otherwise triggers a tslint error..
|
||||
// @ts-ignore
|
||||
provider.handlers[11] = {
|
||||
(provider as any).handlers[11] = {
|
||||
callback: (_: any, id: number): void => {
|
||||
expect(typeof id).toBe('number');
|
||||
},
|
||||
@@ -30,16 +29,13 @@ describe('onMessageSubscribe', (): void => {
|
||||
};
|
||||
|
||||
// We need to access the private WsProvider property 'onSocketMessage' here which would otherwise trigger a tslint error.
|
||||
// @ts-ignore
|
||||
provider.onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":11,"result":22}' }));
|
||||
// @ts-ignore
|
||||
provider.onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","method":"test","params":{"subscription":22,"result":"test"}}' }));
|
||||
(provider as any).onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":11,"result":22}' }));
|
||||
(provider as any).onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","method":"test","params":{"subscription":22,"result":"test"}}' }));
|
||||
});
|
||||
|
||||
it('calls the subscriber with error', (done): void => {
|
||||
// We need to access the private WsProvider property 'handlers' here which otherwise trigger a tslint error..
|
||||
// @ts-ignore
|
||||
provider.handlers[11] = {
|
||||
(provider as any).handlers[11] = {
|
||||
callback: (_: any, id: number): void => {
|
||||
expect(typeof id).toBe('number');
|
||||
},
|
||||
@@ -55,9 +51,7 @@ describe('onMessageSubscribe', (): void => {
|
||||
};
|
||||
|
||||
// We need to access the private WsProvider property 'onSocketMessage' here which would otherwise trigger a tslint error.
|
||||
// @ts-ignore
|
||||
provider.onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":11,"result":22}' }));
|
||||
// @ts-ignore
|
||||
provider.onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","method":"test","params":{"subscription":22,"error":{"message":"test"}}}' }));
|
||||
(provider as any).onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":11,"result":22}' }));
|
||||
(provider as any).onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","method":"test","params":{"subscription":22,"error":{"message":"test"}}}' }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Constructor } from '@polkadot/types/types';
|
||||
|
||||
import { Global } from './../mock/types';
|
||||
|
||||
declare let global: Global;
|
||||
declare const global: Global;
|
||||
|
||||
describe('ws/polyfill', (): void => {
|
||||
let origWs: Constructor<WebSocket>;
|
||||
|
||||
@@ -3,6 +3,5 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
if (typeof WebSocket === 'undefined') {
|
||||
// @ts-ignore
|
||||
global.WebSocket = require('websocket').w3cwebsocket;
|
||||
(global as any).WebSocket = require('websocket').w3cwebsocket;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Global, Mock } from './../mock/types';
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
declare const global: Global;
|
||||
|
||||
let provider: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
@@ -16,7 +17,7 @@ function createMock (requests: any[]): void {
|
||||
mock = mockWs(requests);
|
||||
}
|
||||
|
||||
function createWs (autoConnect: boolean = true): WsProvider {
|
||||
function createWs (autoConnect = true): WsProvider {
|
||||
provider = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return provider;
|
||||
@@ -47,8 +48,9 @@ describe('send', (): void => {
|
||||
};
|
||||
|
||||
provider = createWs(true);
|
||||
// @ts-ignore Accessing private method
|
||||
provider.websocket.onopen();
|
||||
|
||||
// HACK this is a private method...
|
||||
(provider as any).websocket.onopen();
|
||||
|
||||
return provider
|
||||
.send('test_encoding', ['param'])
|
||||
|
||||
@@ -8,7 +8,8 @@ import WsProvider from './';
|
||||
import { Global, Mock } from './../mock/types';
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
declare var global: Global;
|
||||
declare const global: Global;
|
||||
|
||||
let ws: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
@@ -16,7 +17,7 @@ function createMock (requests: any[]): void {
|
||||
mock = mockWs(requests);
|
||||
}
|
||||
|
||||
function createWs (autoConnect: boolean = true): WsProvider {
|
||||
function createWs (autoConnect = true): WsProvider {
|
||||
ws = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
|
||||
@@ -8,7 +8,8 @@ import WsProvider from './';
|
||||
import { Global, Mock } from './../mock/types';
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
declare var global: Global;
|
||||
declare const global: Global;
|
||||
|
||||
let ws: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
@@ -16,7 +17,7 @@ function createMock (requests: any): void {
|
||||
mock = mockWs(requests);
|
||||
}
|
||||
|
||||
function createWs (autoConnect: boolean = true): WsProvider {
|
||||
function createWs (autoConnect = true): WsProvider {
|
||||
ws = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
|
||||
@@ -68,15 +68,12 @@ function mockWs (requests: { method: string }[]): Scope {
|
||||
};
|
||||
|
||||
server.on('connection', (socket): void => {
|
||||
// @ts-ignore definitions are wrong, this is 'on', not 'onmessage'
|
||||
socket.on('message', (body: { [index: string]: {} }): void => {
|
||||
// FIXME This whole any mess is a mess
|
||||
socket.on('message', (body: any): void => {
|
||||
const request = requests[requestCount];
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
const response = request.error
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
? createError(request)
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
: createReply(request);
|
||||
const response = (request as any).error
|
||||
? createError(request as any)
|
||||
: createReply(request as any);
|
||||
|
||||
scope.body[request.method] = body;
|
||||
requestCount++;
|
||||
|
||||
@@ -83,8 +83,8 @@ const getMetadata: RpcMethodOpt = {
|
||||
params: [
|
||||
createParam('block', 'Hash', { isOptional: true })
|
||||
],
|
||||
// @ts-ignore This is not part of InterfaceTypes
|
||||
type: 'Metadata'
|
||||
// This is not part of InterfaceTypes
|
||||
type: 'Metadata' as any
|
||||
};
|
||||
|
||||
const getRuntimeVersion: RpcMethodOpt = {
|
||||
|
||||
@@ -27,12 +27,12 @@
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.5.5",
|
||||
"@polkadot/util": "^1.1.1",
|
||||
"@polkadot/util-crypto": "^1.1.1",
|
||||
"@polkadot/util": "^1.2.0-beta.3",
|
||||
"@polkadot/util-crypto": "^1.2.0-beta.3",
|
||||
"@types/memoizee": "^0.4.2",
|
||||
"memoizee": "^0.4.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^1.1.1"
|
||||
"@polkadot/keyring": "^1.2.0-beta.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export default abstract class AbstractInt extends BN implements Codec {
|
||||
public constructor (
|
||||
isNegative: boolean,
|
||||
value: AnyNumber = 0,
|
||||
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = true) {
|
||||
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson = true) {
|
||||
super(
|
||||
AbstractInt.decodeAbstracInt(value, bitLength, isNegative)
|
||||
);
|
||||
|
||||
@@ -120,6 +120,6 @@ export default class Compact<T extends CompactEncodable> extends Base<T> {
|
||||
* @description Returns the embedded [[UInt]] or [[Moment]] value
|
||||
*/
|
||||
public unwrap (): T {
|
||||
return this.raw as T;
|
||||
return this.raw;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import U64 from '../primitive/U64';
|
||||
|
||||
describe('Date', (): void => {
|
||||
describe('decode', (): void => {
|
||||
const testDecode = (type: string, input: Date | CodecDate | U64 | number, expected: string | number, toJSON: boolean = false): void =>
|
||||
const testDecode = (type: string, input: Date | CodecDate | U64 | number, expected: string | number, toJSON = false): void =>
|
||||
it(`can decode from ${type}`, (): void => {
|
||||
expect(new CodecDate(input)[toJSON ? 'toJSON' : 'toISOString']()).toBe(expected);
|
||||
});
|
||||
|
||||
@@ -93,7 +93,7 @@ export default class CodecDate extends Date implements Codec {
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (isLe: boolean = false): string {
|
||||
public toHex (isLe = false): string {
|
||||
return bnToHex(this.toBn(), {
|
||||
bitLength: BITLENGTH,
|
||||
isLe,
|
||||
|
||||
@@ -122,7 +122,7 @@ export default class Enum extends Base<Codec> {
|
||||
return Enum.createValue(def, index, value);
|
||||
}
|
||||
|
||||
private static createValue (def: TypesDef, index: number = 0, value?: any): Decoded {
|
||||
private static createValue (def: TypesDef, index = 0, value?: any): Decoded {
|
||||
const Clazz = Object.values(def)[index];
|
||||
|
||||
assert(!isUndefined(Clazz), `Unable to create Enum via index ${index}, in ${Object.keys(def).join(', ')}`);
|
||||
|
||||
@@ -21,7 +21,7 @@ import AbstractInt, { DEFAULT_UINT_BITS, UIntBitLength } from './AbstractInt';
|
||||
export default class Int extends AbstractInt {
|
||||
public constructor (
|
||||
value: AnyNumber = 0,
|
||||
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = true) {
|
||||
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson = true) {
|
||||
super(
|
||||
true,
|
||||
value,
|
||||
@@ -33,7 +33,7 @@ export default class Int extends AbstractInt {
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (isLe: boolean = false): string {
|
||||
public toHex (isLe = false): string {
|
||||
return bnToHex(this, {
|
||||
bitLength: this._bitLength,
|
||||
isLe,
|
||||
|
||||
@@ -22,7 +22,7 @@ import AbstractInt, { DEFAULT_UINT_BITS, UIntBitLength } from './AbstractInt';
|
||||
export default class UInt extends AbstractInt {
|
||||
public constructor (
|
||||
value: AnyNumber = 0,
|
||||
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = false) {
|
||||
bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson = false) {
|
||||
super(
|
||||
false,
|
||||
value,
|
||||
@@ -34,7 +34,7 @@ export default class UInt extends AbstractInt {
|
||||
/**
|
||||
* @description Returns a hex string representation of the value
|
||||
*/
|
||||
public toHex (isLe: boolean = false): string {
|
||||
public toHex (isLe = false): string {
|
||||
// For display/JSON, this is BE, for compare, use isLe
|
||||
return bnToHex(this, {
|
||||
bitLength: this._bitLength,
|
||||
|
||||
@@ -95,7 +95,7 @@ function hasWrapper (type: string, [start, end]: [string, string, any]): boolean
|
||||
return false;
|
||||
}
|
||||
|
||||
assert(type[type.length - 1] === end, `Expected '${start}' closing with '${end}'`);
|
||||
assert(type.endsWith(end), `Expected '${start}' closing with '${end}'`);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { ClassOf } from '../create';
|
||||
export function typeToConstructor <T = Codec> (type: InterfaceTypes | Constructor<T>): Constructor<T> {
|
||||
return (
|
||||
isString(type)
|
||||
? ClassOf(type as InterfaceTypes)
|
||||
? ClassOf(type)
|
||||
: type
|
||||
) as Constructor<T>;
|
||||
}
|
||||
|
||||
@@ -38,10 +38,9 @@ export default class Bytes extends U8a {
|
||||
return value;
|
||||
}
|
||||
|
||||
private static decodeBytesStorage (value: Uint8Array): Uint8Array {
|
||||
private static decodeBytesStorage (u8a: Uint8Array): Uint8Array {
|
||||
// Here we cater for the actual StorageData that _could_ have a length prefix. In the
|
||||
// case of `:code` it is not added, for others it is
|
||||
const u8a = value as Uint8Array;
|
||||
const [offset, length] = Compact.decodeU8a(u8a);
|
||||
|
||||
return u8a.length === length.addn(offset).toNumber()
|
||||
|
||||
@@ -241,12 +241,11 @@ export default class Extrinsic extends Base<ExtrinsicVx | ExtrinsicUnknown> impl
|
||||
// payload: ExtrinsicPayloadValue | Uint8Array | string
|
||||
let payload = args[0];
|
||||
|
||||
// @ts-ignore
|
||||
if (args.length === 2) {
|
||||
// FIXME The old support as detailed above... needs to be dropped
|
||||
if ((args as any[]).length === 2) {
|
||||
payload = {
|
||||
blockHash: new Uint8Array(),
|
||||
// @ts-ignore
|
||||
era: args[1] as string,
|
||||
era: (args as any[])[1] as string,
|
||||
genesisHash: new Uint8Array(),
|
||||
method: this.method.toHex(),
|
||||
nonce: args[0] as string,
|
||||
|
||||
@@ -32,7 +32,7 @@ export default class ExtrinsicV1 extends Struct implements IExtrinsicImpl {
|
||||
}, ExtrinsicV1.decodeExtrinsic(value, isSigned));
|
||||
}
|
||||
|
||||
public static decodeExtrinsic (value?: Uint8Array | ExtrinsicValueV1, isSigned: boolean = false): ExtrinsicValueV1 {
|
||||
public static decodeExtrinsic (value?: Uint8Array | ExtrinsicValueV1, isSigned = false): ExtrinsicValueV1 {
|
||||
if (!value) {
|
||||
return {};
|
||||
} else if (value instanceof ExtrinsicV1) {
|
||||
|
||||
@@ -32,7 +32,7 @@ export default class ExtrinsicSignatureV1 extends Struct implements IExtrinsicSi
|
||||
}, ExtrinsicSignatureV1.decodeExtrinsicSignature(value, isSigned));
|
||||
}
|
||||
|
||||
public static decodeExtrinsicSignature (value: ExtrinsicSignatureV1 | Uint8Array | undefined, isSigned: boolean = false): ExtrinsicSignatureV1 | Uint8Array {
|
||||
public static decodeExtrinsicSignature (value: ExtrinsicSignatureV1 | Uint8Array | undefined, isSigned = false): ExtrinsicSignatureV1 | Uint8Array {
|
||||
if (!value) {
|
||||
return EMPTY_U8A;
|
||||
} else if (value instanceof ExtrinsicSignatureV1) {
|
||||
|
||||
@@ -32,7 +32,7 @@ export default class ExtrinsicV2 extends Struct implements IExtrinsicImpl {
|
||||
}, ExtrinsicV2.decodeExtrinsic(value, isSigned));
|
||||
}
|
||||
|
||||
public static decodeExtrinsic (value?: Call | Uint8Array | ExtrinsicValueV2, isSigned: boolean = false): ExtrinsicValueV2 {
|
||||
public static decodeExtrinsic (value?: Call | Uint8Array | ExtrinsicValueV2, isSigned = false): ExtrinsicValueV2 {
|
||||
if (!value) {
|
||||
return {};
|
||||
} else if (value instanceof ExtrinsicV2) {
|
||||
|
||||
@@ -28,7 +28,7 @@ export default class ExtrinsicSignatureV2 extends Struct implements IExtrinsicSi
|
||||
}, ExtrinsicSignatureV2.decodeExtrinsicSignature(value, isSigned));
|
||||
}
|
||||
|
||||
public static decodeExtrinsicSignature (value: ExtrinsicSignatureV2 | Uint8Array | undefined, isSigned: boolean = false): ExtrinsicSignatureV2 | Uint8Array {
|
||||
public static decodeExtrinsicSignature (value: ExtrinsicSignatureV2 | Uint8Array | undefined, isSigned = false): ExtrinsicSignatureV2 | Uint8Array {
|
||||
if (!value) {
|
||||
return EMPTY_U8A;
|
||||
} else if (value instanceof ExtrinsicSignatureV2) {
|
||||
|
||||
@@ -32,7 +32,7 @@ export default class ExtrinsicV3 extends Struct implements IExtrinsicImpl {
|
||||
}, ExtrinsicV3.decodeExtrinsic(value, isSigned));
|
||||
}
|
||||
|
||||
public static decodeExtrinsic (value?: Call | Uint8Array | ExtrinsicValueV3, isSigned: boolean = false): ExtrinsicValueV3 {
|
||||
public static decodeExtrinsic (value?: Call | Uint8Array | ExtrinsicValueV3, isSigned = false): ExtrinsicValueV3 {
|
||||
if (!value) {
|
||||
return {};
|
||||
} else if (value instanceof ExtrinsicV3) {
|
||||
|
||||
@@ -61,7 +61,7 @@ describe('AccountId', (): void => {
|
||||
});
|
||||
|
||||
describe('encoding', (): void => {
|
||||
const testEncode = (to: 'toHex' | 'toJSON' | 'toString' | 'toU8a', expected: Uint8Array | string, input: string = '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF'): void =>
|
||||
const testEncode = (to: 'toHex' | 'toJSON' | 'toString' | 'toU8a', expected: Uint8Array | string, input = '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF'): void =>
|
||||
it(`can encode ${to}`, (): void => {
|
||||
const a = createType('AccountId', input);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
require('@babel/register')({
|
||||
extensions: ['.js', '.ts'],
|
||||
plugins: [
|
||||
|
||||
@@ -74,17 +74,17 @@ function isCompactEncodable (Child: Constructor<any>): boolean {
|
||||
}
|
||||
|
||||
// helper to generate a `export interface <Name> extends <Base> {<Body>}
|
||||
function exportInterface (name: string = '', base: string, body: string = ''): string {
|
||||
function exportInterface (name = '', base: string, body = ''): string {
|
||||
return `/** ${base} */\nexport interface ${name} extends ${base} {${body.length ? '\n' : ''}${body}}`;
|
||||
}
|
||||
|
||||
// helper to create an `export <Name> = <Base>`
|
||||
function exportType (name: string = '', base: string): string {
|
||||
function exportType (name = '', base: string): string {
|
||||
return `/** ${base} */\nexport type ${name} = ${base};`;
|
||||
}
|
||||
|
||||
// helper to generate a `readonly <Name>: <Type>;` getter
|
||||
function createGetter (name: string = '', type: string, imports: TypeImports, doc?: string): string {
|
||||
function createGetter (name = '', type: string, imports: TypeImports, doc?: string): string {
|
||||
setImports(imports, [type]);
|
||||
return ` /** ${doc || type} */\n readonly ${name}: ${type};\n`;
|
||||
}
|
||||
@@ -265,7 +265,7 @@ function createImportCode (header: string, checks: { file: string; types: string
|
||||
}
|
||||
|
||||
// From `T`, generate `Compact<T>, Option<T>, Vec<T>`
|
||||
function getDerivedTypes (type: string, primitiveName: string, imports: TypeImports, indent: number = 2): string {
|
||||
function getDerivedTypes (type: string, primitiveName: string, imports: TypeImports, indent = 2): string {
|
||||
// `primitiveName` represents the actual primitive type our type is mapped to
|
||||
const isCompact = isCompactEncodable((primitiveClasses as any)[primitiveName]);
|
||||
|
||||
@@ -438,8 +438,8 @@ function getSimilarTypes (imports: Imports, type: string): string[] {
|
||||
return ['any'];
|
||||
}
|
||||
|
||||
// @ts-ignore Cannot get isChildClass of abstract class, but it works
|
||||
if (isChildClass(AbstractInt, ClassOfUnsafe(type))) {
|
||||
// Cannot get isChildClass of abstract class, but it works
|
||||
if (isChildClass(AbstractInt as unknown as Constructor<any>, ClassOfUnsafe(type))) {
|
||||
possibleTypes.push('Uint8Array', 'number', 'string');
|
||||
} else if (isChildClass(Uint8Array, ClassOfUnsafe(type))) {
|
||||
possibleTypes.push('Uint8Array', 'string');
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
require('@babel/register')({
|
||||
extensions: ['.js', '.ts']
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user