@acala-network/chopsticks-core 0.8.0-3 → 0.8.0-5

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
@@ -33,11 +33,10 @@ export declare class Api {
33
33
  getSystemName(): Promise<string>;
34
34
  getSystemProperties(): Promise<ChainProperties>;
35
35
  getSystemChain(): Promise<string>;
36
- getMetadata(hash?: string): Promise<string>;
37
- getBlockHash(blockNumber?: number): Promise<`0x${string}`>;
38
- getHeader(hash?: string): Promise<Header>;
39
- getBlock(hash?: string): Promise<SignedBlock>;
40
- getStorage(key: string, hash?: string): Promise<string>;
36
+ getBlockHash(blockNumber?: number): Promise<`0x${string}` | null>;
37
+ getHeader(hash?: string): Promise<Header | null>;
38
+ getBlock(hash?: string): Promise<SignedBlock | null>;
39
+ getStorage(key: string, hash?: string): Promise<string | null>;
41
40
  getKeysPaged(prefix: string, pageSize: number, startKey: string, hash?: string): Promise<string[]>;
42
41
  }
43
42
  export {};
package/lib/api.js CHANGED
@@ -79,11 +79,6 @@ class Api {
79
79
  return __classPrivateFieldGet(this, _Api_provider, "f").send('system_chain', []);
80
80
  });
81
81
  }
