@pezkuwi/rpc-provider 16.5.5 → 16.5.6

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 (125) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +10 -10
  3. package/bizinikiwi-connect/Health.js +259 -0
  4. package/{build/substrate-connect → bizinikiwi-connect}/index.d.ts +3 -3
  5. package/bizinikiwi-connect/index.js +319 -0
  6. package/{build/bundle.d.ts → bundle.d.ts} +1 -1
  7. package/{src/bundle.ts → bundle.js} +1 -4
  8. package/cjs/bizinikiwi-connect/Health.d.ts +7 -0
  9. package/cjs/bizinikiwi-connect/Health.js +264 -0
  10. package/cjs/bizinikiwi-connect/index.d.ts +22 -0
  11. package/cjs/bizinikiwi-connect/index.js +323 -0
  12. package/cjs/bizinikiwi-connect/types.d.ts +12 -0
  13. package/cjs/bizinikiwi-connect/types.js +2 -0
  14. package/cjs/bundle.d.ts +5 -0
  15. package/cjs/bundle.js +14 -0
  16. package/cjs/coder/error.js +53 -0
  17. package/cjs/coder/index.js +63 -0
  18. package/cjs/defaults.js +8 -0
  19. package/{build → cjs}/http/index.d.ts +1 -1
  20. package/cjs/http/index.js +196 -0
  21. package/cjs/http/types.js +2 -0
  22. package/cjs/index.js +5 -0
  23. package/cjs/lru.js +150 -0
  24. package/cjs/mock/index.js +196 -0
  25. package/cjs/mock/mockHttp.js +17 -0
  26. package/cjs/mock/mockWs.js +47 -0
  27. package/cjs/mock/types.js +2 -0
  28. package/cjs/package.json +3 -0
  29. package/cjs/packageDetect.d.ts +1 -0
  30. package/cjs/packageDetect.js +6 -0
  31. package/cjs/packageInfo.js +4 -0
  32. package/cjs/types.js +2 -0
  33. package/cjs/ws/errors.js +41 -0
  34. package/{build → cjs}/ws/index.d.ts +1 -1
  35. package/cjs/ws/index.js +529 -0
  36. package/coder/error.d.ts +29 -0
  37. package/coder/error.js +50 -0
  38. package/coder/index.d.ts +8 -0
  39. package/coder/index.js +58 -0
  40. package/defaults.d.ts +5 -0
  41. package/defaults.js +6 -0
  42. package/http/index.d.ts +81 -0
  43. package/http/index.js +191 -0
  44. package/http/types.d.ts +7 -0
  45. package/http/types.js +1 -0
  46. package/index.d.ts +2 -0
  47. package/index.js +2 -0
  48. package/lru.d.ts +15 -0
  49. package/lru.js +146 -0
  50. package/mock/index.d.ts +35 -0
  51. package/mock/index.js +191 -0
  52. package/mock/mockHttp.d.ts +9 -0
  53. package/mock/mockHttp.js +12 -0
  54. package/mock/mockWs.d.ts +26 -0
  55. package/mock/mockWs.js +43 -0
  56. package/mock/types.d.ts +23 -0
  57. package/mock/types.js +1 -0
  58. package/package.json +316 -15
  59. package/packageDetect.d.ts +1 -0
  60. package/packageDetect.js +4 -0
  61. package/packageInfo.d.ts +6 -0
  62. package/packageInfo.js +1 -0
  63. package/types.d.ts +85 -0
  64. package/types.js +1 -0
  65. package/ws/errors.d.ts +1 -0
  66. package/ws/errors.js +38 -0
  67. package/ws/index.d.ts +121 -0
  68. package/ws/index.js +524 -0
  69. package/src/coder/decodeResponse.spec.ts +0 -70
  70. package/src/coder/encodeJson.spec.ts +0 -20
  71. package/src/coder/encodeObject.spec.ts +0 -25
  72. package/src/coder/error.spec.ts +0 -111
  73. package/src/coder/error.ts +0 -66
  74. package/src/coder/index.ts +0 -88
  75. package/src/defaults.ts +0 -10
  76. package/src/http/index.spec.ts +0 -72
  77. package/src/http/index.ts +0 -238
  78. package/src/http/send.spec.ts +0 -61
  79. package/src/http/types.ts +0 -11
  80. package/src/index.ts +0 -6
  81. package/src/lru.spec.ts +0 -74
  82. package/src/lru.ts +0 -197
  83. package/src/mock/index.ts +0 -259
  84. package/src/mock/mockHttp.ts +0 -35
  85. package/src/mock/mockWs.ts +0 -92
  86. package/src/mock/on.spec.ts +0 -43
  87. package/src/mock/send.spec.ts +0 -38
  88. package/src/mock/subscribe.spec.ts +0 -81
  89. package/src/mock/types.ts +0 -36
  90. package/src/mock/unsubscribe.spec.ts +0 -57
  91. package/src/mod.ts +0 -4
  92. package/src/packageDetect.ts +0 -12
  93. package/src/packageInfo.ts +0 -6
  94. package/src/substrate-connect/Health.ts +0 -325
  95. package/src/substrate-connect/index.spec.ts +0 -638
  96. package/src/substrate-connect/index.ts +0 -415
  97. package/src/substrate-connect/types.ts +0 -16
  98. package/src/types.ts +0 -101
  99. package/src/ws/connect.spec.ts +0 -167
  100. package/src/ws/errors.ts +0 -41
  101. package/src/ws/index.spec.ts +0 -97
  102. package/src/ws/index.ts +0 -652
  103. package/src/ws/send.spec.ts +0 -126
  104. package/src/ws/state.spec.ts +0 -20
  105. package/src/ws/subscribe.spec.ts +0 -68
  106. package/src/ws/unsubscribe.spec.ts +0 -100
  107. package/tsconfig.build.json +0 -17
  108. package/tsconfig.build.tsbuildinfo +0 -1
  109. package/tsconfig.spec.json +0 -18
  110. /package/{build/substrate-connect → bizinikiwi-connect}/Health.d.ts +0 -0
  111. /package/{build/substrate-connect → bizinikiwi-connect}/types.d.ts +0 -0
  112. /package/{build/packageDetect.d.ts → bizinikiwi-connect/types.js} +0 -0
  113. /package/{build → cjs}/coder/error.d.ts +0 -0
  114. /package/{build → cjs}/coder/index.d.ts +0 -0
  115. /package/{build → cjs}/defaults.d.ts +0 -0
  116. /package/{build → cjs}/http/types.d.ts +0 -0
  117. /package/{build → cjs}/index.d.ts +0 -0
  118. /package/{build → cjs}/lru.d.ts +0 -0
  119. /package/{build → cjs}/mock/index.d.ts +0 -0
  120. /package/{build → cjs}/mock/mockHttp.d.ts +0 -0
  121. /package/{build → cjs}/mock/mockWs.d.ts +0 -0
  122. /package/{build → cjs}/mock/types.d.ts +0 -0
  123. /package/{build → cjs}/packageInfo.d.ts +0 -0
  124. /package/{build → cjs}/types.d.ts +0 -0
  125. /package/{build → cjs}/ws/errors.d.ts +0 -0
