@dedot/codegen 0.0.1-next.9dacef43.1 → 0.0.1-next.a5b1d2fb.22

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 (154) hide show
  1. package/{generator → chaintypes/generator}/ApiGen.d.ts +2 -2
  2. package/chaintypes/generator/ConstsGen.d.ts +4 -0
  3. package/{generator → chaintypes/generator}/ConstsGen.js +8 -9
  4. package/chaintypes/generator/ErrorsGen.d.ts +5 -0
  5. package/{generator → chaintypes/generator}/ErrorsGen.js +9 -10
  6. package/chaintypes/generator/EventsGen.d.ts +5 -0
  7. package/{generator → chaintypes/generator}/EventsGen.js +9 -10
  8. package/chaintypes/generator/IndexGen.d.ts +5 -0
  9. package/chaintypes/generator/IndexGen.js +17 -0
  10. package/chaintypes/generator/JsonRpcGen.d.ts +8 -0
  11. package/chaintypes/generator/JsonRpcGen.js +55 -0
  12. package/chaintypes/generator/QueryGen.d.ts +5 -0
  13. package/{generator → chaintypes/generator}/QueryGen.js +24 -16
  14. package/chaintypes/generator/RuntimeApisGen.d.ts +9 -0
  15. package/chaintypes/generator/RuntimeApisGen.js +189 -0
  16. package/chaintypes/generator/TxGen.d.ts +5 -0
  17. package/{generator → chaintypes/generator}/TxGen.js +14 -12
  18. package/chaintypes/generator/TypesGen.d.ts +11 -0
  19. package/chaintypes/generator/TypesGen.js +55 -0
  20. package/chaintypes/generator/index.d.ts +10 -0
  21. package/chaintypes/generator/index.js +10 -0
  22. package/chaintypes/index.d.ts +3 -0
  23. package/chaintypes/index.js +49 -0
  24. package/chaintypes/templates/consts.hbs +7 -0
  25. package/chaintypes/templates/errors.hbs +7 -0
  26. package/chaintypes/templates/events.hbs +7 -0
  27. package/chaintypes/templates/index.hbs +27 -0
  28. package/chaintypes/templates/json-rpc.hbs +5 -0
  29. package/chaintypes/templates/query.hbs +7 -0
  30. package/chaintypes/templates/runtime.hbs +8 -0
  31. package/chaintypes/templates/tx.hbs +9 -0
  32. package/{cjs → chaintypes}/templates/types.hbs +1 -1
  33. package/cjs/{generator → chaintypes/generator}/ConstsGen.js +12 -13
  34. package/cjs/chaintypes/generator/ErrorsGen.js +40 -0
  35. package/cjs/{generator → chaintypes/generator}/EventsGen.js +16 -17
  36. package/cjs/chaintypes/generator/IndexGen.js +21 -0
  37. package/cjs/chaintypes/generator/JsonRpcGen.js +59 -0
  38. package/cjs/{generator → chaintypes/generator}/QueryGen.js +26 -18
  39. package/cjs/chaintypes/generator/RuntimeApisGen.js +193 -0
  40. package/cjs/{generator → chaintypes/generator}/TxGen.js +23 -21
  41. package/cjs/chaintypes/generator/TypesGen.js +59 -0
  42. package/cjs/chaintypes/generator/index.js +26 -0
  43. package/cjs/chaintypes/index.js +76 -0
  44. package/cjs/chaintypes/templates/consts.hbs +7 -0
  45. package/cjs/chaintypes/templates/errors.hbs +7 -0
  46. package/cjs/chaintypes/templates/events.hbs +7 -0
  47. package/cjs/chaintypes/templates/index.hbs +27 -0
  48. package/cjs/chaintypes/templates/json-rpc.hbs +5 -0
  49. package/cjs/chaintypes/templates/query.hbs +7 -0
  50. package/cjs/chaintypes/templates/runtime.hbs +8 -0
  51. package/cjs/chaintypes/templates/tx.hbs +9 -0
  52. package/{templates → cjs/chaintypes/templates}/types.hbs +1 -1
  53. package/cjs/{generator/dirname.js → dirname.js} +0 -1
  54. package/cjs/index.js +4 -62
  55. package/cjs/{generator/TypesGen.js → shared/BaseTypesGen.js} +102 -160
  56. package/cjs/{generator → shared}/TypeImports.js +29 -3
  57. package/cjs/{generator → shared}/index.js +3 -10
  58. package/cjs/shared/known-codecs.js +170 -0
  59. package/cjs/typink/generator/ConstructorQueryGen.js +24 -0
  60. package/cjs/typink/generator/ConstructorTxGen.js +24 -0
  61. package/cjs/typink/generator/IndexGen.js +24 -0
  62. package/cjs/typink/generator/QueryGen.js +72 -0
  63. package/cjs/typink/generator/TxGen.js +25 -0
  64. package/cjs/typink/generator/TypesGen.js +35 -0
  65. package/cjs/typink/generator/index.js +22 -0
  66. package/cjs/typink/index.js +36 -0
  67. package/cjs/typink/templates/constructor-query.hbs +7 -0
  68. package/cjs/typink/templates/constructor-tx.hbs +7 -0
  69. package/cjs/typink/templates/index.hbs +14 -0
  70. package/cjs/typink/templates/query.hbs +7 -0
  71. package/cjs/typink/templates/tx.hbs +7 -0
  72. package/cjs/typink/templates/types.hbs +5 -0
  73. package/cjs/{generator/utils.js → utils.js} +34 -5
  74. package/index.d.ts +2 -4
  75. package/index.js +2 -48
  76. package/package.json +16 -18
  77. package/{generator/TypesGen.d.ts → shared/BaseTypesGen.d.ts} +13 -12
  78. package/{generator/TypesGen.js → shared/BaseTypesGen.js} +89 -147
  79. package/{generator → shared}/TypeImports.d.ts +12 -1
  80. package/{generator → shared}/TypeImports.js +29 -3
  81. package/shared/index.d.ts +3 -0
  82. package/shared/index.js +3 -0
  83. package/shared/known-codecs.d.ts +23 -0
  84. package/shared/known-codecs.js +139 -0
  85. package/typink/generator/ConstructorQueryGen.d.ts +6 -0
  86. package/typink/generator/ConstructorQueryGen.js +20 -0
  87. package/typink/generator/ConstructorTxGen.d.ts +6 -0
  88. package/typink/generator/ConstructorTxGen.js +20 -0
  89. package/typink/generator/IndexGen.d.ts +6 -0
  90. package/typink/generator/IndexGen.js +20 -0
  91. package/typink/generator/QueryGen.d.ts +12 -0
  92. package/typink/generator/QueryGen.js +68 -0
  93. package/typink/generator/TxGen.d.ts +6 -0
  94. package/typink/generator/TxGen.js +21 -0
  95. package/typink/generator/TypesGen.d.ts +8 -0
  96. package/typink/generator/TypesGen.js +31 -0
  97. package/typink/generator/index.d.ts +6 -0
  98. package/typink/generator/index.js +6 -0
  99. package/typink/index.d.ts +2 -0
  100. package/typink/index.js +30 -0
  101. package/typink/templates/constructor-query.hbs +7 -0
  102. package/typink/templates/constructor-tx.hbs +7 -0
  103. package/typink/templates/index.hbs +14 -0
  104. package/typink/templates/query.hbs +7 -0
  105. package/typink/templates/tx.hbs +7 -0
  106. package/typink/templates/types.hbs +5 -0
  107. package/{generator/utils.d.ts → utils.d.ts} +6 -1
  108. package/{generator/utils.js → utils.js} +32 -4
  109. package/cjs/genSupportedChainTypes.js +0 -79
  110. package/cjs/generator/ErrorsGen.js +0 -41
  111. package/cjs/generator/IndexGen.js +0 -18
  112. package/cjs/generator/RpcGen.js +0 -175
  113. package/cjs/generator/RuntimeApisGen.js +0 -115
  114. package/cjs/packageInfo.js +0 -5
  115. package/cjs/templates/consts.hbs +0 -7
  116. package/cjs/templates/errors.hbs +0 -7
  117. package/cjs/templates/events.hbs +0 -7
  118. package/cjs/templates/index.hbs +0 -22
  119. package/cjs/templates/query.hbs +0 -7
  120. package/cjs/templates/rpc.hbs +0 -7
  121. package/cjs/templates/runtime.hbs +0 -8
  122. package/cjs/templates/tx.hbs +0 -9
  123. package/cjs/types.js +0 -2
  124. package/genSupportedChainTypes.d.ts +0 -1
  125. package/genSupportedChainTypes.js +0 -74
  126. package/generator/ConstsGen.d.ts +0 -4
  127. package/generator/ErrorsGen.d.ts +0 -5
  128. package/generator/EventsGen.d.ts +0 -5
  129. package/generator/IndexGen.d.ts +0 -6
  130. package/generator/IndexGen.js +0 -14
  131. package/generator/QueryGen.d.ts +0 -5
  132. package/generator/RpcGen.d.ts +0 -10
  133. package/generator/RpcGen.js +0 -171
  134. package/generator/RuntimeApisGen.d.ts +0 -9
  135. package/generator/RuntimeApisGen.js +0 -111
  136. package/generator/TxGen.d.ts +0 -5
  137. package/generator/index.d.ts +0 -10
  138. package/generator/index.js +0 -10
  139. package/packageInfo.d.ts +0 -4
  140. package/packageInfo.js +0 -2
  141. package/templates/consts.hbs +0 -7
  142. package/templates/errors.hbs +0 -7
  143. package/templates/events.hbs +0 -7
  144. package/templates/index.hbs +0 -22
  145. package/templates/query.hbs +0 -7
  146. package/templates/rpc.hbs +0 -7
  147. package/templates/runtime.hbs +0 -8
  148. package/templates/tx.hbs +0 -9
  149. package/types.d.ts +0 -6
  150. package/types.js +0 -1
  151. /package/{generator → chaintypes/generator}/ApiGen.js +0 -0
  152. /package/cjs/{generator → chaintypes/generator}/ApiGen.js +0 -0
  153. /package/{generator/dirname.d.ts → dirname.d.ts} +0 -0
  154. /package/{generator/dirname.js → dirname.js} +0 -0
