@dedot/codegen 0.0.1-next.8d06d348.17 → 0.0.1-next.8f4b2c24.6

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 (66) hide show
  1. package/cjs/generator/ConstsGen.js +9 -10
  2. package/cjs/generator/ErrorsGen.js +12 -13
  3. package/cjs/generator/EventsGen.js +13 -14
  4. package/cjs/generator/IndexGen.js +8 -9
  5. package/cjs/generator/JsonRpcGen.js +59 -0
  6. package/cjs/generator/QueryGen.js +23 -15
  7. package/cjs/generator/RuntimeApisGen.js +102 -28
  8. package/cjs/generator/TxGen.js +15 -15
  9. package/cjs/generator/TypeImports.js +8 -0
  10. package/cjs/generator/TypesGen.js +23 -32
  11. package/cjs/generator/index.js +10 -10
  12. package/cjs/{helpers/KnownCodecRegistry.js → generator/known-codecs.js} +56 -68
  13. package/cjs/generator/utils.js +30 -1
  14. package/cjs/index.js +32 -32
  15. package/cjs/templates/index.hbs +2 -2
  16. package/cjs/templates/json-rpc.hbs +5 -0
  17. package/generator/ApiGen.d.ts +4 -4
  18. package/generator/ConstsGen.d.ts +1 -1
  19. package/generator/ConstsGen.js +4 -5
  20. package/generator/ErrorsGen.d.ts +1 -1
  21. package/generator/ErrorsGen.js +3 -4
  22. package/generator/EventsGen.d.ts +1 -1
  23. package/generator/EventsGen.js +3 -4
  24. package/generator/IndexGen.d.ts +2 -3
  25. package/generator/IndexGen.js +6 -7
  26. package/generator/JsonRpcGen.d.ts +7 -0
  27. package/generator/JsonRpcGen.js +55 -0
  28. package/generator/QueryGen.d.ts +1 -1
  29. package/generator/QueryGen.js +19 -11
  30. package/generator/RuntimeApisGen.d.ts +5 -5
  31. package/generator/RuntimeApisGen.js +89 -15
  32. package/generator/TxGen.d.ts +1 -1
  33. package/generator/TxGen.js +3 -3
  34. package/generator/TypeImports.d.ts +2 -0
  35. package/generator/TypeImports.js +8 -0
  36. package/generator/TypesGen.d.ts +3 -5
  37. package/generator/TypesGen.js +12 -21
  38. package/generator/index.d.ts +10 -10
  39. package/generator/index.js +10 -10
  40. package/{helpers/KnownCodecRegistry.d.ts → generator/known-codecs.d.ts} +11 -10
  41. package/generator/known-codecs.js +120 -0
  42. package/generator/utils.d.ts +5 -0
  43. package/generator/utils.js +28 -0
  44. package/index.d.ts +2 -3
  45. package/index.js +23 -23
  46. package/package.json +7 -8
  47. package/templates/index.hbs +2 -2
  48. package/templates/json-rpc.hbs +5 -0
  49. package/cjs/genSupportedChainTypes.js +0 -79
  50. package/cjs/generator/RpcGen.js +0 -175
  51. package/cjs/helpers/index.js +0 -17
  52. package/cjs/packageInfo.js +0 -5
  53. package/cjs/templates/rpc.hbs +0 -7
  54. package/cjs/types.js +0 -2
  55. package/genSupportedChainTypes.d.ts +0 -1
  56. package/genSupportedChainTypes.js +0 -74
  57. package/generator/RpcGen.d.ts +0 -10
  58. package/generator/RpcGen.js +0 -171
  59. package/helpers/KnownCodecRegistry.js +0 -135
  60. package/helpers/index.d.ts +0 -1
  61. package/helpers/index.js +0 -1
  62. package/packageInfo.d.ts +0 -4
  63. package/packageInfo.js +0 -2
  64. package/templates/rpc.hbs +0 -7
  65. package/types.d.ts +0 -14
  66. package/types.js +0 -1
