From e7669c2b000f6b8834648a9d0a8e1c3c8c0abc20 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Mon, 27 Jul 2020 09:12:04 +0200 Subject: [PATCH] Add api typesBundle (#2422) * Add api typesBundle * Inject user-defined RPC from spec/chain * Linting cleanups * Invert check fro non-existing * Extract bundle injection * Ignore RPC for the first round * CHANGELOG * Merge master --- CHANGELOG.md | 3 ++- packages/api/src/base/Init.ts | 35 ++++++++++++++++++++++++- packages/rpc-core/src/index.ts | 39 +++++++++++++++++++--------- packages/types-known/src/index.ts | 31 +++++++++++++++++++++- packages/types/src/types/registry.ts | 16 ++++++++++++ 5 files changed, 109 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0e6105e41..8b63dc893c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,10 @@ ## 1.26.0-beta.x -- Update docs for the new `system.accuntNextIndex` (Thanks to https://github.com/shawntabrizi) +- Update docs for the new `system.accountNextIndex` (Thanks to https://github.com/shawntabrizi) - Adjust votingBalance to only return `freeBalance` (only council voting is free + reserved) - Additional checks for referenced Vec sub-type deconstruction in typegen +- Allow for API `typesBundle` option to inject a group of chain versions types - `@polkadot/util` 3.0 ## 1.25.1 Jul 20, 2020 diff --git a/packages/api/src/base/Init.ts b/packages/api/src/base/Init.ts index d4f6e1f3b1..4ddc5fe976 100644 --- a/packages/api/src/base/Init.ts +++ b/packages/api/src/base/Init.ts @@ -9,7 +9,7 @@ import { Observable, Subscription, of } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; import { Metadata, Text } from '@polkadot/types'; import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic'; -import { getMetadataTypes, getSpecTypes } from '@polkadot/types-known'; +import { getMetadataTypes, getSpecAlias, getSpecTypes } from '@polkadot/types-known'; import { logger } from '@polkadot/util'; import { cryptoWaitReady } from '@polkadot/util-crypto'; @@ -35,6 +35,7 @@ export default abstract class Init extends Decorate extends Decorate { + // if (this._rpc) { + // if (!this._rpc[section as 'author']) { + // this._rpc[section as 'author'] = {} as DecoratedRpcSection; + // } + + // Object.entries(value).forEach(([name, method]): void => { + // if (this._rpc && !this._rpc[section as 'author'][name as 'hasKey']) { + // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + // this._rpc[section as 'author'][name as 'hasKey'] = method; + // } + // }); + // } + // }); + } + private async _metaFromChain (optMetadata: Record): Promise { const [runtimeVersion, chain, chainProps] = await Promise.all([ this._rpcCore.state.getRuntimeVersion().toPromise(), @@ -159,6 +187,11 @@ export default abstract class Init extends Decorate (userRpc: Record>): void { - const sectionNames = Object.keys(jsonrpc); - - // these are the base keys (i.e. part of jsonrpc) - this.sections.push(...sectionNames); - + public addUserInterfaces
(userRpc: Record>): void { // add any extra user-defined sections - this.sections.push(...Object.keys(userRpc).filter((key): boolean => !this.sections.includes(key))); + this.sections.push(...Object.keys(userRpc).filter((key) => !this.sections.includes(key))); // decorate the sections with base and user methods this.sections.forEach((sectionName): void => { - (this as Record)[sectionName as Section] = { - ...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}), - ...this._createInterface(sectionName, userRpc[sectionName] || {}) - }; + if (!(this as Record)[sectionName as Section]) { + (this as Record)[sectionName as Section] = {}; + } + + const section = (this as Record)[sectionName as Section] as Record; + + Object + .entries({ + ...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}), + ...this._createInterface(sectionName, userRpc[sectionName] || {}) + }) + .forEach(([key, value]): void => { + // we don't want to clobber existing, i.e. when this is called again after chain is determined + if (!section[key]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + section[key] = value; + } + }); }); } private _createInterface
(section: string, methods: Record): RpcInterface[Section] { return Object .keys(methods) + .filter((method) => !this.mapping.has(`${section}_${method}`)) .reduce((exposed, method): RpcInterface[Section] => { const def = methods[method]; const isSubscription = !!(def as DefinitionRpcSub).pubsub; diff --git a/packages/types-known/src/index.ts b/packages/types-known/src/index.ts index 39644c0e45..2e9e4a4e55 100644 --- a/packages/types-known/src/index.ts +++ b/packages/types-known/src/index.ts @@ -3,7 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import type BN from 'bn.js'; -import { Registry, RegistryTypes, OverrideModuleType, OverrideVersionedType } from '@polkadot/types/types'; +import { DefinitionRpc, DefinitionRpcSub, Registry, RegistryTypes, OverrideModuleType, OverrideVersionedType } from '@polkadot/types/types'; import { Text } from '@polkadot/types'; import { bnToBn, isUndefined } from '@polkadot/util'; @@ -58,7 +58,36 @@ export function getSpecTypes ({ knownTypes }: Registry, chainName: Text | string return { ...filterVersions(typesSpec[_specName], _specVersion), ...filterVersions(typesChain[_chainName], _specVersion), + ...filterVersions(knownTypes.typesBundle?.spec?.[_specName]?.types, _specVersion), + ...filterVersions(knownTypes.typesBundle?.chain?.[_chainName]?.types, _specVersion), ...(knownTypes.typesSpec?.[_specName] || {}), ...(knownTypes.typesChain?.[_chainName] || {}) }; } + +/** + * @description Based on the chain and runtimeVersion, get the applicable rpc definitions (ready for registration) + */ +export function getSpecRpc ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): Record> { + const _chainName = chainName.toString(); + const _specName = specName.toString(); + + return { + ...(knownTypes.typesBundle?.spec?.[_specName]?.rpc || {}), + ...(knownTypes.typesBundle?.chain?.[_chainName]?.rpc || {}) + }; +} + +/** + * @description Based on the chain and runtimeVersion, get the applicable alias definitions (ready for registration) + */ +export function getSpecAlias ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): Record { + const _chainName = chainName.toString(); + const _specName = specName.toString(); + + return { + ...(knownTypes.typesAlias || {}), + ...(knownTypes.typesBundle?.spec?.[_specName]?.alias || {}), + ...(knownTypes.typesBundle?.chain?.[_chainName]?.alias || {}) + }; +} diff --git a/packages/types/src/types/registry.ts b/packages/types/src/types/registry.ts index 016d7239f2..2999e3a4d0 100644 --- a/packages/types/src/types/registry.ts +++ b/packages/types/src/types/registry.ts @@ -7,6 +7,7 @@ import type BN from 'bn.js'; import { ChainProperties } from '../interfaces/system'; import { CallFunction } from './calls'; import { Codec, Constructor } from './codec'; +import { DefinitionRpc, DefinitionRpcSub } from './definitions'; import { AnyJson } from './helpers'; // eslint-disable-next-line @typescript-eslint/no-empty-interface @@ -19,6 +20,17 @@ export interface OverrideVersionedType { export type OverrideModuleType = Record; +export interface OverrideBundleDefinition { + alias?: Record; + rpc?: Record>; + types?: OverrideVersionedType[]; +} + +export interface OverrideBundleType { + chain?: Record; + spec?: Record; +} + export type RegistryTypes = Record | { _enum: string[] | Record } | { _set: Record }>; export interface RegistryMetadataText extends String, Codec { @@ -97,6 +109,10 @@ export interface RegisteredTypes { * @description Alias an types, as received via the metadata, to a JS-specific type to avoid conflicts. For instance, you can rename the `Proposal` in the `treasury` module to `TreasuryProposal` as to not have conflicts with the one for democracy. */ typesAlias?: Record; + /** + * @description A bundle of types related to chain & spec that is injected based on what the chain contains + */ + typesBundle?: OverrideBundleType; /** * @description Additional types that are injected based on the chain we are connecting to. There are keyed by the chain, i.e. `{ 'Kusama CC1': { ... } }` */