@acala-network/chopsticks 0.7.2 → 0.8.0-0

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 (116) hide show
  1. package/lib/cli-options.d.ts +40 -0
  2. package/lib/cli-options.js +43 -0
  3. package/lib/cli.d.ts +1 -2
  4. package/lib/cli.js +20 -183
  5. package/lib/context.d.ts +5 -0
  6. package/lib/context.js +37 -0
  7. package/lib/index.d.ts +2 -7
  8. package/lib/index.js +4 -15
  9. package/lib/logger.d.ts +1 -7
  10. package/lib/logger.js +3 -38
  11. package/lib/plugins/decode-key/index.d.ts +2 -0
  12. package/lib/plugins/decode-key/index.js +27 -0
  13. package/lib/plugins/dry-run/cli.d.ts +2 -0
  14. package/lib/plugins/dry-run/cli.js +46 -0
  15. package/lib/plugins/dry-run/dry-run-extrinsic.d.ts +2 -0
  16. package/lib/{dry-run.js → plugins/dry-run/dry-run-extrinsic.js} +8 -8
  17. package/lib/{dry-run-preimage.d.ts → plugins/dry-run/dry-run-preimage.d.ts} +1 -1
  18. package/lib/{dry-run-preimage.js → plugins/dry-run/dry-run-preimage.js} +10 -12
  19. package/lib/plugins/dry-run/index.d.ts +2 -0
  20. package/lib/plugins/dry-run/index.js +18 -0
  21. package/lib/plugins/dry-run/rpc.d.ts +3 -0
  22. package/lib/{rpc/dev/dry-run.js → plugins/dry-run/rpc.js} +10 -7
  23. package/lib/plugins/index.d.ts +4 -0
  24. package/lib/plugins/index.js +52 -0
  25. package/lib/plugins/new-block/index.d.ts +2 -0
  26. package/lib/plugins/new-block/index.js +28 -0
  27. package/lib/plugins/run-block/index.d.ts +2 -0
  28. package/lib/plugins/run-block/index.js +67 -0
  29. package/lib/plugins/set-block-build-mode/index.d.ts +2 -0
  30. package/lib/plugins/set-block-build-mode/index.js +14 -0
  31. package/lib/plugins/set-head/index.d.ts +2 -0
  32. package/lib/plugins/set-head/index.js +20 -0
  33. package/lib/plugins/set-storage/index.d.ts +2 -0
  34. package/lib/plugins/set-storage/index.js +18 -0
  35. package/lib/plugins/time-travel/index.d.ts +2 -0
  36. package/lib/plugins/time-travel/index.js +13 -0
  37. package/lib/plugins/try-runtime/index.d.ts +2 -0
  38. package/lib/plugins/try-runtime/index.js +58 -0
  39. package/lib/rpc/index.d.ts +1 -1
  40. package/lib/rpc/index.js +11 -4
  41. package/lib/rpc/shared.d.ts +1 -1
  42. package/lib/rpc/shared.js +1 -1
  43. package/lib/rpc/substrate/author.js +3 -3
  44. package/lib/schema/index.d.ts +9 -66
  45. package/lib/schema/index.js +41 -14
  46. package/lib/server.js +2 -1
  47. package/lib/setup-with-server.d.ts +1 -3
  48. package/lib/setup-with-server.js +2 -2
  49. package/lib/utils/decoder.d.ts +1 -1
  50. package/lib/utils/generate-html-diff.d.ts +1 -1
  51. package/lib/utils/override.d.ts +4 -0
  52. package/lib/utils/{import-storage.js → override.js} +6 -6
  53. package/package.json +13 -16
  54. package/lib/api.d.ts +0 -43
  55. package/lib/api.js +0 -79
  56. package/lib/blockchain/block-builder.d.ts +0 -10
  57. package/lib/blockchain/block-builder.js +0 -297
  58. package/lib/blockchain/block.d.ts +0 -45
  59. package/lib/blockchain/block.js +0 -194
  60. package/lib/blockchain/head-state.d.ts +0 -15
  61. package/lib/blockchain/head-state.js +0 -71
  62. package/lib/blockchain/index.d.ts +0 -64
  63. package/lib/blockchain/index.js +0 -243
  64. package/lib/blockchain/inherent/index.d.ts +0 -19
  65. package/lib/blockchain/inherent/index.js +0 -36
  66. package/lib/blockchain/inherent/para-enter.d.ts +0 -7
  67. package/lib/blockchain/inherent/para-enter.js +0 -33
  68. package/lib/blockchain/inherent/parachain/babe-randomness.d.ts +0 -7
  69. package/lib/blockchain/inherent/parachain/babe-randomness.js +0 -15
  70. package/lib/blockchain/inherent/parachain/nimbus-author-inherent.d.ts +0 -7
  71. package/lib/blockchain/inherent/parachain/nimbus-author-inherent.js +0 -15
  72. package/lib/blockchain/inherent/parachain/validation-data.d.ts +0 -19
  73. package/lib/blockchain/inherent/parachain/validation-data.js +0 -172
  74. package/lib/blockchain/storage-layer.d.ts +0 -32
  75. package/lib/blockchain/storage-layer.js +0 -200
  76. package/lib/blockchain/txpool.d.ts +0 -45
  77. package/lib/blockchain/txpool.js +0 -184
  78. package/lib/db/entities.d.ts +0 -5
  79. package/lib/db/entities.js +0 -33
  80. package/lib/db/index.d.ts +0 -3
  81. package/lib/db/index.js +0 -41
  82. package/lib/dry-run.d.ts +0 -2
  83. package/lib/executor.d.ts +0 -40
  84. package/lib/executor.js +0 -131
  85. package/lib/genesis-provider.d.ts +0 -44
  86. package/lib/genesis-provider.js +0 -155
  87. package/lib/offchain.d.ts +0 -10
  88. package/lib/offchain.js +0 -37
  89. package/lib/rpc/dev/dry-run.d.ts +0 -2
  90. package/lib/rpc/dev/index.d.ts +0 -3
  91. package/lib/rpc/dev/index.js +0 -75
  92. package/lib/run-block.d.ts +0 -2
  93. package/lib/run-block.js +0 -51
  94. package/lib/setup.d.ts +0 -11
  95. package/lib/setup.js +0 -86
  96. package/lib/try-runtime.d.ts +0 -2
  97. package/lib/try-runtime.js +0 -36
  98. package/lib/utils/import-storage.d.ts +0 -5
  99. package/lib/utils/index.d.ts +0 -16
  100. package/lib/utils/index.js +0 -59
  101. package/lib/utils/key-cache.d.ts +0 -10
  102. package/lib/utils/key-cache.js +0 -66
  103. package/lib/utils/proof.d.ts +0 -15
  104. package/lib/utils/proof.js +0 -41
  105. package/lib/utils/set-storage.d.ts +0 -7
  106. package/lib/utils/set-storage.js +0 -59
  107. package/lib/utils/time-travel.d.ts +0 -5
  108. package/lib/utils/time-travel.js +0 -65
  109. package/lib/xcm/downward.d.ts +0 -2
  110. package/lib/xcm/downward.js +0 -29
  111. package/lib/xcm/horizontal.d.ts +0 -2
  112. package/lib/xcm/horizontal.js +0 -29
  113. package/lib/xcm/index.d.ts +0 -9
  114. package/lib/xcm/index.js +0 -25
  115. package/lib/xcm/upward.d.ts +0 -2
  116. package/lib/xcm/upward.js +0 -21
