@acala-network/chopsticks-core 0.8.4 → 0.8.5-0

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.
@@ -1,5 +1,5 @@
1
1
  import { Block } from './block';
2
- type Callback = (block: Block, pairs: [string, string][]) => void | Promise<void>;
2
+ type Callback = (block: Block, pairs: [string, string | null][]) => void | Promise<void>;
3
3
  export declare const randomId: () => string;
4
4
  export declare class HeadState {
5
5
  #private;
@@ -48,7 +48,7 @@ class HeadState {
48
48
  const id = (0, exports.randomId)();
49
49
  __classPrivateFieldGet(this, _HeadState_storageListeners, "f")[id] = [keys, cb];
50
50
  for (const key of keys) {
51
- __classPrivateFieldGet(this, _HeadState_oldValues, "f")[key] = yield __classPrivateFieldGet(this, _HeadState_head, "f").get(key);
51
+ __classPrivateFieldGet(this, _HeadState_oldValues, "f")[key] = yield __classPrivateFieldGet(this, _HeadState_head, "f").get(key).then((val) => val || null);
52
52
  }
53
53
  return id;
54
54
  });
@@ -61,7 +61,7 @@ class HeadState {
61
61
  const id = (0, exports.randomId)();
62
62
  const codeKey = (0, util_1.stringToHex)(':code');
63
63
  __classPrivateFieldGet(this, _HeadState_storageListeners, "f")[id] = [[codeKey], cb];
64
- __classPrivateFieldGet(this, _HeadState_oldValues, "f")[codeKey] = yield __classPrivateFieldGet(this, _HeadState_head, "f").get(codeKey);
64
+ __classPrivateFieldGet(this, _HeadState_oldValues, "f")[codeKey] = yield __classPrivateFieldGet(this, _HeadState_head, "f").get(codeKey).then((val) => val || null);
65
65
  return id;
66
66
  });
67
67
  }
@@ -452,6 +452,7 @@ class Blockchain {
452
452
  var _a;
453
453
  return __awaiter(this, void 0, void 0, function* () {
454
454
  yield (0, wasm_executor_1.releaseWorker)();
455
+ yield this.api.disconnect();
455
456
  yield ((_a = this.db) === null || _a === void 0 ? void 0 : _a.destroy());
456
457
  });
457
458
  }
