@pezkuwi/rpc-provider 16.5.16 → 16.5.18

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 (210) hide show
  1. package/build/LICENSE +201 -0
  2. package/build/README.md +68 -0
  3. package/build/bizinikiwi-connect/Health.js +259 -0
  4. package/build/bizinikiwi-connect/index.js +319 -0
  5. package/build/bundle.js +5 -0
  6. package/build/cjs/bizinikiwi-connect/Health.d.ts +7 -0
  7. package/build/cjs/bizinikiwi-connect/Health.js +264 -0
  8. package/build/cjs/bizinikiwi-connect/index.d.ts +22 -0
  9. package/build/cjs/bizinikiwi-connect/index.js +323 -0
  10. package/build/cjs/bizinikiwi-connect/types.d.ts +12 -0
  11. package/build/cjs/bizinikiwi-connect/types.js +2 -0
  12. package/build/cjs/bundle.d.ts +5 -0
  13. package/build/cjs/bundle.js +14 -0
  14. package/build/cjs/coder/error.js +53 -0
  15. package/build/cjs/coder/index.js +63 -0
  16. package/build/cjs/defaults.js +8 -0
  17. package/build/cjs/http/index.js +196 -0
  18. package/build/cjs/http/types.js +2 -0
  19. package/build/cjs/index.js +5 -0
  20. package/build/cjs/lru.js +150 -0
  21. package/build/cjs/mock/index.js +196 -0
  22. package/build/cjs/mock/mockHttp.js +17 -0
  23. package/build/cjs/mock/mockWs.js +47 -0
  24. package/build/cjs/mock/types.js +2 -0
  25. package/build/cjs/packageDetect.d.ts +1 -0
  26. package/build/cjs/packageInfo.js +4 -0
  27. package/build/cjs/types.js +2 -0
  28. package/build/cjs/ws/errors.js +41 -0
  29. package/build/cjs/ws/index.js +529 -0
  30. package/build/coder/error.d.ts +29 -0
  31. package/build/coder/error.js +50 -0
  32. package/build/coder/index.d.ts +8 -0
  33. package/build/coder/index.js +58 -0
  34. package/build/defaults.d.ts +5 -0
  35. package/build/defaults.js +6 -0
  36. package/build/http/index.d.ts +81 -0
  37. package/build/http/index.js +191 -0
  38. package/build/http/types.d.ts +7 -0
  39. package/build/http/types.js +1 -0
  40. package/build/index.d.ts +2 -0
  41. package/build/index.js +2 -0
  42. package/build/lru.d.ts +15 -0
  43. package/build/lru.js +146 -0
  44. package/build/mock/index.d.ts +35 -0
  45. package/build/mock/index.js +191 -0
  46. package/build/mock/mockHttp.d.ts +9 -0
  47. package/build/mock/mockHttp.js +12 -0
  48. package/build/mock/mockWs.d.ts +26 -0
  49. package/build/mock/mockWs.js +43 -0
  50. package/build/mock/types.d.ts +23 -0
  51. package/build/mock/types.js +1 -0
  52. package/build/package.json +344 -0
  53. package/build/packageDetect.d.ts +1 -0
  54. package/build/packageDetect.js +4 -0
  55. package/build/packageInfo.d.ts +6 -0
  56. package/build/packageInfo.js +1 -0
  57. package/build/types.d.ts +85 -0
  58. package/build/types.js +1 -0
  59. package/build/ws/errors.d.ts +1 -0
  60. package/build/ws/errors.js +38 -0
  61. package/build/ws/index.d.ts +121 -0
  62. package/build/ws/index.js +524 -0
  63. package/build-deno/README.md +66 -0
  64. package/build-deno/bizinikiwi-connect/Health.ts +323 -0
  65. package/build-deno/bizinikiwi-connect/index.ts +417 -0
  66. package/build-deno/bizinikiwi-connect/types.ts +14 -0
  67. package/build-deno/bundle.ts +6 -0
  68. package/build-deno/coder/error.ts +64 -0
  69. package/build-deno/coder/index.ts +86 -0
  70. package/build-deno/defaults.ts +8 -0
  71. package/build-deno/http/index.ts +236 -0
  72. package/build-deno/http/types.ts +9 -0
  73. package/build-deno/index.ts +4 -0
  74. package/build-deno/lru.ts +189 -0
  75. package/build-deno/mock/index.ts +257 -0
  76. package/build-deno/mock/mockHttp.ts +33 -0
  77. package/build-deno/mock/mockWs.ts +87 -0
  78. package/build-deno/mock/types.ts +34 -0
  79. package/build-deno/mod.ts +2 -0
  80. package/build-deno/packageDetect.ts +8 -0
  81. package/build-deno/packageInfo.ts +3 -0
  82. package/build-deno/types.ts +99 -0
  83. package/build-deno/ws/errors.ts +38 -0
  84. package/build-deno/ws/index.ts +650 -0
  85. package/build-tsc-cjs/packageDetect.js +6 -0
  86. package/{cjs → build-tsc-cjs}/packageInfo.js +1 -1
  87. package/{packageInfo.js → build-tsc-esm/packageInfo.js} +1 -1
  88. package/package.json +16 -16
  89. package/src/bizinikiwi-connect/Health.ts +325 -0
  90. package/src/bizinikiwi-connect/index.spec.ts +675 -0
  91. package/src/bizinikiwi-connect/index.ts +427 -0
  92. package/src/bizinikiwi-connect/types.ts +16 -0
  93. package/src/bundle.ts +8 -0
  94. package/src/coder/decodeResponse.spec.ts +70 -0
  95. package/src/coder/encodeJson.spec.ts +20 -0
  96. package/src/coder/encodeObject.spec.ts +25 -0
  97. package/src/coder/error.spec.ts +111 -0
  98. package/src/coder/error.ts +66 -0
  99. package/src/coder/index.ts +88 -0
  100. package/src/defaults.ts +10 -0
  101. package/src/http/index.spec.ts +72 -0
  102. package/src/http/index.ts +238 -0
  103. package/src/http/send.spec.ts +61 -0
  104. package/src/http/types.ts +11 -0
  105. package/src/index.ts +6 -0
  106. package/src/lru.spec.ts +74 -0
  107. package/src/lru.ts +197 -0
  108. package/src/mock/index.ts +259 -0
  109. package/src/mock/mockHttp.ts +35 -0
  110. package/src/mock/mockWs.ts +92 -0
  111. package/src/mock/on.spec.ts +43 -0
  112. package/src/mock/send.spec.ts +38 -0
  113. package/src/mock/subscribe.spec.ts +81 -0
  114. package/src/mock/types.ts +36 -0
  115. package/src/mock/unsubscribe.spec.ts +57 -0
  116. package/src/mod.ts +4 -0
  117. package/src/packageDetect.ts +12 -0
  118. package/src/packageInfo.ts +6 -0
  119. package/src/types.ts +101 -0
  120. package/src/ws/connect.spec.ts +167 -0
  121. package/src/ws/errors.ts +41 -0
  122. package/src/ws/index.spec.ts +97 -0
  123. package/src/ws/index.ts +652 -0
  124. package/src/ws/send.spec.ts +126 -0
  125. package/src/ws/state.spec.ts +20 -0
  126. package/src/ws/subscribe.spec.ts +68 -0
  127. package/src/ws/unsubscribe.spec.ts +100 -0
  128. package/tsconfig.build.json +17 -0
  129. package/tsconfig.build.tsbuildinfo +1 -0
  130. package/tsconfig.spec.json +18 -0
  131. package/tsconfig.spec.tsbuildinfo +1 -0
  132. /package/{cjs → build}/bizinikiwi-connect/Health.d.ts +0 -0
  133. /package/{cjs → build}/bizinikiwi-connect/index.d.ts +0 -0
  134. /package/{cjs → build}/bizinikiwi-connect/types.d.ts +0 -0
  135. /package/{packageDetect.d.ts → build/bizinikiwi-connect/types.js} +0 -0
  136. /package/{cjs → build}/bundle.d.ts +0 -0
  137. /package/{coder → build/cjs/coder}/error.d.ts +0 -0
  138. /package/{coder → build/cjs/coder}/index.d.ts +0 -0
  139. /package/{defaults.d.ts → build/cjs/defaults.d.ts} +0 -0
  140. /package/{http → build/cjs/http}/index.d.ts +0 -0
  141. /package/{http → build/cjs/http}/types.d.ts +0 -0
  142. /package/{index.d.ts → build/cjs/index.d.ts} +0 -0
  143. /package/{lru.d.ts → build/cjs/lru.d.ts} +0 -0
  144. /package/{mock → build/cjs/mock}/index.d.ts +0 -0
  145. /package/{mock → build/cjs/mock}/mockHttp.d.ts +0 -0
  146. /package/{mock → build/cjs/mock}/mockWs.d.ts +0 -0
  147. /package/{mock → build/cjs/mock}/types.d.ts +0 -0
  148. /package/{cjs → build/cjs}/package.json +0 -0
  149. /package/{cjs → build/cjs}/packageDetect.js +0 -0
  150. /package/{packageInfo.d.ts → build/cjs/packageInfo.d.ts} +0 -0
  151. /package/{types.d.ts → build/cjs/types.d.ts} +0 -0
  152. /package/{ws → build/cjs/ws}/errors.d.ts +0 -0
  153. /package/{ws → build/cjs/ws}/index.d.ts +0 -0
  154. /package/{bizinikiwi-connect → build-tsc/bizinikiwi-connect}/Health.d.ts +0 -0
  155. /package/{bizinikiwi-connect → build-tsc/bizinikiwi-connect}/index.d.ts +0 -0
  156. /package/{bizinikiwi-connect → build-tsc/bizinikiwi-connect}/types.d.ts +0 -0
  157. /package/{bundle.d.ts → build-tsc/bundle.d.ts} +0 -0
  158. /package/{cjs → build-tsc}/coder/error.d.ts +0 -0
  159. /package/{cjs → build-tsc}/coder/index.d.ts +0 -0
  160. /package/{cjs → build-tsc}/defaults.d.ts +0 -0
  161. /package/{cjs → build-tsc}/http/index.d.ts +0 -0
  162. /package/{cjs → build-tsc}/http/types.d.ts +0 -0
  163. /package/{cjs → build-tsc}/index.d.ts +0 -0
  164. /package/{cjs → build-tsc}/lru.d.ts +0 -0
  165. /package/{cjs → build-tsc}/mock/index.d.ts +0 -0
  166. /package/{cjs → build-tsc}/mock/mockHttp.d.ts +0 -0
  167. /package/{cjs → build-tsc}/mock/mockWs.d.ts +0 -0
  168. /package/{cjs → build-tsc}/mock/types.d.ts +0 -0
  169. /package/{cjs → build-tsc}/packageDetect.d.ts +0 -0
  170. /package/{cjs → build-tsc}/packageInfo.d.ts +0 -0
  171. /package/{cjs → build-tsc}/types.d.ts +0 -0
  172. /package/{cjs → build-tsc}/ws/errors.d.ts +0 -0
  173. /package/{cjs → build-tsc}/ws/index.d.ts +0 -0
  174. /package/{cjs → build-tsc-cjs}/bizinikiwi-connect/Health.js +0 -0
  175. /package/{cjs → build-tsc-cjs}/bizinikiwi-connect/index.js +0 -0
  176. /package/{cjs → build-tsc-cjs}/bizinikiwi-connect/types.js +0 -0
  177. /package/{cjs → build-tsc-cjs}/bundle.js +0 -0
  178. /package/{cjs → build-tsc-cjs}/coder/error.js +0 -0
  179. /package/{cjs → build-tsc-cjs}/coder/index.js +0 -0
  180. /package/{cjs → build-tsc-cjs}/defaults.js +0 -0
  181. /package/{cjs → build-tsc-cjs}/http/index.js +0 -0
  182. /package/{cjs → build-tsc-cjs}/http/types.js +0 -0
  183. /package/{cjs → build-tsc-cjs}/index.js +0 -0
  184. /package/{cjs → build-tsc-cjs}/lru.js +0 -0
  185. /package/{cjs → build-tsc-cjs}/mock/index.js +0 -0
  186. /package/{cjs → build-tsc-cjs}/mock/mockHttp.js +0 -0
  187. /package/{cjs → build-tsc-cjs}/mock/mockWs.js +0 -0
  188. /package/{cjs → build-tsc-cjs}/mock/types.js +0 -0
  189. /package/{cjs → build-tsc-cjs}/types.js +0 -0
  190. /package/{cjs → build-tsc-cjs}/ws/errors.js +0 -0
  191. /package/{cjs → build-tsc-cjs}/ws/index.js +0 -0
  192. /package/{bizinikiwi-connect → build-tsc-esm/bizinikiwi-connect}/Health.js +0 -0
  193. /package/{bizinikiwi-connect → build-tsc-esm/bizinikiwi-connect}/index.js +0 -0
  194. /package/{bizinikiwi-connect → build-tsc-esm/bizinikiwi-connect}/types.js +0 -0
  195. /package/{bundle.js → build-tsc-esm/bundle.js} +0 -0
  196. /package/{coder → build-tsc-esm/coder}/error.js +0 -0
  197. /package/{coder → build-tsc-esm/coder}/index.js +0 -0
  198. /package/{defaults.js → build-tsc-esm/defaults.js} +0 -0
  199. /package/{http → build-tsc-esm/http}/index.js +0 -0
  200. /package/{http → build-tsc-esm/http}/types.js +0 -0
  201. /package/{index.js → build-tsc-esm/index.js} +0 -0
  202. /package/{lru.js → build-tsc-esm/lru.js} +0 -0
  203. /package/{mock → build-tsc-esm/mock}/index.js +0 -0
  204. /package/{mock → build-tsc-esm/mock}/mockHttp.js +0 -0
  205. /package/{mock → build-tsc-esm/mock}/mockWs.js +0 -0
  206. /package/{mock → build-tsc-esm/mock}/types.js +0 -0
  207. /package/{packageDetect.js → build-tsc-esm/packageDetect.js} +0 -0
  208. /package/{types.js → build-tsc-esm/types.js} +0 -0
  209. /package/{ws → build-tsc-esm/ws}/errors.js +0 -0
  210. /package/{ws → build-tsc-esm/ws}/index.js +0 -0
