Use custom hasher for Map (#857)

* Use blake2 instead of two_x

* Add v4

* Update to new v4 static

* Update json

* Revert

* Use hasher enum

* Fix metadata v4 test

* Fix metadata v4 test

* Fix versioned metadata

* refactor & clean

* Use consistent naming

* Make jsons consistent

* Add backward compat

* Fix tests

* Start working on type-storage

* Fix output

* Grumble

* Update to latest static

* Clean code

* Fix imports

* Remove useless imports

* Fix tests

* Use prettier output for toJSON in metadata

* Implement different hashers

* Remove generic storageKey

* Bump version

* Add backwards-compat

* Fix hashing function, use Twox128

* Grumbles

* Add tests
This commit is contained in:
Amaury Martiny
2019-04-25 15:34:35 +02:00
committed by GitHub
parent 38c2215bb1
commit 4dd320fc89
63 changed files with 5622 additions and 1402 deletions
+4
View File
@@ -1,3 +1,7 @@
# 0.78.1
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
# 0.77.1
- Add TresuryProposal (not the same as democracy, type aliassed)
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "0.77.0-beta.7"
"version": "0.77.0"
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"version": "0.77.0-beta.7",
"version": "0.77.0",
"private": true,
"engines": {
"node": ">=10.13.0",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -31,8 +31,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/api": "^0.77.0-beta.7",
"@polkadot/types": "^0.77.0-beta.7",
"@polkadot/api": "^0.77.0",
"@polkadot/types": "^0.77.0",
"@types/memoizee": "^0.4.2",
"memoizee": "^0.4.14"
}
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"keywords": [
@@ -30,12 +30,12 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/api-derive": "^0.77.0-beta.7",
"@polkadot/extrinsics": "^0.77.0-beta.7",
"@polkadot/rpc-provider": "^0.77.0-beta.7",
"@polkadot/rpc-rx": "^0.77.0-beta.7",
"@polkadot/storage": "^0.77.0-beta.7",
"@polkadot/types": "^0.77.0-beta.7",
"@polkadot/api-derive": "^0.77.0",
"@polkadot/extrinsics": "^0.77.0",
"@polkadot/rpc-provider": "^0.77.0",
"@polkadot/rpc-rx": "^0.77.0",
"@polkadot/storage": "^0.77.0",
"@polkadot/types": "^0.77.0",
"@polkadot/util-crypto": "^0.76.1"
}
}
+1 -1
View File
@@ -390,7 +390,7 @@ export default abstract class ApiBase<CodecResult, SubscriptionResult> implement
}
const extrinsics = extrinsicsFromMeta(this.runtimeMetadata.asV0);
const storage = storageFromMeta(this.runtimeMetadata.asV0);
const storage = storageFromMeta(this.runtimeMetadata);
this._extrinsics = this.decorateExtrinsics(extrinsics, this.onCall);
this._query = this.decorateStorage(storage, this.onCall) as any; // FIXME 3.4.1
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-core",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"keywords": [
@@ -30,9 +30,9 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/jsonrpc": "^0.77.0-beta.7",
"@polkadot/rpc-provider": "^0.77.0-beta.7",
"@polkadot/types": "^0.77.0-beta.7",
"@polkadot/jsonrpc": "^0.77.0",
"@polkadot/rpc-provider": "^0.77.0",
"@polkadot/types": "^0.77.0",
"@polkadot/util": "^0.76.1"
}
}
+4 -4
View File
@@ -192,7 +192,7 @@ export default class Rpc implements RpcInterface {
const key = params[0] as StorageKey;
const type = key.outputType || 'Data';
const Clazz = createClass(type);
const meta = key.meta || { default: undefined, modifier: { isOptional: true } };
const meta = key.meta || { fallback: undefined, modifier: { isOptional: true } };
if (key.meta && key.meta.type.isMap && key.meta.type.asMap.isLinked) {
// linked map
@@ -218,11 +218,11 @@ export default class Rpc implements RpcInterface {
const { value } = (base as StorageChangeSet).changes.find((item) =>
item.key.toHex() === hexKey
) || { value: null };
const meta = key.meta || { default: undefined, modifier: { isOptional: true } };
const meta = key.meta || { fallback: undefined, modifier: { isOptional: true } };
if (!value) {
// if we don't have a value, do not fill in the entry, it will be up to the
// caller to sort this out, either ignoring or having a cache for older values
// caller to sort this out, either ignoring or having a cache for older values
result.push(undefined);
} else {
if (key.meta && key.meta.type.isMap && key.meta.type.asMap.isLinked) {
@@ -236,7 +236,7 @@ export default class Rpc implements RpcInterface {
} else {
// for `null` we fallback to the default value, or create an empty type,
// otherwise we return the actual value as retrieved
result.push(new Clazz(value.unwrapOr(meta.default)));
result.push(new Clazz(value.unwrapOr(meta.fallback)));
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-provider",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Transport providers for the API",
"main": "index.js",
"keywords": [
@@ -31,7 +31,7 @@
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/keyring": "^0.76.1",
"@polkadot/storage": "^0.77.0-beta.7",
"@polkadot/storage": "^0.77.0",
"@polkadot/util": "^0.76.1",
"@polkadot/util-crypto": "^0.76.1",
"@types/nock": "^9.3.1",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-rx",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "An RxJs wrapper around the Polkadot JS API",
"main": "index.js",
"keywords": [
@@ -30,8 +30,8 @@
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-rx#readme",
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/rpc-core": "^0.77.0-beta.7",
"@polkadot/rpc-provider": "^0.77.0-beta.7",
"@polkadot/rpc-core": "^0.77.0",
"@polkadot/rpc-provider": "^0.77.0",
"@types/memoizee": "^0.4.2",
"@types/rx": "^4.1.1",
"memoizee": "^0.4.14",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/extrinsics",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"main": "index.js",
"repository": "https://github.com/polkadot-js/api.git",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -11,7 +11,7 @@
"license": "Apache-2.0",
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/types": "^0.77.0-beta.7",
"@polkadot/types": "^0.77.0",
"@polkadot/util": "^0.76.1"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/jsonrpc",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Method definitions for the Polkadot RPC layer",
"main": "index.js",
"engines": {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/storage",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Generic wrapper wrapper around state storage",
"main": "index.js",
"engines": {
@@ -31,7 +31,7 @@
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/keyring": "^0.76.1",
"@polkadot/types": "^0.77.0-beta.7",
"@polkadot/types": "^0.77.0",
"@polkadot/util": "^0.76.1",
"@polkadot/util-crypto": "^0.76.1"
}
@@ -0,0 +1,27 @@
// Copyright 2017-2019 @polkadot/storage 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 { Storage } from '../types';
import Metadata from '@polkadot/types/Metadata';
import fromV0 from './v0';
import fromV4 from './v4';
/**
* Extend a storage object with the storage modules & module functions present
* in the metadata.
*
* @param storage - A storage object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromMetadata (metadata: Metadata): Storage {
// For v0-v3 we convert to v0, and use the fromV0 function to parse
if ([0, 1, 2, 3].includes(metadata.version)) {
return fromV0(metadata.asV0);
}
// For v4, we use fromV4 function
return fromV4(metadata.asV4);
}
@@ -0,0 +1,7 @@
// Copyright 2017-2019 @polkadot/storage 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 fromMetadata from './fromMetadata';
export default fromMetadata;
@@ -2,12 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Modules';
import { PlainType, StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { Compact, Text, createType, StorageKey, Bytes, U8a } from '@polkadot/types';
import { assert, isNull, isUndefined, stringLowerFirst, stringToU8a, u8aConcat } from '@polkadot/util';
import { xxhashAsU8a } from '@polkadot/util-crypto';
import { PlainType } from '@polkadot/types/Metadata/v2/Storage';
export interface CreateItemOptions {
isUnhashed?: boolean;
@@ -60,7 +59,7 @@ export default function createFunction (section: Text | string, method: Text | s
name: meta.name,
modifier: new StorageFunctionModifier('Required'),
type: new StorageFunctionType(new PlainType(meta.type.asMap.key), 0),
default: new Bytes(),
fallback: new Bytes(),
documentation: meta.documentation
});
storageFn.headKey = new StorageKey(keyFn);
@@ -2,13 +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 { ModuleStorage, Storage } from './types';
import { ModuleStorage, Storage } from '../../types';
import MetadataV0 from '@polkadot/types/Metadata/v0';
import { stringLowerFirst } from '@polkadot/util';
import createFunction from './utils/createFunction';
import storage from '.';
import createFunction from './createFunction';
import { storage } from './storage';
/**
* Extend a storage object with the storage modules & module functions present
@@ -17,7 +17,7 @@ import storage from '.';
* @param storage - A storage object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromMetadata (metadata: MetadataV0): Storage {
export default function fromV0 (metadata: MetadataV0): Storage {
return metadata.modules.reduce((result, moduleMetadata) => {
if (moduleMetadata.storage.isNone) {
return result;
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Storage } from './types';
import { Storage } from '../../types';
import * as substrate from './substrate';
export const storage: Storage = {
@@ -2,11 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Modules';
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { Text, Vector } from '@polkadot/types';
import createFunction from './utils/createFunction';
import createFunction from './createFunction';
interface SubstrateMetadata {
documentation: string;
@@ -22,8 +22,7 @@ const createRuntimeFunction = (method: string, key: string, { documentation, typ
documentation: new Vector(Text, [documentation]),
modifier: new StorageFunctionModifier(1), // default
type: new StorageFunctionType(type, 0),
toJSON: (): any =>
key
toJSON: (): any => key
} as StorageFunctionMetadata,
{
isUnhashed: true,
@@ -47,7 +46,7 @@ export const authorityCount = createRuntimeFunction('authorityCount', ':auth:len
});
export const authorityPrefix = createRuntimeFunction('authorityPrefix', ':auth:', {
documentation: 'Prefix under which authorities are storied.',
documentation: 'Prefix under which authorities are stored.',
type: 'u32'
});
@@ -6,13 +6,13 @@ import { u8aToHex } from '@polkadot/util';
import { Metadata } from '@polkadot/types';
import json from '@polkadot/types/Metadata/v0/static';
import fromMetadata from './fromMetadata';
import fromv0 from '.';
// Use the pre-generated metadata
const metadata = new Metadata(json).asV0;
const newStorage = fromMetadata(metadata);
const newStorage = fromv0(metadata);
describe('fromMetadata', () => {
describe('fromv0', () => {
it('should throw if the storage function expects an argument', () => {
expect(() => newStorage.balances.freeBalance()).toThrowError(/expects one argument/);
});
@@ -0,0 +1,56 @@
// Copyright 2017-2019 @polkadot/storage 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 { stringToU8a, u8aConcat } from '@polkadot/util';
import createFunction from './createFunction';
describe('createFunction', () => {
it('should create timestamp.now correctly', () => {
expect(
createFunction(
'Timestamp',
'Now',
{ type: {} } as any
)()
).toEqual(
Uint8Array.from([64, 14, 73, 68, 207, 217, 141, 111, 76, 195, 116, 209, 111, 90, 78, 63, 156]) // Length-prefixed
);
});
it('allows overrides on key (keeping name)', () => {
expect(
createFunction(
'Substrate',
'authorityCount',
{ type: {} } as any,
{
isUnhashed: true,
key: ':auth:len'
}
).method
).toEqual('authorityCount');
});
it('allows overrides on key (unhashed)', () => {
const key = ':auth:len';
expect(
createFunction(
'Substrate',
'authorityCount',
{ type: {} } as any,
{
isUnhashed: true,
key
}
)()
).toEqual(
u8aConcat(
Uint8Array.from([key.length << 2]),
stringToU8a(':auth:len')
)
);
});
});
@@ -0,0 +1,81 @@
// Copyright 2017-2019 @polkadot/storage 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 { createType, Bytes, Compact, StorageKey, Text, U8a } from '@polkadot/types';
import { PlainType, StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v4/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { assert, isNull, isUndefined, stringLowerFirst, stringToU8a, u8aConcat } from '@polkadot/util';
import getHasher from './getHasher';
export interface CreateItemOptions {
isUnhashed?: boolean;
key?: string;
}
/**
* From the schema of a function in the module's storage, generate the function
* that will return the correct storage key.
*
* @param schema - The function's definition schema to create the function from.
* The schema is taken from state_getMetadata.
* @param options - Additional options when creating the function. These options
* are not known at runtime (from state_getMetadata), they need to be supplied
* by us manually at compile time.
*/
export default function createFunction (section: Text | string, method: Text | string, meta: StorageFunctionMetadata, options: CreateItemOptions = {}): StorageFunction {
const stringKey = options.key
? options.key
: `${section.toString()} ${method.toString()}`;
const rawKey = stringToU8a(stringKey);
// Get the hashing function
// FIXME Hash correctly for double map too
const hasher = meta.type.isMap
? getHasher(meta.type.asMap.hasher)
: getHasher();
// Can only have zero or one argument:
// - storage.balances.freeBalance(address)
// - storage.timestamp.blockPeriod()
const storageFn = (arg?: any): Uint8Array => {
let key = rawKey;
if (meta.type.isMap) {
assert(!isUndefined(arg) && !isNull(arg), `${meta.name} expects one argument`);
const type = meta.type.asMap.key.toString();
const param = createType(type, arg).toU8a(false);
key = u8aConcat(key, param);
}
// StorageKey is a Bytes, so is length-prefixed
return Compact.addLengthPrefix(
options.isUnhashed
? key
: hasher(key)
);
};
if (meta.type.isMap && meta.type.asMap.isLinked) {
// TODO: there needs some better way to do this
const keyHash = new U8a(hasher(`head of ${stringKey}`));
const keyFn: any = () => keyHash;
keyFn.meta = new StorageFunctionMetadata({
name: meta.name,
modifier: new StorageFunctionModifier('Required'),
type: new StorageFunctionType(new PlainType(meta.type.asMap.key), 0),
fallback: new Bytes(),
documentation: meta.documentation
});
storageFn.headKey = new StorageKey(keyFn);
}
storageFn.meta = meta;
storageFn.method = stringLowerFirst(method.toString());
storageFn.section = stringLowerFirst(section.toString());
storageFn.toJSON = (): any => meta.toJSON();
return storageFn as StorageFunction;
}
@@ -0,0 +1,39 @@
// Copyright 2017-2019 @polkadot/storage 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 { StorageHasher } from '@polkadot/types/Metadata/v4/Storage';
import { blake2AsU8a, xxhashAsU8a } from '@polkadot/util-crypto';
type HasherInput = string | Buffer | Uint8Array;
type HasherFunction = (data: HasherInput) => Uint8Array;
export default function getHasher (hasher?: StorageHasher): HasherFunction {
// This one is the default for PlainType storage keys
if (!hasher) {
return (data: HasherInput) => xxhashAsU8a(data, 128);
}
if (hasher.isBlake2128) {
return (data: HasherInput) => blake2AsU8a(data, 128);
}
if (hasher.isBlake2256) {
return (data: HasherInput) => blake2AsU8a(data, 256);
}
if (hasher.isTwox128) {
return (data: HasherInput) => xxhashAsU8a(data, 128);
}
if (hasher.isTwox256) {
return (data: HasherInput) => xxhashAsU8a(data, 256);
}
// FIXME Add Twox128Concat
// All cases should be handled above, but if not, return Twox128 for
// backwards-compatbility
return (data: HasherInput) => xxhashAsU8a(data, 128);
}
@@ -0,0 +1,37 @@
// Copyright 2017-2019 @polkadot/storage 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 { ModuleStorage, Storage } from '../../types';
import MetadataV4 from '@polkadot/types/Metadata/v4';
import { stringLowerFirst } from '@polkadot/util';
import createFunction from './createFunction';
import { storage } from './storage';
/**
* Extend a storage object with the storage modules & module functions present
* in the metadata.
*
* @param storage - A storage object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromV4 (metadata: MetadataV4): Storage {
return metadata.modules.reduce((result, moduleMetadata) => {
if (moduleMetadata.storage.isNone) {
return result;
}
const prefix = moduleMetadata.prefix;
// For access, we change the index names, i.e. Balances.FreeBalance -> balances.freeBalance
result[stringLowerFirst(prefix.toString())] = moduleMetadata.storage.unwrap().reduce((newModule, storageFnMeta) => {
newModule[stringLowerFirst(storageFnMeta.name.toString())] = createFunction(prefix, storageFnMeta.name, storageFnMeta);
return newModule;
}, {} as ModuleStorage);
return result;
}, { ...storage });
}
@@ -0,0 +1,17 @@
// Copyright 2017-2019 @polkadot/storage 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 { storage } from './storage';
describe('storage', () => {
it('should return well known keys', () => {
expect(typeof storage.substrate).toBe('object');
expect(storage.substrate.authorityCount).toBeTruthy();
expect(storage.substrate.authorityPrefix).toBeTruthy();
expect(storage.substrate.changesTrieConfig).toBeTruthy();
expect(storage.substrate.code).toBeTruthy();
expect(storage.substrate.extrinsicIndex).toBeTruthy();
expect(storage.substrate.heapPages).toBeTruthy();
});
});
@@ -0,0 +1,10 @@
// Copyright 2017-2019 @polkadot/storage 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 { Storage } from '../../types';
import * as substrate from './substrate';
export const storage: Storage = {
substrate // Prefill storage with well known keys, as not returned by state_getMetadata
};
@@ -0,0 +1,33 @@
// Copyright 2017-2019 @polkadot/storage 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 { authorityCount, authorityPrefix, changesTrieConfig, code, extrinsicIndex, heapPages } from './substrate';
describe('substrate', () => {
it('authorityCount should return the correct storage key', () => {
expect(authorityCount()).toEqual(Uint8Array.from([36, 58, 97, 117, 116, 104, 58, 108, 101, 110])); // Length-prefixed
});
it('authorityPrefix should return the correct storage key', () => {
expect(authorityPrefix()).toEqual(Uint8Array.from([24, 58, 97, 117, 116, 104, 58])); // Length-prefixed
});
it('changesTrieConfig should return the correct storage key', () => {
expect(changesTrieConfig()).toEqual(Uint8Array.from([52, 58, 99, 104, 97, 110, 103, 101, 115, 95, 116, 114, 105, 101])); // Length-prefixed
});
it('code should return the correct storage key', () => {
expect(code()).toEqual(Uint8Array.from([20, 58, 99, 111, 100, 101])); // Length-prefixed
});
it('extrinsicIndex should return the correct storage key', () => {
expect(extrinsicIndex()).toEqual(
Uint8Array.from([64, 58, 101, 120, 116, 114, 105, 110, 115, 105, 99, 95, 105, 110, 100, 101, 120]) // Length-prefixed
);
});
it('heapPages should return the correct storage key', () => {
expect(heapPages()).toEqual(Uint8Array.from([40, 58, 104, 101, 97, 112, 112, 97, 103, 101, 115])); // Length-prefixed
});
});
@@ -0,0 +1,61 @@
// Copyright 2017-2019 @polkadot/storage 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 { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v4/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { Text, Vector } from '@polkadot/types';
import createFunction from './createFunction';
interface SubstrateMetadata {
documentation: string;
type: string;
}
// Small helper function to factorize code on this page.
const createRuntimeFunction = (method: string, key: string, { documentation, type }: SubstrateMetadata): StorageFunction =>
createFunction(
new Text('Substrate'),
new Text(method),
{
documentation: new Vector(Text, [documentation]),
modifier: new StorageFunctionModifier(1), // default
type: new StorageFunctionType(type, 0),
toJSON: (): any => key
} as StorageFunctionMetadata,
{
isUnhashed: true,
key
}
);
export const code = createRuntimeFunction('code', ':code', {
documentation: 'Wasm code of the runtime.',
type: 'Bytes'
});
export const heapPages = createRuntimeFunction('heapPages', ':heappages', {
documentation: 'Number of wasm linear memory pages required for execution of the runtime.',
type: 'u64'
});
export const authorityCount = createRuntimeFunction('authorityCount', ':auth:len', {
documentation: 'Number of authorities.',
type: 'u32'
});
export const authorityPrefix = createRuntimeFunction('authorityPrefix', ':auth:', {
documentation: 'Prefix under which authorities are stored.',
type: 'u32'
});
export const extrinsicIndex = createRuntimeFunction('extrinsicIndex', ':extrinsic_index', {
documentation: 'Current extrinsic index (u32) is stored under this key.',
type: 'u32'
});
export const changesTrieConfig = createRuntimeFunction('changesTrieConfig', ':changes_trie', {
documentation: 'Changes trie configuration is stored under this key.',
type: 'u32'
});
@@ -0,0 +1,35 @@
// Copyright 2017-2019 @polkadot/storage 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 testingPairs from '@polkadot/keyring/testingPairs';
import { Metadata } from '@polkadot/types';
import json from '@polkadot/types/Metadata/v4/static';
import { u8aToHex } from '@polkadot/util';
import fromv4 from '.';
const keyring = testingPairs({ type: 'ed25519' });
// Use the pre-generated metadata
const metadata = new Metadata(json).asV4;
const newStorage = fromv4(metadata);
describe('fromv4', () => {
it('should throw if the storage function expects an argument', () => {
expect(() => newStorage.balances.freeBalance()).toThrowError(/expects one argument/);
});
it('should return a value if the storage function does not expect an argument', () => {
expect(() => newStorage.timestamp.now()).not.toThrow();
});
it('should return the correct length-prefixed storage key', () => {
expect(
u8aToHex(
newStorage.balances.freeBalance(keyring.alice.address())
)
).toEqual(
'0x807f864e18e3dd8b58386310d2fe0919eef27c6e558564b7f67f22d99d20f587bb'
);
});
});
+1 -1
View File
@@ -2,6 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { storage } from './storage';
import { storage } from './fromMetadata/v0/storage';
export default storage;
+1 -1
View File
@@ -8,5 +8,5 @@ import metadataRpc from '@polkadot/types/Metadata/v0/static';
import fromMetadata from './fromMetadata';
export default fromMetadata(
new Metadata(metadataRpc).asV0
new Metadata(metadataRpc)
);
+1 -5
View File
@@ -4,15 +4,11 @@
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import * as substrate from './substrate';
type Substrate = keyof typeof substrate;
export interface ModuleStorage {
[key: string]: StorageFunction;
}
export interface Storage {
[key: string]: ModuleStorage; // Will hold modules returned by state_getMetadata
substrate: { [key in Substrate]: StorageFunction };
substrate: { [key: string]: StorageFunction };
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Implementation of the Parity codec",
"main": "index.js",
"keywords": [
@@ -14,17 +14,20 @@ import MetadataV0 from './v0';
import MetadataV1 from './v1';
import MetadataV2 from './v2';
import MetadataV3 from './v3';
import MetadataV4 from './v4';
import v1ToV0 from './v1/toV0';
import v2ToV1 from './v2/toV1';
import v3ToV2 from './v3/toV2';
import v4ToV3 from './v4/toV3';
class MetadataEnum extends EnumType<Null | MetadataV1 | MetadataV2> {
class MetadataEnum extends EnumType<Null | MetadataV1 | MetadataV2 | MetadataV3 | MetadataV4> {
constructor (value?: any) {
super({
MetadataV0, // once rolled-out, can replace this with Null
MetadataV1, // once rolled-out, can replace this with Null
MetadataV2, // once rolled-out, can replace this with Null
MetadataV3
MetadataV3, // once rolled-out, can replace this with Null
MetadataV4
}, value);
}
@@ -56,6 +59,13 @@ class MetadataEnum extends EnumType<Null | MetadataV1 | MetadataV2> {
return this.value as MetadataV3;
}
/**
* @description Returns the wrapped values as a V4 object
*/
get asV4 (): MetadataV4 {
return this.value as MetadataV4;
}
/**
* @description The version this metadata represents
*/
@@ -73,6 +83,7 @@ export default class MetadataVersioned extends Struct implements MetadataInterfa
private _convertedV0?: MetadataV0;
private _convertedV1?: MetadataV1;
private _convertedV2?: MetadataV2;
private _convertedV3?: MetadataV3;
constructor (value?: any) {
super({
@@ -125,7 +136,7 @@ export default class MetadataVersioned extends Struct implements MetadataInterfa
return this.metadata.asV1;
}
assert([2, 3].includes(this.metadata.version), `Cannot convert metadata from v${this.metadata.version} to v1`);
assert([2, 3, 4].includes(this.metadata.version), `Cannot convert metadata from v${this.metadata.version} to v1`);
if (isUndefined(this._convertedV1)) {
this._convertedV1 = v2ToV1(this.metadata.asV2);
@@ -142,7 +153,7 @@ export default class MetadataVersioned extends Struct implements MetadataInterfa
return this.metadata.asV2;
}
assert(this.metadata.version === 3, `Cannot convert metadata from v${this.metadata.version} to v1`);
assert([3, 4].includes(this.metadata.version), `Cannot convert metadata from v${this.metadata.version} to v2`);
if (isUndefined(this._convertedV2)) {
this._convertedV2 = v3ToV2(this.metadata.asV3);
@@ -155,7 +166,15 @@ export default class MetadataVersioned extends Struct implements MetadataInterfa
* @description Returns the wrapped values as a V3 object
*/
get asV3 (): MetadataV3 {
assert(this.metadata.version === 3, `Cannot convert metadata from v${this.metadata.version} to v3`);
if (this.metadata.version === 3) {
return this.metadata.asV3;
}
assert([4].includes(this.metadata.version), `Cannot convert metadata from v${this.metadata.version} to v2`);
if (isUndefined(this._convertedV3)) {
this._convertedV3 = v4ToV3(this.metadata.asV4);
}
return this.metadata.asV3;
}
@@ -163,4 +182,13 @@ export default class MetadataVersioned extends Struct implements MetadataInterfa
getUniqTypes (throwError: boolean): Array<string> {
return (this.metadata.value as any as MetadataInterface).getUniqTypes(throwError);
}
/**
* @description Returns the wrapped values as a V3 object
*/
get asV4 (): MetadataV4 {
assert(this.metadata.version === 4, `Cannot convert metadata from v${this.metadata.version} to v4`);
return this.metadata.asV4;
}
}
+8
View File
@@ -31,6 +31,14 @@ export class EventMetadata extends Struct {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The name for the event
*/
@@ -33,7 +33,7 @@ describe('Metadata', () => {
mod.storage.unwrap().functions.forEach((fn) => {
it(`creates default types for ${mod.prefix}.${fn.name}, type ${fn.type}`, () => {
expect(
() => createType(fn.type.toString(), fn.default)
() => createType(fn.type.toString(), fn.fallback)
).not.toThrow();
});
});
+10 -178
View File
@@ -2,18 +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 { AnyNumber } from '../../types';
import Enum from '../../codec/Enum';
import EnumType from '../../codec/EnumType';
import Option from '../../codec/Option';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Bytes from '../../primitive/Bytes';
import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
import U16 from '../../primitive/U16';
import { StorageMetadata } from './Storage';
export class FunctionArgumentMetadata extends Struct {
constructor (value?: any) {
super({
@@ -61,6 +58,14 @@ export class FunctionMetadata extends Struct {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The `[sectionIndex, methodIndex]` call id
*/
@@ -122,179 +127,6 @@ export class ModuleMetadata extends Struct {
}
}
export class StorageFunctionModifier extends Enum {
constructor (value?: any) {
super(['Optional', 'Default', 'Required'], value);
}
/**
* @description `true` if the storage entry is optional
*/
get isOptional (): boolean {
return this.toNumber() === 0;
}
}
export class MapType extends Struct {
private _isLinked = false;
constructor (value?: any) {
super({
key: Type,
value: Type
}, value);
if (value && value.isLinked) {
this._isLinked = true;
}
}
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
return this.get('value') as Type;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
return this._isLinked;
}
}
class PlainType extends Type {
}
export class StorageFunctionType extends EnumType<PlainType | MapType> {
constructor (value?: any, index?: number) {
super({
PlainType,
MapType
}, value, index);
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
return this.value as MapType;
}
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
return this.value as PlainType;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
if (this.isMap) {
if (this.asMap.isLinked) {
return `(${this.asMap.value.toString()}, Linkage<${this.asMap.key.toString()}>)`;
}
return this.asMap.value.toString();
}
return this.asType.toString();
}
}
type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
default: Bytes,
documentation: Vector<Text> | Array<string>
};
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
type: StorageFunctionType,
default: Bytes,
documentation: Vector.with(Text)
}, value);
}
/**
* @description The default value of the storage function
*/
get default (): Bytes {
return this.get('default') as Bytes;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The key name
*/
get name (): Text {
return this.get('name') as Text;
}
/**
* @description The modifier
*/
get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
export class StorageMetadata extends Struct {
constructor (value?: any) {
super({
prefix: Text,
functions: Vector.with(StorageFunctionMetadata)
}, value);
}
/**
* @description The [[StorageFunctionMetadata]] for the section
*/
get functions (): Vector<StorageFunctionMetadata> {
return this.get('functions') as Vector<StorageFunctionMetadata>;
}
/**
* @description The section prefix
*/
get prefix (): Text {
return this.get('prefix') as Text;
}
}
export class RuntimeModuleMetadata extends Struct {
constructor (value?: any) {
super({
+207
View File
@@ -0,0 +1,207 @@
// 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 { AnyNumber } from '../../types';
import Enum from '../../codec/Enum';
import EnumType from '../../codec/EnumType';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Bytes from '../../primitive/Bytes';
import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
export class StorageFunctionModifier extends Enum {
constructor (value?: any) {
super(['Optional', 'Default', 'Required'], value);
}
/**
* @description `true` if the storage entry is optional
*/
get isOptional (): boolean {
return this.toNumber() === 0;
}
toJSON (): any {
// This looks prettier in the generated JSON
return this.toString();
}
}
export class MapType extends Struct {
private _isLinked = false;
constructor (value?: any) {
super({
key: Type,
value: Type
}, value);
if (value && value.isLinked) {
this._isLinked = true;
}
}
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
return this.get('value') as Type;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
return this._isLinked;
}
}
export class PlainType extends Type {
}
export class StorageFunctionType extends EnumType<PlainType | MapType> {
constructor (value?: any, index?: number) {
super({
PlainType,
MapType
}, value, index);
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
return this.value as MapType;
}
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
return this.value as PlainType;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
if (this.isMap) {
if (this.asMap.isLinked) {
return `(${this.asMap.value.toString()}, Linkage<${this.asMap.key.toString()}>)`;
}
return this.asMap.value.toString();
}
return this.asType.toString();
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector.with(Text)
}, value);
}
/**
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
return this.fallback;
}
/**
* @description The default value of the storage function
*/
get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The key name
*/
get name (): Text {
return this.get('name') as Text;
}
/**
* @description The modifier
*/
get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
export class StorageMetadata extends Struct {
constructor (value?: any) {
super({
prefix: Text,
functions: Vector.with(StorageFunctionMetadata)
}, value);
}
/**
* @description The [[StorageFunctionMetadata]] for the section
*/
get functions (): Vector<StorageFunctionMetadata> {
return this.get('functions') as Vector<StorageFunctionMetadata>;
}
/**
* @description The section prefix
*/
get prefix (): Text {
return this.get('prefix') as Text;
}
}
File diff suppressed because it is too large Load Diff
+10 -2
View File
@@ -43,7 +43,7 @@ export class MetadataCall extends Struct {
// id: u16,
name: Text,
args: Vector.with(MetadataCallArg),
docs: Vector.with(Text)
documentation: Vector.with(Text)
}, value);
}
@@ -57,8 +57,16 @@ export class MetadataCall extends Struct {
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.get('docs') as Vector<Text>;
return this.documentation;
}
// /**
+10 -2
View File
@@ -17,7 +17,7 @@ export class MetadataEvent extends Struct {
super({
name: Text,
args: Vector.with(Type),
docs: Vector.with(Text)
documentation: Vector.with(Text)
}, value);
}
@@ -31,8 +31,16 @@ export class MetadataEvent extends Struct {
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.get('docs') as Vector<Text>;
return this.documentation;
}
/**
+4 -4
View File
@@ -12,7 +12,7 @@ import { flattenUniq, validateTypes } from '../util';
import { MetadataCall } from './Calls';
import { MetadataEvent } from './Events';
import { MetadataStorage } from './Storage';
import { StorageFunctionMetadata } from './Storage';
/**
* @name MetadataModule
@@ -24,7 +24,7 @@ export class MetadataModule extends Struct {
super({
name: Text,
prefix: Text,
storage: Option.with(Vector.with(MetadataStorage)),
storage: Option.with(Vector.with(StorageFunctionMetadata)),
calls: Option.with(Vector.with(MetadataCall)),
events: Option.with(Vector.with(MetadataEvent))
}, value);
@@ -61,8 +61,8 @@ export class MetadataModule extends Struct {
/**
* @description the associated module storage
*/
get storage (): Option<Vector<MetadataStorage>> {
return this.get('storage') as Option<Vector<MetadataStorage>>;
get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
+15 -160
View File
@@ -2,164 +2,19 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import EnumType from '../../codec/EnumType';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Bytes from '../../primitive/Bytes';
import Null from '../../primitive/Null';
import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
import {
MapType,
PlainType,
StorageFunctionModifier,
StorageFunctionType,
StorageFunctionMetadata
} from '../v0/Storage';
export class Default extends Null {}
export class Optional extends Null {}
export class MetadataStorageModifier extends EnumType<Optional | Default> {
constructor (value?: any, index?: number) {
super({
Optional,
Default
}, value, index);
}
/**
* @description `true` if the storage entry is optional
*/
get isOptional (): boolean {
return this.toNumber() === 0;
}
toJSON (): any {
return this.toString();
}
}
export class MapType extends Struct {
private _isLinked = false;
constructor (value?: any) {
super({
key: Type,
value: Type
}, value);
if (value && value.isLinked) {
this._isLinked = true;
}
}
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
return this.get('value') as Type;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
return this._isLinked;
}
}
export class PlainType extends Type {
}
export class MetadataStorageType extends EnumType<PlainType | MapType> {
constructor (value?: any, index?: number) {
super({
PlainType,
MapType
}, value, index);
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
return this.value as MapType;
}
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
return this.value as PlainType;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
return this.isMap
? this.asMap.value.toString()
: this.asType.toString();
}
}
/**
* @name MetadataModule
* @description
* The definition of a storage function
*/
export class MetadataStorage extends Struct {
constructor (value?: any) {
super({
name: Text,
modifier: MetadataStorageModifier,
type: MetadataStorageType,
fallback: Bytes,
docs: Vector.with(Text)
}, value);
}
/**
* @description The [[Text]] documentation
*/
get docs (): Vector<Text> {
return this.get('docs') as Vector<Text>;
}
/**
* @description The [[Bytes]] fallback default
*/
get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[MetadataArgument]] for arguments
*/
get modifier (): MetadataStorageModifier {
return this.get('modifier') as MetadataStorageModifier;
}
/**
* @description The call name
*/
get name (): Text {
return this.get('name') as Text;
}
/**
* @description The [[MetadataStorageType]]
*/
get type (): MetadataStorageType {
return this.get('type') as MetadataStorageType;
}
}
// Re-export classes that haven't changed between V0 and V1
export {
MapType,
PlainType,
StorageFunctionModifier,
StorageFunctionType,
StorageFunctionMetadata
};
File diff suppressed because it is too large Load Diff
+9 -8
View File
@@ -4,7 +4,8 @@
import { OuterDispatchCall, OuterDispatchMetadata } from '../v0/Calls';
import { EventMetadata, OuterEventMetadata, OuterEventMetadataEvent } from '../v0/Events';
import { CallMetadata, FunctionMetadata, RuntimeModuleMetadata, ModuleMetadata, StorageFunctionMetadata, StorageMetadata, StorageFunctionType } from '../v0/Modules';
import { CallMetadata, FunctionMetadata, RuntimeModuleMetadata, ModuleMetadata } from '../v0/Modules';
import { StorageFunctionMetadata, StorageMetadata, StorageFunctionType } from '../v0/Storage';
import MetadataV0 from '../v0/Metadata';
import MetadataV1, { MetadataModuleV1 } from '.';
@@ -16,13 +17,13 @@ function storageV0 (mod: MetadataModuleV1): StorageMetadata | null {
return new StorageMetadata({
prefix: mod.prefix,
functions: mod.storage.unwrap().map(({ docs, fallback, modifier, name, type }) =>
functions: mod.storage.unwrap().map(({ documentation, fallback, modifier, name, type }) =>
new StorageFunctionMetadata({
name,
modifier: modifier.toNumber(),
type: new StorageFunctionType(type),
default: fallback,
documentation: docs
fallback,
documentation
})
)
});
@@ -35,12 +36,12 @@ function moduleV0 (mod: MetadataModuleV1): ModuleMetadata {
name: 'Call',
functions: mod.calls.isNone
? []
: mod.calls.unwrap().map(({ args, docs, name }, id) =>
: mod.calls.unwrap().map(({ args, documentation, name }, id) =>
new FunctionMetadata({
id,
name,
arguments: args,
documentation: docs
documentation
})
)
})
@@ -81,11 +82,11 @@ function outerEventV0 (v1: MetadataV1): OuterEventMetadata {
.map((mod) =>
new OuterEventMetadataEvent([
mod.name,
mod.events.unwrap().map(({ args, docs, name }) =>
mod.events.unwrap().map(({ args, documentation, name }) =>
new EventMetadata({
name,
arguments: args,
documentation: docs
documentation
})
)
])
+4 -4
View File
@@ -12,7 +12,7 @@ import { flattenUniq, validateTypes } from '../util';
import { MetadataCall } from '../v1/Calls';
import { MetadataEvent } from '../v1/Events';
import { MetadataStorage } from './Storage';
import { StorageFunctionMetadata } from './Storage';
/**
* @name MetadataModule
@@ -24,7 +24,7 @@ export class MetadataModule extends Struct {
super({
name: Text,
prefix: Text,
storage: Option.with(Vector.with(MetadataStorage)),
storage: Option.with(Vector.with(StorageFunctionMetadata)),
calls: Option.with(Vector.with(MetadataCall)),
events: Option.with(Vector.with(MetadataEvent))
}, value);
@@ -61,8 +61,8 @@ export class MetadataModule extends Struct {
/**
* @description the associated module storage
*/
get storage (): Option<Vector<MetadataStorage>> {
return this.get('storage') as Option<Vector<MetadataStorage>>;
get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
+44 -20
View File
@@ -2,19 +2,22 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AnyNumber } from '../../types';
import EnumType from '../../codec/EnumType';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Bool from '../../primitive/Bool';
import Bytes from '../../primitive/Bytes';
import Null from '../../primitive/Null';
import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
import { MetadataStorageModifier } from '../v1/Storage';
import { PlainType, StorageFunctionModifier } from '../v1/Storage';
export class Default extends Null {}
export class Optional extends Null {}
// Re-export classes that haven't changed between V1 and V2
export {
PlainType,
StorageFunctionModifier
};
export class MapType extends Struct {
constructor (value?: any) {
@@ -47,10 +50,7 @@ export class MapType extends Struct {
}
}
export class PlainType extends Type {
}
export class MetadataStorageType extends EnumType<PlainType | MapType> {
export class StorageFunctionType extends EnumType<PlainType | MapType> {
constructor (value?: any, index?: number) {
super({
PlainType,
@@ -89,27 +89,51 @@ export class MetadataStorageType extends EnumType<PlainType | MapType> {
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
/**
* @name MetadataModule
* @description
* The definition of a storage function
*/
export class MetadataStorage extends Struct {
constructor (value?: any) {
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: MetadataStorageModifier,
type: MetadataStorageType,
modifier: StorageFunctionModifier,
type: StorageFunctionType,
fallback: Bytes,
docs: Vector.with(Text)
documentation: Vector.with(Text)
}, value);
}
/**
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
return this.fallback;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.get('docs') as Vector<Text>;
return this.documentation;
}
/**
@@ -122,8 +146,8 @@ export class MetadataStorage extends Struct {
/**
* @description The [[MetadataArgument]] for arguments
*/
get modifier (): MetadataStorageModifier {
return this.get('modifier') as MetadataStorageModifier;
get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
@@ -134,9 +158,9 @@ export class MetadataStorage extends Struct {
}
/**
* @description The [[MetadataStorageType]]
* @description The [[StorageFunctionType]]
*/
get type (): MetadataStorageType {
return this.get('type') as MetadataStorageType;
get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -12,7 +12,7 @@ import { flattenUniq, validateTypes } from '../util';
import { MetadataCall } from '../v1/Calls';
import { MetadataEvent } from '../v1/Events';
import { MetadataStorage } from './Storage';
import { StorageFunctionMetadata } from './Storage';
/**
* @name MetadataModule
@@ -24,7 +24,7 @@ export class MetadataModule extends Struct {
super({
name: Text,
prefix: Text,
storage: Option.with(Vector.with(MetadataStorage)),
storage: Option.with(Vector.with(StorageFunctionMetadata)),
calls: Option.with(Vector.with(MetadataCall)),
events: Option.with(Vector.with(MetadataEvent))
}, value);
@@ -61,8 +61,8 @@ export class MetadataModule extends Struct {
/**
* @description the associated module storage
*/
get storage (): Option<Vector<MetadataStorage>> {
return this.get('storage') as Option<Vector<MetadataStorage>>;
get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
+55 -19
View File
@@ -2,13 +2,25 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AnyNumber } from '../../types';
import EnumType from '../../codec/EnumType';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Bytes from '../../primitive/Bytes';
import Text from '../../primitive/Text';
import { MetadataStorageModifier } from '../v1/Storage';
import { MapType, PlainType } from '../v2/Storage';
import {
MapType,
PlainType,
StorageFunctionModifier
} from '../v2/Storage';
// Re-export classes that haven't changed between V2 and V3
export {
MapType,
PlainType,
StorageFunctionModifier
};
export class DoubleMapType extends Struct {
constructor (value?: any) {
@@ -16,7 +28,7 @@ export class DoubleMapType extends Struct {
key1: Text,
key2: Text,
value: Text,
keyHasher: Text
key2Hasher: Text
}, value);
}
@@ -35,10 +47,10 @@ export class DoubleMapType extends Struct {
}
/**
* @description The mapped key as [[Text]]
* @description The hashing algorithm used to hash key2, as [[Text]]
*/
get keyHasher (): Text {
return this.get('keyHasher') as Text;
get key2Hasher (): Text {
return this.get('key2Hasher') as Text;
}
/**
@@ -49,7 +61,7 @@ export class DoubleMapType extends Struct {
}
}
export class MetadataStorageType extends EnumType<PlainType | MapType | DoubleMapType> {
export class StorageFunctionType extends EnumType<PlainType | MapType | DoubleMapType> {
constructor (value?: any, index?: number) {
super({
PlainType,
@@ -107,27 +119,51 @@ export class MetadataStorageType extends EnumType<PlainType | MapType | DoubleMa
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
/**
* @name MetadataModule
* @name StorageFunctionMetadata
* @description
* The definition of a storage function
*/
export class MetadataStorage extends Struct {
constructor (value?: any) {
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: MetadataStorageModifier,
type: MetadataStorageType,
modifier: StorageFunctionModifier,
type: StorageFunctionType,
fallback: Bytes,
docs: Vector.with(Text)
documentation: Vector.with(Text)
}, value);
}
/**
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
return this.fallback;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.get('docs') as Vector<Text>;
return this.documentation;
}
/**
@@ -140,8 +176,8 @@ export class MetadataStorage extends Struct {
/**
* @description The [[MetadataArgument]] for arguments
*/
get modifier (): MetadataStorageModifier {
return this.get('modifier') as MetadataStorageModifier;
get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
@@ -152,9 +188,9 @@ export class MetadataStorage extends Struct {
}
/**
* @description The [[MetadataStorageType]]
* @description The [[StorageFunctionType]]
*/
get type (): MetadataStorageType {
return this.get('type') as MetadataStorageType;
get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,22 @@
// 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 Metadata from '../Metadata';
import latestParsed from './latest.substrate.v4.json';
import rpcData from './static';
describe('MetadataV4', () => {
const metadata = new Metadata(rpcData);
it('decodes latest properly', () => {
const str = JSON.stringify(metadata.toJSON());
console.error(str);
console.error(metadata.getUniqTypes(true));
expect(metadata.version).toBe(4);
expect(metadata.asV4.modules.length).not.toBe(0);
expect(str).toEqual(JSON.stringify(latestParsed));
});
});
+130
View File
@@ -0,0 +1,130 @@
// 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 { MetadataInterface } from '../types';
import Option from '../../codec/Option';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Text from '../../primitive/Text';
import { flattenUniq, validateTypes } from '../util';
import { MetadataCall } from '../v1/Calls';
import { MetadataEvent } from '../v1/Events';
import { StorageFunctionMetadata } from './Storage';
/**
* @name MetadataModule
* @description
* The definition of a module in the system
*/
export class MetadataModule extends Struct {
constructor (value?: any) {
super({
name: Text,
prefix: Text,
storage: Option.with(Vector.with(StorageFunctionMetadata)),
calls: Option.with(Vector.with(MetadataCall)),
events: Option.with(Vector.with(MetadataEvent))
}, value);
}
/**
* @description the module calls
*/
get calls (): Option<Vector<MetadataCall>> {
return this.get('calls') as Option<Vector<MetadataCall>>;
}
/**
* @description the module events
*/
get events (): Option<Vector<MetadataEvent>> {
return this.get('events') as Option<Vector<MetadataEvent>>;
}
/**
* @description the module name
*/
get name (): Text {
return this.get('name') as Text;
}
/**
* @description the module prefix
*/
get prefix (): Text {
return this.get('prefix') as Text;
}
/**
* @description the associated module storage
*/
get storage (): Option<Vector<StorageFunctionMetadata>> {
return this.get('storage') as Option<Vector<StorageFunctionMetadata>>;
}
}
/**
* @name MetadataV4
* @description
* The runtime metadata as a decoded structure
*/
export default class MetadataV4 extends Struct implements MetadataInterface {
constructor (value?: any) {
super({
modules: Vector.with(MetadataModule)
}, value);
}
/**
* @description The associated modules for this structure
*/
get modules (): Vector<MetadataModule> {
return this.get('modules') as Vector<MetadataModule>;
}
private get callNames () {
return this.modules.map((mod) =>
mod.calls.isNone
? []
: mod.calls.unwrap().map((fn) =>
fn.args.map((arg) => arg.type.toString())
)
);
}
private get eventNames () {
return this.modules.map((mod) =>
mod.events.isNone
? []
: mod.events.unwrap().map((event) =>
event.args.map((arg) => arg.toString())
)
);
}
private get storageNames () {
return this.modules.map((mod) =>
mod.storage.isNone
? []
: mod.storage.unwrap().map((fn) =>
fn.type.isMap
? [fn.type.asMap.key.toString(), fn.type.asMap.value.toString()]
: [fn.type.asType.toString()]
)
);
}
/**
* @description Helper to retrieve a list of all type that are found, sorted and de-deuplicated
*/
getUniqTypes (throwError: boolean): Array<string> {
const types = flattenUniq([this.callNames, this.eventNames, this.storageNames]);
validateTypes(types, throwError);
return types;
}
}
+290
View File
@@ -0,0 +1,290 @@
// 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 { AnyNumber } from '../../types';
import Enum from '../../codec/Enum';
import EnumType from '../../codec/EnumType';
import Struct from '../../codec/Struct';
import Vector from '../../codec/Vector';
import Bool from '../../primitive/Bool';
import Bytes from '../../primitive/Bytes';
import Text from '../../primitive/Text';
import Type from '../../primitive/Type';
import {
PlainType,
StorageFunctionModifier
} from '../v3/Storage';
// Re-export classes that haven't changed between V3 and V4
export {
PlainType,
StorageFunctionModifier
};
export class StorageHasher extends Enum {
constructor (value?: any) {
super(['Blake2_128', 'Blake2_256', 'Twox128', 'Twox256', 'Twox128Concat'], value);
}
/**
* @description Is the enum Blake2_128?
*/
get isBlake2128 (): boolean {
return this.toNumber() === 0;
}
/**
* @description Is the enum Blake2_256?
*/
get isBlake2256 (): boolean {
return this.toNumber() === 1;
}
/**
* @description Is the enum Twox128?
*/
get isTwox128 (): boolean {
return this.toNumber() === 2;
}
/**
* @description Is the enum Twox256?
*/
get isTwox256 (): boolean {
return this.toNumber() === 3;
}
/**
* @description Is the enum isTwox128Concat?
*/
get isTwox128Concat (): boolean {
return this.toNumber() === 4;
}
toJSON (): any {
// This looks prettier in the generated JSON
return this.toString();
}
}
export class MapType extends Struct {
constructor (value?: any) {
super({
hasher: StorageHasher,
key: Type,
value: Type,
isLinked: Bool
}, value);
}
/**
* @description The hash algorithm used to hash keys, as [[StorageHasher]]
*/
get hasher (): StorageHasher {
return this.get('hasher') as StorageHasher;
}
/**
* @description Is this an enumerable linked map
*/
get isLinked (): boolean {
return (this.get('isLinked') as Bool).valueOf();
}
/**
* @description The mapped key as [[Type]]
*/
get key (): Type {
return this.get('key') as Type;
}
/**
* @description The mapped value as [[Type]]
*/
get value (): Type {
return this.get('value') as Type;
}
}
export class DoubleMapType extends Struct {
constructor (value?: any) {
super({
hasher: StorageHasher,
key1: Text,
key2: Text,
value: Text,
key2Hasher: Text
}, value);
}
/**
* @description The hashing algorithm used to hash keys, as [[Text]]
*/
get hasher (): Text {
return this.get('hasher') as Text;
}
/**
* @description The mapped key as [[Text]]
*/
get key1 (): Text {
return this.get('key1') as Text;
}
/**
* @description The mapped key as [[Text]]
*/
get key2 (): Text {
return this.get('key2') as Text;
}
/**
* @description The hashing algorithm used to hash key2, as [[Text]]
*/
get key2Hasher (): Text {
return this.get('key2Hasher') as Text;
}
/**
* @description The mapped key as [[Text]]
*/
get value (): Text {
return this.get('value') as Text;
}
}
export class StorageFunctionType extends EnumType<PlainType | MapType | DoubleMapType> {
constructor (value?: any, index?: number) {
super({
PlainType,
MapType,
DoubleMapType
}, value, index);
}
/**
* @description The value as a mapped value
*/
get asDoubleMap (): DoubleMapType {
return this.value as DoubleMapType;
}
/**
* @description The value as a mapped value
*/
get asMap (): MapType {
return this.value as MapType;
}
/**
* @description The value as a [[Type]] value
*/
get asType (): PlainType {
return this.value as PlainType;
}
/**
* @description `true` if the storage entry is a doublemap
*/
get isDoubleMap (): boolean {
return this.toNumber() === 2;
}
/**
* @description `true` if the storage entry is a map
*/
get isMap (): boolean {
return this.toNumber() === 1;
}
/**
* @description Returns the string representation of the value
*/
toString (): string {
if (this.isDoubleMap) {
return this.asDoubleMap.toString();
}
return this.isMap
? this.asMap.value.toString()
: this.asType.toString();
}
}
export type StorageFunctionMetadataValue = {
name: string | Text,
modifier: StorageFunctionModifier | AnyNumber,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector<Text> | Array<string>
};
/**
* @name StorageFunctionMetadata
* @description
* The definition of a storage function
*/
export class StorageFunctionMetadata extends Struct {
constructor (value?: StorageFunctionMetadataValue | Uint8Array) {
super({
name: Text,
modifier: StorageFunctionModifier,
type: StorageFunctionType,
fallback: Bytes,
documentation: Vector.with(Text)
}, value);
}
/**
* @description The default value of the storage function
* @deprecated Use `.fallback` instead.
*/
get default (): Bytes {
return this.fallback;
}
/**
* @description The default value of the storage function
*/
get fallback (): Bytes {
return this.get('fallback') as Bytes;
}
/**
* @description The [[Text]] documentation
*/
get documentation (): Vector<Text> {
return this.get('documentation') as Vector<Text>;
}
/**
* @description The [[Text]] documentation
* @deprecated Use `.documentation` instead.
*/
get docs (): Vector<Text> {
return this.documentation;
}
/**
* @description The key name
*/
get name (): Text {
return this.get('name') as Text;
}
/**
* @description The modifier
*/
get modifier (): StorageFunctionModifier {
return this.get('modifier') as StorageFunctionModifier;
}
/**
* @description The [[StorageFunctionType]]
*/
get type (): StorageFunctionType {
return this.get('type') as StorageFunctionType;
}
}
+11
View File
@@ -0,0 +1,11 @@
// 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 { default as MetadataV4, MetadataModule as MetadataModuleV4 } from './Metadata';
export default MetadataV4;
export {
MetadataModuleV4
};
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
// 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 MetadataV3 from '../v3/Metadata';
import MetadataV4 from '.';
export default function toV3 (v4: MetadataV4): MetadataV3 {
return new MetadataV3(v4);
}
+6 -5
View File
@@ -7,11 +7,12 @@ import { AnyU8a } from '../types';
import { isFunction } from '@polkadot/util';
import Bytes from './Bytes';
import { StorageFunctionMetadata } from '../Metadata/v0/Modules';
import { StorageFunctionMetadata as MetaV0 } from '../Metadata/v0/Storage';
import { StorageFunctionMetadata as MetaV4 } from '../Metadata/v4/Storage';
export interface StorageFunction {
(arg?: any): Uint8Array;
meta: StorageFunctionMetadata;
meta: MetaV0 | MetaV4;
method: string;
section: string;
toJSON: () => any;
@@ -25,7 +26,7 @@ export interface StorageFunction {
* constructed by passing in a raw key or a StorageFunction with (optional) arguments.
*/
export default class StorageKey extends Bytes {
private _meta: StorageFunctionMetadata | null;
private _meta: MetaV0 | MetaV4 | null;
private _outputType: string | null;
constructor (value: AnyU8a | StorageKey | StorageFunction | [StorageFunction, any]) {
@@ -49,7 +50,7 @@ export default class StorageKey extends Bytes {
return value as Uint8Array;
}
static getMeta (value: StorageKey | StorageFunction | [StorageFunction, any]): StorageFunctionMetadata | null {
static getMeta (value: StorageKey | StorageFunction | [StorageFunction, any]): MetaV0 | MetaV4 | null {
if (value instanceof StorageKey) {
return value.meta;
} else if (isFunction(value)) {
@@ -80,7 +81,7 @@ export default class StorageKey extends Bytes {
/**
* @description The metadata or `null` when not available
*/
get meta (): StorageFunctionMetadata | null {
get meta (): MetaV0 | MetaV4 | null {
return this._meta;
}
@@ -9,7 +9,7 @@ _These are keys that are always available to the runtime implementation_
- **summary**: Number of authorities.
▸ **authorityPrefix**(): `u32`
- **summary**: Prefix under which authorities are storied.
- **summary**: Prefix under which authorities are stored.
▸ **changesTrieConfig**(): `u32`
- **summary**: Changes trie configuration is stored under this key.