@acala-network/chopsticks-core 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 (65) hide show
  1. package/lib/api.d.ts +43 -0
  2. package/lib/api.js +116 -0
  3. package/lib/blockchain/block-builder.d.ts +10 -0
  4. package/lib/blockchain/block-builder.js +290 -0
  5. package/lib/blockchain/block.d.ts +45 -0
  6. package/lib/blockchain/block.js +221 -0
  7. package/lib/blockchain/head-state.d.ts +15 -0
  8. package/lib/blockchain/head-state.js +94 -0
  9. package/lib/blockchain/index.d.ts +73 -0
  10. package/lib/blockchain/index.js +351 -0
  11. package/lib/blockchain/inherent/index.d.ts +19 -0
  12. package/lib/blockchain/inherent/index.js +53 -0
  13. package/lib/blockchain/inherent/para-enter.d.ts +7 -0
  14. package/lib/blockchain/inherent/para-enter.js +37 -0
  15. package/lib/blockchain/inherent/parachain/babe-randomness.d.ts +7 -0
  16. package/lib/blockchain/inherent/parachain/babe-randomness.js +23 -0
  17. package/lib/blockchain/inherent/parachain/nimbus-author-inherent.d.ts +7 -0
  18. package/lib/blockchain/inherent/parachain/nimbus-author-inherent.js +23 -0
  19. package/lib/blockchain/inherent/parachain/validation-data.d.ts +19 -0
  20. package/lib/blockchain/inherent/parachain/validation-data.js +165 -0
  21. package/lib/blockchain/storage-layer.d.ts +32 -0
  22. package/lib/blockchain/storage-layer.js +242 -0
  23. package/lib/blockchain/txpool.d.ts +44 -0
  24. package/lib/blockchain/txpool.js +210 -0
  25. package/lib/db/browser.d.ts +2 -0
  26. package/lib/db/browser.js +33 -0
  27. package/lib/db/entities.d.ts +16 -0
  28. package/lib/db/entities.js +50 -0
  29. package/lib/db/index.d.ts +1 -0
  30. package/lib/db/index.js +17 -0
  31. package/lib/db/node.d.ts +2 -0
  32. package/lib/db/node.js +22 -0
  33. package/lib/executor.d.ts +41 -0
  34. package/lib/executor.js +160 -0
  35. package/lib/genesis-provider.d.ts +44 -0
  36. package/lib/genesis-provider.js +172 -0
  37. package/lib/index.d.ts +13 -0
  38. package/lib/index.js +13 -0
  39. package/lib/logger.d.ts +7 -0
  40. package/lib/logger.js +34 -0
  41. package/lib/offchain.d.ts +10 -0
  42. package/lib/offchain.js +49 -0
  43. package/lib/schema/index.d.ts +62 -0
  44. package/lib/schema/index.js +11 -0
  45. package/lib/setup.d.ts +20 -0
  46. package/lib/setup.js +74 -0
  47. package/lib/utils/index.d.ts +18 -0
  48. package/lib/utils/index.js +65 -0
  49. package/lib/utils/key-cache.d.ts +10 -0
  50. package/lib/utils/key-cache.js +72 -0
  51. package/lib/utils/proof.d.ts +15 -0
  52. package/lib/utils/proof.js +33 -0
  53. package/lib/utils/set-storage.d.ts +7 -0
  54. package/lib/utils/set-storage.js +65 -0
  55. package/lib/utils/time-travel.d.ts +5 -0
  56. package/lib/utils/time-travel.js +67 -0
  57. package/lib/xcm/downward.d.ts +2 -0
  58. package/lib/xcm/downward.js +34 -0
  59. package/lib/xcm/horizontal.d.ts +2 -0
  60. package/lib/xcm/horizontal.js +34 -0
  61. package/lib/xcm/index.d.ts +9 -0
  62. package/lib/xcm/index.js +29 -0
  63. package/lib/xcm/upward.d.ts +2 -0
  64. package/lib/xcm/upward.js +26 -0
  65. package/package.json +46 -0