@@ -0,0 +1,120 @@
1
+ import * as $ from '@dedot/shape';
2
+ import * as Codecs from '@dedot/codecs';
3
+ import { $AccountId20, $AccountId32, $Bytes, $ConsensusEngineId, $Era, $EthereumAddress, $MultiAddress, $OpaqueExtrinsic, $PrefixedStorageKey, $RawBytes, $StorageData, $StorageKey, $UncheckedExtrinsic, } from '@dedot/codecs';
4
+ import { assert } from '@dedot/utils';
5
+ export const normalizeCodecName = (name) => {
6
+ return name.startsWith('$') ? name : `$${name}`;
7
+ };
8
+ // Known paths for codecs (primitives) that are shared between
9
+ // different substrate-based blockchains
10
+ const KNOWN_PATHS = [
11
+ 'sp_core::crypto::AccountId32',
12
+ 'sp_runtime::generic::era::Era',
13
+ 'sp_runtime::multiaddress::MultiAddress',
14
+ /^sp_runtime::DispatchError$/,
15
+ 'sp_runtime::ModuleError',
16
+ 'sp_runtime::TokenError',
17
+ 'sp_arithmetic::ArithmeticError',
18
+ 'sp_runtime::TransactionalError',
19
+ 'frame_support::dispatch::DispatchInfo',
20
+ 'frame_system::Phase',
21
+ 'sp_version::RuntimeVersion',
22
+ 'fp_account::AccountId20',
23
+ 'account::AccountId20',
24
+ 'polkadot_runtime_common::claims::EthereumAddress',
25
+ 'pallet_identity::types::Data',
26
+ 'sp_runtime::generic::digest::Digest',
27
+ 'sp_runtime::generic::digest::DigestItem',
28
+ 'sp_runtime::generic::header::Header',
29
+ 'sp_runtime::generic::unchecked_extrinsic::UncheckedExtrinsic',
30
+ /^primitive_types::\w+$/,
31
+ /^sp_arithmetic::per_things::\w+$/,
32
+ /^sp_arithmetic::fixed_point::\w+$/,
33
+ ];
34
+ const WRAPPER_TYPE_REGEX = /^(\w+)<(.*)>$/;
35
+ const TUPLE_TYPE_REGEX = /^\[(.*)]$/;
36
+ const KNOWN_WRAPPER_TYPES = ['Option', 'Vec', 'Result', 'Array'];
37
+ /**
38
+ * Collection of codec types with loose input types
39
+ *
40
+ * Loose codecs are codecs with different typeIn & typeOut,
41
+ * E.g: Codec `$AccountId32`, we have its typeIn is `AccountId32Like` & typeOut is `AccountId32`
42
+ *
43
+ * This registry keep track the list of codecs which follow this convention
44
+ */
45
+ export const looseTypeCodecs = {
46
+ $AccountId20,
47
+ $EthereumAddress,
48
+ $AccountId32,
49
+ $ConsensusEngineId,
50
+ $StorageKey,
51
+ $StorageData,
52
+ $PrefixedStorageKey,
53
+ $Bytes,
54
+ $RawBytes,
55
+ $MultiAddress,
56
+ $OpaqueExtrinsic,
57
+ $UncheckedExtrinsic,
58
+ $Era,
59
+ };
60
+ export function findKnownCodecType(name) {
61
+ const normalizedName = normalizeCodecName(name);
62
+ const $knownCodec = looseTypeCodecs[normalizedName];
63
+ if ($knownCodec) {
64
+ return {
65
+ name: normalizedName,
66
+ $codec: $knownCodec,
67
+ typeIn: `${name}Like`,
68
+ typeOut: name,
69
+ };
70
+ }
71
+ const $codec = findKnownCodec(name);
72
+ if ($codec.nativeType && $[name]) {
73
+ return {
74
+ name: normalizedName,
75
+ $codec,
76
+ typeIn: $codec.nativeType,
77
+ typeOut: $codec.nativeType,
78
+ };
79
+ }
80
+ return {
81
+ name: normalizedName,
82
+ $codec,
83
+ typeIn: name,
84
+ typeOut: name,
85
+ };
86
+ }
87
+ export function findKnownCodec(typeName) {
88
+ // @ts-ignore
89
+ const $codec = findKnownWrapperCodec(typeName) || Codecs[normalizeCodecName(typeName)] || $[typeName];
90
+ assert($codec, `Known codec not found - ${typeName}`);
91
+ return $codec;
92
+ }
93
+ export function findKnownWrapperCodec(typeName) {
94
+ const matchNames = typeName.match(WRAPPER_TYPE_REGEX);
95
+ if (matchNames) {
96
+ const [_, wrapper, inner] = matchNames;
97
+ if (KNOWN_WRAPPER_TYPES.includes(wrapper)) {
98
+ // @ts-ignore
99
+ const $Wrapper = $[wrapper];
100
+ if (inner.match(TUPLE_TYPE_REGEX) || inner.match(WRAPPER_TYPE_REGEX)) {
101
+ return $Wrapper(findKnownWrapperCodec(inner));
102
+ }
103
+ const $inners = inner.split(',').map((one) => findKnownCodec(one.trim()));
104
+ return $Wrapper(...$inners);
105
+ }
106
+ throw new Error(`Unknown wrapper type ${wrapper} from ${typeName}`);
107
+ }
108
+ else if (typeName.match(TUPLE_TYPE_REGEX)) {
109
+ const $inner = typeName
110
+ .slice(1, -1)
111
+ .split(',')
112
+ .filter((x) => x)
113
+ .map((one) => findKnownCodec(one.trim()));
114
+ return $.Tuple(...$inner);
115
+ }
116
+ }
117
+ export function isKnownCodecType(path) {
118
+ const joinedPath = Array.isArray(path) ? path.join('::') : path;
119
+ return KNOWN_PATHS.some((one) => joinedPath.match(one));
120
+ }
@@ -8,3 +8,8 @@ export declare const compileTemplate: (templateFileName: string) => HandlebarsTe
8
8
  * @param word
