@acala-network/chopsticks-core 0.8.2 → 0.8.4

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 (43) hide show
  1. package/lib/blockchain/block-builder.d.ts +5 -1
  2. package/lib/blockchain/block-builder.js +21 -20
  3. package/lib/blockchain/block.d.ts +1 -1
  4. package/lib/blockchain/block.js +4 -4
  5. package/lib/blockchain/index.d.ts +2 -2
  6. package/lib/blockchain/index.js +4 -2
  7. package/lib/blockchain/inherent/parachain/validation-data.js +5 -5
  8. package/lib/blockchain/storage-layer.js +25 -2
  9. package/lib/blockchain/txpool.js +18 -2
  10. package/lib/chopsticks-provider.d.ts +0 -0
  11. package/lib/chopsticks-provider.js +249 -0
  12. package/lib/chopsticks-worker.d.ts +1 -0
  13. package/lib/chopsticks-worker.js +101 -0
  14. package/lib/genesis-provider.d.ts +1 -1
  15. package/lib/genesis-provider.js +3 -3
  16. package/lib/index.d.ts +2 -1
  17. package/lib/index.js +3 -1
  18. package/lib/rpc/index.d.ts +5 -0
  19. package/lib/rpc/index.js +26 -0
  20. package/lib/rpc/shared.d.ts +27 -0
  21. package/lib/rpc/shared.js +19 -0
  22. package/lib/rpc/substrate/author.d.ts +28 -0
  23. package/lib/rpc/substrate/author.js +98 -0
  24. package/lib/rpc/substrate/chain.d.ts +45 -0
  25. package/lib/rpc/substrate/chain.js +103 -0
  26. package/lib/rpc/substrate/index.d.ts +66 -0
  27. package/lib/rpc/substrate/index.js +38 -0
  28. package/lib/rpc/substrate/payment.d.ts +16 -0
  29. package/lib/rpc/substrate/payment.js +54 -0
  30. package/lib/rpc/substrate/state.d.ts +97 -0
  31. package/lib/rpc/substrate/state.js +184 -0
  32. package/lib/rpc/substrate/system.d.ts +28 -0
  33. package/lib/rpc/substrate/system.js +71 -0
  34. package/lib/utils/time-travel.js +2 -2
  35. package/lib/wasm-executor/browser-wasm-executor.mjs +37 -0
  36. package/lib/wasm-executor/browser-worker.d.ts +5 -0
  37. package/lib/wasm-executor/browser-worker.js +28 -0
  38. package/lib/{executor.d.ts → wasm-executor/index.d.ts} +18 -1
  39. package/lib/{executor.js → wasm-executor/index.js} +60 -15
  40. package/lib/wasm-executor/node-wasm-executor.mjs +34 -0
  41. package/lib/wasm-executor/node-worker.d.ts +5 -0
  42. package/lib/wasm-executor/node-worker.js +31 -0
  43. package/package.json +6 -4
@@ -2,7 +2,11 @@ import { Header, TransactionValidityError } from '@polkadot/types/interfaces';
2
2
  import { Block, TaskCallResponse } from './block';
3
3
  import { HexString } from '@polkadot/util/types';
4
4
  export declare const newHeader: (head: Block, unsafeBlockHeight?: number) => Promise<Header>;
