From 5a1598a389f1288e85169921e593372f312824c5 Mon Sep 17 00:00:00 2001 From: Jaco Date: Fri, 1 Jul 2022 08:58:40 +0200 Subject: [PATCH] Allow for runtime methods interleave (#5005) --- packages/api/src/base/Decorate.ts | 83 +++++++++++++++++----------- packages/types-known/src/util.ts | 20 +++++-- packages/types/src/types/registry.ts | 6 +- 3 files changed, 69 insertions(+), 40 deletions(-) diff --git a/packages/api/src/base/Decorate.ts b/packages/api/src/base/Decorate.ts index 53d1c68d3c..0135fed8d5 100644 --- a/packages/api/src/base/Decorate.ts +++ b/packages/api/src/base/Decorate.ts @@ -8,7 +8,7 @@ import type { Option, Raw, StorageKey, Text, u64 } from '@polkadot/types'; import type { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces'; import type { DecoratedMeta } from '@polkadot/types/metadata/decorate/types'; import type { StorageEntry } from '@polkadot/types/primitive/types'; -import type { AnyFunction, AnyTuple, CallFunction, Codec, DefinitionCallNamed, DefinitionRpc, DefinitionRpcSub, Definitions, DefinitionsCall, DetectCodec, IMethod, IStorageKey, Registry, RegistryError, RegistryTypes } from '@polkadot/types/types'; +import type { AnyFunction, AnyTuple, CallFunction, Codec, DefinitionCallNamed, DefinitionRpc, DefinitionRpcSub, DefinitionsCall, DefinitionsCallEntry, DetectCodec, IMethod, IStorageKey, Registry, RegistryError, RegistryTypes } from '@polkadot/types/types'; import type { HexString } from '@polkadot/util/types'; import type { SubmittableExtrinsic } from '../submittable/types'; import type { ApiDecoration, ApiInterfaceRx, ApiOptions, ApiTypes, AugmentedQuery, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecorateMethod, GenericStorageEntryFunction, PaginationOptions, QueryableConsts, QueryableStorage, QueryableStorageEntry, QueryableStorageEntryAt, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics } from '../types'; @@ -20,6 +20,7 @@ import { getAvailableDerives } from '@polkadot/api-derive'; import { memo, RpcCore } from '@polkadot/rpc-core'; import { WsProvider } from '@polkadot/rpc-provider'; import { expandMetadata, Metadata, typeDefinitions, TypeRegistry, unwrapStorageType } from '@polkadot/types'; +import { getSpecRuntime } from '@polkadot/types-known'; import { arrayChunk, arrayFlatten, assert, assertReturn, BN, compactStripLength, lazyMethod, lazyMethods, logger, nextTick, objectSpread, stringCamelCase, u8aConcatStrict, u8aToHex } from '@polkadot/util'; import { blake2AsHex } from '@polkadot/util-crypto'; @@ -414,46 +415,62 @@ export abstract class Decorate extends Events { return out as DecoratedRpc; } - // extract all runtime definitions - protected _getRuntimeDefs (): DefinitionsCall { - const result = objectSpread({}, this._options.runtime); - const defValues = Object.values(typeDefinitions) as Definitions[]; - - for (let i = 0; i < defValues.length; i++) { - const rt = defValues[i].runtime; - - if (rt) { - const apiEntries = Object.entries(rt); - - for (let j = 0; j < apiEntries.length; j++) { - const [key, defs] = apiEntries[j]; - - if (!result[key]) { - // we don't have this runtime definition, add it - result[key] = defs; - } else { - for (let k = 0; k < defs.length; k++) { - const def = defs[k]; - - if (!result[key].some(({ version }) => def.version === version)) { - // we don't have this specific version, add it - result[key].push(def); - } - } - } - } - } + // add all definition entries + protected _addRuntimeDef (result: DefinitionsCall, additional?: DefinitionsCall): void { + if (!additional) { + return; } - return result; + const entries = Object.entries(additional); + + for (let j = 0; j < entries.length; j++) { + const [key, defs] = entries[j]; + + if (result[key]) { + // we have this one already, step through for new versions or + // new methods and add those as applicable + for (let k = 0; k < defs.length; k++) { + const def = defs[k]; + const prev = result[key].find(({ version }) => def.version === version); + + if (prev) { + // interleave the new methods with the old - last definition wins + objectSpread(prev.methods, def.methods); + } else { + // we don't have this specific version, add it + result[key].push(def); + } + } + } else { + // we don't have this runtime definition, add it as-is + result[key] = defs; + } + } + } + + // extract all runtime definitions + protected _getRuntimeDefs (registry: Registry, specName: Text, chain: Text | string = ''): [string, DefinitionsCallEntry[]][] { + const result: DefinitionsCall = {}; + const defValues = Object.values(typeDefinitions); + + // options > chain/spec > built-in, apply in reverse order with + // methods overriding previous definitions (or interleave missing) + for (let i = 0; i < defValues.length; i++) { + this._addRuntimeDef(result, defValues[i].runtime); + } + + this._addRuntimeDef(result, getSpecRuntime(registry, chain, specName)); + this._addRuntimeDef(result, this._options.runtime); + + return Object.entries(result); } // pre-metadata decoration - protected _decorateCalls ({ registry, runtimeVersion: { apis } }: VersionedRegistry, decorateMethod: DecorateMethod, blockHash?: Uint8Array | string | null): QueryableCalls { + protected _decorateCalls ({ registry, runtimeVersion: { apis, specName } }: VersionedRegistry, decorateMethod: DecorateMethod, blockHash?: Uint8Array | string | null): QueryableCalls { const result = {} as QueryableCalls; const named: Record> = {}; - const sections = Object.entries(this._getRuntimeDefs()); const hashes: HexString[] = []; + const sections = this._getRuntimeDefs(registry, specName, this._runtimeChain); for (let i = 0; i < sections.length; i++) { const [_section, secs] = sections[i]; diff --git a/packages/types-known/src/util.ts b/packages/types-known/src/util.ts index 6966acbd3a..a8a0e9b3fa 100644 --- a/packages/types-known/src/util.ts +++ b/packages/types-known/src/util.ts @@ -3,11 +3,11 @@ import type { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types'; import type { Hash } from '@polkadot/types/interfaces'; -import type { ChainUpgradeVersion, CodecHasher, DefinitionRpc, DefinitionRpcSub, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '@polkadot/types/types'; +import type { ChainUpgradeVersion, CodecHasher, DefinitionRpc, DefinitionRpcSub, DefinitionsCall, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '@polkadot/types/types'; import type { Text } from '@polkadot/types-codec'; import type { BN } from '@polkadot/util'; -import { bnToBn, isNull, isUndefined, objectSpread } from '@polkadot/util'; +import { bnToBn, objectSpread } from '@polkadot/util'; import typesChain from './chain'; import typesSpec from './spec'; @@ -22,8 +22,8 @@ function withNames (chainName: Text | string, specName: Text | string, fn: ( function filterVersions (versions: OverrideVersionedType[] = [], specVersion: number): RegistryTypes { return versions .filter(({ minmax: [min, max] }) => - (isUndefined(min) || isNull(min) || specVersion >= min) && - (isUndefined(max) || isNull(max) || specVersion <= max) + (min === undefined || min === null || specVersion >= min) && + (max === undefined || max === null || specVersion <= max) ) .reduce((result: RegistryTypes, { types }): RegistryTypes => objectSpread(result, types), {} @@ -86,6 +86,18 @@ export function getSpecRpc ({ knownTypes }: Registry, chainName: Text | string, ); } +/** + * @description Based on the chain and runtimeVersion, get the applicable runtime definitions (ready for registration) + */ +export function getSpecRuntime ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): DefinitionsCall { + return withNames(chainName, specName, (c, s) => + objectSpread({}, + knownTypes.typesBundle?.spec?.[s]?.runtime, + knownTypes.typesBundle?.chain?.[c]?.runtime + ) + ); +} + /** * @description Based on the chain and runtimeVersion, get the applicable alias definitions (ready for registration) */ diff --git a/packages/types/src/types/registry.ts b/packages/types/src/types/registry.ts index 4998700189..ed1e9814c0 100644 --- a/packages/types/src/types/registry.ts +++ b/packages/types/src/types/registry.ts @@ -12,7 +12,7 @@ import type { HeaderPartial } from '../interfaces/runtime'; import type { RuntimeVersionPartial } from '../interfaces/state'; import type { Metadata, PortableRegistry } from '../metadata'; import type { Data, StorageKey } from '../primitive'; -import type { DefinitionRpc, DefinitionRpcSub } from './definitions'; +import type { DefinitionRpc, DefinitionRpcSub, DefinitionsCall } from './definitions'; export type { Registry, RegistryError, RegistryTypes } from '@polkadot/types-codec/types'; @@ -65,6 +65,7 @@ export interface OverrideBundleDefinition { hasher?: (data: Uint8Array) => Uint8Array; instances?: Record; rpc?: Record>; + runtime?: DefinitionsCall; signedExtensions?: ExtDef; types?: OverrideVersionedType[]; } @@ -79,14 +80,13 @@ export interface RegisteredTypes { * @description Specify the actual hasher override to use in the API. This generally should be done via the typesBundle */ hasher?: (data: Uint8Array) => Uint8Array; - /** * @description Additional types used by runtime modules. This is necessary if the runtime modules * uses types not available in the base Substrate runtime. */ types?: RegistryTypes; /** - * @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. + * @description Alias 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?: AliasDefinition; /**