@acala-network/chopsticks-core 0.9.4-2 → 0.9.4-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cjs/blockchain/inherent/parachain/validation-data.js +1 -13
  2. package/dist/cjs/rpc/substrate/author.js +6 -0
  3. package/dist/cjs/utils/decoder.js +21 -1
  4. package/dist/cjs/wasm-executor/browser-wasm-executor.js +4 -4
  5. package/dist/{types → cjs}/wasm-executor/index.d.ts +6 -4
  6. package/dist/cjs/wasm-executor/index.js +4 -4
  7. package/dist/cjs/wasm-executor/node-wasm-executor.js +4 -4
  8. package/dist/esm/api.d.ts +56 -0
  9. package/dist/esm/blockchain/block-builder.d.ts +15 -0
  10. package/dist/esm/blockchain/block.d.ts +92 -0
  11. package/dist/esm/blockchain/head-state.d.ts +15 -0
  12. package/dist/esm/blockchain/index.d.ts +172 -0
  13. package/dist/esm/blockchain/inherent/index.d.ts +19 -0
  14. package/dist/esm/blockchain/inherent/para-enter.d.ts +7 -0
  15. package/dist/esm/blockchain/inherent/parachain/babe-randomness.d.ts +7 -0
  16. package/dist/esm/blockchain/inherent/parachain/nimbus-author-inherent.d.ts +7 -0
  17. package/dist/esm/blockchain/inherent/parachain/validation-data.d.ts +19 -0
  18. package/dist/esm/blockchain/inherent/parachain/validation-data.js +1 -13
  19. package/dist/esm/blockchain/storage-layer.d.ts +47 -0
  20. package/dist/esm/blockchain/txpool.d.ts +48 -0
  21. package/dist/esm/chopsticks-provider.d.ts +32 -0
  22. package/dist/esm/database.d.ts +26 -0
  23. package/dist/esm/genesis-provider.d.ts +52 -0
  24. package/dist/esm/index.d.ts +28 -0
  25. package/dist/esm/logger.d.ts +7 -0
  26. package/dist/esm/offchain.d.ts +10 -0
  27. package/dist/esm/rpc/index.d.ts +5 -0
  28. package/dist/esm/rpc/shared.d.ts +27 -0
  29. package/dist/esm/rpc/substrate/author.d.ts +28 -0
  30. package/dist/esm/rpc/substrate/author.js +6 -0
  31. package/dist/esm/rpc/substrate/chain.d.ts +45 -0
  32. package/dist/esm/rpc/substrate/index.d.ts +66 -0
  33. package/dist/esm/rpc/substrate/payment.d.ts +16 -0
  34. package/dist/esm/rpc/substrate/state.d.ts +97 -0
  35. package/dist/esm/rpc/substrate/system.d.ts +28 -0
  36. package/dist/esm/schema/index.d.ts +62 -0
  37. package/dist/esm/setup.d.ts +20 -0
  38. package/dist/esm/utils/decoder.d.ts +28 -0
  39. package/dist/esm/utils/decoder.js +21 -1
  40. package/dist/esm/utils/index.d.ts +23 -0
  41. package/dist/esm/utils/key-cache.d.ts +10 -0
  42. package/dist/esm/utils/proof.d.ts +16 -0
  43. package/dist/esm/utils/set-storage.d.ts +7 -0
  44. package/dist/esm/utils/time-travel.d.ts +5 -0
  45. package/dist/esm/utils/well-known-keys.d.ts +7 -0
  46. package/dist/esm/wasm-executor/browser-wasm-executor.js +4 -4
  47. package/dist/esm/wasm-executor/browser-worker.d.ts +4 -0
  48. package/dist/esm/wasm-executor/index.d.ts +82 -0
  49. package/dist/esm/wasm-executor/index.js +4 -4
  50. package/dist/esm/wasm-executor/node-wasm-executor.js +4 -4
  51. package/dist/esm/wasm-executor/node-worker.d.ts +4 -0
  52. package/dist/esm/xcm/downward.d.ts +2 -0
  53. package/dist/esm/xcm/horizontal.d.ts +2 -0
  54. package/dist/esm/xcm/index.d.ts +9 -0
  55. package/dist/esm/xcm/upward.d.ts +2 -0
  56. package/package.json +8 -15
  57. /package/dist/{types → cjs}/api.d.ts +0 -0
  58. /package/dist/{types → cjs}/blockchain/block-builder.d.ts +0 -0
  59. /package/dist/{types → cjs}/blockchain/block.d.ts +0 -0
  60. /package/dist/{types → cjs}/blockchain/head-state.d.ts +0 -0
  61. /package/dist/{types → cjs}/blockchain/index.d.ts +0 -0
  62. /package/dist/{types → cjs}/blockchain/inherent/index.d.ts +0 -0
  63. /package/dist/{types → cjs}/blockchain/inherent/para-enter.d.ts +0 -0
  64. /package/dist/{types → cjs}/blockchain/inherent/parachain/babe-randomness.d.ts +0 -0
  65. /package/dist/{types → cjs}/blockchain/inherent/parachain/nimbus-author-inherent.d.ts +0 -0
  66. /package/dist/{types → cjs}/blockchain/inherent/parachain/validation-data.d.ts +0 -0
  67. /package/dist/{types → cjs}/blockchain/storage-layer.d.ts +0 -0
  68. /package/dist/{types → cjs}/blockchain/txpool.d.ts +0 -0
  69. /package/dist/{types → cjs}/chopsticks-provider.d.ts +0 -0
  70. /package/dist/{types → cjs}/database.d.ts +0 -0
  71. /package/dist/{types → cjs}/genesis-provider.d.ts +0 -0
  72. /package/dist/{types → cjs}/index.d.ts +0 -0
  73. /package/dist/{types → cjs}/logger.d.ts +0 -0
  74. /package/dist/{types → cjs}/offchain.d.ts +0 -0
  75. /package/dist/{types → cjs}/rpc/index.d.ts +0 -0
  76. /package/dist/{types → cjs}/rpc/shared.d.ts +0 -0
  77. /package/dist/{types → cjs}/rpc/substrate/author.d.ts +0 -0
  78. /package/dist/{types → cjs}/rpc/substrate/chain.d.ts +0 -0
  79. /package/dist/{types → cjs}/rpc/substrate/index.d.ts +0 -0
  80. /package/dist/{types → cjs}/rpc/substrate/payment.d.ts +0 -0
  81. /package/dist/{types → cjs}/rpc/substrate/state.d.ts +0 -0
  82. /package/dist/{types → cjs}/rpc/substrate/system.d.ts +0 -0
  83. /package/dist/{types → cjs}/schema/index.d.ts +0 -0
  84. /package/dist/{types → cjs}/setup.d.ts +0 -0
  85. /package/dist/{types → cjs}/utils/decoder.d.ts +0 -0
  86. /package/dist/{types → cjs}/utils/index.d.ts +0 -0
  87. /package/dist/{types → cjs}/utils/key-cache.d.ts +0 -0
  88. /package/dist/{types → cjs}/utils/proof.d.ts +0 -0
  89. /package/dist/{types → cjs}/utils/set-storage.d.ts +0 -0
  90. /package/dist/{types → cjs}/utils/time-travel.d.ts +0 -0
  91. /package/dist/{types → cjs}/utils/well-known-keys.d.ts +0 -0
  92. /package/dist/{types → cjs}/wasm-executor/browser-worker.d.ts +0 -0
  93. /package/dist/{types → cjs}/wasm-executor/node-worker.d.ts +0 -0
  94. /package/dist/{types → cjs}/xcm/downward.d.ts +0 -0
  95. /package/dist/{types → cjs}/xcm/horizontal.d.ts +0 -0
  96. /package/dist/{types → cjs}/xcm/index.d.ts +0 -0
  97. /package/dist/{types → cjs}/xcm/upward.d.ts +0 -0