82
- getMetadata(hash) {
83
- return __awaiter(this, void 0, void 0, function* () {
84
- return __classPrivateFieldGet(this, _Api_provider, "f").send('state_getMetadata', hash ? [hash] : []);
85
- });
86
- }
87
82
  getBlockHash(blockNumber) {
88
83
  return __awaiter(this, void 0, void 0, function* () {
89
84
  return __classPrivateFieldGet(this, _Api_provider, "f").send('chain_getBlockHash', Number.isInteger(blockNumber) ? [blockNumber] : []);
@@ -75,7 +75,12 @@ class Block {
75
75
  }
76
76
  get extrinsics() {
77
77
  if (!__classPrivateFieldGet(this, _Block_extrinsics, "f")) {
78
- __classPrivateFieldSet(this, _Block_extrinsics, __classPrivateFieldGet(this, _Block_chain, "f").api.getBlock(this.hash).then((b) => b.block.extrinsics), "f");
78
+ __classPrivateFieldSet(this, _Block_extrinsics, __classPrivateFieldGet(this, _Block_chain, "f").api.getBlock(this.hash).then((b) => {
79
+ if (!b) {
80
+ throw new Error(`Block ${this.hash} not found`);
81
+ }
82
+ return b.block.extrinsics;
83
+ }), "f");
79
84
  }
80
85
  return __classPrivateFieldGet(this, _Block_extrinsics, "f");
81
86
  }
@@ -70,4 +70,5 @@ export declare class Blockchain {
70
70
  dryRunDmp(dmp: DownwardMessage[], at?: HexString): Promise<[HexString, HexString | null][]>;
71
71
  dryRunUmp(ump: Record<number, HexString[]>, at?: HexString): Promise<[HexString, HexString | null][]>;
72
72
  getInherents(): Promise<HexString[]>;
73
+ close(): Promise<void>;
73
74
  }
@@ -91,14 +91,16 @@ class Blockchain {
91
91
  * If pass in number, get block by number, else get block by hash
92
92
  */
93
93
  loadBlockFromDB(key) {
94
+ var _a;
94
95
  return __awaiter(this, void 0, void 0, function* () {
95
96
  if (this.db) {
96
97
  const blockData = yield this.db
97
98
  .getRepository(entities_1.BlockEntity)
98
99
  .findOne({ where: { [typeof key === 'number' ? 'number' : 'hash']: key } });
99
100
  if (blockData) {
100
- const { hash, number, header, extrinsics, parentHash, storageDiff } = blockData;
101
+ const { hash, number, header, extrinsics, parentHash } = blockData;
101
102
  const parentBlock = parentHash ? __classPrivateFieldGet(this, _Blockchain_blocksByHash, "f")[parentHash] : undefined;
103
+ const storageDiff = (_a = blockData.storageDiff) !== null && _a !== void 0 ? _a : undefined;
102
104
  const block = new block_1.Block(this, number, hash, parentBlock, { header, extrinsics, storageDiff });
103
105
  __classPrivateFieldGet(this, _Blockchain_instances, "m", _Blockchain_registerBlock).call(this, block);
104
106
  return block;
@@ -121,6 +123,9 @@ class Blockchain {
121
123
  return blockFromDB;
122
124
  }
123
125
  const hash = yield this.api.getBlockHash(number);
126
+ if (!hash) {
127
+ return undefined;
128
+ }
124
129
  const block = new block_1.Block(this, number, hash);
125
130
  __classPrivateFieldGet(this, _Blockchain_instances, "m", _Blockchain_registerBlock).call(this, block);
126
131
  }
@@ -144,6 +149,9 @@ class Blockchain {
144
149
  const blockFromDB = yield this.loadBlockFromDB(hash);
145
150
  if (!blockFromDB) {
146
151
  const header = yield this.api.getHeader(hash);
152
+ if (!header) {
153
+ throw new Error(`Block ${hash} not found`);
154
+ }
147
155
  const block = new block_1.Block(this, Number(header.number), hash);
148
156
  __classPrivateFieldGet(this, _Blockchain_instances, "m", _Blockchain_registerBlock).call(this, block);
149
157
  }
@@ -342,6 +350,12 @@ class Blockchain {
342
350
  return inherents;
343
351
  });
344
352
  }
353
+ close() {
354
+ var _a;
355
+ return __awaiter(this, void 0, void 0, function* () {
356
+ yield ((_a = this.db) === null || _a === void 0 ? void 0 : _a.destroy());
357
+ });
358
+ }
345
359
  }
346
360
  exports.Blockchain = Blockchain;
347
361
  _Blockchain_txpool = new WeakMap(), _Blockchain_inherentProvider = new WeakMap(), _Blockchain_head = new WeakMap(), _Blockchain_blocksByNumber = new WeakMap(), _Blockchain_blocksByHash = new WeakMap(), _Blockchain_loadingBlocks = new WeakMap(), _Blockchain_maxMemoryBlockCount = new WeakMap(), _Blockchain_instances = new WeakSet(), _Blockchain_registerBlock = function _Blockchain_registerBlock(block) {
@@ -47,19 +47,19 @@ class RemoteStorageLayer {
47
47
  __classPrivateFieldSet(this, _RemoteStorageLayer_db, db, "f");
48
48
  }
49
49
  get(key) {
50
- var _a;
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);
53
53
  if (__classPrivateFieldGet(this, _RemoteStorageLayer_db, "f")) {
54
54
  const res = yield (keyValuePair === null || keyValuePair === void 0 ? void 0 : keyValuePair.findOne({ where: { key, blockHash: __classPrivateFieldGet(this, _RemoteStorageLayer_at, "f") } }));
55
55
  if (res) {
56
- return res.value;
56
+ return (_b = res.value) !== null && _b !== void 0 ? _b : undefined;
57
57
  }
58
58
  }
59
59
  logger.trace({ at: __classPrivateFieldGet(this, _RemoteStorageLayer_at, "f"), key }, 'RemoteStorageLayer get');
60
60
  const data = yield __classPrivateFieldGet(this, _RemoteStorageLayer_api, "f").getStorage(key, __classPrivateFieldGet(this, _RemoteStorageLayer_at, "f"));
61
61
  keyValuePair === null || keyValuePair === void 0 ? void 0 : keyValuePair.upsert({ key, blockHash: __classPrivateFieldGet(this, _RemoteStorageLayer_at, "f"), value: data }, ['key', 'blockHash']);
62
- return data;
62
+ return data !== null && data !== void 0 ? data : undefined;
63
63
  });
64
64
  }
65
65
  foldInto(_into) {
@@ -4,13 +4,13 @@ import { HexString } from '@polkadot/util/types';
4
4
  export declare const KeyValuePair: EntitySchema<{
5
5
  blockHash: string;
6
6
  key: string;
7
- value?: string | undefined;
7
+ value: string | null;
8
8
  }>;
9
9
  export declare const BlockEntity: EntitySchema<{
10
10
  hash: HexString;
11
11
  number: number;
12
12
  header: Header;
13
- parentHash?: `0x${string}` | undefined;
13
+ parentHash: HexString | null;
14
14
  extrinsics: HexString[];
15
- storageDiff?: Record<`0x${string}`, `0x${string}` | null> | undefined;
15
+ storageDiff: Record<HexString, HexString | null> | null;
16
16
  }>;
@@ -49,7 +49,6 @@ var _a, _GenesisProvider_isConnected, _GenesisProvider_eventemitter, _GenesisPro
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
50
  exports.GenesisProvider = void 0;
51
51
  const eventemitter3_1 = require("eventemitter3");
52
- const util_1 = require("@polkadot/util");
53
52
  const axios_1 = __importDefault(require("axios"));
54
53
  const schema_1 = require("./schema");
55
54
  const executor_1 = require("./executor");
@@ -105,16 +104,6 @@ class GenesisProvider {
105
104
  return __classPrivateFieldGet(this, _GenesisProvider_genesis, "f").id;
106
105
  case 'system_name':
107
106
  return __classPrivateFieldGet(this, _GenesisProvider_genesis, "f").name;
108
- case 'state_getMetadata': {
109
- const code = __classPrivateFieldGet(this, _GenesisProvider_genesis, "f").genesis.raw.top[(0, util_1.stringToHex)(':code')];
110
- return (0, executor_1.runTask)({
111
- wasm: code,
112
- calls: [['Metadata_metadata', []]],
113
- mockSignatureHost: false,
114
- allowUnresolvedImports: true,
115
- runtimeLogLevel: 0,
116
- }, this._jsCallback);
117
- }
118
107
  case 'chain_getHeader':
119
108
  return this.getHeader();
120
109
  case 'chain_getBlock':
package/lib/setup.js CHANGED
@@ -35,13 +35,24 @@ const setup = (options) => __awaiter(void 0, void 0, void 0, function* () {
35
35
  yield api.isReady;
36
36
  let blockHash;
37
37
  if (options.block == null) {
38
- blockHash = yield api.getBlockHash();
38
+ blockHash = yield api.getBlockHash().then((hash) => {
39
+ if (!hash) {
40
+ // should not happen, but just in case
41
+ throw new Error('Cannot find block hash');
42
+ }
43
+ return hash;
44
+ });
39
45
  }
40
46
  else if (typeof options.block === 'string' && options.block.startsWith('0x')) {
41
47
  blockHash = options.block;
42
48
  }
43
49
  else if (Number.isInteger(+options.block)) {
44
- blockHash = yield api.getBlockHash(Number(options.block));
50
+ blockHash = yield api.getBlockHash(Number(options.block)).then((hash) => {
51
+ if (!hash) {
52
+ throw new Error(`Cannot find block hash for ${options.block}`);
53
+ }
54
+ return hash;
55
+ });
45
56
  }
46
57
  else {
47
58
  throw new Error(`Invalid block number or hash: ${options.block}`);
@@ -52,6 +63,9 @@ const setup = (options) => __awaiter(void 0, void 0, void 0, function* () {
52
63
  db = yield (0, db_1.openDb)(options.db);
53
64
  }
54
65
  const header = yield api.getHeader(blockHash);
66
+ if (!header) {
67
+ throw new Error(`Cannot find header for ${blockHash}`);
68
+ }
55
69
  const inherents = new inherent_1.InherentProviders(new inherent_1.SetTimestamp(), [
56
70
  new inherent_1.SetValidationData(),
57
71
  new inherent_1.ParaInherentEnter(),
@@ -0,0 +1,24 @@
1
+ import '@polkadot/types-codec';
2
+ import { Block } from '../blockchain/block';
3
+ import { DecoratedMeta } from '@polkadot/types/metadata/decorate/types';
4
+ import { HexString } from '@polkadot/util/types';
5
+ import { StorageEntry } from '@polkadot/types/primitive/types';
6
+ import { StorageKey } from '@polkadot/types';
7
+ export declare const decodeKey: (meta: DecoratedMeta, block: Block, key: HexString) => {
8
+ storage?: StorageEntry | undefined;
9
+ decodedKey?: StorageKey<import("@polkadot/types-codec/types").AnyTuple> | undefined;
10
+ };
11
+ export declare const decodeKeyValue: (meta: DecoratedMeta, block: Block, key: HexString, value?: HexString | null) => {
12
+ [x: string]: `0x${string}` | null | undefined;
13
+ } | {
14
+ [x: string]: {
15
+ [x: string]: import("@polkadot/types-codec/types").AnyJson;
16
+ };
17
+ };
18
+ /**
19
+ * Decode block storage diff
20
+ * @param block Block to compare storage diff
21
+ * @param diff Storage diff
22
+ * @returns decoded old state and new state
23
+ */
24
+ export declare const decodeBlockStorageDiff: (block: Block, diff: [HexString, HexString | null][]) => Promise<{}[]>;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.decodeBlockStorageDiff = exports.decodeKeyValue = exports.decodeKey = void 0;
16
+ require("@polkadot/types-codec");
17
+ const util_crypto_1 = require("@polkadot/util-crypto");
18
+ const util_1 = require("@polkadot/util");
19
+ const lodash_1 = __importDefault(require("lodash"));
20
+ const _CACHE = {};
21
+ const getCache = (uid) => {
22
+ if (!_CACHE[uid]) {
23
+ _CACHE[uid] = new Map();
24
+ }
25
+ return _CACHE[uid];
26
+ };
27
+ const getStorageEntry = (meta, block, key) => {
28
+ const cache = getCache(block.chain.uid);
29
+ for (const [prefix, storageEntry] of cache.entries()) {
30
+ if (key.startsWith(prefix))
31
+ return storageEntry;
32
+ }
33
+ for (const module of Object.values(meta.query)) {
34
+ for (const storage of Object.values(module)) {
35
+ const keyPrefix = (0, util_1.u8aToHex)(storage.keyPrefix());
36
+ if (key.startsWith(keyPrefix)) {
37
+ cache.set(keyPrefix, storage);
38
+ return storage;
39
+ }
40
+ }
41
+ }
42
+ return undefined;
43
+ };
44
+ const decodeKey = (meta, block, key) => {
45
+ const storage = getStorageEntry(meta, block, key);
46
+ const decodedKey = meta.registry.createType('StorageKey', key);
47
+ if (storage) {
48
+ decodedKey.setMeta(storage.meta);
49
+ return { storage, decodedKey };
50
+ }
51
+ return {};
52
+ };
53
+ exports.decodeKey = decodeKey;
54
+ const decodeKeyValue = (meta, block, key, value) => {
55
+ const { storage, decodedKey } = (0, exports.decodeKey)(meta, block, key);
56
+ if (!storage || !decodedKey) {
57
+ return { [key]: value };
58
+ }
59
+ const decodeValue = () => {
60
+ if (!value)
61
+ return null;
62
+ if (storage.section === 'substrate' && storage.method === 'code') {
63
+ return `:code blake2_256 ${(0, util_crypto_1.blake2AsHex)(value, 256)} (${(0, util_1.hexToU8a)(value).length} bytes)`;
64
+ }
65
+ return meta.registry.createType(decodedKey.outputType, (0, util_1.hexToU8a)(value)).toHuman();
66
+ };
67
+ switch (decodedKey.args.length) {
68
+ case 2: {
69
+ return {
70
+ [storage.section]: {
71
+ [storage.method]: {
72
+ [decodedKey.args[0].toString()]: {
73
+ [decodedKey.args[1].toString()]: decodeValue(),
74
+ },
75
+ },
76
+ },
77
+ };
78
+ }
79
+ case 1: {
80
+ return {
81
+ [storage.section]: {
82
+ [storage.method]: {
83
+ [decodedKey.args[0].toString()]: decodeValue(),
84
+ },
85
+ },
86
+ };
87
+ }
88
+ default:
89
+ return {
90
+ [storage.section]: {
91
+ [storage.method]: decodeValue(),
92
+ },
93
+ };
94
+ }
95
+ };
96
+ exports.decodeKeyValue = decodeKeyValue;
97
+ /**
98
+ * Decode block storage diff
99
+ * @param block Block to compare storage diff
100
+ * @param diff Storage diff
101
+ * @returns decoded old state and new state
102
+ */
103
+ const decodeBlockStorageDiff = (block, diff) => __awaiter(void 0, void 0, void 0, function* () {
104
+ const oldState = {};
105
+ const newState = {};
106
+ const meta = yield block.meta;
107
+ for (const [key, value] of diff) {
108
+ lodash_1.default.merge(oldState, (0, exports.decodeKeyValue)(meta, block, key, (yield block.get(key))));
109
+ lodash_1.default.merge(newState, (0, exports.decodeKeyValue)(meta, block, key, value));
110
+ }
111
+ return [oldState, newState];
112
+ });
113
+ exports.decodeBlockStorageDiff = decodeBlockStorageDiff;
@@ -3,6 +3,7 @@ import { StorageKey } from '@polkadot/types';
3
3
  import { Blockchain } from '../blockchain';
4
4
  export * from './set-storage';
5
5
  export * from './time-travel';
6
+ export * from './decoder';
6
7
  export type GetKeys = (startKey?: string) => Promise<StorageKey<any>[]>;
7
8
  export type ProcessKey = (key: StorageKey<any>) => any;
8
9
  export declare function fetchKeys(getKeys: GetKeys, processKey: ProcessKey): Promise<void>;
@@ -27,6 +27,7 @@ exports.defer = exports.isUrl = exports.getParaId = exports.compactHex = exports
27
27
  const util_1 = require("@polkadot/util");
28
28
  __exportStar(require("./set-storage"), exports);
29
29
  __exportStar(require("./time-travel"), exports);
30
+ __exportStar(require("./decoder"), exports);
30
31
  function fetchKeys(getKeys, processKey) {
31
32
  return __awaiter(this, void 0, void 0, function* () {
32
33
  const processKeys = (keys) => __awaiter(this, void 0, void 0, function* () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acala-network/chopsticks-core",
3
- "version": "0.8.0-3",
3
+ "version": "0.8.0-5",
4
4
  "author": "Bryan Chen <xlchen1291@gmail.com>",
5
5
  "license": "Apache-2.0",
6
6
  "scripts": {
@@ -9,8 +9,9 @@
9
9
  "build": "yarn pack-wasm; tsc -p ./tsconfig.json"
10
10
  },
11
11
  "dependencies": {
12
- "@acala-network/chopsticks-executor": "0.8.0-3",
12
+ "@acala-network/chopsticks-executor": "0.8.0-5",
13
13
  "@polkadot/api": "^10.9.1",
14
+ "@polkadot/util-crypto": "^12.3.2",
14
15
  "axios": "^1.4.0",
15
16
  "eventemitter3": "^5.0.1",
16
17
  "localforage": "^1.10.0",
@@ -20,7 +21,7 @@
20
21
  "sql.js": "^1.8.0",
21
22
  "sqlite3": "^5.1.6",
22
23
  "typeorm": "^0.3.17",
23
- "zod": "^3.21.4"
24
+ "zod": "^3.22.2"
24
25
  },
25
26
  "devDependencies": {
26
27
  "@types/lodash": "^4.14.197",