@@ -0,0 +1,31 @@
1
+ import { ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
2
+ import { Blockchain } from './blockchain';
3
+ interface SubscriptionHandler {
4
+ callback: ProviderInterfaceCallback;
5
+ type: string;
6
+ }
7
+ /**
8
+ * Provider for local chopsticks chain
9
+ */
10
+ export declare class ChopsticksProvider implements ProviderInterface {
11
+ #private;
12
+ readonly chain: Blockchain;
13
+ constructor(chain: Blockchain);
14
+ static fromEndpoint: (endpoint: string, block?: number | string | null, cache?: string) => Promise<ChopsticksProvider>;
15
+ get hasSubscriptions(): boolean;
16
+ get isClonable(): boolean;
17
+ get isConnected(): boolean;
18
+ get isReady(): Promise<void>;
19
+ clone: () => ChopsticksProvider;
20
+ connect: () => Promise<void>;
21
+ disconnect: () => Promise<void>;
22
+ on: (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb) => (() => void);
23
+ subscriptionManager: {
24
+ subscribe: (method: string, subid: string, onCancel?: () => void) => (data: any) => void;
25
+ unsubscribe: (subid: string) => void;
26
+ };
27
+ send: <T>(method: string, params: unknown[], _isCacheable?: boolean, subscription?: SubscriptionHandler) => Promise<T>;
28
+ subscribe(type: string, method: string, params: unknown[], callback: ProviderInterfaceCallback): Promise<number | string>;
29
+ unsubscribe(_type: string, method: string, id: number | string): Promise<boolean>;
30
+ }
31
+ export {};
@@ -1,249 +1,169 @@
1
1
  "use strict";
2
- // import { EventEmitter } from 'eventemitter3'
3
- // import {
4
- // ProviderInterface,
5
- // ProviderInterfaceCallback,
6
- // ProviderInterfaceEmitCb,
7
- // ProviderInterfaceEmitted,
8
- // ProviderStats,
9
- // } from '@polkadot/rpc-provider/types'
10
- // import { StorageValues } from './utils'
11
- // import { defaultLogger } from './logger'
12
- // const logger = defaultLogger.child({ name: '[Chopsticks provider]' })
13
- // interface SubscriptionHandler {
14
- // callback: ProviderInterfaceCallback
15
- // type: string
16
- // }
17
- // interface Subscription extends SubscriptionHandler {
18
- // method: string
19
- // params: unknown[]
20
- // onCancel?: () => void
21
- // result?: unknown
22
- // }
23
- // interface Handler {
24
- // callback: ProviderInterfaceCallback
25
- // method: string
26
- // params: unknown[]
27
- // start: number
28
- // subscription?: SubscriptionHandler | undefined
29
- // }
30
- // export interface ChopsticksProviderProps {
31
- // /** upstream endpoint */
32
- // endpoint: string
33
- // /** default to latest block */
34
- // blockHash?: string
35
- // dbPath?: string
36
- // storageValues?: StorageValues
37
- // }
38
- // /**
39
- // * A provider for ApiPromise.
40
- // *
41
- // * Currectly only support browser environment.
42
- // */
43
- // export class ChopsticksProvider implements ProviderInterface {
44
- // #isConnected = false
45
- // #eventemitter: EventEmitter
46
- // #isReadyPromise: Promise<void>
47
- // #endpoint: string
48
- // readonly stats?: ProviderStats
49
- // #subscriptions: Record<string, Subscription> = {}
50
- // #worker: Worker
51
- // #blockHash: string | undefined
52
- // #dbPath: string | undefined
53
- // #storageValues: StorageValues | undefined
54
- // #handlers: Record<string, Handler> = {}
55
- // #idCounter = 0
56
- // constructor({ endpoint, blockHash, dbPath, storageValues }: ChopsticksProviderProps) {
57
- // if (!endpoint) {
58
- // throw new Error('ChopsticksProvider requires the upstream endpoint')
59
- // }
60
- // this.#endpoint = endpoint
61
- // this.#blockHash = blockHash
62
- // this.#dbPath = dbPath
63
- // this.#storageValues = storageValues
64
- // this.#eventemitter = new EventEmitter()
65
- // this.#isReadyPromise = new Promise((resolve, reject): void => {
66
- // this.#eventemitter.once('connected', (): void => {
67
- // logger.debug('isReadyPromise: connected.')
68
- // resolve()
69
- // })
70
- // this.#eventemitter.once('error', reject)
71
- // })
72
- // const chopsticksWorker = new Worker(new URL('./chopsticks-worker', import.meta.url), { type: 'module' })
73
- // this.#worker = chopsticksWorker
74
- // this.connect()
75
- // }
76
- // get hasSubscriptions(): boolean {
77
- // return true
78
- // }
79
- // get isClonable(): boolean {
80
- // return true
81
- // }
82
- // get isConnected(): boolean {
83
- // return this.#isConnected
84
- // }
85
- // get isReady(): Promise<void> {
86
- // return this.#isReadyPromise
87
- // }
88
- // clone = (): ProviderInterface => {
89
- // return new ChopsticksProvider({ endpoint: this.#endpoint })
90
- // }
91
- // connect = async (): Promise<void> => {
92
- // if (this.#isConnected) {
93
- // return
94
- // }
95
- // this.#worker!.onmessage = this.#onWorkerMessage
96
- // this.#worker?.postMessage({
97
- // type: 'connect',
98
- // endpoint: this.#endpoint,
99
- // blockHash: this.#blockHash,
100
- // dbPath: this.#dbPath,
101
- // storageValues: this.#storageValues,
102
- // })
103
- // }
104
- // disconnect = async (): Promise<void> => {
105
- // this.#worker?.postMessage({ type: 'disconnect' })
106
- // this.#isConnected = false
107
- // this.#eventemitter.emit('disconnected')
108
- // }
109
- // on = (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): (() => void) => {
110
- // this.#eventemitter.on(type, sub)
111
- // return (): void => {
112
- // this.#eventemitter.removeListener(type, sub)
113
- // }
114
- // }
115
- // send = async <T>(
116
- // method: string,
117
- // params: unknown[],
118
- // _isCacheable?: boolean,
119
- // subscription?: SubscriptionHandler,
120
- // ): Promise<T> => {
121
- // return new Promise<T>((resolve, reject): void => {
122
- // try {
123
- // if (!this.isConnected || this.#worker === undefined) {
124
- // throw new Error('Api is not connected')
125
- // }
126
- // logger.debug('send', { method, params })
127
- // const id = `${method}::${this.#idCounter++}`
128
- // const callback = (error?: Error | null, result?: T): void => {
129
- // if (subscription) {
130
- // // if it's a subscription, we usually returns the subid
131
- // const subid = result as string
132
- // if (subid) {
133
- // if (!this.#subscriptions[subid]) {
134
- // this.#subscriptions[subid] = {
135
- // callback: subscription.callback,
136
- // method,
137
- // params,
138
- // type: subscription.type,
139
- // }
140
- // }
141
- // }
142
- // }
143
- // error ? reject(error) : resolve(result as T)
144
- // }
145
- // this.#handlers[id] = {
146
- // callback,
147
- // method,
148
- // params,
149
- // start: Date.now(),
150
- // subscription,
151
- // }
152
- // this.#worker?.postMessage({
153
- // type: 'send',
154
- // id,
155
- // method,
156
- // params,
157
- // })
158
- // } catch (error) {
159
- // reject(error)
160
- // }
161
- // })
162
- // }
163
- // subscribe(
164
- // type: string,
165
- // method: string,
166
- // params: unknown[],
167
- // callback: ProviderInterfaceCallback,
168
- // ): Promise<number | string> {
169
- // return this.send<string | number>(method, params, false, { callback, type })
170
- // }
171
- // async unsubscribe(_type: string, method: string, id: number | string): Promise<boolean> {
172
- // if (!this.#subscriptions[id]) {
173
- // logger.error(`Unable to find active subscription=${id}`)
174
- // return false
175
- // }
176
- // try {
177
- // return this.isConnected ? this.send<boolean>(method, [id]) : true
178
- // } catch {
179
- // return false
180
- // }
181
- // }
182
- // #onWorkerMessage = (e: any) => {
183
- // switch (e.data.type) {
184
- // case 'connection':
185
- // logger.debug('connection.', e.data)
186
- // if (e.data.connected) {
187
- // this.#isConnected = true
188
- // this.#eventemitter.emit('connected')
189
- // } else {
190
- // this.#isConnected = false
191
- // this.#eventemitter.emit('error', new Error('Unable to connect to the chain'))
192
- // logger.error(`Unable to connect to the chain: ${e.data.message}`)
193
- // }
194
- // break
195
- // case 'subscribe-callback':
196
- // {
197
- // logger.debug('subscribe-callback', e.data)
198
- // const sub = this.#subscriptions[e.data.subid]
199
- // if (!sub) {
200
- // // record it first, sometimes callback comes first
201
- // this.#subscriptions[e.data.subid] = {
202
- // callback: () => {},
203
- // method: e.data.method,
204
- // params: e.data.params,
205
- // type: e.data.type,
206
- // result: JSON.parse(e.data.result),
207
- // }
208
- // return
209
- // }
210
- // sub.callback(null, JSON.parse(e.data.result))
211
- // }
212
- // break
213
- // case 'unsubscribe-callback':
214
- // {
215
- // logger.debug('unsubscribe-callback', e.data)
216
- // const sub = this.#subscriptions[e.data.subid]
217
- // if (!sub) {
218
- // logger.error(`Unable to find active subscription=${e.data.subid}`)
219
- // return
220
- // }
221
- // sub?.onCancel?.()
222
- // delete this.#subscriptions[e.data.subid]
223
- // }
224
- // break
225
- // case 'send-result':
226
- // {
227
- // const handler = this.#handlers[e.data.id]
228
- // if (!handler) {
229
- // logger.error(`Unable to find handler=${e.data.id}`)
230
- // return
231
- // }
232
- // logger.debug('send-result', {
233
- // method: e.data.method,
234
- // result: JSON.parse(e.data.result || '{}'),
235
- // data: e.data,
236
- // })
237
- // try {
238
- // handler.callback(null, e.data.result ? JSON.parse(e.data.result) : undefined)
239
- // } catch (error) {
240
- // handler.callback(error as Error, undefined)
241
- // }
242
- // delete this.#handlers[e.data.id]
243
- // }
244
- // break
245
- // default:
246
- // break
247
- // }
248
- // }
249
- // }
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 __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var _a, _ChopsticksProvider_isConnected, _ChopsticksProvider_eventemitter, _ChopsticksProvider_isReadyPromise, _ChopsticksProvider_subscriptions;
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.ChopsticksProvider = void 0;
25
+ const eventemitter3_1 = require("eventemitter3");
26
+ const rpc_1 = require("./rpc");
27
+ const logger_1 = require("./logger");
28
+ const setup_1 = require("./setup");
29
+ const providerHandlers = Object.assign(Object.assign({}, rpc_1.allHandlers), { dev_newBlock: (context, _params, _subscriptionManager) => __awaiter(void 0, void 0, void 0, function* () {
30
+ const block = yield context.chain.newBlock();
31
+ return block.hash;
32
+ }) });
33
+ const logger = logger_1.defaultLogger.child({ name: '[Chopsticks provider]' });
34
+ /**
35
+ * Provider for local chopsticks chain
36
+ */
37
+ class ChopsticksProvider {
38
+ constructor(chain) {
39
+ this.chain = chain;
40
+ _ChopsticksProvider_isConnected.set(this, false);
41
+ _ChopsticksProvider_eventemitter.set(this, void 0);
42
+ _ChopsticksProvider_isReadyPromise.set(this, void 0);
43
+ _ChopsticksProvider_subscriptions.set(this, {});
44
+ this.clone = () => {
45
+ return new ChopsticksProvider(this.chain);
46
+ };
47
+ this.connect = () => __awaiter(this, void 0, void 0, function* () {
48
+ __classPrivateFieldSet(this, _ChopsticksProvider_isConnected, true, "f");
49
+ __classPrivateFieldGet(this, _ChopsticksProvider_eventemitter, "f").emit('connected');
50
+ });
51
+ this.disconnect = () => __awaiter(this, void 0, void 0, function* () {
52
+ __classPrivateFieldSet(this, _ChopsticksProvider_isConnected, false, "f");
53
+ __classPrivateFieldGet(this, _ChopsticksProvider_eventemitter, "f").emit('disconnected');
54
+ });
55
+ this.on = (type, sub) => {
56
+ __classPrivateFieldGet(this, _ChopsticksProvider_eventemitter, "f").on(type, sub);
57
+ return () => {
58
+ __classPrivateFieldGet(this, _ChopsticksProvider_eventemitter, "f").removeListener(type, sub);
59
+ };
60
+ };
61
+ this.subscriptionManager = {
62
+ subscribe: (method, subid, onCancel = () => { }) => {
63
+ const sub = __classPrivateFieldGet(this, _ChopsticksProvider_subscriptions, "f")[subid];
64
+ if (sub) {
65
+ sub.onCancel = onCancel;
66
+ }
67
+ return (data) => {
68
+ logger.debug('subscribe-callback', method, subid, data);
69
+ const sub = __classPrivateFieldGet(this, _ChopsticksProvider_subscriptions, "f")[subid];
70
+ if (sub) {
71
+ sub.callback(null, data);
72
+ }
73
+ else {
74
+ logger.trace(`Unable to find active subscription=${subid}`);
75
+ }
76
+ };
77
+ },
78
+ unsubscribe: (subid) => {
79
+ var _b;
80
+ logger.debug('unsubscribe-callback', subid);
81
+ const sub = __classPrivateFieldGet(this, _ChopsticksProvider_subscriptions, "f")[subid];
82
+ if (sub) {
83
+ (_b = sub.onCancel) === null || _b === void 0 ? void 0 : _b.call(sub);
84
+ delete __classPrivateFieldGet(this, _ChopsticksProvider_subscriptions, "f")[subid];
85
+ }
86
+ else {
87
+ logger.trace(`Unable to find active subscription=${subid}`);
88
+ }
89
+ },
90
+ };
91
+ this.send = (method, params, _isCacheable, subscription) => __awaiter(this, void 0, void 0, function* () {
92
+ try {
93
+ logger.debug('send', { method, params });
94
+ const rpcHandler = providerHandlers[method];
95
+ if (!rpcHandler) {
96
+ logger.error(`Unable to find rpc handler=${method}`);
97
+ throw new Error(`Unable to find rpc handler=${method}`);
98
+ }
99
+ if (subscription) {
100
+ logger.debug('subscribe', { method, params });
101
+ const subid = yield rpcHandler({ chain: this.chain }, params, this.subscriptionManager);
102
+ if (!subid) {
103
+ throw new Error(`Unable to subscribe=${method}`);
104
+ }
105
+ __classPrivateFieldGet(this, _ChopsticksProvider_subscriptions, "f")[subid] = {
106
+ callback: subscription.callback,
107
+ method,
108
+ params,
109
+ type: subscription.type,
110
+ };
111
+ return subid;
112
+ }
113
+ else {
114
+ logger.debug('call', { method, params });
115
+ return rpcHandler({ chain: this.chain }, params, this.subscriptionManager);
116
+ }
117
+ }
118
+ catch (e) {
119
+ logger.error('send error.', e);
120
+ throw e;
121
+ }
122
+ });
123
+ __classPrivateFieldSet(this, _ChopsticksProvider_eventemitter, new eventemitter3_1.EventEmitter(), "f");
124
+ __classPrivateFieldSet(this, _ChopsticksProvider_isReadyPromise, new Promise((resolve, reject) => {
125
+ __classPrivateFieldGet(this, _ChopsticksProvider_eventemitter, "f").once('connected', resolve);
126
+ __classPrivateFieldGet(this, _ChopsticksProvider_eventemitter, "f").once('error', reject);
127
+ this.connect();
128
+ }), "f");
129
+ }
130
+ get hasSubscriptions() {
131
+ return true;
132
+ }
133
+ get isClonable() {
134
+ return true;
135
+ }
136
+ get isConnected() {
137
+ return __classPrivateFieldGet(this, _ChopsticksProvider_isConnected, "f");
138
+ }
139
+ get isReady() {
140
+ return __classPrivateFieldGet(this, _ChopsticksProvider_isReadyPromise, "f");
141
+ }
142
+ subscribe(type, method, params, callback) {
143
+ return this.send(method, params, false, { callback, type });
144
+ }
145
+ unsubscribe(_type, method, id) {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ if (!__classPrivateFieldGet(this, _ChopsticksProvider_subscriptions, "f")[id]) {
148
+ logger.trace(`Unable to find active subscription=${id}`);
149
+ return false;
150
+ }
151
+ try {
152
+ return this.send(method, [id]);
153
+ }
154
+ catch (_b) {
155
+ return false;
156
+ }
157
+ });
158
+ }
159
+ }
160
+ exports.ChopsticksProvider = ChopsticksProvider;
161
+ _a = ChopsticksProvider, _ChopsticksProvider_isConnected = new WeakMap(), _ChopsticksProvider_eventemitter = new WeakMap(), _ChopsticksProvider_isReadyPromise = new WeakMap(), _ChopsticksProvider_subscriptions = new WeakMap();
162
+ ChopsticksProvider.fromEndpoint = (endpoint, block, cache) => __awaiter(void 0, void 0, void 0, function* () {
163
+ return new ChopsticksProvider(yield (0, setup_1.setup)({
164
+ endpoint,
165
+ mockSignatureHost: true,
166
+ block,
167
+ db: cache,
168
+ }));
169
+ });
package/lib/index.d.ts CHANGED
@@ -22,4 +22,5 @@ export * from './setup';
22
22
  export * from './blockchain/inherent';
