@acala-network/chopsticks-core 0.8.1 → 0.8.3

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.
package/lib/api.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types';
2
2
  import { HexString } from '@polkadot/util/types';
3
3
  import { ProviderInterface } from '@polkadot/rpc-provider/types';
4
- type ChainProperties = {
4
+ export type ChainProperties = {
5
5
  ss58Format?: number;
6
6
  tokenDecimals?: number[];
7
7
  tokenSymbol?: string[];
@@ -22,6 +22,27 @@ type SignedBlock = {
22
22
  };
23
23
  justifications?: HexString[];
24
24
  };
25
+ /**
26
+ * API class. Calls provider to get on-chain data.
27
+ * Either `endpoint` or `genesis` porvider must be provided.
28
+ *
29
+ * @example Instantiate an API
30
+ *
31
+ * ```ts
32
+ * let provider: ProviderInterface
33
+ * if (options.genesis) {
34
+ * if (typeof options.genesis === 'string') {
35
+ * provider = await GenesisProvider.fromUrl(options.genesis)
36
+ * } else {
37
+ * provider = new GenesisProvider(options.genesis)
38
+ * }
39
+ * } else {
40
+ * provider = new WsProvider(options.endpoint)
41
+ * }
42
+ * const api = new Api(provider)
43
+ * await api.isReady
44
+ * ```
45
+ */
25
46
  export declare class Api {
26
47
  #private;
27
48
  readonly signedExtensions: ExtDef;
package/lib/api.js CHANGED
@@ -23,6 +23,27 @@ var _Api_provider, _Api_ready, _Api_chain, _Api_chainProperties;
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.Api = void 0;
25
25
  const utils_1 = require("./utils");
26
+ /**
27
+ * API class. Calls provider to get on-chain data.
28
+ * Either `endpoint` or `genesis` porvider must be provided.
29
+ *
30
+ * @example Instantiate an API
31
+ *
32
+ * ```ts
33
+ * let provider: ProviderInterface
34
+ * if (options.genesis) {
35
+ * if (typeof options.genesis === 'string') {
36
+ * provider = await GenesisProvider.fromUrl(options.genesis)
37
+ * } else {
38
+ * provider = new GenesisProvider(options.genesis)
39
+ * }
40
+ * } else {
41
+ * provider = new WsProvider(options.endpoint)
42
+ * }
43
+ * const api = new Api(provider)
44
+ * await api.isReady
45
+ * ```
46
+ */
26
47
  class Api {
27
48
  constructor(provider, signedExtensions) {
28
49
  _Api_provider.set(this, void 0);
@@ -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,7 +127,8 @@ 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();
@@ -216,15 +218,15 @@ const buildBlock = (head, inherents, extrinsics, ump, onApplyExtrinsicError, uns
216
218
  // apply extrinsics
217
219
  for (const extrinsic of extrinsics) {
218
220
  try {
219
- const { result, storageDiff } = yield newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic]);
220
- const outcome = registry.createType('ApplyExtrinsicResult', result);
221
+ const resp = yield newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic]);
222
+ const outcome = registry.createType('ApplyExtrinsicResult', resp.result);
221
223
  if (outcome.isErr) {
222
- onApplyExtrinsicError(extrinsic, outcome.asErr);
224
+ (_e = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onApplyExtrinsicError) === null || _e === void 0 ? void 0 : _e.call(callbacks, extrinsic, outcome.asErr);
223
225
  continue;
224
226
  }
225
- newBlock.pushStorageLayer().setAll(storageDiff);
226
- logger.trace((0, logger_1.truncate)(storageDiff), 'Applied extrinsic');
227
+ newBlock.pushStorageLayer().setAll(resp.storageDiff);
227
228
  includedExtrinsic.push(extrinsic);
229
+ (_f = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onPhaseApplied) === null || _f === void 0 ? void 0 : _f.call(callbacks, includedExtrinsic.length - 1, resp);
228
230
  }
229
231
  catch (e) {
230
232
  logger.info('Failed to apply extrinsic %o %s', e, e);
@@ -233,16 +235,18 @@ const buildBlock = (head, inherents, extrinsics, ump, onApplyExtrinsicError, uns
233
235
  }
234
236
  {
235
237
  // 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');
238
+ const resp = yield newBlock.call('BlockBuilder_finalize_block', []);
239
+ newBlock.pushStorageLayer().setAll(resp.storageDiff);
240
+ (_g = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onPhaseApplied) === null || _g === void 0 ? void 0 : _g.call(callbacks, 'finalize', resp);
239
241
  }
240
242
  const blockData = registry.createType('Block', {
241
243
  header,
242
244
  extrinsics: includedExtrinsic,
243
245
  });
244
246
  const storageDiff = yield newBlock.storageDiff();
245
- logger.trace(Object.entries(storageDiff).map(([key, value]) => [key, (0, logger_1.truncate)(value)]), 'Final block');
247
+ if (logger.level.toLowerCase() === 'trace') {
248
+ logger.trace(Object.entries(storageDiff).map(([key, value]) => [key, (0, logger_1.truncate)(value)]), 'Final block');
249
+ }
246
250
  const finalBlock = new block_1.Block(head.chain, newBlock.number, blockData.hash.toHex(), head, {
247
251
  header,
248
252
  extrinsics: [...inherents, ...includedExtrinsic],
@@ -11,35 +11,86 @@ export type TaskCallResponse = {
11
11
  offchainStorageDiff: [HexString, HexString | null][];
12
12
  runtimeLogs: string[];
13
13
  };
14
+ /**
15
+ * Block class.
16
+ *
17
+ * @example Instantiate a block
18
+ *
19
+ * ```ts
20
+ * const block = new Block(chain, number, hash)
21
+ * ```
22
+ *
23
+ * @example Get storage
24
+ *
25
+ * ```ts
26
+ * const block = await chain.getBlock('0x...')
27
+ * block.storage()
28
+ * ```
29
+ */
14
30
  export declare class Block {
15
31
  #private;
16
32
  readonly number: number;
17
33
  readonly hash: HexString;
18
34
  constructor(chain: Blockchain, number: number, hash: HexString, parentBlock?: Block, block?: {
35
+ /** See `@polkadot/types/interfaces` Header */
19
36
  header: Header;
37
+ /** Extrinsics */
20
38
  extrinsics: HexString[];
39
+ /** Storage provider. Default to {@link RemoteStorageLayer} with {@link Blockchain.api chain.api} as remote. */
21
40
  storage?: StorageLayerProvider;
41
+ /** Storage diff to apply. */
22
42
  storageDiff?: Record<string, StorageValue | null>;
23
43
  });
24
44
  get chain(): Blockchain;
25
45
  get header(): Header | Promise<Header>;
26
46
  get extrinsics(): HexString[] | Promise<HexString[]>;
27
47
  get parentBlock(): undefined | Block | Promise<Block | undefined>;
48
+ /**
49
+ * Get the block storage.
50
+ */
28
51
  get storage(): StorageLayerProvider;
52
+ /**
53
+ * Get the block storage by key.
54
+ */
29
55
  get(key: string): Promise<string | undefined>;
56
+ /**
57
+ * Get paged storage keys.
58
+ */
30
59
  getKeysPaged(options: {
31
60
  prefix?: string;
32
61
  startKey?: string;
33
62
  pageSize: number;
34
63
  }): Promise<string[]>;
64
+ /**
65
+ * Push a layer to the storage stack.
66
+ */
35
67
  pushStorageLayer(): StorageLayer;
68
+ /**
69
+ * Pop a layer from the storage stack.
70
+ */
36
71
  popStorageLayer(): void;
72
+ /**
73
+ * Get storage diff.
74
+ */
37
75
  storageDiff(): Promise<Record<HexString, HexString | null>>;
76
+ /**
77
+ * Get the wasm string.
78
+ */
38
79
  get wasm(): Promise<`0x${string}`>;
80
+ /**
81
+ * Set the runtime wasm.
82
+ */
39
83
  setWasm(wasm: HexString): void;
84
+ /**
85
+ * Get the type registry.
86
+ * @see https://polkadot.js.org/docs/api/start/types.create#why-create-types
87
+ */
40
88
  get registry(): Promise<TypeRegistry>;
41
89
  get runtimeVersion(): Promise<RuntimeVersion>;
42
90
  get metadata(): Promise<HexString>;
43
91
  get meta(): Promise<DecoratedMeta>;
92
+ /**
93
+ * Call a runtime method.
94
+ */
44
95
  call(method: string, args: HexString[]): Promise<TaskCallResponse>;
45
96
  }
@@ -30,6 +30,22 @@ const storage_layer_1 = require("./storage-layer");
30
30
  const utils_1 = require("../utils");
31
31
  const logger_1 = require("../logger");
32
32
  const executor_1 = require("../executor");
33
+ /**
34
+ * Block class.
35
+ *
36
+ * @example Instantiate a block
37
+ *
38
+ * ```ts
39
+ * const block = new Block(chain, number, hash)
40
+ * ```
41
+ *
42
+ * @example Get storage
43
+ *
44
+ * ```ts
45
+ * const block = await chain.getBlock('0x...')
46
+ * block.storage()
47
+ * ```
48
+ */
33
49
  class Block {
34
50
  constructor(chain, number, hash, parentBlock, block) {
35
51
  var _a;
@@ -93,10 +109,16 @@ class Block {
93
109
  }
94
110
  return __classPrivateFieldGet(this, _Block_parentBlock, "f");
95
111
  }
112
+ /**
113
+ * Get the block storage.
114
+ */
96
115
  get storage() {
97
116
  var _a;
98
117
  return (_a = __classPrivateFieldGet(this, _Block_storages, "f")[__classPrivateFieldGet(this, _Block_storages, "f").length - 1]) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _Block_baseStorage, "f");
99
118
  }
119
+ /**
120
+ * Get the block storage by key.
121
+ */
100
122
  get(key) {
101
123
  return __awaiter(this, void 0, void 0, function* () {
102
124
  const val = yield this.storage.get(key, true);
@@ -108,6 +130,9 @@ class Block {
108
130
  }
109
131
  });
110
132
  }
133
+ /**
134
+ * Get paged storage keys.
135
+ */
111
136
  getKeysPaged(options) {
112
137
  var _a, _b;
113
138
  return __awaiter(this, void 0, void 0, function* () {
@@ -119,14 +144,23 @@ class Block {
119
144
  return layer.getKeysPaged(prefix, pageSize, startKey);
120
145
  });
121
146
  }
147
+ /**
148
+ * Push a layer to the storage stack.
149
+ */
122
150
  pushStorageLayer() {
123
151
  const layer = new storage_layer_1.StorageLayer(this.storage);
124
152
  __classPrivateFieldGet(this, _Block_storages, "f").push(layer);
125
153
  return layer;
126
154
  }
155
+ /**
156
+ * Pop a layer from the storage stack.
157
+ */
127
158
  popStorageLayer() {
128
159
  __classPrivateFieldGet(this, _Block_storages, "f").pop();
129
160
  }
161
+ /**
162
+ * Get storage diff.
163
+ */
130
164
  storageDiff() {
131
165
  return __awaiter(this, void 0, void 0, function* () {
132
166
  const storage = {};
@@ -136,6 +170,9 @@ class Block {
136
170
  return storage;
137
171
  });
138
172
  }
173
+ /**
174
+ * Get the wasm string.
175
+ */
139
176
  get wasm() {
140
177
  if (!__classPrivateFieldGet(this, _Block_wasm, "f")) {
141
178
  __classPrivateFieldSet(this, _Block_wasm, (() => __awaiter(this, void 0, void 0, function* () {
@@ -149,6 +186,9 @@ class Block {
149
186
  }
150
187
  return __classPrivateFieldGet(this, _Block_wasm, "f");
151
188
  }
189
+ /**
190
+ * Set the runtime wasm.
191
+ */
152
192
  setWasm(wasm) {
153
193
  const wasmKey = (0, util_2.stringToHex)(':code');
154
194
  this.pushStorageLayer().set(wasmKey, wasm);
@@ -158,6 +198,10 @@ class Block {
158
198
  __classPrivateFieldSet(this, _Block_meta, undefined, "f");
159
199
  __classPrivateFieldSet(this, _Block_metadata, undefined, "f");
160
200
  }
201
+ /**
202
+ * Get the type registry.
203
+ * @see https://polkadot.js.org/docs/api/start/types.create#why-create-types
204
+ */
161
205
  get registry() {
162
206
  if (!__classPrivateFieldGet(this, _Block_registry, "f")) {
163
207
  __classPrivateFieldSet(this, _Block_registry, Promise.all([
@@ -198,6 +242,9 @@ class Block {
198
242
  }
199
243
  return __classPrivateFieldGet(this, _Block_meta, "f");
200
244
  }
245
+ /**
246
+ * Call a runtime method.
247
+ */
201
248
  call(method, args) {
202
249
  return __awaiter(this, void 0, void 0, function* () {
203
250
  const wasm = yield this.wasm;
@@ -10,31 +10,74 @@ import { HeadState } from './head-state';
10
10
  import { InherentProvider } from './inherent';
11
11
  import { OffchainWorker } from '../offchain';
12
12
  export interface Options {
13
+ /** API instance, for getting on-chain data. */
13
14
  api: Api;
15
+ /** Build block mode. Default to Batch. */
14
16
  buildBlockMode?: BuildBlockMode;
17
+ /** Inherent provider, for creating inherents. */
15
18
  inherentProvider: InherentProvider;
19
+ /** Datasource for caching storage and blocks data. */
16
20
  db?: DataSource;
21
+ /** Used to create the initial head. */
17
22
  header: {
18
23
  number: number;
19
24
  hash: HexString;
20
25
  };
26
+ /** Whether to enable mock signature. Any signature starts with 0xdeadbeef and filled by 0xcd is considered valid */
21
27
  mockSignatureHost?: boolean;
28
+ /** Whether to allow wasm unresolved imports. */
22
29
  allowUnresolvedImports?: boolean;
30
+ /** Wasm runtime log level. */
23
31
  runtimeLogLevel?: number;
32
+ /** Polkadot.js custom types registration. */
24
33
  registeredTypes: RegisteredTypes;
34
+ /** Whether to enable offchain Worker. */
25
35
  offchainWorker?: boolean;
36
+ /** Max memory block count */
26
37
  maxMemoryBlockCount?: number;
27
38
  }
39
+ /**
40
+ * Local blockchain which provides access to blocks, txpool and methods
41
+ * to manipulate the chain such as build blocks, submit extrinsics, xcm and more!
42
+ *
43
+ * @example
44
+ *
45
+ * ```ts
46
+ * const chain = new Blockchain({
47
+ * api,
48
+ * buildBlockMode: BuildBlockMode.Manual,
49
+ * inherentProvider: inherents,
50
+ * header: {
51
+ * hash: blockHash,
52
+ * number: Number(header.number),
53
+ * },
54
+ * mockSignatureHost: true,
55
+ * allowUnresolvedImports: true,
56
+ * registeredTypes: {},
57
+ * })
58
+ * // build a block
59
+ * chain.newBlock()
60
+ * ```
61
+ */
28
62
  export declare class Blockchain {
29
63
  #private;
30
64
  readonly uid: string;
65
+ /** API instance, for getting on-chain data. */
31
66
  readonly api: Api;
67
+ /** Datasource for caching storage and blocks data. */
32
68
  readonly db: DataSource | undefined;
69
+ /** Enable mock signature. Any signature starts with 0xdeadbeef and filled by 0xcd is considered valid */
33
70
  readonly mockSignatureHost: boolean;
71
+ /** Allow wasm unresolved imports. */
34
72
  readonly allowUnresolvedImports: boolean;
73
+ /** Polkadot.js custom types registration. */
35
74
  readonly registeredTypes: RegisteredTypes;
75
+ /** For subscribing and managing the head state. */
36
76
  readonly headState: HeadState;
37
77
  readonly offchainWorker: OffchainWorker | undefined;
78
+ /**
79
+ * @param options - Options for instantiating the blockchain
80
+ */
38
81
  constructor({ api, buildBlockMode, inherentProvider, db, header, mockSignatureHost, allowUnresolvedImports, runtimeLogLevel, registeredTypes, offchainWorker, maxMemoryBlockCount, }: Options);
39
82
  get head(): Block;
40
83
  get txPool(): TxPool;
@@ -42,24 +85,57 @@ export declare class Blockchain {
42
85
  set runtimeLogLevel(level: number);
43
86
  saveBlockToDB(block: Block): Promise<void>;
44
87
  /**
45
- * Try to load block from db and register it
46
- * If pass in number, get block by number, else get block by hash
88
+ * Try to load block from db and register it.
89
+ * If pass in number, get block by number, else get block by hash.
47
90
  */
48
91
  loadBlockFromDB(key: number | HexString): Promise<Block | undefined>;
92
+ /**
93
+ * Get block by number.
94
+ */
49
95
  getBlockAt(number?: number): Promise<Block | undefined>;
96
+ /**
97
+ * Get block by hash.
98
+ */
50
99
  getBlock(hash?: HexString): Promise<Block | undefined>;
100
+ /**
101
+ * Get all blocks in memory.
102
+ */
51
103
  blocksInMemory(): Block[];
104
+ /**
105
+ * Remove block from memory and db.
106
+ */
52
107
  unregisterBlock(block: Block): Promise<void>;
53
108
  onNewBlock(block: Block): Promise<void>;
109
+ /**
110
+ * Set block as head.
111
+ */
54
112
  setHead(block: Block): Promise<void>;
113
+ /**
114
+ * Submit extrinsic to txpool.
115
+ */
55
116
  submitExtrinsic(extrinsic: HexString): Promise<HexString>;
117
+ /**
118
+ * Validate extrinsic by calling `TaggedTransactionQueue_validate_transaction`.
119
+ */
56
120
  validateExtrinsic(extrinsic: HexString, source?: '0x00' | '0x01' | '0x02' /** External */): Promise<TransactionValidity>;
57
121
  submitUpwardMessages(id: number, ump: HexString[]): void;
58
122
  submitDownwardMessages(dmp: DownwardMessage[]): void;
59
123
  submitHorizontalMessages(id: number, hrmp: HorizontalMessage[]): void;
124
+ /**
125
+ * Build a new block with optional params. Use this when you don't have all the {@link BuildBlockParams}
126
+ */
60
127
  newBlock(params?: Partial<BuildBlockParams>): Promise<Block>;
128
+ /**
129
+ * Build a new block with {@link BuildBlockParams}.
130
+ */
61
131
  newBlockWithParams(params: BuildBlockParams): Promise<Block>;
132
+ /**
133
+ * Get the upcoming blocks.
134
+ */
62
135
  upcomingBlocks(): Promise<number>;
136
+ /**
137
+ * Dry run extrinsic in block `at`.
138
+ */
63
139
  dryRunExtrinsic(extrinsic: HexString | {
64
140
  call: HexString;
65
141
  address: string;
@@ -67,9 +143,27 @@ export declare class Blockchain {
67
143
  outcome: ApplyExtrinsicResult;
68
144
  storageDiff: [HexString, HexString | null][];
69
145
  }>;
146
+ /**
147
+ * Dry run hrmp messages in block `at`.
148
+ * Return the storage diff.
149
+ */
70
150
  dryRunHrmp(hrmp: Record<number, HorizontalMessage[]>, at?: HexString): Promise<[HexString, HexString | null][]>;
151
+ /**
152
+ * Dry run dmp messages in block `at`.
153
+ * Return the storage diff.
154
+ */
71
155
  dryRunDmp(dmp: DownwardMessage[], at?: HexString): Promise<[HexString, HexString | null][]>;
156
+ /**
157
+ * Dry run ump messages in block `at`.
158
+ * Return the storage diff.
159
+ */
72
160
  dryRunUmp(ump: Record<number, HexString[]>, at?: HexString): Promise<[HexString, HexString | null][]>;
161
+ /**
162
+ * Get inherents of head.
163
+ */
73
164
  getInherents(): Promise<HexString[]>;
165
+ /**
166
+ * Close the db.
167
+ */
74
168
  close(): Promise<void>;
75
169
  }
@@ -33,7 +33,33 @@ const utils_1 = require("../utils");
33
33
  const logger_1 = require("../logger");
34
34
  const block_builder_1 = require("./block-builder");
35
35
  const logger = logger_1.defaultLogger.child({ name: 'blockchain' });
36
+ /**
37
+ * Local blockchain which provides access to blocks, txpool and methods
38
+ * to manipulate the chain such as build blocks, submit extrinsics, xcm and more!
39
+ *
40
+ * @example
41
+ *
42
+ * ```ts
43
+ * const chain = new Blockchain({
44
+ * api,
45
+ * buildBlockMode: BuildBlockMode.Manual,
46
+ * inherentProvider: inherents,
47
+ * header: {
48
+ * hash: blockHash,
49
+ * number: Number(header.number),
50
+ * },
51
+ * mockSignatureHost: true,
52
+ * allowUnresolvedImports: true,
53
+ * registeredTypes: {},
54
+ * })
55
+ * // build a block
56
+ * chain.newBlock()
57
+ * ```
58
+ */
36
59
  class Blockchain {
60
+ /**
61
+ * @param options - Options for instantiating the blockchain
62
+ */
37
63
  constructor({ api, buildBlockMode, inherentProvider, db, header, mockSignatureHost = false, allowUnresolvedImports = false, runtimeLogLevel = 0, registeredTypes = {}, offchainWorker = false, maxMemoryBlockCount = 2000, }) {
38
64
  _Blockchain_instances.add(this);
39
65
  this.uid = Math.random().toString(36).substring(2);
@@ -43,7 +69,9 @@ class Blockchain {
43
69
  _Blockchain_head.set(this, void 0);
44
70
  _Blockchain_blocksByNumber.set(this, new Map());
45
71
  _Blockchain_blocksByHash.set(this, {});
46
- _Blockchain_loadingBlocks.set(this, {});
72
+ _Blockchain_loadingBlocks.set(this, {}
73
+ /** For subscribing and managing the head state. */
74
+ );
47
75
  _Blockchain_maxMemoryBlockCount.set(this, void 0);
48
76
  this.api = api;
49
77
  this.db = db;
@@ -95,8 +123,8 @@ class Blockchain {
95
123
  });
96
124
  }
97
125
  /**
98
- * Try to load block from db and register it
99
- * If pass in number, get block by number, else get block by hash
126
+ * Try to load block from db and register it.
127
+ * If pass in number, get block by number, else get block by hash.
100
128
  */
101
129
  loadBlockFromDB(key) {
102
130
  var _a;
@@ -127,6 +155,9 @@ class Blockchain {
127
155
  return undefined;
128
156
  });
129
157
  }
158
+ /**
159
+ * Get block by number.
160
+ */
130
161
  getBlockAt(number) {
131
162
  return __awaiter(this, void 0, void 0, function* () {
132
163
  if (number === undefined) {
@@ -150,6 +181,9 @@ class Blockchain {
150
181
  return __classPrivateFieldGet(this, _Blockchain_blocksByNumber, "f").get(number);
151
182
  });
152
183
  }
184
+ /**
185
+ * Get block by hash.
186
+ */
153
187
  getBlock(hash) {
154
188
  return __awaiter(this, void 0, void 0, function* () {
155
189
  yield this.api.isReady;
@@ -186,9 +220,15 @@ class Blockchain {
186
220
  return __classPrivateFieldGet(this, _Blockchain_blocksByHash, "f")[hash];
187
221
  });
188
222
  }
223
+ /**
224
+ * Get all blocks in memory.
225
+ */
189
226
  blocksInMemory() {
190
227
  return Array.from(__classPrivateFieldGet(this, _Blockchain_blocksByNumber, "f").values());
191
228
  }
229
+ /**
230
+ * Remove block from memory and db.
231
+ */
192
232
  unregisterBlock(block) {
193
233
  var _a;
194
234
  return __awaiter(this, void 0, void 0, function* () {
@@ -211,6 +251,9 @@ class Blockchain {
211
251
  yield this.saveBlockToDB(block);
212
252
  });
213
253
  }
254
+ /**
255
+ * Set block as head.
256
+ */
214
257
  setHead(block) {
215
258
  return __awaiter(this, void 0, void 0, function* () {
216
259
  logger.debug({
@@ -225,6 +268,9 @@ class Blockchain {
225
268
  }
226
269
  });
227
270
  }
271
+ /**
272
+ * Submit extrinsic to txpool.
273
+ */
228
274
  submitExtrinsic(extrinsic) {
229
275
  return __awaiter(this, void 0, void 0, function* () {
230
276
  const validity = yield this.validateExtrinsic(extrinsic);
@@ -235,6 +281,9 @@ class Blockchain {
235
281
  throw validity.asErr;
236
282
  });
237
283
  }
284
+ /**
285
+ * Validate extrinsic by calling `TaggedTransactionQueue_validate_transaction`.
286
+ */
238
287
  validateExtrinsic(extrinsic, source = '0x02' /** External */) {
239
288
  return __awaiter(this, void 0, void 0, function* () {
240
289
  const args = (0, util_1.u8aToHex)((0, util_1.u8aConcat)(source, extrinsic, this.head.hash));
@@ -255,23 +304,35 @@ class Blockchain {
255
304
  __classPrivateFieldGet(this, _Blockchain_txpool, "f").submitHorizontalMessages(id, hrmp);
256
305
  logger.debug({ id, hrmp }, 'submitHorizontalMessages');
257
306
  }
307
+ /**
308
+ * Build a new block with optional params. Use this when you don't have all the {@link BuildBlockParams}
309
+ */
258
310
  newBlock(params) {
259
311
  return __awaiter(this, void 0, void 0, function* () {
260
312
  yield __classPrivateFieldGet(this, _Blockchain_txpool, "f").buildBlock(params);
261
313
  return __classPrivateFieldGet(this, _Blockchain_head, "f");
262
314
  });
263
315
  }
316
+ /**
317
+ * Build a new block with {@link BuildBlockParams}.
318
+ */
264
319
  newBlockWithParams(params) {
265
320
  return __awaiter(this, void 0, void 0, function* () {
266
321
  yield __classPrivateFieldGet(this, _Blockchain_txpool, "f").buildBlockWithParams(params);
267
322
  return __classPrivateFieldGet(this, _Blockchain_head, "f");
268
323
  });
269
324
  }
325
+ /**
326
+ * Get the upcoming blocks.
327
+ */
270
328
  upcomingBlocks() {
271
329
  return __awaiter(this, void 0, void 0, function* () {
272
330
  return __classPrivateFieldGet(this, _Blockchain_txpool, "f").upcomingBlocks();
273
331
  });
274
332
  }
333
+ /**
334
+ * Dry run extrinsic in block `at`.
335
+ */
275
336
  dryRunExtrinsic(extrinsic, at) {
276
337
  return __awaiter(this, void 0, void 0, function* () {
277
338
  yield this.api.isReady;
@@ -291,6 +352,10 @@ class Blockchain {
291
352
  return { outcome, storageDiff };
292
353
  });
293
354
  }
355
+ /**
356
+ * Dry run hrmp messages in block `at`.
357
+ * Return the storage diff.
358
+ */
294
359
  dryRunHrmp(hrmp, at) {
295
360
  return __awaiter(this, void 0, void 0, function* () {
296
361
  yield this.api.isReady;
@@ -307,6 +372,10 @@ class Blockchain {
307
372
  return (0, block_builder_1.dryRunInherents)(head, inherents);
308
373
  });
309
374
  }
375
+ /**
376
+ * Dry run dmp messages in block `at`.
377
+ * Return the storage diff.
378
+ */
310
379
  dryRunDmp(dmp, at) {
311
380
  return __awaiter(this, void 0, void 0, function* () {
312
381
  yield this.api.isReady;
@@ -323,6 +392,10 @@ class Blockchain {
323
392
  return (0, block_builder_1.dryRunInherents)(head, inherents);
324
393
  });
325
394
  }
395
+ /**
396
+ * Dry run ump messages in block `at`.
397
+ * Return the storage diff.
398
+ */
326
399
  dryRunUmp(ump, at) {
327
400
  return __awaiter(this, void 0, void 0, function* () {
328
401
  yield this.api.isReady;
@@ -356,6 +429,9 @@ class Blockchain {
356
429
  return (0, block_builder_1.dryRunInherents)(head, inherents);
357
430
  });
358
431
  }
432
+ /**
433
+ * Get inherents of head.
434
+ */
359
435
  getInherents() {
360
436
  return __awaiter(this, void 0, void 0, function* () {
361
437
  yield this.api.isReady;
@@ -368,6 +444,9 @@ class Blockchain {
368
444
  return inherents;
369
445
  });
370
446
  }
447
+ /**
448
+ * Close the db.
449
+ */
371
450
  close() {
372
451
  var _a;
373
452
  return __awaiter(this, void 0, void 0, function* () {
@@ -6,9 +6,21 @@ export declare const enum StorageValueKind {
6
6
  }
7
7
  export type StorageValue = string | StorageValueKind | undefined;
8
8
  export interface StorageLayerProvider {
9
+ /**
10
+ * Get the value of a storage key.
11
+ */
9
12
  get(key: string, cache: boolean): Promise<StorageValue>;
13
+ /**
14
+ * Fold the storage layer into another layer.
15
+ */
10
16
  foldInto(into: StorageLayer): Promise<StorageLayerProvider | undefined>;
17
+ /**
18
+ * Fold the storage layer into the parent if it exists.
19
+ */
11
20
  fold(): Promise<void>;
21
+ /**
22
+ * Get paged storage keys.
23
+ */
12
24
  getKeysPaged(prefix: string, pageSize: number, startKey: string): Promise<string[]>;
13
25
  }
14
26
  export declare class RemoteStorageLayer implements StorageLayerProvider {
@@ -28,5 +40,8 @@ export declare class StorageLayer implements StorageLayerProvider {
28
40
  foldInto(into: StorageLayer): Promise<StorageLayerProvider | undefined>;
29
41
  fold(): Promise<void>;
30
42
  getKeysPaged(prefix: string, pageSize: number, startKey: string): Promise<string[]>;
43
+ /**
44
+ * Merge the storage layer into the given object, can be used to get sotrage diff.
45
+ */
31
46
  mergeInto(into: Record<string, string | null>): Promise<void>;
32
47
  }
@@ -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;
@@ -219,6 +242,9 @@ class StorageLayer {
219
242
  return res;
220
243
  });
221
244
  }
245
+ /**
246
+ * Merge the storage layer into the given object, can be used to get sotrage diff.
247
+ */
222
248
  mergeInto(into) {
223
249
  return __awaiter(this, void 0, void 0, function* () {
224
250
  for (const [key, maybeValue] of Object.entries(__classPrivateFieldGet(this, _StorageLayer_store, "f"))) {
@@ -4,8 +4,11 @@ import { Blockchain } from '.';
4
4
  import { InherentProvider } from './inherent';
5
5
  export declare const APPLY_EXTRINSIC_ERROR = "TxPool::ApplyExtrinsicError";
6
6
  export declare enum BuildBlockMode {
7
+ /** One block per batch (default) */
7
8
  Batch = 0,
9
+ /** One block per tx */
8
10
  Instant = 1,
11
+ /** Only build when triggered */
9
12
  Manual = 2
10
13
  }
11
14
  export interface DownwardMessage {
@@ -34,8 +34,11 @@ const logger = logger_1.defaultLogger.child({ name: 'txpool' });
34
34
  exports.APPLY_EXTRINSIC_ERROR = 'TxPool::ApplyExtrinsicError';
35
35
  var BuildBlockMode;
36
36
  (function (BuildBlockMode) {
37
+ /** One block per batch (default) */
37
38
  BuildBlockMode[BuildBlockMode["Batch"] = 0] = "Batch";
39
+ /** One block per tx */
38
40
  BuildBlockMode[BuildBlockMode["Instant"] = 1] = "Instant";
41
+ /** Only build when triggered */
39
42
  BuildBlockMode[BuildBlockMode["Manual"] = 2] = "Manual";
40
43
  })(BuildBlockMode || (exports.BuildBlockMode = BuildBlockMode = {}));
41
44
  class TxPool {
@@ -206,8 +209,24 @@ _TxPool_chain = new WeakMap(), _TxPool_pool = new WeakMap(), _TxPool_ump = new W
206
209
  logger.trace({ params }, 'build block');
207
210
  const head = __classPrivateFieldGet(this, _TxPool_chain, "f").head;
208
211
  const inherents = yield __classPrivateFieldGet(this, _TxPool_inherentProvider, "f").createInherents(head, params);
209
- const [newBlock, pendingExtrinsics] = yield (0, block_builder_1.buildBlock)(head, inherents, params.transactions, params.upwardMessages, (extrinsic, error) => {
210
- 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,
211
230
  }, params.unsafeBlockHeight);
212
231
  for (const extrinsic of pendingExtrinsics) {
213
232
  __classPrivateFieldGet(this, _TxPool_pool, "f").push({ extrinsic, signer: yield __classPrivateFieldGet(this, _TxPool_instances, "m", _TxPool_getSigner).call(this, extrinsic) });
package/lib/executor.js CHANGED
@@ -18,6 +18,7 @@ const util_crypto_1 = require("@polkadot/util-crypto");
18
18
  const key_cache_1 = require("./utils/key-cache");
19
19
  const chopsticks_executor_1 = require("@acala-network/chopsticks-executor");
20
20
  const logger_1 = require("./logger");
21
+ const utils_1 = require("./utils");
21
22
  const lodash_1 = __importDefault(require("lodash"));
22
23
  const logger = logger_1.defaultLogger.child({ name: 'executor' });
23
24
  const getRuntimeVersion = (code) => __awaiter(void 0, void 0, void 0, function* () {
@@ -78,7 +79,7 @@ const taskHandler = (block) => {
78
79
  pageSize: 1,
79
80
  startKey: key,
80
81
  });
81
- return nextKey;
82
+ return nextKey && (0, utils_1.stripChildPrefix)(nextKey);
82
83
  });
83
84
  },
84
85
  offchainGetStorage: function (key) {
package/lib/index.d.ts CHANGED
@@ -1,9 +1,19 @@
1
+ /**
2
+ * Chopsticks core package. A common package for usage in both server and browser.
3
+ * It contains a local blockchain implementation, a transaction pool, a runtime executor and more!
4
+ *
5
+ * @privateRemarks
6
+ * Above is the package description for `chopsticks-core` package.
7
+ *
8
+ * @packageDocumentation
9
+ */
1
10
  export * from './api';
2
11
  export * from './blockchain';
3
12
  export * from './blockchain/block';
4
13
  export * from './blockchain/block-builder';
5
14
  export * from './blockchain/txpool';
6
15
  export * from './blockchain/storage-layer';
16
+ export * from './blockchain/head-state';
7
17
  export * from './utils';
8
18
  export * from './executor';
9
19
  export * from './schema';
@@ -11,3 +21,4 @@ export * from './xcm';
11
21
  export * from './setup';
12
22
  export * from './blockchain/inherent';
13
23
  export * from './logger';
24
+ export * from './offchain';
package/lib/index.js CHANGED
@@ -14,12 +14,22 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Chopsticks core package. A common package for usage in both server and browser.
19
+ * It contains a local blockchain implementation, a transaction pool, a runtime executor and more!
20
+ *
21
+ * @privateRemarks
22
+ * Above is the package description for `chopsticks-core` package.
23
+ *
24
+ * @packageDocumentation
25
+ */
17
26
  __exportStar(require("./api"), exports);
18
27
  __exportStar(require("./blockchain"), exports);
19
28
  __exportStar(require("./blockchain/block"), exports);
20
29
  __exportStar(require("./blockchain/block-builder"), exports);
21
30
  __exportStar(require("./blockchain/txpool"), exports);
22
31
  __exportStar(require("./blockchain/storage-layer"), exports);
32
+ __exportStar(require("./blockchain/head-state"), exports);
23
33
  __exportStar(require("./utils"), exports);
24
34
  __exportStar(require("./executor"), exports);
25
35
  __exportStar(require("./schema"), exports);
@@ -27,3 +37,4 @@ __exportStar(require("./xcm"), exports);
27
37
  __exportStar(require("./setup"), exports);
28
38
  __exportStar(require("./blockchain/inherent"), exports);
29
39
  __exportStar(require("./logger"), exports);
40
+ __exportStar(require("./offchain"), exports);
package/lib/setup.d.ts CHANGED
@@ -3,7 +3,7 @@ import { RegisteredTypes } from '@polkadot/types/types';
3
3
  import { Blockchain } from './blockchain';
4
4
  import { BuildBlockMode } from './blockchain/txpool';
5
5
  import { Genesis } from './schema';
6
- type Options = {
6
+ export type SetupOptions = {
7
7
  endpoint?: string;
8
8
  block?: string | number | null;
9
9
  genesis?: string | Genesis;
@@ -16,5 +16,4 @@ type Options = {
16
16
  offchainWorker?: boolean;
17
17
  maxMemoryBlockCount?: number;
18
18
  };
19
- export declare const setup: (options: Options) => Promise<Blockchain>;
20
- export {};
19
+ export declare const setup: (options: SetupOptions) => Promise<Blockchain>;
package/package.json CHANGED
@@ -1,18 +1,19 @@
1
1
  {
2
2
  "name": "@acala-network/chopsticks-core",
3
- "version": "0.8.1",
4
- "author": "Bryan Chen <xlchen1291@gmail.com>",
3
+ "version": "0.8.3",
4
+ "author": "Acala Developers <hello@acala.network>",
5
5
  "license": "Apache-2.0",
6
6
  "scripts": {
7
7
  "clean": "rm -rf lib tsconfig.tsbuildinfo",
8
8
  "pack-wasm": "scripts/pack-wasm.js",
9
- "build": "yarn pack-wasm; tsc -p ./tsconfig.json"
9
+ "build": "yarn pack-wasm; tsc -p ./tsconfig.json",
10
+ "docs:prep": "typedoc"
10
11
  },
11
12
  "dependencies": {
12
- "@acala-network/chopsticks-executor": "0.8.1",
13
+ "@acala-network/chopsticks-executor": "0.8.3",
13
14
  "@polkadot/api": "^10.9.1",
14
15
  "@polkadot/util-crypto": "^12.3.2",
15
- "axios": "^1.5.0",
16
+ "axios": "^1.5.1",
16
17
  "eventemitter3": "^5.0.1",
17
18
  "localforage": "^1.10.0",
18
19
  "lodash": "^4.17.21",
@@ -21,10 +22,10 @@
21
22
  "sql.js": "^1.8.0",
22
23
  "sqlite3": "^5.1.6",
23
24
  "typeorm": "^0.3.17",
24
- "zod": "^3.22.2"
25
+ "zod": "^3.22.3"
25
26
  },
26
27
  "devDependencies": {
27
- "@types/lodash": "^4.14.197",
28
+ "@types/lodash": "^4.14.199",
28
29
  "@types/sql.js": "^1.4.4",
29
30
  "fflate": "^0.8.0",
30
31
  "typescript": "^5.1.6"