@@ -1,184 +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
- exports.TxPool = exports.BuildBlockMode = exports.APPLY_EXTRINSIC_ERROR = void 0;
7
- const node_stream_1 = require("node:stream");
8
- const lodash_1 = __importDefault(require("lodash"));
9
- const utils_1 = require("../utils");
10
- const block_builder_1 = require("./block-builder");
11
- const logger_1 = require("../logger");
12
- const logger = logger_1.defaultLogger.child({ name: 'txpool' });
13
- exports.APPLY_EXTRINSIC_ERROR = 'TxPool::ApplyExtrinsicError';
14
- var BuildBlockMode;
15
- (function (BuildBlockMode) {
16
- BuildBlockMode[BuildBlockMode["Batch"] = 0] = "Batch";
17
- BuildBlockMode[BuildBlockMode["Instant"] = 1] = "Instant";
18
- BuildBlockMode[BuildBlockMode["Manual"] = 2] = "Manual";
19
- })(BuildBlockMode || (exports.BuildBlockMode = BuildBlockMode = {}));
20
- class TxPool {
21
- #chain;
22
- #pool = [];
23
- #ump = {};
24
- #dmp = [];
25
- #hrmp = {};
26
- #mode;
27
- #inherentProvider;
28
- #pendingBlocks = [];
29
- event = new node_stream_1.EventEmitter();
30
- #isBuilding = false;
31
- constructor(chain, inherentProvider, mode = BuildBlockMode.Batch) {
32
- this.#chain = chain;
33
- this.#mode = mode;
34
- this.#inherentProvider = inherentProvider;
35
- }
36
- get pendingExtrinsics() {
37
- return this.#pool.map(({ extrinsic }) => extrinsic);
38
- }
39
- get ump() {
40
- return this.#ump;
41
- }
42
- get dmp() {
43
- return this.#dmp;
44
- }
45
- get hrmp() {
46
- return this.#hrmp;
47
- }
48
- get mode() {
49
- return this.#mode;
50
- }
51
- set mode(mode) {
52
- this.#mode = mode;
53
- }
54
- clear() {
55
- this.#pool.length = 0;
56
- for (const id of Object.keys(this.#ump)) {
57
- delete this.#ump[id];
58
- }
59
- this.#dmp.length = 0;
60
- for (const id of Object.keys(this.#hrmp)) {
61
- delete this.#hrmp[id];
62
- }
63
- }
64
- pendingExtrinsicsBy(address) {
65
- return this.#pool.filter(({ signer }) => signer === address).map(({ extrinsic }) => extrinsic);
66
- }
67
- async submitExtrinsic(extrinsic) {
68
- logger.debug({ extrinsic: (0, logger_1.truncate)(extrinsic) }, 'submit extrinsic');
69
- this.#pool.push({ extrinsic, signer: await this.#getSigner(extrinsic) });
70
- this.#maybeBuildBlock();
71
- }
72
- async #getSigner(extrinsic) {
73
- const registry = await this.#chain.head.registry;
74
- const tx = registry.createType('GenericExtrinsic', extrinsic);
75
- return tx.signer.toString();
76
- }
77
- submitUpwardMessages(id, ump) {
78
- logger.debug({ id, ump: (0, logger_1.truncate)(ump) }, 'submit upward messages');
79
- if (!this.#ump[id]) {
80
- this.#ump[id] = [];
81
- }
82
- this.#ump[id].push(...ump);
83
- this.#maybeBuildBlock();
84
- }
85
- submitDownwardMessages(dmp) {
86
- logger.debug({ dmp: (0, logger_1.truncate)(dmp) }, 'submit downward messages');
87
- this.#dmp.push(...dmp);
88
- this.#maybeBuildBlock();
89
- }
90
- submitHorizontalMessages(id, hrmp) {
91
- logger.debug({ id, hrmp: (0, logger_1.truncate)(hrmp) }, 'submit horizontal messages');
92
- if (!this.#hrmp[id]) {
93
- this.#hrmp[id] = [];
94
- }
95
- this.#hrmp[id].push(...hrmp);
96
- this.#maybeBuildBlock();
97
- }
98
- #maybeBuildBlock() {
99
- switch (this.#mode) {
100
- case BuildBlockMode.Batch:
101
- this.#batchBuildBlock();
102
- break;
103
- case BuildBlockMode.Instant:
104
- this.buildBlock();
105
- break;
106
- case BuildBlockMode.Manual:
107
- // does nothing
108
- break;
109
- }
110
- }
111
- #batchBuildBlock = lodash_1.default.debounce(this.buildBlock, 100, { maxWait: 1000 });
112
- async buildBlockWithParams(params) {
113
- this.#pendingBlocks.push({
114
- params,
115
- deferred: (0, utils_1.defer)(),
116
- });
117
- this.#buildBlockIfNeeded();
118
- await this.upcomingBlocks();
119
- }
120
- async buildBlock(params) {
121
- const transactions = params?.transactions || this.#pool.splice(0).map(({ extrinsic }) => extrinsic);
122
- const upwardMessages = params?.upwardMessages || { ...this.#ump };
123
- const downwardMessages = params?.downwardMessages || this.#dmp.splice(0);
124
- const horizontalMessages = params?.horizontalMessages || { ...this.#hrmp };
125
- if (!params?.upwardMessages) {
126
- for (const id of Object.keys(this.#ump)) {
127
- delete this.#ump[id];
128
- }
129
- }
130
- if (!params?.horizontalMessages) {
131
- for (const id of Object.keys(this.#hrmp)) {
132
- delete this.#hrmp[id];
133
- }
134
- }
135
- await this.buildBlockWithParams({
136
- transactions,
137
- upwardMessages,
138
- downwardMessages,
139
- horizontalMessages,
140
- });
141
- }
142
- async upcomingBlocks() {
143
- const count = this.#pendingBlocks.length;
144
- if (count > 0) {
145
- await this.#pendingBlocks[count - 1].deferred.promise;
146
- }
147
- return count;
148
- }
149
- async #buildBlockIfNeeded() {
150
- if (this.#isBuilding)
151
- return;
152
- if (this.#pendingBlocks.length === 0)
153
- return;
154
- this.#isBuilding = true;
155
- try {
156
- await this.#buildBlock();
157
- }
158
- finally {
159
- this.#isBuilding = false;
160
- }
161
- this.#buildBlockIfNeeded();
162
- }
163
- async #buildBlock() {
164
- await this.#chain.api.isReady;
165
- const pending = this.#pendingBlocks[0];
166
- if (!pending) {
167
- throw new Error('Unreachable');
168
- }
169
- const { params, deferred } = pending;
170
- logger.trace({ params }, 'build block');
171
- const head = this.#chain.head;
172
- const inherents = await this.#inherentProvider.createInherents(head, params);
173
- const [newBlock, pendingExtrinsics] = await (0, block_builder_1.buildBlock)(head, inherents, params.transactions, params.upwardMessages, (extrinsic, error) => {
174
- this.event.emit(exports.APPLY_EXTRINSIC_ERROR, [extrinsic, error]);
175
- });
176
- for (const extrinsic of pendingExtrinsics) {
177
- this.#pool.push({ extrinsic, signer: await this.#getSigner(extrinsic) });
178
- }
179
- await this.#chain.setHead(newBlock);
180
- this.#pendingBlocks.shift();
181
- deferred.resolve();
182
- }
183
- }
184
- exports.TxPool = TxPool;
@@ -1,5 +0,0 @@
1
- export declare class KeyValuePair {
2
- blockHash: string;
3
- key: string;
4
- value: string;
5
- }
@@ -1,33 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.KeyValuePair = void 0;
13
- const typeorm_1 = require("typeorm");
14
- let KeyValuePair = exports.KeyValuePair = class KeyValuePair {
15
- blockHash;
16
- key;
17
- value;
18
- };
19
- __decorate([
20
- (0, typeorm_1.PrimaryColumn)(),
21
- __metadata("design:type", String)
22
- ], KeyValuePair.prototype, "blockHash", void 0);
23
- __decorate([
24
- (0, typeorm_1.PrimaryColumn)(),
25
- __metadata("design:type", String)
26
- ], KeyValuePair.prototype, "key", void 0);
27
- __decorate([
28
- (0, typeorm_1.Column)({ nullable: true }),
29
- __metadata("design:type", String)
30
- ], KeyValuePair.prototype, "value", void 0);
31
- exports.KeyValuePair = KeyValuePair = __decorate([
32
- (0, typeorm_1.Entity)()
33
- ], KeyValuePair);
package/lib/db/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import 'reflect-metadata';
2
- import { DataSource } from 'typeorm';
3
- export declare const openDb: (dbPath: string) => Promise<DataSource>;
package/lib/db/index.js DELETED
@@ -1,41 +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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.openDb = void 0;
27
- require("reflect-metadata");
28
- const typeorm_1 = require("typeorm");
29
- const entities = __importStar(require("./entities"));
30
- const openDb = async (dbPath) => {
31
- const source = new typeorm_1.DataSource({
32
- type: 'sqlite',
33
- database: dbPath,
34
- entities: Object.values(entities),
35
- synchronize: true,
36
- logging: false,
37
- });
38
- await source.initialize();
39
- return source;
40
- };
41
- exports.openDb = openDb;
package/lib/dry-run.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import { Config } from './schema';
2
- export declare const dryRun: (argv: Config) => Promise<never>;
package/lib/executor.d.ts DELETED
@@ -1,40 +0,0 @@
1
- import { HexString } from '@polkadot/util/types';
2
- import { Block } from './blockchain/block';
3
- import { JsCallback } from '@acala-network/chopsticks-executor';
4
- import { Registry } from '@polkadot/types-codec/types';
5
- import _ from 'lodash';
6
- export type RuntimeVersion = {
7
- specName: string;
8
- implName: string;
9
- authoringVersion: number;
10
- specVersion: number;
11
- implVersion: number;
12
- apis: [HexString, number][];
13
- transactionVersion: number;
14
- stateVersion: number;
15
- };
16
- export declare const getRuntimeVersion: (code: HexString) => Promise<RuntimeVersion>;
17
- export declare const calculateStateRoot: (entries: [HexString, HexString][], trie_version: number) => Promise<HexString>;
18
- export declare const decodeProof: (trieRootHash: HexString, keys: HexString[], nodes: HexString[]) => Promise<Record<`0x${string}`, `0x${string}` | null>>;
19
- export declare const createProof: (nodes: HexString[], entries: [HexString, HexString | null][]) => Promise<{
20
- trieRootHash: `0x${string}`;
21
- nodes: `0x${string}`[];
22
- }>;
23
- export declare const runTask: (task: {
24
- wasm: HexString;
25
- calls: [string, HexString[]][];
26
- mockSignatureHost: boolean;
27
- allowUnresolvedImports: boolean;
28
- runtimeLogLevel: number;
29
- }, callback?: JsCallback) => Promise<any>;
30
- export declare const taskHandler: (block: Block) => JsCallback;
31
- export declare const emptyTaskHandler: {
32
- getStorage: (_key: HexString) => Promise<never>;
33
- getStateRoot: () => Promise<never>;
34
- getNextKey: (_prefix: HexString, _key: HexString) => Promise<never>;
35
- offchainGetStorage: (_key: HexString) => Promise<never>;
36
- offchainTimestamp: () => Promise<never>;
37
- offchainRandomSeed: () => Promise<never>;
38
- offchainSubmitTransaction: (_tx: HexString) => Promise<never>;
39
- };
40
- export declare const getAuraSlotDuration: ((wasm: HexString, registry: Registry) => Promise<number>) & _.MemoizedFunction;
package/lib/executor.js DELETED
@@ -1,131 +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
- exports.getAuraSlotDuration = exports.emptyTaskHandler = exports.taskHandler = exports.runTask = exports.createProof = exports.decodeProof = exports.calculateStateRoot = exports.getRuntimeVersion = void 0;
7
- const util_1 = require("@polkadot/util");
8
- const util_crypto_1 = require("@polkadot/util-crypto");
9
- const chopsticks_executor_1 = require("@acala-network/chopsticks-executor");
10
- const key_cache_1 = require("./utils/key-cache");
11
- const logger_1 = require("./logger");
12
- const lodash_1 = __importDefault(require("lodash"));
13
- const logger = logger_1.defaultLogger.child({ name: 'executor' });
14
- const getRuntimeVersion = async (code) => {
15
- return (0, chopsticks_executor_1.get_runtime_version)(code).then((version) => {
16
- version.specName = (0, util_1.hexToString)(version.specName);
17
- version.implName = (0, util_1.hexToString)(version.implName);
18
- return version;
19
- });
20
- };
21
- exports.getRuntimeVersion = getRuntimeVersion;
22
- // trie_version: 0 for old trie, 1 for new trie
23
- const calculateStateRoot = async (entries, trie_version) => {
24
- return (0, chopsticks_executor_1.calculate_state_root)(entries, trie_version);
25
- };
26
- exports.calculateStateRoot = calculateStateRoot;
27
- const decodeProof = async (trieRootHash, keys, nodes) => {
28
- const decoded = await (0, chopsticks_executor_1.decode_proof)(trieRootHash, keys, nodes);
29
- return decoded.reduce((accum, [key, value]) => {
30
- accum[key] = value;
31
- return accum;
32
- }, {});
33
- };
34
- exports.decodeProof = decodeProof;
35
- const createProof = async (nodes, entries) => {
36
- const result = await (0, chopsticks_executor_1.create_proof)(nodes, entries);
37
- return { trieRootHash: result[0], nodes: result[1] };
38
- };
39
- exports.createProof = createProof;
40
- const runTask = async (task, callback = exports.emptyTaskHandler) => {
41
- logger.trace((0, logger_1.truncate)(task), 'taskRun');
42
- const response = await (0, chopsticks_executor_1.run_task)(task, callback, process.env.RUST_LOG);
43
- if (response.Call) {
44
- logger.trace((0, logger_1.truncate)(response.Call), 'taskResponse');
45
- }
46
- else {
47
- logger.trace({ response }, 'taskResponse');
48
- }
49
- return response;
50
- };
51
- exports.runTask = runTask;
52
- const taskHandler = (block) => {
53
- return {
54
- getStorage: async function (key) {
55
- return block.get(key);
56
- },
57
- getStateRoot: async function () {
58
- const header = await block.header;
59
- return header.stateRoot.toHex();
60
- },
61
- getNextKey: async function (prefix, key) {
62
- const [nextKey] = await block.getKeysPaged({
63
- prefix: prefix.length === 2 /** 0x */ ? key.slice(0, key_cache_1.PREFIX_LENGTH) : prefix,
64
- pageSize: 1,
65
- startKey: key,
66
- });
67
- return nextKey;
68
- },
69
- offchainGetStorage: async function (key) {
70
- if (!block.chain.offchainWorker)
71
- throw new Error('offchain worker not found');
72
- return block.chain.offchainWorker.get(key);
73
- },
74
- offchainTimestamp: async function () {
75
- return Date.now();
76
- },
77
- offchainRandomSeed: async function () {
78
- return (0, util_crypto_1.randomAsHex)(32);
79
- },
80
- offchainSubmitTransaction: async function (tx) {
81
- if (!block.chain.offchainWorker)
82
- throw new Error('offchain worker not found');
83
- try {
84
- const hash = await block.chain.offchainWorker.pushExtrinsic(block, tx);
85
- logger.trace({ hash }, 'offchainSubmitTransaction');
86
- return true;
87
- }
88
- catch (error) {
89
- logger.trace({ error }, 'offchainSubmitTransaction');
90
- return false;
91
- }
92
- },
93
- };
94
- };
95
- exports.taskHandler = taskHandler;
96
- exports.emptyTaskHandler = {
97
- getStorage: async function (_key) {
98
- throw new Error('Method not implemented');
99
- },
100
- getStateRoot: async function () {
101
- throw new Error('Method not implemented');
102
- },
103
- getNextKey: async function (_prefix, _key) {
104
- throw new Error('Method not implemented');
105
- },
106
- offchainGetStorage: async function (_key) {
107
- throw new Error('Method not implemented');
108
- },
109
- offchainTimestamp: async function () {
110
- throw new Error('Method not implemented');
111
- },
112
- offchainRandomSeed: async function () {
113
- throw new Error('Method not implemented');
114
- },
115
- offchainSubmitTransaction: async function (_tx) {
116
- throw new Error('Method not implemented');
117
- },
118
- };
119
- exports.getAuraSlotDuration = lodash_1.default.memoize(async (wasm, registry) => {
120
- const result = await (0, exports.runTask)({
121
- wasm,
122
- calls: [['AuraApi_slot_duration', []]],
123
- mockSignatureHost: false,
124
- allowUnresolvedImports: false,
125
- runtimeLogLevel: 0,
126
- });
127
- if (!result.Call)
128
- throw new Error(result.Error);
129
- const slotDuration = registry.createType('u64', (0, util_1.hexToU8a)(result.Call.result)).toNumber();
130
- return slotDuration;
131
- });
@@ -1,44 +0,0 @@
1
- import { HexString } from '@polkadot/util/types';
2
- import { JsCallback } from '@acala-network/chopsticks-executor';
3
- import { ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '@polkadot/rpc-provider/types';
4
- import { Genesis } from './schema';
5
- export declare class GenesisProvider implements ProviderInterface {
6
- #private;
7
- readonly stats?: ProviderStats;
8
- constructor(genesis: Genesis);
9
- static fromUrl: (url: string) => Promise<GenesisProvider>;
10
- get isClonable(): boolean;
11
- clone: () => ProviderInterface;
12
- get hasSubscriptions(): boolean;
13
- get isConnected(): boolean;
14
- get isReady(): Promise<void>;
15
- connect: () => Promise<void>;
16
- disconnect: () => Promise<void>;
17
- on: (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb) => (() => void);
18
- get blockHash(): HexString;
19
- getHeader: () => Promise<{
20
- blockHash: `0x${string}`;
21
- number: number;
22
- stateRoot: `0x${string}`;
23
- digest: {
24
- logs: never[];
25
- };
26
- }>;
27
- getBlock: () => Promise<{
28
- block: {
29
- header: {
30
- blockHash: `0x${string}`;
31
- number: number;
32
- stateRoot: `0x${string}`;
33
- digest: {
34
- logs: never[];
35
- };
36
- };
37
- extrinsics: never[];
38
- };
39
- }>;
40
- get _jsCallback(): JsCallback;
41
- send: (method: string, params: unknown[], _isCacheable?: boolean) => Promise<any>;
42
- subscribe: (_type: string, _method: string, _params: unknown[], _cb: ProviderInterfaceCallback) => Promise<number | string>;
43
- unsubscribe: (_type: string, _method: string, _id: number | string) => Promise<boolean>;
44
- }
@@ -1,155 +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
- exports.GenesisProvider = void 0;
7
- const node_events_1 = require("node:events");
8
- const node_fs_1 = require("node:fs");
9
- const util_1 = require("@polkadot/util");
10
- const axios_1 = __importDefault(require("axios"));
11
- const schema_1 = require("./schema");
12
- const executor_1 = require("./executor");
13
- const utils_1 = require("./utils");
14
- class GenesisProvider {
15
- #isConnected = false;
16
- stats;
17
- #eventemitter;
18
- #isReadyPromise;
19
- #genesis;
20
- #stateRoot;
21
- constructor(genesis) {
22
- this.#genesis = genesis;
23
- this.#stateRoot = (0, executor_1.calculateStateRoot)(Object.entries(this.#genesis.genesis.raw.top).reduce((accu, item) => {
24
- accu.push(item);
25
- return accu;
26
- }, []), 1);
27
- this.#eventemitter = new node_events_1.EventEmitter();
28
- this.#isReadyPromise = new Promise((resolve, reject) => {
29
- this.#eventemitter.once('connected', () => {
30
- resolve();
31
- });
32
- this.#eventemitter.once('error', reject);
33
- });
34
- }
35
- static fromUrl = async (url) => {
36
- let file;
37
- if ((0, utils_1.isUrl)(url)) {
38
- file = await axios_1.default.get(url).then((x) => x.data);
39
- }
40
- else if ((0, node_fs_1.lstatSync)(url).isFile()) {
41
- file = JSON.parse(String((0, node_fs_1.readFileSync)(url)));
42
- }
43
- else {
44
- throw Error(`invalid genesis path or url ${url}`);
45
- }
46
- return new GenesisProvider(schema_1.genesisSchema.parse(file));
47
- };
48
- get isClonable() {
49
- return true;
50
- }
51
- clone = () => {
52
- return new GenesisProvider(this.#genesis);
53
- };
54
- get hasSubscriptions() {
55
- return false;
56
- }
57
- get isConnected() {
58
- return this.#isConnected;
59
- }
60
- get isReady() {
61
- this.connect();
62
- return this.#isReadyPromise;
63
- }
64
- connect = async () => {
65
- this.#isConnected = true;
66
- this.#eventemitter.emit('connected');
67
- };
68
- disconnect = async () => {
69
- this.#isConnected = false;
70
- this.#eventemitter.emit('disconnected');
71
- };
72
- on = (type, sub) => {
73
- this.#eventemitter.on(type, sub);
74
- return () => {
75
- this.#eventemitter.removeListener(type, sub);
76
- };
77
- };
78
- get blockHash() {
79
- return '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3';
80
- }
81
- getHeader = async () => {
82
- return {
83
- blockHash: this.blockHash,
84
- number: 0,
85
- stateRoot: await this.#stateRoot,
86
- digest: {
87
- logs: [],
88
- },
89
- };
90
- };
91
- getBlock = async () => {
92
- return {
93
- block: {
94
- header: await this.getHeader(),
95
- extrinsics: [],
96
- },
97
- };
98
- };
99
- get _jsCallback() {
100
- const storage = this.#genesis.genesis.raw.top;
101
- return {
102
- ...executor_1.emptyTaskHandler,
103
- getStorage: async function (key) {
104
- return storage[key];
105
- },
106
- getStateRoot: async function () {
107
- return '0x49416764844ff0d8bad851e8abe686dff9dd2de78621180ef8e9f99bb7a480f1';
108
- },
109
- getNextKey: async function (_prefix, _key) {
110
- return undefined;
111
- },
112
- };
113
- }
114
- send = async (method, params, _isCacheable) => {
115
- await this.isReady;
116
- switch (method) {
117
- case 'system_properties':
118
- return this.#genesis.properties;
119
- case 'system_chain':
120
- return this.#genesis.id;
121
- case 'system_name':
122
- return this.#genesis.name;
123
- case 'state_getMetadata': {
124
- const code = this.#genesis.genesis.raw.top[(0, util_1.stringToHex)(':code')];
125
- return (0, executor_1.runTask)({
126
- wasm: code,
127
- calls: [['Metadata_metadata', []]],
128
- mockSignatureHost: false,
129
- allowUnresolvedImports: true,
130
- runtimeLogLevel: 0,
131
- }, this._jsCallback);
132
- }
133
- case 'chain_getHeader':
134
- return this.getHeader();
135
- case 'chain_getBlock':
136
- return this.getBlock();
137
- case 'chain_getBlockHash':
138
- return this.blockHash;
139
- case 'state_getKeysPagedAt':
140
- return [];
141
- case 'state_getStorage':
142
- case 'state_getStorageAt':
143
- return this.#genesis.genesis.raw.top[params[0]];
144
- default:
145
- throw Error(`${method} not implemented`);
146
- }
147
- };
148
- subscribe = async (_type, _method, _params, _cb) => {
149
- throw Error('unimplemented');
150
- };
151
- unsubscribe = async (_type, _method, _id) => {
152
- throw Error('unimplemented');
153
- };
154
- }
155
- exports.GenesisProvider = GenesisProvider;
package/lib/offchain.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import { Block } from './blockchain/block';
2
- import { HexString } from '@polkadot/util/types';
3
- export declare class OffchainWorker {
4
- readonly pendingExtrinsics: HexString[];
5
- readonly offchainStorage: Map<string, string | null | undefined>;
6
- get(key: string): string | null | undefined;
7
- set(key: string, value: string | null | undefined): void;
8
- run(block: Block): Promise<void>;
9
- pushExtrinsic(block: Block, extrinsic: HexString): Promise<`0x${string}`>;
10
- }