Call.injectMetadata (align with Events) (#1462)

* Call.injectMetadata (align with Events)

* Fix interface builds

* Fix md builds

* Fixup tests with injection
This commit is contained in:
Jaco Greeff
2019-10-10 11:05:01 +02:00
committed by GitHub
parent 2870513453
commit b8d4bc5c6a
27 changed files with 125 additions and 92 deletions
+6
View File
@@ -1,3 +1,9 @@
# 0.95.0-beta.x
- Support Metadata V8 (exposes per-module `decl_error` definitions)
- Support next generation contracts ABI (with additional type definitions)
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
# 0.94.1
- Add handling of `Result<Ok, Error>` definitions
@@ -14,7 +14,7 @@ import { stringCamelCase } from '@polkadot/util';
* @param metadata - The metadata
*/
export default function fromMetadata (metadata: Metadata): Constants {
return metadata.asLatest.modules.reduce((result, moduleMetadata): Constants => {
return metadata.asLatest.modules.reduce((result: Constants, moduleMetadata): Constants => {
if (moduleMetadata.constants.isEmpty) {
return result;
}
@@ -22,7 +22,7 @@ export default function fromMetadata (metadata: Metadata): Constants {
const { name } = moduleMetadata;
// For access, we change the index names, i.e. Democracy.EnactmentPeriod -> democracy.enactmentPeriod
result[stringCamelCase(name.toString())] = moduleMetadata.constants.reduce((newModule, meta): ModuleConstants => {
result[stringCamelCase(name.toString())] = moduleMetadata.constants.reduce((newModule: ModuleConstants, meta): ModuleConstants => {
const codec = createTypeUnsafe(meta.type.toString(), [meta.value]);
// This is not a perfect idea, however as it stands with number-only constants on the metadata
@@ -33,8 +33,8 @@ export default function fromMetadata (metadata: Metadata): Constants {
newModule[stringCamelCase(meta.name.toString())] = codec;
return newModule;
}, {} as unknown as ModuleConstants);
}, {});
return result;
}, {} as unknown as Constants);
}, {});
}
@@ -5,7 +5,7 @@
import { Call, FunctionMetadataLatest } from '@polkadot/types/interfaces';
import { CallFunction } from '@polkadot/types/types';
import { createType } from '@polkadot/types';
import { createType } from '@polkadot/types/codec';
import { assert, stringCamelCase } from '@polkadot/util';
/**
@@ -19,16 +19,16 @@ import createUnchecked from './createUnchecked';
export default function fromMetadata (metadata: Metadata): ModulesWithCalls {
return metadata.asLatest.modules
.filter(({ calls }): boolean => calls.isSome)
.reduce((result, modul: ModuleMetadataV8, sectionIndex): ModulesWithCalls => {
const section = stringCamelCase(modul.name.toString());
.reduce((result, { calls, name }: ModuleMetadataV8, sectionIndex): ModulesWithCalls => {
const section = stringCamelCase(name.toString());
result[section] = modul.calls.unwrap().reduce((newModule, callMetadata, methodIndex): Calls => {
result[section] = calls.unwrap().reduce((newModule: Calls, callMetadata, methodIndex): Calls => {
const method = stringCamelCase(callMetadata.name.toString());
newModule[method] = createUnchecked(section, sectionIndex, methodIndex, callMetadata);
return newModule;
}, {} as unknown as Calls);
}, {});
return result;
}, { ...extrinsics });
@@ -2,17 +2,26 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ModulesWithCalls } from '@polkadot/types/types';
import '@polkadot/types/injector';
import BN from 'bn.js';
import testingPairs from '@polkadot/keyring/testingPairs';
import { createType } from '@polkadot/types';
import { createType, Metadata } from '@polkadot/types';
import metadataStatic from '@polkadot/types/Metadata/static';
import extrinsics from './static';
import fromMetadata from './fromMetadata';
const keyring = testingPairs({ type: 'ed25519' }, false);
describe('extrinsics', (): void => {
let extrinsics: ModulesWithCalls;
beforeEach((): void => {
extrinsics = fromMetadata(new Metadata(metadataStatic));
});
it('encodes an actual transfer (actual data)', (): void => {
expect(
createType('Extrinsic',
@@ -4,7 +4,7 @@
import { ModulesWithCalls } from '@polkadot/types/types';
import { Metadata } from '@polkadot/types';
import Metadata from '@polkadot/types/Metadata';
import metadataRpc from '@polkadot/types/Metadata/static';
import fromMetadata from './fromMetadata';
@@ -5,8 +5,7 @@
import { Codec } from '@polkadot/types/types';
import BN from 'bn.js';
import { Bytes, Compact, StorageKey, U8a } from '@polkadot/types';
import { createType, createTypeUnsafe } from '@polkadot/types/codec';
import { Compact, U8a, createType, createTypeUnsafe } from '@polkadot/types/codec';
import { StorageEntryMetadata, StorageEntryType } from '@polkadot/types/Metadata/v8/Storage';
import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
import { assert, isNull, isUndefined, stringLowerFirst, stringToU8a, u8aConcat } from '@polkadot/util';
@@ -123,13 +122,13 @@ function extendLinkedMap ({ meta: { documentation, name, type } }: CreateItemFn,
name,
modifier: createType('StorageEntryModifierLatest', 1), // required
type: new StorageEntryType(createType('PlainTypeLatest', type.asMap.key), 0),
fallback: new Bytes(createTypeUnsafe(type.asMap.key.toString()).toHex()),
fallback: createType('Bytes', createTypeUnsafe(type.asMap.key.toString()).toHex()),
documentation
});
// here we pass the section/method through as well - these are not on
// the function itself, so specify these explicitly to the constructor
storageFn.headKey = new StorageKey(headFn, {
storageFn.headKey = createType('StorageKey', headFn, {
method: storageFn.method,
section: `head of ${storageFn.section}`
});
@@ -5,18 +5,12 @@
import '@polkadot/types/injector';
import testingPairs from '@polkadot/keyring/testingPairs';
import { Metadata } from '@polkadot/types';
import json from '@polkadot/types/Metadata/static';
import { u8aToHex } from '@polkadot/util';
import fromMetadata from '../fromMetadata';
import storage from '../static';
const keyring = testingPairs({ type: 'ed25519' });
// Use the pre-generated metadata
const metadata = new Metadata(json);
const storage = fromMetadata(metadata);
describe('fromMetadata', (): void => {
it('should throw if the storage function expects an argument', (): void => {
expect((): any => storage.balances.freeBalance()).toThrowError(/requires one argument/);
@@ -4,7 +4,7 @@
import { StorageEntryMetadata, StorageEntryType } from '@polkadot/types/Metadata/v8/Storage';
import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
import { createType, Text, Vec } from '@polkadot/types';
import { createType } from '@polkadot/types/codec';
import createFunction from './createFunction';
@@ -18,7 +18,7 @@ const createRuntimeFunction = (method: string, key: string, { documentation, typ
createFunction(
{
meta: {
documentation: new Vec(Text, [documentation]),
documentation: createType('Vec<Text>', [documentation]),
modifier: createType('StorageEntryModifierLatest', 1), // required
type: new StorageEntryType(type, 0),
toJSON: (): any => key
+1 -1
View File
@@ -172,7 +172,7 @@ export default abstract class Init<ApiType> extends Decorate<ApiType> {
// only inject if we are not a clone (global init)
if (!this._options.source) {
GenericEvent.injectMetadata(metadata);
GenericCall.injectMethods(extrinsics);
GenericCall.injectMetadata(metadata);
// detect the extrinsic version in-use based on the last block
const { block: { extrinsics: [firstTx] } }: SignedBlock = await this._rpcCore.chain.getBlock().toPromise();
@@ -234,24 +234,13 @@ export default class MetadataVersioned extends Struct {
}
/**
* @description
* @description Returns the wrapped metadata as a limited calls-only (latest) version
*/
public get magicNumber (): MagicNumber {
return this.get('magicNumber') as MagicNumber;
}
/**
* @description the metadata wrapped
*/
private get metadata (): MetadataEnum {
return this.get('metadata') as MetadataEnum;
}
/**
* @description the metadata version this structure represents
*/
public get version (): number {
return this.metadata.index;
public get asCallsOnly (): MetadataVersioned {
return new MetadataVersioned({
magicNumber: this.magicNumber,
metadata: new MetadataEnum(toCallsOnly(this.asLatest), this.version)
});
}
/**
@@ -319,16 +308,6 @@ export default class MetadataVersioned extends Struct {
return this.getVersion(8, v7ToV8);
}
/**
* @description Returns the wrapped metadata as a limited calls-only (latest) version
*/
public get asCallsOnly (): MetadataVersioned {
return new MetadataVersioned({
magicNumber: this.magicNumber,
metadata: new MetadataEnum(toCallsOnly(this.asLatest), this.version)
});
}
/**
* @description Returns the wrapped values as a latest version object
*/
@@ -336,6 +315,27 @@ export default class MetadataVersioned extends Struct {
return this.asV8;
}
/**
* @description
*/
public get magicNumber (): MagicNumber {
return this.get('magicNumber') as MagicNumber;
}
/**
* @description the metadata wrapped
*/
private get metadata (): MetadataEnum {
return this.get('metadata') as MetadataEnum;
}
/**
* @description the metadata version this structure represents
*/
public get version (): number {
return this.metadata.index;
}
public getUniqTypes (throwError: boolean): string[] {
return getUniqTypes(this.asLatest, throwError);
}
+1 -3
View File
@@ -4,8 +4,6 @@
import '../../injector';
import extrinsicsFromMeta from '@polkadot/api-metadata/extrinsics/fromMetadata';
import { createTypeUnsafe } from '../../codec/create';
import Metadata from '../Metadata';
import Call from '../../primitive/Generic/Call';
@@ -57,7 +55,7 @@ export function defaultValues (rpcData: string): void {
describe('storage with default values', (): void => {
const metadata = new Metadata(rpcData);
Call.injectMethods(extrinsicsFromMeta(metadata));
Call.injectMetadata(metadata);
metadata.asLatest.modules
.filter(({ storage }): boolean => storage.isSome)
+3 -3
View File
@@ -8,9 +8,9 @@ import { VoteThreshold } from '../interfaces/elections';
import { BlockNumber } from '../interfaces/runtime';
import { CodecTo } from '../types';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import { ClassOf } from './create';
import Metadata from '../Metadata';
import metadataStatic from '../Metadata/static';
import Call from '../primitive/Generic/Call';
import Text from '../primitive/Text';
import U32 from '../primitive/U32';
@@ -66,7 +66,7 @@ describe('Tuple', (): void => {
});
it.skip('creates properly via actual hex string', (): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
const test = new (Tuple.with([
ClassOf('BlockNumber'), ClassOf('Proposal'), ClassOf('VoteThreshold')
+5 -3
View File
@@ -2,11 +2,13 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import '../injector';
import { Proposal, PropIndex } from '../interfaces/democracy';
import { Codec, CodecTo } from '../types';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import Metadata from '../Metadata';
import metadataStatic from '../Metadata/static';
import AccountId from '../primitive/Generic/AccountId';
import Call from '../primitive/Generic/Call';
import Text from '../primitive/Text';
@@ -20,7 +22,7 @@ describe('Vec', (): void => {
beforeEach((): void => {
vector = new Vec(Text, ['1', '23', '345', '4567', new Text('56789')]);
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
it('wraps a sequence of values', (): void => {
+3 -3
View File
@@ -4,8 +4,8 @@
import './injector';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import Metadata from './Metadata';
import metadataStatic from './Metadata/static';
import { createTypeUnsafe } from './codec/create';
import GenericCall from './primitive/Generic/Call';
import { Codec } from './types';
@@ -41,7 +41,7 @@ function testTypes (type: string, typeNames: string[]): void {
});
describe(`${type}:: default creation (empty bytes)`, (): void => {
GenericCall.injectMethods(extrinsics);
GenericCall.injectMetadata(new Metadata(metadataStatic));
typeNames.forEach((name): void => {
it(`creates an empty ${name} (from empty bytes)`, (): void => {
@@ -4,8 +4,8 @@
import '../../injector';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import Metadata from '../../Metadata';
import metadataStatic from '../../Metadata/static';
import { createType } from '../../codec/create';
import Call from '../../primitive/Generic/Call';
import events from '../../json/SignedBlock.002.json';
@@ -15,7 +15,7 @@ import knownMehods from '../../json/SignedBlock.005.json';
describe('SignedBlock', (): void => {
beforeEach((): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
it('decodes a full block', (): void => {
@@ -2,16 +2,18 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import '../../injector';
import { hexToU8a } from '@polkadot/util';
import Call from '../Generic/Call';
import Metadata from '../../Metadata';
import metadataStatic from '../../Metadata/static';
import Extrinsic from './Extrinsic';
describe('Extrinsic', (): void => {
beforeAll((): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
describe('V1', (): void => {
@@ -2,9 +2,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import { createType, GenericCall } from '@polkadot/types';
import Metadata from '../../Metadata';
import metadataStatic from '../../Metadata/static';
import SignerPayload from './SignerPayload';
describe('SignerPayload', (): void => {
@@ -22,7 +23,7 @@ describe('SignerPayload', (): void => {
};
beforeEach((): void => {
GenericCall.injectMethods(extrinsics);
GenericCall.injectMetadata(new Metadata(metadataStatic));
});
it('creates a valid JSON output', (): void => {
@@ -2,10 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import '../../../injector';
import BN from 'bn.js';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import testingPairs from '@polkadot/keyring/testingPairs';
import Metadata from '../../../Metadata';
import metadataStatic from '../../../Metadata/static';
import Call from '../../Generic/Call';
import Extrinsic from './Extrinsic';
@@ -13,7 +17,7 @@ const keyring = testingPairs({ type: 'ed25519' }, false);
describe('ExtrinsicV2', (): void => {
beforeEach((): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
it('constructs a sane Uint8Array (default)', (): void => {
@@ -2,10 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import '../../../injector';
import BN from 'bn.js';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import testingPairs from '@polkadot/keyring/testingPairs';
import Metadata from '../../../Metadata';
import metadataStatic from '../../../Metadata/static';
import Call from '../../Generic/Call';
import Extrinsic from './Extrinsic';
@@ -13,7 +17,7 @@ const keyring = testingPairs({ type: 'ed25519' }, false);
describe('ExtrinsicV3', (): void => {
beforeEach((): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
it('constructs a sane Uint8Array (default)', (): void => {
@@ -4,15 +4,15 @@
import '../../injector';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import Metadata from '../../Metadata';
import metadataStatic from '../../Metadata/static';
import block00300 from '../../json/SignedBlock.003.00.json';
import Call from './Call';
import Block from './Block';
describe('Block', (): void => {
beforeEach((): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
it('has a valid toRawType', (): void => {
@@ -2,13 +2,15 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
import '../../injector';
import Metadata from '../../Metadata';
import metadataStatic from '../../Metadata/static';
import Call from './Call';
describe('Call', (): void => {
beforeEach((): void => {
Call.injectMethods(extrinsics);
Call.injectMetadata(new Metadata(metadataStatic));
});
it('handles decoding correctly (bare)', (): void => {
+9 -7
View File
@@ -3,13 +3,15 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { FunctionArgumentMetadataLatest, FunctionMetadataLatest } from '../../interfaces/metadata';
import { AnyU8a, ArgsDef, CallFunction, Codec, IMethod, ModulesWithCalls } from '../../types';
import { AnyU8a, ArgsDef, CallFunction, Codec, IMethod } from '../../types';
import extrinsicsFromMeta from '@polkadot/api-metadata/extrinsics/fromMetadata';
import { assert, isHex, isObject, isU8a, u8aToU8a } from '@polkadot/util';
import { getTypeDef, getTypeClass } from '../../codec/create';
import Struct from '../../codec/Struct';
import U8aFixed from '../../codec/U8aFixed';
import Metadata from '../../Metadata';
interface DecodeMethodInput {
args: any;
@@ -80,7 +82,7 @@ export default class Call extends Struct implements IMethod {
}
private static decodeCallViaObject (value: DecodedMethod, _meta?: FunctionMetadataLatest): DecodedMethod {
// destructure value, we only pass args/methodsIndex out
// we only pass args/methodsIndex out
const { args, callIndex } = value;
// Get the correct lookupIndex
@@ -154,10 +156,10 @@ export default class Call extends Struct implements IMethod {
}, {} as unknown as ArgsDef);
}
// This is called/injected by the API on init, allowing a snapshot of
// the available system extrinsics to be used in lookups
public static injectMethods (moduleMethods: ModulesWithCalls): void {
Object.values(moduleMethods).forEach((methods): void =>
public static injectMetadata (metadata: Metadata): void {
const extrinsics = extrinsicsFromMeta(metadata);
Object.values(extrinsics).forEach((methods): void =>
Object.values(methods).forEach((method): void => {
injected[method.callIndex.toString()] = method;
})
@@ -173,7 +175,7 @@ export default class Call extends Struct implements IMethod {
}
/**
* @description Thge argument defintions
* @description The argument definitions
*/
public get argsDef (): ArgsDef {
return Call.getArgsDef(this.meta);
@@ -2,6 +2,8 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import '../injector';
import fromMetadata from '@polkadot/api-metadata/storage/fromMetadata';
import { hexToU8a } from '@polkadot/util';
import rpcDataV3 from '@polkadot/types/Metadata/v3/static';
+4 -5
View File
@@ -2,19 +2,15 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// NOTE When adding any types here, we need to update the coumentation links as
// NOTE When adding any types here, we need to update the documentation links as
// well - <root>/docs/SUMMARY.md as well as ../README.md
/**
* @summary Type definitions that are used in the system
*/
// NOTE We are exporting Bool as bool to match with Rust (however also using Bool internally),
// so with the renamed versions, epose both cases, allowing createType to work
export { default as bool } from './Bool';
export { default as Bytes } from './Bytes';
export { default as Data } from './Data';
export * from './Extrinsic';
export * from './Generic';
export { default as H160 } from './H160';
export { default as H256 } from './H256';
export { default as H512 } from './H512';
@@ -38,3 +34,6 @@ export { default as u64 } from './U64';
export { default as u128 } from './U128';
export { default as u256 } from './U256';
export { default as usize } from './USize';
export * from './Generic';
export * from './Extrinsic';
@@ -9,6 +9,7 @@ require('@babel/register')({
plugins: [
['module-resolver', {
alias: {
'^@polkadot/api-metadata(.*)': './packages/api-metadata/src\\1',
'^@polkadot/types(.*)': './packages/types/src\\1'
}
}]
@@ -5,7 +5,15 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@babel/register')({
extensions: ['.js', '.ts']
extensions: ['.js', '.ts'],
plugins: [
['module-resolver', {
alias: {
'^@polkadot/api-metadata(.*)': './packages/api-metadata/src\\1',
'^@polkadot/types(.*)': './packages/types/src\\1'
}
}]
]
});
require('./interfacesTs.ts');