From c6355fb1479dcbc6c2a96cd1b2a20ad1c09f6b49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jerem=C3=ADas=20D=C3=ADaz?= Date: Mon, 24 Feb 2020 18:31:18 -0300 Subject: [PATCH] fix: don't format "unorthodox" query input types (#1934) * fix: don't format "unorthodox" query input types Also add support for tuples in `getSimilarTypes` * fix: refactor type ignore logic into `formatType` Had to use a regexp solution because types like `([AccountId | string | Uint8Array, Data | { none: any } | { raw: any } | { blakeTwo256: any } | { sha256: any } | { keccak256: any } | { shaThree256: any } | string | Uint8Array])[]` were not being ignored with the current logic, so they were passed to `getTypeDef` and causing delimiter errors. * refactor: remove superfluous "FirstKeyType" param --- packages/api/src/augment/query.ts | 24 ++++++++++++------------ packages/api/src/types/storage.ts | 6 +++--- packages/typegen/src/fromChain.ts | 4 ++-- packages/typegen/src/generate/query.ts | 13 ++++++------- packages/typegen/src/generate/tx.ts | 6 +----- packages/typegen/src/util/derived.ts | 11 +++++++++++ packages/typegen/src/util/formatting.ts | 6 ++++++ packages/typegen/src/util/imports.ts | 10 ++++++++-- 8 files changed, 49 insertions(+), 31 deletions(-) diff --git a/packages/api/src/augment/query.ts b/packages/api/src/augment/query.ts index 13be1c007d..6d62642bf8 100644 --- a/packages/api/src/augment/query.ts +++ b/packages/api/src/augment/query.ts @@ -97,7 +97,7 @@ declare module '@polkadot/api/types/storage' { /** * The set of open multisig operations. **/ - multisigs: AugmentedQueryDoubleMap Observable>, AccountId | string | Uint8Array> & QueryableStorageEntry; + multisigs: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; }; babe: { [index: string]: QueryableStorageEntry; @@ -306,11 +306,11 @@ declare module '@polkadot/api/types/storage' { * All slashing events on validators, mapped by era to the highest slash proportion * and slash value of the era. **/ - validatorSlashInEra: AugmentedQueryDoubleMap Observable>>, EraIndex | AnyNumber | Uint8Array> & QueryableStorageEntry; + validatorSlashInEra: AugmentedQueryDoubleMap Observable>>> & QueryableStorageEntry; /** * All slashing events on nominators, mapped by era to the highest slash value of the era. **/ - nominatorSlashInEra: AugmentedQueryDoubleMap Observable>, EraIndex | AnyNumber | Uint8Array> & QueryableStorageEntry; + nominatorSlashInEra: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * Slashing spans for stash accounts. **/ @@ -319,7 +319,7 @@ declare module '@polkadot/api/types/storage' { * Records information about the maximum slash of a stash within a slashing span, * as well as how much reward has been paid out. **/ - spanSlash: AugmentedQuery) => Observable> & QueryableStorageEntry; + spanSlash: AugmentedQuery | [AccountId | string | Uint8Array, SpanIndex | AnyNumber | Uint8Array]) => Observable> & QueryableStorageEntry; /** * The earliest era for which we have a pending, unapplied slash. **/ @@ -355,13 +355,13 @@ declare module '@polkadot/api/types/storage' { * The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of * the trie. Having all data in the same branch should prevent slowing down other queries. **/ - nextKeys: AugmentedQueryDoubleMap Observable>, Bytes | string | Uint8Array> & QueryableStorageEntry; + nextKeys: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * The owner of a key. The second key is the `KeyTypeId` + the encoded key. * The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of * the trie. Having all data in the same branch should prevent slowing down other queries. **/ - keyOwner: AugmentedQueryDoubleMap) => Observable>, Bytes | string | Uint8Array> & QueryableStorageEntry; + keyOwner: AugmentedQueryDoubleMap | [KeyTypeId | AnyNumber | Uint8Array, Bytes | string | Uint8Array]) => Observable>> & QueryableStorageEntry; }; democracy: { [index: string]: QueryableStorageEntry; @@ -409,7 +409,7 @@ declare module '@polkadot/api/types/storage' { * default `Vote` value otherwise). If you don't want to check `voters_for`, then you can * also check for simple existence with `VoteOf::contains_key` first. **/ - voteOf: AugmentedQuery) => Observable> & QueryableStorageEntry; + voteOf: AugmentedQuery | [ReferendumIndex | AnyNumber | Uint8Array, AccountId | string | Uint8Array]) => Observable> & QueryableStorageEntry; /** * Who is able to vote for whom. Value is the fund-holding account, key is the * vote-transaction-sending account. @@ -643,12 +643,12 @@ declare module '@polkadot/api/types/storage' { * For each session index, we keep a mapping of `AuthIndex` * to `offchain::OpaqueNetworkState`. **/ - receivedHeartbeats: AugmentedQueryDoubleMap Observable>, SessionIndex | AnyNumber | Uint8Array> & QueryableStorageEntry; + receivedHeartbeats: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * For each session index, we keep a mapping of `T::ValidatorId` to the * number of blocks authored by the given authority. **/ - authoredBlocks: AugmentedQueryDoubleMap Observable, SessionIndex | AnyNumber | Uint8Array> & QueryableStorageEntry; + authoredBlocks: AugmentedQueryDoubleMap Observable> & QueryableStorageEntry; }; offences: { [index: string]: QueryableStorageEntry; @@ -659,7 +659,7 @@ declare module '@polkadot/api/types/storage' { /** * A vector of reports of the same kind that happened at the same time slot. **/ - concurrentReportsIndex: AugmentedQueryDoubleMap Observable>, Kind | string | Uint8Array> & QueryableStorageEntry; + concurrentReportsIndex: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * Enumerates all reports of a kind along with the time they happened. * All reports are sorted by the time of offence. @@ -754,7 +754,7 @@ declare module '@polkadot/api/types/storage' { /** * Double map from Candidate -> Voter -> (Maybe) Vote. **/ - votes: AugmentedQueryDoubleMap Observable>, AccountId | string | Uint8Array> & QueryableStorageEntry; + votes: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * The defending member currently being challenged. **/ @@ -779,7 +779,7 @@ declare module '@polkadot/api/types/storage' { * First account is the account to be recovered, and the second account * is the user trying to recover the account. **/ - activeRecoveries: AugmentedQueryDoubleMap Observable>, AccountId | string | Uint8Array> & QueryableStorageEntry; + activeRecoveries: AugmentedQueryDoubleMap Observable>> & QueryableStorageEntry; /** * The final list of recovered accounts. * Map from the recovered account to the user who can access it. diff --git a/packages/api/src/types/storage.ts b/packages/api/src/types/storage.ts index 531376e0dc..2646d0b83a 100644 --- a/packages/api/src/types/storage.ts +++ b/packages/api/src/types/storage.ts @@ -15,7 +15,7 @@ export interface AugmentedQueries { } export type AugmentedQuery = MethodResult & StorageEntryBase -export type AugmentedQueryDoubleMap = MethodResult & StorageEntryDoubleMap +export type AugmentedQueryDoubleMap = MethodResult & StorageEntryDoubleMap // This is the most generic typings we can have for a storage entry function type GenericStorageEntryFunction = (arg1?: CodecArg, arg2?: CodecArg) => Observable @@ -36,8 +36,8 @@ export interface StorageEntryBase extends StorageEntryBase { - entries: (arg?: FirstKeyType) => PromiseOrObs>][]>; +export interface StorageEntryDoubleMap extends StorageEntryBase { + entries: (arg?: Parameters[0]) => PromiseOrObs>][]>; } interface StorageEntryObservableMulti { diff --git a/packages/typegen/src/fromChain.ts b/packages/typegen/src/fromChain.ts index 19db88d55d..9c20349fb1 100644 --- a/packages/typegen/src/fromChain.ts +++ b/packages/typegen/src/fromChain.ts @@ -61,7 +61,7 @@ function onSocketOpen (): boolean { export default function main (): void { const { endpoint, output, package: pkg, strict: isStrict } = yargs.strict().options({ endpoint: { - description: 'The endpoint to connect to, e.g. wss://kusama-rpc.polkadot.io or relative file to JSON output', + description: 'The endpoint to connect to (e.g. wss://kusama-rpc.polkadot.io) or relative path to a file containing the JSON output of an RPC state_getMetadata call', type: 'string', required: true }, @@ -75,7 +75,7 @@ export default function main (): void { type: 'string' }, strict: { - description: 'Turns on stict mode, no output of catch-all generic versions', + description: 'Turns on strict mode, no output of catch-all generic versions', type: 'boolean' } }).argv; diff --git a/packages/typegen/src/generate/query.ts b/packages/typegen/src/generate/query.ts index 04b7eca752..04fb3cced0 100644 --- a/packages/typegen/src/generate/query.ts +++ b/packages/typegen/src/generate/query.ts @@ -26,6 +26,8 @@ function addModifier (storageEntry: StorageEntryMetadataLatest, returnType: stri // From a storage entry metadata, we return [args, returnType] /** @internal */ function entrySignature (allDefs: object, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] { + const format = (type: string): string => formatType(allDefs, type, imports); + if (storageEntry.type.isPlain) { setImports(allDefs, imports, [storageEntry.type.asPlain.toString()]); @@ -40,7 +42,7 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor ]); return [ - `arg: ${similarTypes.map((type) => formatType(allDefs, type, imports)).join(' | ')}`, + `arg: ${similarTypes.map(format).join(' | ')}`, formatType(allDefs, addModifier(storageEntry, storageEntry.type.asMap.value.toString()), imports) ]; } else if (storageEntry.type.isDoubleMap) { @@ -54,8 +56,8 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor storageEntry.type.asDoubleMap.value.toString() ]); - const key1Types = similarTypes1.map((type) => formatType(allDefs, type, imports)).join(' | '); - const key2Types = similarTypes2.map((type) => formatType(allDefs, type, imports)).join(' | '); + const key1Types = similarTypes1.map(format).join(' | '); + const key2Types = similarTypes2.map(format).join(' | '); return [ `key1: ${key1Types}, key2: ${key2Types}`, @@ -78,16 +80,13 @@ function generateModule (allDefs: object, registry: Registry, { name, storage }: .concat(storage.unwrap().items.map((storageEntry): string => { const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports); let entryType = 'AugmentedQuery'; - const entryTypeArgs: string[] = ['ApiType', `(${args}) => Observable<${returnType}>`]; if (storageEntry.type.isDoubleMap) { entryType = `${entryType}DoubleMap`; - const firstKeyTypes = /^key1: (.*), key2/.exec(args)![1]; - entryTypeArgs.push(firstKeyTypes); } return createDocComments(6, storageEntry.documentation) + - indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: ${entryType}<${entryTypeArgs.join(', ')}> & QueryableStorageEntry;`); + indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: ${entryType} Observable<${returnType}>> & QueryableStorageEntry;`); })) .concat([indent(4)('};')]); } diff --git a/packages/typegen/src/generate/tx.ts b/packages/typegen/src/generate/tx.ts index 88179c1137..a8c51a77ab 100644 --- a/packages/typegen/src/generate/tx.ts +++ b/packages/typegen/src/generate/tx.ts @@ -43,11 +43,7 @@ function generateModule (registry: Registry, allDefs: object, { calls, name }: M const params = args .map(({ name, type }): [string, string, string] => { const typeStr = type.toString(); - const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string => - type.startsWith('(') || type.startsWith('{') - ? type - : formatType(allDefs, type, imports) - ); + const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string => formatType(allDefs, type, imports)); const nameStr = mapName(name); setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]); diff --git a/packages/typegen/src/util/derived.ts b/packages/typegen/src/util/derived.ts index 7ce394378e..42c1fc6169 100644 --- a/packages/typegen/src/util/derived.ts +++ b/packages/typegen/src/util/derived.ts @@ -13,6 +13,7 @@ import Option from '@polkadot/types/codec/Option'; import Struct from '@polkadot/types/codec/Struct'; import UInt from '@polkadot/types/codec/UInt'; import Vec from '@polkadot/types/codec/Vec'; +import Tuple from '@polkadot/types/codec/Tuple'; import GenericAccountId from '@polkadot/types/generic/AccountId'; import GenericAddress from '@polkadot/types/generic/Address'; import Vote, { convictionNames as _voteConvictions } from '@polkadot/types/generic/Vote'; @@ -80,6 +81,8 @@ export function getSimilarTypes (definitions: object, registry: Registry, _type: } else if (type === 'StorageKey') { // TODO We can do better return ['StorageKey', 'string', 'Uint8Array', 'any']; + } else if (type === '()') { + return ['null']; } const Clazz = ClassOfUnsafe(registry, type); @@ -133,6 +136,14 @@ export function getSimilarTypes (definitions: object, registry: Registry, _type: possibleTypes.push('string', 'Uint8Array'); } else if (isChildClass(String, Clazz)) { possibleTypes.push('string'); + } else if (isChildClass(Tuple, Clazz)) { + const subDef = getTypeDef(type).sub; + + if (Array.isArray(subDef)) { + const subs = subDef.map(({ type }) => getSimilarTypes(definitions, registry, type, imports).join(' | ')); + + possibleTypes.push(`[${subs.join(', ')}]`); + } } return possibleTypes; diff --git a/packages/typegen/src/util/formatting.ts b/packages/typegen/src/util/formatting.ts index 8c6d7e208f..d128b9339d 100644 --- a/packages/typegen/src/util/formatting.ts +++ b/packages/typegen/src/util/formatting.ts @@ -137,6 +137,12 @@ export function formatType (definitions: object, type: string | TypeDef, imports let typeDef: TypeDef; if (typeof type === 'string') { + // If type is "unorthodox" (i.e. `{ something: any }` for an Enum input or `[a | b | c, d | e | f]` for a Tuple's similar types), + // we return it as-is + if (/(^{.+:.+})|^\([^,]+\)|^\(.+\)\[\]|^\[([^;]+|)?[^;]+\]/.exec(type)) { + return type; + } + typeDef = getTypeDef(type); } else { typeDef = type; diff --git a/packages/typegen/src/util/imports.ts b/packages/typegen/src/util/imports.ts index ce24ce033b..fd7485b4f3 100644 --- a/packages/typegen/src/util/imports.ts +++ b/packages/typegen/src/util/imports.ts @@ -50,9 +50,10 @@ export function setImports (allDefs: object, imports: TypeImports, types: string genericTypes[type] = true; } else if ((primitiveClasses as any)[type] || type === 'Metadata') { primitiveTypes[type] = true; - } else if (type.includes('<') || type.includes('(') || type.includes('[')) { + } else if (type.includes('<') || type.includes('(') || (type.includes('[') && !type.includes('|'))) { // If the type is a bit special (tuple, fixed u8, nested type...), then we - // need to parse it with `getTypeDef`. + // need to parse it with `getTypeDef`. We skip the case where type ~ [a | b | c ... , ... , ... w | y | z ] + // since that represents a tuple's similar types, which are covered in the next block const typeDef = getTypeDef(type); setImports(allDefs, imports, [TypeDefInfo[typeDef.info]]); @@ -64,6 +65,11 @@ export function setImports (allDefs: object, imports: TypeImports, types: string // typeDef.sub is a TypeDef in this case setImports(allDefs, imports, [typeDef.sub.type]); } + } else if (type.includes('[') && type.includes('|')) { + // We split the types + const splitTypes = /\[\s?(.+?)\s?\]/.exec(type)![1].split(/\s?\|\s?/); + + setImports(allDefs, imports, splitTypes); } else { // find this module inside the exports from the rest const [moduleName] = Object.entries(allDefs).find(([, { types }]): boolean =>