diff --git a/CHANGELOG.md b/CHANGELOG.md index 370c8c9da5..e15478126a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Changes: - Generated TS Enum interfaces now expose the `type` (with allowed values) - Add Kusama 9130 upgrade block +- Internal maintainability cleanups ## 6.11.1 Dec 5, 2021 diff --git a/packages/api-derive/src/accounts/flags.ts b/packages/api-derive/src/accounts/flags.ts index a60cd8b46b..ad5c149802 100644 --- a/packages/api-derive/src/accounts/flags.ts +++ b/packages/api-derive/src/accounts/flags.ts @@ -40,15 +40,11 @@ function parseFlags (address: AccountId | Address | string | null | undefined, [ */ export function flags (instanceId: string, api: ApiInterfaceRx): (address?: AccountId | Address | string | null) => Observable { return memo(instanceId, (address?: AccountId | Address | string | null): Observable => { - const councilSection = api.query.phragmenElection - ? 'phragmenElection' - : api.query.electionsPhragmen - ? 'electionsPhragmen' - : 'elections'; + const elections = api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections; return combineLatest([ - address && api.query[councilSection]?.members - ? api.query[councilSection].members>>() + address && elections?.members + ? elections.members>>() : of(undefined), address && api.query.council?.members ? api.query.council.members() @@ -63,7 +59,7 @@ export function flags (instanceId: string, api: ApiInterfaceRx): (address?: Acco ? api.query.sudo.key() : of(undefined) ]).pipe( - map((result) => parseFlags(address, result)) + map((r) => parseFlags(address, r)) ); }); } diff --git a/packages/api-derive/src/balances/all.ts b/packages/api-derive/src/balances/all.ts index 4e7c415d15..9fa1dc7695 100644 --- a/packages/api-derive/src/balances/all.ts +++ b/packages/api-derive/src/balances/all.ts @@ -165,9 +165,7 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId, balanceInstanc return [ vesting - ? Array.isArray(vesting) - ? vesting - : [vesting] + ? Array.isArray(vesting) ? vesting : [vesting] : null, lockEmpty.map((e) => e ? api.registry.createType>('Vec') : locks[++offset]) ]; diff --git a/packages/api-derive/src/bounties/bounties.ts b/packages/api-derive/src/bounties/bounties.ts index 038e26168a..d513fd82c0 100644 --- a/packages/api-derive/src/bounties/bounties.ts +++ b/packages/api-derive/src/bounties/bounties.ts @@ -42,14 +42,12 @@ export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observ ? api.query.council.proposalCount() : of(0) ]).pipe( - switchMap(() => - combineLatest([ - bountyBase.bounties.keys<[BountyIndex]>(), - api.derive.council - ? api.derive.council.proposals() - : of([]) - ]) - ), + switchMap(() => combineLatest([ + bountyBase.bounties.keys<[BountyIndex]>(), + api.derive.council + ? api.derive.council.proposals() + : of([]) + ])), switchMap(([keys, proposals]): Observable => { const ids = keys.map(({ args: [id] }) => id); diff --git a/packages/api-derive/src/democracy/dispatchQueue.ts b/packages/api-derive/src/democracy/dispatchQueue.ts index ff6dbfe838..6faebd8f10 100644 --- a/packages/api-derive/src/democracy/dispatchQueue.ts +++ b/packages/api-derive/src/democracy/dispatchQueue.ts @@ -61,10 +61,8 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], (Opt // however we have had cases on Darwinia where the indices have moved around after an // upgrade, which results in invalid on-chain data combineLatest(blockNumbers.map((blockNumber) => - api.query.scheduler.agenda(blockNumber).pipe( - // this does create an issue since it discards all at that block - catchError(() => of(null)) - ) + // this does create an issue since it discards all at that block + api.query.scheduler.agenda(blockNumber).pipe(catchError(() => of(null))) )) ]) : of<[BlockNumber[], null[]]>([[], []]); @@ -78,30 +76,23 @@ function queryScheduler (api: ApiInterfaceRx): Observable { const result: SchedulerInfo[] = []; blockNumbers.forEach((at, index): void => { - (agendas[index] || []) - .filter((opt) => opt.isSome) - .forEach((optScheduled): void => { - const scheduled = optScheduled.unwrap(); + (agendas[index] || []).filter((o) => o.isSome).forEach((o): void => { + const scheduled = o.unwrap(); - if (scheduled.maybeId.isSome) { - const id = scheduled.maybeId.unwrap().toHex(); + if (scheduled.maybeId.isSome) { + const id = scheduled.maybeId.unwrap().toHex(); - if (id.startsWith(DEMOCRACY_ID)) { - const [, index] = api.registry.createType('(u64, ReferendumIndex)', id); - const imageHash = scheduled.call.args[0] as Hash; - - result.push({ at, imageHash, index }); - } - } - }); + id.startsWith(DEMOCRACY_ID) && result.push({ at, imageHash: scheduled.call.args[0] as Hash, index: api.registry.createType('(u64, ReferendumIndex)', id)[1] }); + } + }); }); - return result.length - ? combineLatest([ - of(result), - api.derive.democracy.preimages(result.map(({ imageHash }) => imageHash)) - ]) - : of([[], []]); + return combineLatest([ + of(result), + result.length + ? api.derive.democracy.preimages(result.map(({ imageHash }) => imageHash)) + : of([]) + ]); }), map(([infos, images]): DeriveDispatch[] => infos.map((info, index) => ({ ...info, image: images[index] })) diff --git a/packages/api-derive/src/elections/info.ts b/packages/api-derive/src/elections/info.ts index 25616f9c89..fd29b01360 100644 --- a/packages/api-derive/src/elections/info.ts +++ b/packages/api-derive/src/elections/info.ts @@ -42,6 +42,18 @@ function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [Accoun return balanceB.cmp(balanceA); } +function getConstants (api: ApiInterfaceRx, elections: string | null): Partial { + return elections + ? { + candidacyBond: api.consts[elections].candidacyBond as Balance, + desiredRunnersUp: api.consts[elections].desiredRunnersUp as u32, + desiredSeats: api.consts[elections].desiredMembers as u32, + termDuration: api.consts[elections].termDuration as BlockNumber, + votingBond: api.consts[elections].votingBond as Balance + } + : {}; +} + function queryElections (api: ApiInterfaceRx): Observable { const elections = api.query.phragmenElection ? 'phragmenElection' @@ -68,17 +80,7 @@ function queryElections (api: ApiInterfaceRx): Observable { ]) ).pipe( map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({ - ...( - elections - ? { - candidacyBond: api.consts[elections].candidacyBond as Balance, - desiredRunnersUp: api.consts[elections].desiredRunnersUp as u32, - desiredSeats: api.consts[elections].desiredMembers as u32, - termDuration: api.consts[elections].termDuration as BlockNumber, - votingBond: api.consts[elections].votingBond as Balance - } - : {} - ), + ...getConstants(api, elections), candidateCount: api.registry.createType('u32', candidates.length), candidates: candidates.map(getCandidate), members: members.length diff --git a/packages/api-derive/src/staking/query.ts b/packages/api-derive/src/staking/query.ts index b79c6f3aef..520c491dda 100644 --- a/packages/api-derive/src/staking/query.ts +++ b/packages/api-derive/src/staking/query.ts @@ -29,8 +29,8 @@ function parseDetails (stashId: AccountId, controllerIdOpt: Option | function getLedgers (api: ApiInterfaceRx, optIds: (Option | null)[], { withLedger = false }: StakingQueryFlags): Observable[]> { const ids = optIds - .filter((opt): opt is Option => withLedger && !!opt && opt.isSome) - .map((opt) => opt.unwrap()); + .filter((o): o is Option => withLedger && !!o && o.isSome) + .map((o) => o.unwrap()); const emptyLed = api.registry.createType>('Option'); return ( diff --git a/packages/api/src/base/Init.ts b/packages/api/src/base/Init.ts index 021a3a48e9..e32af9b220 100644 --- a/packages/api/src/base/Init.ts +++ b/packages/api/src/base/Init.ts @@ -7,6 +7,7 @@ import type { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types'; import type { ChainProperties, Hash, RuntimeVersion, RuntimeVersionPartial } from '@polkadot/types/interfaces'; import type { Registry } from '@polkadot/types/types'; import type { BN } from '@polkadot/util'; +import type { HexString } from '@polkadot/util/types'; import type { ApiBase, ApiDecoration, ApiOptions, ApiTypes, DecorateMethod } from '../types'; import type { VersionedRegistry } from './types'; @@ -172,7 +173,7 @@ export abstract class Init extends Decorate { // nothing has been found, construct new const registry = new TypeRegistry(blockHash); const metadata = new Metadata(registry, - await firstValueFrom(this._rpcCore.state.getMetadata.raw(header.parentHash)) + await firstValueFrom(this._rpcCore.state.getMetadata.raw(header.parentHash)) ); this._initRegistry(registry, this._runtimeChain as Text, version, metadata); @@ -314,7 +315,7 @@ export abstract class Init extends Decorate { ).subscribe(); } - private async _metaFromChain (optMetadata?: Record): Promise<[Hash, Metadata]> { + private async _metaFromChain (optMetadata?: Record): Promise<[Hash, Metadata]> { const [genesisHash, runtimeVersion, chain, chainProps, rpcMethods, chainMetadata] = await Promise.all([ firstValueFrom(this._rpcCore.chain.getBlockHash(0)), firstValueFrom(this._rpcCore.state.getRuntimeVersion()), diff --git a/packages/api/src/checkTypes.manual.ts b/packages/api/src/checkTypes.manual.ts index 57bfd2c051..1a3e0621eb 100644 --- a/packages/api/src/checkTypes.manual.ts +++ b/packages/api/src/checkTypes.manual.ts @@ -85,35 +85,6 @@ async function query (api: ApiPromise, pairs: TestKeyringMap): Promise { const multib = await api.query.system.account.multi([pairs.alice.address, pairs.bob.address]); console.log('query types:', bar, bal, bal2, override, oldBal, multia, multib); - - // check multi for unsub - const multiUnsub = await api.queryMulti([ - [api.query.staking.validators], - [api.query.system.events] - ], (values): void => { - console.log('values', values); - - multiUnsub(); - }); - - // check multi , Promise result - const multiRes = await api.queryMulti([ - [api.query.system.account, pairs.eve.address], - // older chains only - [api.query.system.accountNonce, pairs.eve.address] - ]); - - console.log(multiRes); - - // check multi, via at - const apiAt = await api.at('0x12345678'); - const multiResAt = await apiAt.queryMulti([ - api.query.timestamp.now, - [apiAt.query.staking.validators], - [apiAt.query.system.account, pairs.eve.address] - ]); - - console.log(multiResAt); } async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise { @@ -165,6 +136,37 @@ async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise { + // check multi for unsub + const multiUnsub = await api.queryMulti([ + [api.query.staking.validators], + [api.query.system.events] + ], (values): void => { + console.log('values', values); + + multiUnsub(); + }); + + // check multi , Promise result + const multiRes = await api.queryMulti([ + [api.query.system.account, pairs.eve.address], + // older chains only + [api.query.system.accountNonce, pairs.eve.address] + ]); + + console.log(multiRes); + + // check multi, via at + const apiAt = await api.at('0x12345678'); + const multiResAt = await apiAt.queryMulti([ + api.query.timestamp.now, + [apiAt.query.staking.validators], + [apiAt.query.system.account, pairs.eve.address] + ]); + + console.log(multiResAt); +} + async function rpc (api: ApiPromise): Promise { // defaults await api.rpc.chain.subscribeNewHeads((header): void => { @@ -270,6 +272,7 @@ async function main (): Promise { events(api), query(api, pairs), queryExtra(api, pairs), + queryMulti(api, pairs), rpc(api), types(api), tx(api, pairs), diff --git a/packages/api/src/promise/index.spec.ts b/packages/api/src/promise/index.spec.ts index 75471cb10e..8feab88c51 100644 --- a/packages/api/src/promise/index.spec.ts +++ b/packages/api/src/promise/index.spec.ts @@ -1,6 +1,7 @@ // Copyright 2017-2021 @polkadot/api authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; import type { SubmittableExtrinsic } from '../types'; import { jest } from '@jest/globals'; @@ -56,7 +57,7 @@ describe('ApiPromise', (): void => { describe('initialization', (): void => { it('Create API instance with metadata map and makes the runtime, rpc, state & extrinsics available', async (): Promise => { - const rpcData = await provider.send('state_getMetadata', []); + const rpcData = await provider.send('state_getMetadata', []); const genesisHash = registry.createType('Hash', await provider.send('chain_getBlockHash', [])).toHex(); const specVersion = 0; const api = await ApiPromise.create({ metadata: { [`${genesisHash}-${specVersion}`]: rpcData }, provider, registry, throwOnConnect: true }); diff --git a/packages/api/src/types/index.ts b/packages/api/src/types/index.ts index 73b84e002d..b0de37a33a 100644 --- a/packages/api/src/types/index.ts +++ b/packages/api/src/types/index.ts @@ -17,6 +17,7 @@ import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces'; import type { Metadata } from '@polkadot/types/metadata'; import type { CallFunction, DefinitionRpc, DefinitionRpcSub, RegisteredTypes, Registry, RegistryError, SignatureOptions, Signer } from '@polkadot/types/types'; import type { BN } from '@polkadot/util'; +import type { HexString } from '@polkadot/util/types'; import type { ApiBase } from '../base'; import type { DeriveAllSections } from '../util/decorate'; import type { ApiTypes } from './base'; @@ -54,7 +55,7 @@ export interface ApiOptions extends RegisteredTypes { * @description pre-bundles is a map of 'genesis hash and runtime spec version' as key to a metadata hex string * if genesis hash and runtime spec version matches, then use metadata, else fetch it from chain */ - metadata?: Record; + metadata?: Record; /** * @description Transport Provider from rpc-provider. If not specified, it will default to * connecting to a WsProvider connecting localhost with the default port, i.e. `ws://127.0.0.1:9944` diff --git a/packages/typegen/src/fromChain.ts b/packages/typegen/src/fromChain.ts index d000c6ffc5..92d5714e2e 100644 --- a/packages/typegen/src/fromChain.ts +++ b/packages/typegen/src/fromChain.ts @@ -1,6 +1,8 @@ // Copyright 2017-2021 @polkadot/typegen authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; + import path from 'path'; import yargs from 'yargs'; @@ -11,12 +13,13 @@ import { WebSocket } from '@polkadot/x-ws'; import { generateDefaultConsts, generateDefaultErrors, generateDefaultEvents, generateDefaultQuery, generateDefaultRpc, generateDefaultTx } from './generate'; import { HEADER, writeFile } from './util'; -function generate (metaHex: string, pkg: string | undefined, output: string, isStrict?: boolean): void { +function generate (metaHex: HexString, pkg: string | undefined, output: string, isStrict?: boolean): void { console.log(`Generating from metadata, ${formatNumber((metaHex.length - 2) / 2)} bytes`); + const base = path.join(process.cwd(), output); const extraTypes = pkg // eslint-disable-next-line @typescript-eslint/no-var-requires - ? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record } + ? { [pkg]: require(path.join(base, 'definitions')) as Record } : {}; let customLookupDefinitions; @@ -25,20 +28,20 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS customLookupDefinitions = { rpc: {}, // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires - types: require(path.join(process.cwd(), output, 'lookup.ts')).default + types: require(path.join(base, 'lookup.ts')).default } as Definitions; } catch (error) { console.log('No custom definitions found.'); } - generateDefaultConsts(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); - generateDefaultErrors(path.join(process.cwd(), output, 'augment-api-errors.ts'), metaHex, extraTypes, isStrict); - generateDefaultEvents(path.join(process.cwd(), output, 'augment-api-events.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); - generateDefaultQuery(path.join(process.cwd(), output, 'augment-api-query.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); - generateDefaultRpc(path.join(process.cwd(), output, 'augment-api-rpc.ts'), extraTypes); - generateDefaultTx(path.join(process.cwd(), output, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); + generateDefaultConsts(path.join(base, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); + generateDefaultErrors(path.join(base, 'augment-api-errors.ts'), metaHex, extraTypes, isStrict); + generateDefaultEvents(path.join(base, 'augment-api-events.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); + generateDefaultQuery(path.join(base, 'augment-api-query.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); + generateDefaultRpc(path.join(base, 'augment-api-rpc.ts'), extraTypes); + generateDefaultTx(path.join(base, 'augment-api-tx.ts'), metaHex, extraTypes, isStrict, customLookupDefinitions); - writeFile(path.join(process.cwd(), output, 'augment-api.ts'), (): string => + writeFile(path.join(base, 'augment-api.ts'), (): string => [ HEADER('chain'), ...[ @@ -95,13 +98,13 @@ export function main (): void { }; websocket.onmessage = (message: unknown): void => { - generate((JSON.parse((message as Record).data) as Record).result, pkg, output, isStrict); + generate((JSON.parse((message as Record).data) as Record).result, pkg, output, isStrict); }; } catch (error) { process.exit(1); } } else { // eslint-disable-next-line @typescript-eslint/no-var-requires - generate((require(path.join(process.cwd(), endpoint)) as Record).result, pkg, output, isStrict); + generate((require(path.join(process.cwd(), endpoint)) as Record).result, pkg, output, isStrict); } } diff --git a/packages/typegen/src/fromDefs.ts b/packages/typegen/src/fromDefs.ts index d0ea386f55..8a55f7d578 100644 --- a/packages/typegen/src/fromDefs.ts +++ b/packages/typegen/src/fromDefs.ts @@ -1,6 +1,8 @@ // Copyright 2017-2021 @polkadot/typegen authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; + import path from 'path'; import yargs from 'yargs'; @@ -32,7 +34,7 @@ export function main (): void { if (endpoint) { // eslint-disable-next-line @typescript-eslint/no-var-requires - const metaHex = (require(path.join(process.cwd(), endpoint)) as Record).result; + const metaHex = (require(path.join(process.cwd(), endpoint)) as Record).result; generateDefaultLookup(path.join(process.cwd(), input), metaHex); } diff --git a/packages/typegen/src/generate/consts.ts b/packages/typegen/src/generate/consts.ts index 8e89ca48e5..419425fd08 100644 --- a/packages/typegen/src/generate/consts.ts +++ b/packages/typegen/src/generate/consts.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { Metadata } from '@polkadot/types/metadata/Metadata'; +import type { HexString } from '@polkadot/util/types'; import type { ExtraTypes } from './types'; import Handlebars from 'handlebars'; @@ -85,7 +86,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, // Call `generateForMeta()` with current static metadata /** @internal */ -export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { +export function generateDefaultConsts (dest = 'packages/api/src/augment/consts.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { const { metadata } = initMeta(data, extraTypes); return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions); diff --git a/packages/typegen/src/generate/errors.ts b/packages/typegen/src/generate/errors.ts index fdccb6a460..c88c5066b0 100644 --- a/packages/typegen/src/generate/errors.ts +++ b/packages/typegen/src/generate/errors.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { Metadata } from '@polkadot/types/metadata/Metadata'; +import type { HexString } from '@polkadot/util/types'; import type { ExtraTypes } from './types'; import Handlebars from 'handlebars'; @@ -48,7 +49,7 @@ function generateForMeta (meta: Metadata, dest: string, isStrict: boolean): void // Call `generateForMeta()` with current static metadata /** @internal */ -export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false): void { +export function generateDefaultErrors (dest = 'packages/api/src/augment/errors.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false): void { const { metadata } = initMeta(data, extraTypes); return generateForMeta(metadata, dest, isStrict); diff --git a/packages/typegen/src/generate/events.ts b/packages/typegen/src/generate/events.ts index 53ab77db5b..0d91d2ea9d 100644 --- a/packages/typegen/src/generate/events.ts +++ b/packages/typegen/src/generate/events.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { Metadata } from '@polkadot/types/metadata/Metadata'; +import type { HexString } from '@polkadot/util/types'; import type { ExtraTypes } from './types'; import Handlebars from 'handlebars'; @@ -77,7 +78,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, // Call `generateForMeta()` with current static metadata /** @internal */ -export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { +export function generateDefaultEvents (dest = 'packages/api/src/augment/events.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { const { metadata } = initMeta(data, extraTypes); return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions); diff --git a/packages/typegen/src/generate/lookup.ts b/packages/typegen/src/generate/lookup.ts index a9c646e08f..9686faa8e3 100644 --- a/packages/typegen/src/generate/lookup.ts +++ b/packages/typegen/src/generate/lookup.ts @@ -4,6 +4,7 @@ import type { PortableType, SiLookupTypeId, SiPath, SiTypeParameter } from '@polkadot/types/interfaces'; import type { PortableRegistry } from '@polkadot/types/metadata'; import type { TypeDef } from '@polkadot/types/types'; +import type { HexString } from '@polkadot/util/types'; import Handlebars from 'handlebars'; import path from 'path'; @@ -213,7 +214,7 @@ function generateLookupTypes (registry: Registry, filtered: [PortableType, TypeD writeFile(path.join(destDir, 'index.ts'), () => generateLookupIndexTmpl({ headerType: 'defs' }), true); } -function generateLookup (destDir: string, entries: [string | undefined, string][]): void { +function generateLookup (destDir: string, entries: [string | undefined, HexString][]): void { entries.reduce((exclude, [subPath, staticMeta]): string[] => { const { lookup, registry } = initMeta(staticMeta).metadata.asLatest; const filtered = getFilteredTypes(lookup, exclude); @@ -230,7 +231,7 @@ function generateLookup (destDir: string, entries: [string | undefined, string][ } // Generate `packages/types/src/lookup/*s`, the registry of all lookup types -export function generateDefaultLookup (destDir = 'packages/types/src/augment/lookup', staticData?: string): void { +export function generateDefaultLookup (destDir = 'packages/types/src/augment/lookup', staticData?: HexString): void { generateLookup( destDir, staticData diff --git a/packages/typegen/src/generate/query.ts b/packages/typegen/src/generate/query.ts index 81b4d5aa77..fda1f51422 100644 --- a/packages/typegen/src/generate/query.ts +++ b/packages/typegen/src/generate/query.ts @@ -4,6 +4,7 @@ import type { StorageEntryMetadataLatest } from '@polkadot/types/interfaces'; import type { Metadata, PortableRegistry } from '@polkadot/types/metadata'; import type { Definitions, Registry } from '@polkadot/types/types'; +import type { HexString } from '@polkadot/util/types'; import type { ExtraTypes } from './types'; import Handlebars from 'handlebars'; @@ -134,7 +135,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr // Call `generateForMeta()` with current static metadata /** @internal */ -export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { +export function generateDefaultQuery (dest = 'packages/api/src/augment/query.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { const { metadata, registry } = initMeta(data, extraTypes); return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions); diff --git a/packages/typegen/src/generate/tx.ts b/packages/typegen/src/generate/tx.ts index 36282bb1ec..e9482b4285 100644 --- a/packages/typegen/src/generate/tx.ts +++ b/packages/typegen/src/generate/tx.ts @@ -3,6 +3,7 @@ import type { Metadata } from '@polkadot/types/metadata/Metadata'; import type { Definitions, Registry } from '@polkadot/types/types'; +import type { HexString } from '@polkadot/util/types'; import type { ExtraTypes } from './types'; import Handlebars from 'handlebars'; @@ -119,7 +120,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr // Call `generateForMeta()` with current static metadata /** @internal */ -export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: string, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { +export function generateDefaultTx (dest = 'packages/api/src/augment/tx.ts', data?: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void { const { metadata, registry } = initMeta(data, extraTypes); return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions); diff --git a/packages/typegen/src/util/initMeta.ts b/packages/typegen/src/util/initMeta.ts index 601ece2653..01beac3e70 100644 --- a/packages/typegen/src/util/initMeta.ts +++ b/packages/typegen/src/util/initMeta.ts @@ -1,6 +1,7 @@ // Copyright 2017-2021 @polkadot/typegen authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; import type { ExtraTypes } from '../generate/types'; import { Metadata, TypeRegistry } from '@polkadot/types'; @@ -13,7 +14,7 @@ interface Result { registry: TypeRegistry; } -export function initMeta (staticMeta = staticSubstrate, extraTypes: ExtraTypes = {}): Result { +export function initMeta (staticMeta: HexString = staticSubstrate, extraTypes: ExtraTypes = {}): Result { const registry = new TypeRegistry(); registerDefinitions(registry, extraTypes); diff --git a/packages/types/src/metadata/Metadata.spec.ts b/packages/types/src/metadata/Metadata.spec.ts index fcaa7ed32e..cf362bab5f 100644 --- a/packages/types/src/metadata/Metadata.spec.ts +++ b/packages/types/src/metadata/Metadata.spec.ts @@ -1,6 +1,8 @@ // Copyright 2017-2021 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; + import kusama from '@polkadot/types-support/metadata/static-kusama'; import polkadot from '@polkadot/types-support/metadata/static-polkadot'; import substrate from '@polkadot/types-support/metadata/static-substrate'; @@ -8,7 +10,7 @@ import substrate from '@polkadot/types-support/metadata/static-substrate'; import { TypeRegistry } from '../create'; import { Metadata } from './Metadata'; -const allData: Record = { +const allData: Record = { kusama, polkadot, substrate diff --git a/packages/types/src/metadata/Metadata.ts b/packages/types/src/metadata/Metadata.ts index 4453f06153..265807d75e 100644 --- a/packages/types/src/metadata/Metadata.ts +++ b/packages/types/src/metadata/Metadata.ts @@ -1,6 +1,7 @@ // Copyright 2017-2021 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; import type { Registry } from '../types'; import { isHex, isU8a, u8aToU8a } from '@polkadot/util'; @@ -12,42 +13,30 @@ const VERSION_IDX = 4; // magic + lowest supported version const EMPTY_METADATA = new Uint8Array([0x6d, 0x65, 0x74, 0x61, 9]); -const EMPTY_U8A = new Uint8Array(); -function toU8a (value: Uint8Array | string = EMPTY_U8A): Uint8Array { - if (isHex(value)) { - return toU8a(u8aToU8a(value)); - } else if (isU8a(value)) { - return value.length === 0 +function toU8a (value: Uint8Array | HexString): Uint8Array { + return isHex(value) + ? toU8a(u8aToU8a(value)) + : value.length === 0 ? EMPTY_METADATA : value; - } - - throw new Error('Invalid type passed to Metadata constructor'); } -function decodeMetadata (registry: Registry, _value?: Uint8Array | string | Map | Record): MetadataVersioned { - if (isU8a(_value) || !_value || isHex(_value)) { - const value = toU8a(_value); - const version = value[VERSION_IDX]; +function decodeU8a (registry: Registry, value: Uint8Array): MetadataVersioned { + try { + return new MetadataVersioned(registry, value); + } catch (error) { + // This is an f-ing hack as a follow-up to another ugly hack + // https://github.com/polkadot-js/api/commit/a9211690be6b68ad6c6dad7852f1665cadcfa5b2 + // when we fail on V9, try to re-parse it as v10... yes... HACK + if (value[VERSION_IDX] === 9) { + value[VERSION_IDX] = 10; - try { - return new MetadataVersioned(registry, value); - } catch (error) { - // This is an f-ing hack as a follow-up to another ugly hack - // https://github.com/polkadot-js/api/commit/a9211690be6b68ad6c6dad7852f1665cadcfa5b2 - // when we fail on V9, try to re-parse it as v10... yes... HACK - if (version === 9) { - value[VERSION_IDX] = 10; - - return decodeMetadata(registry, value); - } - - throw error; + return decodeU8a(registry, value); } - } - return new MetadataVersioned(registry, _value); + throw error; + } } /** @@ -56,7 +45,12 @@ function decodeMetadata (registry: Registry, _value?: Uint8Array | string | Map< * The versioned runtime metadata as a decoded structure */ export class Metadata extends MetadataVersioned { - constructor (registry: Registry, value?: Uint8Array | string | Map | Record) { - super(registry, decodeMetadata(registry, value)); + constructor (registry: Registry, value?: Uint8Array | HexString | Map | Record) { + super( + registry, + isU8a(value) || isHex(value) + ? decodeU8a(registry, toU8a(value)) + : new MetadataVersioned(registry, value) + ); } } diff --git a/packages/types/src/metadata/decorate/constants/index.spec.ts b/packages/types/src/metadata/decorate/constants/index.spec.ts index 56abc8e278..fadffd5c66 100644 --- a/packages/types/src/metadata/decorate/constants/index.spec.ts +++ b/packages/types/src/metadata/decorate/constants/index.spec.ts @@ -1,6 +1,7 @@ // Copyright 2017-2021 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; import type { BlockNumber } from '../../../interfaces'; import type { Constants } from '../types'; @@ -11,7 +12,7 @@ import { TypeRegistry } from '../../../create'; import { Metadata } from '../../Metadata'; import { decorateConstants } from '..'; -function init (meta: string): [Constants, TypeRegistry] { +function init (meta: HexString): [Constants, TypeRegistry] { const registry = new TypeRegistry(); const metadata = new Metadata(registry, meta); diff --git a/packages/types/src/metadata/util/types.ts b/packages/types/src/metadata/util/types.ts index 023c611691..32b4be51ba 100644 --- a/packages/types/src/metadata/util/types.ts +++ b/packages/types/src/metadata/util/types.ts @@ -1,9 +1,11 @@ // Copyright 2017-2021 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { HexString } from '@polkadot/util/types'; + export interface Check { compare: Record; - data: string; + data: HexString; fails?: string[]; types?: Record; }