From 14026fef426ae20e6b63b75738dd1f2a6da6d087 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Tue, 27 Oct 2020 12:23:18 +0100 Subject: [PATCH] Format similar types transparently (#2788) * Format similar types transparently * Adjust test expectations * Remove console.error * Adjust getTypeDef for check-only --- packages/api/src/augment/rpc.ts | 4 +-- packages/api/src/augment/tx.ts | 12 ++++---- packages/typegen/src/generate/query.ts | 7 ++--- packages/typegen/src/generate/rpc.ts | 3 +- packages/typegen/src/generate/tx.ts | 9 +++--- packages/typegen/src/util/derived.spec.ts | 31 ++++++++++++++++++++ packages/typegen/src/util/derived.ts | 4 +-- packages/typegen/src/util/formatting.spec.ts | 22 ++++++++++++++ packages/typegen/src/util/formatting.ts | 3 +- packages/typegen/src/util/imports.ts | 2 +- packages/types/src/codec/Linkage.ts | 2 -- packages/types/src/create/getTypeDef.spec.ts | 14 +-------- packages/types/src/create/getTypeDef.ts | 22 ++++---------- packages/types/src/create/typeSplit.spec.ts | 4 +-- packages/types/src/create/typeSplit.ts | 2 +- 15 files changed, 82 insertions(+), 59 deletions(-) create mode 100644 packages/typegen/src/util/derived.spec.ts create mode 100644 packages/typegen/src/util/formatting.spec.ts diff --git a/packages/api/src/augment/rpc.ts b/packages/api/src/augment/rpc.ts index d97453036f..ecc1b1dbe9 100644 --- a/packages/api/src/augment/rpc.ts +++ b/packages/api/src/augment/rpc.ts @@ -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>>; + localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable>>; /** * 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>; + localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable>; }; payment: { /** diff --git a/packages/api/src/augment/tx.ts b/packages/api/src/augment/tx.ts index 8a2600ebe9..3ecc854b7c 100644 --- a/packages/api/src/augment/tx.ts +++ b/packages/api/src/augment/tx.ts @@ -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>; + delegate: AugmentedSubmittable<(to: AccountId | string | Uint8Array, conviction: Conviction | 'None' | 'Locked1x' | 'Locked2x' | 'Locked3x' | 'Locked4x' | 'Locked5x' | 'Locked6x' | number | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * 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). * # **/ - addProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic>; + addProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * Publish the hash of a proxy-call that will be made in the future. * @@ -1442,7 +1442,7 @@ declare module '@polkadot/api/types/submittable' { * # * 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>; + anonymous: AugmentedSubmittable<(proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array, index: u16 | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * 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). * # **/ - killAnonymous: AugmentedSubmittable<(spawner: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, index: u16 | AnyNumber | Uint8Array, height: Compact | AnyNumber | Uint8Array, extIndex: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; + killAnonymous: AugmentedSubmittable<(spawner: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, index: u16 | AnyNumber | Uint8Array, height: Compact | AnyNumber | Uint8Array, extIndex: Compact | AnyNumber | Uint8Array) => SubmittableExtrinsic>; /** * 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). * # **/ - removeProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic>; + removeProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic>; }; recovery: { [key: string]: SubmittableExtrinsicFunction; @@ -1999,7 +1999,7 @@ declare module '@polkadot/api/types/submittable' { * Total Complexity: O(M + logM + B + X) * # **/ - judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid'|'Reject'|'Approve' | number | Uint8Array) => SubmittableExtrinsic>; + judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid' | 'Reject' | 'Approve' | number | Uint8Array) => SubmittableExtrinsic>; /** * Allow suspension judgement origin to make judgement on a suspended member. * diff --git a/packages/typegen/src/generate/query.ts b/packages/typegen/src/generate/query.ts index 8b18435531..1ef772c05b 100644 --- a/packages/typegen/src/generate/query.ts +++ b/packages/typegen/src/generate/query.ts @@ -19,7 +19,6 @@ import { ModuleTypes } from '../util/imports'; // From a storage entry metadata, we return [args, returnType] /** @internal */ function entrySignature (allDefs: Record, 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, 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, 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}`, diff --git a/packages/typegen/src/generate/rpc.ts b/packages/typegen/src/generate/rpc.ts index 65b471b44d..a2674b2a60 100644 --- a/packages/typegen/src/generate/rpc.ts +++ b/packages/typegen/src/generate/rpc.ts @@ -17,7 +17,6 @@ const generateRpcTypesTemplate = Handlebars.compile(template); /** @internal */ export function generateRpcTypes (importDefinitions: { [importPath: string]: Record }, 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; @@ -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); diff --git a/packages/typegen/src/generate/tx.ts b/packages/typegen/src/generate/tx.ts index 84428a210c..2a2f3be5a9 100644 --- a/packages/typegen/src/generate/tx.ts +++ b/packages/typegen/src/generate/tx.ts @@ -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 = { 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(', '); diff --git a/packages/typegen/src/util/derived.spec.ts b/packages/typegen/src/util/derived.spec.ts new file mode 100644 index 0000000000..9a436862d3 --- /dev/null +++ b/packages/typegen/src/util/derived.spec.ts @@ -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]' + ]); + }); +}); diff --git a/packages/typegen/src/util/derived.ts b/packages/typegen/src/util/derived.ts index f293976327..88bb5cfa89 100644 --- a/packages/typegen/src/util/derived.ts +++ b/packages/typegen/src/util/derived.ts @@ -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, _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']); diff --git a/packages/typegen/src/util/formatting.spec.ts b/packages/typegen/src/util/formatting.spec.ts new file mode 100644 index 0000000000..03eb8ac1df --- /dev/null +++ b/packages/typegen/src/util/formatting.spec.ts @@ -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]>'); + }); +}); diff --git a/packages/typegen/src/util/formatting.ts b/packages/typegen/src/util/formatting.ts index 99e13bfdb6..e03f200609 100644 --- a/packages/typegen/src/util/formatting.ts +++ b/packages/typegen/src/util/formatting.ts @@ -232,8 +232,7 @@ export function formatType (definitions: Record, 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))) ); } diff --git a/packages/typegen/src/util/imports.ts b/packages/typegen/src/util/imports.ts index 83e66d75b4..530bdc1ff3 100644 --- a/packages/typegen/src/util/imports.ts +++ b/packages/typegen/src/util/imports.ts @@ -62,7 +62,7 @@ export function setImports (allDefs: Record, 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]); diff --git a/packages/types/src/codec/Linkage.ts b/packages/types/src/codec/Linkage.ts index 9b34033ae2..fc6dada353 100644 --- a/packages/types/src/codec/Linkage.ts +++ b/packages/types/src/codec/Linkage.ts @@ -23,8 +23,6 @@ export default class Linkage extends Struct { // eslint-disable-next-line sort-keys next: Option.with(Type) }, value as string); - - console.error([...this.entries()]); } public static withKey (Type: Constructor | keyof InterfaceTypes): Constructor> { diff --git a/packages/types/src/create/getTypeDef.spec.ts b/packages/types/src/create/getTypeDef.spec.ts index 0eb83f65a7..eaff24a1ad 100644 --- a/packages/types/src/create/getTypeDef.spec.ts +++ b/packages/types/src/create/getTypeDef.spec.ts @@ -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 { expect( getTypeDef('()') diff --git a/packages/types/src/create/getTypeDef.ts b/packages/types/src/create/getTypeDef.ts index 3b4f7f12c4..1c2b2b4c6c 100644 --- a/packages/types/src/create/getTypeDef.ts +++ b/packages/types/src/create/getTypeDef.ts @@ -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]; diff --git a/packages/types/src/create/typeSplit.spec.ts b/packages/types/src/create/typeSplit.spec.ts index b0c3ef363e..7dfef10ea0 100644 --- a/packages/types/src/create/typeSplit.spec.ts +++ b/packages/types/src/create/typeSplit.spec.ts @@ -37,12 +37,12 @@ describe('typeSplit', (): void => { it('checks for unclosed vec', (): void => { expect( (): string[] => typeSplit('Text, Vec { expect( (): string[] => typeSplit('Text, (u64, u32') - ).toThrow(/Invalid defintion/); + ).toThrow(/Invalid definition/); }); }); diff --git a/packages/types/src/create/typeSplit.ts b/packages/types/src/create/typeSplit.ts index 00b9e25243..70b74abc68 100644 --- a/packages/types/src/create/typeSplit.ts +++ b/packages/types/src/create/typeSplit.ts @@ -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());