Bump dev (w/ eslint 8) (#4070)

* Bump dev (w/ eslint 8)

* Additional linting

* Additional

* More lint fixes

* Last batch

* Additional

* Cleanups
This commit is contained in:
Jaco
2021-10-17 14:49:26 +03:00
committed by GitHub
parent 806fda67e9
commit 5eb3534d8e
46 changed files with 328 additions and 307 deletions
+4 -4
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Registry } from '@polkadot/types/types';
import type { AnyJson, Registry } from '@polkadot/types/types';
import fs from 'fs';
import path from 'path';
@@ -51,7 +51,7 @@ describe('Abi', (): void => {
it(`initializes from a contract ABI (${abiName})`, (): void => {
try {
const messageIds = (abi.V1 ? abi.V1 : abi).spec.messages.map(({ name }) => Array.isArray(name) ? name[0] : name);
const inkAbi = new Abi(abis[abiName]);
const inkAbi = new Abi(abis[abiName] as AnyJson);
expect(inkAbi.messages.map(({ identifier }) => identifier)).toEqual(messageIds);
} catch (error) {
@@ -66,7 +66,7 @@ describe('Abi', (): void => {
describe('TypeDef', (): void => {
Object.keys(abis).forEach((abiName) => {
it(`initializes from a contract ABI (${abiName})`, (): void => {
const abi = new Abi(abis[abiName]);
const abi = new Abi(abis[abiName] as AnyJson);
const json = stringifyJson(abi.registry);
const cmpPath = path.join(__dirname, `../../test/compare/${abiName}.test.json`);
@@ -88,7 +88,7 @@ describe('Abi', (): void => {
it('has the correct hash for the source', (): void => {
const bundle = abis.ink_v0_flipperBundle as JSONAbi;
const abi = new Abi(bundle as any);
const abi = new Abi(bundle as unknown as AnyJson);
// manual
expect(bundle.source.hash).toEqual(blake2AsHex(bundle.source.wasm));
+6 -6
View File
@@ -173,7 +173,7 @@ export class Abi {
throw error;
}
});
}
};
#createEvent = (spec: ContractEventSpec, index: number): AbiEvent => {
const args = this.#createArgs(spec.args, spec);
@@ -189,7 +189,7 @@ export class Abi {
};
return event;
}
};
#createMessage = (spec: ContractMessageSpec | ContractConstructorSpec, index: number, add: Partial<AbiMessage> = {}): AbiMessage => {
const args = this.#createArgs(spec.args, spec);
@@ -211,7 +211,7 @@ export class Abi {
};
return message;
}
};
#decodeArgs = (args: AbiParam[], data: Uint8Array): Codec[] => {
// for decoding we expect the input to be just the arg data, no selectors
@@ -225,7 +225,7 @@ export class Abi {
return value;
});
}
};
#decodeMessage = (type: 'constructor' | 'message', list: AbiMessage[], data: Uint8Array): DecodedMessage => {
const [, trimmed] = compactStripLength(data);
@@ -235,7 +235,7 @@ export class Abi {
assert(message, `Unable to find ${type} with selector ${u8aToHex(selector)}`);
return message.fromU8a(trimmed.subarray(4));
}
};
#encodeArgs = ({ name, selector }: ContractMessageSpec | ContractConstructorSpec, args: AbiParam[], data: unknown[]): Uint8Array => {
assert(data.length === args.length, () => `Expected ${args.length} arguments to contract message '${name.toString()}', found ${data.length}`);
@@ -248,5 +248,5 @@ export class Abi {
)
)
);
}
};
}
+1 -1
View File
@@ -66,5 +66,5 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
}
};
}
+5 -3
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AnyJson } from '@polkadot/types/types';
import fs from 'fs';
import path from 'path';
@@ -17,19 +19,19 @@ const v0wasmFlipper = fs.readFileSync(path.join(__dirname, '../../test/contracts
describe('Code', (): void => {
it('can construct with an individual ABI/WASM combo', (): void => {
expect(
() => new Code(mockApi, v0abiFlipper, v0wasmFlipper, decorateMethodPromise)
() => new Code(mockApi, v0abiFlipper as AnyJson, v0wasmFlipper, decorateMethodPromise)
).not.toThrow();
});
it('can construct with an .contract ABI (v0)', (): void => {
expect(
() => new Code(mockApi, v0contractFlipper, null, decorateMethodPromise)
() => new Code(mockApi, v0contractFlipper as AnyJson, null, decorateMethodPromise)
).not.toThrow();
});
it.only('can construct with an .contract ABI (v1)', (): void => {
expect(
() => new Code(mockApi, v1contractFlipper, null, decorateMethodPromise)
() => new Code(mockApi, v1contractFlipper as AnyJson, null, decorateMethodPromise)
).not.toThrow();
});
});
+1 -1
View File
@@ -76,5 +76,5 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
[])
) || []))
);
}
};
}
+3 -3
View File
@@ -100,7 +100,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
: this.api.consts.system.maximumBlockWeight as Weight
).muln(64).div(BN_HUNDRED)
: gasLimit;
}
};
#exec = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, value = BN_ZERO }: ContractOptions, params: unknown[]): SubmittableExtrinsic<ApiType> => {
return this.api.tx.contracts
@@ -126,7 +126,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
.filter((decoded): decoded is DecodedEvent => !!decoded)
))
);
}
};
#read = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, value = BN_ZERO }: ContractOptions, params: unknown[]): ContractCallSend<ApiType> => {
assert(this.hasRpcContractsCall, ERROR_NO_CALL);
@@ -159,5 +159,5 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
)
)
};
}
};
}
@@ -3,6 +3,8 @@
// Simple non-runnable checks to test type definitions in the editor itself
import type { AnyJson } from '@polkadot/types/types';
import { ApiPromise } from '@polkadot/api';
import { createTestPairs, TestKeyringMap } from '@polkadot/keyring/testingPairs';
@@ -10,7 +12,7 @@ import abiIncrementer from '../test/contracts/ink/incrementer.json';
import { BlueprintPromise, ContractPromise } from '.';
async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const blueprint = new BlueprintPromise(api, abiIncrementer, '0x1234');
const blueprint = new BlueprintPromise(api, abiIncrementer as AnyJson, '0x1234');
// new style
await blueprint.tx.new({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob);
@@ -21,7 +23,7 @@ async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<
}
async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const contract = new ContractPromise(api, abiIncrementer, '0x1234');
const contract = new ContractPromise(api, abiIncrementer as AnyJson, '0x1234');
// queries
await contract.query.get(pairs.alice.address, {});
@@ -48,7 +48,7 @@ export function stakerExposures (instanceId: string, api: ApiInterfaceRx): (acco
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
api.derive.staking.stakerExposures([accountId, withActive]).pipe(
api.derive.staking.stakerExposures([accountId], withActive).pipe(
map(([first]) => first)
)
);
+2 -2
View File
@@ -18,7 +18,7 @@ function wrapCache (keyStart: string, cache: DeriveCache): DeriveCache {
return {
del: (partial: string): void => cache.del(`${keyStart}${partial}`),
forEach: cache.forEach,
get: <T = any> (partial: string): T | undefined => {
get: <T> (partial: string): T | undefined => {
const key = `${keyStart}${partial}`;
const cached = cache.get<CacheValue<T>>(key);
@@ -40,7 +40,7 @@ function wrapCache (keyStart: string, cache: DeriveCache): DeriveCache {
function clearCache (cache: DeriveCache): void {
// clear all expired values
const now = Date.now();
const all: any[] = [];
const all: string[] = [];
cache.forEach((key: string, { x }: CacheValue<any>): void => {
((now - x) > CHACHE_EXPIRY) && all.push(key);
+1 -1
View File
@@ -21,5 +21,5 @@ export class ProposalFactory {
public proposalIndex = (index: number): ProposalIndex => {
return this.#registry.createType('ProposalIndex', index);
}
};
}
+6 -6
View File
@@ -441,7 +441,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
method.is(other);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction<ApiType>;
return this._decorateFunctionMeta(method as unknown as MetaDecoration, decorated as unknown as MetaDecoration) as unknown as SubmittableExtrinsicFunction<ApiType>;
}
protected _decorateStorage<ApiType extends ApiTypes> ({ query }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
@@ -479,7 +479,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// Disable this where it occurs for each field we are decorating
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
const decorated = this._decorateStorageCall(creator, decorateMethod);
const decorated: AugmentedQuery<'rxjs', GenericStorageEntryFunction, AnyTuple> & MetaDecoration = this._decorateStorageCall(creator, decorateMethod);
decorated.creator = creator;
@@ -551,7 +551,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
/* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
return this._decorateFunctionMeta(creator as unknown as MetaDecoration, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
private _decorateStorageEntryAt<ApiType extends ApiTypes> (registry: Registry, creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array): QueryableStorageEntryAt<ApiType> {
@@ -560,7 +560,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
// Disable this where it occurs for each field we are decorating
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
const decorated = decorateMethod((...args: unknown[]): Observable<Codec> =>
const decorated: AugmentedQuery<'rxjs', GenericStorageEntryFunction, AnyTuple> & MetaDecoration = decorateMethod((...args: unknown[]): Observable<Codec> =>
this._rpcCore.state.getStorage(getArgs(args), blockHash));
decorated.creator = creator;
@@ -598,7 +598,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
/* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
return this._decorateFunctionMeta(creator as unknown as MetaDecoration, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
// Decorate the base storage call. In the case or rxjs or promise-without-callback (await)
@@ -735,5 +735,5 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
*/
protected _rxDecorateMethod = <Method extends AnyFunction>(method: Method): Method => {
return method;
}
};
}
+1 -1
View File
@@ -8,7 +8,7 @@ import EventEmitter from 'eventemitter3';
export class Events {
#eventemitter = new EventEmitter();
protected emit (type: ApiInterfaceEvents, ...args: any[]): boolean {
protected emit (type: ApiInterfaceEvents, ...args: unknown[]): boolean {
return this.#eventemitter.emit(type, ...args);
}
+1 -1
View File
@@ -405,7 +405,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
this.emit('error', error);
}
}
};
#onProviderDisconnect = (): void => {
this._isConnected.next(false);
+4 -4
View File
@@ -6,13 +6,13 @@ import type { UnsubscribePromise } from '../types';
import { isFunction } from '@polkadot/util';
export type CombinatorCallback <T extends any[]> = Callback<T>;
export type CombinatorCallback <T extends unknown[]> = Callback<T>;
export interface CombinatorFunction {
(cb: Callback<any>): UnsubscribePromise;
}
export class Combinator<T extends any[] = any[]> {
export class Combinator<T extends unknown[] = unknown[]> {
#allHasFired = false;
#callback: CombinatorCallback<T>;
@@ -23,11 +23,11 @@ export class Combinator<T extends any[] = any[]> {
#isActive = true;
#results: any[] = [];
#results: unknown[] = [];
#subscriptions: UnsubscribePromise[] = [];
constructor (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>) {
constructor (fns: (CombinatorFunction | [CombinatorFunction, ...unknown[]])[], callback: CombinatorCallback<T>) {
this.#callback = callback;
// eslint-disable-next-line @typescript-eslint/require-await
+3 -3
View File
@@ -66,7 +66,7 @@ function decorateCall<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>
// encoding errors reject immediately, any result unsubscribes and resolves
const subscription: Subscription = method(...actualArgs).pipe(
catchError((error) => tracker.reject(error))
catchError((error: Error) => tracker.reject(error))
).subscribe((result): void => {
tracker.resolve(result);
setTimeout(() => subscription.unsubscribe(), 0);
@@ -82,7 +82,7 @@ function decorateSubscribe<Method extends DecorateFn<ObsInnerType<ReturnType<Met
// errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
const subscription: Subscription = method(...actualArgs).pipe(
catchError((error) => tracker.reject(error)),
catchError((error: Error) => tracker.reject(error)),
tap(() => tracker.resolve(() => subscription.unsubscribe()))
).subscribe((result): void => {
// queue result (back of queue to clear current)
@@ -255,7 +255,7 @@ export class ApiPromise extends ApiBase<'promise'> {
const tracker = promiseTracker(resolve, reject);
super.once('ready', () => tracker.resolve(this));
super.once('error', (e) => tracker.reject(e));
super.once('error', (error: Error) => tracker.reject(error));
});
}
+13 -13
View File
@@ -3,7 +3,7 @@
/* eslint-disable no-dupe-class-members */
import type { Observable } from 'rxjs';
import type { Observable, OperatorFunction } from 'rxjs';
import type { Address, ApplyExtrinsicResult, Call, Extrinsic, ExtrinsicEra, ExtrinsicStatus, Hash, Header, Index, RuntimeDispatchInfo } from '@polkadot/types/interfaces';
import type { Callback, Codec, Constructor, IKeyringPair, ISubmittableResult, Registry, SignatureOptions } from '@polkadot/types/types';
import type { ApiInterfaceRx, ApiTypes, SignerResult } from '../types';
@@ -123,7 +123,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
return decorateMethod(
(): Observable<this> =>
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this))
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this) as OperatorFunction<number | undefined, this>)
)();
}
@@ -181,7 +181,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
}),
nonce
});
}
};
#makeSignOptions = (options: Partial<SignerOptions>, extras: { blockHash?: Hash; era?: ExtrinsicEra; nonce?: Index }): SignatureOptions => {
return {
@@ -193,7 +193,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
signedExtensions: api.registry.signedExtensions,
version: api.extrinsicType
} as SignatureOptions;
}
};
#makeSignAndSendOptions = (optionsOrStatus?: Partial<SignerOptions> | Callback<ISubmittableResult>, statusCb?: Callback<ISubmittableResult>): [Partial<SignerOptions>, Callback<ISubmittableResult>?] => {
let options: Partial<SignerOptions> = {};
@@ -205,7 +205,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
}
return [options, statusCb];
}
};
#observeSign = (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): Observable<number | undefined> => {
const address = isKeyringPair(account) ? account.address : account.toString();
@@ -223,9 +223,9 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
updateId = await this.#signViaSigner(address, eraOptions, signingInfo.header);
}
}),
mapTo(updateId)
mapTo(updateId) as OperatorFunction<void, number | undefined>
);
}
};
#observeStatus = (hash: Hash, status: ExtrinsicStatus): Observable<ISubmittableResult> => {
if (!status.isFinalized && !status.isInBlock) {
@@ -247,7 +247,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
of(this.#transformResult(new SubmittableResult({ internalError, status })))
)
);
}
};
#observeSend = (updateId = -1): Observable<Hash> => {
return api.rpc.author.submitExtrinsic(this).pipe(
@@ -255,7 +255,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
this.#updateSigner(updateId, hash);
})
);
}
};
#observeSubscribe = (updateId = -1): Observable<ISubmittableResult> => {
const hash = this.hash;
@@ -268,7 +268,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
this.#updateSigner(updateId, status);
})
);
}
};
// NOTE here we actually override nonce if it was specified (backwards compat for
// the previous signature - don't let user space break, but allow then time to upgrade)
@@ -276,7 +276,7 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
return isBn(optionsOrNonce) || isNumber(optionsOrNonce)
? { nonce: optionsOrNonce }
: optionsOrNonce;
}
};
#signViaSigner = async (address: Address | string | Uint8Array, options: SignatureOptions, header: Header | null): Promise<number> => {
const signer = options.signer || api.signer;
@@ -305,13 +305,13 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
super.addSignature(address, result.signature, payload.toPayload());
return result.id;
}
};
#updateSigner = (updateId: number, status: Hash | ISubmittableResult): void => {
if ((updateId !== -1) && api.signer && api.signer.update) {
api.signer.update(updateId, status);
}
}
};
}
return Submittable;
+1 -3
View File
@@ -45,9 +45,7 @@ type RawResult = [
AccountInfo
];
type EQDeriveBalancesQuery = (
address: AccountIndex | AccountId | Address | string
) => Observable<EQDeriveBalancesAll>;
type EQDeriveBalancesQuery = (address: AccountIndex | AccountId | Address | string) => Observable<EQDeriveBalancesAll>;
const typesBundle = {
spec: {
+3 -3
View File
@@ -225,7 +225,7 @@ export class RpcCore {
observer.next(value);
observer.complete();
})
.catch((error): void => {
.catch((error: Error): void => {
logErrorMessage(method, def, error);
observer.error(error);
@@ -255,7 +255,7 @@ export class RpcCore {
this.provider
.subscribe(subType, subName, paramsJson, update)
.then(resolve)
.catch((error): void => {
.catch((error: Error): void => {
errorHandler(error);
reject(error);
});
@@ -283,7 +283,7 @@ export class RpcCore {
try {
const params = this._formatInputs(registry, null, def, values);
const paramsJson = params.map((param): AnyJson => param.toJSON());
const paramsJson = params.map((param) => param.toJSON());
const update = (error?: Error | null, result?: T): void => {
if (error) {
+4 -3
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ProviderInterface } from '@polkadot/rpc-provider/types';
import { MockProvider } from '@polkadot/rpc-provider/mock';
import { TypeRegistry } from '@polkadot/types/create';
import { isFunction } from '@polkadot/util';
@@ -12,7 +14,7 @@ describe('Api', (): void => {
it('requires a provider with a send method', (): void => {
expect(
() => new RpcCore('234', registry, {} as any)
() => new RpcCore('234', registry, {} as unknown as ProviderInterface)
).toThrow(/Expected Provider/);
});
@@ -28,8 +30,7 @@ describe('Api', (): void => {
}
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
expect(isFunction((rpc as any).testing.foo)).toBe(true);
expect(isFunction((rpc as unknown as Record<string, Record<string, boolean>>).testing.foo)).toBe(true);
expect(rpc.sections.includes('testing')).toBe(true);
expect(rpc.mapping.get('testing_foo')).toEqual({
description: 'foo',
+6 -5
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ProviderInterface } from '@polkadot/rpc-provider/types';
import type { DefinitionRpc } from '@polkadot/types/types';
import { TypeRegistry } from '@polkadot/types/create';
@@ -11,7 +12,7 @@ describe('methodSend', (): void => {
const registry = new TypeRegistry();
let rpc: RpcCore;
let methods: Record<string, DefinitionRpc>;
let provider: any;
let provider: ProviderInterface;
beforeEach((): void => {
methods = {
@@ -30,10 +31,10 @@ describe('methodSend', (): void => {
};
provider = {
send: jest.fn((method, params: any[]): Promise<any> => {
return Promise.resolve(params[0]);
})
};
send: jest.fn((method: string, params: unknown[]): Promise<unknown> =>
Promise.resolve(params[0])
)
} as unknown as ProviderInterface;
rpc = new RpcCore('987', registry, provider);
});
+5 -4
View File
@@ -10,18 +10,19 @@ import { memoize } from '@polkadot/util';
import { drr } from './drr';
type ObsFn <T> = (...params: any[]) => Observable<T>;
type ObsFn <T> = (...params: unknown[]) => Observable<T>;
// Wraps a derive, doing 2 things to optimize calls -
// 1. creates a memo of the inner fn -> Observable, removing when unsubscribed
// 2. wraps the observable in a drr() (which includes an unsub delay)
/** @internal */
export function memo <T> (instanceId: string, inner: ObsFn<T>): Memoized<ObsFn<T>> {
// eslint-disable-next-line @typescript-eslint/ban-types
export function memo <T> (instanceId: string, inner: Function): Memoized<ObsFn<T>> {
const options = { getInstanceId: () => instanceId };
const cached = memoize(
(...params: any[]): Observable<T> =>
(...params: unknown[]): Observable<T> =>
new Observable((observer: Observer<T>): TeardownLogic => {
const subscription = inner(...params).subscribe(observer);
const subscription = (inner as ObsFn<T>)(...params).subscribe(observer);
return (): void => {
cached.unmemoize(...params);
@@ -12,7 +12,7 @@ describe('encodeJson', (): void => {
it('encodes a valid JsonRPC JSON string', (): void => {
expect(
coder.encodeJson('method', 'params')
).toEqual('{"id":1,"jsonrpc":"2.0","method":"method","params":"params"}');
coder.encodeJson('method', ['params'])
).toEqual('{"id":1,"jsonrpc":"2.0","method":"method","params":["params"]}');
});
});
+1 -1
View File
@@ -46,7 +46,7 @@ export class RpcCoder {
return response.result;
}
public encodeJson (method: string, params: any | any[]): string {
public encodeJson (method: string, params: unknown[]): string {
return stringify(
this.encodeObject(method, params)
);
+3 -4
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '../types';
import type { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '../types';
import { assert, logger } from '@polkadot/util';
import { fetch } from '@polkadot/x-fetch';
@@ -103,7 +103,7 @@ export class HttpProvider implements ProviderInterface {
/**
* @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
*/
public async send <T = any> (method: string, params: unknown[]): Promise<T> {
public async send <T> (method: string, params: unknown[]): Promise<T> {
const body = this.#coder.encodeJson(method, params);
const response = await fetch(this.#endpoint, {
body,
@@ -118,8 +118,7 @@ export class HttpProvider implements ProviderInterface {
assert(response.ok, () => `[${response.status}]: ${response.statusText}`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const result = await response.json();
const result = (await response.json()) as JsonRpcResponse;
return this.#coder.decodeResponse(result) as T;
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Request } from '../../test/mockWs';
import { mockWs } from '../../test/mockWs';
import { Mock } from './../mock/types';
import { WsProvider } from './';
@@ -10,7 +12,7 @@ const TEST_WS_URL = 'ws://localhost-index.spec.ts:9977';
let provider: WsProvider | null;
let mock: Mock;
function createWs (requests: any[], autoConnect = 1000, headers?: Record<string, string>): WsProvider {
function createWs (requests: Request[], autoConnect = 1000, headers?: Record<string, string>): WsProvider {
mock = mockWs(requests, TEST_WS_URL);
provider = new WsProvider(TEST_WS_URL, autoConnect, headers);
+8 -8
View File
@@ -337,7 +337,7 @@ export class WsProvider implements ProviderInterface {
#emit = (type: ProviderInterfaceEmitted, ...args: unknown[]): void => {
this.#eventemitter.emit(type, ...args);
}
};
#onSocketClose = (event: CloseEvent): void => {
const error = new Error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`);
@@ -369,12 +369,12 @@ export class WsProvider implements ProviderInterface {
});
}, this.#autoConnectMs);
}
}
};
#onSocketError = (error: Event): void => {
l.debug(() => ['socket error', error]);
this.#emit('error', error);
}
};
#onSocketMessage = (message: MessageEvent<string>): void => {
l.debug(() => ['received', message.data]);
@@ -384,7 +384,7 @@ export class WsProvider implements ProviderInterface {
return isUndefined(response.method)
? this.#onSocketMessageResult(response)
: this.#onSocketMessageSubscribe(response);
}
};
#onSocketMessageResult = (response: JsonRpcResponse): void => {
const handler = this.#handlers[response.id];
@@ -422,7 +422,7 @@ export class WsProvider implements ProviderInterface {
}
delete this.#handlers[response.id];
}
};
#onSocketMessageSubscribe = (response: JsonRpcResponse): void => {
const method = ALIASES[response.method as string] || response.method || 'invalid';
@@ -448,7 +448,7 @@ export class WsProvider implements ProviderInterface {
} catch (error) {
handler.callback(error as Error, undefined);
}
}
};
#onSocketOpen = (): boolean => {
assert(!isNull(this.#websocket), 'WebSocket cannot be null in onOpen');
@@ -461,7 +461,7 @@ export class WsProvider implements ProviderInterface {
this.#resubscribe();
return true;
}
};
#resubscribe = (): void => {
const subscriptions = this.#subscriptions;
@@ -484,5 +484,5 @@ export class WsProvider implements ProviderInterface {
l.error(error);
}
})).catch(l.error);
}
};
}
+4 -2
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '@polkadot/types/types';
import type { Request } from '../../test/mockWs';
import { mockWs } from '../../test/mockWs';
import { Global, Mock } from './../mock/types';
@@ -14,7 +15,7 @@ const TEST_WS_URL = 'ws://localhost-send.spec.ts:9965';
let provider: WsProvider | null;
let mock: Mock;
function createMock (requests: any[]): void {
function createMock (requests: Request[]): void {
mock = mockWs(requests, TEST_WS_URL);
}
@@ -89,7 +90,8 @@ describe('send', (): void => {
code: 666,
message: 'error'
},
id: 1
id: 1,
method: 'something'
}]);
return createWs().then((ws) =>
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '@polkadot/types/types';
import type { Request } from '../../test/mockWs';
import { mockWs } from '../../test/mockWs';
import { Global, Mock } from './../mock/types';
@@ -14,7 +15,7 @@ const TEST_WS_URL = 'ws://localhost-subscribe.test.ts:9933';
let provider: WsProvider | null;
let mock: Mock;
function createMock (requests: any[]): void {
function createMock (requests: Request[]): void {
mock = mockWs(requests, TEST_WS_URL);
}
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '@polkadot/types/types';
import type { Request } from '../../test/mockWs';
import { mockWs } from '../../test/mockWs';
import { Global, Mock } from './../mock/types';
@@ -14,7 +15,7 @@ const TEST_WS_URL = 'ws://localhost-unsubscribe.test.ts:9933';
let provider: WsProvider | null;
let mock: Mock;
function createMock (requests: any): void {
function createMock (requests: Request[]): void {
mock = mockWs(requests, TEST_WS_URL);
}
+20 -13
View File
@@ -6,7 +6,7 @@ import { Server, WebSocket } from 'mock-socket';
import { stringify } from '@polkadot/util';
interface Scope {
body: { [index: string]: Record<string, any> };
body: { [index: string]: Record<string, unknown> };
requests: number;
server: Server;
done: any;
@@ -27,12 +27,22 @@ interface ReplyDef {
};
}
interface RpcBase {
id: number;
jsonrpc: '2.0';
}
type RpcError = RpcBase & ErrorDef;
type RpcReply = RpcBase & { result: unknown };
export type Request = { method: string } & (ErrorDef | ReplyDef);
global.WebSocket = WebSocket as typeof global.WebSocket;
export const TEST_WS_URL = 'ws://localhost:9955';
// should be JSONRPC def return
function createError ({ error: { code, message }, id }: ErrorDef): any {
function createError ({ error: { code, message }, id }: ErrorDef): RpcError {
return {
error: {
code,
@@ -44,7 +54,7 @@ function createError ({ error: { code, message }, id }: ErrorDef): any {
}
// should be JSONRPC def return
function createReply ({ id, reply: { result } }: ReplyDef): any {
function createReply ({ id, reply: { result } }: ReplyDef): RpcReply {
return {
id,
jsonrpc: '2.0',
@@ -53,7 +63,7 @@ function createReply ({ id, reply: { result } }: ReplyDef): any {
}
// scope definition returned
export function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope {
export function mockWs (requests: Request[], wsUrl: string = TEST_WS_URL): Scope {
const server = new Server(wsUrl);
let requestCount = 0;
@@ -69,16 +79,13 @@ export function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: stri
};
server.on('connection', (socket): void => {
// FIXME This whole any mess is a mess
socket.on('message', (body: any): void => {
const request: any = requests[requestCount];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
const response: any = request.error
? createError(request)
: createReply(request);
socket.on('message', (body): void => {
const request = requests[requestCount];
const response = (request as ErrorDef).error
? createError(request as ErrorDef)
: createReply(request as ReplyDef);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
scope.body[request.method] = body;
scope.body[request.method] = body as unknown as Record<string, unknown>;
requestCount++;
socket.send(stringify(response));
+5 -6
View File
@@ -71,7 +71,7 @@ export function main (): void {
process.exit(1);
};
websocket.onerror = (event: any): void => {
websocket.onerror = (event: unknown): void => {
console.error(event);
process.exit(1);
};
@@ -81,15 +81,14 @@ export function main (): void {
websocket.send('{"id":"1","jsonrpc":"2.0","method":"state_getMetadata","params":[]}');
};
websocket.onmessage = (message: any): void => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
generate(JSON.parse(message.data).result, pkg, output, isStrict);
websocket.onmessage = (message: unknown): void => {
generate((JSON.parse((message as Record<string, string>).data) as Record<string, string>).result, pkg, output, isStrict);
};
} catch (error) {
process.exit(1);
}
} else {
// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-member-access
generate(require(path.join(process.cwd(), endpoint)).result, pkg, output, isStrict);
// eslint-disable-next-line @typescript-eslint/no-var-requires
generate((require(path.join(process.cwd(), endpoint)) as Record<string, string>).result, pkg, output, isStrict);
}
}
+2 -2
View File
@@ -64,9 +64,9 @@ const mockEnumSetObj = [
describe('BTreeSet', (): void => {
describe('decoding', (): void => {
const testDecode = (type: string, input: any, output: string): void =>
const testDecode = (type: string, input: unknown, output: string): void =>
it(`can decode from ${type}`, (): void => {
const s = new BTreeSet(registry, U32, input);
const s = new BTreeSet(registry, U32, input as string);
expect(s.toString()).toBe(output);
});
+2 -2
View File
@@ -31,9 +31,9 @@ const mockU32U32MapUint8Array = Uint8Array.from([16, 4, 49, 2, 0, 0, 0, 8, 50, 5
describe('CodecMap', (): void => {
describe('decoding', (): void => {
const testDecode = (type: string, input: any, output: string): void =>
const testDecode = (type: string, input: unknown, output: string): void =>
it(`can decode from ${type}`, (): void => {
const s = new CodecMap(registry, Text, U32, input);
const s = new CodecMap(registry, Text, U32, input as string);
expect(s.toString()).toBe(output);
});
+2 -2
View File
@@ -36,7 +36,7 @@ function decodeMapFromU8a<K extends Codec, V extends Codec> (registry: Registry,
function decodeMapFromMap<K extends Codec, V extends Codec> (registry: Registry, KeyClass: Constructor<K>, ValClass: Constructor<V>, value: Map<any, any>): Map<K, V> {
const output = new Map<K, V>();
value.forEach((val: any, key: any) => {
value.forEach((val: unknown, key: unknown) => {
const isComplex = KeyClass.prototype instanceof AbstractArray ||
KeyClass.prototype instanceof Struct ||
KeyClass.prototype instanceof Enum;
@@ -45,7 +45,7 @@ function decodeMapFromMap<K extends Codec, V extends Codec> (registry: Registry,
output.set(
key instanceof KeyClass
? key
: new KeyClass(registry, isComplex ? JSON.parse(key) : key),
: new KeyClass(registry, isComplex ? JSON.parse(key as string) : key),
val instanceof ValClass
? val
: new ValClass(registry, val)
+3 -3
View File
@@ -1,21 +1,21 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { CodecTo } from '../types';
import type { AnyU8a, CodecTo } from '../types';
import { TypeRegistry } from '../create';
import { Raw } from '.';
const registry = new TypeRegistry();
const testDecode = (type: string, input: any, expected: string): void =>
const testDecode = (type: string, input: AnyU8a, expected: string): void =>
it(`can decode from ${type}`, (): void => {
const e = new Raw(registry, input);
expect(e.toString()).toBe(expected);
});
const testEncode = (to: CodecTo, expected: any): void =>
const testEncode = (to: CodecTo, expected: AnyU8a): void =>
it(`can encode ${to}`, (): void => {
const e = new Raw(registry, [1, 2, 3, 4, 5]);
+1 -1
View File
@@ -85,7 +85,7 @@ export class Raw extends Uint8Array implements IU8a {
!this.some((value, index) => value !== other[index]);
}
return this.eq(u8aToU8a(other as any));
return this.eq(u8aToU8a(other as string));
}
/**
+1 -1
View File
@@ -156,7 +156,7 @@ export class CodecSet extends Set<string> implements ISet<string> {
super.add(key);
return this;
}
};
/**
* @description Compares the value of the input to see if there is a match
+2 -1
View File
@@ -4,6 +4,7 @@
import type { VoteThreshold } from '../interfaces/elections';
import type { BlockNumber } from '../interfaces/runtime';
import type { CodecTo } from '../types';
import type { AnyTupleValue } from './Tuple';
import rpcMetadata from '@polkadot/types-support/metadata/static-substrate';
@@ -25,7 +26,7 @@ describe('Tuple', (): void => {
});
describe('decoding', (): void => {
const testDecode = (type: string, input: any): void =>
const testDecode = (type: string, input: AnyTupleValue): void =>
it(`can decode from ${type}`, (): void => {
const t = new Tuple(registry, [
Text,
+4 -4
View File
@@ -8,7 +8,7 @@ import { isFunction, isHex, isString, isU8a, stringify, u8aConcat, u8aToU8a } fr
import { AbstractArray } from './AbstractArray';
import { decodeU8a, mapToTypeMap, typeToConstructor } from './utils';
type AnyTuple = AnyU8a | string | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[];
export type AnyTupleValue = AnyU8a | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[];
type TupleConstructors = Constructor[] | {
[index: string]: Constructor;
@@ -21,7 +21,7 @@ type TupleTypes = TupleType[] | {
};
/** @internal */
function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: AnyTuple): Codec[] {
function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: AnyTupleValue): Codec[] {
if (isU8a(value) || isHex(value)) {
return decodeU8a(registry, u8aToU8a(value), _Types);
}
@@ -54,7 +54,7 @@ function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: Any
export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
private _Types: TupleConstructors;
constructor (registry: Registry, Types: TupleTypes | TupleType, value?: AnyTuple) {
constructor (registry: Registry, Types: TupleTypes | TupleType, value?: AnyTupleValue) {
const Clazzes = Array.isArray(Types)
? Types.map((t) => typeToConstructor(registry, t))
: isFunction(Types) || isString(Types)
@@ -68,7 +68,7 @@ export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
public static with (Types: TupleTypes | TupleType): Constructor<Tuple> {
return class extends Tuple {
constructor (registry: Registry, value?: AnyTuple) {
constructor (registry: Registry, value?: AnyTupleValue) {
super(registry, Types, value);
}
};
+7 -6
View File
@@ -13,22 +13,23 @@ function hasMismatch (a?: unknown, b?: unknown): boolean {
);
}
function notEntry (value: any): boolean {
function notEntry (value: unknown): boolean {
return !Array.isArray(value) || value.length !== 2;
}
function compareMapArray (a: Map<any, any>, b: [any, any][]): boolean {
function compareMapArray (a: Map<unknown, unknown>, b: [unknown, unknown][]): boolean {
// equal number of entries and each entry in the array should match
return (a.size === b.length) && !b.some((entry): boolean =>
notEntry(entry) || hasMismatch(a.get(entry[0]), entry[1])
return (a.size === b.length) && !b.some((entry) =>
notEntry(entry) ||
hasMismatch(a.get(entry[0]), entry[1])
);
}
// NOTE These are used internally and when comparing objects, expects that
// when the second is an Map<string, Codec> that the first has to be as well
export function compareMap (a: Map<any, any>, b?: unknown): boolean {
export function compareMap (a: Map<unknown, unknown>, b?: unknown): boolean {
if (Array.isArray(b)) {
return compareMapArray(a, b);
return compareMapArray(a, b as [unknown, unknown][]);
} else if (b instanceof Map) {
return compareMapArray(a, [...b.entries()]);
} else if (isObject(b)) {
+3 -4
View File
@@ -88,14 +88,13 @@ function _decodeSet (value: TypeDef, details: Record<string, number>): TypeDef {
// decode a struct, set or enum
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function _decodeStruct (value: TypeDef, type: string, _: string, count: number): TypeDef {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsed: Record<string, any> = JSON.parse(type);
const parsed = JSON.parse(type) as Record<string, unknown> & { _alias: string };
const keys = Object.keys(parsed);
if (keys.length === 1 && keys[0] === '_enum') {
return _decodeEnum(value, parsed[keys[0]], count);
return _decodeEnum(value, parsed[keys[0]] as string[], count);
} else if (keys.length === 1 && keys[0] === '_set') {
return _decodeSet(value, parsed[keys[0]]);
return _decodeSet(value, parsed[keys[0]] as Record<string, number>);
}
value.alias = parsed._alias
+11 -3
View File
@@ -4,6 +4,8 @@
/* eslint-disable sort-keys */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import type { BlockValue } from './Block';
import block00300 from '@polkadot/types-support/json/SignedBlock.003.00.json';
import metadataStatic from '@polkadot/types-support/metadata/static-substrate';
@@ -11,6 +13,12 @@ import { TypeRegistry } from '../create';
import { Metadata } from '../metadata';
import { GenericBlock as Block } from './Block';
interface BlockJson {
result: {
block: BlockValue;
};
}
const registry = new TypeRegistry();
const metadata = new Metadata(registry, metadataStatic);
@@ -30,9 +38,9 @@ describe('Block', (): void => {
});
it('re-encodes digest items correctly', (): void => {
const digest = new Block(registry, block00300.result.block).header.digest;
const digest = new Block(registry, (block00300 as BlockJson).result.block).header.digest;
expect(digest.logs[0].toHex()).toEqual(block00300.result.block.header.digest.logs[0]);
expect(digest.logs[1].toHex()).toEqual(block00300.result.block.header.digest.logs[1]);
expect(digest.logs[0].toHex()).toEqual((block00300 as BlockJson).result.block.header?.digest?.logs[0]);
expect(digest.logs[1].toHex()).toEqual((block00300 as BlockJson).result.block.header?.digest?.logs[1]);
});
});
@@ -65,7 +65,7 @@ export class MetadataVersioned extends Struct {
*/
#metadata = (): MetadataAll => {
return this.get('metadata') as MetadataAll;
}
};
/**
* @description Returns the wrapped metadata as a limited calls-only (latest) version
+2 -2
View File
@@ -76,7 +76,7 @@ export type __ToTuple<O extends Codec[]> =
: O[0]
: Null;
export type __CodecFirst<K extends unknown> =
export type __CodecFirst<K> =
K extends keyof InterfaceTypes
? InterfaceTypes[K]
: K extends unknown[]
@@ -85,7 +85,7 @@ export type __CodecFirst<K extends unknown> =
? __ToStruct<K>
: Codec;
export type __CodecsNext<K extends unknown, C extends Codec[]> =
export type __CodecsNext<K, C extends Codec[]> =
K extends __WrapOne
? C extends [Codec, ...infer X]
? [__MapWrapOne<C[0]>[K], ...X]