5
- export declare const buildBlock: (head: Block, inherents: HexString[], extrinsics: HexString[], ump: Record<number, HexString[]>, onApplyExtrinsicError: (extrinsic: HexString, error: TransactionValidityError) => void, unsafeBlockHeight?: number) => Promise<[Block, HexString[]]>;
5
+ export type BuildBlockCallbacks = {
6
+ onApplyExtrinsicError?: (extrinsic: HexString, error: TransactionValidityError) => void;
7
+ onPhaseApplied?: (phase: 'initialize' | 'finalize' | number, resp: TaskCallResponse) => void;
8
+ };
9
+ export declare const buildBlock: (head: Block, inherents: HexString[], extrinsics: HexString[], ump: Record<number, HexString[]>, callbacks?: BuildBlockCallbacks, unsafeBlockHeight?: number) => Promise<[Block, HexString[]]>;
6
10
  export declare const dryRunExtrinsic: (head: Block, inherents: HexString[], extrinsic: HexString | {
7
11
  call: HexString;
8
12
  address: string;
@@ -90,7 +90,8 @@ const newHeader = (head, unsafeBlockHeight) => __awaiter(void 0, void 0, void 0,
90
90
  return header;
91
91
  });
92
92
  exports.newHeader = newHeader;
93
- const initNewBlock = (head, header, inherents, storageLayer) => __awaiter(void 0, void 0, void 0, function* () {
93
+ const initNewBlock = (head, header, inherents, storageLayer, callback) => __awaiter(void 0, void 0, void 0, function* () {
94
+ var _c, _d;
94
95
  const blockNumber = header.number.toNumber();
95
96
  const hash = `0x${Math.round(Math.random() * 100000000)
96
97
  .toString(16)
@@ -102,19 +103,19 @@ const initNewBlock = (head, header, inherents, storageLayer) => __awaiter(void 0
102
103
  });
103
104
  {
104
105
  // initialize block
105
- const { storageDiff } = yield newBlock.call('Core_initialize_block', [header.toHex()]);
106
- newBlock.pushStorageLayer().setAll(storageDiff);
107
- logger.trace((0, logger_1.truncate)(storageDiff), 'Initialize block');
106
+ const resp = yield newBlock.call('Core_initialize_block', [header.toHex()]);
107
+ newBlock.pushStorageLayer().setAll(resp.storageDiff);
108
+ (_c = callback === null || callback === void 0 ? void 0 : callback.onPhaseApplied) === null || _c === void 0 ? void 0 : _c.call(callback, 'initialize', resp);
108
109
  }
109
110
  const layers = [];
110
111
  // apply inherents
111
112
  for (const extrinsic of inherents) {
112
113
  try {
113
- const { storageDiff } = yield newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic]);
114
+ const resp = yield newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic]);
114
115
  const layer = newBlock.pushStorageLayer();
115
- layer.setAll(storageDiff);
116
+ layer.setAll(resp.storageDiff);
116
117
  layers.push(layer);
117
- logger.trace((0, logger_1.truncate)(storageDiff), 'Applied inherent');
118
+ (_d = callback === null || callback === void 0 ? void 0 : callback.onPhaseApplied) === null || _d === void 0 ? void 0 : _d.call(callback, layers.length - 1, resp);
118
119
  }
119
120
  catch (e) {
120
121
  logger.warn('Failed to apply inherents %o %s', e, e);
@@ -126,13 +127,11 @@ const initNewBlock = (head, header, inherents, storageLayer) => __awaiter(void 0
126
127
  layers: layers,
127
128
  };
128
129
  });
129
- const buildBlock = (head, inherents, extrinsics, ump, onApplyExtrinsicError, unsafeBlockHeight) => __awaiter(void 0, void 0, void 0, function* () {
130
+ const buildBlock = (head, inherents, extrinsics, ump, callbacks, unsafeBlockHeight) => __awaiter(void 0, void 0, void 0, function* () {
131
+ var _e, _f, _g;
130
132
  const registry = yield head.registry;
131
133
  const header = yield (0, exports.newHeader)(head, unsafeBlockHeight);
132
134
  const newBlockNumber = header.number.toNumber();
133
- if (newBlockNumber < head.number) {
134
- throw new Error('unsafeBlockHeight is not allowed to be less than current block number');
135
- }
136
135
  logger.info({
137
136
  number: newBlockNumber,
138
137
  extrinsicsCount: extrinsics.length,
@@ -216,15 +215,15 @@ const buildBlock = (head, inherents, extrinsics, ump, onApplyExtrinsicError, uns
216
215
  // apply extrinsics
217
216
  for (const extrinsic of extrinsics) {
218
217
  try {
219
- const { result, storageDiff } = yield newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic]);
220
- const outcome = registry.createType('ApplyExtrinsicResult', result);
218
+ const resp = yield newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic]);
219
+ const outcome = registry.createType('ApplyExtrinsicResult', resp.result);
221
220
  if (outcome.isErr) {
222
- onApplyExtrinsicError(extrinsic, outcome.asErr);
221
+ (_e = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onApplyExtrinsicError) === null || _e === void 0 ? void 0 : _e.call(callbacks, extrinsic, outcome.asErr);
223
222
  continue;
224
223
  }
225
- newBlock.pushStorageLayer().setAll(storageDiff);
226
- logger.trace((0, logger_1.truncate)(storageDiff), 'Applied extrinsic');
224
+ newBlock.pushStorageLayer().setAll(resp.storageDiff);
227
225
  includedExtrinsic.push(extrinsic);
226
+ (_f = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onPhaseApplied) === null || _f === void 0 ? void 0 : _f.call(callbacks, includedExtrinsic.length - 1, resp);
228
227
  }
229
228
  catch (e) {
230
229
  logger.info('Failed to apply extrinsic %o %s', e, e);
@@ -233,16 +232,18 @@ const buildBlock = (head, inherents, extrinsics, ump, onApplyExtrinsicError, uns
233
232
  }
234
233
  {
235
234
  // finalize block
236
- const { storageDiff } = yield newBlock.call('BlockBuilder_finalize_block', []);
237
- newBlock.pushStorageLayer().setAll(storageDiff);
238
- logger.trace((0, logger_1.truncate)(storageDiff), 'Finalize block');
235
+ const resp = yield newBlock.call('BlockBuilder_finalize_block', []);
236
+ newBlock.pushStorageLayer().setAll(resp.storageDiff);
237
+ (_g = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onPhaseApplied) === null || _g === void 0 ? void 0 : _g.call(callbacks, 'finalize', resp);
239
238
  }
240
239
  const blockData = registry.createType('Block', {
241
240
  header,
242
241
  extrinsics: includedExtrinsic,
243
242
  });
244
243
  const storageDiff = yield newBlock.storageDiff();
245
- logger.trace(Object.entries(storageDiff).map(([key, value]) => [key, (0, logger_1.truncate)(value)]), 'Final block');
244
+ if (logger.level.toLowerCase() === 'trace') {
245
+ logger.trace(Object.entries(storageDiff).map(([key, value]) => [key, (0, logger_1.truncate)(value)]), 'Final block');
246
+ }
246
247
  const finalBlock = new block_1.Block(head.chain, newBlock.number, blockData.hash.toHex(), head, {
247
248
  header,
248
249
  extrinsics: [...inherents, ...includedExtrinsic],
@@ -4,7 +4,7 @@ import { TypeRegistry } from '@polkadot/types';
4
4
  import type { HexString } from '@polkadot/util/types';
5
5
  import { Blockchain } from '.';
6
6
  import { StorageLayer, StorageLayerProvider, StorageValue } from './storage-layer';
7
- import type { RuntimeVersion } from '../executor';
7
+ import type { RuntimeVersion } from '../wasm-executor';
8
8
  export type TaskCallResponse = {
9
9
  result: HexString;
10
10
  storageDiff: [HexString, HexString | null][];
@@ -29,7 +29,7 @@ const util_2 = require("@polkadot/util");
29
29
  const storage_layer_1 = require("./storage-layer");
30
30
  const utils_1 = require("../utils");
31
31
  const logger_1 = require("../logger");
32
- const executor_1 = require("../executor");
32
+ const wasm_executor_1 = require("../wasm-executor");
33
33
  /**
34
34
  * Block class.
35
35
  *
@@ -223,7 +223,7 @@ class Block {
223
223
  }
224
224
  get runtimeVersion() {
225
225
  if (!__classPrivateFieldGet(this, _Block_runtimeVersion, "f")) {
226
- __classPrivateFieldSet(this, _Block_runtimeVersion, this.wasm.then(executor_1.getRuntimeVersion), "f");
226
+ __classPrivateFieldSet(this, _Block_runtimeVersion, this.wasm.then(wasm_executor_1.getRuntimeVersion), "f");
227
227
  }
228
228
  return __classPrivateFieldGet(this, _Block_runtimeVersion, "f");
229
229
  }
@@ -248,13 +248,13 @@ class Block {
248
248
  call(method, args) {
249
249
  return __awaiter(this, void 0, void 0, function* () {
250
250
  const wasm = yield this.wasm;
251
- const response = yield (0, executor_1.runTask)({
251
+ const response = yield (0, wasm_executor_1.runTask)({
252
252
  wasm,
253
253
  calls: [[method, args]],
254
254
  mockSignatureHost: __classPrivateFieldGet(this, _Block_chain, "f").mockSignatureHost,
255
255
  allowUnresolvedImports: __classPrivateFieldGet(this, _Block_chain, "f").allowUnresolvedImports,
256
256
  runtimeLogLevel: __classPrivateFieldGet(this, _Block_chain, "f").runtimeLogLevel,
257
- }, (0, executor_1.taskHandler)(this));
257
+ }, (0, wasm_executor_1.taskHandler)(this));
258
258
  if (response.Call) {
259
259
  for (const log of response.Call.runtimeLogs) {
260
260
  logger_1.defaultLogger.info(`RuntimeLogs:\n${log}`);
@@ -92,7 +92,7 @@ export declare class Blockchain {
92
92
  /**
93
93
  * Get block by number.
94
94
  */
95
- getBlockAt(number?: number): Promise<Block | undefined>;
95
+ getBlockAt(number?: number | null): Promise<Block | undefined>;
96
96
  /**
97
97
  * Get block by hash.
98
98
  */
@@ -163,7 +163,7 @@ export declare class Blockchain {
163
163
  */
164
164
  getInherents(): Promise<HexString[]>;
165
165
  /**
166
- * Close the db.
166
+ * Close the db and release worker.
167
167
  */
168
168
  close(): Promise<void>;
169
169
  }
@@ -32,6 +32,7 @@ const offchain_1 = require("../offchain");
32
32
  const utils_1 = require("../utils");
33
33
  const logger_1 = require("../logger");
34
34
  const block_builder_1 = require("./block-builder");
35
+ const wasm_executor_1 = require("../wasm-executor");
35
36
  const logger = logger_1.defaultLogger.child({ name: 'blockchain' });
36
37
  /**
37
38
  * Local blockchain which provides access to blocks, txpool and methods
@@ -160,7 +161,7 @@ class Blockchain {
160
161
  */
161
162
  getBlockAt(number) {
162
163
  return __awaiter(this, void 0, void 0, function* () {
163
- if (number === undefined) {
164
+ if (number === null || number === undefined) {
164
165
  return this.head;
165
166
  }
166
167
  if (number > __classPrivateFieldGet(this, _Blockchain_head, "f").number) {
@@ -445,11 +446,12 @@ class Blockchain {
445
446
  });
446
447
  }
447
448
  /**
448
- * Close the db.
449
+ * Close the db and release worker.
449
450
  */
450
451
  close() {
451
452
  var _a;
452
453
  return __awaiter(this, void 0, void 0, function* () {
454
+ yield (0, wasm_executor_1.releaseWorker)();
453
455
  yield ((_a = this.db) === null || _a === void 0 ? void 0 : _a.destroy());
454
456
  });
455
457
  }
@@ -19,7 +19,7 @@ const lodash_1 = __importDefault(require("lodash"));
19
19
  const proof_1 = require("../../../utils/proof");
20
20
  const util_crypto_1 = require("@polkadot/util-crypto");
21
21
  const utils_1 = require("../../../utils");
22
- const executor_1 = require("../../../executor");
22
+ const wasm_executor_1 = require("../../../wasm-executor");
23
23
  const MOCK_VALIDATION_DATA = {
24
24
  validationData: {
25
25
  relayParentNumber: 1000,
@@ -78,7 +78,7 @@ class SetValidationData {
78
78
  const hrmpIngressChannelIndexKey = (0, proof_1.hrmpIngressChannelIndex)(paraId);
79
79
  const hrmpEgressChannelIndexKey = (0, proof_1.hrmpEgressChannelIndex)(paraId);
80
80
  // TODO: refactor this to have a single decodeProof
81
- const decoded = yield (0, executor_1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [...Object.values(proof_1.WELL_KNOWN_KEYS), dmqMqcHeadKey, hrmpIngressChannelIndexKey, hrmpEgressChannelIndexKey], extrinsic.relayChainState.trieNodes);
81
+ const decoded = yield (0, wasm_executor_1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [...Object.values(proof_1.WELL_KNOWN_KEYS), dmqMqcHeadKey, hrmpIngressChannelIndexKey, hrmpEgressChannelIndexKey], extrinsic.relayChainState.trieNodes);
82
82
  for (const key of Object.values(proof_1.WELL_KNOWN_KEYS)) {
83
83
  newEntries.push([key, decoded[key]]);
84
84
  }
@@ -113,7 +113,7 @@ class SetValidationData {
113
113
  receiver: paraId.toNumber(),
114
114
  });
115
115
  const hrmpChannelKey = (0, proof_1.hrmpChannels)(channelId);
116
- const decoded = yield (0, executor_1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [hrmpChannelKey], extrinsic.relayChainState.trieNodes);
116
+ const decoded = yield (0, wasm_executor_1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [hrmpChannelKey], extrinsic.relayChainState.trieNodes);
117
117
  const abridgedHrmpRaw = decoded[hrmpChannelKey];
118
118
  if (!abridgedHrmpRaw)
119
119
  throw new Error('Canoot find hrmp channels from validation data');
@@ -144,7 +144,7 @@ class SetValidationData {
144
144
  receiver,
145
145
  });
146
146
  const hrmpChannelKey = (0, proof_1.hrmpChannels)(channelId);
147
- const decoded = yield (0, executor_1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [hrmpChannelKey], extrinsic.relayChainState.trieNodes);
147
+ const decoded = yield (0, wasm_executor_1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [hrmpChannelKey], extrinsic.relayChainState.trieNodes);
148
148
  newEntries.push([hrmpChannelKey, decoded[hrmpChannelKey]]);
149
149
  }
150
150
  const upgradeKey = (0, proof_1.upgradeGoAheadSignal)(paraId);
@@ -158,7 +158,7 @@ class SetValidationData {
158
158
  // make sure previous goAhead is removed
159
159
  newEntries.push([upgradeKey, null]);
160
160
  }
161
- const { trieRootHash, nodes } = yield (0, executor_1.createProof)(extrinsic.relayChainState.trieNodes, newEntries);
161
+ const { trieRootHash, nodes } = yield (0, wasm_executor_1.createProof)(extrinsic.relayChainState.trieNodes, newEntries);
162
162
  newData = Object.assign(Object.assign({}, extrinsic), { downwardMessages,
163
163
  horizontalMessages, validationData: Object.assign(Object.assign({}, extrinsic.validationData), { relayParentStorageRoot: trieRootHash, relayParentNumber: extrinsic.validationData.relayParentNumber + 2 }), relayChainState: {
164
164
  trieNodes: nodes,
@@ -1,4 +1,27 @@
1
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
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -28,7 +51,7 @@ exports.StorageLayer = exports.RemoteStorageLayer = exports.StorageValueKind = v
28
51
  const lodash_1 = __importDefault(require("lodash"));
29
52
  const entities_1 = require("../db/entities");
30
53
  const logger_1 = require("../logger");
31
- const key_cache_1 = __importDefault(require("../utils/key-cache"));
54
+ const key_cache_1 = __importStar(require("../utils/key-cache"));
32
55
  const logger = logger_1.defaultLogger.child({ name: 'layer' });
33
56
  const BATCH_SIZE = 1000;
34
57
  var StorageValueKind;
@@ -76,7 +99,7 @@ class RemoteStorageLayer {
76
99
  throw new Error(`pageSize must be less or equal to ${BATCH_SIZE}`);
77
100
  logger.trace({ at: __classPrivateFieldGet(this, _RemoteStorageLayer_at, "f"), prefix, pageSize, startKey }, 'RemoteStorageLayer getKeysPaged');
78
101
  // can't handle keyCache without prefix
79
- if (prefix.length < 66) {
102
+ if (prefix.length < key_cache_1.PREFIX_LENGTH || startKey.length < key_cache_1.PREFIX_LENGTH) {
80
103
  return __classPrivateFieldGet(this, _RemoteStorageLayer_api, "f").getKeysPaged(prefix, pageSize, startKey, __classPrivateFieldGet(this, _RemoteStorageLayer_at, "f"));
81
104
  }
82
105
  let batchComplete = false;
@@ -209,8 +209,24 @@ _TxPool_chain = new WeakMap(), _TxPool_pool = new WeakMap(), _TxPool_ump = new W
209
209
  logger.trace({ params }, 'build block');
210
210
  const head = __classPrivateFieldGet(this, _TxPool_chain, "f").head;
211
211
  const inherents = yield __classPrivateFieldGet(this, _TxPool_inherentProvider, "f").createInherents(head, params);
212
- const [newBlock, pendingExtrinsics] = yield (0, block_builder_1.buildBlock)(head, inherents, params.transactions, params.upwardMessages, (extrinsic, error) => {
213
- this.event.emit(exports.APPLY_EXTRINSIC_ERROR, [extrinsic, error]);
212
+ const [newBlock, pendingExtrinsics] = yield (0, block_builder_1.buildBlock)(head, inherents, params.transactions, params.upwardMessages, {
213
+ onApplyExtrinsicError: (extrinsic, error) => {
214
+ this.event.emit(exports.APPLY_EXTRINSIC_ERROR, [extrinsic, error]);
215
+ },
216
+ onPhaseApplied: logger.level.toLowerCase() === 'trace'
217
+ ? (phase, resp) => {
218
+ switch (phase) {
219
+ case 'initialize':
220
+ logger.trace((0, logger_1.truncate)(resp.storageDiff), 'Initialize block');
221
+ break;
222
+ case 'finalize':
223
+ logger.trace((0, logger_1.truncate)(resp.storageDiff), 'Finalize block');
224
+ break;
225
+ default:
226
+ logger.trace((0, logger_1.truncate)(resp.storageDiff), `Apply extrinsic ${phase}`);
227
+ }
228
+ }
229
+ : undefined,
214
230
  }, params.unsafeBlockHeight);
215
231
  for (const extrinsic of pendingExtrinsics) {
216
232
  __classPrivateFieldGet(this, _TxPool_pool, "f").push({ extrinsic, signer: yield __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_getSigner).call(this, extrinsic) });
File without changes
@@ -0,0 +1,249 @@
1
+ "use strict";
2
+ // import { EventEmitter } from 'eventemitter3'
3
+ // import {
4
+ // ProviderInterface,
5
+ // ProviderInterfaceCallback,
6
+ // ProviderInterfaceEmitCb,
7
+ // ProviderInterfaceEmitted,
8
+ // ProviderStats,
9
+ // } from '@polkadot/rpc-provider/types'
10
+ // import { StorageValues } from './utils'
11
+ // import { defaultLogger } from './logger'
12
+ // const logger = defaultLogger.child({ name: '[Chopsticks provider]' })
13
+ // interface SubscriptionHandler {
14
+ // callback: ProviderInterfaceCallback
15
+ // type: string
16
+ // }
17
+ // interface Subscription extends SubscriptionHandler {
18
+ // method: string
19
+ // params: unknown[]
20
+ // onCancel?: () => void
21
+ // result?: unknown
22
+ // }
23
+ // interface Handler {
24
+ // callback: ProviderInterfaceCallback
25
+ // method: string
26
+ // params: unknown[]
27
+ // start: number
28
+ // subscription?: SubscriptionHandler | undefined
29
+ // }
30
+ // export interface ChopsticksProviderProps {
31
+ // /** upstream endpoint */
32
+ // endpoint: string
33
+ // /** default to latest block */
34
+ // blockHash?: string
35
+ // dbPath?: string
36
+ // storageValues?: StorageValues
37
+ // }
38
+ // /**
39
+ // * A provider for ApiPromise.
40
+ // *
41
+ // * Currectly only support browser environment.
42
+ // */
43
+ // export class ChopsticksProvider implements ProviderInterface {
44
+ // #isConnected = false
45
+ // #eventemitter: EventEmitter
46
+ // #isReadyPromise: Promise<void>
47
+ // #endpoint: string
48
+ // readonly stats?: ProviderStats
49
+ // #subscriptions: Record<string, Subscription> = {}
50
+ // #worker: Worker
51
+ // #blockHash: string | undefined
52
+ // #dbPath: string | undefined
53
+ // #storageValues: StorageValues | undefined
54
+ // #handlers: Record<string, Handler> = {}
55
+ // #idCounter = 0
56
+ // constructor({ endpoint, blockHash, dbPath, storageValues }: ChopsticksProviderProps) {
57
+ // if (!endpoint) {
58
+ // throw new Error('ChopsticksProvider requires the upstream endpoint')
59
+ // }
60
+ // this.#endpoint = endpoint
61
+ // this.#blockHash = blockHash
62
+ // this.#dbPath = dbPath
63
+ // this.#storageValues = storageValues
64
+ // this.#eventemitter = new EventEmitter()
65
+ // this.#isReadyPromise = new Promise((resolve, reject): void => {
66
+ // this.#eventemitter.once('connected', (): void => {
67
+ // logger.debug('isReadyPromise: connected.')
68
+ // resolve()
69
+ // })
70
+ // this.#eventemitter.once('error', reject)
71
+ // })
72
+ // const chopsticksWorker = new Worker(new URL('./chopsticks-worker', import.meta.url), { type: 'module' })
73
+ // this.#worker = chopsticksWorker
74
+ // this.connect()
75
+ // }
76
+ // get hasSubscriptions(): boolean {
77
+ // return true
78
+ // }
79
+ // get isClonable(): boolean {
80
+ // return true
81
+ // }
82
+ // get isConnected(): boolean {
83
+ // return this.#isConnected
84
+ // }
85
+ // get isReady(): Promise<void> {
86
+ // return this.#isReadyPromise
87
+ // }
88
+ // clone = (): ProviderInterface => {
89
+ // return new ChopsticksProvider({ endpoint: this.#endpoint })
90
+ // }
91
+ // connect = async (): Promise<void> => {
92
+ // if (this.#isConnected) {
93
+ // return
94
+ // }
95
+ // this.#worker!.onmessage = this.#onWorkerMessage
96
+ // this.#worker?.postMessage({
97
+ // type: 'connect',
98
+ // endpoint: this.#endpoint,
99
+ // blockHash: this.#blockHash,
100
+ // dbPath: this.#dbPath,
101
+ // storageValues: this.#storageValues,
102
+ // })
103
+ // }
104
+ // disconnect = async (): Promise<void> => {
105
+ // this.#worker?.postMessage({ type: 'disconnect' })
106
+ // this.#isConnected = false
107
+ // this.#eventemitter.emit('disconnected')
108
+ // }
109
+ // on = (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): (() => void) => {
110
+ // this.#eventemitter.on(type, sub)
111
+ // return (): void => {
112
+ // this.#eventemitter.removeListener(type, sub)
113
+ // }
114
+ // }
115
+ // send = async <T>(
116
+ // method: string,
117
+ // params: unknown[],
118
+ // _isCacheable?: boolean,
119
+ // subscription?: SubscriptionHandler,
120
+ // ): Promise<T> => {
121
+ // return new Promise<T>((resolve, reject): void => {
122
+ // try {
123
+ // if (!this.isConnected || this.#worker === undefined) {
124
+ // throw new Error('Api is not connected')
125
+ // }
126
+ // logger.debug('send', { method, params })
127
+ // const id = `${method}::${this.#idCounter++}`
128
+ // const callback = (error?: Error | null, result?: T): void => {
129
+ // if (subscription) {
130
+ // // if it's a subscription, we usually returns the subid
131
+ // const subid = result as string
132
+ // if (subid) {
133
+ // if (!this.#subscriptions[subid]) {
134
+ // this.#subscriptions[subid] = {
135
+ // callback: subscription.callback,
136
+ // method,
137
+ // params,
138
+ // type: subscription.type,
139
+ // }
140
+ // }
141
+ // }
142
+ // }
143
+ // error ? reject(error) : resolve(result as T)
144
+ // }
145
+ // this.#handlers[id] = {
146
+ // callback,
147
+ // method,
148
+ // params,
149
+ // start: Date.now(),
150
+ // subscription,
151
+ // }
152
+ // this.#worker?.postMessage({
153
+ // type: 'send',
154
+ // id,
155
+ // method,
156
+ // params,
157
+ // })
158
+ // } catch (error) {
159
+ // reject(error)
160
+ // }
161
+ // })
162
+ // }
163
+ // subscribe(
164
+ // type: string,
165
+ // method: string,
166
+ // params: unknown[],
167
+ // callback: ProviderInterfaceCallback,
168
+ // ): Promise<number | string> {
169
+ // return this.send<string | number>(method, params, false, { callback, type })
170
+ // }
171
+ // async unsubscribe(_type: string, method: string, id: number | string): Promise<boolean> {
172
+ // if (!this.#subscriptions[id]) {
173
+ // logger.error(`Unable to find active subscription=${id}`)
174
+ // return false
175
+ // }
176
+ // try {
177
+ // return this.isConnected ? this.send<boolean>(method, [id]) : true
178
+ // } catch {
179
+ // return false
180
+ // }
181
+ // }
182
+ // #onWorkerMessage = (e: any) => {
183
+ // switch (e.data.type) {
184
+ // case 'connection':
185
+ // logger.debug('connection.', e.data)
186
+ // if (e.data.connected) {
187
+ // this.#isConnected = true
188
+ // this.#eventemitter.emit('connected')
189
+ // } else {
190
+ // this.#isConnected = false
191
+ // this.#eventemitter.emit('error', new Error('Unable to connect to the chain'))
192
+ // logger.error(`Unable to connect to the chain: ${e.data.message}`)
193
+ // }
194
+ // break
195
+ // case 'subscribe-callback':
196
+ // {
197
+ // logger.debug('subscribe-callback', e.data)
198
+ // const sub = this.#subscriptions[e.data.subid]
199
+ // if (!sub) {
200
+ // // record it first, sometimes callback comes first
201
+ // this.#subscriptions[e.data.subid] = {
202
+ // callback: () => {},
203
+ // method: e.data.method,
204
+ // params: e.data.params,
205
+ // type: e.data.type,
206
+ // result: JSON.parse(e.data.result),
207
+ // }
208
+ // return
209
+ // }
210
+ // sub.callback(null, JSON.parse(e.data.result))
211
+ // }
212
+ // break
213
+ // case 'unsubscribe-callback':
214
+ // {
215
+ // logger.debug('unsubscribe-callback', e.data)
216
+ // const sub = this.#subscriptions[e.data.subid]
217
+ // if (!sub) {
218
+ // logger.error(`Unable to find active subscription=${e.data.subid}`)
219
+ // return
220
+ // }
221
+ // sub?.onCancel?.()
222
+ // delete this.#subscriptions[e.data.subid]
223
+ // }
224
+ // break
225
+ // case 'send-result':
226
+ // {
227
+ // const handler = this.#handlers[e.data.id]
228
+ // if (!handler) {
229
+ // logger.error(`Unable to find handler=${e.data.id}`)
230
+ // return
231
+ // }
232
+ // logger.debug('send-result', {
233
+ // method: e.data.method,
234
+ // result: JSON.parse(e.data.result || '{}'),
235
+ // data: e.data,
236
+ // })
237
+ // try {
238
+ // handler.callback(null, e.data.result ? JSON.parse(e.data.result) : undefined)
239
+ // } catch (error) {
240
+ // handler.callback(error as Error, undefined)
241
+ // }
242
+ // delete this.#handlers[e.data.id]
243
+ // }
244
+ // break
245
+ // default:
246
+ // break
247
+ // }
248
+ // }
249
+ // }
@@ -0,0 +1 @@
1
+ export {};