@pezkuwi/rpc-provider 16.5.8 → 16.5.9

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