9
9
  */
10
10
  export declare const isReservedWord: (word: string) => boolean;
11
+ /**
12
+ * Check if a type is native JS/TS type
13
+ * @param type
14
+ */
15
+ export declare const isNativeType: (type: string) => boolean;
@@ -33,3 +33,31 @@ const TS_RESERVED_WORDS = ['new', 'class'];
33
33
  * @param word
34
34
  */
35
35
  export const isReservedWord = (word) => TS_RESERVED_WORDS.includes(word);
36
+ const TS_PRIMITIVE_TYPES = [
37
+ 'void',
38
+ 'undefined',
39
+ 'null',
40
+ 'number',
41
+ 'boolean',
42
+ 'bigint',
43
+ 'Map',
44
+ 'Set',
45
+ 'string',
46
+ 'any',
47
+ 'Array',
48
+ 'Record',
49
+ ];
50
+ /**
51
+ * Check if a type is native JS/TS type
52
+ * @param type
53
+ */
54
+ export const isNativeType = (type) => {
55
+ return TS_PRIMITIVE_TYPES.some((one) => {
56
+ if (typeof one === 'string') {
57
+ return one === type;
58
+ }
59
+ else {
60
+ return type.match(one);
61
+ }
62
+ });
63
+ };
package/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
1
  import { MetadataLatest } from '@dedot/codecs';
2
- import { NetworkInfo } from './types';
3
- export declare function generateTypesFromChain(network: NetworkInfo, endpoint: string, outDir: string): Promise<void>;
4
- export declare function generateTypes(network: NetworkInfo, metadata: MetadataLatest, rpcMethods: string[], runtimeApis: any[], outDir?: string): Promise<void>;
2
+ export declare function generateTypesFromEndpoint(chain: string, endpoint: string, outDir?: string, extension?: string): Promise<void>;
3
+ export declare function generateTypes(chain: string, metadata: MetadataLatest, rpcMethods: string[], runtimeApis: Record<string, number>, outDir?: string, extension?: string): Promise<void>;
package/index.js CHANGED
@@ -1,37 +1,37 @@
1
1
  import { Dedot } from 'dedot';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
