Add injectMetadata to api (with decoration) (#1892)

* Add injectMetadata to api (with decoration)

* warn function

* OCD

* OCD #2

* toHuman entry expansion

* CHANGELOG for injectMetadata
This commit is contained in:
Jaco Greeff
2020-02-18 21:30:43 +01:00
committed by GitHub
parent d4b45921fd
commit c8af75088a
6 changed files with 143 additions and 19 deletions
+27 -7
View File
@@ -14,6 +14,7 @@ import BN from 'bn.js';
import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
import DecoratedMeta from '@polkadot/metadata/Decorated';
import getHasher from '@polkadot/metadata/Decorated/storage/fromMetadata/getHasher';
import RpcCore from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
@@ -25,6 +26,7 @@ import { assert, compactStripLength, isNull, isUndefined, u8aConcat, u8aToHex }
import { createSubmittable } from '../submittable';
import { decorateSections, DeriveAllSections } from '../util/decorate';
import augmentObject from '../util/augmentObject';
import Events from './Events';
interface MetaDecoration {
@@ -43,11 +45,11 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// HACK Use BN import so decorateDerive works... yes, wtf.
protected __phantom = new BN(0);
protected _consts?: Constants;
protected _consts: Constants = {} as Constants;
protected _derive?: ReturnType<Decorate<ApiType>['decorateDerive']>;
protected _extrinsics?: SubmittableExtrinsics<ApiType>;
protected _extrinsics: SubmittableExtrinsics<ApiType> = {} as SubmittableExtrinsics<ApiType>;
protected _extrinsicType: number = EXTRINSIC_DEFAULT_VERSION;
@@ -59,7 +61,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected readonly _options: ApiOptions;
protected _query?: QueryableStorage<ApiType>;
protected _query: QueryableStorage<ApiType> = {} as QueryableStorage<ApiType>;
protected _queryMulti?: QueryableStorageMulti<ApiType>;
@@ -71,7 +73,11 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected _runtimeVersion?: RuntimeVersion;
protected _rx: Partial<ApiInterfaceRx> = {};
protected _rx: ApiInterfaceRx = {
consts: {} as Constants,
query: {} as QueryableStorage<'rxjs'>,
tx: {} as SubmittableExtrinsics<'rxjs'>
} as ApiInterfaceRx;
protected _type: ApiTypes;
@@ -140,6 +146,20 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
return this._rpcCore.provider.hasSubscriptions;
}
public injectMetadata (metadata: Metadata): void {
const decoratedMeta = new DecoratedMeta(this.registry, metadata);
// this API
augmentObject('tx', this.decorateExtrinsics(decoratedMeta.tx, this.decorateMethod), this._extrinsics);
augmentObject('query', this.decorateStorage(decoratedMeta.query, this.decorateMethod), this._query);
augmentObject('consts', decoratedMeta.consts, this._consts);
// rx
augmentObject('', this.decorateExtrinsics(decoratedMeta.tx, this.rxDecorateMethod), this._rx.tx);
augmentObject('', this.decorateStorage(decoratedMeta.query, this.rxDecorateMethod), this._rx.query);
augmentObject('', decoratedMeta.consts, this._rx.consts);
}
private decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
output.meta = input.meta;
output.method = input.method;
@@ -219,7 +239,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
}
protected decorateExtrinsics<ApiType extends ApiTypes> (extrinsics: ModulesWithCalls, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
const creator = createSubmittable(this._type, this._rx as ApiInterfaceRx, decorateMethod);
const creator = createSubmittable(this._type, this._rx, decorateMethod);
return Object.entries(extrinsics).reduce((out, [name, section]): SubmittableExtrinsics<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): SubmittableModuleExtrinsics<ApiType> => {
@@ -411,13 +431,13 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected decorateDeriveRx (decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<'rxjs', ExactDerive> {
// Pull in derive from api-derive
const derive = decorateDerive(this._rx as ApiInterfaceRx, this._options.derives);
const derive = decorateDerive(this._rx, this._options.derives);
return decorateSections<'rxjs', ExactDerive>(derive, decorateMethod);
}
protected decorateDerive (decorateMethod: DecorateMethod<ApiType>): DeriveAllSections<ApiType, ExactDerive> {
return decorateSections<ApiType, ExactDerive>(this._rx.derive as DeriveAllSections<'rxjs', ExactDerive>, decorateMethod);
return decorateSections<ApiType, ExactDerive>(this._rx.derive, decorateMethod);
}
/**
+2 -9
View File
@@ -5,7 +5,6 @@
import { SignedBlock } from '@polkadot/types/interfaces';
import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
import DecoratedMeta from '@polkadot/metadata/Decorated';
import { Metadata } from '@polkadot/types';
import { getChainTypes, getMetadataTypes } from '@polkadot/types/known';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/primitive/Extrinsic/Extrinsic';
@@ -125,7 +124,6 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// inject types based on metadata, if applicable
this.registerTypes(getMetadataTypes(metadata.version));
const decoratedMeta = new DecoratedMeta(this.registry, metadata);
const metaExtrinsic = metadata.asLatest.extrinsic;
// only inject if we are not a clone (global init)
@@ -139,16 +137,11 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
this._extrinsicType = firstTx ? firstTx.type : LATEST_EXTRINSIC_VERSION;
}
this._extrinsics = this.decorateExtrinsics(decoratedMeta.tx, this.decorateMethod);
this._query = this.decorateStorage(decoratedMeta.query, this.decorateMethod);
this._consts = decoratedMeta.consts;
this._rx.extrinsicType = this._extrinsicType;
this._rx.genesisHash = this._genesisHash;
this._rx.runtimeVersion = this._runtimeVersion;
this._rx.tx = this.decorateExtrinsics(decoratedMeta.tx, this.rxDecorateMethod);
this._rx.query = this.decorateStorage(decoratedMeta.query, this.rxDecorateMethod);
this._rx.consts = decoratedMeta.consts;
this.injectMetadata(metadata);
// derive is last, since it uses the decorated rx
this._rx.derive = this.decorateDeriveRx(this.rxDecorateMethod);
+2 -2
View File
@@ -78,11 +78,11 @@ export interface ApiInterfaceRx {
// TODO This needs to be typed correctly
derive: DeriveAllSections<'rxjs', ExactDerive>;
extrinsicType: number;
genesisHash: Hash;
genesisHash?: Hash;
hasSubscriptions: boolean;
registry: Registry;
runtimeMetadata: Metadata;
runtimeVersion: RuntimeVersion;
runtimeVersion?: RuntimeVersion;
query: QueryableStorage<'rxjs'>;
queryMulti: QueryableStorageMulti<'rxjs'>;
rpc: DecoratedRpc<'rxjs', RpcInterface>;
@@ -0,0 +1,44 @@
// Copyright 2017-2020 @polkadot/api 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 augmentObject, { findRemoved } from './augmentObject';
describe('findRemoved', (): void => {
let spy: any;
beforeEach((): void => {
spy = jest.spyOn(console, 'warn');
});
afterEach((): void => {
spy.mockClear();
});
it('logs removed sections', (): void => {
findRemoved('test', { foo: {}, bar: {} }, { cde: {}, foo: {}, bar: {}, baz: {} });
expect(spy).toHaveBeenCalledWith('api.test: Found 2 removed modules: baz, cde');
});
it('logs removed calls', (): void => {
findRemoved('test', { foo: { a: 1 }, bar: {} }, { foo: { a: 1 }, bar: { a: 1 } });
expect(spy).toHaveBeenCalledWith('api.test: Found 1 removed calls: bar.a');
});
});
describe('augmentObject', (): void => {
it('copies sections to the dest', (): void => {
const src = { foo: { a: 1 }, bar: { b: 1 } };
expect(augmentObject('test', src, {})).toEqual(src);
});
it('adds fields to existing sections', (): void => {
const src = { foo: { a: 1 }, bar: { b: 1 } };
const dst = { foo: { b: 2 }, baz: { c: 1 } };
expect(augmentObject('test', src, dst)).toEqual({ foo: { b: 2, a: 1 }, bar: { b: 1 }, baz: { c: 1 } });
});
});
+66
View File
@@ -0,0 +1,66 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// log details to console
function warn (prefix: string, type: 'calls' | 'modules', rmed: string[]): void {
if (rmed.length) {
console.warn(`api.${prefix}: Found ${rmed.length} removed ${type}: ${rmed.join(', ')}`);
}
}
// log all the stuff that has been removed/
export function findRemoved (prefix: string, src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): void {
const srcSections = Object.keys(src);
const dstSections = Object.keys(dst);
warn(prefix, 'modules', dstSections
.filter((section): boolean => !srcSections.includes(section))
.sort()
);
warn(prefix, 'calls', dstSections
.filter((section): boolean => srcSections.includes(section))
.reduce((rmMethods: string[], section): string[] => {
const srcMethods = Object.keys(src[section]);
return rmMethods.concat(
...Object
.keys(dst[section])
.filter((method): boolean => !srcMethods.includes(method))
.map((method): string => `${section}.${method}`)
);
}, [])
.sort()
);
}
/**
* Takes a decorated api section (e.g. api.tx) and augment it with the details. It does not override what is
* already available, but rather just adds new missing ites into the result object.
* @internal
*/
export default function augmentObject (prefix: string, src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): Record<string, Record<string, any>> {
if (prefix && Object.keys(dst).length) {
findRemoved(prefix, src, dst);
}
return Object
.keys(src)
.reduce((newSection, sectionName): Record<string, Record<string, any>> => {
const section = src[sectionName];
newSection[sectionName] = Object
.keys(section)
.reduce((result, methodName): Record<string, any> => {
// TODO When it does match, check the actual details and warn when there are differences
if (!result[methodName]) {
result[methodName] = section[methodName];
}
return result;
}, dst[sectionName] || {});
return newSection;
}, dst);
}