@@ -0,0 +1,210 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
11
+ if (kind === "m") throw new TypeError("Private method is not writable");
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
14
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
15
+ };
16
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
17
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
18
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
19
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
20
+ };
21
+ var _TxPool_instances, _TxPool_chain, _TxPool_pool, _TxPool_ump, _TxPool_dmp, _TxPool_hrmp, _TxPool_mode, _TxPool_inherentProvider, _TxPool_pendingBlocks, _TxPool_isBuilding, _TxPool_getSigner, _TxPool_maybeBuildBlock, _TxPool_batchBuildBlock, _TxPool_buildBlockIfNeeded, _TxPool_buildBlock;
22
+ import { EventEmitter } from 'eventemitter3';
23
+ import _ from 'lodash';
24
+ import { defer } from '../utils';
25
+ import { buildBlock } from './block-builder';
26
+ import { defaultLogger, truncate } from '../logger';
27
+ const logger = defaultLogger.child({ name: 'txpool' });
28
+ export const APPLY_EXTRINSIC_ERROR = 'TxPool::ApplyExtrinsicError';
29
+ export var BuildBlockMode;
30
+ (function (BuildBlockMode) {
31
+ BuildBlockMode[BuildBlockMode["Batch"] = 0] = "Batch";
32
+ BuildBlockMode[BuildBlockMode["Instant"] = 1] = "Instant";
33
+ BuildBlockMode[BuildBlockMode["Manual"] = 2] = "Manual";
34
+ })(BuildBlockMode || (BuildBlockMode = {}));
35
+ export class TxPool {
36
+ constructor(chain, inherentProvider, mode = BuildBlockMode.Batch) {
37
+ _TxPool_instances.add(this);
38
+ _TxPool_chain.set(this, void 0);
39
+ _TxPool_pool.set(this, []);
40
+ _TxPool_ump.set(this, {});
41
+ _TxPool_dmp.set(this, []);
42
+ _TxPool_hrmp.set(this, {});
43
+ _TxPool_mode.set(this, void 0);
44
+ _TxPool_inherentProvider.set(this, void 0);
45
+ _TxPool_pendingBlocks.set(this, []);
46
+ this.event = new EventEmitter();
47
+ _TxPool_isBuilding.set(this, false);
48
+ _TxPool_batchBuildBlock.set(this, _.debounce(this.buildBlock, 100, { maxWait: 1000 }));
49
+ __classPrivateFieldSet(this, _TxPool_chain, chain, "f");
50
+ __classPrivateFieldSet(this, _TxPool_mode, mode, "f");
51
+ __classPrivateFieldSet(this, _TxPool_inherentProvider, inherentProvider, "f");
52
+ }
53
+ get pendingExtrinsics() {
54
+ return __classPrivateFieldGet(this, _TxPool_pool, "f").map(({ extrinsic }) => extrinsic);
55
+ }
56
+ get ump() {
57
+ return __classPrivateFieldGet(this, _TxPool_ump, "f");
58
+ }
59
+ get dmp() {
60
+ return __classPrivateFieldGet(this, _TxPool_dmp, "f");
61
+ }
62
+ get hrmp() {
63
+ return __classPrivateFieldGet(this, _TxPool_hrmp, "f");
64
+ }
65
+ get mode() {
66
+ return __classPrivateFieldGet(this, _TxPool_mode, "f");
67
+ }
68
+ set mode(mode) {
69
+ __classPrivateFieldSet(this, _TxPool_mode, mode, "f");
70
+ }
71
+ clear() {
72
+ __classPrivateFieldGet(this, _TxPool_pool, "f").length = 0;
73
+ for (const id of Object.keys(__classPrivateFieldGet(this, _TxPool_ump, "f"))) {
74
+ delete __classPrivateFieldGet(this, _TxPool_ump, "f")[id];
75
+ }
76
+ __classPrivateFieldGet(this, _TxPool_dmp, "f").length = 0;
77
+ for (const id of Object.keys(__classPrivateFieldGet(this, _TxPool_hrmp, "f"))) {
78
+ delete __classPrivateFieldGet(this, _TxPool_hrmp, "f")[id];
79
+ }
80
+ }
81
+ pendingExtrinsicsBy(address) {
82
+ return __classPrivateFieldGet(this, _TxPool_pool, "f").filter(({ signer }) => signer === address).map(({ extrinsic }) => extrinsic);
83
+ }
84
+ submitExtrinsic(extrinsic) {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ logger.debug({ extrinsic: truncate(extrinsic) }, 'submit extrinsic');
87
+ __classPrivateFieldGet(this, _TxPool_pool, "f").push({ extrinsic, signer: yield __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_getSigner).call(this, extrinsic) });
88
+ __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_maybeBuildBlock).call(this);
89
+ });
90
+ }
91
+ submitUpwardMessages(id, ump) {
92
+ logger.debug({ id, ump: truncate(ump) }, 'submit upward messages');
93
+ if (!__classPrivateFieldGet(this, _TxPool_ump, "f")[id]) {
94
+ __classPrivateFieldGet(this, _TxPool_ump, "f")[id] = [];
95
+ }
96
+ __classPrivateFieldGet(this, _TxPool_ump, "f")[id].push(...ump);
97
+ __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_maybeBuildBlock).call(this);
98
+ }
99
+ submitDownwardMessages(dmp) {
100
+ logger.debug({ dmp: truncate(dmp) }, 'submit downward messages');
101
+ __classPrivateFieldGet(this, _TxPool_dmp, "f").push(...dmp);
102
+ __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_maybeBuildBlock).call(this);
103
+ }
104
+ submitHorizontalMessages(id, hrmp) {
105
+ logger.debug({ id, hrmp: truncate(hrmp) }, 'submit horizontal messages');
106
+ if (!__classPrivateFieldGet(this, _TxPool_hrmp, "f")[id]) {
107
+ __classPrivateFieldGet(this, _TxPool_hrmp, "f")[id] = [];
108
+ }
109
+ __classPrivateFieldGet(this, _TxPool_hrmp, "f")[id].push(...hrmp);
110
+ __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_maybeBuildBlock).call(this);
111
+ }
112
+ buildBlockWithParams(params) {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ __classPrivateFieldGet(this, _TxPool_pendingBlocks, "f").push({
115
+ params,
116
+ deferred: defer(),
117
+ });
118
+ __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_buildBlockIfNeeded).call(this);
119
+ yield this.upcomingBlocks();
120
+ });
121
+ }
122
+ buildBlock(params) {
123
+ return __awaiter(this, void 0, void 0, function* () {
124
+ const transactions = (params === null || params === void 0 ? void 0 : params.transactions) || __classPrivateFieldGet(this, _TxPool_pool, "f").splice(0).map(({ extrinsic }) => extrinsic);
125
+ const upwardMessages = (params === null || params === void 0 ? void 0 : params.upwardMessages) || Object.assign({}, __classPrivateFieldGet(this, _TxPool_ump, "f"));
126
+ const downwardMessages = (params === null || params === void 0 ? void 0 : params.downwardMessages) || __classPrivateFieldGet(this, _TxPool_dmp, "f").splice(0);
127
+ const horizontalMessages = (params === null || params === void 0 ? void 0 : params.horizontalMessages) || Object.assign({}, __classPrivateFieldGet(this, _TxPool_hrmp, "f"));
128
+ if (!(params === null || params === void 0 ? void 0 : params.upwardMessages)) {
129
+ for (const id of Object.keys(__classPrivateFieldGet(this, _TxPool_ump, "f"))) {
130
+ delete __classPrivateFieldGet(this, _TxPool_ump, "f")[id];
131
+ }
132
+ }
133
+ if (!(params === null || params === void 0 ? void 0 : params.horizontalMessages)) {
134
+ for (const id of Object.keys(__classPrivateFieldGet(this, _TxPool_hrmp, "f"))) {
135
+ delete __classPrivateFieldGet(this, _TxPool_hrmp, "f")[id];
136
+ }
137
+ }
138
+ yield this.buildBlockWithParams({
139
+ transactions,
140
+ upwardMessages,
141
+ downwardMessages,
142
+ horizontalMessages,
143
+ });
144
+ });
145
+ }
146
+ upcomingBlocks() {
147
+ return __awaiter(this, void 0, void 0, function* () {
148
+ const count = __classPrivateFieldGet(this, _TxPool_pendingBlocks, "f").length;
149
+ if (count > 0) {
150
+ yield __classPrivateFieldGet(this, _TxPool_pendingBlocks, "f")[count - 1].deferred.promise;
151
+ }
152
+ return count;
153
+ });
154
+ }
155
+ }
156
+ _TxPool_chain = new WeakMap(), _TxPool_pool = new WeakMap(), _TxPool_ump = new WeakMap(), _TxPool_dmp = new WeakMap(), _TxPool_hrmp = new WeakMap(), _TxPool_mode = new WeakMap(), _TxPool_inherentProvider = new WeakMap(), _TxPool_pendingBlocks = new WeakMap(), _TxPool_isBuilding = new WeakMap(), _TxPool_batchBuildBlock = new WeakMap(), _TxPool_instances = new WeakSet(), _TxPool_getSigner = function _TxPool_getSigner(extrinsic) {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ const registry = yield __classPrivateFieldGet(this, _TxPool_chain, "f").head.registry;
159
+ const tx = registry.createType('GenericExtrinsic', extrinsic);
160
+ return tx.signer.toString();
161
+ });
162
+ }, _TxPool_maybeBuildBlock = function _TxPool_maybeBuildBlock() {
163
+ switch (__classPrivateFieldGet(this, _TxPool_mode, "f")) {
164
+ case BuildBlockMode.Batch:
165
+ __classPrivateFieldGet(this, _TxPool_batchBuildBlock, "f").call(this);
166
+ break;
167
+ case BuildBlockMode.Instant:
168
+ this.buildBlock();
169
+ break;
170
+ case BuildBlockMode.Manual:
171
+ // does nothing
172
+ break;
173
+ }
174
+ }, _TxPool_buildBlockIfNeeded = function _TxPool_buildBlockIfNeeded() {
175
+ return __awaiter(this, void 0, void 0, function* () {
176
+ if (__classPrivateFieldGet(this, _TxPool_isBuilding, "f"))
177
+ return;
178
+ if (__classPrivateFieldGet(this, _TxPool_pendingBlocks, "f").length === 0)
179
+ return;
180
+ __classPrivateFieldSet(this, _TxPool_isBuilding, true, "f");
181
+ try {
182
+ yield __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_buildBlock).call(this);
183
+ }
184
+ finally {
185
+ __classPrivateFieldSet(this, _TxPool_isBuilding, false, "f");
186
+ }
187
+ __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_buildBlockIfNeeded).call(this);
188
+ });
189
+ }, _TxPool_buildBlock = function _TxPool_buildBlock() {
190
+ return __awaiter(this, void 0, void 0, function* () {
191
+ yield __classPrivateFieldGet(this, _TxPool_chain, "f").api.isReady;
192
+ const pending = __classPrivateFieldGet(this, _TxPool_pendingBlocks, "f")[0];
193
+ if (!pending) {
194
+ throw new Error('Unreachable');
195
+ }
196
+ const { params, deferred } = pending;
197
+ logger.trace({ params }, 'build block');
198
+ const head = __classPrivateFieldGet(this, _TxPool_chain, "f").head;
199
+ const inherents = yield __classPrivateFieldGet(this, _TxPool_inherentProvider, "f").createInherents(head, params);
200
+ const [newBlock, pendingExtrinsics] = yield buildBlock(head, inherents, params.transactions, params.upwardMessages, (extrinsic, error) => {
201
+ this.event.emit(APPLY_EXTRINSIC_ERROR, [extrinsic, error]);
202
+ });
203
+ for (const extrinsic of pendingExtrinsics) {
204
+ __classPrivateFieldGet(this, _TxPool_pool, "f").push({ extrinsic, signer: yield __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_getSigner).call(this, extrinsic) });
205
+ }
206
+ yield __classPrivateFieldGet(this, _TxPool_chain, "f").onNewBlock(newBlock);
207
+ __classPrivateFieldGet(this, _TxPool_pendingBlocks, "f").shift();
208
+ deferred.resolve();
209
+ });
210
+ };
@@ -0,0 +1,2 @@
1
+ import { DataSource } from 'typeorm';
2
+ export declare const openDb: (dbPath: string) => Promise<DataSource>;
@@ -0,0 +1,33 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { DataSource } from 'typeorm';
11
+ import { createInstance } from 'localforage';
12
+ import initSqlJs from 'sql.js';
13
+ globalThis.localforage = createInstance({ name: 'chopsticks' });
14
+ import * as entities from './entities';
15
+ export const openDb = (dbPath) => __awaiter(void 0, void 0, void 0, function* () {
16
+ const wasmUrl = new URL('../../../../node_modules/sql.js/dist/sql-wasm.wasm', import.meta.url);
17
+ const wasmBinary = yield fetch(wasmUrl).then((response) => response.arrayBuffer());
18
+ const source = new DataSource({
19
+ type: 'sqljs',
20
+ location: dbPath,
21
+ entities: Object.values(entities),
22
+ synchronize: true,
23
+ autoSave: true,
24
+ logging: false,
25
+ useLocalForage: true,
26
+ driver: initSqlJs,
27
+ sqlJsConfig: {
28
+ wasmBinary,
29
+ },
30
+ });
31
+ yield source.initialize();
32
+ return source;
33
+ });
@@ -0,0 +1,16 @@
1
+ import { EntitySchema } from 'typeorm';
2
+ import { Header } from '@polkadot/types/interfaces';
3
+ import { HexString } from '@polkadot/util/types';
4
+ export declare const KeyValuePair: EntitySchema<{
5
+ blockHash: string;
6
+ key: string;
7
+ value?: string | undefined;
8
+ }>;
9
+ export declare const BlockEntity: EntitySchema<{
10
+ hash: HexString;
11
+ number: number;
12
+ header: Header;
13
+ parentHash?: `0x${string}` | undefined;
14
+ extrinsics: HexString[];
15
+ storageDiff?: Record<`0x${string}`, `0x${string}` | null> | undefined;
16
+ }>;
@@ -0,0 +1,50 @@
1
+ import { EntitySchema } from 'typeorm';
2
+ export const KeyValuePair = new EntitySchema({
3
+ name: 'KeyValuePair',
4
+ columns: {
5
+ blockHash: {
6
+ primary: true,
7
+ type: 'varchar',
8
+ nullable: false,
9
+ },
10
+ key: {
11
+ primary: true,
12
+ type: 'varchar',
13
+ nullable: false,
14
+ },
15
+ value: {
16
+ type: 'text',
17
+ nullable: true,
18
+ },
19
+ },
20
+ });
21
+ export const BlockEntity = new EntitySchema({
22
+ name: 'Block',
23
+ columns: {
24
+ hash: {
25
+ primary: true,
26
+ type: 'varchar',
27
+ nullable: false,
28
+ },
29
+ number: {
30
+ type: 'int',
31
+ nullable: false,
32
+ },
33
+ header: {
34
+ type: 'simple-json',
35
+ nullable: false,
36
+ },
37
+ parentHash: {
38
+ type: 'varchar',
39
+ nullable: true,
40
+ },
41
+ extrinsics: {
42
+ type: 'simple-array',
43
+ nullable: false,
44
+ },
45
+ storageDiff: {
46
+ type: 'simple-json',
47
+ nullable: true,
48
+ },
49
+ },
50
+ });
@@ -0,0 +1 @@
1
+ export declare const openDb: (dbPath: string) => Promise<import("typeorm").DataSource>;
@@ -0,0 +1,17 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ export const openDb = (dbPath) => __awaiter(void 0, void 0, void 0, function* () {
11
+ if (typeof window === 'undefined') {
12
+ return (yield import('./node')).openDb(dbPath);
13
+ }
14
+ else {
15
+ return (yield import('./browser')).openDb(dbPath);
16
+ }
17
+ });
@@ -0,0 +1,2 @@
1
+ import { DataSource } from 'typeorm';
2
+ export declare const openDb: (dbPath: string) => Promise<DataSource>;
package/lib/db/node.js ADDED
@@ -0,0 +1,22 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { DataSource } from 'typeorm';
11
+ import * as entities from './entities';
12
+ export const openDb = (dbPath) => __awaiter(void 0, void 0, void 0, function* () {
13
+ const source = new DataSource({
14
+ type: 'sqlite',
15
+ database: dbPath,
16
+ entities: Object.values(entities),
17
+ synchronize: true,
18
+ logging: false,
19
+ });
20
+ yield source.initialize();
21
+ return source;
22
+ });
@@ -0,0 +1,41 @@
1
+ import { HexString } from '@polkadot/util/types';
2
+ import { Block } from './blockchain/block';
3
+ import { Registry } from '@polkadot/types-codec/types';
4
+ import _ from 'lodash';
5
+ import type { JsCallback } from '@acala-network/chopsticks-executor';
6
+ export { JsCallback };
7
+ export type RuntimeVersion = {
8
+ specName: string;
9
+ implName: string;
10
+ authoringVersion: number;
11
+ specVersion: number;
12
+ implVersion: number;
13
+ apis: [HexString, number][];
14
+ transactionVersion: number;
15
+ stateVersion: number;
16
+ };
17
+ export declare const getRuntimeVersion: (code: HexString) => Promise<RuntimeVersion>;
18
+ export declare const calculateStateRoot: (entries: [HexString, HexString][], trie_version: number) => Promise<HexString>;
19
+ export declare const decodeProof: (trieRootHash: HexString, keys: HexString[], nodes: HexString[]) => Promise<Record<`0x${string}`, `0x${string}` | null>>;
20
+ export declare const createProof: (nodes: HexString[], entries: [HexString, HexString | null][]) => Promise<{
21
+ trieRootHash: `0x${string}`;
22
+ nodes: `0x${string}`[];
23
+ }>;
24
+ export declare const runTask: (task: {
25
+ wasm: HexString;
26
+ calls: [string, HexString[]][];
27
+ mockSignatureHost: boolean;
28
+ allowUnresolvedImports: boolean;
29
+ runtimeLogLevel: number;
30
+ }, callback?: JsCallback) => Promise<any>;
31
+ export declare const taskHandler: (block: Block) => JsCallback;
32
+ export declare const emptyTaskHandler: {
33
+ getStorage: (_key: HexString) => Promise<never>;
34
+ getStateRoot: () => Promise<never>;
35
+ getNextKey: (_prefix: HexString, _key: HexString) => Promise<never>;
36
+ offchainGetStorage: (_key: HexString) => Promise<never>;
37
+ offchainTimestamp: () => Promise<never>;
38
+ offchainRandomSeed: () => Promise<never>;
39
+ offchainSubmitTransaction: (_tx: HexString) => Promise<never>;
40
+ };
41
+ export declare const getAuraSlotDuration: ((wasm: HexString, registry: Registry) => Promise<number>) & _.MemoizedFunction;
@@ -0,0 +1,160 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { hexToString, hexToU8a } from '@polkadot/util';
11
+ import { randomAsHex } from '@polkadot/util-crypto';
12
+ import { PREFIX_LENGTH } from './utils/key-cache';
13
+ import { defaultLogger, truncate } from './logger';
14
+ import _ from 'lodash';
15
+ import wasmSetup, { calculate_state_root, create_proof, decode_proof, get_runtime_version, run_task, } from '@acala-network/chopsticks-executor';
16
+ const logger = defaultLogger.child({ name: 'executor' });
17
+ // init wasm on browser
18
+ if (typeof wasmSetup === 'function') {
19
+ wasmSetup();
20
+ }
21
+ export const getRuntimeVersion = (code) => __awaiter(void 0, void 0, void 0, function* () {
22
+ return get_runtime_version(code).then((version) => {
23
+ version.specName = hexToString(version.specName);
24
+ version.implName = hexToString(version.implName);
25
+ return version;
26
+ });
27
+ });
28
+ // trie_version: 0 for old trie, 1 for new trie
29
+ export const calculateStateRoot = (entries, trie_version) => __awaiter(void 0, void 0, void 0, function* () {
30
+ return calculate_state_root(entries, trie_version);
31
+ });
32
+ export const decodeProof = (trieRootHash, keys, nodes) => __awaiter(void 0, void 0, void 0, function* () {
33
+ const decoded = yield decode_proof(trieRootHash, keys, nodes);
34
+ return decoded.reduce((accum, [key, value]) => {
35
+ accum[key] = value;
36
+ return accum;
37
+ }, {});
38
+ });
39
+ export const createProof = (nodes, entries) => __awaiter(void 0, void 0, void 0, function* () {
40
+ const result = yield create_proof(nodes, entries);
41
+ return { trieRootHash: result[0], nodes: result[1] };
42
+ });
43
+ export const runTask = (task, callback = emptyTaskHandler) => __awaiter(void 0, void 0, void 0, function* () {
44
+ logger.trace(truncate(task), 'taskRun');
45
+ const response = yield run_task(task, callback, typeof process === 'object' ? process.env.RUST_LOG : 'info');
46
+ if (response.Call) {
47
+ logger.trace(truncate(response.Call), 'taskResponse');
48
+ }
49
+ else {
50
+ logger.trace({ response }, 'taskResponse');
51
+ }
52
+ return response;
53
+ });
54
+ export const taskHandler = (block) => {
55
+ return {
56
+ getStorage: function (key) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ return block.get(key);
59
+ });
60
+ },
61
+ getStateRoot: function () {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ const header = yield block.header;
64
+ return header.stateRoot.toHex();
65
+ });
66
+ },
67
+ getNextKey: function (prefix, key) {
68
+ return __awaiter(this, void 0, void 0, function* () {
69
+ const [nextKey] = yield block.getKeysPaged({
70
+ prefix: prefix.length === 2 /** 0x */ ? key.slice(0, PREFIX_LENGTH) : prefix,
71
+ pageSize: 1,
72
+ startKey: key,
73
+ });
74
+ return nextKey;
75
+ });
76
+ },
77
+ offchainGetStorage: function (key) {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ if (!block.chain.offchainWorker)
80
+ throw new Error('offchain worker not found');
81
+ return block.chain.offchainWorker.get(key);
82
+ });
83
+ },
84
+ offchainTimestamp: function () {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ return Date.now();
87
+ });
88
+ },
89
+ offchainRandomSeed: function () {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ return randomAsHex(32);
92
+ });
93
+ },
94
+ offchainSubmitTransaction: function (tx) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ if (!block.chain.offchainWorker)
97
+ throw new Error('offchain worker not found');
98
+ try {
99
+ const hash = yield block.chain.offchainWorker.pushExtrinsic(block, tx);
100
+ logger.trace({ hash }, 'offchainSubmitTransaction');
101
+ return true;
102
+ }
103
+ catch (error) {
104
+ logger.trace({ error }, 'offchainSubmitTransaction');
105
+ return false;
106
+ }
107
+ });
108
+ },
109
+ };
110
+ };
111
+ export const emptyTaskHandler = {
112
+ getStorage: function (_key) {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ throw new Error('Method not implemented');
115
+ });
116
+ },
117
+ getStateRoot: function () {
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ throw new Error('Method not implemented');
120
+ });
121
+ },
122
+ getNextKey: function (_prefix, _key) {
123
+ return __awaiter(this, void 0, void 0, function* () {
124
+ throw new Error('Method not implemented');
125
+ });
126
+ },
127
+ offchainGetStorage: function (_key) {
128
+ return __awaiter(this, void 0, void 0, function* () {
129
+ throw new Error('Method not implemented');
130
+ });
131
+ },
132
+ offchainTimestamp: function () {
133
+ return __awaiter(this, void 0, void 0, function* () {
134
+ throw new Error('Method not implemented');
135
+ });
136
+ },
137
+ offchainRandomSeed: function () {
138
+ return __awaiter(this, void 0, void 0, function* () {
139
+ throw new Error('Method not implemented');
140
+ });
141
+ },
142
+ offchainSubmitTransaction: function (_tx) {
143
+ return __awaiter(this, void 0, void 0, function* () {
144
+ throw new Error('Method not implemented');
145
+ });
146
+ },
147
+ };
148
+ export const getAuraSlotDuration = _.memoize((wasm, registry) => __awaiter(void 0, void 0, void 0, function* () {
149
+ const result = yield runTask({
150
+ wasm,
151
+ calls: [['AuraApi_slot_duration', []]],
152
+ mockSignatureHost: false,
153
+ allowUnresolvedImports: false,
154
+ runtimeLogLevel: 0,
155
+ });
156
+ if (!result.Call)
157
+ throw new Error(result.Error);
158
+ const slotDuration = registry.createType('u64', hexToU8a(result.Call.result)).toNumber();
159
+ return slotDuration;
160
+ }));
@@ -0,0 +1,44 @@
1
+ import { HexString } from '@polkadot/util/types';
2
+ import { ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '@polkadot/rpc-provider/types';
3
+ import { Genesis } from './schema';
4
+ import { JsCallback } from './executor';
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
+ }