@@ -71,13 +71,7 @@ class SetValidationData {
71
71
  const dmqMqcHeadKey = (0, _proof.dmqMqcHead)(paraId);
72
72
  const hrmpIngressChannelIndexKey = (0, _proof.hrmpIngressChannelIndex)(paraId);
73
73
  const hrmpEgressChannelIndexKey = (0, _proof.hrmpEgressChannelIndex)(paraId);
74
- // TODO: refactor this to have a single decodeProof
75
- const decoded = await (0, _index1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [
76
- ...Object.values(_proof.WELL_KNOWN_KEYS),
77
- dmqMqcHeadKey,
78
- hrmpIngressChannelIndexKey,
79
- hrmpEgressChannelIndexKey
80
- ], extrinsic.relayChainState.trieNodes);
74
+ const decoded = await (0, _index1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, extrinsic.relayChainState.trieNodes);
81
75
  for (const key of Object.values(_proof.WELL_KNOWN_KEYS)){
82
76
  if (key === _proof.WELL_KNOWN_KEYS.CURRENT_SLOT) {
83
77
  // increment current slot
@@ -140,9 +134,6 @@ class SetValidationData {
140
134
  receiver: paraId.toNumber()
141
135
  });
142
136
  const hrmpChannelKey = (0, _proof.hrmpChannels)(channelId);
143
- const decoded = await (0, _index1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [
144
- hrmpChannelKey
145
- ], extrinsic.relayChainState.trieNodes);
146
137
  const abridgedHrmpRaw = decoded[hrmpChannelKey];
147
138
  if (!abridgedHrmpRaw) throw new Error('Canoot find hrmp channels from validation data');
148
139
  const abridgedHrmp = meta.registry.createType('AbridgedHrmpChannel', (0, _util.hexToU8a)(abridgedHrmpRaw)).toJSON();
@@ -175,9 +166,6 @@ class SetValidationData {
175
166
  receiver
176
167
  });
177
168
  const hrmpChannelKey = (0, _proof.hrmpChannels)(channelId);
178
- const decoded = await (0, _index1.decodeProof)(extrinsic.validationData.relayParentStorageRoot, [
179
- hrmpChannelKey
180
- ], extrinsic.relayChainState.trieNodes);
181
169
  newEntries.push([
182
170
  hrmpChannelKey,
183
171
  decoded[hrmpChannelKey]
@@ -72,6 +72,12 @@ const author_submitAndWatchExtrinsic = async (context, [extrinsic], { subscribe,
72
72
  callback({
73
73
  ready: null
74
74
  });
75
+ // fake broadcast to alice peer
76
+ callback({
77
+ broadcast: [
78
+ '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
79
+ ]
80
+ });
75
81
  }, 50);
76
82
  } catch (error) {
77
83
  logger.error({
@@ -27,11 +27,15 @@ const _lrucache = require("lru-cache");
27
27
  const _util = require("@polkadot/util");
28
28
  const _lodash = /*#__PURE__*/ _interop_require_default(require("lodash"));
29
29
  const _wellknownkeys = require("./well-known-keys.js");
30
+ const _logger = require("../logger.js");
30
31
  function _interop_require_default(obj) {
31
32
  return obj && obj.__esModule ? obj : {
32
33
  default: obj
33
34
  };
34
35
  }
36
+ const logger = _logger.defaultLogger.child({
37
+ module: 'decoder'
38
+ });
35
39
  const _CACHE = {};
36
40
  function createCache() {
37
41
  return new _lrucache.LRUCache({
@@ -85,11 +89,27 @@ const decodeKeyValue = (meta, block, key, value, toHuman = true)=>{
85
89
  }
86
90
  const { storage, decodedKey } = decodeKey(meta, block, key);
87
91
  if (!storage || !decodedKey) {
92
+ logger.warn({
93
+ key,
94
+ value
95
+ }, 'Failed to decode storage key');
88
96
  return undefined;
89
97
  }
90
98
  const decodeValue = ()=>{
91
99
  if (!value) return null;
92
- return meta.registry.createType(decodedKey.outputType, (0, _util.hexToU8a)(value))[toHuman ? 'toHuman' : 'toJSON']();
100
+ try {
101
+ return meta.registry.createType(decodedKey.outputType, (0, _util.hexToU8a)(value))[toHuman ? 'toHuman' : 'toJSON']();
102
+ } catch (error) {
103
+ logger.warn(error, 'Failed to decode storage value');
104
+ logger.warn({
105
+ key,
106
+ value,
107
+ section: storage.section,
108
+ method: storage.method,
109
+ args: decodedKey.args
110
+ }, 'Failed to decode storage value');
111
+ return undefined;
112
+ }
93
113
  };
94
114
  return {
95
115
  section: storage.section,
@@ -52,11 +52,11 @@ const getRuntimeVersion = async (code)=>{
52
52
  const calculateStateRoot = async (entries, trie_version)=>{
53
53
  return _chopsticksexecutor.calculate_state_root(entries, trie_version);
54
54
  };
55
- const decodeProof = async (trieRootHash, keys, nodes)=>{
56
- return _chopsticksexecutor.decode_proof(trieRootHash, keys, nodes);
55
+ const decodeProof = async (trieRootHash, nodes)=>{
56
+ return _chopsticksexecutor.decode_proof(trieRootHash, nodes);
57
57
  };
58
- const createProof = async (nodes, entries)=>{
59
- return _chopsticksexecutor.create_proof(nodes, entries);
58
+ const createProof = async (nodes, updates)=>{
59
+ return _chopsticksexecutor.create_proof(nodes, updates);
60
60
  };
61
61
  const runTask = async (task, callback)=>{
62
62
  return _chopsticksexecutor.run_task(task, callback, 'info');
@@ -33,8 +33,8 @@ export type TaskResponse = {
33
33
  export interface WasmExecutor {
34
34
  getRuntimeVersion: (code: HexString) => Promise<RuntimeVersion>;
35
35
  calculateStateRoot: (entries: [HexString, HexString][], trie_version: number) => Promise<HexString>;
36
- createProof: (nodes: HexString[], entries: [HexString, HexString | null][]) => Promise<[HexString, HexString[]]>;
37
- decodeProof: (trieRootHash: HexString, keys: HexString[], nodes: HexString[]) => Promise<[[HexString, HexString | null]]>;
36
+ createProof: (nodes: HexString[], updates: [HexString, HexString | null][]) => Promise<[HexString, HexString[]]>;
37
+ decodeProof: (trieRootHash: HexString, nodes: HexString[]) => Promise<[[HexString, HexString]]>;
38
38
  runTask: (task: {
39
39
  wasm: HexString;
40
40
  calls: [string, HexString[]][];
@@ -50,8 +50,10 @@ export declare const getWorker: () => Promise<{
50
50
  }>;
51
51
  export declare const getRuntimeVersion: ((code: HexString) => Promise<RuntimeVersion>) & _.MemoizedFunction;
52
52
  export declare const calculateStateRoot: (entries: [HexString, HexString][], trie_version: number) => Promise<HexString>;
53
- export declare const decodeProof: (trieRootHash: HexString, keys: HexString[], nodes: HexString[]) => Promise<{}>;
54
- export declare const createProof: (nodes: HexString[], entries: [HexString, HexString | null][]) => Promise<{
53
+ export declare const decodeProof: (trieRootHash: HexString, nodes: HexString[]) => Promise<{
54
+ [key: `0x${string}`]: `0x${string}`;
55
+ }>;
56
+ export declare const createProof: (nodes: HexString[], updates: [HexString, HexString | null][]) => Promise<{
55
57
  trieRootHash: `0x${string}`;
56
58
  nodes: `0x${string}`[];
57
59
  }>;
@@ -120,17 +120,17 @@ const calculateStateRoot = async (entries, trie_version)=>{
120
120
  const worker = await getWorker();
121
121
  return worker.remote.calculateStateRoot(entries, trie_version);
122
122
  };
123
- const decodeProof = async (trieRootHash, keys, nodes)=>{
123
+ const decodeProof = async (trieRootHash, nodes)=>{
124
124
  const worker = await getWorker();
125
- const result = await worker.remote.decodeProof(trieRootHash, keys, nodes);
125
+ const result = await worker.remote.decodeProof(trieRootHash, nodes);
126
126
  return result.reduce((accum, [key, value])=>{
127
127
  accum[key] = value;
128
128
  return accum;
129
129
  }, {});
130
130
  };
131
- const createProof = async (nodes, entries)=>{
131
+ const createProof = async (nodes, updates)=>{
132
132
  const worker = await getWorker();
133
- const [trieRootHash, newNodes] = await worker.remote.createProof(nodes, entries);
133
+ const [trieRootHash, newNodes] = await worker.remote.createProof(nodes, updates);
134
134
  return {
135
135
  trieRootHash,
136
136
  nodes: newNodes
@@ -59,11 +59,11 @@ const getRuntimeVersion = async (code)=>{
59
59
  const calculateStateRoot = async (entries, trie_version)=>{
60
60
  return _chopsticksexecutor.calculate_state_root(entries, trie_version);
61
61
  };
62
- const decodeProof = async (trieRootHash, keys, nodes)=>{
63
- return _chopsticksexecutor.decode_proof(trieRootHash, keys, nodes);
62
+ const decodeProof = async (trieRootHash, nodes)=>{
63
+ return _chopsticksexecutor.decode_proof(trieRootHash, nodes);
64
64
  };
65
- const createProof = async (nodes, entries)=>{
66
- return _chopsticksexecutor.create_proof(nodes, entries);
65
+ const createProof = async (nodes, updates)=>{
66
+ return _chopsticksexecutor.create_proof(nodes, updates);
67
67
  };
68
68
  const runTask = async (task, callback)=>{
69
69
  return _chopsticksexecutor.run_task(task, callback, process.env.RUST_LOG);
@@ -0,0 +1,56 @@
1
+ import { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types';
2
+ import { HexString } from '@polkadot/util/types';
3
+ import { ProviderInterface, ProviderInterfaceCallback } from '@polkadot/rpc-provider/types';
4
+ export type ChainProperties = {
5
+ ss58Format?: number;
6
+ tokenDecimals?: number[];
7
+ tokenSymbol?: string[];
8
+ };
9
+ type Header = {
10
+ parentHash: HexString;
11
+ number: HexString;
12
+ stateRoot: HexString;
13
+ extrinsicsRoot: HexString;
14
+ digest: {
15
+ logs: HexString[];
16
+ };
17
+ };
18
+ type SignedBlock = {
19
+ block: {
20
+ header: Header;
21
+ extrinsics: HexString[];
22
+ };
23
+ justifications?: HexString[];
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
+ * const provider = new WsProvider(options.endpoint)
33
+ * const api = new Api(provider)
34
+ * await api.isReady
35
+ * ```
36
+ */
37
+ export declare class Api {
38
+ #private;
39
+ readonly signedExtensions: ExtDef;
40
+ constructor(provider: ProviderInterface, signedExtensions?: ExtDef);
41
+ disconnect(): Promise<void>;
42
+ get isReady(): Promise<void> | undefined;
43
+ get chain(): Promise<string>;
44
+ get chainProperties(): Promise<ChainProperties>;
45
+ getSystemName(): Promise<string>;
46
+ getSystemProperties(): Promise<ChainProperties>;
47
+ getSystemChain(): Promise<string>;
48
+ getBlockHash(blockNumber?: number): Promise<`0x${string}` | null>;
49
+ getHeader(hash?: string): Promise<Header | null>;
50
+ getBlock(hash?: string): Promise<SignedBlock | null>;
51
+ getStorage(key: string, hash?: string): Promise<`0x${string}` | null>;
52
+ getKeysPaged(prefix: string, pageSize: number, startKey: string, hash?: string): Promise<string[]>;
53
+ subscribeRemoteNewHeads(cb: ProviderInterfaceCallback): Promise<string | number>;
54
+ subscribeRemoteFinalizedHeads(cb: ProviderInterfaceCallback): Promise<string | number>;
55
+ }
56
+ export {};
@@ -0,0 +1,15 @@
1
+ import { Header, TransactionValidityError } from '@polkadot/types/interfaces';
2
+ import { Block } from './block.js';
3
+ import { HexString } from '@polkadot/util/types';
4
+ import { TaskCallResponse } from '../wasm-executor/index.js';
5
+ export declare const newHeader: (head: Block, unsafeBlockHeight?: number) => Promise<Header>;
6
+ export type BuildBlockCallbacks = {
7
+ onApplyExtrinsicError?: (extrinsic: HexString, error: TransactionValidityError) => void;
8
+ onPhaseApplied?: (phase: 'initialize' | 'finalize' | number, resp: TaskCallResponse) => void;
9
+ };
10
+ export declare const buildBlock: (head: Block, inherents: HexString[], extrinsics: HexString[], ump: Record<number, HexString[]>, callbacks?: BuildBlockCallbacks, unsafeBlockHeight?: number) => Promise<[Block, HexString[]]>;
11
+ export declare const dryRunExtrinsic: (head: Block, inherents: HexString[], extrinsic: HexString | {
12
+ call: HexString;
13
+ address: string;
14
+ }) => Promise<TaskCallResponse>;
15
+ export declare const dryRunInherents: (head: Block, inherents: HexString[]) => Promise<[HexString, HexString | null][]>;
@@ -0,0 +1,92 @@
1
+ import { DecoratedMeta } from '@polkadot/types/metadata/decorate/types';
2
+ import { Header } from '@polkadot/types/interfaces';
3
+ import { TypeRegistry } from '@polkadot/types';
4
+ import { StorageEntry } from '@polkadot/types/primitive/types';
5
+ import type { HexString } from '@polkadot/util/types';
6
+ import { Blockchain } from './index.js';
7
+ import { StorageLayer, StorageLayerProvider, StorageValue } from './storage-layer.js';
8
+ import type { RuntimeVersion, TaskCallResponse } from '../wasm-executor/index.js';
9
+ /**
10
+ * Block class.
11
+ *
12
+ * @example Instantiate a block
13
+ *
14
+ * ```ts
15
+ * const block = new Block(chain, number, hash)
16
+ * ```
17
+ *
18
+ * @example Get storage
19
+ *
20
+ * ```ts
21
+ * const block = await chain.getBlock('0x...')
22
+ * block.storage()
23
+ * ```
24
+ */
25
+ export declare class Block {
26
+ #private;
27
+ readonly number: number;
28
+ readonly hash: HexString;
29
+ constructor(chain: Blockchain, number: number, hash: HexString, parentBlock?: Block, block?: {
30
+ /** See `@polkadot/types/interfaces` Header */
31
+ header: Header;
32
+ /** Extrinsics */
33
+ extrinsics: HexString[];
34
+ /** Storage provider. Default to {@link RemoteStorageLayer} with {@link Blockchain.api chain.api} as remote. */
35
+ storage?: StorageLayerProvider;
36
+ /** Storage diff to apply. */
37
+ storageDiff?: Record<string, StorageValue | null>;
38
+ });
39
+ get chain(): Blockchain;
40
+ get header(): Header | Promise<Header>;
41
+ get extrinsics(): HexString[] | Promise<HexString[]>;
42
+ get parentBlock(): Promise<Block | undefined>;
43
+ /**
44
+ * Get the block storage.
45
+ */
46
+ get storage(): StorageLayerProvider;
47
+ /**
48
+ * Get the block storage by key.
49
+ */
50
+ get(key: string): Promise<HexString | undefined>;
51
+ read<T extends string>(type: T, query: StorageEntry, ...args: any[]): Promise<import("@polkadot/types/types").DetectCodec<import("@polkadot/types-codec/types").Codec, T> | undefined>;
52
+ /**
53
+ * Get paged storage keys.
54
+ */
55
+ getKeysPaged(options: {
56
+ prefix?: string;
57
+ startKey?: string;
58
+ pageSize: number;
59
+ }): Promise<string[]>;
60
+ /**
61
+ * Push a layer to the storage stack.
62
+ */
63
+ pushStorageLayer(): StorageLayer;
64
+ /**
65
+ * Pop a layer from the storage stack.
66
+ */
67
+ popStorageLayer(): void;
68
+ /**
69
+ * Get storage diff.
70
+ */
71
+ storageDiff(): Promise<Record<HexString, HexString | null>>;
72
+ /**
73
+ * Get the wasm string.
74
+ */
75
+ get wasm(): Promise<`0x${string}`>;
76
+ /**
77
+ * Set the runtime wasm.
78
+ */
79
+ setWasm(wasm: HexString): void;
80
+ /**
81
+ * Get the type registry.
82
+ * @see https://polkadot.js.org/docs/api/start/types.create#why-create-types
83
+ */
84
+ get registry(): Promise<TypeRegistry>;
85
+ get runtimeVersion(): Promise<RuntimeVersion>;
86
+ get metadata(): Promise<HexString>;
87
+ get meta(): Promise<DecoratedMeta>;
88
+ /**
89
+ * Call a runtime method.
90
+ */
91
+ call(method: string, args: HexString[]): Promise<TaskCallResponse>;
92
+ }
@@ -0,0 +1,15 @@
1
+ import { Block } from './block.js';
2
+ type Callback = (block: Block, pairs: [string, string | null][]) => void | Promise<void>;
3
+ export declare const randomId: () => string;
4
+ export declare class HeadState {
5
+ #private;
6
+ constructor(head: Block);
7
+ subscribeHead(cb: (block: Block) => void): string;
8
+ unsubscribeHead(id: string): void;
9
+ subscribeStorage(keys: string[], cb: Callback): Promise<string>;
10
+ unsubscribeStorage(id: string): void;
11
+ subscrubeRuntimeVersion(cb: (block: Block) => void): Promise<string>;
12
+ unsubscribeRuntimeVersion(id: string): void;
13
+ setHead(head: Block): Promise<void>;
14
+ }
15
+ export {};
@@ -0,0 +1,172 @@
1
+ import { ApplyExtrinsicResult } from '@polkadot/types/interfaces';
2
+ import { HexString } from '@polkadot/util/types';
3
+ import { TypeRegistry } from '@polkadot/types';
4
+ import { RegisteredTypes } from '@polkadot/types/types';
5
+ import type { TransactionValidity } from '@polkadot/types/interfaces/txqueue';
6
+ import { Api } from '../api.js';
7
+ import { Block } from './block.js';
8
+ import { BuildBlockMode, BuildBlockParams, DownwardMessage, HorizontalMessage, TxPool } from './txpool.js';
9
+ import { Database } from '../database.js';
10
+ import { HeadState } from './head-state.js';
11
+ import { InherentProvider } from './inherent/index.js';
12
+ import { OffchainWorker } from '../offchain.js';
13
+ import { RuntimeVersion } from '../wasm-executor/index.js';
14
+ export interface Options {
15
+ /** API instance, for getting on-chain data. */
16
+ api: Api;
17
+ /** Build block mode. Default to Batch. */
18
+ buildBlockMode?: BuildBlockMode;
19
+ /** Inherent provider, for creating inherents. */
20
+ inherentProvider: InherentProvider;
21
+ /** Datasource for caching storage and blocks data. */
22
+ db?: Database;
23
+ /** Used to create the initial head. */
24
+ header: {
25
+ number: number;
26
+ hash: HexString;
27
+ };
28
+ /** Whether to enable mock signature. Any signature starts with 0xdeadbeef and filled by 0xcd is considered valid */
29
+ mockSignatureHost?: boolean;
30
+ /** Whether to allow wasm unresolved imports. */
31
+ allowUnresolvedImports?: boolean;
32
+ /** Wasm runtime log level. */
33
+ runtimeLogLevel?: number;
34
+ /** Polkadot.js custom types registration. */
35
+ registeredTypes: RegisteredTypes;
36
+ /** Whether to enable offchain Worker. */
37
+ offchainWorker?: boolean;
38
+ /** Max memory block count */
39
+ maxMemoryBlockCount?: number;
40
+ }
41
+ /**
42
+ * Local blockchain which provides access to blocks, txpool and methods
43
+ * to manipulate the chain such as build blocks, submit extrinsics, xcm and more!
44
+ *
45
+ * @example
46
+ *
47
+ * ```ts
48
+ * const chain = new Blockchain({
49
+ * api,
50
+ * buildBlockMode: BuildBlockMode.Manual,
51
+ * inherentProvider: inherents,
52
+ * header: {
53
+ * hash: blockHash,
54
+ * number: Number(header.number),
55
+ * },
56
+ * mockSignatureHost: true,
57
+ * allowUnresolvedImports: true,
58
+ * registeredTypes: {},
59
+ * })
60
+ * // build a block
61
+ * chain.newBlock()
62
+ * ```
63
+ */
64
+ export declare class Blockchain {
65
+ #private;
66
+ readonly uid: string;
67
+ /** API instance, for getting on-chain data. */
68
+ readonly api: Api;
69
+ /** Datasource for caching storage and blocks data. */
70
+ readonly db: Database | undefined;
71
+ /** Enable mock signature. Any signature starts with 0xdeadbeef and filled by 0xcd is considered valid */
72
+ readonly mockSignatureHost: boolean;
73
+ /** Allow wasm unresolved imports. */
74
+ readonly allowUnresolvedImports: boolean;
75
+ /** Polkadot.js custom types registration. */
76
+ readonly registeredTypes: RegisteredTypes;
77
+ /** For subscribing and managing the head state. */
78
+ readonly headState: HeadState;
79
+ readonly offchainWorker: OffchainWorker | undefined;
80
+ /**
81
+ * @param options - Options for instantiating the blockchain
82
+ */
83
+ constructor({ api, buildBlockMode, inherentProvider, db, header, mockSignatureHost, allowUnresolvedImports, runtimeLogLevel, registeredTypes, offchainWorker, maxMemoryBlockCount, }: Options);
84
+ get head(): Block;
85
+ get txPool(): TxPool;
86
+ get runtimeLogLevel(): number;
87
+ set runtimeLogLevel(level: number);
88
+ buildRegistry(metadata: HexString, version: RuntimeVersion): Promise<TypeRegistry>;
89
+ saveBlockToDB(block: Block): Promise<void>;
90
+ /**
91
+ * Try to load block from db and register it.
92
+ * If pass in number, get block by number, else get block by hash.
93
+ */
94
+ loadBlockFromDB(hashOrNumber: number | HexString): Promise<Block | undefined>;
95
+ /**
96
+ * Get block by number.
97
+ */
98
+ getBlockAt(number?: number | null): Promise<Block | undefined>;
99
+ /**
100
+ * Get block by hash.
101
+ */
102
+ getBlock(hash?: HexString): Promise<Block | undefined>;
103
+ /**
104
+ * Get all blocks in memory.
105
+ */
106
+ blocksInMemory(): Block[];
107
+ /**
108
+ * Remove block from memory and db.
109
+ */
110
+ unregisterBlock(block: Block): Promise<void>;
111
+ onNewBlock(block: Block): Promise<void>;
112
+ /**
113
+ * Set block as head.
114
+ */
115
+ setHead(block: Block): Promise<void>;
116
+ /**
117
+ * Submit extrinsic to txpool.
118
+ */
119
+ submitExtrinsic(extrinsic: HexString): Promise<HexString>;
120
+ /**
121
+ * Validate extrinsic by calling `TaggedTransactionQueue_validate_transaction`.
122
+ */
123
+ validateExtrinsic(extrinsic: HexString, source?: '0x00' | '0x01' | '0x02' /** External */): Promise<TransactionValidity>;
124
+ submitUpwardMessages(id: number, ump: HexString[]): void;
125
+ submitDownwardMessages(dmp: DownwardMessage[]): void;
126
+ submitHorizontalMessages(id: number, hrmp: HorizontalMessage[]): void;
127
+ /**
128
+ * Build a new block with optional params. Use this when you don't have all the {@link BuildBlockParams}
129
+ */
130
+ newBlock(params?: Partial<BuildBlockParams>): Promise<Block>;
131
+ /**
132
+ * Build a new block with {@link BuildBlockParams}.
133
+ */
134
+ newBlockWithParams(params: BuildBlockParams): Promise<Block>;
135
+ /**
136
+ * Get the upcoming blocks.
137
+ */
138
+ upcomingBlocks(): Promise<number>;
139
+ /**
140
+ * Dry run extrinsic in block `at`.
141
+ */
142
+ dryRunExtrinsic(extrinsic: HexString | {
143
+ call: HexString;
144
+ address: string;
145
+ }, at?: HexString): Promise<{
146
+ outcome: ApplyExtrinsicResult;
147
+ storageDiff: [HexString, HexString | null][];
148
+ }>;
149
+ /**
150
+ * Dry run hrmp messages in block `at`.
151
+ * Return the storage diff.
152
+ */
153
+ dryRunHrmp(hrmp: Record<number, HorizontalMessage[]>, at?: HexString): Promise<[HexString, HexString | null][]>;
154
+ /**
155
+ * Dry run dmp messages in block `at`.
156
+ * Return the storage diff.
157
+ */
158
+ dryRunDmp(dmp: DownwardMessage[], at?: HexString): Promise<[HexString, HexString | null][]>;
159
+ /**
160
+ * Dry run ump messages in block `at`.
161
+ * Return the storage diff.
162
+ */
163
+ dryRunUmp(ump: Record<number, HexString[]>, at?: HexString): Promise<[HexString, HexString | null][]>;
164
+ /**
165
+ * Get inherents of head.
166
+ */
167
+ getInherents(): Promise<HexString[]>;
168
+ /**
169
+ * Close the db and disconnect api.
170
+ */
171
+ close(): Promise<void>;
172
+ }
@@ -0,0 +1,19 @@
1
+ import { Block } from '../block.js';
2
+ import { BuildBlockParams } from '../txpool.js';
3
+ import { HexString } from '@polkadot/util/types';
4
+ export { SetValidationData } from './parachain/validation-data.js';
5
+ export { ParaInherentEnter } from './para-enter.js';
6
+ export { SetBabeRandomness } from './parachain/babe-randomness.js';
7
+ export { SetNimbusAuthorInherent } from './parachain/nimbus-author-inherent.js';
8
+ export interface CreateInherents {
9
+ createInherents(parent: Block, params: BuildBlockParams): Promise<HexString[]>;
10
+ }
11
+ export type InherentProvider = CreateInherents;
12
+ export declare class SetTimestamp implements InherentProvider {
13
+ createInherents(parent: Block): Promise<HexString[]>;
14
+ }
15
+ export declare class InherentProviders implements InherentProvider {
16
+ #private;
17
+ constructor(base: InherentProvider, providers: CreateInherents[]);
18
+ createInherents(parent: Block, params: BuildBlockParams): Promise<HexString[]>;
19
+ }
@@ -0,0 +1,7 @@
1
+ import { HexString } from '@polkadot/util/types';
2
+ import { Block } from '../block.js';
3
+ import { BuildBlockParams } from '../txpool.js';
4
+ import { CreateInherents } from './index.js';
5
+ export declare class ParaInherentEnter implements CreateInherents {
6
+ createInherents(parent: Block, _params: BuildBlockParams): Promise<HexString[]>;
7
+ }
@@ -0,0 +1,7 @@
1
+ import { HexString } from '@polkadot/util/types';
2
+ import { Block } from '../../block.js';
3
+ import { BuildBlockParams } from '../../txpool.js';
4
+ import { CreateInherents } from '../index.js';
5
+ export declare class SetBabeRandomness implements CreateInherents {
6
+ createInherents(parent: Block, _params: BuildBlockParams): Promise<HexString[]>;
7
+ }
@@ -0,0 +1,7 @@
1
+ import { HexString } from '@polkadot/util/types';
2
+ import { Block } from '../../block.js';
3
+ import { BuildBlockParams } from '../../txpool.js';
4
+ import { CreateInherents } from '../index.js';
5
+ export declare class SetNimbusAuthorInherent implements CreateInherents {
6
+ createInherents(parent: Block, _params: BuildBlockParams): Promise<HexString[]>;
7
+ }
@@ -0,0 +1,19 @@
1
+ import { HexString } from '@polkadot/util/types';
2
+ import { Block } from '../../block.js';
3
+ import { BuildBlockParams, DownwardMessage, HorizontalMessage } from '../../txpool.js';
4
+ import { CreateInherents } from '../index.js';
5
+ export type ValidationData = {
6
+ downwardMessages: DownwardMessage[];
7
+ horizontalMessages: Record<number, HorizontalMessage[]>;
8
+ validationData: {
9
+ relayParentNumber: number;
10
+ relayParentStorageRoot: HexString;
11
+ maxPovSize: number;
12
+ };
13
+ relayChainState: {
14
+ trieNodes: HexString[];
15
+ };
16
+ };
17
+ export declare class SetValidationData implements CreateInherents {
18
+ createInherents(parent: Block, params: BuildBlockParams): Promise<HexString[]>;
19
+ }
@@ -56,13 +56,7 @@ export class SetValidationData {
56
56
  const dmqMqcHeadKey = dmqMqcHead(paraId);
57
57
  const hrmpIngressChannelIndexKey = hrmpIngressChannelIndex(paraId);
58
58
  const hrmpEgressChannelIndexKey = hrmpEgressChannelIndex(paraId);
59
- // TODO: refactor this to have a single decodeProof
60
- const decoded = await decodeProof(extrinsic.validationData.relayParentStorageRoot, [
61
- ...Object.values(WELL_KNOWN_KEYS),
62
- dmqMqcHeadKey,
63
- hrmpIngressChannelIndexKey,
64
- hrmpEgressChannelIndexKey
65
- ], extrinsic.relayChainState.trieNodes);
59
+ const decoded = await decodeProof(extrinsic.validationData.relayParentStorageRoot, extrinsic.relayChainState.trieNodes);
66
60
  for (const key of Object.values(WELL_KNOWN_KEYS)){
67
61
  if (key === WELL_KNOWN_KEYS.CURRENT_SLOT) {
68
62
  // increment current slot
@@ -125,9 +119,6 @@ export class SetValidationData {
125
119
  receiver: paraId.toNumber()
126
120
  });
127
121
  const hrmpChannelKey = hrmpChannels(channelId);
128
- const decoded = await decodeProof(extrinsic.validationData.relayParentStorageRoot, [
129
- hrmpChannelKey
130
- ], extrinsic.relayChainState.trieNodes);
131
122
  const abridgedHrmpRaw = decoded[hrmpChannelKey];
132
123
  if (!abridgedHrmpRaw) throw new Error('Canoot find hrmp channels from validation data');
133
124
  const abridgedHrmp = meta.registry.createType('AbridgedHrmpChannel', hexToU8a(abridgedHrmpRaw)).toJSON();
@@ -160,9 +151,6 @@ export class SetValidationData {
160
151
  receiver
161
152
  });
162
153
  const hrmpChannelKey = hrmpChannels(channelId);
163
- const decoded = await decodeProof(extrinsic.validationData.relayParentStorageRoot, [
164
- hrmpChannelKey
165
- ], extrinsic.relayChainState.trieNodes);
166
154
  newEntries.push([
167
155
  hrmpChannelKey,
168
156
  decoded[hrmpChannelKey]