23
23
  export * from './logger';
24
24
  export * from './offchain';
25
+ export * from './chopsticks-provider';
25
26
  export * from './rpc';
package/lib/index.js CHANGED
@@ -38,5 +38,5 @@ __exportStar(require("./setup"), exports);
38
38
  __exportStar(require("./blockchain/inherent"), exports);
39
39
  __exportStar(require("./logger"), exports);
40
40
  __exportStar(require("./offchain"), exports);
41
- // export * from './chopsticks-provider'
41
+ __exportStar(require("./chopsticks-provider"), exports);
42
42
  __exportStar(require("./rpc"), exports);
@@ -66,9 +66,12 @@ const author_submitAndWatchExtrinsic = (context, [extrinsic], { subscribe, unsub
66
66
  });
67
67
  try {
68
68
  yield context.chain.submitExtrinsic(extrinsic);
69
- callback({
70
- ready: null,
71
- });
69
+ // send callback after subscription id is returned
70
+ setTimeout(() => {
71
+ callback({
72
+ ready: null,
73
+ });
74
+ }, 50);
72
75
  }
73
76
  catch (error) {
74
77
  logger.error({ error }, 'ExtrinsicFailed');
@@ -78,7 +78,7 @@ const chain_subscribeNewHead = (context, _params, { subscribe }) => __awaiter(vo
78
78
  update = () => __awaiter(void 0, void 0, void 0, function* () {
79
79
  callback(processHeader(yield context.chain.head.header));
80
80
  });
81
- update();
81
+ setTimeout(update, 50);
82
82
  return id;
83
83
  });