@@ -1,4 +1,4 @@
1
- import { TypesGen } from '../generator';
1
+ import { TypesGen } from './TypesGen.js';
2
2
  export declare abstract class ApiGen {
3
3
  readonly typesGen: TypesGen;
4
4
  constructor(typesGen: TypesGen);
@@ -134,5 +134,5 @@ export declare abstract class ApiGen {
134
134
  }>;
135
135
  };
136
136
  };
137
- get registry(): import("@dedot/codecs").CodecRegistry;
137
+ get registry(): import("@dedot/codecs").PortableRegistry;
138
138
  }
@@ -0,0 +1,4 @@
1
+ import { ApiGen } from './ApiGen.js';
2
+ export declare class ConstsGen extends ApiGen {
3
+ generate(useSubPaths?: boolean): Promise<string>;
4
+ }
@@ -1,12 +1,11 @@
1
- import { stringLowerFirst } from '@polkadot/util';
2
- import { normalizeName } from '@dedot/utils';
3
- import { ApiGen } from '../generator';
4
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils';
1
+ import { normalizeName, stringCamelCase } from '@dedot/utils';
2
+ import { beautifySourceCode, commentBlock, compileTemplate } from '../../utils.js';
3
+ import { ApiGen } from './ApiGen.js';
5
4
  export class ConstsGen extends ApiGen {
6
- generate() {
5
+ generate(useSubPaths = false) {
7
6
  const { pallets } = this.metadata;
8
7
  this.typesGen.clearCache();
9
- this.typesGen.typeImports.addKnownType('GenericChainConsts');
8
+ this.typesGen.typeImports.addKnownType('GenericChainConsts', 'RpcVersion');
10
9
  let defTypeOut = '';
11
10
  for (let pallet of pallets) {
12
11
  const typedConstants = pallet.constants.map((one) => ({
@@ -15,14 +14,14 @@ 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,
22
21
  },`;
23
22
  }
24
- const importTypes = this.typesGen.typeImports.toImports();
25
- const template = compileTemplate('consts.hbs');
23
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
24
+ const template = compileTemplate('chaintypes/templates/consts.hbs');
26
25
  return beautifySourceCode(template({ importTypes, defTypeOut }));
27
26
  }
28
27
  }
@@ -0,0 +1,5 @@
1
+ import { ApiGen } from './ApiGen.js';
2
+ export declare class ErrorsGen extends ApiGen {
3
+ #private;
4
+ generate(useSubPaths?: boolean): Promise<string>;
5
+ }
@@ -1,12 +1,11 @@
1
- import { ApiGen } from './ApiGen';
2
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils';
3
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
4
- import { assert } from '@dedot/utils';
1
+ import { assert, stringCamelCase, stringPascalCase } from '@dedot/utils';
2
+ import { beautifySourceCode, commentBlock, compileTemplate } from '../../utils.js';
3
+ import { ApiGen } from './ApiGen.js';
5
4
  export class ErrorsGen extends ApiGen {
6
- generate() {
5
+ generate(useSubPaths = false) {
7
6
  const { pallets } = this.metadata;
8
7
  this.typesGen.clearCache();
9
- this.typesGen.typeImports.addKnownType('GenericChainErrors', 'GenericPalletError');
8
+ this.typesGen.typeImports.addKnownType('GenericChainErrors', 'GenericPalletError', 'RpcVersion');
10
9
  let defTypeOut = '';
11
10
  for (let pallet of pallets) {
12
11
  const errorTypeId = pallet.error;
@@ -17,14 +16,14 @@ export class ErrorsGen extends ApiGen {
17
16
  defTypeOut += commentBlock(`Pallet \`${pallet.name}\`'s errors`);
18
17
  defTypeOut += `${stringCamelCase(pallet.name)}: {
19
18
  ${errorDefs
20
- .map(({ name, docs }) => `${commentBlock(docs)}${stringPascalCase(name)}: GenericPalletError`)
19
+ .map(({ name, docs }) => `${commentBlock(docs)}${stringPascalCase(name)}: GenericPalletError<Rv>`)
21
20
  .join(',\n')}
22
21
 
23
- ${commentBlock('Generic pallet error')}[error: string]: GenericPalletError,
22
+ ${commentBlock('Generic pallet error')}[error: string]: GenericPalletError<Rv>,
24
23
  },`;
25
24
  }
26
- const importTypes = this.typesGen.typeImports.toImports();
27
- const template = compileTemplate('errors.hbs');
25
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
26
+ const template = compileTemplate('chaintypes/templates/errors.hbs');
28
27
  return beautifySourceCode(template({ importTypes, defTypeOut }));
29
28
  }
30
29
  #getErrorDefs(errorTypeId) {
@@ -0,0 +1,5 @@
1
+ import { ApiGen } from './ApiGen.js';
2
+ export declare class EventsGen extends ApiGen {
3
+ #private;
4
+ generate(useSubPaths?: boolean): Promise<string>;
5
+ }
@@ -1,12 +1,11 @@
1
- import { ApiGen } from './ApiGen';
2
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils';
3
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
4
- import { assert } from '@dedot/utils';
1
+ import { assert, stringCamelCase, stringPascalCase } from '@dedot/utils';
2
+ import { beautifySourceCode, commentBlock, compileTemplate } from '../../utils.js';
3
+ import { ApiGen } from './ApiGen.js';
5
4
  export class EventsGen extends ApiGen {
6
- generate() {
5
+ generate(useSubPaths = false) {
7
6
  const { pallets } = this.metadata;
8
7
  this.typesGen.clearCache();
9
- this.typesGen.typeImports.addKnownType('GenericChainEvents', 'GenericPalletEvent');
8
+ this.typesGen.typeImports.addKnownType('GenericChainEvents', 'GenericPalletEvent', 'RpcVersion');
10
9
  let defTypeOut = '';
11
10
  for (let pallet of pallets) {
12
11
  const eventTypeId = pallet.event;
@@ -29,14 +28,14 @@ export class EventsGen extends ApiGen {
29
28
  }
30
29
  return { ...def, genericParts };
31
30
  })
32
- .map(({ name, docs, fields, genericParts }) => `${commentBlock(docs)}${stringPascalCase(name)}: GenericPalletEvent<${genericParts.join(', ')}>`)
31
+ .map(({ name, docs, fields, genericParts }) => `${commentBlock(docs)}${stringPascalCase(name)}: GenericPalletEvent<Rv, ${genericParts.join(', ')}>`)
33
32
  .join(',\n')}
34
33
 
35
- ${commentBlock('Generic pallet event')}[prop: string]: GenericPalletEvent,
34
+ ${commentBlock('Generic pallet event')}[prop: string]: GenericPalletEvent<Rv>,
36
35
  },`;
37
36
  }
38
- const importTypes = this.typesGen.typeImports.toImports();
39
- const template = compileTemplate('events.hbs');
37
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
38
+ const template = compileTemplate('chaintypes/templates/events.hbs');
40
39
  return beautifySourceCode(template({ importTypes, defTypeOut }));
41
40
  }
42
41
  #getEventDefs(typeId) {
@@ -0,0 +1,5 @@
1
+ export declare class IndexGen {
2
+ readonly chain: string;
3
+ constructor(chain: string);
4
+ generate(useSubPaths?: boolean): Promise<string>;
5
+ }
@@ -0,0 +1,17 @@
1
+ import { stringPascalCase } from '@dedot/utils';
2
+ import { TypeImports } from '../../shared/index.js';
3
+ import { beautifySourceCode, compileTemplate } from '../../utils.js';
4
+ export class IndexGen {
5
+ chain;
6
+ constructor(chain) {
7
+ this.chain = chain;
8
+ }
9
+ async generate(useSubPaths = false) {
10
+ const interfaceName = stringPascalCase(this.chain);
11
+ const typeImports = new TypeImports();
12
+ typeImports.addKnownType('GenericSubstrateApi', 'RpcLegacy', 'RpcV2', 'RpcVersion');
13
+ const importTypes = typeImports.toImports({ useSubPaths });
14
+ const template = compileTemplate('chaintypes/templates/index.hbs');
15
+ return beautifySourceCode(template({ importTypes, interfaceName }));
16
+ }
17
+ }
@@ -0,0 +1,8 @@
1
+ import { ApiGen } from './ApiGen.js';
2
+ import { TypesGen } from './TypesGen.js';
3
+ export declare class JsonRpcGen extends ApiGen {
4
+ readonly typesGen: TypesGen;
5
+ readonly rpcMethods: string[];
6
+ constructor(typesGen: TypesGen, rpcMethods: string[]);
7
+ generate(useSubPaths?: boolean): Promise<string>;
8
+ }
@@ -0,0 +1,55 @@
1
+ import { subscriptionsInfo } from '@dedot/api';
2
+ import { beautifySourceCode, compileTemplate } from '../../utils.js';
3
+ import { ApiGen } from './ApiGen.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(useSubPaths = false) {
42
+ this.typesGen.clearCache();
43
+ this.typesGen.typeImports.addKnownType('GenericJsonRpcApis', 'RpcVersion');
44
+ this.typesGen.typeImports.addKnownJsonRpcType('JsonRpcApis');
45
+ const toExclude = Object.values(subscriptionsInfo).flat();
46
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
47
+ const template = compileTemplate('chaintypes/templates/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
+ }
@@ -0,0 +1,5 @@
1
+ import { ApiGen } from './ApiGen.js';
2
+ export declare class QueryGen extends ApiGen {
3
+ #private;
4
+ generate(useSubPaths?: boolean): Promise<string>;
5
+ }
@@ -1,39 +1,46 @@
1
- import { stringLowerFirst } from '@polkadot/util';
2
- import { normalizeName } from '@dedot/utils';
3
- import { ApiGen } from '../generator';
4
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils';
1
+ import { normalizeName, stringCamelCase } from '@dedot/utils';
2
+ import { beautifySourceCode, commentBlock, compileTemplate } from '../../utils.js';
3
+ import { ApiGen } from './ApiGen.js';
5
4
  export class QueryGen extends ApiGen {
6
- generate() {
5
+ generate(useSubPaths = false) {
7
6
  const { pallets } = this.metadata;
8
7
  this.typesGen.clearCache();
9
- this.typesGen.typeImports.addKnownType('GenericChainStorage', 'GenericStorageQuery', 'Callback');
8
+ this.typesGen.typeImports.addKnownType('GenericChainStorage', 'GenericStorageQuery', 'Callback', 'RpcVersion');
10
9
  let defTypeOut = '';
11
10
  for (let pallet of pallets) {
12
11
  const storage = pallet.storage;
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<Rv, (${keyType}) => ${valueType}, ${keyTypeOut}>`;
18
+ }
19
+ else {
20
+ return `${commentBlock(docs)}${name}: GenericStorageQuery<Rv, (${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
- ${commentBlock('Generic pallet storage query')}[storage: string]: GenericStorageQuery;
27
+ ${commentBlock('Generic pallet storage query')}[storage: string]: GenericStorageQuery<Rv>;
22
28
  },`;
23
29
  }
24
- const importTypes = this.typesGen.typeImports.toImports();
25
- const template = compileTemplate('query.hbs');
30
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
31
+ const template = compileTemplate('chaintypes/templates/query.hbs');
26
32
  return beautifySourceCode(template({ importTypes, defTypeOut }));
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
  }
@@ -0,0 +1,9 @@
1
+ import { ApiGen } from './ApiGen.js';
2
+ import { TypesGen } from './TypesGen.js';
3
+ export declare class RuntimeApisGen extends ApiGen {
4
+ #private;
5
+ readonly typesGen: TypesGen;
6
+ readonly runtimeApis: Record<string, number>;
7
+ constructor(typesGen: TypesGen, runtimeApis: Record<string, number>);
8
+ generate(useSubPaths?: boolean): Promise<string>;
9
+ }
@@ -0,0 +1,189 @@
1
+ import { getRuntimeApiNames, getRuntimeApiSpecs } from '@dedot/runtime-specs';
2
+ import { calcRuntimeApiHash, stringSnakeCase, stringCamelCase } from '@dedot/utils';
3
+ import { findKnownCodecType } from '../../shared/index.js';
4
+ import { beautifySourceCode, commentBlock, compileTemplate, isNativeType, TUPLE_TYPE_REGEX, WRAPPER_TYPE_REGEX, } from '../../utils.js';
5
+ import { ApiGen } from './ApiGen.js';
6
+ export class RuntimeApisGen extends ApiGen {
7
+ typesGen;
8
+ runtimeApis;
9
+ constructor(typesGen, runtimeApis) {
10
+ super(typesGen);
11
+ this.typesGen = typesGen;
12
+ this.runtimeApis = runtimeApis;
13
+ }
14
+ generate(useSubPaths = false) {
15
+ this.typesGen.clearCache();
16
+ this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod', 'RpcVersion');
17
+ let runtimeCallsOut = '';
18
+ if (this.metadata.apis.length > 0) {
19
+ this.metadata.apis.forEach((runtimeApi) => {
20
+ const { name: runtimeApiName, methods } = runtimeApi;
21
+ runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calcRuntimeApiHash(runtimeApiName)}`);
22
+ runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
23
+ ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
24
+
25
+ ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod<Rv>
26
+ }`;
27
+ });
28
+ }
29
+ else {
30
+ const specs = this.#targetRuntimeApiSpecs();
31
+ specs.forEach(({ methods, runtimeApiName, runtimeApiHash, version }) => {
32
+ runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${runtimeApiHash}`, `@version: ${version}`);
33
+ runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
34
+ ${Object.keys(methods)
35
+ .map((methodName) => this.#generateMethodDefFromSpec({
36
+ ...methods[methodName],
37
+ runtimeApiName,
38
+ methodName,
39
+ }))
40
+ .join('\n')}
41
+
42
+ ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod<Rv>
43
+ }`;
44
+ });
45
+ }
46
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
47
+ const template = compileTemplate('chaintypes/templates/runtime.hbs');
48
+ return beautifySourceCode(template({ importTypes, runtimeCallsOut }));
49
+ }
50
+ #isOptionalType(type) {
51
+ return type.startsWith('Option<') || type.endsWith('| undefined');
52
+ }
53
+ #isOptionalParam(params, type, idx) {
54
+ return this.#isOptionalType(type) && params.slice(idx + 1).every(({ type }) => this.#isOptionalType(type));
55
+ }
56
+ #generateMethodDefFromSpec(spec) {
57
+ const { docs = [], params, type, runtimeApiName, methodName } = spec;
58
+ const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
59
+ const defaultDocs = [`@callname: ${callName}`];
60
+ this.#addTypeImport(type, false);
61
+ params.forEach(({ type }) => this.#addTypeImport(type));
62
+ const typedParams = params.map((param, idx) => ({
63
+ ...param,
64
+ isOptional: this.#isOptionalParam(params, param.type, idx),
65
+ plainType: this.#getGeneratedTypeName(param.type),
66
+ }));
67
+ const paramsOut = typedParams
68
+ .map(({ name, isOptional, plainType }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${plainType}`)
69
+ .join(', ');
70
+ const typeOut = this.#getGeneratedTypeName(type, false);
71
+ return `${commentBlock(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<Rv, (${paramsOut}) => Promise<${typeOut}>>`;
72
+ }
73
+ #generateMethodDef(runtimeApiName, methodDef) {
74
+ const { name: methodName, inputs, output, docs } = methodDef;
75
+ const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
76
+ const defaultDocs = [`@callname: ${callName}`];
77
+ const typeOut = this.typesGen.generateType(output, 1, true);
78
+ this.#addTypeImport(typeOut, false);
79
+ const typedInputs = inputs
80
+ .map((input, idx) => ({
81
+ ...input,
82
+ type: this.typesGen.generateType(input.typeId, 1),
83
+ }))
84
+ .map((input, idx, inputs) => ({
85
+ ...input,
86
+ isOptional: this.#isOptionalParam(inputs, input.type, idx),
87
+ }));
88
+ this.#addTypeImport(typedInputs.map((t) => t.type));
89
+ const paramsOut = typedInputs
90
+ .map(({ name, type, isOptional }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${type}`)
91
+ .join(', ');
92
+ return `${commentBlock(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${stringCamelCase(methodName)}: GenericRuntimeApiMethod<Rv, (${paramsOut}) => Promise<${typeOut}>>`;
93
+ }
94
+ #targetRuntimeApiSpecs() {
95
+ const specs = Object.entries(this.runtimeApis).map(([runtimeApiHash, version]) => {
96
+ const runtimeApiSpec = this.#findRuntimeApiSpec(runtimeApiHash, version);
97
+ if (!runtimeApiSpec)
98
+ return;
99
+ return {
100
+ ...runtimeApiSpec,
101
+ runtimeApiHash,
102
+ };
103
+ });
104
+ return specs.reduce((o, spec) => {
105
+ if (!spec) {
106
+ return o;
107
+ }
108
+ return [...o, spec];
109
+ }, []);
110
+ }
111
+ #findRuntimeApiSpec = (runtimeApiHash, version) => {
112
+ const runtimeApiName = getRuntimeApiNames().find((one) => calcRuntimeApiHash(one) === runtimeApiHash);
113
+ return getRuntimeApiSpecs().find((one) => one.runtimeApiName === runtimeApiName && one.version === version);
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
+ }
189
+ }
@@ -0,0 +1,5 @@
1
+ import { ApiGen } from '../generator/index.js';
2
+ export declare class TxGen extends ApiGen {
3
+ #private;
4
+ generate(useSubPaths?: boolean): Promise<string>;
5
+ }
@@ -1,11 +1,11 @@
1
- import { ApiGen } from '../generator';
2
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
3
- import { beautifySourceCode, commentBlock, compileTemplate, isReservedWord } from './utils';
1
+ import { stringCamelCase, stringPascalCase } from '@dedot/utils';
2
+ import { beautifySourceCode, commentBlock, compileTemplate, isReservedWord } from '../../utils.js';
3
+ import { ApiGen } from '../generator/index.js';
4
4
  export class TxGen extends ApiGen {
5
- generate() {
5
+ generate(useSubPaths = false) {
6
6
  const { pallets, types } = this.metadata;
7
7
  this.typesGen.clearCache();
8
- this.typesGen.typeImports.addKnownType('GenericChainTx', 'GenericTxCall', 'ISubmittableExtrinsic', 'ISubmittableResult', 'IRuntimeTxCall');
8
+ this.typesGen.typeImports.addKnownType('GenericChainTx', 'GenericTxCall', 'ISubmittableExtrinsic', 'ISubmittableResult', 'IRuntimeTxCall', 'RpcVersion', 'RpcV2', 'ISubmittableExtrinsicLegacy', 'TransactionStatusLegacy', 'TransactionStatusV2');
9
9
  const { callTypeId, addressTypeId, signatureTypeId } = this.metadata.extrinsic;
10
10
  const callTypeIn = this.typesGen.generateType(callTypeId, 1);
11
11
  const addressTypeIn = this.typesGen.generateType(addressTypeId, 1);
@@ -41,22 +41,24 @@ export class TxGen extends ApiGen {
41
41
  txDefsOut += commentBlock(`Pallet \`${pallet.name}\`'s transaction calls`);
42
42
  txDefsOut += `${stringCamelCase(pallet.name)}: {
43
43
  ${typedTxs
44
- .map(({ functionName, params, docs, callInput }) => `${commentBlock(docs, '\n', params.map((p) => `@param {${p.type}} ${p.normalizedName} ${p.docs}`))}${functionName}: GenericTxCall<(${params.map((p) => `${p.normalizedName}: ${p.type}`).join(', ')}) => ChainSubmittableExtrinsic<${callInput}>>`)
44
+ .map(({ functionName, params, docs, callInput }) => `${commentBlock(docs, '\n', params.map((p) => `@param {${p.type}} ${p.normalizedName} ${p.docs}`))}${functionName}: GenericTxCall<Rv, (${params.map((p) => `${p.normalizedName}: ${p.type}`).join(', ')}) => ChainSubmittableExtrinsic<Rv, ${callInput}>>`)
45
45
  .join(',\n')}
46
46
 
47
- ${commentBlock('Generic pallet tx call')}[callName: string]: GenericTxCall<TxCall>,
47
+ ${commentBlock('Generic pallet tx call')}[callName: string]: GenericTxCall<Rv, TxCall<Rv>>,
48
48
  },`;
49
49
  }
50
- const importTypes = this.typesGen.typeImports.toImports();
50
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
51
51
  // TODO make explicit separate type for Extra
52
52
  const defTypes = `
53
- export type ChainSubmittableExtrinsic<T extends IRuntimeTxCall = ${callTypeIn}> =
53
+ export type ChainSubmittableExtrinsic<Rv extends RpcVersion, T extends IRuntimeTxCall = ${callTypeIn}> =
54
54
  Extrinsic<${addressTypeIn}, T, ${signatureTypeIn}, any[]> &
55
- ISubmittableExtrinsic<ISubmittableResult<FrameSystemEventRecord>>
55
+ (Rv extends RpcV2
56
+ ? ISubmittableExtrinsic<ISubmittableResult<FrameSystemEventRecord, TransactionStatusV2>>
57
+ : ISubmittableExtrinsicLegacy<ISubmittableResult<FrameSystemEventRecord, TransactionStatusLegacy>>)
56
58
 
57
- export type TxCall = (...args: any[]) => ChainSubmittableExtrinsic;
59
+ export type TxCall<Rv extends RpcVersion> = (...args: any[]) => ChainSubmittableExtrinsic<Rv>;
58
60
  `;
59
- const template = compileTemplate('tx.hbs');
61
+ const template = compileTemplate('chaintypes/templates/tx.hbs');
60
62
  return beautifySourceCode(template({ importTypes, defTypes, txDefsOut }));
61
63
  }
62
64
  #normalizeParamName(name) {
@@ -0,0 +1,11 @@
1
+ import { MetadataLatest, PortableRegistry, TypeId } from '@dedot/codecs';
2
+ import { EnumOptions } from '@dedot/shape';
3
+ import { BaseTypesGen } from '../../shared/index.js';
4
+ export declare class TypesGen extends BaseTypesGen {
5
+ metadata: MetadataLatest;
6
+ registry: PortableRegistry;
7
+ constructor(metadata: MetadataLatest);
8
+ generate(useSubPaths?: boolean): Promise<string>;
9
+ shouldGenerateTypeIn(id: TypeId): boolean;
10
+ getEnumOptions(typeId: TypeId): EnumOptions;
11
+ }
@@ -0,0 +1,55 @@
1
+ import { PortableRegistry } from '@dedot/codecs';
2
+ import { BaseTypesGen } from '../../shared/index.js';
3
+ import { beautifySourceCode, commentBlock, compileTemplate } from '../../utils.js';
4
+ // Skip generate types for these
5
+ // as we do have native types for them
6
+ const SKIP_TYPES = [
7
+ 'BoundedBTreeMap',
8
+ 'BoundedBTreeSet',
9
+ 'BoundedVec',
10
+ 'Box',
11
+ 'BTreeMap',
12
+ 'BTreeSet',
13
+ 'Cow',
14
+ 'Option',
15
+ 'Range',
16
+ 'RangeInclusive',
17
+ 'Result',
18
+ 'WeakBoundedVec',
19
+ 'WrapperKeepOpaque',
20
+ 'WrapperOpaque',
21
+ ];
22
+ export class TypesGen extends BaseTypesGen {
23
+ metadata;
24
+ registry;
25
+ constructor(metadata) {
26
+ super(metadata.types);
27
+ this.metadata = metadata;
28
+ this.skipTypes = SKIP_TYPES;
29
+ this.registry = new PortableRegistry(this.metadata);
30
+ this.includedTypes = this.includeTypes();
31
+ }
32
+ generate(useSubPaths = false) {
33
+ this.clearCache();
34
+ let defTypeOut = '';
35
+ Object.values(this.includedTypes)
36
+ .filter(({ skip, knownType }) => !(skip || knownType))
37
+ .forEach(({ name, nameOut, id, docs }) => {
38
+ defTypeOut += `${commentBlock(docs)}export type ${nameOut} = ${this.generateType(id, 0, true)};\n\n`;
39
+ if (this.shouldGenerateTypeIn(id)) {
40
+ defTypeOut += `export type ${name} = ${this.generateType(id)};\n\n`;
41
+ }
42
+ });
43
+ const importTypes = this.typeImports.toImports({ excludeModules: ['./types'], useSubPaths });
44
+ const template = compileTemplate('chaintypes/templates/types.hbs');
45
+ return beautifySourceCode(template({ importTypes, defTypeOut }));
46
+ }
47
+ shouldGenerateTypeIn(id) {
48
+ const { callTypeId } = this.metadata.extrinsic;
49
+ const palletCallTypeIds = this.registry.getPalletCallTypeIds();
50
+ return callTypeId === id || palletCallTypeIds.includes(id);
51
+ }
52
+ getEnumOptions(typeId) {
53
+ return this.registry.getEnumOptions(typeId);
54
+ }
55
+ }