@acala-network/chopsticks-core 0.8.0 → 0.8.2

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;
@@ -36,7 +57,7 @@ export declare class Api {
36
57
  getBlockHash(blockNumber?: number): Promise<`0x${string}` | null>;
37
58
  getHeader(hash?: string): Promise<Header | null>;
38
59
  getBlock(hash?: string): Promise<SignedBlock | null>;
39
- getStorage(key: string, hash?: string): Promise<string | null>;
60
+ getStorage(key: string, hash?: string): Promise<`0x${string}` | null>;
40
61
  getKeysPaged(prefix: string, pageSize: number, startKey: string, hash?: string): Promise<string[]>;
41
62
  }
42
63
  export {};
package/lib/api.js CHANGED
@@ -22,6 +22,28 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
22
22
  var _Api_provider, _Api_ready, _Api_chain, _Api_chainProperties;
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.Api = void 0;
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
+ */
25
47
  class Api {
26
48
  constructor(provider, signedExtensions) {
27
49
  _Api_provider.set(this, void 0);
@@ -96,18 +118,43 @@ class Api {
96
118
  }
97
119
  getStorage(key, hash) {
98
120
  return __awaiter(this, void 0, void 0, function* () {
99
- const params = [key];
100
- if (hash)
101
- params.push(hash);
102
- return __classPrivateFieldGet(this, _Api_provider, "f").send('state_getStorage', params);
121
+ const [child, storageKey] = (0, utils_1.splitChildKey)(key);
122
+ if (child) {
123
+ // child storage key, use childstate_getStorage
124
+ const params = [child, storageKey];
125
+ if (hash)
126
+ params.push(hash);
127
+ return __classPrivateFieldGet(this, _Api_provider, "f").send('childstate_getStorage', params);
128
+ }
129
+ else {
130
+ // main storage key, use state_getStorage
131
+ const params = [key];
132
+ if (hash)
133
+ params.push(hash);
134
+ return __classPrivateFieldGet(this, _Api_provider, "f").send('state_getStorage', params);
135
+ }
103
136
  });
104
137
  }
105
138
  getKeysPaged(prefix, pageSize, startKey, hash) {
106
139
  return __awaiter(this, void 0, void 0, function* () {
107
- const params = [prefix, pageSize, startKey];
108
- if (hash)
109
- params.push(hash);
110
- return __classPrivateFieldGet(this, _Api_provider, "f").send('state_getKeysPaged', params);
140
+ const [child, storageKey] = (0, utils_1.splitChildKey)(prefix);
141
+ if (child) {
142
+ // child storage key, use childstate_getKeysPaged
143
+ // strip child prefix from startKey
144
+ const params = [child, storageKey, pageSize, (0, utils_1.stripChildPrefix)(startKey)];
145
+ if (hash)
146
+ params.push(hash);
147
+ return __classPrivateFieldGet(this, _Api_provider, "f")
148
+ .send('childstate_getKeysPaged', params)
149
+ .then((keys) => keys.map((key) => (0, utils_1.prefixedChildKey)(child, key)));
150
+ }
151
+ else {
152
+ // main storage key, use state_getKeysPaged
153
+ const params = [prefix, pageSize, startKey];
154
+ if (hash)
155
+ params.push(hash);
156
+ return __classPrivateFieldGet(this, _Api_provider, "f").send('state_getKeysPaged', params);
157
+ }
111
158
  });
112
159
  }
113
160
  }
@@ -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,25 +130,37 @@ 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* () {
114
139
  const layer = new storage_layer_1.StorageLayer(this.storage);
115
140
  yield layer.fold();
116
141
  const prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : '0x';
117
- const startKey = (_b = options.startKey) !== null && _b !== void 0 ? _b : prefix;
142
+ const startKey = (_b = options.startKey) !== null && _b !== void 0 ? _b : '0x';
118
143
  const pageSize = options.pageSize;
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;
@@ -106,13 +134,18 @@ class Blockchain {
106
134
  .getRepository(entities_1.BlockEntity)
107
135
  .findOne({ where: { [typeof key === 'number' ? 'number' : 'hash']: key } });
108
136
  if (blockData) {
109
- const { hash, number, header, extrinsics, parentHash } = blockData;
110
- const parentBlock = parentHash ? __classPrivateFieldGet(this, _Blockchain_blocksByHash, "f")[parentHash] : undefined;
137
+ const { hash, number, header, extrinsics } = blockData;
138
+ const parentHash = blockData.parentHash || undefined;
139
+ let parentBlock = parentHash ? __classPrivateFieldGet(this, _Blockchain_blocksByHash, "f")[parentHash] : undefined;
140
+ if (!parentBlock) {
141
+ parentBlock = yield this.getBlock(parentHash);
142
+ }
111
143
  const storageDiff = (_a = blockData.storageDiff) !== null && _a !== void 0 ? _a : undefined;
112
144
  const registry = yield this.head.registry;
113
145
  const block = new block_1.Block(this, number, hash, parentBlock, {
114
146
  header: registry.createType('Header', header),
115
147
  extrinsics,
148
+ storage: parentBlock === null || parentBlock === void 0 ? void 0 : parentBlock.storage,
116
149
  storageDiff,
117
150
  });
118
151
  __classPrivateFieldGet(this, _Blockchain_instances, "m", _Blockchain_registerBlock).call(this, block);
@@ -122,6 +155,9 @@ class Blockchain {
122
155
  return undefined;
123
156
  });
124
157
  }
158
+ /**
159
+ * Get block by number.
160
+ */
125
161
  getBlockAt(number) {
126
162
  return __awaiter(this, void 0, void 0, function* () {
127
163
  if (number === undefined) {
@@ -145,6 +181,9 @@ class Blockchain {
145
181
  return __classPrivateFieldGet(this, _Blockchain_blocksByNumber, "f").get(number);
146
182
  });
147
183
  }
184
+ /**
185
+ * Get block by hash.
186
+ */
148
187
  getBlock(hash) {
149
188
  return __awaiter(this, void 0, void 0, function* () {
150
189
  yield this.api.isReady;
@@ -181,9 +220,15 @@ class Blockchain {
181
220
  return __classPrivateFieldGet(this, _Blockchain_blocksByHash, "f")[hash];
182
221
  });
183
222
  }
223
+ /**
224
+ * Get all blocks in memory.
225
+ */
184
226
  blocksInMemory() {
185
227
  return Array.from(__classPrivateFieldGet(this, _Blockchain_blocksByNumber, "f").values());
186
228
  }
229
+ /**
230
+ * Remove block from memory and db.
231
+ */
187
232
  unregisterBlock(block) {
188
233
  var _a;
189
234
  return __awaiter(this, void 0, void 0, function* () {
@@ -206,6 +251,9 @@ class Blockchain {
206
251
  yield this.saveBlockToDB(block);
207
252
  });
208
253
  }
254
+ /**
255
+ * Set block as head.
256
+ */
209
257
  setHead(block) {
210
258
  return __awaiter(this, void 0, void 0, function* () {
211
259
  logger.debug({
@@ -220,6 +268,9 @@ class Blockchain {
220
268
  }
221
269
  });
222
270
  }
271
+ /**
272
+ * Submit extrinsic to txpool.
273
+ */
223
274
  submitExtrinsic(extrinsic) {
224
275
  return __awaiter(this, void 0, void 0, function* () {
225
276
  const validity = yield this.validateExtrinsic(extrinsic);
@@ -230,6 +281,9 @@ class Blockchain {
230
281
  throw validity.asErr;
231
282
  });
232
283
  }
284
+ /**
285
+ * Validate extrinsic by calling `TaggedTransactionQueue_validate_transaction`.
286
+ */
233
287
  validateExtrinsic(extrinsic, source = '0x02' /** External */) {
234
288
  return __awaiter(this, void 0, void 0, function* () {
235
289
  const args = (0, util_1.u8aToHex)((0, util_1.u8aConcat)(source, extrinsic, this.head.hash));
@@ -250,23 +304,35 @@ class Blockchain {
250
304
  __classPrivateFieldGet(this, _Blockchain_txpool, "f").submitHorizontalMessages(id, hrmp);
251
305
  logger.debug({ id, hrmp }, 'submitHorizontalMessages');
252
306
  }
307
+ /**
308
+ * Build a new block with optional params. Use this when you don't have all the {@link BuildBlockParams}
309
+ */
253
310
  newBlock(params) {
254
311
  return __awaiter(this, void 0, void 0, function* () {
255
312
  yield __classPrivateFieldGet(this, _Blockchain_txpool, "f").buildBlock(params);
256
313
  return __classPrivateFieldGet(this, _Blockchain_head, "f");
257
314
  });
258
315
  }
316
+ /**
317
+ * Build a new block with {@link BuildBlockParams}.
318
+ */
259
319
  newBlockWithParams(params) {
260
320
  return __awaiter(this, void 0, void 0, function* () {
261
321
  yield __classPrivateFieldGet(this, _Blockchain_txpool, "f").buildBlockWithParams(params);
262
322
  return __classPrivateFieldGet(this, _Blockchain_head, "f");
263
323
  });
264
324
  }
325
+ /**
326
+ * Get the upcoming blocks.
327
+ */
265
328
  upcomingBlocks() {
266
329
  return __awaiter(this, void 0, void 0, function* () {
267
330
  return __classPrivateFieldGet(this, _Blockchain_txpool, "f").upcomingBlocks();
268
331
  });
269
332
  }
333
+ /**
334
+ * Dry run extrinsic in block `at`.
335
+ */
270
336
  dryRunExtrinsic(extrinsic, at) {
271
337
  return __awaiter(this, void 0, void 0, function* () {
272
338
  yield this.api.isReady;
@@ -286,6 +352,10 @@ class Blockchain {
286
352
  return { outcome, storageDiff };
287
353
  });
288
354
  }
355
+ /**
356
+ * Dry run hrmp messages in block `at`.
357
+ * Return the storage diff.
358
+ */
289
359
  dryRunHrmp(hrmp, at) {
290
360
  return __awaiter(this, void 0, void 0, function* () {
291
361
  yield this.api.isReady;
@@ -302,6 +372,10 @@ class Blockchain {
302
372
  return (0, block_builder_1.dryRunInherents)(head, inherents);
303
373
  });
304
374
  }
375
+ /**
376
+ * Dry run dmp messages in block `at`.
377
+ * Return the storage diff.
378
+ */
305
379
  dryRunDmp(dmp, at) {
306
380
  return __awaiter(this, void 0, void 0, function* () {
307
381
  yield this.api.isReady;
@@ -318,6 +392,10 @@ class Blockchain {
318
392
  return (0, block_builder_1.dryRunInherents)(head, inherents);
319
393
  });
320
394
  }
395
+ /**
396
+ * Dry run ump messages in block `at`.
397
+ * Return the storage diff.
398
+ */
321
399
  dryRunUmp(ump, at) {
322
400
  return __awaiter(this, void 0, void 0, function* () {
323
401
  yield this.api.isReady;
@@ -351,6 +429,9 @@ class Blockchain {
351
429
  return (0, block_builder_1.dryRunInherents)(head, inherents);
352
430
  });
353
431
  }
432
+ /**
433
+ * Get inherents of head.
434
+ */
354
435
  getInherents() {
355
436
  return __awaiter(this, void 0, void 0, function* () {
356
437
  yield this.api.isReady;
@@ -363,6 +444,9 @@ class Blockchain {
363
444
  return inherents;
364
445
  });
365
446
  }
447
+ /**
448
+ * Close the db.
449
+ */
366
450
  close() {
367
451
  var _a;
368
452
  return __awaiter(this, void 0, void 0, function* () {
@@ -6,15 +6,27 @@ 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 {
15
27
  #private;
16
28
  constructor(api: Api, at: string, db: DataSource | undefined);
17
- get(key: string): Promise<StorageValue>;
29
+ get(key: string, _cache: boolean): Promise<StorageValue>;
18
30
  foldInto(_into: StorageLayer): Promise<StorageLayerProvider>;
19
31
  fold(): Promise<void>;
20
32
  getKeysPaged(prefix: string, pageSize: number, startKey: string): Promise<string[]>;
@@ -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
  }
@@ -46,7 +46,7 @@ class RemoteStorageLayer {
46
46
  __classPrivateFieldSet(this, _RemoteStorageLayer_at, at, "f");
47
47
  __classPrivateFieldSet(this, _RemoteStorageLayer_db, db, "f");
48
48
  }
49
- get(key) {
49
+ get(key, _cache) {
50
50
  var _a, _b;
51
51
  return __awaiter(this, void 0, void 0, function* () {
52
52
  const keyValuePair = (_a = __classPrivateFieldGet(this, _RemoteStorageLayer_db, "f")) === null || _a === void 0 ? void 0 : _a.getRepository(entities_1.KeyValuePair);
@@ -124,7 +124,7 @@ class StorageLayer {
124
124
  if (key in __classPrivateFieldGet(this, _StorageLayer_store, "f")) {
125
125
  return __classPrivateFieldGet(this, _StorageLayer_store, "f")[key];
126
126
  }
127
- if (__classPrivateFieldGet(this, _StorageLayer_deletedPrefix, "f").some((prefix) => key.startsWith(prefix))) {
127
+ if (__classPrivateFieldGet(this, _StorageLayer_deletedPrefix, "f").some((dp) => key.startsWith(dp))) {
128
128
  return StorageValueKind.Deleted;
129
129
  }
130
130
  if (__classPrivateFieldGet(this, _StorageLayer_parent, "f")) {
@@ -194,10 +194,10 @@ class StorageLayer {
194
194
  getKeysPaged(prefix, pageSize, startKey) {
195
195
  var _a, _b;
196
196
  return __awaiter(this, void 0, void 0, function* () {
197
- if (!__classPrivateFieldGet(this, _StorageLayer_deletedPrefix, "f").some((prefix) => startKey.startsWith(prefix))) {
197
+ if (!__classPrivateFieldGet(this, _StorageLayer_deletedPrefix, "f").some((dp) => startKey.startsWith(dp))) {
198
198
  const remote = (_b = (yield ((_a = __classPrivateFieldGet(this, _StorageLayer_parent, "f")) === null || _a === void 0 ? void 0 : _a.getKeysPaged(prefix, pageSize, startKey)))) !== null && _b !== void 0 ? _b : [];
199
199
  for (const key of remote) {
200
- if (__classPrivateFieldGet(this, _StorageLayer_deletedPrefix, "f").some((prefix) => key.startsWith(prefix))) {
200
+ if (__classPrivateFieldGet(this, _StorageLayer_deletedPrefix, "f").some((dp) => key.startsWith(dp))) {
201
201
  continue;
202
202
  }
203
203
  __classPrivateFieldGet(this, _StorageLayer_instances, "m", _StorageLayer_addKey).call(this, key);
@@ -219,6 +219,9 @@ class StorageLayer {
219
219
  return res;
220
220
  });
221
221
  }
222
+ /**
223
+ * Merge the storage layer into the given object, can be used to get sotrage diff.
224
+ */
222
225
  mergeInto(into) {
223
226
  return __awaiter(this, void 0, void 0, function* () {
224
227
  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 {
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);
@@ -34,12 +34,12 @@ export declare const genesisSchema: z.ZodObject<{
34
34
  }>;
35
35
  }, "strip", z.ZodTypeAny, {
36
36
  name: string;
37
- id: string;
38
37
  properties: {
39
38
  ss58Format?: number | undefined;
40
39
  tokenDecimals?: number | number[] | undefined;
41
40
  tokenSymbol?: string | string[] | undefined;
42
41
  };
42
+ id: string;
43
43
  genesis: {
44
44
  raw: {
45
45
  top: Record<string, string>;
@@ -47,12 +47,12 @@ export declare const genesisSchema: z.ZodObject<{
47
47
  };
48
48
  }, {
49
49
  name: string;
50
- id: string;
51
50
  properties: {
52
51
  ss58Format?: number | undefined;
53
52
  tokenDecimals?: number | number[] | undefined;
54
53
  tokenSymbol?: string | string[] | undefined;
55
54
  };
55
+ id: string;
56
56
  genesis: {
57
57
  raw: {
58
58
  top: Record<string, string>;
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>;
@@ -17,3 +17,7 @@ export type Deferred<T> = {
17
17
  promise: Promise<T>;
18
18
  };
19
19
  export declare function defer<T>(): Deferred<T>;
20
+ export declare const prefixedChildKey: (prefix: HexString, key: HexString) => string;
21
+ export declare const isPrefixedChildKey: (key: HexString) => boolean;
22
+ export declare const splitChildKey: (key: HexString) => never[] | [`0x${string}`, `0x${string}`];
23
+ export declare const stripChildPrefix: (key: HexString) => `0x${string}`;
@@ -23,8 +23,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
23
23
  });
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.defer = exports.isUrl = exports.getParaId = exports.compactHex = exports.fetchKeysToArray = exports.fetchKeys = void 0;
26
+ exports.stripChildPrefix = exports.splitChildKey = exports.isPrefixedChildKey = exports.prefixedChildKey = exports.defer = exports.isUrl = exports.getParaId = exports.compactHex = exports.fetchKeysToArray = exports.fetchKeys = void 0;
27
27
  const util_1 = require("@polkadot/util");
28
+ const hex_1 = require("@polkadot/util/hex");
28
29
  __exportStar(require("./set-storage"), exports);
29
30
  __exportStar(require("./time-travel"), exports);
30
31
  __exportStar(require("./decoder"), exports);
@@ -87,3 +88,34 @@ function defer() {
87
88
  return deferred;
88
89
  }
89
90
  exports.defer = defer;
91
+ // Chopsticks treats both main storage and child storage as a key-value store
92
+ // The difference is that child storage keys are prefixed with the child storage key
93
+ // :child_storage:default: as hex string
94
+ const DEFAULT_CHILD_STORAGE = '0x3a6368696c645f73746f726167653a64656661756c743a';
95
+ // length of the child storage key
96
+ const CHILD_LENGTH = DEFAULT_CHILD_STORAGE.length + 64;
97
+ // returns a key that is prefixed with the child storage key
98
+ const prefixedChildKey = (prefix, key) => prefix + (0, hex_1.hexStripPrefix)(key);
99
+ exports.prefixedChildKey = prefixedChildKey;
100
+ // returns true if the key is a child storage key
101
+ const isPrefixedChildKey = (key) => key.startsWith(DEFAULT_CHILD_STORAGE);
102
+ exports.isPrefixedChildKey = isPrefixedChildKey;
103
+ // returns a key that is split into the child storage key and the rest
104
+ const splitChildKey = (key) => {
105
+ if (!key.startsWith(DEFAULT_CHILD_STORAGE))
106
+ return [];
107
+ if (key.length < CHILD_LENGTH)
108
+ return [];
109
+ const child = key.slice(0, CHILD_LENGTH);
110
+ const rest = key.slice(CHILD_LENGTH);
111
+ return [child, (0, hex_1.hexAddPrefix)(rest)];
112
+ };
113
+ exports.splitChildKey = splitChildKey;
114
+ // returns a key that is stripped of the child storage key
115
+ const stripChildPrefix = (key) => {
116
+ const [child, storageKey] = (0, exports.splitChildKey)(key);
117
+ if (!child)
118
+ return key;
119
+ return storageKey;
120
+ };
121
+ exports.stripChildPrefix = stripChildPrefix;
package/package.json CHANGED
@@ -1,18 +1,19 @@
1
1
  {
2
2
  "name": "@acala-network/chopsticks-core",
3
- "version": "0.8.0",
4
- "author": "Bryan Chen <xlchen1291@gmail.com>",
3
+ "version": "0.8.2",
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.0",
13
+ "@acala-network/chopsticks-executor": "0.8.2",
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"