- import { ConstsGen, ErrorsGen, EventsGen, IndexGen, QueryGen, RpcGen, RuntimeApisGen, TxGen, TypesGen, } from './generator';
5
- import { stringCamelCase } from '@polkadot/util';
6
- export async function generateTypesFromChain(network, endpoint, outDir) {
7
- const api = await Dedot.create(endpoint);
8
- const { methods } = await api.rpc.rpc.methods();
9
- const apis = api.runtimeVersion?.apis || [];
10
- if (!network.chain) {
11
- network.chain = stringCamelCase(api.runtimeVersion?.specName || api.runtimeChain || 'local');
4
+ import { ConstsGen, ErrorsGen, EventsGen, IndexGen, QueryGen, JsonRpcGen, RuntimeApisGen, TxGen, TypesGen, } from './generator/index.js';
5
+ import { stringCamelCase } from '@dedot/utils';
6
+ export async function generateTypesFromEndpoint(chain, endpoint, outDir, extension = 'd.ts') {
7
+ const api = await Dedot.new(endpoint);
8
+ const { methods } = await api.rpc.rpc_methods();
9
+ const apis = api.runtimeVersion.apis || {};
10
+ if (!chain) {
11
+ chain = stringCamelCase(api.runtimeVersion.specName || api.runtimeChain || 'local');
12
12
  }
13
- await generateTypes(network, api.metadataLatest, methods, apis, outDir);
13
+ await generateTypes(chain, api.metadata.latest, methods, apis, outDir, extension);
14
14
  await api.disconnect();
15
15
  }
16
- export async function generateTypes(network, metadata, rpcMethods, runtimeApis, outDir = '.') {
17
- const dirPath = path.resolve(outDir, network.chain);
18
- const defTypesFileName = path.join(dirPath, `types.d.ts`);
19
- const constsTypesFileName = path.join(dirPath, `consts.d.ts`);
20
- const queryTypesFileName = path.join(dirPath, `query.d.ts`);
21
- const rpcCallsFileName = path.join(dirPath, `rpc.d.ts`);
22
- const indexFileName = path.join(dirPath, `index.d.ts`);
23
- const errorsFileName = path.join(dirPath, `errors.d.ts`);
24
- const eventsFileName = path.join(dirPath, `events.d.ts`);
25
- const runtimeApisFileName = path.join(dirPath, `runtime.d.ts`);
26
- const txFileName = path.join(dirPath, `tx.d.ts`);
16
+ export async function generateTypes(chain, metadata, rpcMethods, runtimeApis, outDir = '.', extension = 'd.ts') {
17
+ const dirPath = path.resolve(outDir, chain);
18
+ const defTypesFileName = path.join(dirPath, `types.${extension}`);
19
+ const constsTypesFileName = path.join(dirPath, `consts.${extension}`);
20
+ const queryTypesFileName = path.join(dirPath, `query.${extension}`);
21
+ const jsonRpcFileName = path.join(dirPath, `json-rpc.${extension}`);
22
+ const indexFileName = path.join(dirPath, `index.${extension}`);
23
+ const errorsFileName = path.join(dirPath, `errors.${extension}`);
24
+ const eventsFileName = path.join(dirPath, `events.${extension}`);
25
+ const runtimeApisFileName = path.join(dirPath, `runtime.${extension}`);
26
+ const txFileName = path.join(dirPath, `tx.${extension}`);
27
27
  if (!fs.existsSync(dirPath)) {
28
28
  fs.mkdirSync(dirPath, { recursive: true });
29
29
  }
30
30
  const typesGen = new TypesGen(metadata);
31
31
  const constsGen = new ConstsGen(typesGen);
32
32
  const queryGen = new QueryGen(typesGen);
33
- const rpcGen = new RpcGen(typesGen, rpcMethods);
34
- const indexGen = new IndexGen(network);
33
+ const jsonRpcGen = new JsonRpcGen(typesGen, rpcMethods);
34
+ const indexGen = new IndexGen(chain);
35
35
  const errorsGen = new ErrorsGen(typesGen);
36
36
  const eventsGen = new EventsGen(typesGen);
37
37
  const runtimeApisGen = new RuntimeApisGen(typesGen, runtimeApis);
@@ -39,7 +39,7 @@ export async function generateTypes(network, metadata, rpcMethods, runtimeApis,
39
39
  fs.writeFileSync(defTypesFileName, await typesGen.generate());
40
40
  fs.writeFileSync(errorsFileName, await errorsGen.generate());
41
41
  fs.writeFileSync(eventsFileName, await eventsGen.generate());
42
- fs.writeFileSync(rpcCallsFileName, await rpcGen.generate());
42
+ fs.writeFileSync(jsonRpcFileName, await jsonRpcGen.generate());
43
43
  fs.writeFileSync(queryTypesFileName, await queryGen.generate());
44
44
  fs.writeFileSync(constsTypesFileName, await constsGen.generate());
45
45
  fs.writeFileSync(txFileName, await txGen.generate());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dedot/codegen",
3
- "version": "0.0.1-next.8d06d348.17+8d06d34",
3
+ "version": "0.0.1-next.8f4b2c24.6+8f4b2c2",
4
4
  "description": "Generate types",
5
5
  "author": "Thang X. Vu <thang@coongcrafts.io>",
6
6
  "homepage": "https://github.com/dedotdev/dedot/tree/main/packages/codegen",
@@ -18,12 +18,11 @@
18
18
  "copy": "cp -R ./src/templates ./dist && cp -R ./src/templates ./dist/cjs"
19
19
  },
20
20
  "dependencies": {
21
- "@dedot/codecs": "0.0.1-next.8d06d348.17+8d06d34",
22
- "@dedot/shape": "0.0.1-next.8d06d348.17+8d06d34",
23
- "@dedot/specs": "0.0.1-next.8d06d348.17+8d06d34",
24
- "@dedot/utils": "0.0.1-next.8d06d348.17+8d06d34",
25
- "@polkadot/util": "^12.6.2",
26
- "dedot": "0.0.1-next.8d06d348.17+8d06d34",
21
+ "@dedot/codecs": "0.0.1-next.8f4b2c24.6+8f4b2c2",
22
+ "@dedot/shape": "0.0.1-next.8f4b2c24.6+8f4b2c2",
23
+ "@dedot/specs": "0.0.1-next.8f4b2c24.6+8f4b2c2",
24
+ "@dedot/utils": "0.0.1-next.8f4b2c24.6+8f4b2c2",
25
+ "dedot": "0.0.1-next.8f4b2c24.6+8f4b2c2",
27
26
  "handlebars": "^4.7.8",
28
27
  "prettier": "^3.0.3"
29
28
  },
@@ -32,7 +31,7 @@
32
31
  "directory": "dist"
33
32
  },
34
33
  "license": "Apache-2.0",
35
- "gitHead": "8d06d348e231fd78008acd9122e6ac8ed2794b51",
34
+ "gitHead": "8f4b2c2459e3b2e4635a6433af57abbec7d1fb42",
36
35
  "module": "./index.js",
37
36
  "types": "./index.d.ts",
38
37
  "exports": {
@@ -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;
@@ -1,79 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const index_1 = require("./index");
7
- const static_substrate_1 = require("@polkadot/types-support/metadata/static-substrate");
8
- const substrate_hex_1 = __importDefault(require("@polkadot/types-support/metadata/v15/substrate-hex"));
9
- const codecs_1 = require("@dedot/codecs");
10
- const dedot_1 = require("dedot");
11
- const NETWORKS = [
12
- {
13
- chain: 'substrate',
14
- metadataHex: substrate_hex_1.default,
15
- rpcMethods: static_substrate_1.rpc.methods,
16
- },
17
- {
18
- chain: 'polkadot',
19
- endpoint: 'wss://rpc.polkadot.io',
20
- },
21
- {
22
- chain: 'kusama',
23
- endpoint: 'wss://kusama-rpc.polkadot.io',
24
- },
25
- {
26
- chain: 'astar',
27
- endpoint: 'wss://rpc.astar.network',
28
- },
29
- {
30
- chain: 'moonbeam',
31
- endpoint: 'wss://moonbeam.api.onfinality.io/public-ws',
32
- },
33
- {
34
- chain: 'polkadotAssetHub',
35
- endpoint: 'wss://polkadot-asset-hub-rpc.polkadot.io/',
36
- },
37
- {
38
- chain: 'kusamaAssetHub',
39
- endpoint: 'wss://kusama-asset-hub-rpc.polkadot.io/',
40
- },
41
- {
42
- chain: 'rococoAssetHub',
43
- endpoint: 'wss://rococo-asset-hub-rpc.polkadot.io/',
44
- },
45
- {
46
- chain: 'aleph',
47
- endpoint: 'wss://aleph-zero.api.onfinality.io/public-ws',
48
- },
49
- {
50
- chain: 'westendAssetHub',
51
- endpoint: 'wss://westend-asset-hub-rpc.polkadot.io',
52
- },
53
- ];
54
- const OUT_DIR = 'packages/chaintypes/src';
55
- async function run() {
56
- for (const network of NETWORKS) {
57
- const { chain, endpoint, metadataHex, rpcMethods } = network;
58
- if (endpoint) {
59
- console.log(`Generate types for ${chain} via endpoint ${endpoint}`);
60
- await (0, index_1.generateTypesFromChain)(network, endpoint, OUT_DIR);
61
- }
62
- else if (metadataHex && rpcMethods) {
63
- console.log(`Generate types for ${chain} via raw data`);
64
- const metadata = codecs_1.$Metadata.tryDecode(metadataHex);
65
- const runtimeVersion = getRuntimeVersion(metadata);
66
- await (0, index_1.generateTypes)(network, metadata.latest, rpcMethods, runtimeVersion.apis, OUT_DIR);
67
- }
68
- }
69
- console.log('DONE!');
70
- }
71
- const getRuntimeVersion = (metadata) => {
72
- const registry = new codecs_1.CodecRegistry(metadata.latest);
73
- const executor = new dedot_1.ConstantExecutor({
74
- registry,
75
- metadataLatest: metadata.latest,
76
- });
77
- return executor.execute('system', 'version');
78
- };
79
- run().catch(console.log);
@@ -1,175 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RpcGen = void 0;
4
- const specs_1 = require("@dedot/specs");
5
- const utils_1 = require("@dedot/utils");
6
- const generator_1 = require("../generator");
7
- const utils_2 = require("./utils");
8
- const HIDDEN_RPCS = [
9
- // Ref: https://github.com/paritytech/polkadot-sdk/blob/43415ef58c143b985e09015cd000dbd65f6d3997/substrate/client/rpc-servers/src/lib.rs#L152C9-L158
10
- 'rpc_methods',
11
- ];
12
- class RpcGen extends generator_1.ApiGen {
13
- typesGen;
14
- rpcMethods;
15
- constructor(typesGen, rpcMethods) {
16
- super(typesGen);
17
- this.typesGen = typesGen;
18
- this.rpcMethods = rpcMethods;
19
- HIDDEN_RPCS.filter((one) => !rpcMethods.includes(one)).forEach((one) => rpcMethods.push(one));
20
- rpcMethods.sort();
21
- }
22
- generate() {
23
- this.typesGen.clearCache();
24
- this.typesGen.typeImports.addKnownType('GenericRpcCalls', 'Unsub', 'Callback', 'GenericRpcCall');
25
- const specsByModule = this.rpcMethods
26
- .filter((one) => !(0, specs_1.findAliasRpcSpec)(one)) // we'll ignore alias rpc for now if defined in the specs! TODO should we generate alias rpc as well?
27
- .filter((one) => !(0, specs_1.isUnsubscribeMethod)(one)) // we'll ignore unsubscribe method as well
28
- .map((one) => {
29
- const spec = (0, specs_1.findRpcSpec)(one);
30
- if (spec) {
31
- return spec;
32
- }
33
- const [module, ...methodParts] = one.split('_');
34
- const method = methodParts.join('_');
35
- return {
36
- params: [],
37
- type: 'GenericRpcCall',
38
- module,
39
- method,
40
- };
41
- })
42
- .reduce((o, spec) => {
43
- const { module, method } = spec;
44
- // ignore if rpc name does not confront with the general convention
45
- if (!module || !method) {
46
- return o;
47
- }
48
- return {
49
- ...o,
50
- [module]: o[module] ? [...o[module], spec] : [spec],
51
- };
52
- }, {});
53
- let rpcCallsOut = '';
54
- Object.keys(specsByModule).forEach((module) => {
55
- const specs = specsByModule[module];
56
- // TODO add alias info to docs block!
57
- rpcCallsOut += `${module}: {
58
- ${specs.map((spec) => this.#generateMethodDef(spec)).join(',\n')},
59
-
60
- [method: string]: GenericRpcCall,
61
- },`;
62
- });
63
- // TODO include & define external types
64
- const importTypes = this.typesGen.typeImports.toImports();
65
- const template = (0, utils_2.compileTemplate)('rpc.hbs');
66
- return (0, utils_2.beautifySourceCode)(template({ importTypes, rpcCallsOut }));
67
- }
68
- #generateMethodDef(spec) {
69
- const { name, type, module, method, docs = [], params, pubsub, deprecated } = spec;
70
- const rpcName = name || `${module}_${method}`;
71
- let defaultDocs = [`@rpcname: ${rpcName}`];
72
- if (deprecated) {
73
- defaultDocs.push(`@deprecated: ${deprecated}`);
74
- }
75
- if (type === 'GenericRpcCall' && params.length === 0) {
76
- return `${(0, utils_2.commentBlock)(defaultDocs)}${method}: GenericRpcCall`;
77
- }
78
- this.addTypeImport(type, false);
79
- params.forEach(({ type, isScale }) => {
80
- this.addTypeImport(type, !!isScale);
81
- });
82
- const typedParams = params.map((param) => ({
83
- ...param,
84
- plainType: this.getGeneratedTypeName(param.type, !!param.isScale),
85
- }));
86
- const isSubscription = !!pubsub;
87
- const paramsOut = typedParams.map(({ name, type, isOptional, isScale, plainType }) => `${name}${isOptional ? '?' : ''}: ${plainType}`);
88
- const paramsDoc = typedParams.map(({ name, plainType }) => `@param {${plainType}} ${name}`);
89
- const typeOut = this.getGeneratedTypeName(type, false);
90
- if (isSubscription) {
91
- defaultDocs.shift();
92
- defaultDocs.unshift(`@pubsub: ${pubsub?.join(', ')}`);
93
- paramsOut.push(`callback: Callback<${typeOut}>`);
94
- return `${(0, utils_2.commentBlock)(docs, '\n', defaultDocs, paramsDoc)}${method}: GenericRpcCall<(${paramsOut.join(', ')}) => Promise<Unsub>>`;
95
- }
96
- else {
97
- return `${(0, utils_2.commentBlock)(docs, '\n', defaultDocs, paramsDoc)}${method}: GenericRpcCall<(${paramsOut.join(', ')}) => Promise<${typeOut}>>`;
98
- }
99
- }
100
- // TODO check typeIn, typeOut if param type, or rpc type isScale
101
- addTypeImport(type, toTypeIn = true) {
102
- if (Array.isArray(type)) {
103
- type.forEach((one) => this.addTypeImport(one, toTypeIn));
104
- return;
105
- }
106
- type = type.trim();
107
- if ((0, utils_1.isNativeType)(type)) {
108
- return;
109
- }
110
- // Handle generic wrapper types
111
- const matchArray = type.match(utils_2.WRAPPER_TYPE_REGEX);
112
- if (matchArray) {
113
- const [_, $1, $2] = matchArray;
114
- this.addTypeImport($1, toTypeIn);
115
- if ($2.match(utils_2.WRAPPER_TYPE_REGEX) || $2.match(utils_2.TUPLE_TYPE_REGEX)) {
116
- this.addTypeImport($2, toTypeIn);
117
- }
118
- else {
119
- this.addTypeImport($2.split(','), toTypeIn);
120
- }
121
- return;
122
- }
123
- // Check tuple type
124
- if (type.match(utils_2.TUPLE_TYPE_REGEX)) {
125
- this.addTypeImport(type.slice(1, -1).split(','), toTypeIn);
126
- return;
127
- }
128
- if (type.includes(' | ')) {
129
- this.addTypeImport(type.split(' | ').map((one) => one.trim()), toTypeIn);
130
- return;
131
- }
132
- try {
133
- const codecType = this.#getCodecType(type, toTypeIn);
134
- if ((0, utils_1.isNativeType)(codecType))
135
- return;
136
- this.typesGen.typeImports.addCodecType(codecType);
137
- return;
138
- }
139
- catch (e) { }
140
- this.typesGen.addTypeImport(type);
141
- }
142
- getGeneratedTypeName(type, toTypeIn = true) {
143
- try {
144
- const matchArray = type.match(utils_2.WRAPPER_TYPE_REGEX);
145
- if (matchArray) {
146
- const [_, $1, $2] = matchArray;
147
- const wrapperTypeName = this.#getCodecType($1, toTypeIn);
148
- if ($2.match(utils_2.WRAPPER_TYPE_REGEX) || $2.match(utils_2.TUPLE_TYPE_REGEX)) {
149
- return `${wrapperTypeName}<${this.getGeneratedTypeName($2, toTypeIn)}>`;
150
- }
151
- const innerTypeNames = $2
152
- .split(',')
153
- .map((one) => this.getGeneratedTypeName(one.trim(), toTypeIn))
154
- .join(', ');
155
- return `${wrapperTypeName}<${innerTypeNames}>`;
156
- }
157
- else if (type.match(utils_2.TUPLE_TYPE_REGEX)) {
158
- const innerTypeNames = type
159
- .slice(1, -1)
160
- .split(',')
161
- .map((one) => this.getGeneratedTypeName(one.trim(), toTypeIn))
162
- .join(', ');
163
- return `[${innerTypeNames}]`;
164
- }
165
- return this.#getCodecType(type, toTypeIn);
166
- }
167
- catch (e) { }
168
- return type;
169
- }
170
- #getCodecType(type, toTypeIn = true) {
171
- const { typeIn, typeOut } = this.typesGen.knownCodecRegistry.findCodecType(type);
172
- return toTypeIn ? typeIn : typeOut;
173
- }
174
- }
175
- exports.RpcGen = RpcGen;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./KnownCodecRegistry"), exports);
@@ -1,5 +0,0 @@
1
- "use strict";
2
- // THIS FILE IS AUTO-GENERATED, DO NOT EDIT!
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.packageInfo = void 0;
5
- exports.packageInfo = { name: '@dedot/codegen', version: '0.0.1-alpha.26' };
@@ -1,7 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface RpcCalls extends GenericRpcCalls {
6
- {{{rpcCallsOut}}}
7
- }
package/cjs/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1 +0,0 @@
1
- export {};
@@ -1,74 +0,0 @@
1
- import { generateTypes, generateTypesFromChain } from './index';
2
- import { rpc } from '@polkadot/types-support/metadata/static-substrate';
3
- import staticSubstrate from '@polkadot/types-support/metadata/v15/substrate-hex';
4
- import { $Metadata, CodecRegistry } from '@dedot/codecs';
5
- import { ConstantExecutor } from 'dedot';
6
- const NETWORKS = [
7
- {
8
- chain: 'substrate',
9
- metadataHex: staticSubstrate,
10
- rpcMethods: rpc.methods,
11
- },
12
- {
13
- chain: 'polkadot',
14
- endpoint: 'wss://rpc.polkadot.io',
15
- },
16
- {
17
- chain: 'kusama',
18
- endpoint: 'wss://kusama-rpc.polkadot.io',
19
- },
20
- {
21
- chain: 'astar',
22
- endpoint: 'wss://rpc.astar.network',
23
- },
24
- {
25
- chain: 'moonbeam',
26
- endpoint: 'wss://moonbeam.api.onfinality.io/public-ws',
27
- },
28
- {
29
- chain: 'polkadotAssetHub',
30
- endpoint: 'wss://polkadot-asset-hub-rpc.polkadot.io/',
31
- },
32
- {
33
- chain: 'kusamaAssetHub',
34
- endpoint: 'wss://kusama-asset-hub-rpc.polkadot.io/',
35
- },
36
- {
37
- chain: 'rococoAssetHub',
38
- endpoint: 'wss://rococo-asset-hub-rpc.polkadot.io/',
39
- },
40
- {
41
- chain: 'aleph',
42
- endpoint: 'wss://aleph-zero.api.onfinality.io/public-ws',
43
- },
44
- {
45
- chain: 'westendAssetHub',
46
- endpoint: 'wss://westend-asset-hub-rpc.polkadot.io',
47
- },
48
- ];
49
- const OUT_DIR = 'packages/chaintypes/src';
50
- async function run() {
51
- for (const network of NETWORKS) {
52
- const { chain, endpoint, metadataHex, rpcMethods } = network;
53
- if (endpoint) {
54
- console.log(`Generate types for ${chain} via endpoint ${endpoint}`);
55
- await generateTypesFromChain(network, endpoint, OUT_DIR);
56
- }
57
- else if (metadataHex && rpcMethods) {
58
- console.log(`Generate types for ${chain} via raw data`);
59
- const metadata = $Metadata.tryDecode(metadataHex);
60
- const runtimeVersion = getRuntimeVersion(metadata);
61
- await generateTypes(network, metadata.latest, rpcMethods, runtimeVersion.apis, OUT_DIR);
62
- }
63
- }
64
- console.log('DONE!');
65
- }
66
- const getRuntimeVersion = (metadata) => {
67
- const registry = new CodecRegistry(metadata.latest);
68
- const executor = new ConstantExecutor({
69
- registry,
70
- metadataLatest: metadata.latest,
71
- });
72
- return executor.execute('system', 'version');
73
- };
74
- run().catch(console.log);