@@ -0,0 +1,675 @@
1
+ // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
+
6
+ import type * as Sc from '@bizinikiwi/connect';
7
+ import type { HealthChecker, SmoldotHealth } from './types.js';
8
+
9
+ import { stringify } from '@pezkuwi/util';
10
+
11
+ import { ScProvider } from './index.js';
12
+
13
+ interface MockChain extends Sc.Chain {
14
+ _spec: () => string;
15
+ _recevedRequests: () => string[];
16
+ _isTerminated: () => boolean;
17
+ _triggerCallback: (response: string | object) => void;
18
+ _setTerminateInterceptor: (fn: () => void) => void;
19
+ _setSendJsonRpcInterceptor: (fn: (rpc: string) => void) => void;
20
+ _getLatestRequest: () => string;
21
+ }
22
+
23
+ interface MockedHealthChecker extends HealthChecker {
24
+ _isActive: () => boolean;
25
+ _triggerHealthUpdate: (update: SmoldotHealth) => void;
26
+ }
27
+
28
+ type MockSc = typeof Sc & {
29
+ latestChain: () => MockChain;
30
+ };
31
+
32
+ enum WellKnownChain {
33
+ pezkuwi = 'pezkuwi',
34
+ ksmcc3 = 'ksmcc3',
35
+ pezkuwichain_v2_2 = 'pezkuwichain_v2_2',
36
+ dicle2 = 'dicle2'
37
+ }
38
+
39
+ const wait = (ms: number) =>
40
+ new Promise((resolve) =>
41
+ setTimeout(resolve, ms)
42
+ );
43
+
44
+ function healthCheckerMock (): MockedHealthChecker {
45
+ let cb: (health: SmoldotHealth) => void = () => undefined;
46
+ let sendJsonRpc: (request: string) => void = () => undefined;
47
+ let isActive = false;
48
+
49
+ return {
50
+ _isActive: () => isActive,
51
+ _triggerHealthUpdate: (update: SmoldotHealth) => {
52
+ cb(update);
53
+ },
54
+ responsePassThrough: (response) => response,
55
+ sendJsonRpc: (...args) => sendJsonRpc(...args),
56
+ setSendJsonRpc: (cb) => {
57
+ sendJsonRpc = cb;
58
+ },
59
+ start: (x) => {
60
+ isActive = true;
61
+ cb = x;
62
+ },
63
+ stop: () => {
64
+ isActive = false;
65
+ }
66
+ };
67
+ }
68
+
69
+ function healthCheckerFactory () {
70
+ const _healthCheckers: MockedHealthChecker[] = [];
71
+
72
+ return {
73
+ _healthCheckers,
74
+ _latestHealthChecker: () => _healthCheckers.slice(-1)[0],
75
+ healthChecker: () => {
76
+ const result = healthCheckerMock();
77
+
78
+ _healthCheckers.push(result);
79
+
80
+ return result;
81
+ }
82
+ };
83
+ }
84
+
85
+ function getFakeChain (spec: string): MockChain {
86
+ const _receivedRequests: string[] = [];
87
+ let _isTerminated = false;
88
+ const _pendingResponses: string[] = [];
89
+ let _responseResolver: ((value: string) => void) | null = null;
90
+
91
+ let terminateInterceptor = Function.prototype;
92
+ let sendJsonRpcInterceptor = Function.prototype;
93
+
94
+ const triggerCallback = (response: string | object) => {
95
+ const res = typeof response === 'string' ? response : stringify(response);
96
+
97
+ if (_responseResolver) {
98
+ _responseResolver(res);
99
+ _responseResolver = null;
100
+ } else {
101
+ _pendingResponses.push(res);
102
+ }
103
+ };
104
+
105
+ const nextJsonRpcResponse = (): Promise<string> => {
106
+ if (_pendingResponses.length > 0) {
107
+ return Promise.resolve(_pendingResponses.shift()!);
108
+ }
109
+
110
+ return new Promise((resolve) => {
111
+ _responseResolver = resolve;
112
+ });
113
+ };
114
+
115
+ const jsonRpcResponses: AsyncIterableIterator<string> = {
116
+ [Symbol.asyncIterator] () {
117
+ return this;
118
+ },
119
+ async next () {
120
+ if (_isTerminated) {
121
+ return { done: true, value: undefined };
122
+ }
123
+
124
+ const value = await nextJsonRpcResponse();
125
+
126
+ return { done: false, value };
127
+ }
128
+ };
129
+
130
+ return {
131
+ _getLatestRequest: () => _receivedRequests[_receivedRequests.length - 1],
132
+ _isTerminated: () => _isTerminated,
133
+ _recevedRequests: () => _receivedRequests,
134
+ _setSendJsonRpcInterceptor: (fn) => {
135
+ sendJsonRpcInterceptor = fn;
136
+ },
137
+ _setTerminateInterceptor: (fn) => {
138
+ terminateInterceptor = fn;
139
+ },
140
+ _spec: () => spec,
141
+ _triggerCallback: triggerCallback,
142
+ addChain: (chainSpec) =>
143
+ Promise.resolve(getFakeChain(chainSpec)),
144
+ remove: () => {
145
+ terminateInterceptor();
146
+ _isTerminated = true;
147
+ },
148
+ sendJsonRpc: (rpc) => {
149
+ sendJsonRpcInterceptor(rpc);
150
+ _receivedRequests.push(rpc);
151
+ },
152
+ nextJsonRpcResponse,
153
+ jsonRpcResponses
154
+ };
155
+ }
156
+
157
+ function getFakeClient () {
158
+ const chains: MockChain[] = [];
159
+ let addChainInterceptor: Promise<void> = Promise.resolve();
160
+ let addWellKnownChainInterceptor: Promise<void> = Promise.resolve();
161
+
162
+ return {
163
+ _chains: () => chains,
164
+ _setAddChainInterceptor: (interceptor: Promise<void>) => {
165
+ addChainInterceptor = interceptor;
166
+ },
167
+ _setAddWellKnownChainInterceptor: (interceptor: Promise<void>) => {
168
+ addWellKnownChainInterceptor = interceptor;
169
+ },
170
+ addChain: (chainSpec: string): Promise<MockChain> =>
171
+ addChainInterceptor.then(() => {
172
+ const result = getFakeChain(chainSpec);
173
+
174
+ chains.push(result);
175
+
176
+ return result;
177
+ }),
178
+ addWellKnownChain: (
179
+ wellKnownChain: string
180
+ ): Promise<MockChain> =>
181
+ addWellKnownChainInterceptor.then(() => {
182
+ const result = getFakeChain(wellKnownChain);
183
+
184
+ chains.push(result);
185
+
186
+ return result;
187
+ })
188
+ };
189
+ }
190
+
191
+ function connectorFactory (): MockSc {
192
+ const clients: ReturnType<typeof getFakeClient>[] = [];
193
+ const latestClient = () => clients[clients.length - 1];
194
+
195
+ return {
196
+ WellKnownChain,
197
+ _clients: () => clients,
198
+ createScClient: () => {
199
+ const result = getFakeClient();
200
+
201
+ clients.push(result);
202
+
203
+ return result;
204
+ },
205
+ latestChain: () =>
206
+ latestClient()._chains()[latestClient()._chains().length - 1],
207
+ latestClient
208
+ } as unknown as MockSc;
209
+ }
210
+
211
+ function setChainSyncyingStatus (isSyncing: boolean): void {
212
+ getCurrentHealthChecker()._triggerHealthUpdate({
213
+ isSyncing,
214
+ peers: 1,
215
+ shouldHavePeers: true
216
+ });
217
+ }
218
+
219
+ let mockSc: MockSc;
220
+ let mockedHealthChecker: ReturnType<typeof healthCheckerFactory>;
221
+ const getCurrentHealthChecker = () => mockedHealthChecker._latestHealthChecker();
222
+
223
+ describe('ScProvider', () => {
224
+ beforeAll(() => {
225
+ mockSc = connectorFactory();
226
+ mockedHealthChecker = healthCheckerFactory();
227
+ });
228
+
229
+ describe('on', () => {
230
+ it('emits `connected` as soon as the chain is not syncing', async () => {
231
+ const provider = new ScProvider(mockSc, '');
232
+
233
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
234
+
235
+ const onConnected = jest.fn();
236
+
237
+ provider.on('connected', onConnected);
238
+
239
+ expect(onConnected).not.toHaveBeenCalled();
240
+ setChainSyncyingStatus(false);
241
+ expect(onConnected).toHaveBeenCalled();
242
+ });
243
+
244
+ it('stops receiving notifications after unsubscribing', async () => {
245
+ const provider = new ScProvider(mockSc, '');
246
+
247
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
248
+
249
+ const onConnected = jest.fn();
250
+
251
+ provider.on('connected', onConnected)();
252
+ expect(onConnected).not.toHaveBeenCalled();
253
+
254
+ setChainSyncyingStatus(false);
255
+ expect(onConnected).not.toHaveBeenCalled();
256
+ });
257
+
258
+ it('synchronously emits connected if the Provider is already `connected`', async () => {
259
+ const provider = new ScProvider(mockSc, '');
260
+
261
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
262
+
263
+ setChainSyncyingStatus(false);
264
+
265
+ const onConnected = jest.fn();
266
+
267
+ provider.on('connected', onConnected);
268
+ expect(onConnected).toHaveBeenCalled();
269
+ });
270
+
271
+ it('emits `disconnected` once the chain goes back to syncing', async () => {
272
+ const provider = new ScProvider(mockSc, '');
273
+
274
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
275
+
276
+ setChainSyncyingStatus(false);
277
+
278
+ const onConnected = jest.fn();
279
+ const onDisconnected = jest.fn();
280
+
281
+ provider.on('connected', onConnected);
282
+ provider.on('disconnected', onDisconnected);
283
+
284
+ expect(onConnected).toHaveBeenCalled();
285
+ expect(onDisconnected).not.toHaveBeenCalled();
286
+
287
+ onConnected.mockReset();
288
+ setChainSyncyingStatus(true);
289
+
290
+ expect(onConnected).not.toHaveBeenCalled();
291
+ expect(onDisconnected).toHaveBeenCalled();
292
+ });
293
+ });
294
+
295
+ describe('hasSubscriptions', () => {
296
+ it('supports subscriptions', async () => {
297
+ const provider = new ScProvider(mockSc, '');
298
+
299
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
300
+
301
+ expect(provider.hasSubscriptions).toBe(true);
302
+ });
303
+ });
304
+
305
+ describe('clone', () => {
306
+ it('can not be clonned', async () => {
307
+ const provider = new ScProvider(mockSc, '');
308
+
309
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
310
+
311
+ expect(() => provider.clone()).toThrow();
312
+ });
313
+ });
314
+
315
+ describe('connect', () => {
316
+ it('does not create a new chain when trying to re-connect while the current chain is syncing', async () => {
317
+ const provider = new ScProvider(mockSc, '');
318
+
319
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
320
+ const chain = mockSc.latestChain();
321
+
322
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
323
+ expect(chain).toBe(mockSc.latestChain());
324
+ });
325
+
326
+ it('throws when trying to connect on an already connected Provider', async () => {
327
+ const provider = new ScProvider(mockSc, '');
328
+
329
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
330
+
331
+ setChainSyncyingStatus(false);
332
+
333
+ await expect(
334
+ provider.connect(undefined, mockedHealthChecker.healthChecker)
335
+ ).rejects.toThrow(/Already connected/);
336
+ });
337
+ });
338
+
339
+ describe('disconnect', () => {
340
+ it('removes the chain and cleans up', async () => {
341
+ const provider = new ScProvider(mockSc, '');
342
+
343
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
344
+ const chain = mockSc.latestChain();
345
+
346
+ await provider.disconnect();
347
+
348
+ expect(chain._isTerminated()).toBe(true);
349
+ });
350
+
351
+ // eslint-disable-next-line jest/expect-expect
352
+ it('does not throw when disconnecting on an already disconnected Provider', async () => {
353
+ const provider = new ScProvider(mockSc, '');
354
+
355
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
356
+ await provider.disconnect();
357
+ await provider.disconnect();
358
+ });
359
+ });
360
+
361
+ describe('send', () => {
362
+ it('throws when trying to send a request while the Provider is not connected', async () => {
363
+ const provider = new ScProvider(mockSc, '');
364
+
365
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
366
+
367
+ await expect(provider.send('', [])).rejects.toThrow();
368
+ });
369
+
370
+ it('receives responses to its requests', async () => {
371
+ const provider = new ScProvider(mockSc, '');
372
+
373
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
374
+ const chain = mockSc.latestChain();
375
+
376
+ setChainSyncyingStatus(false);
377
+
378
+ const responsePromise = provider.send<unknown>('getData', ['foo']);
379
+
380
+ await wait(0);
381
+ expect(chain._getLatestRequest()).toEqual(
382
+ '{"id":1,"jsonrpc":"2.0","method":"getData","params":["foo"]}'
383
+ );
384
+
385
+ const result = { foo: 'foo' };
386
+
387
+ chain._triggerCallback({
388
+ id: 1,
389
+ jsonrpc: '2.0',
390
+ result
391
+ });
392
+
393
+ const response = await responsePromise;
394
+
395
+ expect(response).toEqual(result);
396
+ });
397
+
398
+ it("rejects when the response can't be deserialized", async () => {
399
+ const provider = new ScProvider(mockSc, '');
400
+
401
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
402
+ const chain = mockSc.latestChain();
403
+
404
+ setChainSyncyingStatus(false);
405
+
406
+ setTimeout(() => {
407
+ chain._triggerCallback({
408
+ id: 1,
409
+ jsonrpc: '2.0'
410
+ });
411
+ }, 0);
412
+
413
+ await expect(provider.send('getData', ['foo'])).rejects.toThrow();
414
+ });
415
+
416
+ it('rejects when the smoldot chain has crashed', async () => {
417
+ const provider = new ScProvider(mockSc, '');
418
+
419
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
420
+ const chain = mockSc.latestChain();
421
+
422
+ setChainSyncyingStatus(false);
423
+ await wait(0);
424
+
425
+ chain._setSendJsonRpcInterceptor(() => {
426
+ throw new Error('boom!');
427
+ });
428
+
429
+ await expect(
430
+ provider.send('getData', ['foo'])
431
+ ).rejects.toThrow(/Disconnected/);
432
+ expect(provider.isConnected).toBe(false);
433
+ });
434
+ });
435
+
436
+ describe('subscribe', () => {
437
+ it('subscribes and recives messages until it unsubscribes', async () => {
438
+ const provider = new ScProvider(mockSc, '');
439
+
440
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
441
+ const chain = mockSc.latestChain();
442
+
443
+ setChainSyncyingStatus(false);
444
+
445
+ const unsubscribeToken = 'unsubscribeToken';
446
+
447
+ setTimeout(() => {
448
+ chain._triggerCallback({
449
+ id: 1,
450
+ jsonrpc: '2.0',
451
+ result: unsubscribeToken
452
+ });
453
+ }, 0);
454
+
455
+ const cb = jest.fn();
456
+ const token = await provider.subscribe(
457
+ 'foo',
458
+ 'chain_subscribeNewHeads',
459
+ ['baz'],
460
+ cb
461
+ );
462
+
463
+ expect(token).toBe(unsubscribeToken);
464
+ expect(cb).not.toHaveBeenCalled();
465
+
466
+ chain._triggerCallback({
467
+ jsonrpc: '2.0',
468
+ method: 'foo',
469
+ params: {
470
+ result: 1,
471
+ subscription: token
472
+ }
473
+ });
474
+
475
+ await wait(0);
476
+ expect(cb).toHaveBeenCalledTimes(1);
477
+ expect(cb).toHaveBeenLastCalledWith(null, 1);
478
+
479
+ chain._triggerCallback({
480
+ jsonrpc: '2.0',
481
+ method: 'foo',
482
+ params: {
483
+ result: 2,
484
+ subscription: token
485
+ }
486
+ });
487
+
488
+ await wait(0);
489
+ expect(cb).toHaveBeenCalledTimes(2);
490
+ expect(cb).toHaveBeenLastCalledWith(null, 2);
491
+
492
+ provider
493
+ .unsubscribe('foo', 'chain_unsubscribeNewHeads', unsubscribeToken)
494
+ .catch(console.error);
495
+
496
+ chain._triggerCallback({
497
+ jsonrpc: '2.0',
498
+ method: 'foo',
499
+ params: {
500
+ result: 3,
501
+ subscription: token
502
+ }
503
+ });
504
+ expect(cb).toHaveBeenCalledTimes(2);
505
+ expect(cb).toHaveBeenLastCalledWith(null, 2);
506
+ });
507
+
508
+ it('ignores subscription messages that were received before the subscription token', async () => {
509
+ const provider = new ScProvider(mockSc, '');
510
+
511
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
512
+ const chain = mockSc.latestChain();
513
+
514
+ setChainSyncyingStatus(false);
515
+
516
+ const unsubscribeToken = 'unsubscribeToken';
517
+
518
+ chain._triggerCallback({
519
+ jsonrpc: '2.0',
520
+ method: 'foo',
521
+ params: {
522
+ result: 1,
523
+ subscription: unsubscribeToken
524
+ }
525
+ });
526
+ setTimeout(() => {
527
+ chain._triggerCallback({
528
+ id: 1,
529
+ jsonrpc: '2.0',
530
+ result: unsubscribeToken
531
+ });
532
+ }, 0);
533
+
534
+ const cb = jest.fn();
535
+ const token = await provider.subscribe(
536
+ 'foo',
537
+ 'chain_subscribeNewHeads',
538
+ ['baz'],
539
+ cb
540
+ );
541
+
542
+ expect(token).toBe(unsubscribeToken);
543
+ expect(cb).not.toHaveBeenCalled();
544
+ });
545
+
546
+ it('emits the error when the message has an error', async () => {
547
+ const provider = new ScProvider(mockSc, '');
548
+
549
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
550
+ const chain = mockSc.latestChain();
551
+
552
+ setChainSyncyingStatus(false);
553
+ await wait(0);
554
+
555
+ const unsubscribeToken = 'unsubscribeToken';
556
+
557
+ setTimeout(() => {
558
+ chain._triggerCallback({
559
+ id: 1,
560
+ jsonrpc: '2.0',
561
+ result: unsubscribeToken
562
+ });
563
+ }, 0);
564
+
565
+ const cb = jest.fn();
566
+ await provider.subscribe(
567
+ 'foo',
568
+ 'chain_subscribeNewHeads',
569
+ ['baz'],
570
+ cb
571
+ );
572
+
573
+ chain._triggerCallback({
574
+ jsonrpc: '2.0',
575
+ method: 'foo',
576
+ params: {
577
+ error: 'boom',
578
+ subscription: unsubscribeToken
579
+ }
580
+ });
581
+
582
+ await wait(0);
583
+ expect(cb).toHaveBeenCalledTimes(1);
584
+ expect(cb).toHaveBeenLastCalledWith(new Error('boom!'), undefined);
585
+ });
586
+
587
+ it('errors when subscribing to an unsupported method', async () => {
588
+ const provider = new ScProvider(mockSc, '');
589
+
590
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
591
+
592
+ setChainSyncyingStatus(false);
593
+
594
+ await wait(0);
595
+ await expect(
596
+ provider.subscribe('foo', 'bar', ['baz'], () => undefined)
597
+ ).rejects.toThrow(/Unsupported subscribe method: bar/);
598
+ });
599
+ });
600
+
601
+ describe('unsubscribe', () => {
602
+ it('rejects when trying to unsubscribe from un unexisting subscription', async () => {
603
+ const provider = new ScProvider(mockSc, '');
604
+
605
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
606
+
607
+ setChainSyncyingStatus(false);
608
+
609
+ await expect(
610
+ provider.unsubscribe('', '', '')
611
+ ).rejects.toThrow(/Unable to find active subscription/);
612
+ });
613
+ });
614
+
615
+ it('cleans up the stale subscriptions once it reconnects', async () => {
616
+ const provider = new ScProvider(mockSc, '');
617
+
618
+ await provider.connect(undefined, mockedHealthChecker.healthChecker);
619
+ const chain = mockSc.latestChain();
620
+
621
+ // setting the syncing status of the chain to fals so that the Provider
622
+ // gets `connected`
623
+ setChainSyncyingStatus(false);
624
+
625
+ // while connected we create a subscription
626
+ const unsubscribeToken = 'unsubscribeToken';
627
+
628
+ setTimeout(() => {
629
+ chain._triggerCallback({
630
+ id: 1,
631
+ jsonrpc: '2.0',
632
+ result: unsubscribeToken
633
+ });
634
+ }, 0);
635
+
636
+ const cb = jest.fn();
637
+ const token = await provider.subscribe(
638
+ 'foo',
639
+ 'chain_subscribeNewHeads',
640
+ ['baz'],
641
+ cb
642
+ );
643
+
644
+ // setting the syncing status of the chain to fals so that the Provider
645
+ // gets `disconnected`
646
+ setChainSyncyingStatus(true);
647
+
648
+ // let's wait some time in order to ensure that the stale unsubscription
649
+ // messages are not sent until the chain syncing status changes back to false
650
+ await wait(200);
651
+
652
+ // before we let the healthChecker know that the chain is no longer syncing,
653
+ // let's make sure that the chain has received the correct request, and
654
+ // most importantly that it has not received a request for unsubscribing
655
+ // from the stale subscription, since that request should happen once the
656
+ // chain is no longer syncing
657
+ expect(chain._recevedRequests()).toEqual([
658
+ '{"id":1,"jsonrpc":"2.0","method":"chain_subscribeNewHeads","params":["baz"]}'
659
+ ]);
660
+
661
+ // lets change the sync status back to false
662
+ setChainSyncyingStatus(false);
663
+
664
+ // let's wait one tick to ensure that the microtasks got processed
665
+ await wait(0);
666
+
667
+ // let's make sure that we have now sent the request for killing the
668
+ // stale subscription
669
+ expect(chain._recevedRequests()).toEqual([
670
+ '{"id":1,"jsonrpc":"2.0","method":"chain_subscribeNewHeads","params":["baz"]}',
671
+ `{"id":2,"jsonrpc":"2.0","method":"chain_unsubscribeNewHeads","params":["${token}"]}`,
672
+ '{"id":3,"jsonrpc":"2.0","method":"chain_subscribeNewHeads","params":["baz"]}'
673
+ ]);
674
+ });
675
+ });