Add extraction of calls-only metadata (#1356)

* Add extraction of calls-only metadata

* Add --ws option to chain info

* Validate types
This commit is contained in:
Jaco Greeff
2019-09-02 14:22:49 +02:00
committed by GitHub
parent 20b835778d
commit bc3d21b66b
11 changed files with 143 additions and 22 deletions
@@ -22,14 +22,14 @@ import v3ToV4 from './v3/toV4';
import v4ToV5 from './v4/toV5';
import v5ToV6 from './v5/toV6';
import v6ToV7 from './v6/toV7';
import { getUniqTypes } from './util';
import { getUniqTypes, toCallsOnly } from './util';
type MetaMapped = MetadataV0 | MetadataV1 | MetadataV2 | MetadataV3 | MetadataV4 | MetadataV5 | MetadataV6 | MetadataV7;
type MetaVersions = 1 | 2 | 3 | 4 | 5 | 6 | 7;
type MetaAsX = 'asV0' | 'asV1' | 'asV2' | 'asV3' | 'asV4' | 'asV5' | 'asV6';
class MetadataEnum extends Enum {
public constructor (value?: any) {
public constructor (value?: any, index?: number) {
super({
V0: 'MetadataV0', // once rolled-out, can replace this with MetadataDeprecated
V1: 'MetadataV1', // once rolled-out, can replace this with MetadataDeprecated
@@ -39,7 +39,7 @@ class MetadataEnum extends Enum {
V5: MetadataV5, // once rolled-out, can replace this with MetadataDeprecated
V6: MetadataV6, // once rolled-out, can replace this with MetadataDeprecated
V7: MetadataV7
}, value);
}, value, index);
}
/**
@@ -293,6 +293,16 @@ export default class MetadataVersioned extends Struct {
return this.getVersion(7, v6ToV7);
}
/**
* @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
*/
@@ -4,4 +4,5 @@
export { default as flattenUniq } from './flattenUniq';
export { default as getUniqTypes } from './getUniqTypes';
export { default as toCallsOnly } from './toCallsOnly';
export { default as validateTypes } from './validateTypes';
@@ -0,0 +1,25 @@
// Copyright 2017-2019 @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 '../../injector';
import staticData from '../static';
import Metadata from '..';
describe('toCallsOnly', (): void => {
it('creates a calls-only version of the metadata', (): void => {
const stripped = new Metadata(staticData).asCallsOnly;
console.error(JSON.stringify(stripped));
expect(stripped).toBeDefined();
});
it('can serialize from the input', (): void => {
const s1 = new Metadata(staticData).asCallsOnly.toU8a();
const s2 = new Metadata(s1).asCallsOnly.toU8a();
expect(s1).toEqual(s2);
});
});
@@ -0,0 +1,18 @@
// Copyright 2017-2019 @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 MetadataV7 from '../v7';
/**
* @description Convert from MetadataV7 to a stripped representation of MetadataV7
*/
export default function toCallsOnly ({ modules }: MetadataV7): any {
return new MetadataV7({
// FIXME, this needs typing, not any
modules: modules.map(({ calls, name }): any => ({
name,
calls
}))
}).toJSON();
}
+13 -6
View File
@@ -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 { stringToU8a, u8aConcat } from '@polkadot/util';
import Text from './Text';
import Type from './Type';
@@ -66,12 +68,6 @@ describe('Type', (): void => {
).toEqual('Null');
});
it('does not allow toU8a', (): void => {
expect(
(): Uint8Array => new Type().toU8a()
).toThrow(/unimplemented/);
});
it('has a length for the type', (): void => {
expect(
new Type(
@@ -91,4 +87,15 @@ describe('Type', (): void => {
new Type('<T::InherentOfflineReport as InherentOfflineReport>::Inherent').toString()
).toEqual('InherentOfflineReport');
});
it('encodes correctly via toU8a()', (): void => {
const type = 'Compact<Balance>';
expect(new Text(type).toU8a()).toEqual(
u8aConcat(
new Uint8Array([type.length << 2]),
stringToU8a(type)
)
);
});
});
-12
View File
@@ -91,18 +91,6 @@ export default class Type extends Text {
return this._originalLength;
}
/**
* @description Encodes the value as a Uint8Array as per the SCALE specifications
* @param isBare true when the value has none of the type-specific prefixes (internal)
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public toU8a (isBare?: boolean): Uint8Array {
// Note Since we are mangling what we get in beyond recognition, we really should
// not allow the re-encoding. Additionally, this is probably more of a decoder-only
// helper, so treat it as such.
throw new Error('Type::toU8a: unimplemented');
}
// given a starting index, find the closing >
private static _findClosing (value: string, start: number): number {
let depth = 0;
@@ -9,7 +9,7 @@ require('@babel/register')({
plugins: [
['module-resolver', {
alias: {
'^@polkadot/types(.*)': './packages/types/src\\2'
'^@polkadot/types(.*)': './packages/types/src\\1'
}
}]
]
@@ -0,0 +1,46 @@
// Copyright 2017-2019 @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.
// Connects to the local chain and outputs a re-usable calls-only chain definition in the form
// export default { chain: 'Development', genesisHash: '0x27b6d5e0f4fdce1c4d20b82406f193acacce0c19e0d2c0e7ca47725c2572a06a', ss58Format: 42, tokenDecimals: 0, tokenSymbol: 'UNIT'; metaCalls: 'bWV0...4AAA==' };
import process from 'process';
import yargs from 'yargs';
import { ApiPromise, WsProvider } from '@polkadot/api/index';
// retrieve and parse arguments - we do this globally, since this is a single command
const { argv: { ws } } = yargs
.usage('Usage: [options]')
.wrap(120)
.options({
ws: {
default: 'ws://127.0.0.1:9944',
description: 'The API endpoint to connect to, e.g. wss://poc3-rpc.polkadot.io',
type: 'string',
required: true
}
});
async function main (): Promise<void> {
const provider = new WsProvider(ws);
const api = await ApiPromise.create({ provider });
const chain = await api.rpc.system.chain();
const props = await api.rpc.system.properties();
const meta = await api.rpc.state.getMetadata();
// output the chain info, for easy re-use
console.error(`export default { chain: '${chain.toString()}', genesisHash: '${api.genesisHash.toHex()}', ss58Format: ${props.ss58Format.unwrapOr(42)}, tokenDecimals: ${props.tokenDecimals.unwrapOr(0)}, tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT')}', metaCalls: '${Buffer.from(meta.asCallsOnly.toU8a()).toString('base64')}' };`);
// show any missing types
meta.getUniqTypes(false);
}
main()
.then((): void => {
process.exit(0);
})
.catch((error: Error) => {
console.error('FATAL:', error.message);
process.exit(-1);
});
@@ -0,0 +1,24 @@
#!/usr/bin/env node
// Copyright 2017-2019 @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.
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@babel/register')({
extensions: ['.js', '.ts'],
plugins: [
['module-resolver', {
alias: {
'^@polkadot/api-derive(.*)': './packages/api-derive/src\\1',
'^@polkadot/api-metadata(.*)': './packages/api-metadata/src\\1',
'^@polkadot/api(.*)': './packages/api/src/\\1',
'^@polkadot/jsonrpc(.*)': './packages/type-jsonrpc/src\\1',
'^@polkadot/rpc-core(.*)': './packages/rpc-core/src\\1',
'^@polkadot/rpc-provider(.*)': './packages/rpc-provider/src\\1',
'^@polkadot/types(.*)': './packages/types/src\\1'
}
}]
]
});
require('./extractChain.ts');