diff --git a/docs/examples/promise/03_listen_to_balance_change/index.js b/docs/examples/promise/03_listen_to_balance_change/index.js index 2d177875f9..2cac33d4b9 100755 --- a/docs/examples/promise/03_listen_to_balance_change/index.js +++ b/docs/examples/promise/03_listen_to_balance_change/index.js @@ -1,6 +1,7 @@ /* eslint-disable header/header */ /* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/unbound-method */ +/* eslint-disable @typescript-eslint/no-floating-promises */ // Import the API const { ApiPromise } = require('@polkadot/api'); diff --git a/docs/examples/promise/03_listen_to_multiple_balances_change/index.js b/docs/examples/promise/03_listen_to_multiple_balances_change/index.js index f91c1294ec..07e7716c8c 100755 --- a/docs/examples/promise/03_listen_to_multiple_balances_change/index.js +++ b/docs/examples/promise/03_listen_to_multiple_balances_change/index.js @@ -1,6 +1,7 @@ /* eslint-disable header/header */ /* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/unbound-method */ +/* eslint-disable @typescript-eslint/no-floating-promises */ // Import the API const { ApiPromise } = require('@polkadot/api'); diff --git a/docs/examples/promise/08_system_events/index.js b/docs/examples/promise/08_system_events/index.js index 76634ec999..0f50c176ed 100755 --- a/docs/examples/promise/08_system_events/index.js +++ b/docs/examples/promise/08_system_events/index.js @@ -1,6 +1,7 @@ /* eslint-disable header/header */ /* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/unbound-method */ +/* eslint-disable @typescript-eslint/no-floating-promises */ // Import the API const { ApiPromise } = require('@polkadot/api'); diff --git a/docs/examples/promise/09_transfer_events/index.js b/docs/examples/promise/09_transfer_events/index.js index b9aff5c52d..9d727ddf61 100755 --- a/docs/examples/promise/09_transfer_events/index.js +++ b/docs/examples/promise/09_transfer_events/index.js @@ -1,6 +1,7 @@ /* eslint-disable header/header */ /* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-disable @typescript-eslint/no-floating-promises */ // Import the API & Provider and some utility functions const { ApiPromise } = require('@polkadot/api'); diff --git a/docs/examples/promise/10_upgrade_chain/index.js b/docs/examples/promise/10_upgrade_chain/index.js index 97173bc29d..d463f575a1 100755 --- a/docs/examples/promise/10_upgrade_chain/index.js +++ b/docs/examples/promise/10_upgrade_chain/index.js @@ -1,6 +1,7 @@ /* eslint-disable header/header */ /* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/unbound-method */ +/* eslint-disable @typescript-eslint/no-floating-promises */ // Import the API & Provider and some utility functions const { ApiPromise, WsProvider } = require('@polkadot/api'); diff --git a/package.json b/package.json index 897737c3ee..aa4d9c671a 100644 --- a/package.json +++ b/package.json @@ -27,8 +27,8 @@ "@babel/core": "^7.9.6", "@babel/register": "^7.9.0", "@babel/runtime": "^7.9.6", - "@polkadot/dev": "^0.53.5", - "@polkadot/ts": "^0.3.22", + "@polkadot/dev": "^0.54.1", + "@polkadot/ts": "^0.3.23", "@polkadot/typegen": "workspace:packages/typegen", "@types/jest": "^25.2.3", "@vuepress/plugin-search": "^1.5.0", diff --git a/packages/api-contract/src/ContractRegistry.ts b/packages/api-contract/src/ContractRegistry.ts index fad7526768..db13e9494b 100644 --- a/packages/api-contract/src/ContractRegistry.ts +++ b/packages/api-contract/src/ContractRegistry.ts @@ -19,7 +19,7 @@ function parseSelector (registry: Registry, fnname: string, input: ContractABIMe return registry.createType('u32', hexToU8a(input)); } else if (typeof input === 'string') { try { - const array = JSON.parse(input); + const array = JSON.parse(input) as unknown[]; assert(array.length === 4, `${fnname}: Invalid selector length`); @@ -108,7 +108,7 @@ export default class ContractRegistry extends MetaRegistry { public createMessage (name: string, message: Partial & ContractABIMessageBase): ContractABIFn { const args = message.args.map(({ name, type }): ContractABIFnArg => { - assert(isObject(type), `Invalid type at index ${type}`); + assert(isObject(type), `Invalid type at index ${type.toString()}`); return { name: stringCamelCase(name), @@ -183,6 +183,7 @@ export default class ContractRegistry extends MetaRegistry { public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage { return { ...message, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment args: this.convertArgs(args), name: this._stringAt(name), returnType: returnType ? this.convertType(returnType) : null @@ -191,6 +192,7 @@ export default class ContractRegistry extends MetaRegistry { public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent { return { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment args: this.convertArgs(args) }; } diff --git a/packages/api-contract/src/MetaRegistry.ts b/packages/api-contract/src/MetaRegistry.ts index 693207351a..c8eb188818 100644 --- a/packages/api-contract/src/MetaRegistry.ts +++ b/packages/api-contract/src/MetaRegistry.ts @@ -7,11 +7,11 @@ import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, Met import { assert } from '@polkadot/util'; import { displayType, withTypeString } from '@polkadot/types'; -const builtinMap: [(id: any) => boolean, MetaTypeInfo][] = [ - [(id: any): boolean => typeof id === 'string', MetaTypeInfo.BuiltinPlain], - [(id: any): boolean => Array.isArray(id), MetaTypeInfo.BuiltinTuple], - [(id: any): boolean => !!(id['array.type']), MetaTypeInfo.BuiltinVecFixed], - [(id: any): boolean => !!(id['slice.type']), MetaTypeInfo.BuiltinVec] +const builtinMap: [(id: unknown | unknown[] | { 'array.type': unknown } | { 'slice.type': unknown }) => boolean, MetaTypeInfo][] = [ + [(id: any) => typeof id === 'string', MetaTypeInfo.BuiltinPlain], + [(id: any) => Array.isArray(id), MetaTypeInfo.BuiltinTuple], + [(id: any) => !!((id as { 'array.type': unknown })['array.type']), MetaTypeInfo.BuiltinVecFixed], + [(id: any) => !!((id as { 'slice.type': unknown })['slice.type']), MetaTypeInfo.BuiltinVec] ]; const typeMap: [string, MetaTypeInfo][] = [ @@ -25,8 +25,8 @@ function detectedType ({ def, id }: MetaType): MetaTypeInfo { assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found'); const lookup = def === 'builtin' - ? builtinMap.find(([test]): boolean => test(id)) - : typeMap.find(([test]): boolean => !!(def as any)[test]); + ? builtinMap.find(([test]) => test(id)) + : typeMap.find(([test]) => !!(def as unknown as Record)[test]); return lookup ? lookup[1] @@ -59,7 +59,7 @@ class MetadataRegistryLookup { } } - protected _itemAt (index: number, variant: MetaRegistryItem): any { + protected _itemAt (index: number, variant: MetaRegistryItem): string | MetaType | TypeDef { assert(this._hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`); switch (variant) { @@ -72,24 +72,24 @@ class MetadataRegistryLookup { } } - protected _itemsAt (indices: number[], variant: MetaRegistryItem): any[] { - return indices.map((index: number): string => this._itemAt(index, variant)); + protected _itemsAt (indices: number[], variant: MetaRegistryItem): (string | MetaType | TypeDef)[] { + return indices.map((index: number) => this._itemAt(index, variant)); } protected _stringAt (index: StringIndex): string { - return this._itemAt(index, MetaRegistryItem.String); + return this._itemAt(index, MetaRegistryItem.String) as string; } public stringsAt (indices: StringIndex[]): string[] { - return this._itemsAt(indices, MetaRegistryItem.String); + return this._itemsAt(indices, MetaRegistryItem.String) as string[]; } public typeAt (index: TypeIndex): MetaType { - return this._itemAt(index, MetaRegistryItem.Type); + return this._itemAt(index, MetaRegistryItem.Type) as MetaType; } public typesAt (indices: TypeIndex[]): MetaType[] { - return this._itemsAt(indices, MetaRegistryItem.Type); + return this._itemsAt(indices, MetaRegistryItem.Type) as MetaType[]; } public hasTypeDefAt (index: TypeIndex): boolean { @@ -98,7 +98,7 @@ class MetadataRegistryLookup { public typeDefAt (index: TypeIndex, extra: Pick = {}): TypeDef { return { - ...this._itemAt(index, MetaRegistryItem.TypeDef), + ...this._itemAt(index, MetaRegistryItem.TypeDef) as TypeDef, ...extra }; } @@ -136,7 +136,7 @@ export default class MetaRegistry extends MetadataRegistryLookup { }; } - private _typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick { + private _typeDefDefFields (metaType: MetaType, typeIndex: TypeIndex = -1): Pick { let typeDef; switch (detectedType(metaType)) { @@ -234,7 +234,7 @@ export default class MetaRegistry extends MetadataRegistryLookup { }; } - private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick { + private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex: TypeIndex = -1): Pick { const { 'slice.type': vecTypeIndex } = id; assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`); @@ -250,7 +250,7 @@ export default class MetaRegistry extends MetadataRegistryLookup { }; } - private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick { + private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex: TypeIndex = -1): Pick { const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id; assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; ], where length <= 256'); @@ -301,7 +301,7 @@ export default class MetaRegistry extends MetadataRegistryLookup { }; } - public typeDefForOption (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick { + public typeDefForOption (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick { assert(id['custom.params'] && id['custom.params'][0], `Invalid Option type defined at index ${typeIndex}`); return { @@ -310,7 +310,7 @@ export default class MetaRegistry extends MetadataRegistryLookup { }; } - public typeDefForResult (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick { + public typeDefForResult (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick { assert(id['custom.params'] && id['custom.params'][0] && id['custom.params'][1], `Invalid Result type defined at index ${typeIndex}`); return { diff --git a/packages/api-contract/src/base/Blueprint.ts b/packages/api-contract/src/base/Blueprint.ts index e83e021eae..89d6e99ad7 100644 --- a/packages/api-contract/src/base/Blueprint.ts +++ b/packages/api-contract/src/base/Blueprint.ts @@ -47,6 +47,7 @@ export default class Blueprint extends BaseWithTx => { return this._apiContracts diff --git a/packages/api-contract/src/base/Code.ts b/packages/api-contract/src/base/Code.ts index c4b531953b..7bc7afb581 100644 --- a/packages/api-contract/src/base/Code.ts +++ b/packages/api-contract/src/base/Code.ts @@ -19,7 +19,6 @@ import { BaseWithTx } from './util'; type CodePutCodeResultSubscription = Observable>; -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface CodePutCode { signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription; } @@ -46,6 +45,7 @@ export default class Code extends BaseWithTx public createBlueprint = (maxGas: number | BN): CodePutCode => { return { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment signAndSend: this.decorateMethod( (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription => this._apiContracts diff --git a/packages/api-contract/src/base/Contract.ts b/packages/api-contract/src/base/Contract.ts index 8f2a34373f..5978dc1ad4 100644 --- a/packages/api-contract/src/base/Contract.ts +++ b/packages/api-contract/src/base/Contract.ts @@ -21,7 +21,6 @@ type ContractCallResultSubscription> : Promise>>; -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface ContractCall { send (account: IKeyringPair | string | AccountId | Address): ContractCallResultSubscription; } @@ -45,6 +44,7 @@ export default class Contract extends BaseWithTxAndRpc const { def, fn } = this.getMessage(message); return { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment send: this.decorateMethod( as === 'rpc' && this.hasRpcContractsCall ? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> => diff --git a/packages/api-contract/src/base/util.ts b/packages/api-contract/src/base/util.ts index 843eb31a95..2f695a6fb1 100644 --- a/packages/api-contract/src/base/util.ts +++ b/packages/api-contract/src/base/util.ts @@ -46,7 +46,7 @@ export abstract class Base implements ContractBase { export interface ContractABITypePre { ty: TypeIndex; + // eslint-disable-next-line camelcase display_name: StringIndex[]; } @@ -56,6 +57,7 @@ export interface ContractABIMessageCommon { export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre { name: StringIndex; + // eslint-disable-next-line camelcase return_type: ContractABITypePre | null; } @@ -187,6 +189,7 @@ export interface InterfaceAbi { } export interface InterfaceContractCalls { + // eslint-disable-next-line @typescript-eslint/ban-types [index: string]: Function; } diff --git a/packages/api-derive/src/democracy/referendumIds.ts b/packages/api-derive/src/democracy/referendumIds.ts index 57e2c5130c..3960dcbc2d 100644 --- a/packages/api-derive/src/democracy/referendumIds.ts +++ b/packages/api-derive/src/democracy/referendumIds.ts @@ -20,6 +20,7 @@ export function referendumIds (api: ApiInterfaceRx): () => Observable { ]).pipe( map(([first, total]): BN[] => total.gt(first) + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment ? [...Array(total.sub(first).toNumber())].map((_, i): BN => first.addn(i)) : [] ) diff --git a/packages/api-derive/src/index.spec.ts b/packages/api-derive/src/index.spec.ts index b269a2b561..fa7bbbb0e9 100644 --- a/packages/api-derive/src/index.spec.ts +++ b/packages/api-derive/src/index.spec.ts @@ -2,6 +2,10 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/restrict-template-expressions */ + import { Observable, from } from 'rxjs'; import ApiRx from '@polkadot/api/rx/Api'; import MockProvider from '@polkadot/rpc-provider/mock'; @@ -33,7 +37,7 @@ describe('derive', (): void => { const api = new ApiRx({ provider: new MockProvider(registry), registry }); beforeAll((done): void => { - api.isReady.subscribe((): void => done()); + api.isReady.subscribe(() => done()); }); testFunction(api)('accounts', 'idAndIndex', []); diff --git a/packages/api-derive/src/index.ts b/packages/api-derive/src/index.ts index 5156022a5c..641e84c1ed 100644 --- a/packages/api-derive/src/index.ts +++ b/packages/api-derive/src/index.ts @@ -76,9 +76,11 @@ function injectFunctions (api: ApiInterfaceRx, allSections: AllSect .reduce((sectionAcc, _methodName): DeriveSection => { const methodName = _methodName as keyof typeof section; // Not sure what to do here, casting as any. Though the final types are good + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call const method = (section[methodName] as any)(api); // idem + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access (sectionAcc as any)[methodName] = method; return sectionAcc; diff --git a/packages/api-derive/src/staking/erasExposure.ts b/packages/api-derive/src/staking/erasExposure.ts index 8b8ed08756..d5a7d1ecc4 100644 --- a/packages/api-derive/src/staking/erasExposure.ts +++ b/packages/api-derive/src/staking/erasExposure.ts @@ -38,7 +38,7 @@ function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposur export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable { return memo((era: EraIndex, withActive: boolean): Observable => { - const cacheKey = `${CACHE_KEY}-${era}`; + const cacheKey = `${CACHE_KEY}-${era.toString()}`; const cached = withActive ? undefined : deriveCache.get(cacheKey); diff --git a/packages/api-derive/src/staking/erasPoints.ts b/packages/api-derive/src/staking/erasPoints.ts index 4cc46c69b2..51f6f3a192 100644 --- a/packages/api-derive/src/staking/erasPoints.ts +++ b/packages/api-derive/src/staking/erasPoints.ts @@ -40,7 +40,7 @@ export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive const cached: DeriveEraPoints[] = withActive ? [] : eras - .map((era) => deriveCache.get(`${CACHE_KEY}-${era}`)) + .map((era) => deriveCache.get(`${CACHE_KEY}-${era.toString()}`)) .filter((value): value is DeriveEraPoints => !!value); const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era))); @@ -50,7 +50,7 @@ export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive map((points): DeriveEraPoints[] => { const query = mapPoints(remaining, points); - !withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era}`, q)); + !withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q)); return eras.map((era): DeriveEraPoints => cached.find((cached) => era.eq(cached.era)) || diff --git a/packages/api-derive/src/staking/erasPrefs.ts b/packages/api-derive/src/staking/erasPrefs.ts index 37dbf9a5b5..caef07829b 100644 --- a/packages/api-derive/src/staking/erasPrefs.ts +++ b/packages/api-derive/src/staking/erasPrefs.ts @@ -26,7 +26,7 @@ function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEr export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable { return memo((era: EraIndex, withActive: boolean): Observable => { - const cacheKey = `${CACHE_KEY}-${era}`; + const cacheKey = `${CACHE_KEY}-${era.toString()}`; const cached = withActive ? undefined : deriveCache.get(cacheKey); diff --git a/packages/api-derive/src/staking/erasRewards.ts b/packages/api-derive/src/staking/erasRewards.ts index 75e21d7f7c..8158cc0624 100644 --- a/packages/api-derive/src/staking/erasRewards.ts +++ b/packages/api-derive/src/staking/erasRewards.ts @@ -30,7 +30,7 @@ export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActiv const cached: DeriveEraRewards[] = withActive ? [] : eras - .map((era) => deriveCache.get(`${CACHE_KEY}-${era}`)) + .map((era) => deriveCache.get(`${CACHE_KEY}-${era.toString()}`)) .filter((value): value is DeriveEraRewards => !!value); const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era))); @@ -42,7 +42,7 @@ export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActiv map((optRewards) => { const query = mapRewards(remaining, optRewards); - !withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era}`, q)); + !withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q)); return eras.map((era): DeriveEraRewards => cached.find((cached) => era.eq(cached.era)) || diff --git a/packages/api-derive/src/staking/erasSlashes.ts b/packages/api-derive/src/staking/erasSlashes.ts index e46578ce8d..ec413359a1 100644 --- a/packages/api-derive/src/staking/erasSlashes.ts +++ b/packages/api-derive/src/staking/erasSlashes.ts @@ -32,7 +32,7 @@ function mapSlashes (era: EraIndex, noms: [StorageKey, Option][], val export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable { return memo((era: EraIndex, withActive: boolean): Observable => { - const cacheKey = `${CACHE_KEY}-${era}`; + const cacheKey = `${CACHE_KEY}-${era.toString()}`; const cached = withActive ? undefined : deriveCache.get(cacheKey); diff --git a/packages/api-derive/src/type/HeaderExtended.ts b/packages/api-derive/src/type/HeaderExtended.ts index 61cfbc508b..7b0b8869cc 100644 --- a/packages/api-derive/src/type/HeaderExtended.ts +++ b/packages/api-derive/src/type/HeaderExtended.ts @@ -9,7 +9,7 @@ import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions'; import { Struct } from '@polkadot/types'; // We can ignore the properties, added via Struct.with -const _Header: Constructor
= Struct.with(runtimeTypes.types.Header as any) as any; +const _Header = Struct.with(runtimeTypes.types.Header as any) as Constructor
; /** * @name HeaderExtended diff --git a/packages/api-derive/src/util/cache.ts b/packages/api-derive/src/util/cache.ts index e63afdc5d1..2c1e3c08fe 100644 --- a/packages/api-derive/src/util/cache.ts +++ b/packages/api-derive/src/util/cache.ts @@ -32,7 +32,7 @@ function wrapCache (keyStart: string, cache: DeriveCache): DeriveCache { return undefined; }, - set: (partial: string, v: any): void => { + set: (partial: string, v: unknown): void => { cache.set(`${keyStart}${partial}`, { v, x: Date.now() }); } }; diff --git a/packages/api-derive/src/util/cacheImpl.ts b/packages/api-derive/src/util/cacheImpl.ts index cf7c725c4a..8346681447 100644 --- a/packages/api-derive/src/util/cacheImpl.ts +++ b/packages/api-derive/src/util/cacheImpl.ts @@ -4,7 +4,7 @@ import { DeriveCache } from './types'; -const mapCache: Map = new Map(); +const mapCache = new Map(); const deriveMapCache: DeriveCache = { del: (key: string): void => { @@ -18,7 +18,7 @@ const deriveMapCache: DeriveCache = { } }, get: (key: string): T | undefined => { - return mapCache.get(key); + return mapCache.get(key) as T; }, set: (key: string, value: any): void => { mapCache.set(key, value); @@ -29,7 +29,7 @@ const deriveNoopCache: DeriveCache = { del: (): void => undefined, forEach: () => undefined, get: (): undefined => undefined, - set: (_: string, value: any): any => value + set: (_: string, value: unknown): unknown => value }; export { deriveMapCache, deriveNoopCache }; diff --git a/packages/api/src/base/Decorate.ts b/packages/api/src/base/Decorate.ts index a48ad17bcd..4d12f58944 100644 --- a/packages/api/src/base/Decorate.ts +++ b/packages/api/src/base/Decorate.ts @@ -31,7 +31,7 @@ import Events from './Events'; interface MetaDecoration { callIndex?: Uint8Array; - meta: any; + meta: Record; method: string; section: string; toJSON: () => any; @@ -246,9 +246,9 @@ export default abstract class Decorate extends Events ) // eslint-disable-next-line @typescript-eslint/no-unused-vars .forEach(([_, { method, section }]): void => { - delete (this._rpc as any)[section][method]; - delete (this._rpcCore as any)[section][method]; - delete (this._rx.rpc as any)[section][method]; + delete (this._rpc as Record>)[section][method]; + delete (this._rpcCore as unknown as Record>)[section][method]; + delete (this._rx.rpc as Record>)[section][method]; }); } @@ -257,11 +257,12 @@ export default abstract class Decorate extends Events const sectionName = _sectionName as keyof DecoratedRpc; // 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 => { + (out as Record)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection => { // skip subscriptions where we have a non-subscribe interface if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) { - (section as any)[methodName] = decorateMethod(method, { methodName }); - (section as any)[methodName].raw = decorateMethod(method.raw, { methodName }); + (section as Record)[methodName] = decorateMethod(method, { methodName }) as unknown; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (section as Record)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown; } return section; @@ -272,10 +273,12 @@ export default abstract class Decorate extends Events } protected _decorateMulti (decorateMethod: DecorateMethod): QueryableStorageMulti { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return decorateMethod((calls: QueryableStorageMultiArg[]): Observable => this._rpcCore.state.subscribeStorage( calls.map((arg: QueryableStorageMultiArg): [QueryableStorageEntry, ...Arg[]] => // the input is a QueryableStorageEntry, convert to StorageEntry + // eslint-disable-next-line @typescript-eslint/no-unsafe-return Array.isArray(arg) ? [arg[0].creator, ...arg.slice(1)] : [arg.creator] as any))); @@ -299,7 +302,8 @@ export default abstract class Decorate extends Events const decorated = (...params: Arg[]): SubmittableExtrinsic => creator(method(...params)); - return this._decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction; + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction; } protected _decorateStorage (storage: Storage, decorateMethod: DecorateMethod): QueryableStorage { @@ -319,6 +323,7 @@ export default abstract class Decorate extends Events const getArgs = (...args: any[]): any[] => extractStorageArgs(creator, args); // FIXME We probably want to be able to query the full list with non-subs as well + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue ? this._decorateStorageLinked(creator, decorateMethod) : decorateMethod((...args: any[]): Observable => ( @@ -332,32 +337,41 @@ export default abstract class Decorate extends Events : this._rpcCore.state.getStorage(getArgs(...args)) ), { methodName: creator.method }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access decorated.creator = creator; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.at = decorateMethod((hash: Hash, arg1?: Arg, arg2?: Arg): Observable => this._rpcCore.state.getStorage(getArgs(arg1, arg2), hash)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable => this._rpcCore.state.getStorageHash(getArgs(arg1, arg2))); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access decorated.key = (arg1?: Arg, arg2?: Arg): string => u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access decorated.keyPrefix = (key1?: Arg): string => u8aToHex(creator.keyPrefix(key1)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> => this._decorateStorageRange(decorated, [arg1, arg2], range)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.size = decorateMethod((arg1?: Arg, arg2?: Arg): Observable => this._rpcCore.state.getStorageSize(getArgs(arg1, arg2))); // .keys() & .entries() only available on map types if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.entries = decorateMethod( memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> => this._retrieveMapEntries(creator, doubleMapArg))); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.keys = decorateMethod( memo((doubleMapArg?: Arg): Observable => this._retrieveMapKeys(creator, doubleMapArg))); @@ -366,12 +380,13 @@ export default abstract class Decorate extends Events // only support multi where subs are available if (this.hasSubscriptions) { // When using double map storage function, user need to pass double map key as an array + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment decorated.multi = decorateMethod((args: (Arg | Arg[])[]): Observable => this._rpcCore.state.subscribeStorage( args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg]))); } - return this._decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry; + return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry; } private _decorateStorageRange (decorated: QueryableStorageEntry, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> { @@ -388,7 +403,7 @@ export default abstract class Decorate extends Events } private _decorateStorageLinked (creator: StorageEntry, decorateMethod: DecorateMethod): ReturnType> { - const result: Map]> | null> = new Map(); + const result = new Map]> | null>(); let subject: BehaviorSubject; let head: Codec | null = null; const iterKey = creator.iterKey; @@ -451,9 +466,11 @@ export default abstract class Decorate extends Events // this handles the case where the head changes effectively, i.e. a new entry // appears at the top of the list, the new getNext gets kicked off + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return decorateMethod((...args: any[]): Observable]> => args.length ? this._rpcCore.state + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment .subscribeStorage<[[Codec, Linkage]]>([[creator, ...args]]) .pipe(map(([data]): [Codec, Linkage] => data)) : this._rpcCore.state diff --git a/packages/api/src/base/Init.ts b/packages/api/src/base/Init.ts index 68d0fba128..d4f6e1f3b1 100644 --- a/packages/api/src/base/Init.ts +++ b/packages/api/src/base/Init.ts @@ -62,6 +62,7 @@ export default abstract class Init extends Decorate extends Decorate { - Object.keys((source.rpc as any)[section]).forEach((method): void => { + Object.keys((source.rpc as Record>)[section]).forEach((method): void => { methods.push(`${section}_${method}`); }); }); @@ -130,7 +131,7 @@ export default abstract class Init extends Decorate { - l.log(`Runtime version updated to ${version.specVersion}`); + l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`); this._runtimeMetadata = metadata; this._runtimeVersion = version; @@ -167,7 +168,7 @@ export default abstract class Init extends Decorate extends Decorate { - pkgJson = _pkgJson; + .then((_pkgJson: unknown): void => { + pkgJson = _pkgJson as PkgJson; }) .catch((): void => { // ignore diff --git a/packages/api/src/checkTypes.manual.ts b/packages/api/src/checkTypes.manual.ts index 5d8ba68fe1..19d97abeca 100644 --- a/packages/api/src/checkTypes.manual.ts +++ b/packages/api/src/checkTypes.manual.ts @@ -87,7 +87,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise { // check range types const entries = await api.query.system.events.range(['0x12345', '0x7890']); - console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`)}`); + console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`).join(', ')}`); } async function rpc (api: ApiPromise): Promise { @@ -105,6 +105,7 @@ async function rpc (api: ApiPromise): Promise { await api.rpc.chain.getBlock.raw('0x123456'); // using raw subs + // eslint-disable-next-line @typescript-eslint/no-floating-promises api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => { console.log(result); }); @@ -125,7 +126,7 @@ function types (api: ApiPromise): void { async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise { // transfer, also allows for BigInt inputs here - const transfer = api.tx.balances.transfer(keyring.bob.address, 123_456_789n); + const transfer = api.tx.balances.transfer(keyring.bob.address, 123456789n); console.log('transfer as Call', transfer as IMethod); console.log('transfer as Extrinsic', transfer as IExtrinsic); @@ -161,6 +162,7 @@ async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise { // it allows for query & then using the submittable const second = api.tx.democracy.second(123, 5); + // eslint-disable-next-line @typescript-eslint/no-floating-promises second.signAndSend('123', (result): void => { console.log(result); }); @@ -173,12 +175,15 @@ async function main (): Promise { const api = await ApiPromise.create(); const keyring = testKeyring(); - consts(api); - derive(api); - query(api, keyring); - rpc(api); - types(api); - tx(api, keyring); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Promise.all([ + consts(api), + derive(api), + query(api, keyring), + rpc(api), + types(api), + tx(api, keyring) + ]); } // eslint-disable-next-line @typescript-eslint/unbound-method diff --git a/packages/api/src/promise/Api.spec.ts b/packages/api/src/promise/Api.spec.ts index 7419106de0..7080ed27b1 100644 --- a/packages/api/src/promise/Api.spec.ts +++ b/packages/api/src/promise/Api.spec.ts @@ -39,7 +39,7 @@ describe('ApiPromise', (): void => { const signer = new SingleAccountSigner(registry, aliceEd); const api = await ApiPromise.create({ provider, registry, signer }); - const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321_564_789_876_512_345n); + const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321564789876512345n); return { api, transfer: await transfer.signAsync(aliceEd.address, {}) }; } @@ -57,8 +57,10 @@ describe('ApiPromise', (): void => { const metadata: any = {}; const key = `${genesisHash}-${specVersion}`; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access metadata[key] = rpcData; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const api = await ApiPromise.create({ metadata, provider, registry } as ApiOptions); expect(api.genesisHash).toBeDefined(); diff --git a/packages/api/src/promise/Api.ts b/packages/api/src/promise/Api.ts index 5c3afa85e9..38aa881ec2 100644 --- a/packages/api/src/promise/Api.ts +++ b/packages/api/src/promise/Api.ts @@ -25,6 +25,7 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback void) => void, reject: (value: Error) => void): Tracker { let isCompleted = false; + // eslint-disable-next-line @typescript-eslint/ban-types const complete = (fn: Function, value: any): void => { if (!isCompleted) { isCompleted = true; @@ -68,24 +70,22 @@ export function decorateMethod (method: Method, opti const [actualArgs, callback] = extractArgs(args, !!needsCallback); if (!callback) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access return method(...actualArgs).pipe(first()).toPromise() as Promise>>; } 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 => - tracker.reject(error) - ), - // upon the first result, resolve with the unsub function - tap((): void => - tracker.resolve((): void => subscription.unsubscribe()) - ) - ) - .subscribe(callback); - }) as any; // ??? + + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment + const subscription: { unsubscribe: () => void } = method(...actualArgs).pipe( + // if we find an error (invalid params, etc), reject the promise + catchError((error): Observable => tracker.reject(error)), + // upon the first result, resolve with the unsub function + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return + tap(() => tracker.resolve(() => subscription.unsubscribe())) + ).subscribe(callback); + }) as UnsubscribePromise; } as StorageEntryPromiseOverloads; } diff --git a/packages/api/src/promise/Combinator.ts b/packages/api/src/promise/Combinator.ts index 81a1c2ed01..ef7478c805 100644 --- a/packages/api/src/promise/Combinator.ts +++ b/packages/api/src/promise/Combinator.ts @@ -41,6 +41,7 @@ export default class Combinator { this.#fns.push(fn); // Not quite 100% how to have a variable number at the front here + // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/ban-types return (fn as Function)(...args, this._createCallback(index)); }); } @@ -54,7 +55,7 @@ export default class Combinator { } protected _createCallback (index: number): (value: any) => void { - return (value: any): void => { + return (value: unknown): void => { this.#fired[index] = true; this.#results[index] = value; @@ -68,6 +69,7 @@ export default class Combinator { } try { + // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#callback(this.#results as T); } catch (error) { // swallow, we don't want the handler to trip us up diff --git a/packages/api/src/submittable/createClass.ts b/packages/api/src/submittable/createClass.ts index 8d344848d0..51e991f9c1 100644 --- a/packages/api/src/submittable/createClass.ts +++ b/packages/api/src/submittable/createClass.ts @@ -41,6 +41,7 @@ export default function createClass ({ api, apiType, const [allOptions] = this.#makeSignAndSendOptions(options); const address = isKeyringPair(account) ? account.address : account.toString(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call return decorateMethod( (): Observable => api.derive.tx.signingInfo(address, allOptions.nonce, allOptions.era).pipe( @@ -70,6 +71,7 @@ export default function createClass ({ api, apiType, // // also supports signing through external signers public signAsync (account: AddressOrPair, optionsOrNonce?: Partial): SubmittableThis { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call return decorateMethod( (): Observable => this.#observeSign(account, optionsOrNonce).pipe(mapTo(this)) @@ -90,6 +92,7 @@ export default function createClass ({ api, apiType, const [options, statusCb] = this.#makeSignAndSendOptions(optionsOrStatus, optionalStatusCb); const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call return decorateMethod( (): Observable => ( this.#observeSign(account, options).pipe( @@ -112,6 +115,7 @@ export default function createClass ({ api, apiType, public send (statusCb?: Callback): SubmittableResultResult | SubmittableResultSubscription { const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call return decorateMethod( isSubscription ? this.#observeSubscribe diff --git a/packages/api/src/submittable/createSubmittable.ts b/packages/api/src/submittable/createSubmittable.ts index 3415df7639..be6ae3a048 100644 --- a/packages/api/src/submittable/createSubmittable.ts +++ b/packages/api/src/submittable/createSubmittable.ts @@ -22,6 +22,6 @@ export default function createSubmittable (apiType: Ap Submittable = createClass({ api, apiType, decorateMethod }); } - return new Submittable(api.registry, extrinsic); + return new Submittable(api.registry, extrinsic) as SubmittableExtrinsic; }; } diff --git a/packages/api/src/util/augmentObject.spec.ts b/packages/api/src/util/augmentObject.spec.ts index a7c05faaa0..db640498d8 100644 --- a/packages/api/src/util/augmentObject.spec.ts +++ b/packages/api/src/util/augmentObject.spec.ts @@ -12,6 +12,7 @@ describe('augmentObject', (): void => { }); afterEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access spy.mockClear(); }); diff --git a/packages/api/src/util/augmentObject.ts b/packages/api/src/util/augmentObject.ts index 0957ba9999..83c84e2600 100644 --- a/packages/api/src/util/augmentObject.ts +++ b/packages/api/src/util/augmentObject.ts @@ -74,7 +74,7 @@ function extractMethods (src: Record>, dst: Record>, dst: Record>, fromEmpty = false): Record> { +export default function augmentObject (prefix: string, src: Record>, dst: Record>, fromEmpty = false): Record> { if (fromEmpty) { Object.keys(dst).forEach((key): void => { delete dst[key]; @@ -88,12 +88,12 @@ export default function augmentObject (prefix: string, src: Record> => { + .reduce((newSection, sectionName): Record> => { const section = src[sectionName]; newSection[sectionName] = Object .keys(section) - .reduce((result, methodName): Record => { + .reduce((result, methodName): Record => { // TODO When it does match, check the actual details and warn when there are differences if (!result[methodName]) { result[methodName] = section[methodName]; diff --git a/packages/api/src/util/decorate.ts b/packages/api/src/util/decorate.ts index fbc1d97562..ab05b22580 100644 --- a/packages/api/src/util/decorate.ts +++ b/packages/api/src/util/decorate.ts @@ -14,17 +14,14 @@ export type DeriveAllSections (obj: T): (keyof T)[] { - return Object.keys(obj) as (keyof T)[]; +function keys> (obj: T): (keyof T)[] { + return Object.keys(obj); } /** * This is a methods decorator which keeps all type information. */ -function decorateMethods> ( - section: Section, - decorateMethod: DecorateMethod -): DeriveSection { +function decorateMethods> (section: Section, decorateMethod: DecorateMethod): DeriveSection { return keys(section).reduce( ( acc: DeriveSection, @@ -32,7 +29,8 @@ function decorateMethods => { const method = section[methodName]; - acc[methodName] = decorateMethod(method); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + acc[methodName] = decorateMethod(method) as MethodResult; return acc; }, diff --git a/packages/api/src/util/filterEvents.ts b/packages/api/src/util/filterEvents.ts index 6bd2e9c439..3cccb54c25 100644 --- a/packages/api/src/util/filterEvents.ts +++ b/packages/api/src/util/filterEvents.ts @@ -18,7 +18,7 @@ export default function filterEvents (extHash: H256, { block: { extrinsics, head if (index === -1) { // only warn on filtering with isInBlock (finalization finalizes after) if (status.isInBlock) { - l.warn(`block ${header.hash}: Unable to find extrinsic ${myHash} inside ${allHashes}`); + l.warn(`block ${header.hash.toHex()}: Unable to find extrinsic ${myHash} inside ${allHashes.join(', ')}`); } return; diff --git a/packages/api/src/util/validate.spec.ts b/packages/api/src/util/validate.spec.ts index 4c0b4d8116..08a36df018 100644 --- a/packages/api/src/util/validate.spec.ts +++ b/packages/api/src/util/validate.spec.ts @@ -35,8 +35,7 @@ describe('extractStorageArgs', (): void => { it('validates no-arg plain (failing when there are args)', (): void => { expect( - (): any[] => - extractStorageArgs(storage.timestamp.now, [123, 456]) + (): unknown => extractStorageArgs(storage.timestamp.now, [123, 456]) ).toThrow('timestamp.now() does not take any arguments, 2 found'); }); diff --git a/packages/api/src/util/validate.ts b/packages/api/src/util/validate.ts index fe2a8cba1b..bfac4d4dc2 100644 --- a/packages/api/src/util/validate.ts +++ b/packages/api/src/util/validate.ts @@ -35,7 +35,7 @@ function doMap (creator: StorageEntry, args: any[]): [StorageEntry] | [StorageEn // sets up the arguments in the form of [creator, args] ready to be used in a storage // call. Additionally, it verifies that the correct number of arguments have been passed -export function extractStorageArgs (creator: StorageEntry, _args: any[]): any[] { +export function extractStorageArgs (creator: StorageEntry, _args: any[]): [StorageEntry, [any, any]] | [StorageEntry] | [StorageEntry, any] { const args = _args.filter((arg) => !isUndefined(arg)); if (creator.meta.type.isDoubleMap) { diff --git a/packages/api/test/util/logEvents.ts b/packages/api/test/util/logEvents.ts index 50f10d42e1..95d381b3cc 100644 --- a/packages/api/test/util/logEvents.ts +++ b/packages/api/test/util/logEvents.ts @@ -7,7 +7,7 @@ import { EventRecord } from '@polkadot/types/interfaces'; import { SubmittableResult } from '../../src'; // log all events for the transfers, calling done() when finalized -export const logEvents = (done: () => {}): (r: SubmittableResult) => void => +export const logEvents = (done: () => Record): (r: SubmittableResult) => void => ({ events, status }: SubmittableResult): void => { console.log('Transaction status:', status.type); diff --git a/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.spec.ts b/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.spec.ts index 82686393b8..fefa800499 100644 --- a/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.spec.ts +++ b/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.spec.ts @@ -14,6 +14,7 @@ describe('createFunction', (): void => { it('should create timestamp.now correctly', (): void => { expect( createFunction(registry, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment meta: { type: {} } as any, method: 'Now', prefix: 'Timestamp', @@ -29,6 +30,7 @@ describe('createFunction', (): void => { createFunction( registry, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment meta: { type: {} } as any, method: 'authorityCount', prefix: 'Substrate', @@ -50,6 +52,7 @@ describe('createFunction', (): void => { createFunction( registry, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment meta: { type: {} } as any, method: 'authorityCount', prefix: 'Substrate', @@ -74,6 +77,7 @@ describe('createFunction', (): void => { beforeAll((): void => { storageFn = createFunction(registry, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment meta: { name: 'metaName', type: { @@ -119,6 +123,7 @@ describe('createFunction', (): void => { it('allows creates double map function with a Null type key', (): void => { const storageFn = createFunction(registry, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment meta: { type: { asDoubleMap: { @@ -144,6 +149,7 @@ describe('createFunction', (): void => { it('allows creating of known DoubleMap keys (with Bytes)', (): void => { const storageFn = createFunction(registry, { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment meta: { type: { asDoubleMap: { diff --git a/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.ts b/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.ts index 19454c23d5..23efef4870 100644 --- a/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.ts +++ b/packages/metadata/src/Decorated/storage/fromMetadata/createFunction.ts @@ -73,10 +73,7 @@ function createKeyDoubleMap (registry: Registry, itemFn: CreateItemFn, stringKey const { meta: { name, type } } = itemFn; // since we are passing an almost-unknown through, trust, but verify - assert( - Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]), - `${name} is a DoubleMap and requires two arguments` - ); + assert(Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]), `${(name || 'unknown').toString()} is a DoubleMap and requires two arguments`); // if this fails, we have bigger issues assert(!isUndefined(hasher2), '2 hashing functions should be defined for DoubleMaps'); @@ -110,7 +107,7 @@ function createKey (registry: Registry, itemFn: CreateItemFn, stringKey: string, if (type.isMap) { const map = type.asMap; - assert(!isUndefined(arg) && !isNull(arg), `${name} is a Map and requires one argument`); + assert(!isUndefined(arg) && !isNull(arg), `${name.toString()} is a Map and requires one argument`); param = createTypeUnsafe(registry, map.key.toString(), [arg]).toU8a(); } @@ -134,7 +131,7 @@ function expandWithMeta ({ meta, method, prefix, section }: CreateItemFn, storag // explicitly add the actual method in the toJSON, this gets used to determine caching and without it // instances (e.g. collective) will not work since it is only matched on param meta storageFn.toJSON = (): any => ({ - ...(meta.toJSON() as any), + ...(meta.toJSON() as Record), storage: { method, prefix, section } }); diff --git a/packages/metadata/src/Decorated/storage/fromMetadata/getHasher.ts b/packages/metadata/src/Decorated/storage/fromMetadata/getHasher.ts index 93aac5bc3c..6d3cb4912c 100644 --- a/packages/metadata/src/Decorated/storage/fromMetadata/getHasher.ts +++ b/packages/metadata/src/Decorated/storage/fromMetadata/getHasher.ts @@ -14,11 +14,11 @@ export type HasherFunction = (data: HasherInput) => Uint8Array; const DEFAULT_FN = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128); const HASHERS: Record = { - Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase + Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase blake2AsU8a(data, 128), - Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase + Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase u8aConcat(blake2AsU8a(data, 128), u8aToU8a(data)), - Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase + Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase blake2AsU8a(data, 256), Identity: (data: HasherInput): Uint8Array => u8aToU8a(data), diff --git a/packages/metadata/src/Decorated/storage/fromMetadata/storage.ts b/packages/metadata/src/Decorated/storage/fromMetadata/storage.ts index 1fea140b0c..8d1da283c5 100644 --- a/packages/metadata/src/Decorated/storage/fromMetadata/storage.ts +++ b/packages/metadata/src/Decorated/storage/fromMetadata/storage.ts @@ -14,7 +14,7 @@ export default function getStorage (registry: Registry, metaVersion: number): St substrate: Object .entries(substrate) .reduce((storage: Record, [key, fn]): Record => { - (storage as any)[key] = fn(registry, metaVersion); + (storage as Record)[key] = fn(registry, metaVersion); return storage; }, {}) diff --git a/packages/metadata/src/Metadata/MagicNumber.ts b/packages/metadata/src/Metadata/MagicNumber.ts index aec435e778..ce3ccf316d 100644 --- a/packages/metadata/src/Metadata/MagicNumber.ts +++ b/packages/metadata/src/Metadata/MagicNumber.ts @@ -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 { Registry } from '@polkadot/types/types'; +import { AnyNumber, Registry } from '@polkadot/types/types'; import { assert } from '@polkadot/util'; @@ -11,7 +11,7 @@ import U32 from '@polkadot/types/primitive/U32'; export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding export default class MagicNumber extends U32 { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: AnyNumber) { super(registry, value); if (!this.isEmpty) { diff --git a/packages/metadata/src/Metadata/MetadataVersioned.ts b/packages/metadata/src/Metadata/MetadataVersioned.ts index bf15ce20ff..c94aa5fae6 100644 --- a/packages/metadata/src/Metadata/MetadataVersioned.ts +++ b/packages/metadata/src/Metadata/MetadataVersioned.ts @@ -33,13 +33,13 @@ type MetaAsX = 'asV0' | 'asV1' | 'asV2' | 'asV3' | 'asV4' | 'asV5' | 'asV6' | 'a * The versioned runtime metadata as a decoded structure */ export default class MetadataVersioned extends Struct { - readonly #converted: Map = new Map(); + readonly #converted = new Map(); - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: unknown) { super(registry, { magicNumber: MagicNumber, metadata: 'MetadataAll' - }, value); + }, value as Map); registry.setMetadata(this); } diff --git a/packages/metadata/src/Metadata/util/flattenUniq.ts b/packages/metadata/src/Metadata/util/flattenUniq.ts index 40b66ceeac..5e71523843 100644 --- a/packages/metadata/src/Metadata/util/flattenUniq.ts +++ b/packages/metadata/src/Metadata/util/flattenUniq.ts @@ -2,9 +2,11 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +type Types = string | Types[]; + /** @internal */ -export default function flattenUniq (list: any[]): any[] { - const flat = list.reduce((result, entry): any[] => { +export default function flattenUniq (list: Types[]): string[] { + const flat = list.reduce((result: string[], entry): string[] => { return result.concat( Array.isArray(entry) ? flattenUniq(entry) @@ -13,6 +15,6 @@ export default function flattenUniq (list: any[]): any[] { }, []); return [...new Set(flat)] - .filter((value: any): any => value) + .filter((value: string) => value) .sort(); } diff --git a/packages/metadata/src/Metadata/util/testUtil.ts b/packages/metadata/src/Metadata/util/testUtil.ts index c3f7da6fa4..4eff2f4850 100644 --- a/packages/metadata/src/Metadata/util/testUtil.ts +++ b/packages/metadata/src/Metadata/util/testUtil.ts @@ -11,7 +11,7 @@ import getUniqTypes from './getUniqTypes'; import Metadata from '../Metadata'; /** @internal */ -export function decodeLatestSubstrate (registry: Registry, version: number, rpcData: string, staticSubstrate: object): void { +export function decodeLatestSubstrate (registry: Registry, version: number, rpcData: string, staticSubstrate: Record): void { it('decodes latest substrate properly', (): void => { const metadata = new Metadata(registry, rpcData); @@ -49,14 +49,14 @@ export function defaultValues (registry: Registry, rpcData: string, withThrow = metadata.asLatest.modules.filter(({ storage }): boolean => storage.isSome).forEach((mod): void => { mod.storage.unwrap().items.forEach(({ fallback, name, type }): void => { const inner = unwrapStorageType(type); - const location = `${mod.name}.${name}: ${inner}`; + const location = `${mod.name.toString()}.${name.toString()}: ${inner}`; it(`creates default types for ${location}`, (): void => { expect((): void => { try { registry.createType(inner, fallback); } catch (error) { - const message = `${location}:: ${error.message}`; + const message = `${location}:: ${(error as Error).message}`; if (withThrow) { throw new Error(message); diff --git a/packages/metadata/src/Metadata/util/toCallsOnly.ts b/packages/metadata/src/Metadata/util/toCallsOnly.ts index b20b8ee293..7c4a89079c 100644 --- a/packages/metadata/src/Metadata/util/toCallsOnly.ts +++ b/packages/metadata/src/Metadata/util/toCallsOnly.ts @@ -26,7 +26,7 @@ function mapCalls (registry: Registry, _calls: Option>; } /** @internal */ diff --git a/packages/metadata/src/Metadata/util/validateTypes.ts b/packages/metadata/src/Metadata/util/validateTypes.ts index a6e111d0b2..51aeefb85d 100644 --- a/packages/metadata/src/Metadata/util/validateTypes.ts +++ b/packages/metadata/src/Metadata/util/validateTypes.ts @@ -8,9 +8,11 @@ import { getTypeDef } from '@polkadot/types/create'; import flattenUniq from './flattenUniq'; +type Extracted = string | Extracted[]; + /** @internal */ -function extractTypes (types: string[]): any[] { - return types.map((type): any => { +function extractTypes (types: string[]): Extracted[] { + return types.map((type): Extracted => { const decoded = getTypeDef(type); switch (decoded.info) { @@ -38,12 +40,10 @@ function extractTypes (types: string[]): any[] { /** @internal */ export default function validateTypes (registry: Registry, types: string[], throwError: boolean): void { - const missing = flattenUniq(extractTypes(types)).filter((type): boolean => - !registry.hasType(type) - ); + const missing = flattenUniq(extractTypes(types)).filter((type) => !registry.hasType(type)); if (missing.length !== 0) { - const message = `Unknown types found, no types for ${missing}`; + const message = `Unknown types found, no types for ${missing.join(', ')}`; if (throwError) { throw new Error(message); diff --git a/packages/rpc-core/src/cached.spec.ts b/packages/rpc-core/src/cached.spec.ts index cbf05a5dba..8991c192ec 100644 --- a/packages/rpc-core/src/cached.spec.ts +++ b/packages/rpc-core/src/cached.spec.ts @@ -84,6 +84,7 @@ describe('Cached Observables', (): void => { it('creates different observables for different methods but same arguments', (): void => { // params do not match here + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access const observable1 = (rpc.chain as any).subscribeNewHeads([123]); const observable2 = rpc.state.subscribeStorage([123]); diff --git a/packages/rpc-core/src/index.spec.ts b/packages/rpc-core/src/index.spec.ts index 25adf46b21..ffdecddf17 100644 --- a/packages/rpc-core/src/index.spec.ts +++ b/packages/rpc-core/src/index.spec.ts @@ -28,6 +28,7 @@ describe('Api', (): void => { } }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(isFunction((rpc as any).testing.foo)).toBe(true); expect(rpc.sections.includes('testing')).toBe(true); expect(rpc.mapping.get('testing_foo')).toEqual({ diff --git a/packages/rpc-core/src/index.ts b/packages/rpc-core/src/index.ts index 0a7ae19f2c..0548a32617 100644 --- a/packages/rpc-core/src/index.ts +++ b/packages/rpc-core/src/index.ts @@ -63,7 +63,7 @@ function logErrorMessage (method: string, { params, type }: DefinitionRpc, error export default class Rpc implements RpcInterface { readonly #storageCache = new Map(); - public readonly mapping: Map = new Map(); + public readonly mapping = new Map(); public readonly provider: ProviderInterface; @@ -134,7 +134,7 @@ export default class Rpc implements RpcInterface { // decorate the sections with base and user methods this.sections.forEach((sectionName): void => { - (this as any)[sectionName as Section] = { + (this as Record)[sectionName as Section] = { ...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}), ...this._createInterface(sectionName, userRpc[sectionName] || {}) }; @@ -156,7 +156,7 @@ export default class Rpc implements RpcInterface { // `` // Not doing so, because it makes this class a little bit less readable, // and leaving it as-is doesn't harm much - (exposed as any)[method] = isSubscription + (exposed as Record)[method] = isSubscription ? this._createMethodSubscribe(section, method, def as DefinitionRpcSub) : this._createMethodSend(section, method, def); @@ -333,7 +333,7 @@ export default class Rpc implements RpcInterface { try { return this._formatStorageData(key, result); } catch (error) { - console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message); + console.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:`, (error as Error).message); throw error; } @@ -341,10 +341,10 @@ export default class Rpc implements RpcInterface { const keys = params[0] as Vec; return keys - ? this._formatStorageSet(keys, result.changes) + ? this._formatStorageSet(keys, (result as { changes: [string, string | null][] }).changes) : this.registry.createType('StorageChangeSet', result); } else if (rpc.type === 'Vec') { - const mapped = result.map(({ block, changes }: { block: string; changes: [string, string | null][] }): [Hash, Codec[]] => [ + const mapped = (result as { block: string; changes: [string, string | null][] }[]).map(({ block, changes }): [Hash, Codec[]] => [ this.registry.createType('Hash', block), this._formatStorageSet(params[0] as Vec, changes) ]); @@ -352,7 +352,7 @@ export default class Rpc implements RpcInterface { // we only query at a specific block, not a range - flatten return method === 'queryStorageAt' ? mapped[0][1] - : mapped; + : mapped as unknown as Codec[]; } return createTypeUnsafe(this.registry, rpc.type, [result]); @@ -404,7 +404,7 @@ export default class Rpc implements RpcInterface { try { results.push(this._formatStorageSetEntry(key, changes, withCache)); } catch (error) { - console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message); + console.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:`, (error as Error).message); throw error; } diff --git a/packages/rpc-core/src/methodSend.spec.ts b/packages/rpc-core/src/methodSend.spec.ts index 4e6bc8b7ab..ae1419fccf 100644 --- a/packages/rpc-core/src/methodSend.spec.ts +++ b/packages/rpc-core/src/methodSend.spec.ts @@ -31,7 +31,7 @@ describe('methodSend', (): void => { }; provider = { - send: jest.fn((method, params): Promise => { + send: jest.fn((method, params: any[]): Promise => { return Promise.resolve(params[0]); }) }; @@ -41,8 +41,10 @@ describe('methodSend', (): void => { it('checks for mismatched parameters', (done): void => { // private method + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access const method = (rpc as any)._createMethodSend('test', 'bleh', methods.bleh); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access method(1).subscribe( (): void => undefined, (error: Error): void => { @@ -53,10 +55,13 @@ describe('methodSend', (): void => { it('calls the provider with the correct parameters', (done): void => { // private method + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access const method = (rpc as any)._createMethodSend('test', 'blah', methods.blah); // Args are length-prefixed, because it's a Bytes + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe((): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']); done(); }); diff --git a/packages/rpc-core/src/replay.spec.ts b/packages/rpc-core/src/replay.spec.ts index 7f50d3bb24..fa26379466 100644 --- a/packages/rpc-core/src/replay.spec.ts +++ b/packages/rpc-core/src/replay.spec.ts @@ -18,7 +18,9 @@ describe('replay', (): void => { it('subscribes via the rpc section', (done): void => { // we don't honor types or number of params here + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (rpc.chain as any).getBlockHash = jest.fn((): Observable => of(1)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access (rpc.chain as any).getBlockHash(123, false).subscribe((): void => { expect( // eslint-disable-next-line @typescript-eslint/unbound-method @@ -32,6 +34,7 @@ describe('replay', (): void => { it('returns the observable value', (done): void => { rpc.system.chain().subscribe((value: any): void => { if (value) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access expect(value.toString()).toEqual('mockChain'); // Defined in MockProvider done(); } @@ -40,9 +43,9 @@ describe('replay', (): void => { it('replay(1) works as expected', (done): void => { const observable = rpc.system.chain(); - let a: string | undefined; + let a: any | undefined; - observable.subscribe((value: any): void => { a = value; }); + observable.subscribe((value?: unknown): void => { a = value; }); setTimeout((): void => { // Subscribe again to the same observable, it should fire value immediately diff --git a/packages/rpc-core/src/rxjs/drr.ts b/packages/rpc-core/src/rxjs/drr.ts index 932c732361..50d0f5341a 100644 --- a/packages/rpc-core/src/rxjs/drr.ts +++ b/packages/rpc-core/src/rxjs/drr.ts @@ -18,7 +18,7 @@ interface Options { const l = logger('drr'); -const CMP = (a: any, b: any): boolean => +const CMP = (a: unknown, b: unknown): boolean => JSON.stringify({ t: a }) === JSON.stringify({ t: b }); const ERR = (error: Error): Observable => { @@ -40,7 +40,7 @@ export const drr = ({ skipChange = false, skipTimeout = false }: Options = {}): catchError(ERR), skipChange ? tap(NOOP) - : distinctUntilChanged(CMP), + : distinctUntilChanged(CMP), publishReplay(1), skipTimeout ? refCount() diff --git a/packages/rpc-provider/src/coder/encodeObject.spec.ts b/packages/rpc-provider/src/coder/encodeObject.spec.ts index f01d47f4ca..1e53914496 100644 --- a/packages/rpc-provider/src/coder/encodeObject.spec.ts +++ b/packages/rpc-provider/src/coder/encodeObject.spec.ts @@ -17,12 +17,12 @@ describe('encodeObject', (): void => { it('encodes a valid JsonRPC object', (): void => { expect( - coder.encodeObject('method', 'params') + coder.encodeObject('method', ['a', 'b']) ).toEqual({ id: 1, jsonrpc: '2.0', method: 'method', - params: 'params' + params: ['a', 'b'] }); expect(coder.getId()).toEqual(1); }); diff --git a/packages/rpc-provider/src/coder/index.ts b/packages/rpc-provider/src/coder/index.ts index f6a46e0897..34e5c0f895 100644 --- a/packages/rpc-provider/src/coder/index.ts +++ b/packages/rpc-provider/src/coder/index.ts @@ -24,7 +24,7 @@ function formatErrorData (data?: string | number): string { export default class RpcCoder { #id = 0; - public decodeResponse (response: JsonRpcResponse): any { + public decodeResponse (response: JsonRpcResponse): unknown { assert(response, 'Empty response object received'); assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object'); @@ -51,7 +51,7 @@ export default class RpcCoder { ); } - public encodeObject (method: string, params: any | any[]): JsonRpcRequest { + public encodeObject (method: string, params: unknown[]): JsonRpcRequest { return { id: ++this.#id, jsonrpc: '2.0', diff --git a/packages/rpc-provider/src/http/index.spec.ts b/packages/rpc-provider/src/http/index.spec.ts index 95f39ceadc..6f10f59e49 100644 --- a/packages/rpc-provider/src/http/index.spec.ts +++ b/packages/rpc-provider/src/http/index.spec.ts @@ -32,13 +32,13 @@ describe('Http', (): void => { return http.subscribe('', '', [], (cb): void => { expect(cb).toEqual(expect.anything()); }).catch((error): void => { - expect(error.message).toMatch(/does not have subscriptions/); + expect((error as Error).message).toMatch(/does not have subscriptions/); }); }); it('does not (yet) support unsubscribe', (): Promise => { return http.unsubscribe('', '', 0).catch((error): void => { - expect(error.message).toMatch(/does not have subscriptions/); + expect((error as Error).message).toMatch(/does not have subscriptions/); }); }); }); diff --git a/packages/rpc-provider/src/http/index.ts b/packages/rpc-provider/src/http/index.ts index 98201f654c..624cfcb8a3 100644 --- a/packages/rpc-provider/src/http/index.ts +++ b/packages/rpc-provider/src/http/index.ts @@ -109,6 +109,7 @@ export default 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(); return this.#coder.decodeResponse(result); diff --git a/packages/rpc-provider/src/http/polyfill.spec.ts b/packages/rpc-provider/src/http/polyfill.spec.ts index 0369285692..cd94ed1cbf 100644 --- a/packages/rpc-provider/src/http/polyfill.spec.ts +++ b/packages/rpc-provider/src/http/polyfill.spec.ts @@ -10,14 +10,17 @@ describe('http/polyfill', (): void => { let origFetch: any; beforeEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment origFetch = global.fetch; }); afterEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment global.fetch = origFetch; }); it('polyfills with no exceptions (without fetch)', (): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (global as any).fetch = undefined; require('./polyfill'); @@ -25,6 +28,7 @@ describe('http/polyfill', (): void => { }); it('polyfills with no exceptions (with fetch)', (): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (global as any).fetch = (): boolean => true; require('./polyfill'); diff --git a/packages/rpc-provider/src/http/send.spec.ts b/packages/rpc-provider/src/http/send.spec.ts index 52d52fafff..1f7f03ba0c 100644 --- a/packages/rpc-provider/src/http/send.spec.ts +++ b/packages/rpc-provider/src/http/send.spec.ts @@ -21,6 +21,7 @@ describe('send', (): void => { }); it('passes the body through correctly', (): Promise => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mock = mockHttp([{ method: 'test_body', reply: { @@ -31,6 +32,7 @@ describe('send', (): void => { return http .send('test_body', ['param']) .then((): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect((mock.body as any).test_body).toEqual({ id: 1, jsonrpc: '2.0', @@ -41,6 +43,7 @@ describe('send', (): void => { }); it('throws error when !response.ok', (): Promise => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mock = mockHttp([{ code: 500, method: 'test_error' @@ -49,7 +52,7 @@ describe('send', (): void => { return http .send('test_error', []) .catch((error): void => { - expect(error.message).toMatch(/\[500\]: Internal Server/); + expect((error as Error).message).toMatch(/\[500\]: Internal Server/); }); }); }); diff --git a/packages/rpc-provider/src/mock/index.ts b/packages/rpc-provider/src/mock/index.ts index f188fb5656..b6c0392629 100644 --- a/packages/rpc-provider/src/mock/index.ts +++ b/packages/rpc-provider/src/mock/index.ts @@ -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. -/* eslint-disable @typescript-eslint/camelcase */ +/* eslint-disable camelcase */ import { Header } from '@polkadot/types/interfaces'; import { Codec, Registry } from '@polkadot/types/types'; @@ -22,14 +22,15 @@ import { randomAsU8a } from '@polkadot/util-crypto'; const INTERVAL = 1000; const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply( - [], Object.values(jsonrpc).map((section): string[] => + [], + Object.values(jsonrpc).map((section): string[] => Object .values(section) .filter(({ isSubscription }) => isSubscription) .map(({ jsonrpc }) => jsonrpc) .concat('chain_subscribeNewHead') ) -); +) as string[]; const keyring = testKeyring({ type: 'ed25519' }); const l = logger('api-mock'); @@ -50,12 +51,14 @@ export default class Mock implements ProviderInterface { private prevNumber = new BN(-1); - private requests: Record any> = { - // eslint-disable-next-line @typescript-eslint/no-unused-vars + private requests: Record unknown> = { + // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-unsafe-member-access chain_getBlock: (hash: string): any => this.registry.createType('SignedBlock', rpcSignedBlock.result).toJSON(), // eslint-disable-next-line @typescript-eslint/no-unused-vars chain_getBlockHash: (blockNumber: number): string => '0x1234', + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access chain_getFinalizedHead: () => this.registry.createType('Header', rpcHeader.result).hash, + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access chain_getHeader: () => this.registry.createType('Header', rpcHeader.result).toJSON(), state_getKeys: (): string[] => [], state_getKeysPaged: (): string[] => [], @@ -112,7 +115,7 @@ export default class Mock implements ProviderInterface { } // eslint-disable-next-line @typescript-eslint/require-await - public async send (method: string, params: any[]): Promise { + public async send (method: string, params: any[]): Promise { if (!this.requests[method]) { throw new Error(`provider.send: Invalid method '${method}'`); } @@ -121,11 +124,11 @@ export default class Mock implements ProviderInterface { } // eslint-disable-next-line @typescript-eslint/require-await - public async subscribe (type: string, method: string, ...params: any[]): Promise { + public async subscribe (type: string, method: string, ...params: unknown[]): Promise { l.debug((): any => ['subscribe', method, params]); if (this.subscriptions[method]) { - const callback: MockStateSubscriptionCallback = params.pop(); + const callback = params.pop() as MockStateSubscriptionCallback; const id = ++this.subscriptionId; this.subscriptions[method].callbacks[id] = callback; diff --git a/packages/rpc-provider/src/mock/send.spec.ts b/packages/rpc-provider/src/mock/send.spec.ts index 87b00228b4..a51c368c53 100644 --- a/packages/rpc-provider/src/mock/send.spec.ts +++ b/packages/rpc-provider/src/mock/send.spec.ts @@ -18,7 +18,7 @@ describe('send', (): void => { return mock .send('something_invalid', []) .catch((error): void => { - expect(error.message).toMatch(/Invalid method/); + expect((error as Error).message).toMatch(/Invalid method/); }); }); diff --git a/packages/rpc-provider/src/mock/subscribe.spec.ts b/packages/rpc-provider/src/mock/subscribe.spec.ts index b4187a9c82..2a65eeec24 100644 --- a/packages/rpc-provider/src/mock/subscribe.spec.ts +++ b/packages/rpc-provider/src/mock/subscribe.spec.ts @@ -18,7 +18,7 @@ describe('subscribe', (): void => { return mock .subscribe('test', 'test_notFound') .catch((error): void => { - expect(error.message).toMatch(/Invalid method 'test_notFound'/); + expect((error as Error).message).toMatch(/Invalid method 'test_notFound'/); }); }); @@ -41,7 +41,7 @@ describe('subscribe', (): void => { }); it('calls back with new headers', (done): Promise => { - return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => { + return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: { number: number }): void => { if (header.number === 4) { done(); } @@ -51,7 +51,7 @@ describe('subscribe', (): void => { it('handles errors withing callbacks gracefully', (done): Promise => { let hasThrown = false; - return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => { + return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: { number: number }): void => { if (!hasThrown) { hasThrown = true; diff --git a/packages/rpc-provider/src/mock/types.ts b/packages/rpc-provider/src/mock/types.ts index 73def73563..4162f8d8ea 100644 --- a/packages/rpc-provider/src/mock/types.ts +++ b/packages/rpc-provider/src/mock/types.ts @@ -5,6 +5,7 @@ import { Server } from 'mock-socket'; import { Constructor } from '@polkadot/types/types'; +// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access export interface Global extends NodeJS.Global { WebSocket: Constructor; fetch: any; @@ -14,7 +15,7 @@ export interface Mock { body: Record; requests: number; server: Server; - done: () => {}; + done: () => Record; } export type MockStateSubscriptionCallback = (error: Error | null, value: any) => void; diff --git a/packages/rpc-provider/src/mock/unsubscribe.spec.ts b/packages/rpc-provider/src/mock/unsubscribe.spec.ts index 2ea572e78b..8bfbf13888 100644 --- a/packages/rpc-provider/src/mock/unsubscribe.spec.ts +++ b/packages/rpc-provider/src/mock/unsubscribe.spec.ts @@ -25,7 +25,7 @@ describe('unsubscribe', (): void => { return mock .unsubscribe('chain_newHead', 'chain_subscribeNewHead', 5) .catch((error): boolean => { - expect(error.message).toMatch(/Unable to find/); + expect((error as Error).message).toMatch(/Unable to find/); return false; }); @@ -41,7 +41,7 @@ describe('unsubscribe', (): void => { mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id) ) .catch((error): boolean => { - expect(error.message).toMatch(/Unable to find/); + expect((error as Error).message).toMatch(/Unable to find/); return false; }); diff --git a/packages/rpc-provider/src/types.ts b/packages/rpc-provider/src/types.ts index ed0c6c7931..c2e8346a7c 100644 --- a/packages/rpc-provider/src/types.ts +++ b/packages/rpc-provider/src/types.ts @@ -9,7 +9,7 @@ export interface JsonRpcObject { export interface JsonRpcRequest extends JsonRpcObject { method: string; - params: any[]; + params: unknown[]; } export interface JsonRpcResponseBaseError { @@ -20,14 +20,14 @@ export interface JsonRpcResponseBaseError { interface JsonRpcResponseSingle { error?: JsonRpcResponseBaseError; - result?: any; + result?: unknown; } interface JsonRpcResponseSubscription { method?: string; params: { error?: JsonRpcResponseBaseError; - result: any; + result: unknown; subscription: number; }; } diff --git a/packages/rpc-provider/src/ws/Provider.ts b/packages/rpc-provider/src/ws/Provider.ts index 8a434b5ae7..71b564ab2a 100644 --- a/packages/rpc-provider/src/ws/Provider.ts +++ b/packages/rpc-provider/src/ws/Provider.ts @@ -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. -/* eslint-disable @typescript-eslint/camelcase */ +/* eslint-disable camelcase */ import { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types'; @@ -108,6 +108,7 @@ export default class WsProvider implements WSProviderInterface { this.#websocket = null; if (autoConnectMs > 0) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises this.connect(); } } @@ -247,9 +248,9 @@ export default class WsProvider implements WSProviderInterface { * ``` */ public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise { - const id = await this.send(method, params, { callback, type }); + const id = await this.send(method, params, { callback, type }) as Promise; - return id as number; + return id; } /** @@ -270,9 +271,9 @@ export default class WsProvider implements WSProviderInterface { delete this.#subscriptions[subscription]; - const result = await this.send(method, [id]); + const result = await this.send(method, [id]) as Promise; - return result as boolean; + return result; } #emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => { @@ -289,6 +290,7 @@ export default class WsProvider implements WSProviderInterface { if (this.#autoConnectMs > 0) { setTimeout((): void => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises this.connect(); }, this.#autoConnectMs); } @@ -300,9 +302,10 @@ export default class WsProvider implements WSProviderInterface { } #onSocketMessage = (message: MessageEvent): void => { - l.debug((): any => ['received', message.data]); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + l.debug(() => ['received', message.data]); - const response: JsonRpcResponse = JSON.parse(message.data as string); + const response = JSON.parse(message.data as string) as JsonRpcResponse; return isUndefined(response.method) ? this.#onSocketMessageResult(response) @@ -320,7 +323,7 @@ export default class WsProvider implements WSProviderInterface { try { const { method, params, subscription } = handler; - const result = this.#coder.decodeResponse(response); + const result = this.#coder.decodeResponse(response) as string; // first send the result - in case of subs, we may have an update // immediately if we have some queued results already @@ -348,7 +351,7 @@ export default class WsProvider implements WSProviderInterface { } #onSocketMessageSubscribe = (response: JsonRpcResponse): void => { - const method = ALIASSES[response.method as string] || response.method; + const method = ALIASSES[response.method as string] || response.method || 'invalid'; const subId = `${method}::${response.params.subscription}`; const handler = this.#subscriptions[subId]; diff --git a/packages/rpc-provider/src/ws/getWSClass.spec.ts b/packages/rpc-provider/src/ws/getWSClass.spec.ts index 930b96ab44..00d76ab11d 100644 --- a/packages/rpc-provider/src/ws/getWSClass.spec.ts +++ b/packages/rpc-provider/src/ws/getWSClass.spec.ts @@ -21,6 +21,7 @@ describe('getWebScoket', (): void => { }); it('polyfills with no exceptions (with WebSocket)', async (): Promise => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (global as any).WebSocket = undefined; const WS = await getWSClass(); @@ -29,6 +30,7 @@ describe('getWebScoket', (): void => { }); it('polyfills with no exceptions (without WebSocket)', async (): Promise => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (global as any).WebSocket = (): boolean => true; const WS = await getWSClass(); diff --git a/packages/rpc-provider/src/ws/onOpen.spec.ts b/packages/rpc-provider/src/ws/onOpen.spec.ts index 3cd49600a0..4e19b3c986 100644 --- a/packages/rpc-provider/src/ws/onOpen.spec.ts +++ b/packages/rpc-provider/src/ws/onOpen.spec.ts @@ -33,6 +33,7 @@ describe('onOpen', (): void => { }], 0); const sendPromise = ws.send('test_queue', []); + // eslint-disable-next-line @typescript-eslint/no-floating-promises ws.connect(); return sendPromise.then((result): void => { diff --git a/packages/rpc-provider/src/ws/send.spec.ts b/packages/rpc-provider/src/ws/send.spec.ts index 446db05a38..8a53851503 100644 --- a/packages/rpc-provider/src/ws/send.spec.ts +++ b/packages/rpc-provider/src/ws/send.spec.ts @@ -50,7 +50,7 @@ describe('send', (): void => { return createWs() .send('test_encoding', [{ error: 'send error' }]) .catch((error): void => { - expect(error.message).toEqual('send error'); + expect((error as Error).message).toEqual('send error'); }); }); @@ -67,6 +67,7 @@ describe('send', (): void => { .send('test_body', ['param']) .then((): void => { expect( + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (mock.body as any).test_body ).toEqual('{"id":1,"jsonrpc":"2.0","method":"test_body","params":["param"]}'); }); @@ -84,7 +85,7 @@ describe('send', (): void => { return createWs() .send('test_error', []) .catch((error): void => { - expect(error.message).toMatch(/666: error/); + expect((error as Error).message).toMatch(/666: error/); }); }); diff --git a/packages/rpc-provider/test/mockHttp.ts b/packages/rpc-provider/test/mockHttp.ts index fdc2cda017..67fce6c8ba 100644 --- a/packages/rpc-provider/test/mockHttp.ts +++ b/packages/rpc-provider/test/mockHttp.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable */ + import nock from 'nock'; const TEST_HTTP_URL = 'http://localhost:9944'; diff --git a/packages/rpc-provider/test/mockWs.ts b/packages/rpc-provider/test/mockWs.ts index ebf18196c2..8c1662c732 100644 --- a/packages/rpc-provider/test/mockWs.ts +++ b/packages/rpc-provider/test/mockWs.ts @@ -7,7 +7,7 @@ import { Server } from 'mock-socket'; const TEST_WS_URL = 'ws://localhost:9955'; interface Scope { - body: { [index: string]: {} }; + body: { [index: string]: Record }; requests: number; server: Server; done: any; @@ -24,7 +24,7 @@ interface ErrorDef { interface ReplyDef { id: number; reply: { - result: any; + result: unknown; }; } @@ -50,7 +50,7 @@ function createReply ({ id, reply: { result } }: ReplyDef): any { } // scope definition returned -function mockWs (requests: { method: string }[], wsUrl: string = TEST_WS_URL): Scope { +function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope { const server = new Server(wsUrl); let requestCount = 0; @@ -68,11 +68,13 @@ function mockWs (requests: { method: string }[], wsUrl: string = TEST_WS_URL): S server.on('connection', (socket): void => { // FIXME This whole any mess is a mess socket.on('message', (body: any): void => { - const request = requests[requestCount]; - const response = (request as any).error - ? createError(request as any) - : createReply(request as any); + 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); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access scope.body[request.method] = body; requestCount++; diff --git a/packages/typegen/src/extractChain.ts b/packages/typegen/src/extractChain.ts index 2be99dd878..fb290bcca3 100644 --- a/packages/typegen/src/extractChain.ts +++ b/packages/typegen/src/extractChain.ts @@ -19,7 +19,7 @@ async function run (ws: string): Promise { ]); // output the chain info, for easy re-use - console.error(`// Generated via 'yarn run chain:info ${ws}'\n\nexport default {\n chain: '${chain.toString()}',\n genesisHash: '${api.genesisHash.toHex()}',\n specVersion: ${api.runtimeVersion.specVersion.toNumber()},\n ss58Format: ${props.ss58Format.unwrapOr(42)},\n tokenDecimals: ${props.tokenDecimals.unwrapOr(0)},\n tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT')}',\n metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}'\n};`); + console.error(`// Generated via 'yarn run chain:info ${ws}'\n\nexport default {\n chain: '${chain.toString()}',\n genesisHash: '${api.genesisHash.toHex()}',\n specVersion: ${api.runtimeVersion.specVersion.toNumber()},\n ss58Format: ${props.ss58Format.unwrapOr(42).toString()},\n tokenDecimals: ${props.tokenDecimals.unwrapOr(0).toString()},\n tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT').toString()}',\n metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}'\n};`); // show any missing types api.runtimeMetadata.getUniqTypes(false); diff --git a/packages/typegen/src/fromChain.ts b/packages/typegen/src/fromChain.ts index 4f3f598a2f..4cfd07729b 100644 --- a/packages/typegen/src/fromChain.ts +++ b/packages/typegen/src/fromChain.ts @@ -12,13 +12,13 @@ import generateQuery from './generate/query'; import generateTx from './generate/tx'; import { HEADER, writeFile } from './util'; -let websocket: any = null; +let websocket: WebSocket; function generate (metaHex: string, pkg: string | undefined, output: string, isStrict?: boolean): void { console.log(`Generating from metadata, ${formatNumber((metaHex.length - 2) / 2)} bytes`); const extraTypes = pkg - ? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) } + ? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record } : {}; generateConst(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict); @@ -38,7 +38,7 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS process.exit(0); } -function onSocketClose (event: any): void { +function onSocketClose (event: { code: number; reason: string }): void { console.error(`disconnected, code: '${event.code}' reason: '${event.reason}'`); process.exit(1); @@ -89,6 +89,7 @@ export default function main (): void { websocket.onopen = onSocketOpen; websocket.onmessage = (message: any): void => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access generate(JSON.parse(message.data).result, pkg, output, isStrict); }; }) @@ -96,6 +97,7 @@ export default function main (): void { process.exit(1); }); } else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access generate(require(path.join(process.cwd(), endpoint)).result, pkg, output, isStrict); } } diff --git a/packages/typegen/src/fromDefs.ts b/packages/typegen/src/fromDefs.ts index cf851a37eb..385df28391 100644 --- a/packages/typegen/src/fromDefs.ts +++ b/packages/typegen/src/fromDefs.ts @@ -24,10 +24,10 @@ export default function main (): void { }).argv; // eslint-disable-next-line @typescript-eslint/no-var-requires - const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')); + const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')) as Record; const userKeys = Object.keys(userDefs); const filteredBase = Object - .entries(substrateDefs) + .entries(substrateDefs as Record) .filter(([key]) => { if (userKeys.includes(key)) { console.warn(`Override found for ${key} in user types, ignoring in @polkadot/types`); @@ -37,7 +37,7 @@ export default function main (): void { return true; }) - .reduce((defs: any, [key, value]) => { + .reduce((defs: Record, [key, value]) => { defs[key] = value; return defs; diff --git a/packages/typegen/src/generate/consts.ts b/packages/typegen/src/generate/consts.ts index 705c79f812..631d4839f0 100644 --- a/packages/typegen/src/generate/consts.ts +++ b/packages/typegen/src/generate/consts.ts @@ -18,7 +18,7 @@ const generateForMetaTemplate = Handlebars.compile(template); /** @internal */ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record }>>, isStrict: boolean): void { writeFile(dest, (): string => { - const allTypes: Record }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes }; + const allTypes: Record }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes }; const imports = createImports(allTypes); const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => { return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs); diff --git a/packages/typegen/src/generate/interfaceRegistry.ts b/packages/typegen/src/generate/interfaceRegistry.ts index 3c8082bdb5..d07ae95473 100644 --- a/packages/typegen/src/generate/interfaceRegistry.ts +++ b/packages/typegen/src/generate/interfaceRegistry.ts @@ -9,6 +9,7 @@ import * as defaultDefinitions from '@polkadot/types/interfaces/definitions'; import * as defaultPrimitives from '@polkadot/types/primitive'; import { createImports, getDerivedTypes, readTemplate, setImports, writeFile } from '../util'; +import { ModuleTypes } from '../util/imports'; const primitiveClasses = { ...defaultPrimitives, @@ -19,9 +20,9 @@ const template = readTemplate('interfaceRegistry'); const generateInterfaceTypesTemplate = Handlebars.compile(template); /** @internal */ -export function generateInterfaceTypes (importDefinitions: { [importPath: string]: object }, dest: string): void { +export function generateInterfaceTypes (importDefinitions: { [importPath: string]: Record }, dest: string): void { writeFile(dest, (): string => { - Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {} as object); + Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {}); const imports = createImports(importDefinitions); const definitions = imports.definitions; @@ -46,7 +47,8 @@ export function generateInterfaceTypes (importDefinitions: { [importPath: string uniqueTypes.forEach((type) => { existingTypes[type] = true; - items.push(...getDerivedTypes(definitions, type, types[type], imports)); + + items.push(...getDerivedTypes(definitions, type, types[type] as string, imports)); }); }); diff --git a/packages/typegen/src/generate/query.ts b/packages/typegen/src/generate/query.ts index d831724bed..1688f45a8e 100644 --- a/packages/typegen/src/generate/query.ts +++ b/packages/typegen/src/generate/query.ts @@ -15,10 +15,11 @@ import { TypeRegistry } from '@polkadot/types/create'; import { stringCamelCase } from '@polkadot/util'; import { TypeImports, createImports, compareName, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util'; +import { ModuleTypes } from '../util/imports'; // From a storage entry metadata, we return [args, returnType] /** @internal */ -function entrySignature (allDefs: object, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] { +function entrySignature (allDefs: Record, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] { const format = (type: string): string => formatType(allDefs, type, imports); const outputType = unwrapStorageType(storageEntry.type, storageEntry.modifier.isOptional); @@ -59,7 +60,7 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor ]; } - throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name}`); + throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name.toString()}`); } const template = readTemplate('query'); diff --git a/packages/typegen/src/generate/rpc.ts b/packages/typegen/src/generate/rpc.ts index 37c6980ffd..3dcc1662c6 100644 --- a/packages/typegen/src/generate/rpc.ts +++ b/packages/typegen/src/generate/rpc.ts @@ -60,7 +60,8 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t if (args === undefined) { setImports(allDefs, imports, [def.type]); - args = def.params.map((param: any) => { + + args = def.params.map((param) => { const similarTypes = getSimilarTypes(definitions, registry, param.type, imports); setImports(allDefs, imports, [param.type, ...similarTypes]); diff --git a/packages/typegen/src/generate/tsDef.ts b/packages/typegen/src/generate/tsDef.ts index 702e1aeef8..3fbbe440a4 100644 --- a/packages/typegen/src/generate/tsDef.ts +++ b/packages/typegen/src/generate/tsDef.ts @@ -2,14 +2,14 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import Handlebars from 'handlebars'; - import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types'; +import { ModuleTypes } from '../util/imports'; +import Handlebars from 'handlebars'; import path from 'path'; import { getTypeDef } from '@polkadot/types/create'; import * as defaultDefinitions from '@polkadot/types/interfaces/definitions'; -import { isString, stringCamelCase, stringUpperFirst } from '@polkadot/util'; +import { isString, stringCamelCase, stringUpperFirst, assert } from '@polkadot/util'; import { TypeImports, createImports, exportInterface, exportType, readTemplate, formatType, setImports, writeFile } from '../util'; @@ -19,7 +19,7 @@ interface Imports extends TypeImports { // helper to generate a `readonly : ;` getter /** @internal */ -export function createGetter (definitions: object, name = '', type: string, imports: TypeImports): string { +export function createGetter (definitions: Record, name = '', type: string, imports: TypeImports): string { setImports(definitions, imports, [type]); return ` readonly ${name}: ${type};\n`; @@ -27,12 +27,12 @@ export function createGetter (definitions: object, name = '', type: string, impo /** @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars -function errorUnhandled (definitions: object, def: TypeDef, imports: TypeImports): string { - throw new Error(`Generate: ${name}: Unhandled type ${TypeDefInfo[def.info]}`); +function errorUnhandled (definitions: Record, def: TypeDef, imports: TypeImports): string { + throw new Error(`Generate: ${def.name || ''}: Unhandled type ${TypeDefInfo[def.info]}`); } /** @internal */ -function tsExport (definitions: object, def: TypeDef, imports: TypeImports): string { +function tsExport (definitions: Record, def: TypeDef, imports: TypeImports): string { return exportInterface(def.name, formatType(definitions, def, imports)); } @@ -46,7 +46,7 @@ const tsPlain = tsExport; const tsTuple = tsExport; /** @internal */ -function tsEnum (definitions: object, { name: enumName, sub }: TypeDef, imports: TypeImports): string { +function tsEnum (definitions: Record, { name: enumName, sub }: TypeDef, imports: TypeImports): string { setImports(definitions, imports, ['Enum']); const keys = (sub as TypeDef[]).map(({ info, name = '', type }): string => { @@ -64,21 +64,21 @@ function tsEnum (definitions: object, { name: enumName, sub }: TypeDef, imports: return `${isGetter}${asGetter}`; default: - throw new Error(`Enum: ${enumName}: Unhandled type ${TypeDefInfo[info]}`); + throw new Error(`Enum: ${enumName || 'undefined'}: Unhandled type ${TypeDefInfo[info]}`); } }); return exportInterface(enumName, 'Enum', keys.join('')); } -function tsInt (definitions: object, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string { +function tsInt (definitions: Record, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string { setImports(definitions, imports, [type]); return exportInterface(def.name, type); } /** @internal */ -function tsResultGetter (definitions: object, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string { +function tsResultGetter (definitions: Record, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string { const { info, type } = def; const asGetter = type === 'Null' ? '' @@ -97,7 +97,7 @@ function tsResultGetter (definitions: object, resultName = '', getter: 'Ok' | 'E } /** @internal */ -function tsResult (definitions: object, def: TypeDef, imports: TypeImports): string { +function tsResult (definitions: Record, def: TypeDef, imports: TypeImports): string { const [okDef, errorDef] = (def.sub as TypeDef[]); const inner = [ tsResultGetter(definitions, def.name, 'Error', errorDef, imports), @@ -110,18 +110,20 @@ function tsResult (definitions: object, def: TypeDef, imports: TypeImports): str } /** @internal */ -function tsSet (definitions: object, { name: setName, sub }: TypeDef, imports: TypeImports): string { +function tsSet (definitions: Record, { name: setName, sub }: TypeDef, imports: TypeImports): string { setImports(definitions, imports, ['Set']); - const types = (sub as TypeDef[]).map(({ name }): string => - createGetter(definitions, `is${name}`, 'boolean', imports) - ); + const types = (sub as TypeDef[]).map(({ name }): string => { + assert(!!name, 'Invalid TypeDef found, no name specified'); + + return createGetter(definitions, `is${name}`, 'boolean', imports); + }); return exportInterface(setName, 'Set', types.join('')); } /** @internal */ -function tsStruct (definitions: object, { name: structName, sub }: TypeDef, imports: TypeImports): string { +function tsStruct (definitions: Record, { name: structName, sub }: TypeDef, imports: TypeImports): string { setImports(definitions, imports, ['Struct']); const keys = (sub as TypeDef[]).map((typedef): string => { @@ -134,12 +136,12 @@ function tsStruct (definitions: object, { name: structName, sub }: TypeDef, impo } /** @internal */ -function tsUInt (definitions: object, def: TypeDef, imports: TypeImports): string { +function tsUInt (definitions: Record, def: TypeDef, imports: TypeImports): string { return tsInt(definitions, def, imports, 'UInt'); } /** @internal */ -function tsVec (definitions: object, def: TypeDef, imports: TypeImports): string { +function tsVec (definitions: Record, def: TypeDef, imports: TypeImports): string { const type = (def.sub as TypeDef).type; if (def.info === TypeDefInfo.VecFixed && type === 'u8') { @@ -152,7 +154,7 @@ function tsVec (definitions: object, def: TypeDef, imports: TypeImports): string } /** @internal */ -function generateInterfaces (definitions: object, { types }: { types: Record }, imports: Imports): [string, string][] { +function generateInterfaces (definitions: Record, { types }: { types: Record }, imports: Imports): [string, string][] { // handlers are defined externally to use - this means that when we do a // `generators[typedef.info](...)` TS will show any unhandled types. Rather // we are being explicit in having no handlers where we do not support (yet) @@ -194,7 +196,7 @@ const templateTypes = readTemplate('tsDef/types'); const generateTsDefTypesTemplate = Handlebars.compile(templateTypes); /** @internal */ -function generateTsDefFor (importDefinitions: { [importPath: string]: object }, defName: string, { types }: { types: Record }, outputDir: string): void { +function generateTsDefFor (importDefinitions: { [importPath: string]: Record }, defName: string, { types }: { types: Record }, outputDir: string): void { const imports = { ...createImports(importDefinitions, { types }), interfaces: [] } as Imports; const definitions = imports.definitions; const interfaces = generateInterfaces(definitions, { types }, imports); @@ -218,7 +220,7 @@ function generateTsDefFor (importDefinitions: { [importPath: string]: object }, } /** @internal */ -export function generateTsDef (importDefinitions: { [importPath: string]: object }, outputDir: string, generatingPackage: string): void { +export function generateTsDef (importDefinitions: { [importPath: string]: Record }, outputDir: string, generatingPackage: string): void { writeFile(path.join(outputDir, 'types.ts'), (): string => { const definitions = importDefinitions[generatingPackage]; diff --git a/packages/typegen/src/generate/tx.ts b/packages/typegen/src/generate/tx.ts index 43dcc82916..1b0cfaa891 100644 --- a/packages/typegen/src/generate/tx.ts +++ b/packages/typegen/src/generate/tx.ts @@ -39,7 +39,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr const modules = meta.asLatest.modules .sort(compareName) - .filter(({ calls }) => calls.unwrapOr([]).length) + .filter(({ calls }) => calls.unwrapOr([]).length !== 0) .map(({ calls, name }) => { setImports(allDefs, imports, ['Call', 'Extrinsic', 'SubmittableExtrinsic']); diff --git a/packages/typegen/src/metadataMd.ts b/packages/typegen/src/metadataMd.ts index 863f37f65a..7843906ba5 100644 --- a/packages/typegen/src/metadataMd.ts +++ b/packages/typegen/src/metadataMd.ts @@ -3,6 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { MetadataLatest } from '@polkadot/types/interfaces/metadata'; +import { Codec } from '@polkadot/types/types'; import fs from 'fs'; import Decorated from '@polkadot/metadata/Decorated'; @@ -81,8 +82,9 @@ function renderPage (page: Page): string { Object.keys(item).filter((i) => i !== 'name').forEach((bullet) => { md += `\n- **${bullet}**: ${ + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions item[bullet] instanceof Vec - ? documentationVecToMarkdown(item[bullet] as Vec, 2) + ? documentationVecToMarkdown(item[bullet] as Vec, 2).toString() : item[bullet] }`; }); @@ -94,8 +96,9 @@ function renderPage (page: Page): string { return md; } -function sortByName (a: T, b: T): number { +function sortByName (a: T, b: T): number { // case insensitive (all-uppercase) sorting + // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access return a.name.toString().toUpperCase().localeCompare(b.name.toString().toUpperCase()); } @@ -119,6 +122,7 @@ function addRpc (): string { .map((methodName) => { const method = section.rpc[methodName]; const args = method.params.map(({ isOptional, name, type }: any): string => { + // eslint-disable-next-line @typescript-eslint/restrict-plus-operands return name + (isOptional ? '?' : '') + ': `' + type + '`'; }).join(', '); const type = '`' + method.type + '`'; @@ -155,7 +159,7 @@ function addConstants (metadata: MetadataLatest): string { return { interface: '`' + `api.consts.${sectionName}.${methodName}` + '`', - name: `${methodName}: ` + '`' + func.type + '`', + name: `${methodName}: ` + '`' + func.type.toString() + '`', ...(func.documentation.length && { summary: func.documentation }) }; }), @@ -196,7 +200,8 @@ function addStorage (metadata: MetadataLatest): string { }; }); - const knownSection = JSON.parse(fs.readFileSync('docs/substrate/storage-known-section.json', 'utf8')); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const knownSection: any = JSON.parse(fs.readFileSync('docs/substrate/storage-known-section.json', 'utf8')); return renderPage({ description: DESC_STORAGE, @@ -211,7 +216,7 @@ function addExtrinsics (metadata: MetadataLatest): string { description: DESC_EXTRINSICS, sections: metadata.modules .sort(sortByName) - .filter((meta) => !meta.calls.isNone && meta.calls.unwrap().length) + .filter((meta) => !meta.calls.isNone && meta.calls.unwrap().length !== 0) .map((meta) => { const sectionName = stringCamelCase(meta.name.toString()); @@ -220,7 +225,7 @@ function addExtrinsics (metadata: MetadataLatest): string { .sort(sortByName) .map((func) => { const methodName = stringCamelCase(func.name.toString()); - const args = Call.filterOrigin(func).map(({ name, type }): string => `${name}: ` + '`' + type + '`').join(', '); + const args = Call.filterOrigin(func).map(({ name, type }) => `${name.toString()}: ` + '`' + type.toString() + '`').join(', '); return { interface: '`' + `api.tx.${sectionName}.${methodName}` + '`', @@ -241,13 +246,13 @@ function addEvents (metadata: MetadataLatest): string { description: DESC_EVENTS, sections: metadata.modules .sort(sortByName) - .filter((meta) => !meta.events.isNone && meta.events.unwrap().length) + .filter((meta) => !meta.events.isNone && meta.events.unwrap().length !== 0) .map((meta) => ({ items: meta.events.unwrap() .sort(sortByName) .map((func) => { const methodName = func.name.toString(); - const args = func.args.map((type): string => '`' + type + '`').join(', '); + const args = func.args.map((type): string => '`' + type.toString() + '`').join(', '); return { name: `${methodName}(${args})`, diff --git a/packages/typegen/src/util/derived.ts b/packages/typegen/src/util/derived.ts index 11655b97f2..712a92dd53 100644 --- a/packages/typegen/src/util/derived.ts +++ b/packages/typegen/src/util/derived.ts @@ -24,7 +24,7 @@ import { isChildClass } from '@polkadot/util'; import { isCompactEncodable } from './class'; import { formatType } from './formatting'; -import { setImports, TypeImports } from './imports'; +import { setImports, ModuleTypes, TypeImports } from './imports'; function arrayToStrType (arr: string[]): string { return `${arr.map((c): string => `'${c}'`).join(' | ')}`; @@ -34,9 +34,9 @@ const voteConvictions = arrayToStrType(AllConvictions); // From `T`, generate `Compact, Option, Vec` /** @internal */ -export function getDerivedTypes (definitions: object, type: string, primitiveName: string, imports: TypeImports): string[] { +export function getDerivedTypes (definitions: Record, type: string, primitiveName: string, imports: TypeImports): string[] { // `primitiveName` represents the actual primitive type our type is mapped to - const isCompact = isCompactEncodable((primitiveClasses as any)[primitiveName]); + const isCompact = isCompactEncodable((primitiveClasses as Record)[primitiveName]); const def = getTypeDef(type); setImports(definitions, imports, ['Option', 'Vec', isCompact ? 'Compact' : '']); @@ -73,7 +73,7 @@ export function getDerivedTypes (definitions: object, type: string, primitiveNam // - if param instanceof AbstractInt, then param: u64 | Uint8array | AnyNumber // etc /** @internal */ -export function getSimilarTypes (definitions: object, registry: Registry, _type: string, imports: TypeImports): string[] { +export function getSimilarTypes (definitions: Record, registry: Registry, _type: string, imports: TypeImports): string[] { const typeParts = _type.split('::'); const type = typeParts[typeParts.length - 1]; const possibleTypes = [type]; diff --git a/packages/typegen/src/util/formatting.ts b/packages/typegen/src/util/formatting.ts index 4fb72b39d9..74ef273a14 100644 --- a/packages/typegen/src/util/formatting.ts +++ b/packages/typegen/src/util/formatting.ts @@ -9,9 +9,17 @@ import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types'; import { getTypeDef } from '@polkadot/types/create'; import { paramsNotation } from '@polkadot/types/codec/utils'; -import { setImports, TypeImports } from './imports'; +import { setImports, ModuleTypes, TypeImports } from './imports'; import { readTemplate } from './file'; +interface This { + imports: TypeImports; + types: { + file: string; + types: string[]; + }[] +} + const TYPES_NON_PRIMITIVE = ['Metadata']; export const HEADER = (type: 'chain' | 'defs'): string => `// Auto-generated via \`yarn polkadot-types-from-${type}\`, do not edit\n/* eslint-disable */\n\n`; @@ -23,9 +31,8 @@ Handlebars.registerPartial({ Handlebars.registerHelper({ imports () { - const { imports, types } = this as any; - - return [ + const { imports, types } = this as unknown as This; + const defs = [ { file: '@polkadot/types/types', types: Object.keys(imports.typesTypes) @@ -34,7 +41,7 @@ Handlebars.registerHelper({ file: '@polkadot/types/codec', types: Object .keys(imports.codecTypes) - .filter((name): boolean => name !== 'Tuple') + .filter((name) => name !== 'Tuple') }, { file: '@polkadot/types/extrinsic', @@ -48,25 +55,27 @@ Handlebars.registerHelper({ file: '@polkadot/types/primitive', types: Object .keys(imports.primitiveTypes) - .filter((name): boolean => !TYPES_NON_PRIMITIVE.includes(name)) + .filter((name) => !TYPES_NON_PRIMITIVE.includes(name)) }, { file: '@polkadot/types', types: Object .keys(imports.primitiveTypes) - .filter((name): boolean => TYPES_NON_PRIMITIVE.includes(name)) + .filter((name) => TYPES_NON_PRIMITIVE.includes(name)) }, ...types - ].reduce((result, { file, types }): string => { + ]; + + return defs.reduce((result, { file, types }): string => { return types.length ? `${result}import { ${types.sort().join(', ')} } from '${file}';\n` : result; }, ''); }, - trim (options) { + trim (options: { fn: (self: unknown) => string }) { return options.fn(this).trim(); }, - upper (options) { + upper (options: { fn: (self: unknown) => string }) { return options.fn(this).toUpperCase(); } }); @@ -172,7 +181,7 @@ function formatVec (inner: string): string { * Correctly format a given type */ /** @internal */ -export function formatType (definitions: object, type: string | TypeDef, imports: TypeImports): string { +export function formatType (definitions: Record, type: string | TypeDef, imports: TypeImports): string { let typeDef: TypeDef; if (typeof type === 'string') { diff --git a/packages/typegen/src/util/imports.ts b/packages/typegen/src/util/imports.ts index 6975cc5325..36894599c1 100644 --- a/packages/typegen/src/util/imports.ts +++ b/packages/typegen/src/util/imports.ts @@ -10,6 +10,10 @@ import * as extrinsicClasses from '@polkadot/types/extrinsic'; import * as genericClasses from '@polkadot/types/generic'; import * as primitiveClasses from '@polkadot/types/primitive'; +export interface ModuleTypes { + types: Record; +} + // these map all the codec and primitive types for import, see the TypeImports below. If // we have an unseen type, it is `undefined`/`false`, if we need to import it, it is `true` type TypeExist = Record; @@ -26,14 +30,14 @@ export interface TypeImports { localTypes: TypeExistMap; // `import {} from '../something'` primitiveTypes: TypeExist; // `import {} from '@polkadot/types/primitive` typesTypes: TypeExist; // `import {} from '@polkadot/types/types` - definitions: object; // all definitions + definitions: Record; // all definitions typeToModule: Record; } // Maps the types as found to the source location. This is used to generate the // imports in the output file, dep-duped and sorted /** @internal */ -export function setImports (allDefs: object, imports: TypeImports, types: string[]): void { +export function setImports (allDefs: Record, imports: TypeImports, types: string[]): void { const { codecTypes, extrinsicTypes, genericTypes, ignoredTypes, localTypes, primitiveTypes, typesTypes } = imports; types.forEach((type): void => { @@ -41,13 +45,13 @@ export function setImports (allDefs: object, imports: TypeImports, types: string // do nothing } else if (['AnyNumber', 'CallFunction', 'Codec', 'IExtrinsic', 'ITuple'].includes(type)) { typesTypes[type] = true; - } else if ((codecClasses as any)[type]) { + } else if ((codecClasses as Record)[type]) { codecTypes[type] = true; - } else if ((extrinsicClasses as any)[type]) { + } else if ((extrinsicClasses as Record)[type]) { extrinsicTypes[type] = true; - } else if ((genericClasses as any)[type]) { + } else if ((genericClasses as Record)[type]) { genericTypes[type] = true; - } else if ((primitiveClasses as any)[type] || type === 'Metadata') { + } else if ((primitiveClasses as Record)[type] || type === 'Metadata') { primitiveTypes[type] = true; } else if (type.includes('<') || type.includes('(') || (type.includes('[') && !type.includes('|'))) { // If the type is a bit special (tuple, fixed u8, nested type...), then we @@ -84,8 +88,8 @@ export function setImports (allDefs: object, imports: TypeImports, types: string // Create an Imports object, can be pre-filled with `ignoredTypes` /** @internal */ -export function createImports (importDefinitions: Record, { types }: { types: Record } = { types: {} }): TypeImports { - const definitions = {} as Record; +export function createImports (importDefinitions: Record>, { types }: ModuleTypes = { types: {} }): TypeImports { + const definitions = {} as Record; const typeToModule = {} as Record; Object.entries(importDefinitions).forEach(([packagePath, packageDef]): void => { diff --git a/packages/types/src/codec/AbstractArray.ts b/packages/types/src/codec/AbstractArray.ts index 2e23ab8f24..83a3ba3f40 100644 --- a/packages/types/src/codec/AbstractArray.ts +++ b/packages/types/src/codec/AbstractArray.ts @@ -62,7 +62,7 @@ export default abstract class AbstractArray extends Array im /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return compareArray(this, other); } @@ -141,7 +141,7 @@ export default abstract class AbstractArray extends Array im * @param callbackfn The filter function * @param thisArg The `this` object to apply the result to */ - public filter (callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[] { + public filter (callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: unknown): T[] { return this.toArray().filter(callbackfn, thisArg); } @@ -150,14 +150,14 @@ export default abstract class AbstractArray extends Array im * @param callbackfn The mapping function * @param thisArg The `this` onject to apply the result to */ - public map (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[] { + public map (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: unknown): U[] { return this.toArray().map(callbackfn, thisArg); } /** * @description Checks if the array includes a specific value */ - public includes (check: any): boolean { - return this.some((value: T): boolean => value.eq(check)); + public includes (check: unknown): boolean { + return this.some((value: T) => value.eq(check)); } } diff --git a/packages/types/src/codec/AbstractInt.ts b/packages/types/src/codec/AbstractInt.ts index b3aa3ee861..739b0a2feb 100644 --- a/packages/types/src/codec/AbstractInt.ts +++ b/packages/types/src/codec/AbstractInt.ts @@ -25,7 +25,7 @@ function decodeAbstracIntU8a (value: Uint8Array, bitLength: UIntBitLength, isNeg // NOTE When passing u8a in (typically from decoded data), it is always Little Endian return u8aToBn(value.subarray(0, bitLength / 8), { isLe: true, isNegative }).toString(); } catch (error) { - throw new Error(`AbstractInt: failed on ${JSON.stringify(value)}:: ${error.message}`); + throw new Error(`AbstractInt: failed on ${JSON.stringify(value)}:: ${(error as Error).message}`); } } @@ -111,13 +111,13 @@ export default abstract class AbstractInt extends BN implements Codec { * @description Compares the value of the input to see if there is a match */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { // Here we are actually overriding the built-in .eq to take care of both // number and BN inputs (no `.eqn` needed) - numbers will be converted return super.eq( isHex(other) ? hexToBn(other.toString(), { isLe: false, isNegative: this.#isSigned }) - : bnToBn(other) + : bnToBn(other as string) ); } diff --git a/packages/types/src/codec/BTreeMap.spec.ts b/packages/types/src/codec/BTreeMap.spec.ts index dc501ea1ce..39b97103d5 100644 --- a/packages/types/src/codec/BTreeMap.spec.ts +++ b/packages/types/src/codec/BTreeMap.spec.ts @@ -36,7 +36,7 @@ describe('BTreeMap', (): void => { it('decodes within more complicated types', (): void => { const s = new Struct(registry, { placeholder: U32, - value: 'BTreeMap' as any + value: 'BTreeMap' as 'u32' }); s.set('value', new (BTreeMap.with(Text, U32))(registry, mockU32TextMap)); diff --git a/packages/types/src/codec/BTreeMap.ts b/packages/types/src/codec/BTreeMap.ts index b9491c9f53..8e144c2fc6 100644 --- a/packages/types/src/codec/BTreeMap.ts +++ b/packages/types/src/codec/BTreeMap.ts @@ -9,7 +9,7 @@ import CodecMap from './Map'; export default class BTreeMap extends CodecMap { public static with (keyType: Constructor | keyof InterfaceTypes, valType: Constructor | keyof InterfaceTypes): Constructor> { return class extends BTreeMap { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: Uint8Array | string | Map) { super(registry, 'BTreeMap', keyType, valType, value); } }; diff --git a/packages/types/src/codec/BTreeSet.ts b/packages/types/src/codec/BTreeSet.ts index dfdc5fc819..1a94881ee1 100644 --- a/packages/types/src/codec/BTreeSet.ts +++ b/packages/types/src/codec/BTreeSet.ts @@ -39,7 +39,8 @@ function decodeSetFromSet (registry: Registry, ValClass try { output.add((val instanceof ValClass) ? val : new ValClass(registry, val)); } catch (error) { - console.error('Failed to decode BTreeSet key or value:', error.message); + console.error('Failed to decode BTreeSet key or value:', (error as Error).message); + throw error; } }); @@ -61,7 +62,7 @@ function decodeSetFromSet (registry: Registry, ValClass * @param jsonSet * @internal */ -function decodeSet (registry: Registry, valType: Constructor | keyof InterfaceTypes, value: Uint8Array | string | Set): Set { +function decodeSet (registry: Registry, valType: Constructor | keyof InterfaceTypes, value?: Uint8Array | string | Set): Set { if (!value) { return new Set(); } @@ -84,7 +85,7 @@ export default class BTreeSet extends Set implements readonly #ValClass: Constructor; - constructor (registry: Registry, valType: Constructor | keyof InterfaceTypes, rawValue: any) { + constructor (registry: Registry, valType: Constructor | keyof InterfaceTypes, rawValue?: Uint8Array | string | Set) { super(decodeSet(registry, valType, rawValue)); this.registry = registry; @@ -93,7 +94,7 @@ export default class BTreeSet extends Set implements public static with (valType: Constructor | keyof InterfaceTypes): Constructor> { return class extends BTreeSet { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: Uint8Array | string | Set) { super(registry, valType, value); } }; @@ -129,7 +130,7 @@ export default class BTreeSet extends Set implements /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return compareSet(this, other); } @@ -144,7 +145,7 @@ export default class BTreeSet extends Set implements * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information */ public toHuman (isExtended?: boolean): AnyJson { - const json: any = []; + const json: AnyJson = []; this.forEach((v: V) => { json.push(v.toHuman(isExtended)); @@ -157,7 +158,7 @@ export default class BTreeSet extends Set implements * @description Converts the Object to JSON, typically used for RPC transfers */ public toJSON (): AnyJson { - const json: any = []; + const json: AnyJson = []; this.forEach((v: V) => { json.push(v.toJSON()); diff --git a/packages/types/src/codec/Base.ts b/packages/types/src/codec/Base.ts index 041e950d96..f4be89bf49 100644 --- a/packages/types/src/codec/Base.ts +++ b/packages/types/src/codec/Base.ts @@ -18,7 +18,7 @@ export default abstract class Base implements Codec { protected readonly _raw: T; - protected constructor (registry: Registry, value?: any) { + protected constructor (registry: Registry, value: T) { this.registry = registry; this._raw = value; } @@ -47,7 +47,7 @@ export default abstract class Base implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return this._raw.eq(other); } diff --git a/packages/types/src/codec/Compact.spec.ts b/packages/types/src/codec/Compact.spec.ts index d12afdc129..26d1bc8b6f 100644 --- a/packages/types/src/codec/Compact.spec.ts +++ b/packages/types/src/codec/Compact.spec.ts @@ -109,7 +109,7 @@ describe('Compact', (): void => { describe('constructor', (): void => { it('has support for BigInt', (): void => { expect( - new Compact(registry, 'u128', 123_456_789_000_123_456_789n).toHuman() + new Compact(registry, 'u128', 123456789000123456789n).toHuman() ).toEqual('123,456,789,000,123,456,789'); }); diff --git a/packages/types/src/codec/Compact.ts b/packages/types/src/codec/Compact.ts index 0da2381208..08661ac08e 100644 --- a/packages/types/src/codec/Compact.ts +++ b/packages/types/src/codec/Compact.ts @@ -28,12 +28,14 @@ export interface CompactEncodable extends Codec { */ export default class Compact extends Base implements ICompact { constructor (registry: Registry, Type: Constructor | keyof InterfaceTypes, value: Compact | AnyNumber = 0) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore super(registry, Compact.decodeCompact(registry, typeToConstructor(registry, Type), value)); } public static with (Type: Constructor | keyof InterfaceTypes): Constructor> { return class extends Compact { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: Compact | AnyNumber) { super(registry, Type, value); } }; @@ -79,7 +81,7 @@ export default class Compact extends Base impleme /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return this._raw.eq( other instanceof Compact ? other._raw diff --git a/packages/types/src/codec/Date.ts b/packages/types/src/codec/Date.ts index 6aa3cf415e..1c1d7a1748 100644 --- a/packages/types/src/codec/Date.ts +++ b/packages/types/src/codec/Date.ts @@ -33,13 +33,13 @@ export default class CodecDate extends Date implements Codec { } /** @internal */ - public static decodeDate (value: CodecDate | Date | AnyNumber): Date { + public static decodeDate (value: CodecDate | Date | AnyNumber | unknown): Date { if (value instanceof Date) { return value; } else if (isU8a(value)) { value = u8aToBn(value.subarray(0, BITLENGTH / 8), true); } else if (isString(value)) { - value = new BN(value, 10, 'le'); + value = new BN(value.toString(), 10, 'le'); } return new Date( @@ -71,7 +71,7 @@ export default class CodecDate extends Date implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return CodecDate.decodeDate(other).getTime() === this.getTime(); } diff --git a/packages/types/src/codec/Enum.ts b/packages/types/src/codec/Enum.ts index 3b6ba5afb9..19b529c10b 100644 --- a/packages/types/src/codec/Enum.ts +++ b/packages/types/src/codec/Enum.ts @@ -123,7 +123,7 @@ export default class Enum extends Base { private _isBasic: boolean; - constructor (registry: Registry, def: Record | string[], value?: any, index?: number) { + constructor (registry: Registry, def: Record | string[], value?: unknown, index?: number) { const defInfo = extractDef(registry, def); const decoded = decodeEnum(registry, defInfo.def, value, index); @@ -137,7 +137,7 @@ export default class Enum extends Base { public static with (Types: Record | string[]): EnumConstructor { return class extends Enum { - constructor (registry: Registry, value?: any, index?: number) { + constructor (registry: Registry, value?: unknown, index?: number) { super(registry, Types, value, index); Object.keys(this._def).forEach((_key): void => { @@ -146,6 +146,7 @@ export default class Enum extends Base { const iskey = `is${name}`; // do not clobber existing properties on the object + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (isUndefined((this as any)[iskey])) { Object.defineProperty(this, iskey, { enumerable: true, @@ -153,10 +154,12 @@ export default class Enum extends Base { }); } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (isUndefined((this as any)[askey])) { Object.defineProperty(this, askey, { enumerable: true, get: (): Codec => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access assert((this as any)[iskey], `Cannot convert '${this.type}' via ${askey}`); return this.value; @@ -234,7 +237,7 @@ export default class Enum extends Base { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { // cater for the case where we only pass the enum index if (isNumber(other)) { return this.toNumber() === other; diff --git a/packages/types/src/codec/HashMap.ts b/packages/types/src/codec/HashMap.ts index fc8f150a0c..03b3e59a65 100644 --- a/packages/types/src/codec/HashMap.ts +++ b/packages/types/src/codec/HashMap.ts @@ -9,7 +9,7 @@ import CodecMap from './Map'; export default class HashMap extends CodecMap { public static with (keyType: Constructor | keyof InterfaceTypes, valType: Constructor | keyof InterfaceTypes): Constructor> { return class extends HashMap { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: Uint8Array | string | Map) { super(registry, 'HashMap', keyType, valType, value); } }; diff --git a/packages/types/src/codec/Int.ts b/packages/types/src/codec/Int.ts index 4ae326538d..760ddb53ca 100644 --- a/packages/types/src/codec/Int.ts +++ b/packages/types/src/codec/Int.ts @@ -23,7 +23,7 @@ export default class Int extends AbstractInt { public static with (bitLength: UIntBitLength, typeName?: string): Constructor { return class extends Int { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: AnyNumber) { super(registry, value, bitLength); } diff --git a/packages/types/src/codec/Linkage.spec.ts b/packages/types/src/codec/Linkage.spec.ts index dd60b5686d..4e9661d0ff 100644 --- a/packages/types/src/codec/Linkage.spec.ts +++ b/packages/types/src/codec/Linkage.spec.ts @@ -26,7 +26,7 @@ describe('Linkage', (): void => { ).toEqual(LINKA); expect( registry.createType( - 'Linkage' as any, + 'Linkage' as 'u32', '0x0001da30b68f54f686f586ddb29de12b682dd8bd1404566fb8a8db5dec20aa5b6b36' ).toHuman() ).toEqual(LINKA); @@ -34,7 +34,7 @@ describe('Linkage', (): void => { // actual check expect( registry.createType( - '(ValidatorPrefs, Linkage)' as any, + '(ValidatorPrefs, Linkage)' as 'u32', '0x0284d7170001da30b68f54f686f586ddb29de12b682dd8bd1404566fb8a8db5dec20aa5b6b36' ).toHuman() ).toEqual([PREFS, LINKA]); diff --git a/packages/types/src/codec/Linkage.ts b/packages/types/src/codec/Linkage.ts index ccc4fa3efb..ab3ddbbf21 100644 --- a/packages/types/src/codec/Linkage.ts +++ b/packages/types/src/codec/Linkage.ts @@ -18,19 +18,19 @@ const EMPTY = new Uint8Array(); * @description The wrapper for the result from a LinkedMap */ export default class Linkage extends Struct { - constructor (registry: Registry, Type: Constructor | keyof InterfaceTypes, value?: any) { + constructor (registry: Registry, Type: Constructor | keyof InterfaceTypes, value?: unknown) { super(registry, { previous: Option.with(Type), // eslint-disable-next-line sort-keys next: Option.with(Type) - }, value); + }, value as string); console.error([...this.entries()]); } public static withKey (Type: Constructor | keyof InterfaceTypes): Constructor> { return class extends Linkage { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: unknown) { super(registry, Type, value); } }; diff --git a/packages/types/src/codec/Map.ts b/packages/types/src/codec/Map.ts index 3aff3a6f4e..a077a8a1d0 100644 --- a/packages/types/src/codec/Map.ts +++ b/packages/types/src/codec/Map.ts @@ -48,7 +48,7 @@ function decodeMapFromMap (reg : new ValClass(registry, val) ); } catch (error) { - console.error('Failed to decode Map key or value:', error.message); + console.error('Failed to decode Map key or value:', (error as Error).message); throw error; } @@ -72,7 +72,7 @@ function decodeMapFromMap (reg * @param jsonMap * @internal */ -function decodeMap (registry: Registry, keyType: Constructor | keyof InterfaceTypes, valType: Constructor | keyof InterfaceTypes, value: Uint8Array | string | Map): Map { +function decodeMap (registry: Registry, keyType: Constructor | keyof InterfaceTypes, valType: Constructor | keyof InterfaceTypes, value?: Uint8Array | string | Map): Map { const KeyClass = typeToConstructor(registry, keyType); const ValClass = typeToConstructor(registry, valType); @@ -100,7 +100,7 @@ export default class CodecMap readonly #type: string; - constructor (registry: Registry, type: 'BTreeMap' | 'HashMap', keyType: Constructor | keyof InterfaceTypes, valType: Constructor | keyof InterfaceTypes, rawValue: any) { + constructor (registry: Registry, type: 'BTreeMap' | 'HashMap', keyType: Constructor | keyof InterfaceTypes, valType: Constructor | keyof InterfaceTypes, rawValue?: Uint8Array | string | Map) { super(decodeMap(registry, keyType, valType, rawValue)); this.registry = registry; @@ -139,7 +139,7 @@ export default class CodecMap /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return compareMap(this, other); } @@ -154,7 +154,7 @@ export default class CodecMap * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information */ public toHuman (isExtended?: boolean): AnyJson { - const json: any = {}; + const json: AnyJson = {}; this.forEach((v: V, k: K) => { json[k.toString()] = v.toHuman(isExtended); @@ -167,7 +167,7 @@ export default class CodecMap * @description Converts the Object to JSON, typically used for RPC transfers */ public toJSON (): AnyJson { - const json: any = {}; + const json: AnyJson = {}; this.forEach((v: V, k: K) => { json[k.toString()] = v.toJSON(); diff --git a/packages/types/src/codec/Option.spec.ts b/packages/types/src/codec/Option.spec.ts index df46a471f9..eedcce580b 100644 --- a/packages/types/src/codec/Option.spec.ts +++ b/packages/types/src/codec/Option.spec.ts @@ -10,7 +10,7 @@ import Option from './Option'; const registry = new TypeRegistry(); -const testDecode = (type: string, input: any, expected: any): void => +const testDecode = (type: string, input: any, expected: string): void => it(`can decode from ${type}`, (): void => { const o = new Option(registry, Text, input); @@ -18,11 +18,11 @@ const testDecode = (type: string, input: any, expected: any): void => expect(o.isNone).toBe(!expected.length); }); -const testEncode = (to: string, expected: any): void => +const testEncode = (to: 'toHex' | 'toString' | 'toU8a', expected: any): void => it(`can encode ${to}`, (): void => { const e = new Option(registry, Text, 'foo'); - expect((e as any)[to]()).toEqual(expected); + expect(e[to]()).toEqual(expected); }); describe('Option', (): void => { diff --git a/packages/types/src/codec/Option.ts b/packages/types/src/codec/Option.ts index f5f9aa5a2d..e33bfa82fb 100644 --- a/packages/types/src/codec/Option.ts +++ b/packages/types/src/codec/Option.ts @@ -18,7 +18,7 @@ function decodeOptionU8a (registry: Registry, Type: Constructor, value: Uint8Arr } /** @internal */ -function decodeOption (registry: Registry, typeName: Constructor | keyof InterfaceTypes, value?: any): Codec { +function decodeOption (registry: Registry, typeName: Constructor | keyof InterfaceTypes, value?: unknown): Codec { if (isNull(value) || isUndefined(value) || value instanceof Null) { return new Null(registry); } @@ -51,7 +51,9 @@ function decodeOption (registry: Registry, typeName: Constructor | keyof Interfa export default class Option extends Base { readonly #Type: Constructor; - constructor (registry: Registry, typeName: Constructor | keyof InterfaceTypes, value?: any) { + constructor (registry: Registry, typeName: Constructor | keyof InterfaceTypes, value?: unknown) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore super(registry, decodeOption(registry, typeName, value)); this.#Type = typeToConstructor(registry, typeName); @@ -59,7 +61,7 @@ export default class Option extends Base { public static with (Type: Constructor | keyof InterfaceTypes): Constructor> { return class extends Option { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: unknown) { super(registry, Type, value); } }; @@ -104,7 +106,7 @@ export default class Option extends Base { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { if (other instanceof Option) { return (this.isSome === other.isSome) && this.value.eq(other.value); } diff --git a/packages/types/src/codec/Raw.ts b/packages/types/src/codec/Raw.ts index e035c8a4e9..8eef2f88e5 100644 --- a/packages/types/src/codec/Raw.ts +++ b/packages/types/src/codec/Raw.ts @@ -74,7 +74,7 @@ export default class Raw extends Uint8Array implements IU8a { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { if (other instanceof Uint8Array) { return (this.length === other.length) && !this.some((value, index): boolean => value !== other[index]); diff --git a/packages/types/src/codec/Result.ts b/packages/types/src/codec/Result.ts index 8cc1bf7577..dd20b6f894 100644 --- a/packages/types/src/codec/Result.ts +++ b/packages/types/src/codec/Result.ts @@ -14,7 +14,7 @@ import Enum from './Enum'; * A Result maps to the Rust Result type, that can either wrap a success or error value */ export default class Result extends Enum { - constructor (registry: Registry, Ok: Constructor | keyof InterfaceTypes, Error: Constructor | keyof InterfaceTypes, value?: any) { + constructor (registry: Registry, Ok: Constructor | keyof InterfaceTypes, Error: Constructor | keyof InterfaceTypes, value?: unknown) { // NOTE This is order-dependent, Ok (with index 0) needs to be first // eslint-disable-next-line sort-keys super(registry, { Ok, Error }, value); @@ -22,7 +22,7 @@ export default class Result extends Enum { public static with (Types: { Ok: Constructor | keyof InterfaceTypes; Error: Constructor | keyof InterfaceTypes }): Constructor> { return class extends Result { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: unknown) { super(registry, Types.Ok, Types.Error, value); } }; @@ -71,8 +71,8 @@ export default class Result extends Enum { * @description Returns the base runtime type name for this instance */ public toRawType (): string { - const Types = this._toRawStruct() as { Ok: any; Error: any }; + const Types = this._toRawStruct() as { Ok: unknown; Error: unknown }; - return `Result<${Types.Ok},${Types.Error}>`; + return `Result<${Types.Ok as string},${Types.Error as string}>`; } } diff --git a/packages/types/src/codec/Set.ts b/packages/types/src/codec/Set.ts index 35b6fed5b0..277e0006fd 100644 --- a/packages/types/src/codec/Set.ts +++ b/packages/types/src/codec/Set.ts @@ -44,7 +44,7 @@ function decodeSetNumber (setValues: SetValues, _value: BN | number): string[] { const computed = encodeSet(setValues, result); - assert(bn.eq(computed), `Set: Mismatch decoding '${bn}', computed as '${computed}' with ${result}`); + assert(bn.eq(computed), `Set: Mismatch decoding '${bn.toString()}', computed as '${computed.toString()}' with ${result.join(', ')}`); return result; } @@ -96,14 +96,15 @@ export default class CodecSet extends Set implements Codec { public static with (values: SetValues, bitLength?: number): Constructor { return class extends CodecSet { - constructor (registry: Registry, value?: any) { - super(registry, values, value, bitLength); + constructor (registry: Registry, value?: unknown) { + super(registry, values, value as undefined, bitLength); Object.keys(values).forEach((_key): void => { const name = stringUpperFirst(stringCamelCase(_key)); const iskey = `is${name}`; // do not clobber existing properties on the object + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (isUndefined((this as any)[iskey])) { Object.defineProperty(this, iskey, { enumerable: true, @@ -167,14 +168,14 @@ export default class CodecSet extends Set implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { if (Array.isArray(other)) { // we don't actually care about the order, sort the values return compareArray(this.strings.sort(), other.sort()); } else if (other instanceof Set) { return this.eq([...other.values()]); - } else if (isNumber(other) || isBn(other)) { - return this.valueEncoded.eq(bnToBn(other)); + } else if (isNumber(other) || isBn(other as string)) { + return this.valueEncoded.eq(bnToBn(other as string)); } return false; diff --git a/packages/types/src/codec/Struct.spec.ts b/packages/types/src/codec/Struct.spec.ts index f40874fb3b..57145c44fc 100644 --- a/packages/types/src/codec/Struct.spec.ts +++ b/packages/types/src/codec/Struct.spec.ts @@ -143,7 +143,9 @@ describe('Struct', (): void => { }) )(registry, { txt: 'foo', u32: 0x123456 }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call expect((struct as any).txt.toString()).toEqual('foo'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call expect((struct as any).u32.toNumber()).toEqual(0x123456); }); diff --git a/packages/types/src/codec/Struct.ts b/packages/types/src/codec/Struct.ts index 6ec720bb0e..5b8ccad802 100644 --- a/packages/types/src/codec/Struct.ts +++ b/packages/types/src/codec/Struct.ts @@ -18,21 +18,26 @@ function decodeStructFromObject (registry: Registry, Types: ConstructorDef, return Object.keys(Types).reduce((raw, key, index): T => { // The key in the JSON can be snake_case (or other cases), but in our // Types, result or any other maps, it's camelCase + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access const jsonKey = (jsonMap.get(key as any) && !value[key]) ? jsonMap.get(key as any) : key; try { if (Array.isArray(value)) { // TS2322: Type 'Codec' is not assignable to type 'T[keyof S]'. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access (raw as any)[key] = value[index] instanceof Types[key] ? value[index] : new Types[key](registry, value[index]); } else if (value instanceof Map) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const mapped = value.get(jsonKey); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (raw as any)[key] = mapped instanceof Types[key] ? mapped : new Types[key](registry, mapped); } else if (isObject(value)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access (raw as any)[key] = value[jsonKey as string] instanceof Types[key] ? value[jsonKey as string] : new Types[key](registry, value[jsonKey as string]); @@ -40,7 +45,7 @@ function decodeStructFromObject (registry: Registry, Types: ConstructorDef, throw new Error(`Struct: cannot decode type ${Types[key].name} with value ${JSON.stringify(value)}`); } } catch (error) { - throw new Error(`Struct: failed on '${jsonKey}':: ${error.message}`); + throw new Error(`Struct: failed on '${jsonKey as string}':: ${(error as Error).message}`); } return raw; @@ -63,7 +68,7 @@ function decodeStructFromObject (registry: Registry, Types: ConstructorDef, * @param jsonMap * @internal */ -function decodeStruct (registry: Registry, Types: ConstructorDef, value: any, jsonMap: Map): T { +function decodeStruct (registry: Registry, Types: ConstructorDef, value: unknown, jsonMap: Map): T { if (isHex(value)) { return decodeStruct(registry, Types, hexToU8a(value as string), jsonMap); } else if (isU8a(value)) { @@ -72,6 +77,7 @@ function decodeStruct (registry: Registry, Types: ConstructorDef, value: any // Transform array of values to {key: value} mapping return Object.keys(Types).reduce((raw, key, index): T => { // TS2322: Type 'Codec' is not assignable to type 'T[keyof S]'. + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (raw as any)[key] = values[index]; return raw; @@ -109,7 +115,8 @@ export default class Struct< readonly #Types: ConstructorDef; - constructor (registry: Registry, Types: S, value: V | Map | any[] | string = {} as V, jsonMap: Map = new Map()) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + constructor (registry: Registry, Types: S, value: V | Map | unknown[] | string = {} as V, jsonMap: Map = new Map()) { super(Object.entries( decodeStruct(registry, mapToTypeMap(registry, Types), value, jsonMap) ) as [keyof S, Codec][]); @@ -121,11 +128,12 @@ export default class Struct< public static with (Types: S, jsonMap?: Map): Constructor> { return class extends Struct { - constructor (registry: Registry, value?: any) { - super(registry, Types, value, jsonMap); + constructor (registry: Registry, value?: unknown) { + super(registry, Types, value as string, jsonMap); (Object.keys(Types) as (keyof S)[]).forEach((key): void => { // do not clobber existing properties on the object + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (!isUndefined((this as any)[key])) { return; } @@ -168,6 +176,7 @@ export default class Struct< return (Object .entries(this.#Types) as [keyof S, Constructor][]) .reduce((result: E, [key, Type]): E => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (result as any)[key] = new Type(this.registry).toRawType(); return result; @@ -195,7 +204,7 @@ export default class Struct< /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return compareMap(this, other); } @@ -232,13 +241,13 @@ export default class Struct< * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information */ public toHuman (isExtended?: boolean): AnyJson { - return [...this.keys()].reduce((json, key): any => { + return [...this.keys()].reduce((json, key): Record => { const value = this.get(key); json[key] = value && value.toHuman(isExtended); return json; - }, {} as any); + }, {} as Record); } /** @@ -247,14 +256,14 @@ export default class Struct< public toJSON (): AnyJson { // FIXME the return type string is only used by Extrinsic (extends Struct), // but its toJSON is the hex value - return [...this.keys()].reduce((json, key): any => { + return [...this.keys()].reduce((json, key): Record => { const jsonKey = this.#jsonMap.get(key) || key; const value = this.get(key); json[jsonKey] = value && value.toJSON(); return json; - }, {} as any); + }, {} as Record); } public static typesToMap (registry: Registry, Types: Record): Record { diff --git a/packages/types/src/codec/StructAny.ts b/packages/types/src/codec/StructAny.ts index efb0eecc45..e3bcafb294 100644 --- a/packages/types/src/codec/StructAny.ts +++ b/packages/types/src/codec/StructAny.ts @@ -13,7 +13,7 @@ import Raw from './Raw'; import { compareMap } from './utils'; /** @internal */ -function decodeJson (value?: { [index: string]: any } | null): [string, any][] { +function decodeJson (value?: Record | null): [string, any][] { return Object.entries(value || {}); } @@ -28,7 +28,7 @@ function decodeJson (value?: { [index: string]: any } | null): [string, any][] { export default class StructAny extends Map implements Codec { public readonly registry: Registry; - constructor (registry: Registry, value?: { [index: string]: any } | null) { + constructor (registry: Registry, value?: Record | null) { const decoded = decodeJson(value); super(decoded); @@ -38,13 +38,14 @@ export default class StructAny extends Map implements Codec { // like we are doing with structs, add the keys as getters decoded.forEach(([key]): void => { // do not clobber existing properties on the object + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (!isUndefined((this as any)[key])) { return; } Object.defineProperty(this, key, { enumerable: true, - get: (): Codec | undefined => this.get(key) + get: (): Codec | undefined => this.get(key) as Codec }); }); } @@ -73,7 +74,7 @@ export default class StructAny extends Map implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return compareMap(this, other); } @@ -95,8 +96,8 @@ export default class StructAny extends Map implements Codec { * @description Converts the Object to JSON, typically used for RPC transfers */ public toJSON (): AnyJson { - return [...this.entries()].reduce((json: { [index: string]: AnyJson }, [key, value]): { [index: string]: AnyJson } => { - json[key] = value; + return [...this.entries()].reduce((json: Record, [key, value]): Record => { + json[key] = value as AnyJson; return json; }, {}); diff --git a/packages/types/src/codec/Tuple.spec.ts b/packages/types/src/codec/Tuple.spec.ts index a16163e40c..65a1bf0ec1 100644 --- a/packages/types/src/codec/Tuple.spec.ts +++ b/packages/types/src/codec/Tuple.spec.ts @@ -54,7 +54,7 @@ describe('Tuple', (): void => { it('decodes properly from complex types', (): void => { const INPUT = '0xcc0200000000'; - const test = registry.createType('(u32, [u32; 0], u16)' as any, INPUT); + const test = registry.createType('(u32, [u32; 0], u16)' as 'u32', INPUT); expect(test.encodedLength).toEqual(4 + 0 + 2); expect(test.toHex()).toEqual(INPUT); diff --git a/packages/types/src/codec/Tuple.ts b/packages/types/src/codec/Tuple.ts index 079e1a21f4..f0f268c2df 100644 --- a/packages/types/src/codec/Tuple.ts +++ b/packages/types/src/codec/Tuple.ts @@ -9,6 +9,8 @@ import { isU8a, u8aConcat, isHex, hexToU8a } from '@polkadot/util'; import { decodeU8a, mapToTypeMap, typeToConstructor } from './utils'; import AbstractArray from './AbstractArray'; +type AnyTuple = AnyU8a | string | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[]; + type TupleConstructors = Constructor[] | { [index: string]: Constructor; }; @@ -18,7 +20,7 @@ type TupleTypes = (Constructor | keyof InterfaceTypes)[] | { }; /** @internal */ -function decodeTuple (registry: Registry, _Types: TupleConstructors, value: AnyU8a | string | (AnyU8a | AnyNumber | AnyString | undefined | null)[]): Codec[] { +function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: AnyTuple): Codec[] { if (isU8a(value)) { return decodeU8a(registry, value, _Types); } else if (isHex(value)) { @@ -31,11 +33,15 @@ function decodeTuple (registry: Registry, _Types: TupleConstructors, value: AnyU return Types.map((Type, index): Codec => { try { - if (value?.[index] instanceof Type) return value[index] as any; + const entry = value?.[index]; - return new Type(registry, value?.[index]); + if (entry instanceof Type) { + return entry; + } + + return new Type(registry, entry); } catch (error) { - throw new Error(`Tuple: failed on ${index}:: ${error.message}`); + throw new Error(`Tuple: failed on ${index}:: ${(error as Error).message}`); } }); } @@ -49,7 +55,7 @@ function decodeTuple (registry: Registry, _Types: TupleConstructors, value: AnyU export default class Tuple extends AbstractArray { private _Types: TupleConstructors; - constructor (registry: Registry, Types: TupleTypes, value?: any) { + constructor (registry: Registry, Types: TupleTypes, value?: AnyTuple) { const Clazzes = Array.isArray(Types) ? Types.map((type): Constructor => typeToConstructor(registry, type)) : mapToTypeMap(registry, Types); @@ -61,7 +67,7 @@ export default class Tuple extends AbstractArray { public static with (Types: TupleTypes): Constructor { return class extends Tuple { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: AnyTuple) { super(registry, Types, value); } }; diff --git a/packages/types/src/codec/U8aFixed.ts b/packages/types/src/codec/U8aFixed.ts index 2431ca5900..d5252db170 100644 --- a/packages/types/src/codec/U8aFixed.ts +++ b/packages/types/src/codec/U8aFixed.ts @@ -48,7 +48,7 @@ export default class U8aFixed extends Raw { public static with (bitLength: BitLength, typeName?: string): Constructor { return class extends U8aFixed { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: AnyU8a) { super(registry, value, bitLength); } diff --git a/packages/types/src/codec/UInt.spec.ts b/packages/types/src/codec/UInt.spec.ts index 32b8931839..cfb204113a 100644 --- a/packages/types/src/codec/UInt.spec.ts +++ b/packages/types/src/codec/UInt.spec.ts @@ -18,7 +18,7 @@ describe('UInt', (): void => { it('allows for construction via BigInt', (): void => { expect( - new UInt(registry, 123_456_789_123_456_789_123_456_789n, 128).toHuman() + new UInt(registry, 123456789123456789123456789n, 128).toHuman() ).toEqual('123,456,789,123,456,789,123,456,789'); }); diff --git a/packages/types/src/codec/UInt.ts b/packages/types/src/codec/UInt.ts index 75ba9c3cb3..bdbcea81be 100644 --- a/packages/types/src/codec/UInt.ts +++ b/packages/types/src/codec/UInt.ts @@ -23,7 +23,7 @@ export default class UInt extends AbstractInt { public static with (bitLength: UIntBitLength, typeName?: string): Constructor { return class extends UInt { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: AnyNumber) { super(registry, value, bitLength); } diff --git a/packages/types/src/codec/Vec.spec.ts b/packages/types/src/codec/Vec.spec.ts index 2ef18def95..34ba312632 100644 --- a/packages/types/src/codec/Vec.spec.ts +++ b/packages/types/src/codec/Vec.spec.ts @@ -124,7 +124,7 @@ describe('Vec', (): void => { it('exposes a working reduce', (): void => { expect( - vector.reduce((r, e): string => `${r}${e}`, '') + vector.reduce((r, e): string => `${r}${e.toString()}`, '') ).toEqual('123345456756789'); }); diff --git a/packages/types/src/codec/Vec.ts b/packages/types/src/codec/Vec.ts index 312be5f347..0ab3339fae 100644 --- a/packages/types/src/codec/Vec.ts +++ b/packages/types/src/codec/Vec.ts @@ -22,7 +22,7 @@ const MAX_LENGTH = 32768; export default class Vec extends AbstractArray { private _Type: Constructor; - constructor (registry: Registry, Type: Constructor | keyof InterfaceTypes, value: Vec | Uint8Array | string | any[] = [] as any[]) { + constructor (registry: Registry, Type: Constructor | keyof InterfaceTypes, value: Vec | Uint8Array | string | unknown[] = []) { const Clazz = typeToConstructor(registry, Type); super(registry, ...Vec.decodeVec(registry, Clazz, value)); @@ -31,15 +31,16 @@ export default class Vec extends AbstractArray { } /** @internal */ - public static decodeVec (registry: Registry, Type: Constructor, value: Vec | Uint8Array | string | any[]): T[] { + public static decodeVec (registry: Registry, Type: Constructor, value: Vec | Uint8Array | string | unknown[]): T[] { if (Array.isArray(value)) { - return value.map((entry, index): T => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return (value as unknown[]).map((entry: unknown, index: number): T => { try { return entry instanceof Type ? entry : new Type(registry, entry); } catch (error) { - console.error(`Unable to decode Vec on index ${index}`, error.message); + console.error(`Unable to decode Vec on index ${index}`, (error as Error).message); throw error; } @@ -72,7 +73,7 @@ export default class Vec extends AbstractArray { /** * @description Finds the index of the value in the array */ - public indexOf (_other?: any): number { + public indexOf (_other?: unknown): number { // convert type first, this removes overhead from the eq const other = _other instanceof this._Type ? _other diff --git a/packages/types/src/codec/utils/compareArray.ts b/packages/types/src/codec/utils/compareArray.ts index 020e613587..8a5d1cb03d 100644 --- a/packages/types/src/codec/utils/compareArray.ts +++ b/packages/types/src/codec/utils/compareArray.ts @@ -2,15 +2,17 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { isFunction, isUndefined } from '@polkadot/util'; +import { isUndefined } from '@polkadot/util'; + +import { hasEq } from './util'; // NOTE These are used internally and when comparing objects, expects that // when the second is an Codec[] that the first has to be as well -export default function compareArray (a: any[], b?: any): boolean { +export default function compareArray (a: unknown[], b?: unknown): boolean { if (Array.isArray(b)) { return (a.length === b.length) && isUndefined( a.find((value, index): boolean => - isFunction(value.eq) + hasEq(value) ? !value.eq(b[index]) : value !== b[index] ) diff --git a/packages/types/src/codec/utils/compareMap.ts b/packages/types/src/codec/utils/compareMap.ts index 4565a37a58..cd79721ae6 100644 --- a/packages/types/src/codec/utils/compareMap.ts +++ b/packages/types/src/codec/utils/compareMap.ts @@ -2,12 +2,13 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { isFunction, isObject, isUndefined } from '@polkadot/util'; +import { isObject, isUndefined } from '@polkadot/util'; -function hasMismatch (a?: any, b?: any): boolean { +import { hasEq } from './util'; + +function hasMismatch (a?: unknown, b?: unknown): boolean { return isUndefined(a) || ( - // Codec has .eq, use it here - isFunction(a.eq) + hasEq(a) ? !a.eq(b) : a !== b ); @@ -26,7 +27,7 @@ function compareMapArray (a: Map, b: [any, any][]): boolean { // NOTE These are used internally and when comparing objects, expects that // when the second is an Map that the first has to be as well -export default function compareMap (a: Map, b?: any): boolean { +export default function compareMap (a: Map, b?: unknown): boolean { if (Array.isArray(b)) { return compareMapArray(a, b); } else if (b instanceof Map) { diff --git a/packages/types/src/codec/utils/compareSet.ts b/packages/types/src/codec/utils/compareSet.ts index 1283902a4e..11a63362c7 100644 --- a/packages/types/src/codec/utils/compareSet.ts +++ b/packages/types/src/codec/utils/compareSet.ts @@ -4,14 +4,14 @@ import { isObject } from '@polkadot/util'; -function compareSetArray (a: Set, b: any[]): boolean { +function compareSetArray (a: Set, b: any[]): boolean { // equal number of entries and each entry in the array should match return (a.size === b.length) && !b.some((entry): boolean => !a.has(entry)); } // NOTE These are used internally and when comparing objects, expects that // when the second is an Set that the first has to be as well -export default function compareSet (a: Set, b?: any): boolean { +export default function compareSet (a: Set, b?: unknown): boolean { if (Array.isArray(b)) { return compareSetArray(a, b); } else if (b instanceof Set) { diff --git a/packages/types/src/codec/utils/encodeTypes.ts b/packages/types/src/codec/utils/encodeTypes.ts index 2d4214d448..f1c823561d 100644 --- a/packages/types/src/codec/utils/encodeTypes.ts +++ b/packages/types/src/codec/utils/encodeTypes.ts @@ -20,6 +20,7 @@ export function paramsNotation (outer: string, inner?: string | any[], transform return `${outer}${arrayStr}`; } +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment function encodeWithParams (typeDef: Pick, outer = typeDef.displayName || typeDef.type): string { const { info, params, sub } = typeDef; @@ -39,11 +40,13 @@ function encodeWithParams (typeDef: Pick, outer = typeDef.displayN (param: TypeDef) => displayType(param) ); default: + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return outer; } } function encodeDoNotConstruct ({ displayName }: TypeDef): string { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions return `DoNotEncode<${displayName}>`; } @@ -79,6 +82,7 @@ function encodeEnum (typeDef: Pick): string { if (isClikeEnum) { return `[${ sub + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions .map(({ name }: TypeDef): string => `"${name}"`) .join(', ') }]`; @@ -117,6 +121,7 @@ function encodeUInt ({ length }: Pick, type: 'Int' | 'UInt'): stri function encodeVecFixed ({ length, sub }: Pick): string { assert(isNumber(length) && !isUndefined(sub), 'Unable to encode VecFixed type'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/restrict-template-expressions return `[${sub.type};${length}]`; } @@ -147,7 +152,7 @@ const encoders: Record string> = { export function encodeType (typeDef: Pick): string { const encoder = encoders[(typeDef as TypeDef).info]; - assert(encoder, `Cannot encode type: ${typeDef}.`); + assert(encoder, `Cannot encode type: ${typeDef.toString()}`); return encoder(typeDef as TypeDef); } @@ -168,12 +173,14 @@ export function displayType (typeDef: Pick): string { } export function withTypeString (typeDef: Pick): Pick { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const type = SPECIAL_TYPES.includes(typeDef.displayName) ? typeDef.displayName : encodeType(typeDef); return { ...typeDef, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment type }; } diff --git a/packages/types/src/codec/utils/util.ts b/packages/types/src/codec/utils/util.ts new file mode 100644 index 0000000000..88624a628b --- /dev/null +++ b/packages/types/src/codec/utils/util.ts @@ -0,0 +1,10 @@ +// Copyright 2017-2020 @polkadot/types authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +import { isFunction } from '@polkadot/util'; + +export function hasEq (o: unknown): o is { eq: (other: unknown) => boolean } { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return isFunction((o as any).eq); +} diff --git a/packages/types/src/create/createClass.ts b/packages/types/src/create/createClass.ts index 3d7e990d9c..73204647f8 100644 --- a/packages/types/src/create/createClass.ts +++ b/packages/types/src/create/createClass.ts @@ -43,6 +43,7 @@ export function ClassOfUnsafe (registry: Registry, name: K): Constructor { // TS2589: Type instantiation is excessively deep and possibly infinite. // The above happens with as Constructor; + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return ClassOfUnsafe(registry, name) as any; } @@ -67,7 +68,7 @@ function getTypeClassMap (value: TypeDef): Record const result: Record = {}; return getSubDefArray(value).reduce((result, sub): Record => { - result[sub.name as string] = sub.type as any; + result[sub.name as string] = sub.type as keyof InterfaceTypes; return result; }, result); @@ -113,7 +114,9 @@ const infoMapping: Record C // eslint-disable-next-line sort-keys const Clazz = Struct.with({ previous: type, next: type } as any); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access ClassOf.prototype.toRawType = function (): string { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call return `Linkage<${this.next.toRawType(true)}>`; }; diff --git a/packages/types/src/create/createType.spec.ts b/packages/types/src/create/createType.spec.ts index 16d510bac9..39897052a8 100644 --- a/packages/types/src/create/createType.spec.ts +++ b/packages/types/src/create/createType.spec.ts @@ -178,14 +178,18 @@ describe('createType', (): void => { } }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const cmpDef: any = createTypeUnsafe(registry, 'TestComplex'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call expect(cmpDef.balance.bitLength()).toEqual(128); registry.register({ Balance: 'u32' }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const cmpu32: any = createTypeUnsafe(registry, 'TestComplex'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call expect(cmpu32.balance.bitLength()).toEqual(32); }); }); diff --git a/packages/types/src/create/createType.ts b/packages/types/src/create/createType.ts index 837e5a04ed..68a2ff0a7a 100644 --- a/packages/types/src/create/createType.ts +++ b/packages/types/src/create/createType.ts @@ -44,6 +44,7 @@ function checkInstance (valu // where isPedantic is specified (storage decoding), also check the format/structure function initType (registry: Registry, Type: Constructor>, params: any[] = [], isPedantic?: boolean): FromReg { const created = new Type(registry, ...params); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const [value] = params; if (isPedantic && isU8a(value)) { @@ -63,7 +64,7 @@ export function createTypeUnsafe(registry, type), params); // , isPedantic); } catch (error) { - throw new Error(`createType(${type}):: ${error.message}`); + throw new Error(`createType(${type}):: ${(error as Error).message}`); } } diff --git a/packages/types/src/create/getTypeDef.ts b/packages/types/src/create/getTypeDef.ts index fe38dd800a..5717a3200b 100644 --- a/packages/types/src/create/getTypeDef.ts +++ b/packages/types/src/create/getTypeDef.ts @@ -51,7 +51,8 @@ function _decodeSet (value: TypeDef, details: Record): TypeDef { // decode a struct, set or enum // eslint-disable-next-line @typescript-eslint/no-unused-vars function _decodeStruct (value: TypeDef, type: string, _: string): TypeDef { - const parsed = JSON.parse(type); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const parsed: Record = JSON.parse(type); const keys = Object.keys(parsed); if (keys.length === 1 && keys[0] === '_enum') { diff --git a/packages/types/src/create/registry.spec.ts b/packages/types/src/create/registry.spec.ts index bd648fa1b5..f6d56d4025 100644 --- a/packages/types/src/create/registry.spec.ts +++ b/packages/types/src/create/registry.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import { Codec, Constructor } from '../types'; import { isChildClass } from '@polkadot/util'; @@ -70,6 +72,7 @@ describe('TypeRegistry', (): void => { const first = new Recursive(registry, { next: last }); expect((first as any).next.isSome).toBe(true); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call expect((first as any).next.unwrap().next.isSome).toBe(false); }); @@ -122,7 +125,9 @@ describe('TypeRegistry', (): void => { }); expect(struct instanceof Struct).toBe(true); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call expect(struct.foo.toNumber()).toEqual(42); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call expect(struct.bar.toString()).toEqual('testing'); }); }); diff --git a/packages/types/src/create/registry.ts b/packages/types/src/create/registry.ts index 806c423b69..f756647baf 100644 --- a/packages/types/src/create/registry.ts +++ b/packages/types/src/create/registry.ts @@ -48,6 +48,7 @@ function decorateEvents (registry: Registry, metadata: RegistryMetadata, metadat section.events.unwrap().forEach((meta, methodIndex): void => { const methodName = meta.name.toString(); const eventIndex = new Uint8Array([sectionIndex, methodIndex]); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access const typeDef = meta.args.map((arg): TypeDef => getTypeDef(arg.toString())); let Types: Constructor[] = []; @@ -79,9 +80,9 @@ function decorateExtrinsics (registry: Registry, metadata: RegistryMetadata, met } export class TypeRegistry implements Registry { - readonly #classes: Map = new Map(); + readonly #classes = new Map(); - readonly #definitions: Map = new Map(); + readonly #definitions = new Map(); readonly #metadataCalls: Record = {}; @@ -89,7 +90,7 @@ export class TypeRegistry implements Registry { readonly #metadataEvents: Record> = {}; - readonly #unknownTypes: Map = new Map(); + readonly #unknownTypes = new Map(); #chainProperties?: ChainProperties; @@ -101,7 +102,9 @@ export class TypeRegistry implements Registry { // we only want to import these on creation, i.e. we want to avoid types // weird side-effects from circular references. (Since registry is injected // into types, this can be a real concern now) + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const baseTypes: RegistryTypes = require('../index.types'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const definitions: Record = require('../interfaces/definitions'); // since these are classes, they are injected first @@ -143,6 +146,7 @@ export class TypeRegistry implements Registry { * @describe Creates an instance of the class */ public createClass (type: K): Constructor { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return createClass(this, type) as any; } @@ -158,7 +162,7 @@ export class TypeRegistry implements Registry { const hexIndex = u8aToHex(callIndex); const fn = this.#metadataCalls[hexIndex]; - assert(!isUndefined(fn), `findMetaCall: Unable to find Call with index ${hexIndex}/[${callIndex}]`); + assert(!isUndefined(fn), `findMetaCall: Unable to find Call with index ${hexIndex}/[${callIndex.toString()}]`); return fn; } @@ -172,7 +176,7 @@ export class TypeRegistry implements Registry { ); const error = this.#metadataErrors[hexIndex]; - assert(!isUndefined(error), `findMetaError: Unable to find Error with index ${hexIndex}/[${errorIndex}]`); + assert(!isUndefined(error), `findMetaError: Unable to find Error with index ${hexIndex}/[${errorIndex.toString()}]`); return error; } @@ -181,7 +185,7 @@ export class TypeRegistry implements Registry { const hexIndex = u8aToHex(eventIndex); const Event = this.#metadataEvents[hexIndex]; - assert(!isUndefined(Event), `findMetaEvent: Unable to find Event with index ${hexIndex}/[${eventIndex}]`); + assert(!isUndefined(Event), `findMetaEvent: Unable to find Event with index ${hexIndex}/[${eventIndex.toString()}]`); return Event; } diff --git a/packages/types/src/extrinsic/ExtrinsicEra.ts b/packages/types/src/extrinsic/ExtrinsicEra.ts index 7ad597fb10..be15e46526 100644 --- a/packages/types/src/extrinsic/ExtrinsicEra.ts +++ b/packages/types/src/extrinsic/ExtrinsicEra.ts @@ -203,11 +203,11 @@ export class MortalEra extends Tuple { * The era for an extrinsic, indicating either a mortal or immortal extrinsic */ export default class ExtrinsicEra extends Enum implements IExtrinsicEra { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: unknown) { super(registry, { ImmortalEra, MortalEra - }, ExtrinsicEra._decodeExtrinsicEra(value)); + }, ExtrinsicEra._decodeExtrinsicEra(value as string)); } /** @internal */ diff --git a/packages/types/src/extrinsic/ExtrinsicPayload.ts b/packages/types/src/extrinsic/ExtrinsicPayload.ts index 6eca860660..32355137e5 100644 --- a/packages/types/src/extrinsic/ExtrinsicPayload.ts +++ b/packages/types/src/extrinsic/ExtrinsicPayload.ts @@ -113,7 +113,7 @@ export default class ExtrinsicPayload extends Base { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return this._raw.eq(other); } diff --git a/packages/types/src/extrinsic/ExtrinsicPayloadUnknown.ts b/packages/types/src/extrinsic/ExtrinsicPayloadUnknown.ts index d698c9e47c..93ab33014d 100644 --- a/packages/types/src/extrinsic/ExtrinsicPayloadUnknown.ts +++ b/packages/types/src/extrinsic/ExtrinsicPayloadUnknown.ts @@ -13,7 +13,7 @@ import Struct from '../codec/Struct'; * A default handler for payloads where the version is not known (default throw) */ export default class ExtrinsicPayloadUnknown extends Struct { - constructor (registry: Registry, value?: any, { version = 0 }: Partial = {}) { + constructor (registry: Registry, value?: unknown, { version = 0 }: Partial = {}) { super(registry, {}); throw new Error(`Unsupported extrinsic payload version ${version}`); diff --git a/packages/types/src/extrinsic/ExtrinsicUnknown.ts b/packages/types/src/extrinsic/ExtrinsicUnknown.ts index 1197719f50..a4d2cc06d9 100644 --- a/packages/types/src/extrinsic/ExtrinsicUnknown.ts +++ b/packages/types/src/extrinsic/ExtrinsicUnknown.ts @@ -14,7 +14,7 @@ import { UNMASK_VERSION } from './constants'; * A default handler for extrinsics where the version is not known (default throw) */ export default class ExtrinsicUnknown extends Struct { - constructor (registry: Registry, value?: any, { isSigned = false, version = 0 }: Partial = {}) { + constructor (registry: Registry, value?: unknown, { isSigned = false, version = 0 }: Partial = {}) { super(registry, {}); throw new Error(`Unsupported ${isSigned ? '' : 'un'}signed extrinsic version ${version & UNMASK_VERSION}`); diff --git a/packages/types/src/extrinsic/SignerPayload.ts b/packages/types/src/extrinsic/SignerPayload.ts index 2ed8ef85a9..99547fbdb6 100644 --- a/packages/types/src/extrinsic/SignerPayload.ts +++ b/packages/types/src/extrinsic/SignerPayload.ts @@ -29,7 +29,7 @@ export interface SignerPayloadType extends Codec { // We explicitly cast the type here to get the actual TypeScript exports right // We can ignore the properties, added via Struct.with -const _Payload: Constructor = Struct.with({ +const _Payload = Struct.with({ address: 'Address', blockHash: 'Hash', blockNumber: 'BlockNumber', @@ -41,7 +41,7 @@ const _Payload: Constructor = Struct.with({ signedExtensions: 'Vec', tip: 'Compact', version: 'u8' -}) as any; +}) as unknown as Constructor; /** * @name SignerPayload diff --git a/packages/types/src/generic/AccountId.spec.ts b/packages/types/src/generic/AccountId.spec.ts index 98597ea4a6..01ae1415c0 100644 --- a/packages/types/src/generic/AccountId.spec.ts +++ b/packages/types/src/generic/AccountId.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import { TypeRegistry } from '../create'; import Raw from '../codec/Raw'; import jsonVec from '../json/AccountIdVec.001.json'; diff --git a/packages/types/src/generic/AccountId.ts b/packages/types/src/generic/AccountId.ts index 309a094efc..28dc40878b 100644 --- a/packages/types/src/generic/AccountId.ts +++ b/packages/types/src/generic/AccountId.ts @@ -10,7 +10,7 @@ import { decodeAddress, encodeAddress } from '@polkadot/util-crypto'; import U8aFixed from '../codec/U8aFixed'; /** @internal */ -function decodeAccountId (value: AnyU8a | AnyString): Uint8Array { +function decodeAccountId (value: AnyU8a | AnyString): AnyU8a { if (isU8a(value) || Array.isArray(value)) { return u8aToU8a(value); } else if (isHex(value)) { @@ -41,8 +41,8 @@ export default class AccountId extends U8aFixed { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { - return super.eq(decodeAccountId(other)); + public eq (other?: unknown): boolean { + return super.eq(decodeAccountId(other as AnyU8a)); } /** diff --git a/packages/types/src/generic/AccountIndex.spec.ts b/packages/types/src/generic/AccountIndex.spec.ts index 1cc3543e49..f4ccea7d93 100644 --- a/packages/types/src/generic/AccountIndex.spec.ts +++ b/packages/types/src/generic/AccountIndex.spec.ts @@ -18,7 +18,7 @@ describe('AccountIndex', (): void => { it('creates from BigInt', (): void => { expect( - registry.createType('AccountIndex', 336_794_129n).toNumber() + registry.createType('AccountIndex', 336794129n).toNumber() ).toEqual(336794129); }); diff --git a/packages/types/src/generic/AccountIndex.ts b/packages/types/src/generic/AccountIndex.ts index 751164fbca..9adef19ef4 100644 --- a/packages/types/src/generic/AccountIndex.ts +++ b/packages/types/src/generic/AccountIndex.ts @@ -85,9 +85,9 @@ export default class AccountIndex extends U32 { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { // shortcut for BN or Number, don't create an object - if (isBn(other) || isNumber(other)) { + if (isBn(other as string) || isNumber(other)) { return super.eq(other); } diff --git a/packages/types/src/generic/Block.spec.ts b/packages/types/src/generic/Block.spec.ts index 9666f911e8..af1c1eade7 100644 --- a/packages/types/src/generic/Block.spec.ts +++ b/packages/types/src/generic/Block.spec.ts @@ -3,6 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. /* eslint-disable sort-keys */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ import Metadata from '@polkadot/metadata/Metadata'; import metadataStatic from '@polkadot/metadata/Metadata/static'; diff --git a/packages/types/src/generic/Call.ts b/packages/types/src/generic/Call.ts index e21795ed49..715f134aaf 100644 --- a/packages/types/src/generic/Call.ts +++ b/packages/types/src/generic/Call.ts @@ -12,7 +12,7 @@ import Struct from '../codec/Struct'; import U8aFixed from '../codec/U8aFixed'; interface DecodeMethodInput { - args: any; + args: unknown; callIndex: CallIndex | Uint8Array; } @@ -90,14 +90,14 @@ function decodeCallViaU8a (registry: Registry, value: Uint8Array, _meta?: Functi * necessary. * @internal */ -function decodeCall (registry: Registry, value: DecodedMethod | Uint8Array | string = new Uint8Array(), _meta?: FunctionMetadataLatest): DecodedMethod { +function decodeCall (registry: Registry, value: unknown | DecodedMethod | Uint8Array | string = new Uint8Array(), _meta?: FunctionMetadataLatest): DecodedMethod { if (isHex(value) || isU8a(value)) { - return decodeCallViaU8a(registry, u8aToU8a(value), _meta); + return decodeCallViaU8a(registry, u8aToU8a(value as string), _meta); } else if (isObject(value) && value.callIndex && value.args) { - return decodeCallViaObject(registry, value, _meta); + return decodeCallViaObject(registry, value as DecodedMethod, _meta); } - throw new Error(`Call: Cannot decode value '${value}' of type ${typeof value}`); + throw new Error(`Call: Cannot decode value '${value as string}' of type ${typeof value}`); } /** @@ -120,7 +120,7 @@ export class CallIndex extends U8aFixed { export default class Call extends Struct implements IMethod { protected _meta: FunctionMetadataLatest; - constructor (registry: Registry, value: any, meta?: FunctionMetadataLatest) { + constructor (registry: Registry, value: unknown, meta?: FunctionMetadataLatest) { const decoded = decodeCall(registry, value, meta); super(registry, { diff --git a/packages/types/src/interfaces/author/ExtrinsicStatus.spec.ts b/packages/types/src/interfaces/author/ExtrinsicStatus.spec.ts index 1910bd8bb3..25e365edd9 100644 --- a/packages/types/src/interfaces/author/ExtrinsicStatus.spec.ts +++ b/packages/types/src/interfaces/author/ExtrinsicStatus.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import { ExtrinsicStatus } from './types'; import { TypeRegistry } from '../../create'; diff --git a/packages/types/src/interfaces/metadata/definitions.ts b/packages/types/src/interfaces/metadata/definitions.ts index 771728df5f..0800b68d51 100644 --- a/packages/types/src/interfaces/metadata/definitions.ts +++ b/packages/types/src/interfaces/metadata/definitions.ts @@ -8,9 +8,9 @@ import { Definitions } from '../../types'; const AllHashers = { - Blake2_128: null, // eslint-disable-line @typescript-eslint/camelcase - Blake2_256: null, // eslint-disable-line @typescript-eslint/camelcase - Blake2_128Concat: null, // eslint-disable-line @typescript-eslint/camelcase + Blake2_128: null, // eslint-disable-line camelcase + Blake2_256: null, // eslint-disable-line camelcase + Blake2_128Concat: null, // eslint-disable-line camelcase Twox128: null, Twox256: null, Twox64Concat: null, @@ -238,8 +238,8 @@ export default { }, StorageHasherV4: { _enum: { - Blake2_128: null, // eslint-disable-line @typescript-eslint/camelcase - Blake2_256: null, // eslint-disable-line @typescript-eslint/camelcase + Blake2_128: null, // eslint-disable-line camelcase + Blake2_256: null, // eslint-disable-line camelcase Twox128: null, Twox256: null, Twox64Concat: null @@ -440,9 +440,9 @@ export default { }, StorageHasherV10: { _enum: { - Blake2_128: null, // eslint-disable-line @typescript-eslint/camelcase - Blake2_256: null, // eslint-disable-line @typescript-eslint/camelcase - Blake2_128Concat: null, // eslint-disable-line @typescript-eslint/camelcase + Blake2_128: null, // eslint-disable-line camelcase + Blake2_256: null, // eslint-disable-line camelcase + Blake2_128Concat: null, // eslint-disable-line camelcase Twox128: null, Twox256: null, Twox64Concat: null diff --git a/packages/types/src/interfaces/runtime/Digest.spec.ts b/packages/types/src/interfaces/runtime/Digest.spec.ts index f85ade27d2..48b69856c1 100644 --- a/packages/types/src/interfaces/runtime/Digest.spec.ts +++ b/packages/types/src/interfaces/runtime/Digest.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import { TypeRegistry } from '../../create'; import json3 from '../../json/Header.003.json'; diff --git a/packages/types/src/interfaces/runtime/Header.spec.ts b/packages/types/src/interfaces/runtime/Header.spec.ts index d31472084b..2840afc260 100644 --- a/packages/types/src/interfaces/runtime/Header.spec.ts +++ b/packages/types/src/interfaces/runtime/Header.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import BN from 'bn.js'; import { TypeRegistry } from '../../create'; diff --git a/packages/types/src/interfaces/runtime/SignedBlock.spec.ts b/packages/types/src/interfaces/runtime/SignedBlock.spec.ts index 7401876532..82d46f9d32 100644 --- a/packages/types/src/interfaces/runtime/SignedBlock.spec.ts +++ b/packages/types/src/interfaces/runtime/SignedBlock.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import Metadata from '@polkadot/metadata/Metadata'; import metadataStatic from '@polkadot/metadata/Metadata/static'; diff --git a/packages/types/src/interfaces/state/RuntimeVersion.spec.ts b/packages/types/src/interfaces/state/RuntimeVersion.spec.ts index d773ffc18f..0e348a1073 100644 --- a/packages/types/src/interfaces/state/RuntimeVersion.spec.ts +++ b/packages/types/src/interfaces/state/RuntimeVersion.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import { RuntimeVersion } from './types'; import { TypeRegistry } from '../../create'; diff --git a/packages/types/src/interfaces/state/StorageChangeSet.spec.ts b/packages/types/src/interfaces/state/StorageChangeSet.spec.ts index 9dc2978c5d..1671194576 100644 --- a/packages/types/src/interfaces/state/StorageChangeSet.spec.ts +++ b/packages/types/src/interfaces/state/StorageChangeSet.spec.ts @@ -2,6 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import { TypeRegistry } from '@polkadot/types'; import json from '../../json/StorageChangeSet.001.json'; diff --git a/packages/types/src/interfaces/system/EventRecord.spec.ts b/packages/types/src/interfaces/system/EventRecord.spec.ts index f1ad7a320e..4b54fc8f6a 100644 --- a/packages/types/src/interfaces/system/EventRecord.spec.ts +++ b/packages/types/src/interfaces/system/EventRecord.spec.ts @@ -2,6 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ + import Metadata from '@polkadot/metadata/Metadata'; import rpcMetadataV1 from '@polkadot/metadata/Metadata/v1/static'; import rpcMetadata from '@polkadot/metadata/Metadata/static'; @@ -42,12 +45,12 @@ describe('EventRecord', (): void => { it('decodes EventRecord with topics correctly', (): void => { const hex = json3.params.result.changes[0][1]; - const records = registry.createType('Vec', hex, true) as any; + const records = registry.createType('Vec', hex, true); const er = records[0]; expect(er.phase.type).toEqual('ApplyExtrinsic'); // additional payment info, weight u64 (vs u32) - expect(records.toHex()).toEqual(hex + '000000000000' + '00000000'); + expect(records.toHex()).toEqual(`${hex as string}00000000000000000000`); }); }); }); diff --git a/packages/types/src/primitive/Bool.ts b/packages/types/src/primitive/Bool.ts index 5d926329d5..ca4ca43485 100644 --- a/packages/types/src/primitive/Bool.ts +++ b/packages/types/src/primitive/Bool.ts @@ -73,7 +73,7 @@ export default class Bool extends Boolean implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return this.valueOf() === ( other instanceof Boolean ? other.valueOf() @@ -113,7 +113,7 @@ export default class Bool extends Boolean implements Codec { * @description Returns the string representation of the value */ public toString (): string { - return `${this.toJSON()}`; + return this.toJSON().toString(); } /** diff --git a/packages/types/src/primitive/Null.ts b/packages/types/src/primitive/Null.ts index 00e9ed3a36..dc998319c1 100644 --- a/packages/types/src/primitive/Null.ts +++ b/packages/types/src/primitive/Null.ts @@ -43,7 +43,7 @@ export default class Null implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return other instanceof Null || isNull(other); } diff --git a/packages/types/src/primitive/StorageKey.ts b/packages/types/src/primitive/StorageKey.ts index 769b7061d7..b1b44919bb 100644 --- a/packages/types/src/primitive/StorageKey.ts +++ b/packages/types/src/primitive/StorageKey.ts @@ -34,9 +34,9 @@ interface StorageKeyExtra { const HASHER_MAP: Record = { // opaque - Blake2_128: [16, false], // eslint-disable-line @typescript-eslint/camelcase - Blake2_128Concat: [16, true], // eslint-disable-line @typescript-eslint/camelcase - Blake2_256: [32, false], // eslint-disable-line @typescript-eslint/camelcase + Blake2_128: [16, false], // eslint-disable-line camelcase + Blake2_128Concat: [16, true], // eslint-disable-line camelcase + Blake2_256: [32, false], // eslint-disable-line camelcase Identity: [0, true], Twox128: [16, false], Twox256: [32, false], @@ -92,7 +92,7 @@ function decodeStorageKey (value?: AnyU8a | StorageKey | StorageEntry | [Storage section: value.section }; } else if (Array.isArray(value)) { - const [fn, ...arg]: [StorageEntry, ...any[]] = value as any; + const [fn, ...arg] = value as [StorageEntry, ...any[]]; assert(isFunction(fn), 'Expected function input for key construction'); @@ -103,7 +103,7 @@ function decodeStorageKey (value?: AnyU8a | StorageKey | StorageEntry | [Storage }; } - throw new Error(`Unable to convert input ${value} to StorageKey`); + throw new Error(`Unable to convert input ${value as string} to StorageKey`); } function decodeHashers (registry: Registry, value: Uint8Array, hashers: [StorageHasher, string][]): Codec[] { @@ -152,7 +152,7 @@ function decodeArgsFromMeta (registry: Registry, value: Uint8Array, meta?: Stora * constructed by passing in a raw key or a StorageEntry with (optional) arguments. */ export default class StorageKey extends Bytes { - // eslint-disable-next-line @typescript-eslint/ban-ts-ignore + // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore This is assigned via this.decodeArgsFromMeta() private _args: Codec[]; diff --git a/packages/types/src/primitive/Text.ts b/packages/types/src/primitive/Text.ts index 7a340acd31..8003219672 100644 --- a/packages/types/src/primitive/Text.ts +++ b/packages/types/src/primitive/Text.ts @@ -34,7 +34,7 @@ function decodeText (value: Text | string | AnyU8a | { toString: () => string }) return u8aToString(value.subarray(offset, total)); } - return `${value}`; + return value.toString(); } /** @@ -90,7 +90,7 @@ export default class Text extends String implements Codec { /** * @description Compares the value of the input to see if there is a match */ - public eq (other?: any): boolean { + public eq (other?: unknown): boolean { return isString(other) ? this.toString() === other.toString() : false; diff --git a/packages/types/src/primitive/USize.ts b/packages/types/src/primitive/USize.ts index e0f8e1f5ea..ae8d6edb9e 100644 --- a/packages/types/src/primitive/USize.ts +++ b/packages/types/src/primitive/USize.ts @@ -14,7 +14,7 @@ import U32 from './U32'; * It is not to be used, since it created consensus mismatches. */ export default class USize extends U32 { - constructor (registry: Registry, value?: any) { + constructor (registry: Registry, value?: unknown) { super(registry, value); throw new Error('The `usize` type should not be used. Since it is platform-specific, it creates incompatibilities between native (generally u64) and WASM (always u32) code. Use one of the `u32` or `u64` types explicitly.'); diff --git a/packages/types/src/types/codec.ts b/packages/types/src/types/codec.ts index bd9bbc2f8c..3c162a9234 100644 --- a/packages/types/src/types/codec.ts +++ b/packages/types/src/types/codec.ts @@ -1,7 +1,6 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -/* eslint-disable @typescript-eslint/interface-name-prefix */ import { H256 } from '../interfaces/runtime'; import { AnyJson, BareOpts } from './helpers'; @@ -57,7 +56,7 @@ export interface Codec { /** * @description Compares the value of the input to see if there is a match */ - eq (other?: any): boolean; + eq (other?: unknown): boolean; /** * @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation diff --git a/packages/types/src/types/definitions.ts b/packages/types/src/types/definitions.ts index ed9056796f..7586e1a014 100644 --- a/packages/types/src/types/definitions.ts +++ b/packages/types/src/types/definitions.ts @@ -8,8 +8,7 @@ export type DefinitionTypeEnum = { _enum: DefinitionTypeType[] } | { _enum: Reco export type DefinitionTypeSet = { _set: Record }; -// Don't believe the `& object` here is proper, but cannot do `& Record` -export type DefinitionTypeStruct = Record | { _alias?: Record } & object; +export type DefinitionTypeStruct = Record | { _alias?: Record } & Record; export type DefinitionType = string | DefinitionTypeEnum | DefinitionTypeSet | DefinitionTypeStruct; diff --git a/packages/types/src/types/extrinsic.ts b/packages/types/src/types/extrinsic.ts index e5c5de02d5..f1c851bddf 100644 --- a/packages/types/src/types/extrinsic.ts +++ b/packages/types/src/types/extrinsic.ts @@ -10,7 +10,6 @@ import { Codec } from './codec'; import { AnyJson, AnyNumber, AnyU8a } from './helpers'; import { ICompact, IKeyringPair, IMethod, IRuntimeVersion } from './interfaces'; -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface ISubmittableResult { readonly events: EventRecord[]; readonly status: ExtrinsicStatus; @@ -85,34 +84,29 @@ export interface ExtrinsicPayloadValue { transactionVersion: AnyNumber; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface IExtrinsicSignature extends ExtrinsicSignatureBase, Codec { addSignature (signer: Address | Uint8Array | string, signature: Uint8Array | string, payload: Uint8Array | string): IExtrinsicSignature; sign (method: Call, account: IKeyringPair, options: SignatureOptions): IExtrinsicSignature; signFake (method: Call, address: Address | Uint8Array | string, options: SignatureOptions): IExtrinsicSignature; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface IExtrinsicEra extends Codec { asImmortalEra: Codec; asMortalEra: Codec; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix interface IExtrinsicSignable { addSignature (signer: Address | Uint8Array | string, signature: Uint8Array | string, payload: ExtrinsicPayloadValue | Uint8Array | string): T; sign (account: IKeyringPair, options: SignatureOptions): T; signFake (address: Address | Uint8Array | string, options: SignatureOptions): T; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface IExtrinsicImpl extends IExtrinsicSignable, Codec { readonly method: Call; readonly signature: IExtrinsicSignature; readonly version: number; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface IExtrinsic extends IExtrinsicSignable, ExtrinsicSignatureBase, IMethod { readonly length: number; readonly method: Call; @@ -206,7 +200,6 @@ export interface SignerPayloadRaw extends SignerPayloadRawBase { type: 'bytes' | 'payload'; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface ISignerPayload { toPayload (): SignerPayloadJSON; toRaw (): SignerPayloadRaw; diff --git a/packages/types/src/types/interfaces.ts b/packages/types/src/types/interfaces.ts index 60b4bc9693..3a3efe86bc 100644 --- a/packages/types/src/types/interfaces.ts +++ b/packages/types/src/types/interfaces.ts @@ -1,7 +1,6 @@ // Copyright 2017-2020 @polkadot/types authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -/* eslint-disable @typescript-eslint/interface-name-prefix */ import type BN from 'bn.js'; import { SignOptions } from '@polkadot/keyring/types'; @@ -21,7 +20,6 @@ export interface IKeyringPair { sign: (data: Uint8Array, options?: SignOptions) => Uint8Array; } -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface IMethod extends Codec { readonly args: Codec[]; readonly argsDef: ArgsDef; @@ -47,7 +45,6 @@ export interface IRuntimeVersion { // A type alias for [Type1, Type2] & Codec, representing a tuple (Type1, Type2) // FIXME Implement this generic on Tuple.ts itself. -// eslint-disable-next-line @typescript-eslint/interface-name-prefix export type ITuple = Sub & Codec export interface IU8a extends Uint8Array, Codec { diff --git a/packages/types/src/types/registry.ts b/packages/types/src/types/registry.ts index 481ee5b158..03ea0d8a26 100644 --- a/packages/types/src/types/registry.ts +++ b/packages/types/src/types/registry.ts @@ -115,7 +115,7 @@ export interface Registry { readonly signedExtensions: string[]; findMetaCall (callIndex: Uint8Array): CallFunction; - findMetaError (errorIndex: Uint8Array): any; + findMetaError (errorIndex: Uint8Array): RegistryError; // due to same circular imports where types don't really want to import from EventData, // keep this as a generic Codec, however the actual impl. returns the correct findMetaEvent (eventIndex: Uint8Array): Constructor; diff --git a/yarn.lock b/yarn.lock index a931da3ed5..0a8105e4b5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2579,8 +2579,8 @@ __metadata: linkType: hard "@octokit/request@npm:^5.2.0": - version: 5.4.2 - resolution: "@octokit/request@npm:5.4.2" + version: 5.4.3 + resolution: "@octokit/request@npm:5.4.3" dependencies: "@octokit/endpoint": ^6.0.1 "@octokit/request-error": ^2.0.0 @@ -2590,7 +2590,7 @@ __metadata: node-fetch: ^2.3.0 once: ^1.4.0 universal-user-agent: ^5.0.0 - checksum: 3/4e215376a466d20b6abdf3d48106acb88b18b17a667a53d69760cd6094e3f7ebdc8d7f952c1174c68916ca175c802c8ffef0d16f8dfc51356047a547346fe6db + checksum: 3/58b965548d67cf0fff6ea5b5b047d3979abf9c6e729574b28699776a4a2799b1a7ae55f21b180ed2edec635133e2d38a8931691f6044cae14353f9cb179562cd languageName: node linkType: hard @@ -2688,9 +2688,9 @@ __metadata: languageName: unknown linkType: soft -"@polkadot/dev@npm:^0.53.5": - version: 0.53.5 - resolution: "@polkadot/dev@npm:0.53.5" +"@polkadot/dev@npm:^0.54.1": + version: 0.54.1 + resolution: "@polkadot/dev@npm:0.54.1" dependencies: "@babel/cli": ^7.8.4 "@babel/core": ^7.9.6 @@ -2712,8 +2712,8 @@ __metadata: "@babel/preset-typescript": ^7.9.0 "@babel/register": ^7.9.0 "@babel/runtime": ^7.9.6 - "@typescript-eslint/eslint-plugin": 2.33.0 - "@typescript-eslint/parser": 2.33.0 + "@typescript-eslint/eslint-plugin": 3.0.0 + "@typescript-eslint/parser": 3.0.0 "@vue/component-compiler-utils": ^3.1.2 babel-core: ^7.0.0-bridge.0 babel-jest: ^26.0.1 @@ -2722,7 +2722,7 @@ __metadata: browserslist: ^4.12.0 coveralls: ^3.1.0 cpx: ^1.5.0 - eslint: ^7.0.0 + eslint: ^7.1.0 eslint-config-standard: ^14.1.1 eslint-import-resolver-node: ^0.3.3 eslint-plugin-header: ^3.0.0 @@ -2744,10 +2744,10 @@ __metadata: madge: ^3.9.0 mkdirp: ^1.0.4 rimraf: ^3.0.2 - typedoc: ^0.17.6 + typedoc: ^0.17.7 typedoc-plugin-markdown: ^2.2.17 typedoc-plugin-no-inherit: ^1.1.10 - typescript: ^3.9.2 + typescript: ^3.9.3 vuepress: ^1.5.0 webpack: ^4.43.0 webpack-cli: ^3.3.11 @@ -2771,7 +2771,7 @@ __metadata: polkadot-exec-typedoc: scripts/polkadot-exec-typedoc.js polkadot-exec-vuepress: scripts/polkadot-exec-vuepress.js polkadot-exec-webpack: scripts/polkadot-exec-webpack.js - checksum: 3/f22c87387f6e82b85689d4a0738e165820dd844cc903bd1fd80d9e0c14258483003322ba007d11f41120618f1f0dc83f533d9855906130aa10ef1caee59e6b1b + checksum: 3/395fd6527f4be34a6790c00b499bab470b3349156d312e3ff23f932bb408b54f363d4aacf35b61ad3cc3f1a93f9f60096a791e9ee757943faf7952703b7fd849 languageName: node linkType: hard @@ -2834,12 +2834,12 @@ __metadata: languageName: unknown linkType: soft -"@polkadot/ts@npm:^0.3.22": - version: 0.3.22 - resolution: "@polkadot/ts@npm:0.3.22" +"@polkadot/ts@npm:^0.3.23": + version: 0.3.23 + resolution: "@polkadot/ts@npm:0.3.23" dependencies: - "@types/chrome": ^0.0.112 - checksum: 3/d8a0531723e5822e28ca06c08b41f7803be4833b2a4640dfb431ae66967cb7e20af057d92983e8bcc17db060e23e95f7a726d759a962a6f98c0ebfaf87bc3afb + "@types/chrome": ^0.0.114 + checksum: 3/ad4b5faf5346e090407549800f5c1aac4be32d89b83af8fbb47ea3643cb34127619602acc8a0b934bb809cff320a603f0ca3136ca7e8aa29a48d42ee140e7e1a languageName: node linkType: hard @@ -3026,13 +3026,13 @@ __metadata: languageName: node linkType: hard -"@types/chrome@npm:^0.0.112": - version: 0.0.112 - resolution: "@types/chrome@npm:0.0.112" +"@types/chrome@npm:^0.0.114": + version: 0.0.114 + resolution: "@types/chrome@npm:0.0.114" dependencies: "@types/filesystem": "*" "@types/har-format": "*" - checksum: 3/51d4dda4b2665bffa97fb5a4b20613685b02e1078c73a2824450f89408f814b46f7a54746dd99de03698d12519758b25d4231cee0ae9fe55d0cb6be46f1870ad + checksum: 3/c03b1579ada5fd3bff88da145790a439417bd2fa8e7cb63e889d3391a54e4076147c9df915bc789c313ff5809357e7f357e1d07f9740f2c636405add2d7a8411 languageName: node linkType: hard @@ -3174,9 +3174,9 @@ __metadata: linkType: hard "@types/node@npm:*, @types/node@npm:>= 8": - version: 14.0.4 - resolution: "@types/node@npm:14.0.4" - checksum: 3/ea723cbd063ab777920a624002d3caaa274482e055d29d92247bd39b4c826f0a62d3badb173f360a9d6fe03ff607ce27310a0b8a4c9835ecb91fa17d9627aecd + version: 14.0.5 + resolution: "@types/node@npm:14.0.5" + checksum: 3/38a9f9b66c2657b4ba520e40073369d4a33438dd45f9c001d98a7cda40e88a5ea28485c320fa00fc706b5473b549cacc9a8b9796e4d69681c032619e12f73f7d languageName: node linkType: hard @@ -3195,9 +3195,9 @@ __metadata: linkType: hard "@types/prettier@npm:^2.0.0": - version: 2.0.0 - resolution: "@types/prettier@npm:2.0.0" - checksum: 3/aee539015e8c815b211ffdb1a4b6e6aab24bd5665b3c71cc1aa95b9b65b3452f3e2b8541146577ba25535317532e6c8d9626e27568a89fad1888f248142a19bb + version: 2.0.1 + resolution: "@types/prettier@npm:2.0.1" + checksum: 3/fba408d98574b9790446bd5d5f1200a1baf164beea676eaad139320a1d1cdf54f2e411a865b253fc75fbadd1a096bb7eacbf13083fa7d26785e98dca57932b47 languageName: node linkType: hard @@ -3249,60 +3249,61 @@ __metadata: languageName: node linkType: hard -"@typescript-eslint/eslint-plugin@npm:2.33.0": - version: 2.33.0 - resolution: "@typescript-eslint/eslint-plugin@npm:2.33.0" +"@typescript-eslint/eslint-plugin@npm:3.0.0": + version: 3.0.0 + resolution: "@typescript-eslint/eslint-plugin@npm:3.0.0" dependencies: - "@typescript-eslint/experimental-utils": 2.33.0 + "@typescript-eslint/experimental-utils": 3.0.0 functional-red-black-tree: ^1.0.1 regexpp: ^3.0.0 + semver: ^7.3.2 tsutils: ^3.17.1 peerDependencies: - "@typescript-eslint/parser": ^2.0.0 - eslint: ^5.0.0 || ^6.0.0 + "@typescript-eslint/parser": ^3.0.0 + eslint: ^5.0.0 || ^6.0.0 || ^7.0.0 typescript: "*" peerDependenciesMeta: typescript: optional: true - checksum: 3/fbac64a9ebf0c7dd61fb2b7bb8cd721116560d78aa5edfed517eea2d68e5e93f86953f99733f0db203a9b5363a53bf6944b23df63242d74ea7184fd2a0f76b3b + checksum: 3/986b1c8f02f2230fff8a45b9302383a140852df17915d41584c8bfe01bf908b2e63c186873312784e0d9e60788ce986c255abe7ceec7251bda93410b06f19fca languageName: node linkType: hard -"@typescript-eslint/experimental-utils@npm:2.33.0": - version: 2.33.0 - resolution: "@typescript-eslint/experimental-utils@npm:2.33.0" +"@typescript-eslint/experimental-utils@npm:3.0.0": + version: 3.0.0 + resolution: "@typescript-eslint/experimental-utils@npm:3.0.0" dependencies: "@types/json-schema": ^7.0.3 - "@typescript-eslint/typescript-estree": 2.33.0 + "@typescript-eslint/typescript-estree": 3.0.0 eslint-scope: ^5.0.0 eslint-utils: ^2.0.0 peerDependencies: eslint: "*" - checksum: 3/d4e084287045b2c7bb9b0762010e7c538fec45492d6e83464181a7f73d1616644655e09eb30948c6e82a908b6859cbec85e3da27b4d5914218030485a99e5252 + checksum: 3/ccaa9b2aea4a7148d301f2384271e35b39ff8d526beb076705140290b497aa75e032c9efac6492a7d03fac65857d999f555534a186e90601059ee295a3cb9d58 languageName: node linkType: hard -"@typescript-eslint/parser@npm:2.33.0": - version: 2.33.0 - resolution: "@typescript-eslint/parser@npm:2.33.0" +"@typescript-eslint/parser@npm:3.0.0": + version: 3.0.0 + resolution: "@typescript-eslint/parser@npm:3.0.0" dependencies: "@types/eslint-visitor-keys": ^1.0.0 - "@typescript-eslint/experimental-utils": 2.33.0 - "@typescript-eslint/typescript-estree": 2.33.0 + "@typescript-eslint/experimental-utils": 3.0.0 + "@typescript-eslint/typescript-estree": 3.0.0 eslint-visitor-keys: ^1.1.0 peerDependencies: - eslint: ^5.0.0 || ^6.0.0 + eslint: ^5.0.0 || ^6.0.0 || ^7.0.0 typescript: "*" peerDependenciesMeta: typescript: optional: true - checksum: 3/dfbe4d5bd7187d98c95a33a8875222af550fd690f5b4d922f6b8ac27dc3113349d81144dc1a6ad7d737289eaf183162eeae2b5a62cf724bf415ed574af99cc67 + checksum: 3/c4388d1a217a026acf9b8ab07e2cf182670e3f3c5b96ef28033a114b794e4ee0d018e63f8c3ef0e9677c075436950afddb886649ca3f0e74e3500389ca307549 languageName: node linkType: hard -"@typescript-eslint/typescript-estree@npm:2.33.0, @typescript-eslint/typescript-estree@npm:^2.29.0": - version: 2.33.0 - resolution: "@typescript-eslint/typescript-estree@npm:2.33.0" +"@typescript-eslint/typescript-estree@npm:3.0.0": + version: 3.0.0 + resolution: "@typescript-eslint/typescript-estree@npm:3.0.0" dependencies: debug: ^4.1.1 eslint-visitor-keys: ^1.1.0 @@ -3316,7 +3317,27 @@ __metadata: peerDependenciesMeta: typescript: optional: true - checksum: 3/d917169d05f709fd5ae4e5b7b336b832f59eeb4a5ecd2a812f63a5c68dd4212366ff321c8c8444cad687047a37454feafa2400652d87022e51d85e6b9cb1621f + checksum: 3/12020a20f0b181204f4287c6b86d12d450cd88d2c788d22502880e364647cbe34213ca81a13265cd010755f8509dc39578b8354b8d0f738014d4a096dde0ef89 + languageName: node + linkType: hard + +"@typescript-eslint/typescript-estree@npm:^2.29.0": + version: 2.34.0 + resolution: "@typescript-eslint/typescript-estree@npm:2.34.0" + dependencies: + debug: ^4.1.1 + eslint-visitor-keys: ^1.1.0 + glob: ^7.1.6 + is-glob: ^4.0.1 + lodash: ^4.17.15 + semver: ^7.3.2 + tsutils: ^3.17.1 + peerDependencies: + typescript: "*" + peerDependenciesMeta: + typescript: + optional: true + checksum: 3/77d1a758dfd4a2813fb51d6102aa79d7eccb006c66db8cff49a10706c8cf64cae6b256b8ec6694058c1c333775e1dbc6ca7501769138fc89165b9c10f8201e40 languageName: node linkType: hard @@ -4437,9 +4458,9 @@ __metadata: linkType: hard "aws4@npm:^1.8.0": - version: 1.9.1 - resolution: "aws4@npm:1.9.1" - checksum: 3/d59822631844f9da1caf966cfab90ffafa22cc6c50835f9f5ebff83acdbcffc24eca44fa50d4aa191a6cee81747df38b9880547cc1df8a1380c80dd507b8e6ce + version: 1.10.0 + resolution: "aws4@npm:1.10.0" + checksum: 3/f8c20a0031a2ae88bb29a89d5e5f8139eb0cc8aa964d0a8d69a476a4b0f6cf3954e3dd40bd08cea69c95ee31e2e69226d82e804628261a2375223ac67582009d languageName: node linkType: hard @@ -5243,9 +5264,9 @@ __metadata: linkType: hard "caniuse-lite@npm:^1.0.0, caniuse-lite@npm:^1.0.30001043, caniuse-lite@npm:^1.0.30001061": - version: 1.0.30001062 - resolution: "caniuse-lite@npm:1.0.30001062" - checksum: 3/53711c8c75be1d09c166b80f355a6ec4e15af1ddaaa24808aa89cae89d7f0dc87292392e31fdcc103d37eab59e02184bb764d1e01fa1d6ac3b3ba8a405739651 + version: 1.0.30001064 + resolution: "caniuse-lite@npm:1.0.30001064" + checksum: 3/5287759ddd5bf00c272d5224d7eaf06996be6f671fce49c33484d2ee8a0403b7eb729ed1ea06e7c3c0d1ba6ad702ffa0948f378dde5c0d985c8c5a4a7b9da9e7 languageName: node linkType: hard @@ -7235,9 +7256,9 @@ __metadata: linkType: hard "electron-to-chromium@npm:^1.3.413": - version: 1.3.448 - resolution: "electron-to-chromium@npm:1.3.448" - checksum: 3/7a96f1bb805bddf15d58e0dc2d95bbcd8bd3d344815300c6e7123ba41c5df1213d17335d245fc19d14d68c97a56518c0b3254e51bc9e198a3b1d7d305c970782 + version: 1.3.451 + resolution: "electron-to-chromium@npm:1.3.451" + checksum: 3/5cd94ad18dd4bef3d1854fbff0d70364424953b03776f3962b1a23767ac106bc27132df4dde5acf01822e4333920afc8f753946dd39bc3ec9d0bcebd769088b9 languageName: node linkType: hard @@ -7729,9 +7750,9 @@ __metadata: languageName: node linkType: hard -"eslint@npm:^7.0.0": - version: 7.0.0 - resolution: "eslint@npm:7.0.0" +"eslint@npm:^7.1.0": + version: 7.1.0 + resolution: "eslint@npm:7.1.0" dependencies: "@babel/code-frame": ^7.0.0 ajv: ^6.10.0 @@ -7771,7 +7792,7 @@ __metadata: v8-compile-cache: ^2.0.3 bin: eslint: bin/eslint.js - checksum: 3/6f5b92b843767f459b60f52312da7ba31c34b8d958f29c1fa96d1c564c270ebe272250f81fe8f1368ddfe2ec2fd3d89c6a160b18effe1269853f7e35c7010317 + checksum: 3/26b8bc7947b9b8c42f05965a24cd9ea261f0d7b2b5993135bdac403bc65df7812338a2a0999810cae865ff877ec0e17eb818534179d765b7ed36a3a90c3a69b3 languageName: node linkType: hard @@ -7923,8 +7944,8 @@ __metadata: linkType: hard "execa@npm:^4.0.0": - version: 4.0.1 - resolution: "execa@npm:4.0.1" + version: 4.0.2 + resolution: "execa@npm:4.0.2" dependencies: cross-spawn: ^7.0.0 get-stream: ^5.0.0 @@ -7935,7 +7956,7 @@ __metadata: onetime: ^5.1.0 signal-exit: ^3.0.2 strip-final-newline: ^2.0.0 - checksum: 3/334a54e5a07290f1b988069db52ff4525e992e1ac6fc7449495635f773ff57aea0d0110b4544796e640f9a47cc14291273ff607dae4534feb31d353203b5b56f + checksum: 3/c48f3d6a044daa1bb5d93486e1c8eee12a8724b439b7f8c270c556a37cf7e2ffd528a86d2ef08adcbe78b485956cfca56c6027ec15d8370bef959097b9ba23ba languageName: node linkType: hard @@ -9677,9 +9698,9 @@ __metadata: linkType: hard "ignore@npm:^5.1.1": - version: 5.1.4 - resolution: "ignore@npm:5.1.4" - checksum: 3/215721af976442f3836b5baa3c1e212c946aadb15609940f851d058b283c84950659bceb245faee7f5476a50d32999af4cdccb7f1c1e4446a728133584938e6c + version: 5.1.6 + resolution: "ignore@npm:5.1.6" + checksum: 3/e7167d699477a44d6065b3ddfaada5f3f7dcc522ea8d702b21b983b2eaadefed2f2b63614e2697446dd2d875ce4c64ce4c1cc80eac2c068d6c5598eddd7d31ce languageName: node linkType: hard @@ -11141,14 +11162,14 @@ __metadata: linkType: hard "js-yaml@npm:^3.11.0, js-yaml@npm:^3.13.1": - version: 3.13.1 - resolution: "js-yaml@npm:3.13.1" + version: 3.14.0 + resolution: "js-yaml@npm:3.14.0" dependencies: argparse: ^1.0.7 esprima: ^4.0.0 bin: js-yaml: bin/js-yaml.js - checksum: 3/277157fdf235757b71cfbf24f6bef57576a26d9b4cf89b63d89c9044da7b0f9d16c3629c8b5fd549ae343523727a0df1598794e9a4429763cee4e17056ff8523 + checksum: 3/2eb95464e5263aedc20ae2d9280f0e29b00adab15ece080ec42473d7055efaab24b904108644d115f687efe05a5bde02972b883aafa93607c4c108f667a56fa7 languageName: node linkType: hard @@ -12875,8 +12896,8 @@ __metadata: linkType: hard "node-notifier@npm:^7.0.0": - version: 7.0.0 - resolution: "node-notifier@npm:7.0.0" + version: 7.0.1 + resolution: "node-notifier@npm:7.0.1" dependencies: growly: ^1.3.0 is-wsl: ^2.1.1 @@ -12884,7 +12905,7 @@ __metadata: shellwords: ^0.1.1 uuid: ^7.0.3 which: ^2.0.2 - checksum: 3/1f47316d572bb0e448525a62334605bf51c7768998dbe9b93ad1fa1b3b10285664ed5cff9817fe043854442a632d77ce3978c6b4f77074696622ed03565ff65a + checksum: 3/d851b89ba6e6cbab7803370516ff25424b95d2fa0d0a15c01c199447502cd959f2153d2976674eb297a01faff64a85598297e54da362c933c3fb199ecfc39118 languageName: node linkType: hard @@ -15684,8 +15705,8 @@ __metadata: "@babel/core": ^7.9.6 "@babel/register": ^7.9.0 "@babel/runtime": ^7.9.6 - "@polkadot/dev": ^0.53.5 - "@polkadot/ts": ^0.3.22 + "@polkadot/dev": ^0.54.1 + "@polkadot/ts": ^0.3.23 "@polkadot/typegen": "workspace:packages/typegen" "@types/jest": ^25.2.3 "@vuepress/plugin-search": ^1.5.0 @@ -16326,12 +16347,12 @@ __metadata: linkType: hard "spdx-correct@npm:^3.0.0": - version: 3.1.0 - resolution: "spdx-correct@npm:3.1.0" + version: 3.1.1 + resolution: "spdx-correct@npm:3.1.1" dependencies: spdx-expression-parse: ^3.0.0 spdx-license-ids: ^3.0.0 - checksum: 3/3b0874df2bb18f7bd1f7e1308b5bd5f1184b55c23753eb0ae4d4f4cd9e9006ce4ec800df7b3f438fdd64b4dc7e923d46787e7f7bda2abae4c1d6f161dd93163b + checksum: 3/f3413eb225ef9f13aa2ec05230ff7669bffad055a7f62ec85164dd27f00a9f1e19880554a8fa5350fc434764ff895836c207f98813511a0180b0e929581bfe01 languageName: node linkType: hard @@ -17585,7 +17606,7 @@ __metadata: languageName: node linkType: hard -"typedoc@npm:^0.17.6": +"typedoc@npm:^0.17.7": version: 0.17.7 resolution: "typedoc@npm:0.17.7" dependencies: @@ -17607,7 +17628,7 @@ __metadata: languageName: node linkType: hard -"typescript@^3.0.3, typescript@^3.7.5, typescript@^3.8.3, typescript@^3.9.2": +"typescript@^3.0.3, typescript@^3.7.5, typescript@^3.8.3, typescript@^3.9.3": version: 3.9.3 resolution: "typescript@npm:3.9.3" bin: @@ -17617,7 +17638,7 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@^3.0.3#builtin, typescript@patch:typescript@^3.7.5#builtin, typescript@patch:typescript@^3.8.3#builtin, typescript@patch:typescript@^3.9.2#builtin": +"typescript@patch:typescript@^3.0.3#builtin, typescript@patch:typescript@^3.7.5#builtin, typescript@patch:typescript@^3.8.3#builtin, typescript@patch:typescript@^3.9.3#builtin": version: 3.9.3 resolution: "typescript@patch:typescript@npm%3A3.9.3#builtin::version=3.9.3&hash=8cac75" bin: