Expand enum & struct defnitions, generator strict mode (#1798)

This commit is contained in:
Jaco Greeff
2020-02-03 11:56:06 +01:00
committed by GitHub
parent 328630fb17
commit 2ee3afcd61
14 changed files with 128 additions and 85 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ import { Gas } from '@polkadot/types/interfaces/contracts';
import { SessionIndex } from '@polkadot/types/interfaces/session'; import { SessionIndex } from '@polkadot/types/interfaces/session';
import { EraIndex } from '@polkadot/types/interfaces/staking'; import { EraIndex } from '@polkadot/types/interfaces/staking';
declare module '@polkadot/metadata/Decorated/types' { declare module '@polkadot/metadata/Decorated/consts/types' {
export interface Constants { export interface Constants {
babe: { babe: {
[index: string]: Codec; [index: string]: Codec;
+2 -2
View File
@@ -30,7 +30,7 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/** /**
* Remove given extrinsic from the pool and temporarily ban it to prevent reimporting * Remove given extrinsic from the pool and temporarily ban it to prevent reimporting
**/ **/
removeExtrinsic(bytesOrHash: Vec<ExtrinsicOrHash> | (ExtrinsicOrHash | object | number | Uint8Array | string)[]): Observable<Vec<Hash>>; removeExtrinsic(bytesOrHash: Vec<ExtrinsicOrHash> | (ExtrinsicOrHash | { hash: any } | { extrinsic: any } | string | Uint8Array)[]): Observable<Vec<Hash>>;
/** /**
* Generate new session keys and returns the corresponding public keys * Generate new session keys and returns the corresponding public keys
**/ **/
@@ -74,7 +74,7 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/** /**
* Executes a call to a contract * Executes a call to a contract
**/ **/
call(callRequest: ContractCallRequest | object | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<ContractExecResult>; call(callRequest: ContractCallRequest | { origin?: any; dest?: any; value?: any; gasLimit?: any; inputData?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array): Observable<ContractExecResult>;
/** /**
* Returns the value under a specified storage key in a contract * Returns the value under a specified storage key in a contract
**/ **/
+18 -18
View File
@@ -76,7 +76,7 @@ declare module '@polkadot/api/types/submittable' {
* and the error of the failed call. If all were successful, then the `BatchCompleted` * and the error of the failed call. If all were successful, then the `BatchCompleted`
* event is deposited. * event is deposited.
**/ **/
batch: AugmentedSubmittable<(calls: Vec<Call> | (Call | object | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>; batch: AugmentedSubmittable<(calls: Vec<Call> | (Call | { callIndex?: any; args?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>;
/** /**
* Send a call through an indexed pseudonym of the sender. * Send a call through an indexed pseudonym of the sender.
* The dispatch origin for this call must be _Signed_. * The dispatch origin for this call must be _Signed_.
@@ -84,7 +84,7 @@ declare module '@polkadot/api/types/submittable' {
* - The weight of the `call`. * - The weight of the `call`.
* # </weight> * # </weight>
**/ **/
asSub: AugmentedSubmittable<(index: u16 | AnyNumber | Uint8Array, call: Call | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; asSub: AugmentedSubmittable<(index: u16 | AnyNumber | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Register approval for a dispatch to be made from a deterministic composite account if * Register approval for a dispatch to be made from a deterministic composite account if
* approved by a total of `threshold - 1` of `other_signatories`. * approved by a total of `threshold - 1` of `other_signatories`.
@@ -121,7 +121,7 @@ declare module '@polkadot/api/types/submittable' {
* `MultisigDepositBase + threshold * MultisigDepositFactor`. * `MultisigDepositBase + threshold * MultisigDepositFactor`.
* # </weight> * # </weight>
**/ **/
asMulti: AugmentedSubmittable<(threshold: u16 | AnyNumber | Uint8Array, otherSignatories: Vec<AccountId> | (AccountId | string | Uint8Array)[], maybeTimepoint: Option<Timepoint> | null | object | string | Uint8Array, call: Call | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; asMulti: AugmentedSubmittable<(threshold: u16 | AnyNumber | Uint8Array, otherSignatories: Vec<AccountId> | (AccountId | string | Uint8Array)[], maybeTimepoint: Option<Timepoint> | null | object | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Register approval for a dispatch to be made from a deterministic composite account if * Register approval for a dispatch to be made from a deterministic composite account if
* approved by a total of `threshold - 1` of `other_signatories`. * approved by a total of `threshold - 1` of `other_signatories`.
@@ -173,7 +173,7 @@ declare module '@polkadot/api/types/submittable' {
* - Storage: removes one item. * - Storage: removes one item.
* # </weight> * # </weight>
**/ **/
cancelAsMulti: AugmentedSubmittable<(threshold: u16 | AnyNumber | Uint8Array, otherSignatories: Vec<AccountId> | (AccountId | string | Uint8Array)[], timepoint: Timepoint | object | string | Uint8Array, callHash: Raw | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; cancelAsMulti: AugmentedSubmittable<(threshold: u16 | AnyNumber | Uint8Array, otherSignatories: Vec<AccountId> | (AccountId | string | Uint8Array)[], timepoint: Timepoint | { height?: any; index?: any } | string | Uint8Array, callHash: Raw | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
}; };
timestamp: { timestamp: {
[index: string]: SubmittableExtrinsicFunction<ApiType>; [index: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -192,7 +192,7 @@ declare module '@polkadot/api/types/submittable' {
/** /**
* Provide a set of uncles. * Provide a set of uncles.
**/ **/
setUncles: AugmentedSubmittable<(newUncles: Vec<Header> | (Header | object | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>; setUncles: AugmentedSubmittable<(newUncles: Vec<Header> | (Header | { parentHash?: any; number?: any; stateRoot?: any; extrinsicsRoot?: any; digest?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>;
}; };
balances: { balances: {
[index: string]: SubmittableExtrinsicFunction<ApiType>; [index: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -319,7 +319,7 @@ declare module '@polkadot/api/types/submittable' {
* - Writes are limited to the `origin` account key. * - Writes are limited to the `origin` account key.
* # </weight> * # </weight>
**/ **/
validate: AugmentedSubmittable<(prefs: ValidatorPrefs | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; validate: AugmentedSubmittable<(prefs: ValidatorPrefs | { commission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Declare the desire to nominate `targets` for the origin controller. * Declare the desire to nominate `targets` for the origin controller.
* Effects will be felt at the beginning of the next era. * Effects will be felt at the beginning of the next era.
@@ -583,14 +583,14 @@ declare module '@polkadot/api/types/submittable' {
* Dispatch a proposal from a member using the `Member` origin. * Dispatch a proposal from a member using the `Member` origin.
* Origin must be a member of the collective. * Origin must be a member of the collective.
**/ **/
execute: AugmentedSubmittable<(proposal: Proposal | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; execute: AugmentedSubmittable<(proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* # <weight> * # <weight>
* - Bounded storage reads and writes. * - Bounded storage reads and writes.
* - Argument `threshold` has bearing on weight. * - Argument `threshold` has bearing on weight.
* # </weight> * # </weight>
**/ **/
propose: AugmentedSubmittable<(threshold: Compact<MemberCount> | AnyNumber | Uint8Array, proposal: Proposal | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; propose: AugmentedSubmittable<(threshold: Compact<MemberCount> | AnyNumber | Uint8Array, proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* # <weight> * # <weight>
* - Bounded storage read and writes. * - Bounded storage read and writes.
@@ -611,14 +611,14 @@ declare module '@polkadot/api/types/submittable' {
* Dispatch a proposal from a member using the `Member` origin. * Dispatch a proposal from a member using the `Member` origin.
* Origin must be a member of the collective. * Origin must be a member of the collective.
**/ **/
execute: AugmentedSubmittable<(proposal: Proposal | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; execute: AugmentedSubmittable<(proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* # <weight> * # <weight>
* - Bounded storage reads and writes. * - Bounded storage reads and writes.
* - Argument `threshold` has bearing on weight. * - Argument `threshold` has bearing on weight.
* # </weight> * # </weight>
**/ **/
propose: AugmentedSubmittable<(threshold: Compact<MemberCount> | AnyNumber | Uint8Array, proposal: Proposal | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; propose: AugmentedSubmittable<(threshold: Compact<MemberCount> | AnyNumber | Uint8Array, proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* # <weight> * # <weight>
* - Bounded storage read and writes. * - Bounded storage read and writes.
@@ -873,7 +873,7 @@ declare module '@polkadot/api/types/submittable' {
* Updates the schedule for metering contracts. * Updates the schedule for metering contracts.
* The schedule must have a greater version than the stored schedule. * The schedule must have a greater version than the stored schedule.
**/ **/
updateSchedule: AugmentedSubmittable<(schedule: Schedule | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; updateSchedule: AugmentedSubmittable<(schedule: Schedule | { version?: any; putCodePerByteCost?: any; growMemCost?: any; regularOpCost?: any; returnDataPerByteCost?: any; eventDataPerByteCost?: any; eventPerTopicCost?: any; eventBaseCost?: any; sandboxDataReadCost?: any; sandboxDataWriteCost?: any; transferCost?: any; maxEventTopics?: any; maxStackHeight?: any; maxMemoryPages?: any; enablePrintln?: any; maxSubjectLen?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Stores the given binary Wasm code into the chain's storage and returns its `codehash`. * Stores the given binary Wasm code into the chain's storage and returns its `codehash`.
* You can instantiate contracts only with stored code. * You can instantiate contracts only with stored code.
@@ -919,7 +919,7 @@ declare module '@polkadot/api/types/submittable' {
* - Unknown weight of derivative `proposal` execution. * - Unknown weight of derivative `proposal` execution.
* # </weight> * # </weight>
**/ **/
sudo: AugmentedSubmittable<(proposal: Proposal | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; sudo: AugmentedSubmittable<(proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key. * Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key.
* The dispatch origin for this call must be _Signed_. * The dispatch origin for this call must be _Signed_.
@@ -941,11 +941,11 @@ declare module '@polkadot/api/types/submittable' {
* - Unknown weight of derivative `proposal` execution. * - Unknown weight of derivative `proposal` execution.
* # </weight> * # </weight>
**/ **/
sudoAs: AugmentedSubmittable<(who: Address | string | AccountId | AccountIndex | Uint8Array, proposal: Proposal | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; sudoAs: AugmentedSubmittable<(who: Address | string | AccountId | AccountIndex | Uint8Array, proposal: Proposal | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
}; };
imOnline: { imOnline: {
[index: string]: SubmittableExtrinsicFunction<ApiType>; [index: string]: SubmittableExtrinsicFunction<ApiType>;
heartbeat: AugmentedSubmittable<(heartbeat: Heartbeat | object | string | Uint8Array, signature: Signature | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; heartbeat: AugmentedSubmittable<(heartbeat: Heartbeat | { blockNumber?: any; networkState?: any; sessionIndex?: any; authorityIndex?: any } | string | Uint8Array, signature: Signature | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
}; };
identity: { identity: {
[index: string]: SubmittableExtrinsicFunction<ApiType>; [index: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -976,7 +976,7 @@ declare module '@polkadot/api/types/submittable' {
* - One event. * - One event.
* # </weight> * # </weight>
**/ **/
setIdentity: AugmentedSubmittable<(info: IdentityInfo | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; setIdentity: AugmentedSubmittable<(info: IdentityInfo | { additional?: any; display?: any; legal?: any; web?: any; riot?: any; email?: any; pgpFingerprint?: any; image?: any; twitter?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Set the sub-accounts of the sender. * Set the sub-accounts of the sender.
* Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned * Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned
@@ -991,7 +991,7 @@ declare module '@polkadot/api/types/submittable' {
* one storage-exists. * one storage-exists.
* # </weight> * # </weight>
**/ **/
setSubs: AugmentedSubmittable<(subs: Vec<ITuple<[AccountId, Data]>> | ([AccountId | string | Uint8Array, Data | object | number | Uint8Array | string])[]) => SubmittableExtrinsic<ApiType>>; setSubs: AugmentedSubmittable<(subs: Vec<ITuple<[AccountId, Data]>> | ([AccountId | string | Uint8Array, Data | { none: any } | { raw: any } | { blakeTwo256: any } | { sha256: any } | { keccak256: any } | { shaThree256: any } | string | Uint8Array])[]) => SubmittableExtrinsic<ApiType>>;
/** /**
* Clear an account's identity info and all sub-account and return all deposits. * Clear an account's identity info and all sub-account and return all deposits.
* Payment: All reserved balances on the account are returned. * Payment: All reserved balances on the account are returned.
@@ -1094,7 +1094,7 @@ declare module '@polkadot/api/types/submittable' {
* - One event. * - One event.
* # </weight> * # </weight>
**/ **/
provideJudgement: AugmentedSubmittable<(regIndex: Compact<RegistrarIndex> | AnyNumber | Uint8Array, target: Address | string | AccountId | AccountIndex | Uint8Array, judgement: IdentityJudgement | object | number | Uint8Array | string) => SubmittableExtrinsic<ApiType>>; provideJudgement: AugmentedSubmittable<(regIndex: Compact<RegistrarIndex> | AnyNumber | Uint8Array, target: Address | string | AccountId | AccountIndex | Uint8Array, judgement: IdentityJudgement | { unknown: any } | { feePaid: any } | { reasonable: any } | { knownGood: any } | { outOfDate: any } | { lowQuality: any } | { erroneous: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Remove an account's identity and sub-account information and slash the deposits. * Remove an account's identity and sub-account information and slash the deposits.
* Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by * Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by
@@ -1389,7 +1389,7 @@ declare module '@polkadot/api/types/submittable' {
* - One storage lookup to check account is recovered by `who`. O(1) * - One storage lookup to check account is recovered by `who`. O(1)
* # </weight> * # </weight>
**/ **/
asRecovered: AugmentedSubmittable<(account: AccountId | string | Uint8Array, call: Call | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>>; asRecovered: AugmentedSubmittable<(account: AccountId | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/** /**
* Allow ROOT to bypass the recovery process and set an a rescuer account * Allow ROOT to bypass the recovery process and set an a rescuer account
* for a lost account directly. * for a lost account directly.
@@ -0,0 +1,19 @@
// Copyright 2017-2020 @polkadot/metadata authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Codec } from '@polkadot/types/types';
import { ModuleConstantMetadataLatest } from '@polkadot/types/interfaces';
export type AugmentedConst<T extends Codec> = T & ConstantCodec;
export type ModuleConstants = Record<string, Codec>;
export interface Constants {
[index: string]: ModuleConstants;
}
export interface ConstantCodec extends Codec {
meta: ModuleConstantMetadataLatest;
}
+1 -13
View File
@@ -3,20 +3,8 @@
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { StorageEntry } from '@polkadot/types/primitive/StorageKey'; import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
import { Codec } from '@polkadot/types/types';
import { ModuleConstantMetadataLatest } from '@polkadot/types/interfaces';
export type AugmentedConst<T extends Codec> = T & ConstantCodec; export * from './consts/types';
export interface ConstantCodec extends Codec {
meta: ModuleConstantMetadataLatest;
}
export type ModuleConstants = Record<string, Codec>;
export interface Constants {
[index: string]: ModuleConstants;
}
export interface ModuleStorage { export interface ModuleStorage {
[key: string]: StorageEntry; [key: string]: StorageEntry;
+8 -1
View File
@@ -203,6 +203,13 @@ export default class Enum extends Base<Codec> {
return this.raw instanceof Null; return this.raw instanceof Null;
} }
/**
* @description The available keys for this enum
*/
public get defEntries (): string[] {
return Object.keys(this._def);
}
/** /**
* @description The available keys for this enum * @description The available keys for this enum
*/ */
@@ -275,7 +282,7 @@ export default class Enum extends Base<Codec> {
*/ */
protected toRawStruct (): string[] | Record<string, string> { protected toRawStruct (): string[] | Record<string, string> {
return this._isBasic return this._isBasic
? Object.keys(this._def) ? this.defKeys
: Struct.typesToMap(this.registry, this._def); : Struct.typesToMap(this.registry, this._def);
} }
+7
View File
@@ -139,6 +139,13 @@ export default class Struct<
}; };
} }
/**
* @description The available keys for this enum
*/
public get defKeys (): string[] {
return Object.keys(this._Types);
}
/** /**
* @description Checks if the value is an empty value * @description Checks if the value is an empty value
*/ */
@@ -13,7 +13,7 @@ import { FOOTER, HEADER, TypeImports, createDocComments, createImportCode, creat
// Generate types for one module // Generate types for one module
/** @internal */ /** @internal */
function generateModule (allDefs: object, { constants, name }: ModuleMetadataLatest, imports: TypeImports): string[] { function generateModule (allDefs: object, { constants, name }: ModuleMetadataLatest, imports: TypeImports, isStrict: boolean): string[] {
if (!constants.length) { if (!constants.length) {
return []; return [];
} }
@@ -21,18 +21,18 @@ function generateModule (allDefs: object, { constants, name }: ModuleMetadataLat
setImports(allDefs, imports, ['Codec']); setImports(allDefs, imports, ['Codec']);
return [indent(4)(`${stringCamelCase(name.toString())}: {`)] return [indent(4)(`${stringCamelCase(name.toString())}: {`)]
.concat(indent(6)('[index: string]: Codec;')) .concat(isStrict ? '' : indent(6)('[index: string]: Codec;'))
.concat(constants.map(({ documentation, name, type }): string => { .concat(constants.map(({ documentation, name, type }): string => {
setImports(allDefs, imports, [type.toString()]); setImports(allDefs, imports, [type.toString()]);
return createDocComments(documentation).map((d): string => indent(6)(d)).join('\n') + return createDocComments(6, documentation) +
indent(6)(`${stringCamelCase(name.toString())}: AugmentedConst<${type}>;`); indent(6)(`${stringCamelCase(name.toString())}: AugmentedConst<${type}>;`);
})) }))
.concat([indent(4)('};')]); .concat([indent(4)('};')]);
} }
/** @internal */ /** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, object>>): void { function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, object>>, isStrict: boolean): void {
writeFile(dest, (): string => { writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, object>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes }; const allTypes: Record<string, Record<string, object>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes); const imports = createImports(allTypes);
@@ -40,7 +40,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<strin
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [key]: value }), defs); return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [key]: value }), defs);
}, {}); }, {});
const body = meta.asLatest.modules.reduce((acc, mod): string[] => { const body = meta.asLatest.modules.reduce((acc, mod): string[] => {
return acc.concat(generateModule(allDefs, mod, imports)); return acc.concat(generateModule(allDefs, mod, imports, isStrict));
}, [] as string[]); }, [] as string[]);
const header = createImportCode(HEADER, imports, [ const header = createImportCode(HEADER, imports, [
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({ ...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
@@ -49,7 +49,7 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<strin
})) }))
]); ]);
const interfaceStart = [ const interfaceStart = [
"declare module '@polkadot/metadata/Decorated/types' {", "declare module '@polkadot/metadata/Decorated/consts/types' {",
indent(2)('export interface Constants {\n') indent(2)('export interface Constants {\n')
].join('\n'); ].join('\n');
const interfaceEnd = `\n${indent(2)('}')}\n}`; const interfaceEnd = `\n${indent(2)('}')}\n}`;
@@ -64,8 +64,8 @@ function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<strin
// Call `generateForMeta()` with current static metadata // Call `generateForMeta()` with current static metadata
/** @internal */ /** @internal */
export default function generateConsts (dest = 'packages/api/src/types/augment/consts.ts', data = staticData, extraTypes: Record<string, Record<string, object>> = {}): void { export default function generateConsts (dest = 'packages/api/src/types/augment/consts.ts', data = staticData, extraTypes: Record<string, Record<string, object>> = {}, isStrict = false): void {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
return generateForMeta(new Metadata(registry, data), dest, extraTypes); return generateForMeta(new Metadata(registry, data), dest, extraTypes, isStrict);
} }
+7 -7
View File
@@ -68,24 +68,24 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor
// Generate types for one module // Generate types for one module
/** @internal */ /** @internal */
function generateModule (allDefs: object, registry: Registry, { name, storage }: ModuleMetadataLatest, imports: TypeImports): string[] { function generateModule (allDefs: object, registry: Registry, { name, storage }: ModuleMetadataLatest, imports: TypeImports, isStrict: boolean): string[] {
if (storage.isNone) { if (storage.isNone) {
return []; return [];
} }
return [indent(4)(`${stringLowerFirst(name.toString())}: {`)] return [indent(4)(`${stringLowerFirst(name.toString())}: {`)]
.concat(indent(6)('[index: string]: QueryableStorageEntry<ApiType>;')) .concat(isStrict ? '' : indent(6)('[index: string]: QueryableStorageEntry<ApiType>;'))
.concat(storage.unwrap().items.map((storageEntry): string => { .concat(storage.unwrap().items.map((storageEntry): string => {
const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports); const [args, returnType] = entrySignature(allDefs, registry, storageEntry, imports);
return createDocComments(storageEntry.documentation).map((d): string => indent(6)(d)).join('\n') + return createDocComments(6, storageEntry.documentation) +
indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: AugmentedQuery<ApiType, (${args}) => Observable<${returnType}>> & QueryableStorageEntry<ApiType>;`); indent(6)(`${stringLowerFirst(storageEntry.name.toString())}: AugmentedQuery<ApiType, (${args}) => Observable<${returnType}>> & QueryableStorageEntry<ApiType>;`);
})) }))
.concat([indent(4)('};')]); .concat([indent(4)('};')]);
} }
/** @internal */ /** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, object>>): void { function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, object>>, isStrict: boolean): void {
writeFile(dest, (): string => { writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, object>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes }; const allTypes: Record<string, Record<string, object>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes); const imports = createImports(allTypes);
@@ -93,7 +93,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [key]: value }), defs); return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [key]: value }), defs);
}, {}); }, {});
const body = meta.asLatest.modules.reduce((acc, mod): string[] => { const body = meta.asLatest.modules.reduce((acc, mod): string[] => {
return acc.concat(generateModule(allDefs, registry, mod, imports)); return acc.concat(generateModule(allDefs, registry, mod, imports, isStrict));
}, [] as string[]); }, [] as string[]);
const header = createImportCode(HEADER, imports, [ const header = createImportCode(HEADER, imports, [
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({ ...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
@@ -121,8 +121,8 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
// Call `generateForMeta()` with current static metadata // Call `generateForMeta()` with current static metadata
/** @internal */ /** @internal */
export default function generateQuery (dest = 'packages/api/src/types/augment/query.ts', data = staticData, extraTypes: Record<string, Record<string, object>> = {}): void { export default function generateQuery (dest = 'packages/api/src/types/augment/query.ts', data = staticData, extraTypes: Record<string, Record<string, object>> = {}, isStrict = false): void {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
return generateForMeta(registry, new Metadata(registry, data), dest, extraTypes); return generateForMeta(registry, new Metadata(registry, data), dest, extraTypes, isStrict);
} }
+2 -2
View File
@@ -5,7 +5,7 @@
import interfaces from '../../../../type-jsonrpc/src'; import interfaces from '../../../../type-jsonrpc/src';
import * as definitions from '../../interfaces/definitions'; import * as definitions from '../../interfaces/definitions';
import { TypeRegistry } from '../../codec/create'; import { TypeRegistry } from '../../codec/create';
import { FOOTER, HEADER, createImportCode, createImports, getSimilarTypes, setImports, writeFile } from '../util'; import { FOOTER, HEADER, createDocComments, createImportCode, createImports, getSimilarTypes, setImports, writeFile, indent } from '../util';
/** @internal */ /** @internal */
export default function generateRpcTypes (dest = 'packages/api/src/types/augment/rpc.ts'): void { export default function generateRpcTypes (dest = 'packages/api/src/types/augment/rpc.ts'): void {
@@ -35,7 +35,7 @@ export default function generateRpcTypes (dest = 'packages/api/src/types/augment
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`; return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
}); });
return ` /**\n * ${method.description}\n **/\n ${method.method}(${args.join(', ')}): Observable<${method.type}>;`; return createDocComments(6, [method.description]) + indent(6)(`${method.method}(${args.join(', ')}): Observable<${method.type}>;`);
}); });
return allSections.concat( return allSections.concat(
+22 -19
View File
@@ -26,7 +26,7 @@ function mapName (_name: Text): string {
// Generate types for one module // Generate types for one module
/** @internal */ /** @internal */
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
function generateModule (registry: Registry, allDefs: object, { calls, name }: ModuleMetadataLatest, imports: TypeImports): string[] { function generateModule (registry: Registry, allDefs: object, { calls, name }: ModuleMetadataLatest, imports: TypeImports, isStrict: boolean): string[] {
const allCalls = calls.unwrapOr(null); const allCalls = calls.unwrapOr(null);
if (!allCalls?.length) { if (!allCalls?.length) {
@@ -37,30 +37,33 @@ function generateModule (registry: Registry, allDefs: object, { calls, name }: M
// NOTE Not removing this concat yet, first see the fallout // NOTE Not removing this concat yet, first see the fallout
return [indent(4)(`${stringCamelCase(name.toString())}: {`)] return [indent(4)(`${stringCamelCase(name.toString())}: {`)]
.concat(indent(6)('[index: string]: SubmittableExtrinsicFunction<ApiType>;')) .concat(isStrict ? '' : indent(6)('[index: string]: SubmittableExtrinsicFunction<ApiType>;'))
.concat(allCalls.map(({ args, documentation, name }): string => { .concat(allCalls.map(({ args, documentation, name }): string => {
const params = args.map(({ name, type }): [string, string, string] => { const params = args
const typeStr = type.toString(); .map(({ name, type }): [string, string, string] => {
const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string => const typeStr = type.toString();
type.startsWith('(') || type.startsWith('{') const similarTypes = getSimilarTypes(allDefs, registry, typeStr, imports).map((type): string =>
? type type.startsWith('(') || type.startsWith('{')
: formatType(allDefs, type, imports) ? type
); : formatType(allDefs, type, imports)
const nameStr = mapName(name); );
const nameStr = mapName(name);
setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]); setImports(allDefs, imports, [...similarTypes.filter((type): boolean => !type.startsWith('(') && !type.startsWith('{')), typeStr]);
return [`${nameStr}: ${similarTypes.join(' | ')}`, nameStr, typeStr]; return [`${nameStr}: ${similarTypes.join(' | ')}`, nameStr, typeStr];
}); })
.map(([full]): string => full)
.join(', ');
return createDocComments(documentation).map((d): string => indent(6)(d)).join('\n') + return createDocComments(6, documentation) +
indent(6)(`${stringCamelCase(name.toString())}: AugmentedSubmittable<(${params.map(([full]): string => full).join(', ')}) => SubmittableExtrinsic<ApiType>>;`); indent(6)(`${stringCamelCase(name.toString())}: AugmentedSubmittable<(${params}) => SubmittableExtrinsic<ApiType>>;`);
})) }))
.concat([indent(4)('};')]); .concat([indent(4)('};')]);
} }
/** @internal */ /** @internal */
function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, object>>): void { function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: Record<string, Record<string, object>>, isStrict: boolean): void {
writeFile(dest, (): string => { writeFile(dest, (): string => {
const allTypes: Record<string, Record<string, object>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes }; const allTypes: Record<string, Record<string, object>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
const imports = createImports(allTypes); const imports = createImports(allTypes);
@@ -68,7 +71,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [key]: value }), defs); return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [key]: value }), defs);
}, {}); }, {});
const body = meta.asLatest.modules.reduce((acc, mod): string[] => { const body = meta.asLatest.modules.reduce((acc, mod): string[] => {
return acc.concat(generateModule(registry, allDefs, mod, imports)); return acc.concat(generateModule(registry, allDefs, mod, imports, isStrict));
}, [] as string[]); }, [] as string[]);
const header = createImportCode(HEADER, imports, [ const header = createImportCode(HEADER, imports, [
...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({ ...Object.keys(imports.localTypes).map((moduleName): { file: string; types: string[] } => ({
@@ -96,8 +99,8 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
// Call `generateForMeta()` with current static metadata // Call `generateForMeta()` with current static metadata
/** @internal */ /** @internal */
export default function generateTx (dest = 'packages/api/src/types/augment/tx.ts', data = staticData, extraTypes: Record<string, Record<string, object>> = {}): void { export default function generateTx (dest = 'packages/api/src/types/augment/tx.ts', data = staticData, extraTypes: Record<string, Record<string, object>> = {}, isStrict = false): void {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
return generateForMeta(registry, new Metadata(registry, data), dest, extraTypes); return generateForMeta(registry, new Metadata(registry, data), dest, extraTypes, isStrict);
} }
@@ -27,7 +27,7 @@ const generateConst = require('./generate/consts').default;
const generateQuery = require('./generate/query').default; const generateQuery = require('./generate/query').default;
const generateTx = require('./generate/tx').default; const generateTx = require('./generate/tx').default;
const { endpoint, output, package } = yargs.strict().options({ const { endpoint, output, package, strict: isStrict } = yargs.strict().options({
endpoint: { 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 file to JSON output',
type: 'string', type: 'string',
@@ -40,6 +40,10 @@ const { endpoint, output, package } = yargs.strict().options({
}, },
package: { package: {
description: 'Optional package in output location (for extra definitions)' description: 'Optional package in output location (for extra definitions)'
},
strinct: {
description: 'Turns on stirct mode, not outputting genric versions',
type: 'boolean'
} }
}).argv; }).argv;
let websocket = null; let websocket = null;
@@ -51,9 +55,9 @@ function generate (metaHex) {
? { [package]: require(path.join(process.cwd(), output, 'definitions')) } ? { [package]: require(path.join(process.cwd(), output, 'definitions')) }
: {}; : {};
generateConst(path.join(process.cwd(), output, 'augment.consts.ts'), metaHex, extraTypes); generateConst(path.join(process.cwd(), output, 'augment.consts.ts'), metaHex, extraTypes, isStrict);
generateQuery(path.join(process.cwd(), output, 'augment.query.ts'), metaHex, extraTypes); generateQuery(path.join(process.cwd(), output, 'augment.query.ts'), metaHex, extraTypes, isStrict);
generateTx(path.join(process.cwd(), output, 'augment.tx.ts'), metaHex, extraTypes); generateTx(path.join(process.cwd(), output, 'augment.tx.ts'), metaHex, extraTypes, isStrict);
process.exit(0); process.exit(0);
} }
+14 -4
View File
@@ -5,6 +5,7 @@
import { TypeDef, TypeDefInfo } from '../../codec/types'; import { TypeDef, TypeDefInfo } from '../../codec/types';
import { Constructor, Registry } from '../../types'; import { Constructor, Registry } from '../../types';
import { stringLowerFirst } from '@polkadot/util';
import { isChildClass, isCompactEncodable } from './class'; import { isChildClass, isCompactEncodable } from './class';
import { ClassOf, ClassOfUnsafe, getTypeDef } from '../../codec/create'; import { ClassOf, ClassOfUnsafe, getTypeDef } from '../../codec/create';
import AbstractInt from '../../codec/AbstractInt'; import AbstractInt from '../../codec/AbstractInt';
@@ -13,6 +14,7 @@ import Enum from '../../codec/Enum';
import Option from '../../codec/Option'; import Option from '../../codec/Option';
import Struct from '../../codec/Struct'; import Struct from '../../codec/Struct';
import Vec from '../../codec/Vec'; import Vec from '../../codec/Vec';
import Null from '../../primitive/Null';
import Vote, { convictionNames as _voteConvictions } from '../../primitive/Generic/Vote'; import Vote, { convictionNames as _voteConvictions } from '../../primitive/Generic/Vote';
import * as primitiveClasses from '../../primitive'; import * as primitiveClasses from '../../primitive';
import { formatType } from './formatting'; import { formatType } from './formatting';
@@ -94,19 +96,27 @@ export function getSimilarTypes (definitions: object, registry: Registry, type:
const e = new Clazz(registry) as Enum; const e = new Clazz(registry) as Enum;
if (e.isBasic) { if (e.isBasic) {
possibleTypes.push(arrayToStrType(e.defKeys), 'number', 'Uint8Array'); possibleTypes.push(arrayToStrType(e.defKeys), 'number');
} else { } else {
// TODO Handle this more gracefully (expand actual options) // TODO We don't really want any here, these should be expanded
possibleTypes.push('object', 'number', 'Uint8Array', 'string'); possibleTypes.push(...e.defKeys.map((key): string => `{ ${stringLowerFirst(key)}: any }`), 'string');
} }
possibleTypes.push('Uint8Array');
} else if (isChildClass(AbstractInt as unknown as Constructor<any>, Clazz) || isChildClass(Compact, Clazz)) { } else if (isChildClass(AbstractInt as unknown as Constructor<any>, Clazz) || isChildClass(Compact, Clazz)) {
possibleTypes.push('AnyNumber', 'Uint8Array'); possibleTypes.push('AnyNumber', 'Uint8Array');
} else if (isChildClass(ClassOf(registry, 'Address'), Clazz)) { } else if (isChildClass(ClassOf(registry, 'Address'), Clazz)) {
possibleTypes.push('string', 'AccountId', 'AccountIndex', 'Uint8Array'); possibleTypes.push('string', 'AccountId', 'AccountIndex', 'Uint8Array');
} else if (isChildClass(ClassOf(registry, 'bool'), Clazz)) { } else if (isChildClass(ClassOf(registry, 'bool'), Clazz)) {
possibleTypes.push('boolean', 'Uint8Array'); possibleTypes.push('boolean', 'Uint8Array');
} else if (isChildClass(Null, Clazz)) {
possibleTypes.push('null');
} else if (isChildClass(Struct, Clazz)) { } else if (isChildClass(Struct, Clazz)) {
possibleTypes.push('object', 'string', 'Uint8Array'); // TODO We don't really want any here, these should be expanded
const s = new Clazz(registry) as Struct;
const obj = s.defKeys.map((key): string => `${key}?: any`).join('; ');
possibleTypes.push(`{ ${obj} }`, 'string', 'Uint8Array');
} else if (isChildClass(Option, Clazz)) { } else if (isChildClass(Option, Clazz)) {
// TODO inspect container // TODO inspect container
possibleTypes.push('null', 'object', 'string', 'Uint8Array'); possibleTypes.push('null', 'object', 'string', 'Uint8Array');
+11 -6
View File
@@ -4,15 +4,20 @@
import { Text } from '@polkadot/types'; import { Text } from '@polkadot/types';
type Arg = [Text | string, Text | string]; import { indent } from './formatting';
export function createDocComments (docs: Text[], args: Arg[] = []): string[] { type AnyString = Text | string;
type Arg = [AnyString, AnyString];
export function createDocComments (spaces: number, docs: AnyString[], args: Arg[] = []): string {
const contents = [ const contents = [
...docs.map((doc): string => doc.toString().trim()).filter((doc): boolean => !!doc).map((doc): string => ` * ${doc}`), ...docs.map((doc): string => doc.toString().trim()).filter((doc): boolean => !!doc),
...args.map(([name, type]): string => ` * @param ${name} ${type}`) ...args.map(([name, type]): string => `@param ${name} ${type}`)
]; ].map((d): string => ` * ${d}`);
return contents.length return contents.length
? ['/**', ...contents, ' **/\n'] ? ['/**', ...contents, ' **/\n']
: []; .map((s): string => indent(spaces)(s))
.join('\n')
: '';
} }