84
84
  exports.chain_subscribeNewHead = chain_subscribeNewHead;
@@ -89,7 +89,7 @@ const chain_subscribeFinalizedHeads = (context, _params, { subscribe }) => __awa
89
89
  update = () => __awaiter(void 0, void 0, void 0, function* () {
90
90
  callback(processHeader(yield context.chain.head.header));
91
91
  });
92
- update();
92
+ setTimeout(update, 50);
93
93
  return id;
94
94
  });
95
95
  exports.chain_subscribeFinalizedHeads = chain_subscribeFinalizedHeads;
@@ -24,20 +24,20 @@ declare const handlers: {
24
24
  }>;
25
25
  system_dryRun: import("..").Handler<[`0x${string}`, `0x${string}`], string>;
26
26
  system_accountNextIndex: import("..").Handler<[`0x${string}`], number>;
27
- state_getRuntimeVersion: import("..").Handler<[`0x${string}`], import("../..").RuntimeVersion | undefined>;
28
- state_getMetadata: import("..").Handler<[`0x${string}`], `0x${string}` | undefined>;
29
- state_getStorage: import("..").Handler<[`0x${string}`, `0x${string}`], string | undefined>;
27
+ state_getRuntimeVersion: import("..").Handler<[`0x${string}`], import("../..").RuntimeVersion | null>;
28
+ state_getMetadata: import("..").Handler<[`0x${string}`], `0x${string}` | null>;
29
+ state_getStorage: import("..").Handler<[`0x${string}`, `0x${string}`], string | null>;
30
30
  state_getKeysPaged: import("..").Handler<[string, number, string, `0x${string}`], string[] | undefined>;
