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
This commit is contained in:
@@ -97,7 +97,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* The set of open multisig operations.
|
||||
**/
|
||||
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>, AccountId | string | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
babe: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -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<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ITuple<[Perbill, BalanceOf]>>>, EraIndex | AnyNumber | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
validatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ITuple<[Perbill, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* All slashing events on nominators, mapped by era to the highest slash value of the era.
|
||||
**/
|
||||
nominatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<BalanceOf>>, EraIndex | AnyNumber | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
nominatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<BalanceOf>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* 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<ApiType, (arg: ITuple<[AccountId, SpanIndex]>) => Observable<SpanRecord>> & QueryableStorageEntry<ApiType>;
|
||||
spanSlash: AugmentedQuery<ApiType, (arg: ITuple<[AccountId, SpanIndex]> | [AccountId | string | Uint8Array, SpanIndex | AnyNumber | Uint8Array]) => Observable<SpanRecord>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* 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<ApiType, (key1: Bytes | string | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<Option<Keys>>, Bytes | string | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
nextKeys: AugmentedQueryDoubleMap<ApiType, (key1: Bytes | string | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<Option<Keys>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* 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<ApiType, (key1: Bytes | string | Uint8Array, key2: ITuple<[KeyTypeId, Bytes]>) => Observable<Option<ValidatorId>>, Bytes | string | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
keyOwner: AugmentedQueryDoubleMap<ApiType, (key1: Bytes | string | Uint8Array, key2: ITuple<[KeyTypeId, Bytes]> | [KeyTypeId | AnyNumber | Uint8Array, Bytes | string | Uint8Array]) => Observable<Option<ValidatorId>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
democracy: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -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<ApiType, (arg: ITuple<[ReferendumIndex, AccountId]>) => Observable<Vote>> & QueryableStorageEntry<ApiType>;
|
||||
voteOf: AugmentedQuery<ApiType, (arg: ITuple<[ReferendumIndex, AccountId]> | [ReferendumIndex | AnyNumber | Uint8Array, AccountId | string | Uint8Array]) => Observable<Vote>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* 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<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: AuthIndex | AnyNumber | Uint8Array) => Observable<Option<Bytes>>, SessionIndex | AnyNumber | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
receivedHeartbeats: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: AuthIndex | AnyNumber | Uint8Array) => Observable<Option<Bytes>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* For each session index, we keep a mapping of `T::ValidatorId` to the
|
||||
* number of blocks authored by the given authority.
|
||||
**/
|
||||
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, SessionIndex | AnyNumber | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
offences: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -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<ApiType, (key1: Kind | string | Uint8Array, key2: OpaqueTimeSlot | string | Uint8Array) => Observable<Vec<ReportIdOf>>, Kind | string | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
concurrentReportsIndex: AugmentedQueryDoubleMap<ApiType, (key1: Kind | string | Uint8Array, key2: OpaqueTimeSlot | string | Uint8Array) => Observable<Vec<ReportIdOf>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* 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<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<SocietyVote>>, AccountId | string | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
votes: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<SocietyVote>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* 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<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>, AccountId | string | Uint8Array> & QueryableStorageEntry<ApiType>;
|
||||
activeRecoveries: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The final list of recovered accounts.
|
||||
* Map from the recovered account to the user who can access it.
|
||||
|
||||
@@ -15,7 +15,7 @@ export interface AugmentedQueries<ApiType extends ApiTypes> { }
|
||||
|
||||
export type AugmentedQuery<ApiType extends ApiTypes, F extends AnyFunction> = MethodResult<ApiType, F> & StorageEntryBase<ApiType, F>
|
||||
|
||||
export type AugmentedQueryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction, FirstKeyType = any> = MethodResult<ApiType, F> & StorageEntryDoubleMap<ApiType, F, FirstKeyType>
|
||||
export type AugmentedQueryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> = MethodResult<ApiType, F> & StorageEntryDoubleMap<ApiType, F>
|
||||
|
||||
// This is the most generic typings we can have for a storage entry function
|
||||
type GenericStorageEntryFunction = (arg1?: CodecArg, arg2?: CodecArg) => Observable<Codec>
|
||||
@@ -36,8 +36,8 @@ export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunctio
|
||||
multi: ApiType extends 'rxjs' ? StorageEntryObservableMulti : StorageEntryPromiseMulti;
|
||||
}
|
||||
|
||||
export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction, FirstKeyType> extends StorageEntryBase<ApiType, F> {
|
||||
entries: (arg?: FirstKeyType) => PromiseOrObs<ApiType, [StorageKey, ObsInnerType<ReturnType<F>>][]>;
|
||||
export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> extends StorageEntryBase<ApiType, F> {
|
||||
entries: (arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, ObsInnerType<ReturnType<F>>][]>;
|
||||
}
|
||||
|
||||
interface StorageEntryObservableMulti {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ApiType>;`);
|
||||
indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: ${entryType}<ApiType, (${args}) => Observable<${returnType}>> & QueryableStorageEntry<ApiType>;`);
|
||||
}))
|
||||
.concat([indent(4)('};')]);
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 =>
|
||||
|
||||
Reference in New Issue
Block a user