Rework asLatest update (#2802)
* Revert "[CI Skip] release/beta 2.4.2-10" This reverts commit5cb1c2d33a. * Revert "Use asLatest in metadata extraction (#2800)" This reverts commit600666de1c. * Bumps * Expansion * Flatten * Metadata class imports * Cleanup Decorate exports * Move Metadata to top-level * Swap logger on ABI * Adjust imports * Cleanups * Updates
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeDef, TypeDefInfo } from '@polkadot/types/types';
|
||||
|
||||
import { getTypeDef } from '@polkadot/types/create';
|
||||
|
||||
type Extracted = string | Extracted[];
|
||||
|
||||
/** @internal */
|
||||
export default function extractTypes (types: string[]): Extracted[] {
|
||||
return types.map((type): Extracted => {
|
||||
const decoded = getTypeDef(type);
|
||||
|
||||
switch (decoded.info) {
|
||||
case TypeDefInfo.Plain:
|
||||
return decoded.type;
|
||||
|
||||
case TypeDefInfo.BTreeSet:
|
||||
case TypeDefInfo.Compact:
|
||||
case TypeDefInfo.Option:
|
||||
case TypeDefInfo.Vec:
|
||||
case TypeDefInfo.VecFixed:
|
||||
return extractTypes([(decoded.sub as TypeDef).type]);
|
||||
|
||||
case TypeDefInfo.BTreeMap:
|
||||
case TypeDefInfo.HashMap:
|
||||
case TypeDefInfo.Result:
|
||||
case TypeDefInfo.Tuple:
|
||||
return extractTypes((decoded.sub as TypeDef[]).map(({ type }) => type));
|
||||
|
||||
default:
|
||||
throw new Error(`Unhandled: Unable to create and validate type from ${type}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
type Types = string | Types[];
|
||||
|
||||
/** @internal */
|
||||
export default function flattenUniq (list: Types[]): string[] {
|
||||
const flat = list.reduce((result: string[], entry): string[] => {
|
||||
return result.concat(
|
||||
Array.isArray(entry)
|
||||
? flattenUniq(entry)
|
||||
: entry
|
||||
);
|
||||
}, []);
|
||||
|
||||
return [...new Set(flat)]
|
||||
.filter((value: string) => value)
|
||||
.sort();
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Codec, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { Option, Vec } from '@polkadot/types/codec';
|
||||
import { Text, Type } from '@polkadot/types/primitive';
|
||||
|
||||
import flattenUniq from './flattenUniq';
|
||||
import validateTypes from './validateTypes';
|
||||
|
||||
type Arg = { type: Type } & Codec;
|
||||
|
||||
type Item = {
|
||||
type: {
|
||||
isDoubleMap?: boolean;
|
||||
isMap: boolean;
|
||||
isPlain: boolean;
|
||||
asDoubleMap?: {
|
||||
key1: Text;
|
||||
key2: Text;
|
||||
value: Text;
|
||||
};
|
||||
asMap: {
|
||||
key: Text;
|
||||
value: Text;
|
||||
};
|
||||
asPlain: Text;
|
||||
};
|
||||
} & Codec;
|
||||
|
||||
type Storage = Option<Vec<Item> | {
|
||||
// v0
|
||||
functions?: Vec<Item>;
|
||||
// V7+
|
||||
items?: Vec<Item>;
|
||||
} & Codec>;
|
||||
|
||||
type Call = { args: Vec<Arg> } & Codec;
|
||||
|
||||
type Calls = Option<Vec<Call>>;
|
||||
|
||||
type Event = { args: Vec<Type> } & Codec;
|
||||
|
||||
type Events = Option<Vec<Event>>;
|
||||
|
||||
type Module = {
|
||||
// V0
|
||||
module?: {
|
||||
call: {
|
||||
functions: Vec<Call>;
|
||||
};
|
||||
};
|
||||
// V1+
|
||||
calls?: Calls;
|
||||
// V6+
|
||||
constants?: Vec<{ type: Text } & Codec>;
|
||||
events?: Events;
|
||||
storage?: Storage;
|
||||
} & Codec;
|
||||
|
||||
interface ExtractionMetadata {
|
||||
modules: Vec<Module>;
|
||||
|
||||
// V0
|
||||
outerEvent?: {
|
||||
events: Vec<[Text, Vec<Event>] & Codec>;
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function unwrapCalls (mod: Module): Call[] {
|
||||
return mod.calls
|
||||
? mod.calls.unwrapOr([])
|
||||
// V0
|
||||
: mod.module
|
||||
? mod.module.call.functions
|
||||
: [];
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function getCallNames ({ modules }: ExtractionMetadata): string[][][] {
|
||||
return modules.map((mod): string[][] =>
|
||||
unwrapCalls(mod).map(({ args }): string[] =>
|
||||
args.map((arg): string =>
|
||||
arg.type.toString()
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function getConstantNames ({ modules }: ExtractionMetadata): string[][] {
|
||||
return modules.map(({ constants }): string[] =>
|
||||
constants
|
||||
? constants.map((constant): string =>
|
||||
constant.type.toString()
|
||||
)
|
||||
: []
|
||||
);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function unwrapEvents (events?: Events): Event[] {
|
||||
if (!events) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return events.unwrapOr([]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function getEventNames ({ modules, outerEvent }: ExtractionMetadata): string[][][] {
|
||||
const mapArg = ({ args }: Event): string[] =>
|
||||
args.map((arg): string =>
|
||||
arg.toString()
|
||||
);
|
||||
|
||||
// V0
|
||||
if (outerEvent) {
|
||||
return outerEvent.events.map(([, events]): string[][] =>
|
||||
events.map(mapArg)
|
||||
);
|
||||
}
|
||||
|
||||
// V1+
|
||||
return modules.map(({ events }): string[][] =>
|
||||
unwrapEvents(events).map(mapArg)
|
||||
);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function unwrapStorage (storage?: Storage): Item[] {
|
||||
if (!storage) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = storage.unwrapOr([]);
|
||||
|
||||
return Array.isArray(data)
|
||||
? data
|
||||
: (data.items || data.functions) as Item[];
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function getStorageNames ({ modules }: ExtractionMetadata): string[][][] {
|
||||
return modules.map(({ storage }): string[][] =>
|
||||
unwrapStorage(storage).map(({ type }): string[] => {
|
||||
if (type.isDoubleMap && type.asDoubleMap) {
|
||||
return [
|
||||
type.asDoubleMap.key1.toString(),
|
||||
type.asDoubleMap.key2.toString(),
|
||||
type.asDoubleMap.value.toString()
|
||||
];
|
||||
} else if (type.isMap) {
|
||||
return [
|
||||
type.asMap.key.toString(),
|
||||
type.asMap.value.toString()
|
||||
];
|
||||
} else {
|
||||
return [
|
||||
type.asPlain.toString()
|
||||
];
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export default function getUniqTypes (registry: Registry, meta: ExtractionMetadata, throwError: boolean): string[] {
|
||||
const types = flattenUniq([
|
||||
getCallNames(meta),
|
||||
getConstantNames(meta),
|
||||
getEventNames(meta),
|
||||
getStorageNames(meta)
|
||||
]);
|
||||
|
||||
validateTypes(registry, types, throwError);
|
||||
|
||||
return types;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
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,77 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Codec, Registry } from '@polkadot/types/types';
|
||||
import { MetadataInterface } from '../types';
|
||||
|
||||
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
|
||||
|
||||
import getUniqTypes from './getUniqTypes';
|
||||
import Metadata from '..';
|
||||
|
||||
/** @internal */
|
||||
export function decodeLatestSubstrate<Modules extends Codec> (registry: Registry, version: number, rpcData: string, staticSubstrate: Record<string, unknown>): void {
|
||||
it('decodes latest substrate properly', (): void => {
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
|
||||
registry.setMetadata(metadata);
|
||||
|
||||
try {
|
||||
expect(metadata.version).toBe(version);
|
||||
expect((metadata[`asV${version}` as keyof Metadata] as unknown as MetadataInterface<Modules>).modules.length).not.toBe(0);
|
||||
expect(metadata.toJSON()).toEqual(staticSubstrate);
|
||||
} catch (error) {
|
||||
console.error(JSON.stringify(metadata.toJSON()));
|
||||
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function toLatest<Modules extends Codec> (registry: Registry, version: number, rpcData: string, withThrow = true): void {
|
||||
it(`converts v${version} to latest`, (): void => {
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
|
||||
registry.setMetadata(metadata);
|
||||
|
||||
const metadataInit = metadata[`asV${version}` as keyof Metadata];
|
||||
const metadataLatest = metadata.asLatest;
|
||||
|
||||
expect(
|
||||
getUniqTypes(registry, metadataInit as unknown as MetadataInterface<Modules>, withThrow)
|
||||
).toEqual(
|
||||
getUniqTypes(registry, metadataLatest, withThrow)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function defaultValues (registry: Registry, rpcData: string, withThrow = true): void {
|
||||
describe('storage with default values', (): void => {
|
||||
const metadata = new Metadata(registry, rpcData);
|
||||
|
||||
metadata.asLatest.modules.filter(({ storage }): boolean => storage.isSome).forEach((mod): void => {
|
||||
mod.storage.unwrap().items.forEach(({ fallback, name, type }): void => {
|
||||
const inner = unwrapStorageType(type);
|
||||
const location = `${mod.name.toString()}.${name.toString()}: ${inner}`;
|
||||
|
||||
it(`creates default types for ${location}`, (): void => {
|
||||
expect((): void => {
|
||||
try {
|
||||
registry.createType(inner, fallback);
|
||||
} catch (error) {
|
||||
const message = `${location}:: ${(error as Error).message}`;
|
||||
|
||||
if (withThrow) {
|
||||
throw new Error(message);
|
||||
} else {
|
||||
console.warn(message);
|
||||
}
|
||||
}
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types';
|
||||
|
||||
import staticData from '../static';
|
||||
import Metadata from '..';
|
||||
|
||||
describe('toCallsOnly', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
it('creates a calls-only version of the metadata', (): void => {
|
||||
const stripped = new Metadata(registry, staticData).asCallsOnly;
|
||||
|
||||
try {
|
||||
expect(stripped).toBeDefined();
|
||||
} catch (error) {
|
||||
console.error(JSON.stringify(stripped));
|
||||
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
it('can serialize from the input', (): void => {
|
||||
const s1 = new Metadata(registry, staticData).asCallsOnly.toU8a();
|
||||
const s2 = new Metadata(registry, s1).asCallsOnly.toU8a();
|
||||
|
||||
expect(s1).toEqual(s2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { FunctionMetadataLatest, MetadataLatest } from '@polkadot/types/interfaces/metadata';
|
||||
import { AnyJson, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { Option, Text, Vec, u8 } from '@polkadot/types';
|
||||
|
||||
interface ModuleMetadataTrimmed {
|
||||
calls: Option<Vec<FunctionMetadataLatest>>;
|
||||
index: u8;
|
||||
name: Text;
|
||||
}
|
||||
|
||||
function trimDocs (documentation: Vec<Text>): string[] {
|
||||
const strings = documentation.map((doc) => doc.toString().trim());
|
||||
const firstEmpty = strings.findIndex((doc) => !doc.length);
|
||||
|
||||
return firstEmpty === -1
|
||||
? strings
|
||||
: strings.slice(0, firstEmpty);
|
||||
}
|
||||
|
||||
function mapCalls (registry: Registry, _calls: Option<Vec<FunctionMetadataLatest>>): Option<Vec<FunctionMetadataLatest>> {
|
||||
const calls = _calls.unwrapOr(null);
|
||||
|
||||
return registry.createType(
|
||||
'Option<Vec<FunctionMetadataLatest>>' as any,
|
||||
calls
|
||||
? calls.map(({ args, documentation, name }) =>
|
||||
registry.createType('FunctionMetadataLatest', {
|
||||
args,
|
||||
documentation: trimDocs(documentation),
|
||||
name
|
||||
})
|
||||
)
|
||||
: null
|
||||
) as Option<Vec<FunctionMetadataLatest>>;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export default function toCallsOnly (registry: Registry, { extrinsic, modules }: MetadataLatest): AnyJson {
|
||||
return registry.createType('MetadataLatest', {
|
||||
extrinsic,
|
||||
modules: modules.map(({ calls, index, name }): ModuleMetadataTrimmed => ({
|
||||
calls: mapCalls(registry, calls),
|
||||
index,
|
||||
name
|
||||
}))
|
||||
}).toJSON();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Copyright 2017-2020 @polkadot/metadata authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { logger } from '@polkadot/util';
|
||||
|
||||
import extractTypes from './extractTypes';
|
||||
import flattenUniq from './flattenUniq';
|
||||
|
||||
const l = logger('metadata');
|
||||
|
||||
/** @internal */
|
||||
export default function validateTypes (registry: Registry, types: string[], throwError: boolean): void {
|
||||
const missing = flattenUniq(extractTypes(types)).filter((type) => !registry.hasType(type));
|
||||
|
||||
if (missing.length !== 0) {
|
||||
const message = `Unknown types found, no types for ${missing.join(', ')}`;
|
||||
|
||||
if (throwError) {
|
||||
throw new Error(message);
|
||||
} else {
|
||||
l.warn(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user