31
31
  state_queryStorageAt: import("..").Handler<[string[], `0x${string}`], [] | [{
32
32
  block: `0x${string}`;
33
- changes: (string | undefined)[][];
33
+ changes: [string, string | null][];
34
34
  }]>;
35
35
  state_call: import("..").Handler<[`0x${string}`, `0x${string}`, `0x${string}`], `0x${string}`>;
36
36
  state_subscribeRuntimeVersion: import("..").Handler<[], string>;
37
37
  state_unsubscribeRuntimeVersion: import("..").Handler<[`0x${string}`], void>;
38
38
  state_subscribeStorage: import("..").Handler<[string[]], string>;
39
39
  state_unsubscribeStorage: import("..").Handler<[string], void>;
40
- childstate_getStorage: import("..").Handler<[`0x${string}`, `0x${string}`, `0x${string}`], string | undefined>;
40
+ childstate_getStorage: import("..").Handler<[`0x${string}`, `0x${string}`, `0x${string}`], string | null>;
41
41
  childstate_getKeysPaged: import("..").Handler<[`0x${string}`, `0x${string}`, number, `0x${string}`, `0x${string}`], `0x${string}`[] | undefined>;
42
42
  payment_queryFeeDetails: import("..").Handler<[`0x${string}`, `0x${string}`], `0x${string}`>;