package/ws/index.d.ts ADDED
@@ -0,0 +1,121 @@
1
+ import type { EndpointStats, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types.js';
2
+ interface SubscriptionHandler {
3
+ callback: ProviderInterfaceCallback;
4
+ type: string;
5
+ }
6
+ /**
7
+ * # @pezkuwi/rpc-provider/ws
8
+ *
9
+ * @name WsProvider
10
+ *
11
+ * @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes.
12
+ *
13
+ * @example
14
+ * <BR>
15
+ *
16
+ * ```javascript
17
+ * import Api from '@pezkuwi/api/promise';
18
+ * import { WsProvider } from '@pezkuwi/rpc-provider/ws';
19
+ *
20
+ * const provider = new WsProvider('ws://127.0.0.1:9944');
21
+ * const api = new Api(provider);
22
+ * ```
23
+ *
24
+ * @see [[HttpProvider]]
25
+ */
26
+ export declare class WsProvider implements ProviderInterface {
27
+ #private;
28
+ /**
29
+ * @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
30
+ * @param {number | false} autoConnectMs Whether to connect automatically or not (default). Provided value is used as a delay between retries.
31
+ * @param {Record<string, string>} headers The headers provided to the underlying WebSocket
32
+ * @param {number} [timeout] Custom timeout value used per request . Defaults to `DEFAULT_TIMEOUT_MS`
33
+ * @param {number} [cacheCapacity] Custom size of the WsProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
34
+ * @param {number} [cacheTtl] Custom TTL of the WsProvider LRUCache. Determines how long an object can live in the cache. Defaults to DEFAULT_TTL` (30000)
35
+ */
36
+ constructor(endpoint?: string | string[], autoConnectMs?: number | false, headers?: Record<string, string>, timeout?: number, cacheCapacity?: number, cacheTtl?: number | null);
37
+ /**
38
+ * @summary `true` when this provider supports subscriptions
39
+ */
40
+ get hasSubscriptions(): boolean;
41
+ /**
42
+ * @summary `true` when this provider supports clone()
43
+ */
44
+ get isClonable(): boolean;
45
+ /**
46
+ * @summary Whether the node is connected or not.
47
+ * @return {boolean} true if connected
48
+ */
49
+ get isConnected(): boolean;
50
+ /**
51
+ * @description Promise that resolves the first time we are connected and loaded
52
+ */
53
+ get isReady(): Promise<WsProvider>;
54
+ get endpoint(): string;
55
+ /**
56
+ * @description Returns a clone of the object
57
+ */
58
+ clone(): WsProvider;
59
+ protected selectEndpointIndex(endpoints: string[]): number;
60
+ /**
61
+ * @summary Manually connect
62
+ * @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may
63
+ * connect manually using this method.
64
+ */
65
+ connect(): Promise<void>;
66
+ /**
67
+ * @description Connect, never throwing an error, but rather forcing a retry
68
+ */
69
+ connectWithRetry(): Promise<void>;
70
+ /**
71
+ * @description Manually disconnect from the connection, clearing auto-connect logic
72
+ */
73
+ disconnect(): Promise<void>;
74
+ /**
75
+ * @description Returns the connection stats
76
+ */
77
+ get stats(): ProviderStats;
78
+ /**
79
+ * @description Returns the connection stats
80
+ */
81
+ get ttl(): number | null | undefined;
82
+ get endpointStats(): EndpointStats;
83
+ /**
84
+ * @summary Listens on events after having subscribed using the [[subscribe]] function.
85
+ * @param {ProviderInterfaceEmitted} type Event
86
+ * @param {ProviderInterfaceEmitCb} sub Callback
87
+ * @return unsubscribe function
88
+ */
89
+ on(type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
90
+ /**
91
+ * @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue.
92
+ * @param method The RPC methods to execute
93
+ * @param params Encoded parameters as applicable for the method
94
+ * @param subscription Subscription details (internally used)
95
+ */
96
+ send<T = any>(method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise<T>;
97
+ /**
98
+ * @name subscribe
99
+ * @summary Allows subscribing to a specific event.
100
+ *
101
+ * @example
102
+ * <BR>
103
+ *
104
+ * ```javascript
105
+ * const provider = new WsProvider('ws://127.0.0.1:9944');
106
+ * const rpc = new Rpc(provider);
107
+ *
108
+ * rpc.state.subscribeStorage([[storage.system.account, <Address>]], (_, values) => {
109
+ * console.log(values)
110
+ * }).then((subscriptionId) => {
111
+ * console.log('balance changes subscription id: ', subscriptionId)
112
+ * })
113
+ * ```
114
+ */
115
+ subscribe(type: string, method: string, params: unknown[], callback: ProviderInterfaceCallback): Promise<number | string>;
116
+ /**
117
+ * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
118
+ */
119
+ unsubscribe(type: string, method: string, id: number | string): Promise<boolean>;
120
+ }
121
+ export {};
package/ws/index.js ADDED
@@ -0,0 +1,524 @@
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { isChildClass, isNull, isUndefined, logger, noop, objectSpread, stringify } from '@pezkuwi/util';
3
+ import { xglobal } from '@pezkuwi/x-global';
4
+ import { WebSocket } from '@pezkuwi/x-ws';
5
+ import { RpcCoder } from '../coder/index.js';
6
+ import defaults from '../defaults.js';
7
+ import { DEFAULT_CAPACITY, DEFAULT_TTL, LRUCache } from '../lru.js';
8
+ import { getWSErrorString } from './errors.js';
9
+ const ALIASES = {
10
+ chain_finalisedHead: 'chain_finalizedHead',
11
+ chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
12
+ chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
13
+ };
14
+ const RETRY_DELAY = 2_500;
15
+ const DEFAULT_TIMEOUT_MS = 60 * 1000;
16
+ const TIMEOUT_INTERVAL = 5_000;
17
+ const l = logger('api-ws');
18
+ /** @internal Clears a Record<*> of all keys, optionally with all callback on clear */
19
+ function eraseRecord(record, cb) {
20
+ Object.keys(record).forEach((key) => {
21
+ if (cb) {
22
+ cb(record[key]);
23
+ }
24
+ delete record[key];
25
+ });
26
+ }
27
+ /** @internal Creates a default/empty stats object */
28
+ function defaultEndpointStats() {
29
+ return { bytesRecv: 0, bytesSent: 0, cached: 0, errors: 0, requests: 0, subscriptions: 0, timeout: 0 };
30
+ }
31
+ /**
32
+ * # @pezkuwi/rpc-provider/ws
33
+ *
34
+ * @name WsProvider
35
+ *
36
+ * @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes.
37
+ *
38
+ * @example
39
+ * <BR>
40
+ *
41
+ * ```javascript
42
+ * import Api from '@pezkuwi/api/promise';
43
+ * import { WsProvider } from '@pezkuwi/rpc-provider/ws';
44
+ *
45
+ * const provider = new WsProvider('ws://127.0.0.1:9944');
46
+ * const api = new Api(provider);
47
+ * ```
48
+ *
49
+ * @see [[HttpProvider]]
50
+ */
51
+ export class WsProvider {
52
+ #callCache;
53
+ #coder;
54
+ #endpoints;
55
+ #headers;
56
+ #eventemitter;
57
+ #handlers = {};
58
+ #isReadyPromise;
59
+ #stats;
60
+ #waitingForId = {};
61
+ #cacheCapacity;
62
+ #ttl;
63
+ #autoConnectMs;
64
+ #endpointIndex;
65
+ #endpointStats;
66
+ #isConnected = false;
67
+ #subscriptions = {};
68
+ #timeoutId = null;
69
+ #websocket;
70
+ #timeout;
71
+ /**
72
+ * @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
73
+ * @param {number | false} autoConnectMs Whether to connect automatically or not (default). Provided value is used as a delay between retries.
74
+ * @param {Record<string, string>} headers The headers provided to the underlying WebSocket
75
+ * @param {number} [timeout] Custom timeout value used per request . Defaults to `DEFAULT_TIMEOUT_MS`
76
+ * @param {number} [cacheCapacity] Custom size of the WsProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
77
+ * @param {number} [cacheTtl] Custom TTL of the WsProvider LRUCache. Determines how long an object can live in the cache. Defaults to DEFAULT_TTL` (30000)
78
+ */
79
+ constructor(endpoint = defaults.WS_URL, autoConnectMs = RETRY_DELAY, headers = {}, timeout, cacheCapacity, cacheTtl) {
80
+ const endpoints = Array.isArray(endpoint)
81
+ ? endpoint
82
+ : [endpoint];
83
+ if (endpoints.length === 0) {
84
+ throw new Error('WsProvider requires at least one Endpoint');
85
+ }
86
+ endpoints.forEach((endpoint) => {
87
+ if (!/^(wss|ws):\/\//.test(endpoint)) {
88
+ throw new Error(`Endpoint should start with 'ws://', received '${endpoint}'`);
89
+ }
90
+ });
91
+ const ttl = cacheTtl === undefined ? DEFAULT_TTL : cacheTtl;
92
+ this.#callCache = new LRUCache(cacheCapacity === 0 ? 0 : cacheCapacity || DEFAULT_CAPACITY, ttl);
93
+ this.#ttl = cacheTtl;
94
+ this.#cacheCapacity = cacheCapacity || DEFAULT_CAPACITY;
95
+ this.#eventemitter = new EventEmitter();
96
+ this.#autoConnectMs = autoConnectMs || 0;
97
+ this.#coder = new RpcCoder();
98
+ this.#endpointIndex = -1;
99
+ this.#endpoints = endpoints;
100
+ this.#headers = headers;
101
+ this.#websocket = null;
102
+ this.#stats = {
103
+ active: { requests: 0, subscriptions: 0 },
104
+ total: defaultEndpointStats()
105
+ };
106
+ this.#endpointStats = defaultEndpointStats();
107
+ this.#timeout = timeout || DEFAULT_TIMEOUT_MS;
108
+ if (autoConnectMs && autoConnectMs > 0) {
109
+ this.connectWithRetry().catch(noop);
110
+ }
111
+ this.#isReadyPromise = new Promise((resolve) => {
112
+ this.#eventemitter.once('connected', () => {
113
+ resolve(this);
114
+ });
115
+ });
116
+ }
117
+ /**
118
+ * @summary `true` when this provider supports subscriptions
119
+ */
120
+ get hasSubscriptions() {
121
+ return !!true;
122
+ }
123
+ /**
124
+ * @summary `true` when this provider supports clone()
125
+ */
126
+ get isClonable() {
127
+ return !!true;
128
+ }
129
+ /**
130
+ * @summary Whether the node is connected or not.
131
+ * @return {boolean} true if connected
132
+ */
133
+ get isConnected() {
134
+ return this.#isConnected;
135
+ }
136
+ /**
137
+ * @description Promise that resolves the first time we are connected and loaded
138
+ */
139
+ get isReady() {
140
+ return this.#isReadyPromise;
141
+ }
142
+ get endpoint() {
143
+ return this.#endpoints[this.#endpointIndex];
144
+ }
145
+ /**
146
+ * @description Returns a clone of the object
147
+ */
148
+ clone() {
149
+ return new WsProvider(this.#endpoints);
150
+ }
151
+ selectEndpointIndex(endpoints) {
152
+ return (this.#endpointIndex + 1) % endpoints.length;
153
+ }
154
+ /**
155
+ * @summary Manually connect
156
+ * @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may
157
+ * connect manually using this method.
158
+ */
159
+ // eslint-disable-next-line @typescript-eslint/require-await
160
+ async connect() {
161
+ if (this.#websocket) {
162
+ throw new Error('WebSocket is already connected');
163
+ }
164
+ try {
165
+ this.#endpointIndex = this.selectEndpointIndex(this.#endpoints);
166
+ // the as here is Deno-specific - not available on the globalThis
167
+ this.#websocket = typeof xglobal.WebSocket !== 'undefined' && isChildClass(xglobal.WebSocket, WebSocket)
168
+ ? new WebSocket(this.endpoint)
169
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
170
+ // @ts-ignore - WS may be an instance of ws, which supports options
171
+ : new WebSocket(this.endpoint, undefined, {
172
+ headers: this.#headers
173
+ });
174
+ if (this.#websocket) {
175
+ this.#websocket.onclose = this.#onSocketClose;
176
+ this.#websocket.onerror = this.#onSocketError;
177
+ this.#websocket.onmessage = this.#onSocketMessage;
178
+ this.#websocket.onopen = this.#onSocketOpen;
179
+ }
180
+ // timeout any handlers that have not had a response
181
+ this.#timeoutId = setInterval(() => this.#timeoutHandlers(), TIMEOUT_INTERVAL);
182
+ }
183
+ catch (error) {
184
+ l.error(error);
185
+ this.#emit('error', error);
186
+ throw error;
187
+ }
188
+ }
189
+ /**
190
+ * @description Connect, never throwing an error, but rather forcing a retry
191
+ */
192
+ async connectWithRetry() {
193
+ if (this.#autoConnectMs > 0) {
194
+ try {
195
+ await this.connect();
196
+ }
197
+ catch {
198
+ setTimeout(() => {
199
+ this.connectWithRetry().catch(noop);
200
+ }, this.#autoConnectMs);
201
+ }
202
+ }
203
+ }
204
+ /**
205
+ * @description Manually disconnect from the connection, clearing auto-connect logic
206
+ */
207
+ // eslint-disable-next-line @typescript-eslint/require-await
208
+ async disconnect() {
209
+ // switch off autoConnect, we are in manual mode now
210
+ this.#autoConnectMs = 0;
211
+ try {
212
+ if (this.#websocket) {
213
+ // 1000 - Normal closure; the connection successfully completed
214
+ this.#websocket.close(1000);
215
+ }
216
+ }
217
+ catch (error) {
218
+ l.error(error);
219
+ this.#emit('error', error);
220
+ throw error;
221
+ }
222
+ }
223
+ /**
224
+ * @description Returns the connection stats
225
+ */
226
+ get stats() {
227
+ return {
228
+ active: {
229
+ requests: Object.keys(this.#handlers).length,
230
+ subscriptions: Object.keys(this.#subscriptions).length
231
+ },
232
+ total: this.#stats.total
233
+ };
234
+ }
235
+ /**
236
+ * @description Returns the connection stats
237
+ */
238
+ get ttl() {
239
+ return this.#ttl;
240
+ }
241
+ get endpointStats() {
242
+ return this.#endpointStats;
243
+ }
244
+ /**
245
+ * @summary Listens on events after having subscribed using the [[subscribe]] function.
246
+ * @param {ProviderInterfaceEmitted} type Event
247
+ * @param {ProviderInterfaceEmitCb} sub Callback
248
+ * @return unsubscribe function
249
+ */
250
+ on(type, sub) {
251
+ this.#eventemitter.on(type, sub);
252
+ return () => {
253
+ this.#eventemitter.removeListener(type, sub);
254
+ };
255
+ }
256
+ /**
257
+ * @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue.
258
+ * @param method The RPC methods to execute
259
+ * @param params Encoded parameters as applicable for the method
260
+ * @param subscription Subscription details (internally used)
261
+ */
262
+ send(method, params, isCacheable, subscription) {
263
+ this.#endpointStats.requests++;
264
+ this.#stats.total.requests++;
265
+ const [id, body] = this.#coder.encodeJson(method, params);
266
+ if (this.#cacheCapacity === 0) {
267
+ return this.#send(id, body, method, params, subscription);
268
+ }
269
+ const cacheKey = isCacheable ? `${method}::${stringify(params)}` : '';
270
+ let resultPromise = isCacheable
271
+ ? this.#callCache.get(cacheKey)
272
+ : null;
273
+ if (!resultPromise) {
274
+ resultPromise = this.#send(id, body, method, params, subscription);
275
+ if (isCacheable) {
276
+ this.#callCache.set(cacheKey, resultPromise);
277
+ }
278
+ }
279
+ else {
280
+ this.#endpointStats.cached++;
281
+ this.#stats.total.cached++;
282
+ }
283
+ return resultPromise;
284
+ }
285
+ async #send(id, body, method, params, subscription) {
286
+ return new Promise((resolve, reject) => {
287
+ try {
288
+ if (!this.isConnected || this.#websocket === null) {
289
+ throw new Error('WebSocket is not connected');
290
+ }
291
+ const callback = (error, result) => {
292
+ error
293
+ ? reject(error)
294
+ : resolve(result);
295
+ };
296
+ l.debug(() => ['calling', method, body]);
297
+ this.#handlers[id] = {
298
+ callback,
299
+ method,
300
+ params,
301
+ start: Date.now(),
302
+ subscription
303
+ };
304
+ const bytesSent = body.length;
305
+ this.#endpointStats.bytesSent += bytesSent;
306
+ this.#stats.total.bytesSent += bytesSent;
307
+ this.#websocket.send(body);
308
+ }
309
+ catch (error) {
310
+ this.#endpointStats.errors++;
311
+ this.#stats.total.errors++;
312
+ const rpcError = error;
313
+ const failedRequest = `\nFailed WS Request: ${JSON.stringify({ method, params })}`;
314
+ // Provide WS Request alongside the error
315
+ rpcError.message = `${rpcError.message}${failedRequest}`;
316
+ reject(rpcError);
317
+ }
318
+ });
319
+ }
320
+ /**
321
+ * @name subscribe
322
+ * @summary Allows subscribing to a specific event.
323
+ *
324
+ * @example
325
+ * <BR>
326
+ *
327
+ * ```javascript
328
+ * const provider = new WsProvider('ws://127.0.0.1:9944');
329
+ * const rpc = new Rpc(provider);
330
+ *
331
+ * rpc.state.subscribeStorage([[storage.system.account, <Address>]], (_, values) => {
332
+ * console.log(values)
333
+ * }).then((subscriptionId) => {
334
+ * console.log('balance changes subscription id: ', subscriptionId)
335
+ * })
336
+ * ```
337
+ */
338
+ subscribe(type, method, params, callback) {
339
+ this.#endpointStats.subscriptions++;
340
+ this.#stats.total.subscriptions++;
341
+ // subscriptions are not cached, LRU applies to .at(<blockHash>) only
342
+ return this.send(method, params, false, { callback, type });
343
+ }
344
+ /**
345
+ * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
346
+ */
347
+ async unsubscribe(type, method, id) {
348
+ const subscription = `${type}::${id}`;
349
+ // FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
350
+ // the assigned id now does not match what the API user originally received. It has
351
+ // a slight complication in solving - since we cannot rely on the send id, but rather
352
+ // need to find the actual subscription id to map it
353
+ if (isUndefined(this.#subscriptions[subscription])) {
354
+ l.debug(() => `Unable to find active subscription=${subscription}`);
355
+ return false;
356
+ }
357
+ delete this.#subscriptions[subscription];
358
+ try {
359
+ return this.isConnected && !isNull(this.#websocket)
360
+ ? this.send(method, [id])
361
+ : true;
362
+ }
363
+ catch {
364
+ return false;
365
+ }
366
+ }
367
+ #emit = (type, ...args) => {
368
+ this.#eventemitter.emit(type, ...args);
369
+ };
370
+ #onSocketClose = (event) => {
371
+ const error = new Error(`disconnected from ${this.endpoint}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`);
372
+ if (this.#autoConnectMs > 0) {
373
+ l.error(error.message);
374
+ }
375
+ this.#isConnected = false;
376
+ if (this.#websocket) {
377
+ this.#websocket.onclose = null;
378
+ this.#websocket.onerror = null;
379
+ this.#websocket.onmessage = null;
380
+ this.#websocket.onopen = null;
381
+ this.#websocket = null;
382
+ }
383
+ if (this.#timeoutId) {
384
+ clearInterval(this.#timeoutId);
385
+ this.#timeoutId = null;
386
+ }
387
+ // reject all hanging requests
388
+ eraseRecord(this.#handlers, (h) => {
389
+ try {
390
+ h.callback(error, undefined);
391
+ }
392
+ catch (err) {
393
+ // does not throw
394
+ l.error(err);
395
+ }
396
+ });
397
+ eraseRecord(this.#waitingForId);
398
+ // Reset stats for active endpoint
399
+ this.#endpointStats = defaultEndpointStats();
400
+ this.#emit('disconnected');
401
+ if (this.#autoConnectMs > 0) {
402
+ setTimeout(() => {
403
+ this.connectWithRetry().catch(noop);
404
+ }, this.#autoConnectMs);
405
+ }
406
+ };
407
+ #onSocketError = (error) => {
408
+ l.debug(() => ['socket error', error]);
409
+ this.#emit('error', error);
410
+ };
411
+ #onSocketMessage = (message) => {
412
+ l.debug(() => ['received', message.data]);
413
+ const bytesRecv = message.data.length;
414
+ this.#endpointStats.bytesRecv += bytesRecv;
415
+ this.#stats.total.bytesRecv += bytesRecv;
416
+ const response = JSON.parse(message.data);
417
+ return isUndefined(response.method)
418
+ ? this.#onSocketMessageResult(response)
419
+ : this.#onSocketMessageSubscribe(response);
420
+ };
421
+ #onSocketMessageResult = (response) => {
422
+ const handler = this.#handlers[response.id];
423
+ if (!handler) {
424
+ l.debug(() => `Unable to find handler for id=${response.id}`);
425
+ return;
426
+ }
427
+ try {
428
+ const { method, params, subscription } = handler;
429
+ const result = this.#coder.decodeResponse(response);
430
+ // first send the result - in case of subs, we may have an update
431
+ // immediately if we have some queued results already
432
+ handler.callback(null, result);
433
+ if (subscription) {
434
+ const subId = `${subscription.type}::${result}`;
435
+ this.#subscriptions[subId] = objectSpread({}, subscription, {
436
+ method,
437
+ params
438
+ });
439
+ // if we have a result waiting for this subscription already
440
+ if (this.#waitingForId[subId]) {
441
+ this.#onSocketMessageSubscribe(this.#waitingForId[subId]);
442
+ }
443
+ }
444
+ }
445
+ catch (error) {
446
+ this.#endpointStats.errors++;
447
+ this.#stats.total.errors++;
448
+ handler.callback(error, undefined);
449
+ }
450
+ delete this.#handlers[response.id];
451
+ };
452
+ #onSocketMessageSubscribe = (response) => {
453
+ if (!response.method) {
454
+ throw new Error('No method found in JSONRPC response');
455
+ }
456
+ const method = ALIASES[response.method] || response.method;
457
+ const subId = `${method}::${response.params.subscription}`;
458
+ const handler = this.#subscriptions[subId];
459
+ if (!handler) {
460
+ // store the JSON, we could have out-of-order subid coming in
461
+ this.#waitingForId[subId] = response;
462
+ l.debug(() => `Unable to find handler for subscription=${subId}`);
463
+ return;
464
+ }
465
+ // housekeeping
466
+ delete this.#waitingForId[subId];
467
+ try {
468
+ const result = this.#coder.decodeResponse(response);
469
+ handler.callback(null, result);
470
+ }
471
+ catch (error) {
472
+ this.#endpointStats.errors++;
473
+ this.#stats.total.errors++;
474
+ handler.callback(error, undefined);
475
+ }
476
+ };
477
+ #onSocketOpen = () => {
478
+ if (this.#websocket === null) {
479
+ throw new Error('WebSocket cannot be null in onOpen');
480
+ }
481
+ l.debug(() => ['connected to', this.endpoint]);
482
+ this.#isConnected = true;
483
+ this.#resubscribe();
484
+ this.#emit('connected');
485
+ return true;
486
+ };
487
+ #resubscribe = () => {
488
+ const subscriptions = this.#subscriptions;
489
+ this.#subscriptions = {};
490
+ Promise.all(Object.keys(subscriptions).map(async (id) => {
491
+ const { callback, method, params, type } = subscriptions[id];
492
+ // only re-create subscriptions which are not in author (only area where
493
+ // transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic'
494
+ // are not included (and will not be re-broadcast)
495
+ if (type.startsWith('author_')) {
496
+ return;
497
+ }
498
+ try {
499
+ await this.subscribe(type, method, params, callback);
500
+ }
501
+ catch (error) {
502
+ l.error(error);
503
+ }
504
+ })).catch(l.error);
505
+ };
506
+ #timeoutHandlers = () => {
507
+ const now = Date.now();
508
+ const ids = Object.keys(this.#handlers);
509
+ for (let i = 0, count = ids.length; i < count; i++) {
510
+ const handler = this.#handlers[ids[i]];
511
+ if ((now - handler.start) > this.#timeout) {
512
+ try {
513
+ handler.callback(new Error(`No response received from RPC endpoint in ${this.#timeout / 1000}s`), undefined);
514
+ }
515
+ catch {
516
+ // ignore
517
+ }
518
+ this.#endpointStats.timeout++;
519
+ this.#stats.total.timeout++;
520
+ delete this.#handlers[ids[i]];
521
+ }
522
+ }
523
+ };
524
+ }