Format similar types transparently (#2788)
* Format similar types transparently * Adjust test expectations * Remove console.error * Adjust getTypeDef for check-only
This commit is contained in:
@@ -153,11 +153,11 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
/**
|
||||
* Get offchain local storage under given key and prefix
|
||||
**/
|
||||
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED'|'PERSISTENT'|'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
/**
|
||||
* Set offchain local storage under given key and prefix
|
||||
**/
|
||||
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED'|'PERSISTENT'|'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
|
||||
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
|
||||
};
|
||||
payment: {
|
||||
/**
|
||||
|
||||
@@ -391,7 +391,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* Weight: `O(R)` where R is the number of referendums the voter delegating to has
|
||||
* voted on. Weight is charged as if maximum votes.
|
||||
**/
|
||||
delegate: AugmentedSubmittable<(to: AccountId | string | Uint8Array, conviction: Conviction | 'None'|'Locked1x'|'Locked2x'|'Locked3x'|'Locked4x'|'Locked5x'|'Locked6x' | number | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
delegate: AugmentedSubmittable<(to: AccountId | string | Uint8Array, conviction: Conviction | 'None' | 'Locked1x' | 'Locked2x' | 'Locked3x' | 'Locked4x' | 'Locked5x' | 'Locked6x' | number | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Schedule an emergency cancellation of a referendum. Cannot happen twice to the same
|
||||
* referendum.
|
||||
@@ -1392,7 +1392,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* Weight is a function of the number of proxies the user has (P).
|
||||
* # </weight>
|
||||
**/
|
||||
addProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
addProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Publish the hash of a proxy-call that will be made in the future.
|
||||
*
|
||||
@@ -1442,7 +1442,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* # </weight>
|
||||
* TODO: Might be over counting 1 read
|
||||
**/
|
||||
anonymous: AugmentedSubmittable<(proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array, index: u16 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
anonymous: AugmentedSubmittable<(proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array, index: u16 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Removes a previously spawned anonymous proxy.
|
||||
*
|
||||
@@ -1465,7 +1465,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* Weight is a function of the number of proxies the user has (P).
|
||||
* # </weight>
|
||||
**/
|
||||
killAnonymous: AugmentedSubmittable<(spawner: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, index: u16 | AnyNumber | Uint8Array, height: Compact<BlockNumber> | AnyNumber | Uint8Array, extIndex: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
killAnonymous: AugmentedSubmittable<(spawner: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, index: u16 | AnyNumber | Uint8Array, height: Compact<BlockNumber> | AnyNumber | Uint8Array, extIndex: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Dispatch the given `call` from an account that the sender is authorised for through
|
||||
* `add_proxy`.
|
||||
@@ -1568,7 +1568,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* Weight is a function of the number of proxies the user has (P).
|
||||
* # </weight>
|
||||
**/
|
||||
removeProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
removeProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
};
|
||||
recovery: {
|
||||
[key: string]: SubmittableExtrinsicFunction<ApiType>;
|
||||
@@ -1999,7 +1999,7 @@ declare module '@polkadot/api/types/submittable' {
|
||||
* Total Complexity: O(M + logM + B + X)
|
||||
* # </weight>
|
||||
**/
|
||||
judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid'|'Reject'|'Approve' | number | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid' | 'Reject' | 'Approve' | number | Uint8Array) => SubmittableExtrinsic<ApiType>>;
|
||||
/**
|
||||
* Allow suspension judgement origin to make judgement on a suspended member.
|
||||
*
|
||||
|
||||
@@ -19,7 +19,6 @@ import { ModuleTypes } from '../util/imports';
|
||||
// From a storage entry metadata, we return [args, returnType]
|
||||
/** @internal */
|
||||
function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
|
||||
const format = (type: string) => formatType(allDefs, type, imports);
|
||||
const outputType = unwrapStorageType(storageEntry.type, storageEntry.modifier.isOptional);
|
||||
|
||||
if (storageEntry.type.isPlain) {
|
||||
@@ -36,7 +35,7 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
|
||||
]);
|
||||
|
||||
return [
|
||||
`arg: ${similarTypes.map(format).join(' | ')}`,
|
||||
`arg: ${similarTypes.join(' | ')}`,
|
||||
formatType(allDefs, outputType, imports)
|
||||
];
|
||||
} else if (storageEntry.type.isDoubleMap) {
|
||||
@@ -50,8 +49,8 @@ function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registr
|
||||
storageEntry.type.asDoubleMap.value.toString()
|
||||
]);
|
||||
|
||||
const key1Types = similarTypes1.map(format).join(' | ');
|
||||
const key2Types = similarTypes2.map(format).join(' | ');
|
||||
const key1Types = similarTypes1.join(' | ');
|
||||
const key2Types = similarTypes2.join(' | ');
|
||||
|
||||
return [
|
||||
`key1: ${key1Types}, key2: ${key2Types}`,
|
||||
|
||||
@@ -17,7 +17,6 @@ const generateRpcTypesTemplate = Handlebars.compile(template);
|
||||
/** @internal */
|
||||
export function generateRpcTypes (importDefinitions: { [importPath: string]: Record<string, Definitions> }, dest: string): void {
|
||||
writeFile(dest, (): string => {
|
||||
const format = (type: string) => formatType(allDefs, type, imports);
|
||||
const registry = new TypeRegistry();
|
||||
const imports = createImports(importDefinitions);
|
||||
const definitions = imports.definitions as Record<string, Definitions>;
|
||||
@@ -72,7 +71,7 @@ export function generateRpcTypes (importDefinitions: { [importPath: string]: Rec
|
||||
|
||||
setImports(allDefs, imports, [param.type, ...similarTypes]);
|
||||
|
||||
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.map(format).join(' | ')}`;
|
||||
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
|
||||
});
|
||||
|
||||
type = formatType(allDefs, def.type, imports);
|
||||
|
||||
@@ -12,7 +12,7 @@ import { Text } from '@polkadot/types/primitive';
|
||||
import { TypeRegistry } from '@polkadot/types/create';
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import { createImports, compareName, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
|
||||
import { createImports, compareName, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
|
||||
|
||||
const MAPPED_NAMES: Record<string, string> = {
|
||||
new: 'updated'
|
||||
@@ -48,12 +48,11 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
|
||||
const params = args
|
||||
.map(({ name, type }) => {
|
||||
const typeStr = type.toString();
|
||||
const similarTypes = getSimilarTypes(registry, allDefs, typeStr, imports).map((type): string => formatType(allDefs, type, imports));
|
||||
const nameStr = mapName(name);
|
||||
const similarTypes = getSimilarTypes(registry, allDefs, typeStr, imports);
|
||||
|
||||
setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]);
|
||||
setImports(allDefs, imports, [typeStr, ...similarTypes]);
|
||||
|
||||
return `${nameStr}: ${similarTypes.join(' | ')}`;
|
||||
return `${mapName(name)}: ${similarTypes.join(' | ')}`;
|
||||
})
|
||||
.join(', ');
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2017-2020 @polkadot/typegen authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types/create';
|
||||
|
||||
import { getSimilarTypes } from './derived';
|
||||
|
||||
describe('getSimilarTypes', (): void => {
|
||||
let registry: TypeRegistry;
|
||||
|
||||
beforeAll((): void => {
|
||||
registry = new TypeRegistry();
|
||||
});
|
||||
|
||||
it('handles nested Tuples', (): void => {
|
||||
expect(getSimilarTypes(registry, {}, '(AccountId, (Balance, u32), u64)', {
|
||||
codecTypes: {},
|
||||
definitions: {},
|
||||
extrinsicTypes: {},
|
||||
genericTypes: {},
|
||||
ignoredTypes: [],
|
||||
localTypes: {},
|
||||
primitiveTypes: {},
|
||||
typeToModule: {},
|
||||
typesTypes: {}
|
||||
})).toEqual([
|
||||
'ITuple<[AccountId, ITuple<[Balance, u32]>, u64]>',
|
||||
'[AccountId | string | Uint8Array, ITuple<[Balance, u32]> | [Balance | AnyNumber | Uint8Array, u32 | AnyNumber | Uint8Array], u64 | AnyNumber | Uint8Array]'
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -26,7 +26,7 @@ import { formatType } from './formatting';
|
||||
import { setImports, ModuleTypes, TypeImports } from './imports';
|
||||
|
||||
function arrayToStrType (arr: string[]): string {
|
||||
return `${arr.map((c): string => `'${c}'`).join(' | ')}`;
|
||||
return `${arr.map((c) => `'${c}'`).join(' | ')}`;
|
||||
}
|
||||
|
||||
const voteConvictions = arrayToStrType(AllConvictions);
|
||||
@@ -75,7 +75,7 @@ export function getDerivedTypes (registry: Registry, definitions: Record<string,
|
||||
export function getSimilarTypes (registry: Registry, definitions: Record<string, ModuleTypes>, _type: string, imports: TypeImports): string[] {
|
||||
const typeParts = _type.split('::');
|
||||
const type = typeParts[typeParts.length - 1];
|
||||
const possibleTypes = [type];
|
||||
const possibleTypes = [formatType(definitions, type, imports)];
|
||||
|
||||
if (type === 'Extrinsic') {
|
||||
setImports(definitions, imports, ['IExtrinsic']);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2020 @polkadot/typegen authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { formatType } from './formatting';
|
||||
|
||||
describe('formatType', (): void => {
|
||||
it('handles nested Tuples', (): void => {
|
||||
expect(
|
||||
formatType({}, '(AccountId, (Balance, u32), u64)', {
|
||||
codecTypes: {},
|
||||
definitions: {},
|
||||
extrinsicTypes: {},
|
||||
genericTypes: {},
|
||||
ignoredTypes: [],
|
||||
localTypes: {},
|
||||
primitiveTypes: {},
|
||||
typeToModule: {},
|
||||
typesTypes: {}
|
||||
})
|
||||
).toEqual('ITuple<[AccountId, ITuple<[Balance, u32]>, u64]>');
|
||||
});
|
||||
});
|
||||
@@ -232,8 +232,7 @@ export function formatType (definitions: Record<string, ModuleTypes>, type: stri
|
||||
|
||||
// `(a,b)` gets transformed into `ITuple<[a, b]>`
|
||||
return formatTuple(
|
||||
((typeDef.sub as TypeDef[])
|
||||
.map((sub): string => formatType(definitions, sub.type, imports)))
|
||||
((typeDef.sub as TypeDef[]).map((sub) => formatType(definitions, sub.type, imports)))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ export function setImports (allDefs: Record<string, ModuleTypes>, imports: TypeI
|
||||
|
||||
// TypeDef.sub is a `TypeDef | TypeDef[]`
|
||||
if (Array.isArray(typeDef.sub)) {
|
||||
typeDef.sub.forEach((subType): void => setImports(allDefs, imports, [subType.type]));
|
||||
typeDef.sub.forEach((subType) => setImports(allDefs, imports, [subType.type]));
|
||||
} else if (typeDef.sub && (typeDef.info !== TypeDefInfo.VecFixed || typeDef.sub.type !== 'u8')) {
|
||||
// typeDef.sub is a TypeDef in this case
|
||||
setImports(allDefs, imports, [typeDef.sub.type]);
|
||||
|
||||
@@ -23,8 +23,6 @@ export default class Linkage<T extends Codec> extends Struct {
|
||||
// eslint-disable-next-line sort-keys
|
||||
next: Option.with(Type)
|
||||
}, value as string);
|
||||
|
||||
console.error([...this.entries()]);
|
||||
}
|
||||
|
||||
public static withKey<O extends Codec> (Type: Constructor | keyof InterfaceTypes): Constructor<Linkage<O>> {
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
// Copyright 2017-2020 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TypeDef, TypeDefInfo } from './types';
|
||||
import { TypeDefInfo } from './types';
|
||||
|
||||
import { TypeRegistry, getTypeDef } from '.';
|
||||
|
||||
describe('getTypeDef', (): void => {
|
||||
it('does not allow invalid tuples, end )', (): void => {
|
||||
expect(
|
||||
(): TypeDef => getTypeDef('(u64, u32')
|
||||
).toThrow(/Expected '\(' closing with '\)'/);
|
||||
});
|
||||
|
||||
it('does not allow invalid vectors, end >', (): void => {
|
||||
expect(
|
||||
(): TypeDef => getTypeDef('Vec<u64')
|
||||
).toThrow(/Unable to find closing matching/);
|
||||
});
|
||||
|
||||
it('maps empty tuples to empty tuple', (): void => {
|
||||
expect(
|
||||
getTypeDef('()')
|
||||
|
||||
@@ -99,10 +99,8 @@ function _decodeFixedVec (value: TypeDef, type: string, _: string, count: number
|
||||
function _decodeTuple (value: TypeDef, _: string, subType: string, count: number): TypeDef {
|
||||
value.sub = subType.length === 0
|
||||
? []
|
||||
: typeSplit(subType).map((inner): TypeDef =>
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
getTypeDef(inner, {}, count)
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
: typeSplit(subType).map((inner) => getTypeDef(inner, {}, count));
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -140,13 +138,7 @@ function _decodeDoNotConstruct (value: TypeDef, type: string, _: string): TypeDe
|
||||
}
|
||||
|
||||
function hasWrapper (type: string, [start, end]: [string, string, TypeDefInfo, any?]): boolean {
|
||||
if (type.substr(0, start.length) !== start) {
|
||||
return false;
|
||||
}
|
||||
|
||||
assert(type.endsWith(end), `Expected '${start}' closing with '${end}' on ${type}`);
|
||||
|
||||
return true;
|
||||
return (type.substr(0, start.length) === start) && (type.substr(-1 * end.length) === end);
|
||||
}
|
||||
|
||||
const nestedExtraction: [string, string, TypeDefInfo, (value: TypeDef, type: string, subType: string, count: number) => TypeDef][] = [
|
||||
@@ -185,9 +177,7 @@ export function getTypeDef (_type: string, { displayName, name }: TypeDefOptions
|
||||
return value;
|
||||
}
|
||||
|
||||
const nested = nestedExtraction.find((nested): boolean =>
|
||||
hasWrapper(type, nested)
|
||||
);
|
||||
const nested = nestedExtraction.find((nested) => hasWrapper(type, nested));
|
||||
|
||||
if (nested) {
|
||||
value.info = nested[2];
|
||||
@@ -195,9 +185,7 @@ export function getTypeDef (_type: string, { displayName, name }: TypeDefOptions
|
||||
return nested[3](value, type, extractSubType(type, nested), count);
|
||||
}
|
||||
|
||||
const wrapped = wrappedExtraction.find((wrapped): boolean =>
|
||||
hasWrapper(type, wrapped)
|
||||
);
|
||||
const wrapped = wrappedExtraction.find((wrapped) => hasWrapper(type, wrapped));
|
||||
|
||||
if (wrapped) {
|
||||
value.info = wrapped[2];
|
||||
|
||||
@@ -37,12 +37,12 @@ describe('typeSplit', (): void => {
|
||||
it('checks for unclosed vec', (): void => {
|
||||
expect(
|
||||
(): string[] => typeSplit('Text, Vec<u64')
|
||||
).toThrow(/Invalid defintion/);
|
||||
).toThrow(/Invalid definition/);
|
||||
});
|
||||
|
||||
it('checks for unclosed tuple', (): void => {
|
||||
expect(
|
||||
(): string[] => typeSplit('Text, (u64, u32')
|
||||
).toThrow(/Invalid defintion/);
|
||||
).toThrow(/Invalid definition/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,7 +42,7 @@ export function typeSplit (type: string): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
assert(isNotNested(cDepth, fDepth, sDepth, tDepth), `Invalid defintion (missing terminators) found in ${type}`);
|
||||
assert(isNotNested(cDepth, fDepth, sDepth, tDepth), `Invalid definition (missing terminators) found in ${type}`);
|
||||
|
||||
// the final leg of the journey
|
||||
result.push(type.substr(start, type.length - start).trim());
|
||||
|
||||
Reference in New Issue
Block a user