43
43
  payment_queryInfo: import("..").Handler<[`0x${string}`, `0x${string}`], `0x${string}`>;
@@ -7,21 +7,21 @@ import { RuntimeVersion } from '../../wasm-executor';
7
7
  *
8
8
  * @return runtime version
9
9
  */
10
- export declare const state_getRuntimeVersion: Handler<[HexString], RuntimeVersion | undefined>;
10
+ export declare const state_getRuntimeVersion: Handler<[HexString], RuntimeVersion | null>;
11
11
  /**
12
12
  * @param context
13
13
  * @param params - [`blockhash`]
14
14
  *
15
15
  * @return metadata
16
16
  */
17
- export declare const state_getMetadata: Handler<[HexString], HexString | undefined>;
17
+ export declare const state_getMetadata: Handler<[HexString], HexString | null>;
18
18
  /**
19
19
  * @param context
20
20
  * @param params - [`key`, `blockhash`]
21
21
  *
22
22
  * @return storage value
23
23
  */
24
- export declare const state_getStorage: Handler<[HexString, HexString], string | undefined>;
24
+ export declare const state_getStorage: Handler<[HexString, HexString], string | null>;
25
25
  /**
26
26
  * @param context
27
27
  * @param params - [`prefix`, `pageSize`, `startKey`, `blockhash`]
@@ -41,7 +41,7 @@ export declare const state_queryStorageAt: Handler<[
41
41
  ], [] | [
42
42
  {
43
43
  block: HexString;
44
- changes: (string | undefined)[][];
44
+ changes: [string, string | null][];
45
45
  }
46
46
  ]>;
47
47
  /**
@@ -81,7 +81,7 @@ export declare const state_unsubscribeStorage: Handler<[string], void>;
81
81
  *
82
82
  * @return storage valuse
83
83
  */
84
- export declare const childstate_getStorage: Handler<[HexString, HexString, HexString], string | undefined>;
84
+ export declare const childstate_getStorage: Handler<[HexString, HexString, HexString], string | null>;
85
85
  /**
86
86
  * @param context
87
87
  * @param params - [`child`, `prefix`, `pageSize`, `startKey`, `blockhash`]
@@ -22,7 +22,7 @@ const logger = logger_1.defaultLogger.child({ name: 'rpc-state' });
22
22
  */
23
23
  const state_getRuntimeVersion = (context, [hash]) => __awaiter(void 0, void 0, void 0, function* () {
24
24
  const block = yield context.chain.getBlock(hash);
25
- return block === null || block === void 0 ? void 0 : block.runtimeVersion;
25
+ return (block === null || block === void 0 ? void 0 : block.runtimeVersion) || null;
26
26
  });
27
27
  exports.state_getRuntimeVersion = state_getRuntimeVersion;
28
28
  /**
@@ -33,7 +33,7 @@ exports.state_getRuntimeVersion = state_getRuntimeVersion;
33
33
  */
34
34
  const state_getMetadata = (context, [hash]) => __awaiter(void 0, void 0, void 0, function* () {
35
35
  const block = yield context.chain.getBlock(hash);
36
- return block === null || block === void 0 ? void 0 : block.metadata;
36
+ return (block === null || block === void 0 ? void 0 : block.metadata) || null;
37
37
  });
38
38
  exports.state_getMetadata = state_getMetadata;
39
39
  /**
@@ -44,7 +44,8 @@ exports.state_getMetadata = state_getMetadata;
44
44
  */
45
45
  const state_getStorage = (context, [key, hash]) => __awaiter(void 0, void 0, void 0, function* () {
46
46
  const block = yield context.chain.getBlock(hash);
47
- return block === null || block === void 0 ? void 0 : block.get(key);
47
+ const value = (yield (block === null || block === void 0 ? void 0 : block.get(key))) || null;
48
+ return value || null;
48
49
  });
