@dedot/codegen 0.0.1-next.f1aed4d8.4 → 0.0.1-next.fecbe32d.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/cjs/generator/ConstsGen.js +3 -4
  2. package/cjs/generator/ErrorsGen.js +3 -4
  3. package/cjs/generator/EventsGen.js +3 -4
  4. package/cjs/generator/IndexGen.js +5 -6
  5. package/cjs/generator/JsonRpcGen.js +59 -0
  6. package/cjs/generator/QueryGen.js +18 -10
  7. package/cjs/generator/RuntimeApisGen.js +93 -19
  8. package/cjs/generator/TxGen.js +6 -6
  9. package/cjs/generator/TypeImports.js +8 -0
  10. package/cjs/generator/TypesGen.js +8 -15
  11. package/cjs/generator/index.js +1 -1
  12. package/cjs/generator/known-codecs.js +1 -1
  13. package/cjs/generator/utils.js +30 -1
  14. package/cjs/index.js +24 -24
  15. package/cjs/templates/index.hbs +2 -2
  16. package/cjs/templates/json-rpc.hbs +5 -0
  17. package/generator/ApiGen.d.ts +3 -3
  18. package/generator/ConstsGen.d.ts +1 -1
  19. package/generator/ConstsGen.js +3 -4
  20. package/generator/ErrorsGen.js +1 -2
  21. package/generator/EventsGen.js +1 -2
  22. package/generator/IndexGen.d.ts +2 -3
  23. package/generator/IndexGen.js +5 -6
  24. package/generator/{RpcGen.d.ts → JsonRpcGen.d.ts} +1 -4
  25. package/generator/JsonRpcGen.js +55 -0
  26. package/generator/QueryGen.d.ts +1 -1
  27. package/generator/QueryGen.js +18 -10
  28. package/generator/RuntimeApisGen.d.ts +4 -4
  29. package/generator/RuntimeApisGen.js +89 -15
  30. package/generator/TxGen.js +1 -1
  31. package/generator/TypeImports.d.ts +2 -0
  32. package/generator/TypeImports.js +8 -0
  33. package/generator/TypesGen.d.ts +1 -1
  34. package/generator/TypesGen.js +3 -10
  35. package/generator/index.d.ts +1 -1
  36. package/generator/index.js +1 -1
  37. package/generator/known-codecs.js +1 -1
  38. package/generator/utils.d.ts +5 -0
  39. package/generator/utils.js +28 -0
  40. package/index.d.ts +2 -3
  41. package/index.js +23 -23
  42. package/package.json +7 -8
  43. package/templates/index.hbs +2 -2
  44. package/templates/json-rpc.hbs +5 -0
  45. package/cjs/genSupportedChainTypes.js +0 -83
  46. package/cjs/generator/RpcGen.js +0 -176
  47. package/cjs/generator/known-types.js +0 -33
  48. package/cjs/packageInfo.js +0 -5
  49. package/cjs/templates/rpc.hbs +0 -7
  50. package/cjs/types.js +0 -2
  51. package/genSupportedChainTypes.d.ts +0 -1
  52. package/genSupportedChainTypes.js +0 -78
  53. package/generator/RpcGen.js +0 -172
  54. package/generator/known-types.d.ts +0 -6
  55. package/generator/known-types.js +0 -30
  56. package/packageInfo.d.ts +0 -4
  57. package/packageInfo.js +0 -2
  58. package/templates/rpc.hbs +0 -7
  59. package/types.d.ts +0 -6
  60. package/types.js +0 -1
package/cjs/index.js CHANGED
@@ -23,42 +23,42 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.generateTypes = exports.generateTypesFromChain = void 0;
26
+ exports.generateTypes = exports.generateTypesFromEndpoint = void 0;
27
+ const utils_1 = require("@dedot/utils");
27
28
  const dedot_1 = require("dedot");
28
29
  const fs = __importStar(require("fs"));
29
30
  const path = __importStar(require("path"));
30
31
  const index_js_1 = require("./generator/index.js");
