Add typeAlias to API construction options (#1989)
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
- Fix storage parsing not resulting in rejected Promises (Fix from https://github.com/aniiantt applied)
|
||||
- Type generation will now handle the same sub-module name across packages, i.e. `@polkadot/types/interfaces/runtime` & `@mine/interfaces/runtime`)
|
||||
- Add `.range([from, to]: [Hash, Hash?], ...args: any[]): [Hash, Codec][]` on all storage entries
|
||||
- Allow pre-module type aliasing with `typesAlias: { <moduleName>: { <meta-type>: <alias-type> } }`on API construction options
|
||||
- Allow `BTreeMap` to be initialized with a `Record<string, any>` object (in addition to `Map`)
|
||||
- Allow for `HashMap<KeyType, ValueType>` definitions
|
||||
- `Bool` will now correctly return `isEmpty` on false/default values
|
||||
|
||||
@@ -31,11 +31,21 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
l.warn('Api will be available in a limited mode since the provider does not support subscriptions');
|
||||
}
|
||||
|
||||
// all injected types added to the registry for overrides
|
||||
this.registry.setKnownTypes({
|
||||
types: options.types,
|
||||
typesAlias: options.typesAlias,
|
||||
typesChain: options.typesChain,
|
||||
typesSpec: options.typesSpec
|
||||
});
|
||||
|
||||
// We only register the types (global) if this is not a cloned instance.
|
||||
// Do right up-front, so we get in the user types before we are actually
|
||||
// doing anything on-chain, this ensures we have the overrides in-place
|
||||
if (!options.source && options.types) {
|
||||
if (!options.source) {
|
||||
this.registerTypes(options.types);
|
||||
} else {
|
||||
this.registry.setKnownTypes(options.source.registry.knownTypes);
|
||||
}
|
||||
|
||||
this._rpc = this.decorateRpc(this._rpcCore, this.decorateMethod);
|
||||
@@ -130,7 +140,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this._runtimeMetadata = metadata;
|
||||
this._runtimeVersion = version;
|
||||
|
||||
this.registerTypes(getSpecTypes(this._runtimeChain as Text, version));
|
||||
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version));
|
||||
this.injectMetadata(metadata, false);
|
||||
|
||||
return true;
|
||||
@@ -139,7 +149,6 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
}
|
||||
|
||||
private async metaFromChain (optMetadata: Record<string, string>): Promise<Metadata> {
|
||||
const { typesChain, typesSpec } = this._options;
|
||||
const [runtimeVersion, chain, chainProps] = await Promise.all([
|
||||
this._rpcCore.state.getRuntimeVersion().toPromise(),
|
||||
this._rpcCore.system.chain().toPromise(),
|
||||
@@ -152,8 +161,8 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
|
||||
// do the setup for the specific chain
|
||||
this.registry.setChainProperties(chainProps);
|
||||
this.registerTypes(getSpecTypes(chain, runtimeVersion));
|
||||
this.registerTypes(getUserTypes(chain, runtimeVersion, typesChain, typesSpec));
|
||||
this.registerTypes(getSpecTypes(this.registry, chain, runtimeVersion));
|
||||
this.registerTypes(getUserTypes(this.registry, chain, runtimeVersion));
|
||||
this.subscribeUpdates();
|
||||
|
||||
// filter the RPC methods (this does an rpc-methods call)
|
||||
@@ -173,7 +182,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
|
||||
private async initFromMeta (metadata: Metadata): Promise<boolean> {
|
||||
// inject types based on metadata, if applicable
|
||||
this.registerTypes(getMetadataTypes(metadata.version));
|
||||
this.registerTypes(getMetadataTypes(this.registry, metadata.version));
|
||||
|
||||
const metaExtrinsic = metadata.asLatest.extrinsic;
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { Constants } from '@polkadot/metadata/Decorated/types';
|
||||
import { RpcInterface, UserRpc } from '@polkadot/rpc-core/types';
|
||||
import { Metadata } from '@polkadot/types';
|
||||
import { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { RegistryTypes, Signer, SignerResult, SignatureOptions, Registry } from '@polkadot/types/types';
|
||||
import { Signer, SignerResult, SignatureOptions, Registry, RegisteredTypes } from '@polkadot/types/types';
|
||||
|
||||
import ApiBase from '../base';
|
||||
import { DeriveAllSections } from '../util/decorate';
|
||||
@@ -26,13 +26,13 @@ export * from './rpc';
|
||||
export * from './storage';
|
||||
export * from './submittable';
|
||||
|
||||
export interface ApiOptions {
|
||||
export interface ApiOptions extends RegisteredTypes {
|
||||
/**
|
||||
* @description Add custom derives to be injected
|
||||
*/
|
||||
derives?: DeriveCustom;
|
||||
/**
|
||||
* @description prebundles is a map of 'genesis hash and runtime spec version' as key to metadata's hex string
|
||||
* @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<string, string>;
|
||||
@@ -57,19 +57,6 @@ export interface ApiOptions {
|
||||
* @description The source object to use for runtime information (only used when cloning)
|
||||
*/
|
||||
source?: ApiBase<any>;
|
||||
/**
|
||||
* @description Additional types used by runtime modules. This is nessusary if the runtime modules
|
||||
* uses types not available in the base Substrate runtime.
|
||||
*/
|
||||
types?: RegistryTypes;
|
||||
/**
|
||||
* @description Additional types that are injected based on the chain we are connecting to. There are keyed by the chain, i.e. `{ 'Kusama CC1': { ... } }`
|
||||
*/
|
||||
typesChain?: Record<string, RegistryTypes>;
|
||||
/**
|
||||
* @description Additional types that are injected based on the type of node we are connecting to, as set via specName in the runtime version. There are keyed by the node, i.e. `{ 'edgeware': { ... } }`
|
||||
*/
|
||||
typesSpec?: Record<string, RegistryTypes>;
|
||||
}
|
||||
|
||||
// A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic
|
||||
|
||||
@@ -71,7 +71,7 @@ export default function toLatest (registry: Registry, { modules, extrinsic }: Me
|
||||
modules: modules.map((mod): ModuleMetadataLatest => {
|
||||
const calls = mod.calls.unwrapOr(null);
|
||||
const storage = mod.storage.unwrapOr(null);
|
||||
const sectionTypes = getModuleTypes(stringCamelCase(mod.name.toString()));
|
||||
const sectionTypes = getModuleTypes(registry, stringCamelCase(mod.name.toString()));
|
||||
|
||||
return registry.createType('ModuleMetadataLatest', {
|
||||
...mod,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ChainProperties, DispatchErrorModule } from '../interfaces/types';
|
||||
import { CallFunction, Codec, Constructor, InterfaceTypes, RegistryError, RegistryTypes, Registry, RegistryMetadata, TypeDef } from '../types';
|
||||
import { CallFunction, Codec, Constructor, InterfaceTypes, RegistryError, RegistryTypes, Registry, RegistryMetadata, RegisteredTypes, TypeDef } from '../types';
|
||||
|
||||
import extrinsicsFromMeta from '@polkadot/metadata/Decorated/extrinsics/fromMetadata';
|
||||
import { assert, formatBalance, isFunction, isString, isU8a, isUndefined, stringCamelCase, u8aToHex } from '@polkadot/util';
|
||||
@@ -94,6 +94,8 @@ export class TypeRegistry implements Registry {
|
||||
|
||||
#metadataExtensions: string[] = defaultExtensions;
|
||||
|
||||
#knownTypes: RegisteredTypes = {};
|
||||
|
||||
constructor () {
|
||||
// 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
|
||||
@@ -128,6 +130,10 @@ export class TypeRegistry implements Registry {
|
||||
: formatBalance.getDefaults().unit;
|
||||
}
|
||||
|
||||
public get knownTypes (): RegisteredTypes {
|
||||
return this.#knownTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @describe Creates an instance of the class
|
||||
*/
|
||||
@@ -294,6 +300,10 @@ export class TypeRegistry implements Registry {
|
||||
}
|
||||
}
|
||||
|
||||
setKnownTypes (knownTypes: RegisteredTypes): void {
|
||||
this.#knownTypes = knownTypes;
|
||||
}
|
||||
|
||||
// sets the metadata
|
||||
public setMetadata (metadata: RegistryMetadata): void {
|
||||
decorateExtrinsics(this, metadata, this.#metadataCalls);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { RuntimeVersion } from '../interfaces';
|
||||
import { RegistryTypes } from '../types';
|
||||
import { Registry, RegistryTypes } from '../types';
|
||||
import { OverrideModuleType, OverrideVersionedType } from './types';
|
||||
|
||||
import { Text } from '@polkadot/types';
|
||||
@@ -27,13 +27,13 @@ function filterVersions (versions: OverrideVersionedType[] = [], version: number
|
||||
|
||||
// based on the metadata version, return the registry types
|
||||
/** @internal */
|
||||
export function getMetadataTypes (version: number): RegistryTypes {
|
||||
export function getMetadataTypes (_registry: Registry, version: number): RegistryTypes {
|
||||
return filterVersions(TYPES_META, version);
|
||||
}
|
||||
|
||||
// based on the chain and runtimeVersion, get the applicable types (ready for registration)
|
||||
/** @internal */
|
||||
export function getSpecTypes (chainName: Text | string, { specName, specVersion }: RuntimeVersion): RegistryTypes {
|
||||
export function getSpecTypes (_registry: Registry, chainName: Text | string, { specName, specVersion }: RuntimeVersion): RegistryTypes {
|
||||
const _chainName = chainName.toString();
|
||||
const _specName = specName.toString();
|
||||
const _specVersion = specVersion.toNumber();
|
||||
@@ -46,18 +46,21 @@ export function getSpecTypes (chainName: Text | string, { specName, specVersion
|
||||
|
||||
// based on the spec and chain, get the specific user-defind types
|
||||
/** @internal */
|
||||
export function getUserTypes (chainName: Text | string, { specName }: RuntimeVersion, typesChain: Record<string, RegistryTypes> = {}, typesSpec: Record<string, RegistryTypes> = {}): RegistryTypes {
|
||||
export function getUserTypes ({ knownTypes }: Registry, chainName: Text | string, { specName }: RuntimeVersion): RegistryTypes {
|
||||
const _chainName = chainName.toString();
|
||||
const _specName = specName.toString();
|
||||
|
||||
return {
|
||||
...(typesSpec[_specName] || {}),
|
||||
...(typesChain[_chainName] || {})
|
||||
...(knownTypes.typesSpec?.[_specName] || {}),
|
||||
...(knownTypes.typesChain?.[_chainName] || {})
|
||||
};
|
||||
}
|
||||
|
||||
// get types for specific modules (metadata override)
|
||||
/** @internal */
|
||||
export function getModuleTypes (section: string): OverrideModuleType {
|
||||
return TYPES_MODULES[section] || {};
|
||||
export function getModuleTypes ({ knownTypes }: Registry, section: string): OverrideModuleType {
|
||||
return {
|
||||
...(TYPES_MODULES[section] || {}),
|
||||
...(knownTypes.typesAlias?.[section] || {})
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// 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 { TypeRegistry } from '../create/registry';
|
||||
import { getModuleTypes } from './';
|
||||
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
registry.setKnownTypes({
|
||||
typesAlias: {
|
||||
identity: {
|
||||
Id: 'IdentityId'
|
||||
},
|
||||
testModule: {
|
||||
Proposal: 'TestProposal'
|
||||
},
|
||||
treasury: {
|
||||
Proposal: 'TreasuryProposals2'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('getModuleTypes', (): void => {
|
||||
it('collects the pre-defined types for contracts', (): void => {
|
||||
expect(getModuleTypes(registry, 'contracts')).toEqual({
|
||||
StorageKey: 'ContractStorageKey'
|
||||
});
|
||||
});
|
||||
|
||||
it('collects the user-defined types for testModule', (): void => {
|
||||
expect(getModuleTypes(registry, 'testModule')).toEqual({
|
||||
Proposal: 'TestProposal'
|
||||
});
|
||||
});
|
||||
|
||||
it('overrides pre-defined with user-defined for treasury', (): void => {
|
||||
expect(getModuleTypes(registry, 'treasury')).toEqual({
|
||||
Proposal: 'TreasuryProposals2'
|
||||
});
|
||||
});
|
||||
|
||||
it('merges pre-defined and user-defined for identity', (): void => {
|
||||
expect(getModuleTypes(registry, 'identity')).toEqual({
|
||||
Judgement: 'IdentityJudgement',
|
||||
Id: 'IdentityId'
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ChainProperties } from '../interfaces/rpc';
|
||||
import { OverrideModuleType } from '../known/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
@@ -81,10 +82,31 @@ export interface RegistryMetadata {
|
||||
asLatest: RegistryMetadataLatest;
|
||||
}
|
||||
|
||||
export interface RegisteredTypes {
|
||||
/**
|
||||
* @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.
|
||||
*/
|
||||
typesAlias?: Record<string, OverrideModuleType>;
|
||||
/**
|
||||
* @description Additional types that are injected based on the chain we are connecting to. There are keyed by the chain, i.e. `{ 'Kusama CC1': { ... } }`
|
||||
*/
|
||||
typesChain?: Record<string, RegistryTypes>;
|
||||
/**
|
||||
* @description Additional types that are injected based on the type of node we are connecting to, as set via specName in the runtime version. There are keyed by the node, i.e. `{ 'edgeware': { ... } }`
|
||||
*/
|
||||
typesSpec?: Record<string, RegistryTypes>;
|
||||
}
|
||||
|
||||
export interface Registry {
|
||||
readonly chainDecimals: number;
|
||||
readonly chainSS58: number | undefined;
|
||||
readonly chainToken: string;
|
||||
readonly knownTypes: RegisteredTypes;
|
||||
|
||||
findMetaCall (callIndex: Uint8Array): CallFunction;
|
||||
findMetaError (errorIndex: Uint8Array): any;
|
||||
@@ -99,6 +121,7 @@ export interface Registry {
|
||||
getDefinition (name: string): string | undefined;
|
||||
getOrThrow <T extends Codec = Codec> (name: string, msg?: string): Constructor<T>;
|
||||
getOrUnknown <T extends Codec = Codec> (name: string): Constructor<T>;
|
||||
setKnownTypes (types: RegisteredTypes): void;
|
||||
getSignedExtensionExtra (): Record<string, keyof InterfaceTypes>;
|
||||
getSignedExtensionTypes (): Record<string, keyof InterfaceTypes>;
|
||||
hasClass (name: string): boolean;
|
||||
|
||||
Reference in New Issue
Block a user