49
50
  exports.state_getStorage = state_getStorage;
50
51
  /**
@@ -69,7 +70,7 @@ const state_queryStorageAt = (context, [keys, hash]) => __awaiter(void 0, void 0
69
70
  if (!block) {
70
71
  return [];
71
72
  }
72
- const values = yield Promise.all(keys.map((key) => __awaiter(void 0, void 0, void 0, function* () { return [key, yield block.get(key)]; })));
73
+ const values = yield Promise.all(keys.map((key) => __awaiter(void 0, void 0, void 0, function* () { return [key, yield block.get(key).then((val) => val || null)]; })));
73
74
  return [
74
75
  {
75
76
  block: block.hash,
@@ -101,7 +102,9 @@ const state_subscribeRuntimeVersion = (context, _params, { subscribe }) => __awa
101
102
  const id = yield context.chain.headState.subscrubeRuntimeVersion((block) => update(block));
102
103
  const callback = subscribe('state_runtimeVersion', id);
103
104
  update = (block) => __awaiter(void 0, void 0, void 0, function* () { return callback(yield block.runtimeVersion); });
104
- context.chain.head.runtimeVersion.then(callback);
105
+ setTimeout(() => {
106
+ context.chain.head.runtimeVersion.then(callback);
107
+ }, 50);
105
108
  return id;
106
109
  });
107
110
  exports.state_subscribeRuntimeVersion = state_subscribeRuntimeVersion;
@@ -135,7 +138,7 @@ const state_subscribeStorage = (context, [keys], { subscribe }) => __awaiter(voi
135
138
  (() => __awaiter(void 0, void 0, void 0, function* () {
136
139
  const pairs = yield Promise.all(keys.map((key) => __awaiter(void 0, void 0, void 0, function* () {
137
140
  const val = yield context.chain.head.get(key);
138
- return [key, val];
141
+ return [key, val || null];
139
142
  })));
140
143
  callback({
141
144
  block: context.chain.head.hash,
@@ -165,7 +168,8 @@ const childstate_getStorage = (context, [child, key, hash]) => __awaiter(void 0,
165
168
  throw new shared_1.ResponseError(-32000, 'Client error: Invalid child storage key');
166
169
  }
167
170
  const block = yield context.chain.getBlock(hash);
168
- return block === null || block === void 0 ? void 0 : block.get((0, utils_1.prefixedChildKey)(child, key));
171
+ const value = yield (block === null || block === void 0 ? void 0 : block.get((0, utils_1.prefixedChildKey)(child, key)));
172
+ return value || null;
169
173
  });
170
174
  exports.childstate_getStorage = childstate_getStorage;
171
175
  /**
@@ -30,7 +30,7 @@ export interface WasmExecutor {
30
30
  runtimeLogLevel: number;
31
31
  }, callback?: JsCallback) => Promise<any>;
32
32
  }
33
- export declare const getRuntimeVersion: (code: HexString) => Promise<RuntimeVersion>;
33
+ export declare const getRuntimeVersion: ((code: HexString) => Promise<RuntimeVersion>) & _.MemoizedFunction;
34
34
  export declare const calculateStateRoot: (entries: [HexString, HexString][], trie_version: number) => Promise<HexString>;
35
35
  export declare const decodeProof: (trieRootHash: HexString, keys: HexString[], nodes: HexString[]) => Promise<Record<`0x${string}`, `0x${string}` | null>>;
36
36
  export declare const createProof: (nodes: HexString[], entries: [HexString, HexString | null][]) => Promise<{
@@ -56,15 +56,14 @@ const getWorker = () => __awaiter(void 0, void 0, void 0, function* () {
56
56
  }
57
57
  return __executor_worker;
58
58
  });
59
- const getRuntimeVersion = (code) => __awaiter(void 0, void 0, void 0, function* () {
59
+ exports.getRuntimeVersion = lodash_1.default.memoize((code) => __awaiter(void 0, void 0, void 0, function* () {
60
60
  const worker = yield getWorker();
61
61
  return worker.remote.getRuntimeVersion(code).then((version) => {
62
62
  version.specName = (0, util_1.hexToString)(version.specName);
63
63
  version.implName = (0, util_1.hexToString)(version.implName);
64
64
  return version;
65
65
  });
66
- });
67
- exports.getRuntimeVersion = getRuntimeVersion;
66
+ }));
68
67
  // trie_version: 0 for old trie, 1 for new trie
69
68
  const calculateStateRoot = (entries, trie_version) => __awaiter(void 0, void 0, void 0, function* () {
70
69
  const worker = yield getWorker();
@@ -29,6 +29,6 @@ const runTask = async (task, callback) => {
29
29
  return pkg.run_task(task, callback, process.env.RUST_LOG)
30
30
  }
31
31
 
32
- export const wasmExecutor = { runTask, getRuntimeVersion, calculateStateRoot, createProof, decodeProof }
32
+ const wasmExecutor = { runTask, getRuntimeVersion, calculateStateRoot, createProof, decodeProof }
33
33
 
34
34
  Comlink.expose(wasmExecutor, nodeEndpoint(parentPort))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acala-network/chopsticks-core",
3
- "version": "0.8.4",
3
+ "version": "0.8.5-0",
4
4
  "author": "Acala Developers <hello@acala.network>",
5
5
  "license": "Apache-2.0",
6
6
  "scripts": {
@@ -11,7 +11,7 @@
11
11
  "docs:prep": "typedoc"
12
12
  },
13
13
  "dependencies": {
14
- "@acala-network/chopsticks-executor": "0.8.4",
14
+ "@acala-network/chopsticks-executor": "0.8.5-0",
15
15
  "@polkadot/api": "^10.9.1",
16
16
  "@polkadot/util-crypto": "^12.3.2",
17
17
  "axios": "^1.5.1",
@@ -47,5 +47,9 @@
47
47
  "default": "./lib/*.js"
48
48
  },
49
49
  "./package.json": "./package.json"
50
+ },
51
+ "browser": {
52
+ "./lib/wasm-executor/node-wasm-executor.mjs": "./lib/wasm-executor/browser-wasm-executor.mjs",
53
+ "./lib/wasm-executor/node-worker.js": "./lib/wasm-executor/browser-worker.js"
50
54
  }
51
55
  }
@@ -1 +0,0 @@
1
- export {};
@@ -1,101 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const rpc_1 = require("./rpc");
13
- const logger_1 = require("./logger");
14
- const utils_1 = require("./utils");
15
- const setup_1 = require("./setup");
16
- let chain;
17
- const logger = logger_1.defaultLogger.child({ name: '[Chopsticks worker]' });
18
- const subscriptions = {};
19
- const providerHandlers = Object.assign(Object.assign({}, rpc_1.allHandlers), { new_block: (context, _params, _subscriptionManager) => __awaiter(void 0, void 0, void 0, function* () {
20
- const { chain } = context;
21
- const block = yield chain.newBlock();
22
- return block;
23
- }) });
24
- const subscriptionManager = {
25
- subscribe: (method, subid, onCancel = () => { }) => {
26
- subscriptions[subid] = onCancel;
27
- return (data) => {
28
- postMessage({
29
- type: 'subscribe-callback',
30
- method,
31
- subid,
32
- result: JSON.stringify(data),
33
- });
34
- };
35
- },
36
- unsubscribe: (subid) => {
37
- if (subscriptions[subid]) {
38
- subscriptions[subid](subid); // call onCancel
39
- postMessage({
40
- type: 'unsubscribe-callback',
41
- subid,
42
- });
43
- }
44
- },
45
- };
46
- onmessage = (e) => __awaiter(void 0, void 0, void 0, function* () {
47
- var _a;
48
- switch (e.data.type) {
49
- case 'connect':
50
- try {
51
- logger.debug('onMessage: connect. Initializing...');
52
- chain = yield (0, setup_1.setup)({
53
- endpoint: e.data.endpoint,
54
- mockSignatureHost: true,
55
- db: e.data.dbPath,
56
- block: e.data.blockHash,
57
- });
58
- logger.debug('onMessage: connect. Chain setup done.');
59
- yield (0, utils_1.setStorage)(chain, e.data.storageValues);
60
- logger.debug('onMessage: connect. Set storage done.');
61
- postMessage({
62
- type: 'connection',
63
- connected: true,
64
- });
65
- }
66
- catch (e) {
67
- logger.error('onMessage: connect error.', e);
68
- postMessage({
69
- type: 'connection',
70
- connected: false,
71
- message: e,
72
- });
73
- }
74
- break;
75
- case 'disconnect':
76
- if (chain) {
77
- yield ((_a = chain === null || chain === void 0 ? void 0 : chain.api) === null || _a === void 0 ? void 0 : _a.disconnect());
78
- yield (chain === null || chain === void 0 ? void 0 : chain.close());
79
- }
80
- break;
81
- case 'send':
82
- {
83
- const { method, params } = e.data;
84
- const handler = providerHandlers[method];
85
- if (!handler) {
86
- logger.error(`Unable to find rpc handler=${method}`);
87
- return Promise.reject(new Error(`Unable to find handler=${method}`));
88
- }
89
- const result = yield handler({ chain: chain }, params, subscriptionManager);
90
- postMessage({
91
- type: 'send-result',
92
- id: e.data.id,
93
- method: method,
94
- result: JSON.stringify(result),
95
- });
96
- }
97
- break;
98
- default:
99
- break;
100
- }
101
- });