31
- const util_1 = require("@polkadot/util");
32
- async function generateTypesFromChain(network, endpoint, outDir) {
33
- const api = await dedot_1.Dedot.create(endpoint);
34
- const { methods } = await api.rpc.rpc.methods();
35
- const apis = api.runtimeVersion?.apis || [];
36
- if (!network.chain) {
37
- network.chain = (0, util_1.stringCamelCase)(api.runtimeVersion?.specName || api.runtimeChain || 'local');
32
+ async function generateTypesFromEndpoint(chain, endpoint, outDir, extension = 'd.ts') {
33
+ const api = await dedot_1.Dedot.new(endpoint);
34
+ const { methods } = await api.rpc.rpc_methods();
35
+ const apis = api.runtimeVersion.apis || {};
36
+ if (!chain) {
37
+ chain = (0, utils_1.stringCamelCase)(api.runtimeVersion.specName || 'local');
38
38
  }
39
- await generateTypes(network, api.metadataLatest, methods, apis, outDir);
39
+ await generateTypes(chain, api.metadata.latest, methods, apis, outDir, extension);
40
40
  await api.disconnect();
41
41
  }
42
- exports.generateTypesFromChain = generateTypesFromChain;
43
- async function generateTypes(network, metadata, rpcMethods, runtimeApis, outDir = '.') {
44
- const dirPath = path.resolve(outDir, network.chain);
45
- const defTypesFileName = path.join(dirPath, `types.d.ts`);
46
- const constsTypesFileName = path.join(dirPath, `consts.d.ts`);
47
- const queryTypesFileName = path.join(dirPath, `query.d.ts`);
48
- const rpcCallsFileName = path.join(dirPath, `rpc.d.ts`);
49
- const indexFileName = path.join(dirPath, `index.d.ts`);
50
- const errorsFileName = path.join(dirPath, `errors.d.ts`);
51
- const eventsFileName = path.join(dirPath, `events.d.ts`);
52
- const runtimeApisFileName = path.join(dirPath, `runtime.d.ts`);
53
- const txFileName = path.join(dirPath, `tx.d.ts`);
42
+ exports.generateTypesFromEndpoint = generateTypesFromEndpoint;
43
+ async function generateTypes(chain, metadata, rpcMethods, runtimeApis, outDir = '.', extension = 'd.ts') {
44
+ const dirPath = path.resolve(outDir, chain);
45
+ const defTypesFileName = path.join(dirPath, `types.${extension}`);
46
+ const constsTypesFileName = path.join(dirPath, `consts.${extension}`);
47
+ const queryTypesFileName = path.join(dirPath, `query.${extension}`);
48
+ const jsonRpcFileName = path.join(dirPath, `json-rpc.${extension}`);
49
+ const indexFileName = path.join(dirPath, `index.${extension}`);
50
+ const errorsFileName = path.join(dirPath, `errors.${extension}`);
51
+ const eventsFileName = path.join(dirPath, `events.${extension}`);
52
+ const runtimeApisFileName = path.join(dirPath, `runtime.${extension}`);
53
+ const txFileName = path.join(dirPath, `tx.${extension}`);
54
54
  if (!fs.existsSync(dirPath)) {
55
55
  fs.mkdirSync(dirPath, { recursive: true });
56
56
  }
57
57
  const typesGen = new index_js_1.TypesGen(metadata);
58
58
  const constsGen = new index_js_1.ConstsGen(typesGen);
59
59
  const queryGen = new index_js_1.QueryGen(typesGen);
60
- const rpcGen = new index_js_1.RpcGen(typesGen, rpcMethods);
61
- const indexGen = new index_js_1.IndexGen(network);
60
+ const jsonRpcGen = new index_js_1.JsonRpcGen(typesGen, rpcMethods);
61
+ const indexGen = new index_js_1.IndexGen(chain);
62
62
  const errorsGen = new index_js_1.ErrorsGen(typesGen);
63
63
  const eventsGen = new index_js_1.EventsGen(typesGen);
64
64
  const runtimeApisGen = new index_js_1.RuntimeApisGen(typesGen, runtimeApis);
@@ -66,7 +66,7 @@ async function generateTypes(network, metadata, rpcMethods, runtimeApis, outDir
66
66
  fs.writeFileSync(defTypesFileName, await typesGen.generate());
67
67
  fs.writeFileSync(errorsFileName, await errorsGen.generate());
68
68
  fs.writeFileSync(eventsFileName, await eventsGen.generate());
69
- fs.writeFileSync(rpcCallsFileName, await rpcGen.generate());
69
+ fs.writeFileSync(jsonRpcFileName, await jsonRpcGen.generate());
70
70
  fs.writeFileSync(queryTypesFileName, await queryGen.generate());
71
71
  fs.writeFileSync(constsTypesFileName, await constsGen.generate());
72
72
  fs.writeFileSync(txFileName, await txGen.generate());
@@ -3,7 +3,7 @@
3
3
  import { GenericSubstrateApi } from '@dedot/types';
4
4
  import { ChainConsts } from './consts';
5
5
  import { ChainStorage } from './query';
6
- import { RpcCalls } from './rpc';
6
+ import { ChainJsonRpcApis } from './json-rpc';
7
7
  import { ChainErrors } from './errors';
8
8
  import { ChainEvents } from './events';
9
9
  import { RuntimeApis } from './runtime';
@@ -12,7 +12,7 @@ import { ChainTx } from './tx';
12
12
  export * from './types';
13
13
 
14
14
  export interface {{{interfaceName}}}Api extends GenericSubstrateApi {
15
- rpc: RpcCalls;
15
+ rpc: ChainJsonRpcApis;
16
16
  consts: ChainConsts;
17
17
  query: ChainStorage;
18
18
  errors: ChainErrors;
@@ -0,0 +1,5 @@
1
+ // Generated by @dedot/codegen
2
+
3
+ {{{ importTypes }}}
4
+
5
+ export type ChainJsonRpcApis = Pick<JsonRpcApis, {{{jsonRpcMethods}}}> & GenericJsonRpcApis;
@@ -13,14 +13,14 @@ export declare abstract class ApiGen {
13
13
  type: {
14
14
  tag: "Struct";
15
15
  value: {
16
- fields: import("@dedot/codecs").Field[];
16
+ fields: import("dedot").Field[];
17
17
  };
18
18
  } | {
19
19
  tag: "Enum";
20
20
  value: {
21
21
  members: {
22
22
  name: string;
23
- fields: import("@dedot/codecs").Field[];
23
+ fields: import("dedot").Field[];
24
24
  index: number;
25
25
  docs: string[];
26
26
  }[];
@@ -134,5 +134,5 @@ export declare abstract class ApiGen {
134
134
  }>;
135
135
  };
136
136
  };
137
- get registry(): import("@dedot/codecs").PortableRegistry;
137
+ get registry(): import("dedot").PortableRegistry;
138
138
  }
@@ -1,4 +1,4 @@
1
- import { ApiGen } from '../generator/index.js';
1
+ import { ApiGen } from './ApiGen.js';
2
2
  export declare class ConstsGen extends ApiGen {
3
3
  generate(): Promise<string>;
4
4
  }
@@ -1,6 +1,5 @@
1
- import { stringLowerFirst } from '@polkadot/util';
2
- import { normalizeName } from '@dedot/utils';
3
- import { ApiGen } from '../generator/index.js';
1
+ import { normalizeName, stringCamelCase } from '@dedot/utils';
2
+ import { ApiGen } from './ApiGen.js';
4
3
  import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
5
4
  export class ConstsGen extends ApiGen {
6
5
  generate() {
@@ -15,7 +14,7 @@ export class ConstsGen extends ApiGen {
15
14
  docs: one.docs,
16
15
  }));
17
16
  defTypeOut += commentBlock(`Pallet \`${pallet.name}\`'s constants`);
18
- defTypeOut += `${stringLowerFirst(pallet.name)}: {
17
+ defTypeOut += `${stringCamelCase(pallet.name)}: {
19
18
  ${typedConstants.map(({ name, type, docs }) => `${commentBlock(docs)}${name}: ${type}`).join(',\n')}
20
19
 
21
20
  ${commentBlock('Generic pallet constant')}[name: string]: any,
@@ -1,7 +1,6 @@
1
+ import { assert, stringCamelCase, stringPascalCase } from '@dedot/utils';
1
2
  import { ApiGen } from './ApiGen.js';
2
3
  import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
3
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
4
- import { assert } from '@dedot/utils';
5
4
  export class ErrorsGen extends ApiGen {
6
5
  generate() {
7
6
  const { pallets } = this.metadata;
@@ -1,7 +1,6 @@
1
+ import { assert, stringCamelCase, stringPascalCase } from '@dedot/utils';
1
2
  import { ApiGen } from './ApiGen.js';
2
3
  import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
3
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
4
- import { assert } from '@dedot/utils';
5
4
  export class EventsGen extends ApiGen {
6
5
  generate() {
7
6
  const { pallets } = this.metadata;
@@ -1,6 +1,5 @@
1
- import { NetworkInfo } from '../types.js';
2
1
  export declare class IndexGen {
3
- readonly networkInfo: NetworkInfo;
4
- constructor(networkInfo: NetworkInfo);
2
+ readonly chain: string;
3
+ constructor(chain: string);
5
4
  generate(): Promise<string>;
6
5
  }
@@ -1,13 +1,12 @@
1
+ import { stringPascalCase } from '@dedot/utils';
1
2
  import { beautifySourceCode, compileTemplate } from './utils.js';
2
- import { stringPascalCase } from '@polkadot/util';
3
3
  export class IndexGen {
4
- networkInfo;
5
- constructor(networkInfo) {
6
- this.networkInfo = networkInfo;
4
+ chain;
5
+ constructor(chain) {
6
+ this.chain = chain;
7
7
  }
8
8
  async generate() {
9
- const { chain } = this.networkInfo;
10
- const interfaceName = stringPascalCase(chain);
9
+ const interfaceName = stringPascalCase(this.chain);
11
10
  const template = compileTemplate('index.hbs');
12
11
  return beautifySourceCode(template({ interfaceName }));
13
12
  }
@@ -1,10 +1,7 @@
1
1
  import { ApiGen, TypesGen } from '../generator/index.js';
2
- export declare class RpcGen extends ApiGen {
3
- #private;
2
+ export declare class JsonRpcGen extends ApiGen {
4
3
  readonly typesGen: TypesGen;
5
4
  readonly rpcMethods: string[];
6
5
  constructor(typesGen: TypesGen, rpcMethods: string[]);
7
6
  generate(): Promise<string>;
8
- addTypeImport(type: string | string[], toTypeIn?: boolean): void;
9
- getGeneratedTypeName(type: string, toTypeIn?: boolean): string;
10
7
  }
@@ -0,0 +1,55 @@
1
+ import { subscriptionsInfo } from '@dedot/specs';
2
+ import { ApiGen } from '../generator/index.js';
3
+ import { beautifySourceCode, compileTemplate } from './utils.js';
4
+ const HIDDEN_RPCS = [
5
+ // Ref: https://github.com/paritytech/polkadot-sdk/blob/43415ef58c143b985e09015cd000dbd65f6d3997/substrate/client/rpc-servers/src/lib.rs#L152C9-L158
6
+ 'rpc_methods',
7
+ ];
8
+ const ALIAS_RPCS = [
9
+ // TODO include these into the specs
10
+ 'account_nextIndex',
11
+ 'system_dryRunAt',
12
+ 'state_callAt',
13
+ 'state_getKeysPagedAt',
14
+ 'state_getStorageAt',
15
+ 'state_getStorageHashAt',
16
+ 'state_getStorageSizeAt',
17
+ 'chain_getRuntimeVersion',
18
+ 'chain_getHead',
19
+ 'chain_getFinalisedHead',
20
+ 'childstate_getKeysPagedAt',
21
+ // Subscription pairs
22
+ 'chain_subscribeRuntimeVersion',
23
+ 'chain_unsubscribeRuntimeVersion',
24
+ 'chain_unsubscribeNewHead',
25
+ 'chain_subscribeNewHead',
26
+ 'subscribe_newHead',
27
+ 'unsubscribe_newHead',
28
+ 'chain_subscribeFinalisedHeads',
29
+ 'chain_unsubscribeFinalisedHeads',
30
+ ];
31
+ export class JsonRpcGen extends ApiGen {
32
+ typesGen;
33
+ rpcMethods;
34
+ constructor(typesGen, rpcMethods) {
35
+ super(typesGen);
36
+ this.typesGen = typesGen;
37
+ this.rpcMethods = rpcMethods;
38
+ HIDDEN_RPCS.filter((one) => !rpcMethods.includes(one)).forEach((one) => rpcMethods.push(one));
39
+ rpcMethods.sort();
40
+ }
41
+ generate() {
42
+ this.typesGen.clearCache();
43
+ this.typesGen.typeImports.addKnownType('GenericJsonRpcApis');
44
+ this.typesGen.typeImports.addSpecType('JsonRpcApis');
45
+ const toExclude = Object.values(subscriptionsInfo).flat();
46
+ const importTypes = this.typesGen.typeImports.toImports();
47
+ const template = compileTemplate('json-rpc.hbs');
48
+ const jsonRpcMethods = this.rpcMethods
49
+ .filter((one) => !ALIAS_RPCS.includes(one)) // exclude alias rpcs
50
+ .filter((one) => !toExclude.includes(one)) // exclude unsubscribe methods
51
+ .map((one) => `'${one}'`)
52
+ .join(' | ');
53
+ return beautifySourceCode(template({ importTypes, jsonRpcMethods }));
54
+ }
55
+ }
@@ -1,4 +1,4 @@
1
- import { ApiGen } from '../generator/index.js';
1
+ import { ApiGen } from './ApiGen.js';
2
2
  export declare class QueryGen extends ApiGen {
3
3
  #private;
4
4
  generate(): Promise<string>;
@@ -1,6 +1,5 @@
1
- import { stringLowerFirst } from '@polkadot/util';
2
- import { normalizeName } from '@dedot/utils';
3
- import { ApiGen } from '../generator/index.js';
1
+ import { normalizeName, stringCamelCase } from '@dedot/utils';
2
+ import { ApiGen } from './ApiGen.js';
4
3
  import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
5
4
  export class QueryGen extends ApiGen {
6
5
  generate() {
@@ -13,9 +12,16 @@ export class QueryGen extends ApiGen {
13
12
  if (!storage)
14
13
  continue;
15
14
  const queries = storage.entries.map((one) => this.#generateEntry(one));
16
- const queryDefs = queries.map(({ name, valueType, keyType, docs }) => `${commentBlock(docs)}${name}: GenericStorageQuery<(${keyType}) => ${valueType}>`);
15
+ const queryDefs = queries.map(({ name, valueType, keyType, docs, keyTypeOut }) => {
16
+ if (keyTypeOut) {
17
+ return `${commentBlock(docs)}${name}: GenericStorageQuery<(${keyType}) => ${valueType}, ${keyTypeOut}>`;
18
+ }
19
+ else {
20
+ return `${commentBlock(docs)}${name}: GenericStorageQuery<(${keyType}) => ${valueType}>`;
21
+ }
22
+ });
17
23
  defTypeOut += commentBlock(`Pallet \`${pallet.name}\`'s storage queries`);
18
- defTypeOut += `${stringLowerFirst(pallet.name)}: {
24
+ defTypeOut += `${stringCamelCase(pallet.name)}: {
19
25
  ${queryDefs.join(',\n')}
20
26
 
21
27
  ${commentBlock('Generic pallet storage query')}[storage: string]: GenericStorageQuery;
@@ -27,13 +33,14 @@ export class QueryGen extends ApiGen {
27
33
  }
28
34
  #generateEntry(entry) {
29
35
  const { name, type, docs, modifier } = entry;
30
- let valueType, keyType;
36
+ let valueType, keyTypeOut, keyTypeIn;
31
37
  if (type.tag === 'Plain') {
32
38
  valueType = this.typesGen.generateType(type.value.valueTypeId, 1, true);
33
39
  }
34
40
  else if (type.tag === 'Map') {
35
41
  valueType = this.typesGen.generateType(type.value.valueTypeId, 1, true);
36
- keyType = this.typesGen.generateType(type.value.keyTypeId, 1);
42
+ keyTypeOut = this.typesGen.generateType(type.value.keyTypeId, 1, true);
43
+ keyTypeIn = this.typesGen.generateType(type.value.keyTypeId, 1);
37
44
  }
38
45
  else {
39
46
  throw Error('Invalid entry type!');
@@ -41,14 +48,15 @@ export class QueryGen extends ApiGen {
41
48
  const isOptional = modifier === 'Optional';
42
49
  valueType = `${valueType}${isOptional ? ' | undefined' : ''}`;
43
50
  docs.push('\n');
44
- if (keyType) {
45
- docs.push(`@param {${keyType}} arg`);
51
+ if (keyTypeIn) {
52
+ docs.push(`@param {${keyTypeIn}} arg`);
46
53
  }
47
54
  docs.push(`@param {Callback<${valueType}> =} callback`);
48
55
  return {
49
56
  name: normalizeName(name),
50
57
  valueType,
51
- keyType: keyType ? `arg: ${keyType}` : '',
58
+ keyType: keyTypeIn ? `arg: ${keyTypeIn}` : '',
59
+ keyTypeOut,
52
60
  docs,
53
61
  };
54
62
  }
@@ -1,9 +1,9 @@
1
+ import { ApiGen } from './ApiGen.js';
1
2
  import { TypesGen } from './TypesGen.js';
2
- import { RpcGen } from './RpcGen.js';
3
- export declare class RuntimeApisGen extends RpcGen {
3
+ export declare class RuntimeApisGen extends ApiGen {
4
4
  #private;
5
5
  readonly typesGen: TypesGen;
6
- readonly runtimeApis: [string, number][];
7
- constructor(typesGen: TypesGen, runtimeApis: [string, number][]);
6
+ readonly runtimeApis: Record<string, number>;
7
+ constructor(typesGen: TypesGen, runtimeApis: Record<string, number>);
8
8
  generate(): Promise<string>;
9
9
  }
@@ -1,13 +1,13 @@
1
1
  import { getRuntimeApiNames, getRuntimeApiSpecs } from '@dedot/specs';
2
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
3
- import { calculateRuntimeApiHash, stringSnakeCase } from '@dedot/utils';
4
- import { RpcGen } from './RpcGen.js';
5
- import { stringCamelCase } from '@polkadot/util';
6
- export class RuntimeApisGen extends RpcGen {
2
+ import { calcRuntimeApiHash, stringSnakeCase, stringCamelCase } from '@dedot/utils';
3
+ import { ApiGen } from './ApiGen.js';
4
+ import { findKnownCodecType } from './known-codecs.js';
5
+ import { beautifySourceCode, commentBlock, compileTemplate, isNativeType, TUPLE_TYPE_REGEX, WRAPPER_TYPE_REGEX, } from './utils.js';
6
+ export class RuntimeApisGen extends ApiGen {
7
7
  typesGen;
8
8
  runtimeApis;
9
9
  constructor(typesGen, runtimeApis) {
10
- super(typesGen, []);
10
+ super(typesGen);
11
11
  this.typesGen = typesGen;
12
12
  this.runtimeApis = runtimeApis;
13
13
  }
@@ -18,7 +18,7 @@ export class RuntimeApisGen extends RpcGen {
18
18
  if (this.metadata.apis.length > 0) {
19
19
  this.metadata.apis.forEach((runtimeApi) => {
20
20
  const { name: runtimeApiName, methods } = runtimeApi;
21
- runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calculateRuntimeApiHash(runtimeApiName)}`);
21
+ runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calcRuntimeApiHash(runtimeApiName)}`);
22
22
  runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
23
23
  ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
24
24
 
@@ -57,17 +57,17 @@ export class RuntimeApisGen extends RpcGen {
57
57
  const { docs = [], params, type, runtimeApiName, methodName } = spec;
58
58
  const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
59
59
  const defaultDocs = [`@callname: ${callName}`];
60
- this.addTypeImport(type, false);
61
- params.forEach(({ type }) => this.addTypeImport(type));
60
+ this.#addTypeImport(type, false);
61
+ params.forEach(({ type }) => this.#addTypeImport(type));
62
62
  const typedParams = params.map((param, idx) => ({
63
63
  ...param,
64
64
  isOptional: this.#isOptionalParam(params, param.type, idx),
65
- plainType: this.getGeneratedTypeName(param.type),
65
+ plainType: this.#getGeneratedTypeName(param.type),
66
66
  }));
67
67
  const paramsOut = typedParams
68
68
  .map(({ name, isOptional, plainType }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${plainType}`)
69
69
  .join(', ');
70
- const typeOut = this.getGeneratedTypeName(type, false);
70
+ const typeOut = this.#getGeneratedTypeName(type, false);
71
71
  return `${commentBlock(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
72
72
  }
73
73
  #generateMethodDef(runtimeApiName, methodDef) {
@@ -75,7 +75,7 @@ export class RuntimeApisGen extends RpcGen {
75
75
  const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
76
76
  const defaultDocs = [`@callname: ${callName}`];
77
77
  const typeOut = this.typesGen.generateType(output, 1, true);
78
- this.addTypeImport(typeOut, false);
78
+ this.#addTypeImport(typeOut, false);
79
79
  const typedInputs = inputs
80
80
  .map((input, idx) => ({
81
81
  ...input,
@@ -85,14 +85,14 @@ export class RuntimeApisGen extends RpcGen {
85
85
  ...input,
86
86
  isOptional: this.#isOptionalParam(inputs, input.type, idx),
87
87
  }));
88
- this.addTypeImport(typedInputs.map((t) => t.type));
88
+ this.#addTypeImport(typedInputs.map((t) => t.type));
89
89
  const paramsOut = typedInputs
90
90
  .map(({ name, type, isOptional }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${type}`)
91
91
  .join(', ');
92
92
  return `${commentBlock(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${stringCamelCase(methodName)}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
93
93
  }
94
94
  #targetRuntimeApiSpecs() {
95
- const specs = this.runtimeApis.map(([runtimeApiHash, version]) => {
95
+ const specs = Object.entries(this.runtimeApis).map(([runtimeApiHash, version]) => {
96
96
  const runtimeApiSpec = this.#findRuntimeApiSpec(runtimeApiHash, version);
97
97
  if (!runtimeApiSpec)
98
98
  return;
@@ -109,7 +109,81 @@ export class RuntimeApisGen extends RpcGen {
109
109
  }, []);
110
110
  }
111
111
  #findRuntimeApiSpec = (runtimeApiHash, version) => {
112
- const runtimeApiName = getRuntimeApiNames().find((one) => calculateRuntimeApiHash(one) === runtimeApiHash);
112
+ const runtimeApiName = getRuntimeApiNames().find((one) => calcRuntimeApiHash(one) === runtimeApiHash);
113
113
  return getRuntimeApiSpecs().find((one) => one.runtimeApiName === runtimeApiName && one.version === version);
114
114
  };
115
+ // TODO check typeIn, typeOut if param type, or rpc type isScale
116
+ #addTypeImport(type, toTypeIn = true) {
117
+ if (Array.isArray(type)) {
118
+ type.forEach((one) => this.#addTypeImport(one, toTypeIn));
119
+ return;
120
+ }
121
+ type = type.trim();
122
+ if (isNativeType(type)) {
123
+ return;
124
+ }
125
+ // Handle generic wrapper types
126
+ const matchArray = type.match(WRAPPER_TYPE_REGEX);
127
+ if (matchArray) {
128
+ const [_, $1, $2] = matchArray;
129
+ this.#addTypeImport($1, toTypeIn);
130
+ if ($2.match(WRAPPER_TYPE_REGEX) || $2.match(TUPLE_TYPE_REGEX)) {
131
+ this.#addTypeImport($2, toTypeIn);
132
+ }
133
+ else {
134
+ this.#addTypeImport($2.split(','), toTypeIn);
135
+ }
136
+ return;
137
+ }
138
+ // Check tuple type
139
+ if (type.match(TUPLE_TYPE_REGEX)) {
140
+ this.#addTypeImport(type.slice(1, -1).split(','), toTypeIn);
141
+ return;
142
+ }
143
+ if (type.includes(' | ')) {
144
+ this.#addTypeImport(type.split(' | ').map((one) => one.trim()), toTypeIn);
145
+ return;
146
+ }
147
+ try {
148
+ const codecType = this.#getCodecType(type, toTypeIn);
149
+ if (isNativeType(codecType))
150
+ return;
151
+ this.typesGen.typeImports.addCodecType(codecType);
152
+ return;
153
+ }
154
+ catch (e) { }
155
+ this.typesGen.addTypeImport(type);
156
+ }
157
+ #getGeneratedTypeName(type, toTypeIn = true) {
158
+ try {
159
+ const matchArray = type.match(WRAPPER_TYPE_REGEX);
160
+ if (matchArray) {
161
+ const [_, $1, $2] = matchArray;
162
+ const wrapperTypeName = this.#getCodecType($1, toTypeIn);
163
+ if ($2.match(WRAPPER_TYPE_REGEX) || $2.match(TUPLE_TYPE_REGEX)) {
164
+ return `${wrapperTypeName}<${this.#getGeneratedTypeName($2, toTypeIn)}>`;
165
+ }
166
+ const innerTypeNames = $2
167
+ .split(',')
168
+ .map((one) => this.#getGeneratedTypeName(one.trim(), toTypeIn))
169
+ .join(', ');
170
+ return `${wrapperTypeName}<${innerTypeNames}>`;
171
+ }
172
+ else if (type.match(TUPLE_TYPE_REGEX)) {
173
+ const innerTypeNames = type
174
+ .slice(1, -1)
175
+ .split(',')
176
+ .map((one) => this.#getGeneratedTypeName(one.trim(), toTypeIn))
177
+ .join(', ');
178
+ return `[${innerTypeNames}]`;
179
+ }
180
+ return this.#getCodecType(type, toTypeIn);
181
+ }
182
+ catch (e) { }
183
+ return type;
184
+ }
185
+ #getCodecType(type, toTypeIn = true) {
186
+ const { typeIn, typeOut } = findKnownCodecType(type);
187
+ return toTypeIn ? typeIn : typeOut;
188
+ }
115
189
  }
@@ -1,5 +1,5 @@
1
+ import { stringCamelCase, stringPascalCase } from '@dedot/utils';
1
2
  import { ApiGen } from '../generator/index.js';
2
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
3
3
  import { beautifySourceCode, commentBlock, compileTemplate, isReservedWord } from './utils.js';
4
4
  export class TxGen extends ApiGen {
5
5
  generate() {
@@ -3,6 +3,7 @@ export declare class TypeImports {
3
3
  portableTypes: Set<string>;
4
4
  codecTypes: Set<string>;
5
5
  knownTypes: Set<string>;
6
+ specTypes: Set<string>;
6
7
  outTypes: Set<string>;
7
8
  constructor();
8
9
  clear(): void;
@@ -10,5 +11,6 @@ export declare class TypeImports {
10
11
  addPortableType(...types: string[]): void;
11
12
  addCodecType(...types: string[]): void;
12
13
  addKnownType(...types: string[]): void;
14
+ addSpecType(...types: string[]): void;
13
15
  addOutType(...types: string[]): void;
14
16
  }
@@ -5,30 +5,35 @@ export class TypeImports {
5
5
  codecTypes;
6
6
  // Known types that're not codecs or chain/portable types defined in @dedot/types
7
7
  knownTypes;
8
+ specTypes;
8
9
  // External types to define explicitly
9
10
  outTypes;
10
11
  constructor() {
11
12
  this.portableTypes = new Set();
12
13
  this.codecTypes = new Set();
13
14
  this.knownTypes = new Set();
15
+ this.specTypes = new Set();
14
16
  this.outTypes = new Set();
15
17
  }
16
18
  clear() {
17
19
  this.portableTypes.clear();
18
20
  this.codecTypes.clear();
19
21
  this.knownTypes.clear();
22
+ this.specTypes.clear();
20
23
  this.outTypes.clear();
21
24
  }
22
25
  toImports(...excludeModules) {
23
26
  // TODO generate outTypes!
24
27
  const toImports = [
25
28
  [this.knownTypes, '@dedot/types'],
29
+ [this.specTypes, '@dedot/specs'],
26
30
  [this.codecTypes, '@dedot/codecs'],
27
31
  [this.portableTypes, './types'],
28
32
  ];
29
33
  return toImports
30
34
  .filter(([_, module]) => !excludeModules.includes(module))
31
35
  .map(([types, module]) => this.#toImportLine(types, module))
36
+ .filter((line) => line.length > 0)
32
37
  .join('\n');
33
38
  }
34
39
  #toImportLine(types, module) {
@@ -46,6 +51,9 @@ export class TypeImports {
46
51
  addKnownType(...types) {
47
52
  types.forEach((one) => this.knownTypes.add(one));
48
53
  }
54
+ addSpecType(...types) {
55
+ types.forEach((one) => this.specTypes.add(one));
56
+ }
49
57
  addOutType(...types) {
50
58
  types.forEach((one) => this.outTypes.add(one));
51
59
  }
@@ -1,4 +1,4 @@
1
- import { PortableRegistry, Field, MetadataLatest, PortableType, TypeId } from '@dedot/codecs';
1
+ import { Field, MetadataLatest, PortableRegistry, PortableType, TypeId } from '@dedot/codecs';
2
2
  import { TypeImports } from './TypeImports.js';
3
3
  interface NamedType extends PortableType {
4
4
  name: string;
@@ -1,10 +1,8 @@
1
- import { stringPascalCase } from '@polkadot/util';
2
1
  import { PortableRegistry } from '@dedot/codecs';
3
- import { isNativeType, normalizeName } from '@dedot/utils';
4
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
5
- import { knownTypes } from './known-types.js';
2
+ import { normalizeName, stringPascalCase } from '@dedot/utils';
6
3
  import { TypeImports } from './TypeImports.js';
7
4
  import { findKnownCodec, findKnownCodecType, isKnownCodecType } from './known-codecs.js';
5
+ import { beautifySourceCode, commentBlock, compileTemplate, isNativeType } from './utils.js';
8
6
  // Skip generate types for these
9
7
  // as we do have native types for them
10
8
  const SKIP_TYPES = [
@@ -423,11 +421,6 @@ export class TypesGen {
423
421
  this.typeImports.addCodecType(typeName);
424
422
  return;
425
423
  }
426
- if (knownTypes.includes(typeName)) {
427
- this.typeImports.addKnownType(typeName);
428
- }
429
- else {
430
- this.typeImports.addOutType(typeName);
431
- }
424
+ this.typeImports.addOutType(typeName);
432
425
  }
433
426
  }
@@ -2,7 +2,7 @@ export * from './TypesGen.js';
2
2
  export * from './ApiGen.js';
3
3
  export * from './ConstsGen.js';
4
4
  export * from './QueryGen.js';
5
- export * from './RpcGen.js';
5
+ export * from './JsonRpcGen.js';
6
6
  export * from './IndexGen.js';
7
7
  export * from './ErrorsGen.js';
8
8
  export * from './EventsGen.js';
@@ -2,7 +2,7 @@ export * from './TypesGen.js';
2
2
  export * from './ApiGen.js';
3
3
  export * from './ConstsGen.js';
4
4
  export * from './QueryGen.js';
5
- export * from './RpcGen.js';
5
+ export * from './JsonRpcGen.js';
6
6
  export * from './IndexGen.js';
7
7
  export * from './ErrorsGen.js';
8
8
  export * from './EventsGen.js';
@@ -1,6 +1,6 @@
1
- import * as $ from '@dedot/shape';
2
1
  import * as Codecs from '@dedot/codecs';
3
2
  import { $AccountId20, $AccountId32, $Bytes, $ConsensusEngineId, $Era, $EthereumAddress, $MultiAddress, $OpaqueExtrinsic, $PrefixedStorageKey, $RawBytes, $StorageData, $StorageKey, $UncheckedExtrinsic, } from '@dedot/codecs';
3
+ import * as $ from '@dedot/shape';
4
4
  import { assert } from '@dedot/utils';
5
5
  export const normalizeCodecName = (name) => {
6
6
  return name.startsWith('$') ? name : `$${name}`;