@pezkuwi/rpc-provider 16.5.5 → 16.5.8

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 (277) 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/bizinikiwi-connect/types.js +1 -0
  7. package/build/LICENSE +201 -0
  8. package/build/README.md +68 -0
  9. package/build/bizinikiwi-connect/Health.d.ts +7 -0
  10. package/build/bizinikiwi-connect/Health.js +259 -0
  11. package/build/bizinikiwi-connect/index.d.ts +22 -0
  12. package/build/bizinikiwi-connect/index.js +319 -0
  13. package/build/bizinikiwi-connect/types.d.ts +12 -0
  14. package/build/bizinikiwi-connect/types.js +1 -0
  15. package/build/bundle.d.ts +1 -1
  16. package/build/bundle.js +5 -0
  17. package/build/cjs/bizinikiwi-connect/Health.d.ts +7 -0
  18. package/build/cjs/bizinikiwi-connect/Health.js +264 -0
  19. package/build/cjs/bizinikiwi-connect/index.d.ts +22 -0
  20. package/build/cjs/bizinikiwi-connect/index.js +323 -0
  21. package/build/cjs/bizinikiwi-connect/types.d.ts +12 -0
  22. package/build/cjs/bizinikiwi-connect/types.js +2 -0
  23. package/build/cjs/bundle.d.ts +5 -0
  24. package/build/cjs/bundle.js +14 -0
  25. package/build/cjs/coder/error.d.ts +29 -0
  26. package/build/cjs/coder/error.js +53 -0
  27. package/build/cjs/coder/index.d.ts +8 -0
  28. package/build/cjs/coder/index.js +63 -0
  29. package/build/cjs/defaults.d.ts +5 -0
  30. package/build/cjs/defaults.js +8 -0
  31. package/build/cjs/http/index.d.ts +81 -0
  32. package/build/cjs/http/index.js +196 -0
  33. package/build/cjs/http/types.d.ts +7 -0
  34. package/build/cjs/http/types.js +2 -0
  35. package/build/cjs/index.d.ts +2 -0
  36. package/build/cjs/index.js +5 -0
  37. package/build/cjs/lru.d.ts +15 -0
  38. package/build/cjs/lru.js +150 -0
  39. package/build/cjs/mock/index.d.ts +35 -0
  40. package/build/cjs/mock/index.js +196 -0
  41. package/build/cjs/mock/mockHttp.d.ts +9 -0
  42. package/build/cjs/mock/mockHttp.js +17 -0
  43. package/build/cjs/mock/mockWs.d.ts +26 -0
  44. package/build/cjs/mock/mockWs.js +47 -0
  45. package/build/cjs/mock/types.d.ts +23 -0
  46. package/build/cjs/mock/types.js +2 -0
  47. package/build/cjs/package.json +3 -0
  48. package/build/cjs/packageDetect.d.ts +1 -0
  49. package/build/cjs/packageDetect.js +6 -0
  50. package/build/cjs/packageInfo.d.ts +6 -0
  51. package/build/cjs/packageInfo.js +4 -0
  52. package/build/cjs/types.d.ts +85 -0
  53. package/build/cjs/types.js +2 -0
  54. package/build/cjs/ws/errors.d.ts +1 -0
  55. package/build/cjs/ws/errors.js +41 -0
  56. package/build/cjs/ws/index.d.ts +121 -0
  57. package/build/cjs/ws/index.js +529 -0
  58. package/build/coder/error.js +50 -0
  59. package/build/coder/index.js +58 -0
  60. package/build/defaults.js +6 -0
  61. package/build/http/index.d.ts +1 -1
  62. package/build/http/index.js +191 -0
  63. package/build/http/types.js +1 -0
  64. package/build/index.js +2 -0
  65. package/build/lru.js +146 -0
  66. package/build/mock/index.js +191 -0
  67. package/build/mock/mockHttp.js +12 -0
  68. package/build/mock/mockWs.js +43 -0
  69. package/build/mock/types.js +1 -0
  70. package/build/package.json +344 -0
  71. package/build/packageDetect.js +4 -0
  72. package/build/packageInfo.js +1 -0
  73. package/build/types.js +1 -0
  74. package/build/ws/errors.js +38 -0
  75. package/build/ws/index.d.ts +1 -1
  76. package/build/ws/index.js +524 -0
  77. package/build-deno/README.md +66 -0
  78. package/build-deno/bizinikiwi-connect/Health.ts +323 -0
  79. package/build-deno/bizinikiwi-connect/index.ts +417 -0
  80. package/build-deno/bizinikiwi-connect/types.ts +14 -0
  81. package/build-deno/bundle.ts +6 -0
  82. package/build-deno/coder/error.ts +64 -0
  83. package/build-deno/coder/index.ts +86 -0
  84. package/build-deno/defaults.ts +8 -0
  85. package/build-deno/http/index.ts +236 -0
  86. package/build-deno/http/types.ts +9 -0
  87. package/build-deno/index.ts +4 -0
  88. package/build-deno/lru.ts +189 -0
  89. package/build-deno/mock/index.ts +257 -0
  90. package/build-deno/mock/mockHttp.ts +33 -0
  91. package/build-deno/mock/mockWs.ts +87 -0
  92. package/build-deno/mock/types.ts +34 -0
  93. package/build-deno/mod.ts +2 -0
  94. package/build-deno/packageDetect.ts +8 -0
  95. package/build-deno/packageInfo.ts +3 -0
  96. package/build-deno/types.ts +99 -0
  97. package/build-deno/ws/errors.ts +38 -0
  98. package/build-deno/ws/index.ts +650 -0
  99. package/build-tsc/bizinikiwi-connect/Health.d.ts +7 -0
  100. package/build-tsc/bizinikiwi-connect/index.d.ts +22 -0
  101. package/build-tsc/bizinikiwi-connect/types.d.ts +12 -0
  102. package/build-tsc/bundle.d.ts +5 -0
  103. package/build-tsc/coder/error.d.ts +29 -0
  104. package/build-tsc/coder/index.d.ts +8 -0
  105. package/build-tsc/defaults.d.ts +5 -0
  106. package/build-tsc/http/index.d.ts +81 -0
  107. package/build-tsc/http/types.d.ts +7 -0
  108. package/build-tsc/index.d.ts +2 -0
  109. package/build-tsc/lru.d.ts +15 -0
  110. package/build-tsc/mock/index.d.ts +35 -0
  111. package/build-tsc/mock/mockHttp.d.ts +9 -0
  112. package/build-tsc/mock/mockWs.d.ts +26 -0
  113. package/build-tsc/mock/types.d.ts +23 -0
  114. package/build-tsc/packageDetect.d.ts +1 -0
  115. package/build-tsc/packageInfo.d.ts +6 -0
  116. package/build-tsc/types.d.ts +85 -0
  117. package/build-tsc/ws/errors.d.ts +1 -0
  118. package/build-tsc/ws/index.d.ts +121 -0
  119. package/build-tsc-cjs/bizinikiwi-connect/Health.js +264 -0
  120. package/build-tsc-cjs/bizinikiwi-connect/index.js +323 -0
  121. package/build-tsc-cjs/bizinikiwi-connect/types.js +2 -0
  122. package/build-tsc-cjs/bundle.js +14 -0
  123. package/build-tsc-cjs/coder/error.js +53 -0
  124. package/build-tsc-cjs/coder/index.js +63 -0
  125. package/build-tsc-cjs/defaults.js +8 -0
  126. package/build-tsc-cjs/http/index.js +196 -0
  127. package/build-tsc-cjs/http/types.js +2 -0
  128. package/build-tsc-cjs/index.js +5 -0
  129. package/build-tsc-cjs/lru.js +150 -0
  130. package/build-tsc-cjs/mock/index.js +196 -0
  131. package/build-tsc-cjs/mock/mockHttp.js +17 -0
  132. package/build-tsc-cjs/mock/mockWs.js +47 -0
  133. package/build-tsc-cjs/mock/types.js +2 -0
  134. package/build-tsc-cjs/packageDetect.js +6 -0
  135. package/build-tsc-cjs/packageInfo.js +4 -0
  136. package/build-tsc-cjs/types.js +2 -0
  137. package/build-tsc-cjs/ws/errors.js +41 -0
  138. package/build-tsc-cjs/ws/index.js +529 -0
  139. package/build-tsc-esm/bizinikiwi-connect/Health.js +259 -0
  140. package/build-tsc-esm/bizinikiwi-connect/index.js +319 -0
  141. package/build-tsc-esm/bizinikiwi-connect/types.js +1 -0
  142. package/build-tsc-esm/bundle.js +5 -0
  143. package/build-tsc-esm/coder/error.js +50 -0
  144. package/build-tsc-esm/coder/index.js +58 -0
  145. package/build-tsc-esm/defaults.js +6 -0
  146. package/build-tsc-esm/http/index.js +191 -0
  147. package/build-tsc-esm/http/types.js +1 -0
  148. package/build-tsc-esm/index.js +2 -0
  149. package/build-tsc-esm/lru.js +146 -0
  150. package/build-tsc-esm/mock/index.js +191 -0
  151. package/build-tsc-esm/mock/mockHttp.js +12 -0
  152. package/build-tsc-esm/mock/mockWs.js +43 -0
  153. package/build-tsc-esm/mock/types.js +1 -0
  154. package/build-tsc-esm/packageDetect.js +4 -0
  155. package/build-tsc-esm/packageInfo.js +1 -0
  156. package/build-tsc-esm/types.js +1 -0
  157. package/build-tsc-esm/ws/errors.js +38 -0
  158. package/build-tsc-esm/ws/index.js +524 -0
  159. package/bundle.d.ts +5 -0
  160. package/bundle.js +5 -0
  161. package/cjs/bizinikiwi-connect/Health.d.ts +7 -0
  162. package/cjs/bizinikiwi-connect/Health.js +264 -0
  163. package/cjs/bizinikiwi-connect/index.d.ts +22 -0
  164. package/cjs/bizinikiwi-connect/index.js +323 -0
  165. package/cjs/bizinikiwi-connect/types.d.ts +12 -0
  166. package/cjs/bizinikiwi-connect/types.js +2 -0
  167. package/cjs/bundle.d.ts +5 -0
  168. package/cjs/bundle.js +14 -0
  169. package/cjs/coder/error.d.ts +29 -0
  170. package/cjs/coder/error.js +53 -0
  171. package/cjs/coder/index.d.ts +8 -0
  172. package/cjs/coder/index.js +63 -0
  173. package/cjs/defaults.d.ts +5 -0
  174. package/cjs/defaults.js +8 -0
  175. package/cjs/http/index.d.ts +81 -0
  176. package/cjs/http/index.js +196 -0
  177. package/cjs/http/types.d.ts +7 -0
  178. package/cjs/http/types.js +2 -0
  179. package/cjs/index.d.ts +2 -0
  180. package/cjs/index.js +5 -0
  181. package/cjs/lru.d.ts +15 -0
  182. package/cjs/lru.js +150 -0
  183. package/cjs/mock/index.d.ts +35 -0
  184. package/cjs/mock/index.js +196 -0
  185. package/cjs/mock/mockHttp.d.ts +9 -0
  186. package/cjs/mock/mockHttp.js +17 -0
  187. package/cjs/mock/mockWs.d.ts +26 -0
  188. package/cjs/mock/mockWs.js +47 -0
  189. package/cjs/mock/types.d.ts +23 -0
  190. package/cjs/mock/types.js +2 -0
  191. package/cjs/package.json +3 -0
  192. package/cjs/packageDetect.d.ts +1 -0
  193. package/cjs/packageDetect.js +6 -0
  194. package/cjs/packageInfo.d.ts +6 -0
  195. package/cjs/packageInfo.js +4 -0
  196. package/cjs/types.d.ts +85 -0
  197. package/cjs/types.js +2 -0
  198. package/cjs/ws/errors.d.ts +1 -0
  199. package/cjs/ws/errors.js +41 -0
  200. package/cjs/ws/index.d.ts +121 -0
  201. package/cjs/ws/index.js +529 -0
  202. package/coder/error.d.ts +29 -0
  203. package/coder/error.js +50 -0
  204. package/coder/index.d.ts +8 -0
  205. package/coder/index.js +58 -0
  206. package/defaults.d.ts +5 -0
  207. package/defaults.js +6 -0
  208. package/http/index.d.ts +81 -0
  209. package/http/index.js +191 -0
  210. package/http/types.d.ts +7 -0
  211. package/http/types.js +1 -0
  212. package/index.d.ts +2 -0
  213. package/index.js +2 -0
  214. package/lru.d.ts +15 -0
  215. package/lru.js +146 -0
  216. package/mock/index.d.ts +35 -0
  217. package/mock/index.js +191 -0
  218. package/mock/mockHttp.d.ts +9 -0
  219. package/mock/mockHttp.js +12 -0
  220. package/mock/mockWs.d.ts +26 -0
  221. package/mock/mockWs.js +43 -0
  222. package/mock/types.d.ts +23 -0
  223. package/mock/types.js +1 -0
  224. package/package.json +316 -15
  225. package/packageDetect.d.ts +1 -0
  226. package/packageDetect.js +4 -0
  227. package/packageInfo.d.ts +6 -0
  228. package/packageInfo.js +1 -0
  229. package/src/{substrate-connect → bizinikiwi-connect}/Health.ts +1 -1
  230. package/src/{substrate-connect → bizinikiwi-connect}/index.spec.ts +55 -22
  231. package/src/{substrate-connect → bizinikiwi-connect}/index.ts +27 -15
  232. package/src/{substrate-connect → bizinikiwi-connect}/types.ts +1 -1
  233. package/src/bundle.ts +2 -2
  234. package/src/coder/decodeResponse.spec.ts +1 -1
  235. package/src/coder/encodeJson.spec.ts +1 -1
  236. package/src/coder/encodeObject.spec.ts +1 -1
  237. package/src/coder/error.spec.ts +1 -1
  238. package/src/coder/error.ts +1 -1
  239. package/src/coder/index.ts +1 -1
  240. package/src/defaults.ts +1 -1
  241. package/src/http/index.spec.ts +1 -1
  242. package/src/http/index.ts +2 -2
  243. package/src/http/send.spec.ts +1 -1
  244. package/src/http/types.ts +1 -1
  245. package/src/index.ts +1 -1
  246. package/src/lru.spec.ts +1 -1
  247. package/src/lru.ts +2 -2
  248. package/src/mock/index.ts +2 -2
  249. package/src/mock/mockHttp.ts +1 -1
  250. package/src/mock/mockWs.ts +1 -1
  251. package/src/mock/on.spec.ts +1 -1
  252. package/src/mock/send.spec.ts +1 -1
  253. package/src/mock/subscribe.spec.ts +1 -1
  254. package/src/mock/types.ts +1 -1
  255. package/src/mock/unsubscribe.spec.ts +1 -1
  256. package/src/mod.ts +1 -1
  257. package/src/packageDetect.ts +2 -2
  258. package/src/packageInfo.ts +3 -3
  259. package/src/types.ts +1 -1
  260. package/src/ws/connect.spec.ts +1 -1
  261. package/src/ws/errors.ts +1 -1
  262. package/src/ws/index.spec.ts +1 -1
  263. package/src/ws/index.ts +2 -2
  264. package/src/ws/send.spec.ts +1 -1
  265. package/src/ws/state.spec.ts +1 -1
  266. package/src/ws/subscribe.spec.ts +1 -1
  267. package/src/ws/unsubscribe.spec.ts +1 -1
  268. package/tsconfig.build.tsbuildinfo +1 -1
  269. package/tsconfig.spec.tsbuildinfo +1 -0
  270. package/types.d.ts +85 -0
  271. package/types.js +1 -0
  272. package/ws/errors.d.ts +1 -0
  273. package/ws/errors.js +38 -0
  274. package/ws/index.d.ts +121 -0
  275. package/ws/index.js +524 -0
  276. /package/{build/substrate-connect → bizinikiwi-connect}/Health.d.ts +0 -0
  277. /package/{build/substrate-connect → bizinikiwi-connect}/types.d.ts +0 -0
@@ -0,0 +1,319 @@
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { isError, isFunction, isObject, logger, noop, objectSpread } from '@pezkuwi/util';
3
+ import { RpcCoder } from '../coder/index.js';
4
+ import { healthChecker } from './Health.js';
5
+ const l = logger('api-bizinikiwi-connect');
6
+ const subscriptionUnsubscriptionMethods = new Map([
7
+ ['author_submitAndWatchExtrinsic', 'author_unwatchExtrinsic'],
8
+ ['chain_subscribeAllHeads', 'chain_unsubscribeAllHeads'],
9
+ ['chain_subscribeFinalizedHeads', 'chain_unsubscribeFinalizedHeads'],
10
+ ['chain_subscribeFinalisedHeads', 'chain_subscribeFinalisedHeads'],
11
+ ['chain_subscribeNewHeads', 'chain_unsubscribeNewHeads'],
12
+ ['chain_subscribeNewHead', 'chain_unsubscribeNewHead'],
13
+ ['chain_subscribeRuntimeVersion', 'chain_unsubscribeRuntimeVersion'],
14
+ ['subscribe_newHead', 'unsubscribe_newHead'],
15
+ ['state_subscribeRuntimeVersion', 'state_unsubscribeRuntimeVersion'],
16
+ ['state_subscribeStorage', 'state_unsubscribeStorage']
17
+ ]);
18
+ const scClients = new WeakMap();
19
+ export class ScProvider {
20
+ #Sc;
21
+ #coder = new RpcCoder();
22
+ #spec;
23
+ #sharedSandbox;
24
+ #subscriptions = new Map();
25
+ #resubscribeMethods = new Map();
26
+ #requests = new Map();
27
+ #wellKnownChains;
28
+ #eventemitter = new EventEmitter();
29
+ #chain = null;
30
+ #isChainReady = false;
31
+ constructor(Sc, spec, sharedSandbox) {
32
+ if (!isObject(Sc) || !isObject(Sc.WellKnownChain) || !isFunction(Sc.createScClient)) {
33
+ throw new Error('Expected an @bizinikiwi/connect interface as first parameter to ScProvider');
34
+ }
35
+ this.#Sc = Sc;
36
+ this.#spec = spec;
37
+ this.#sharedSandbox = sharedSandbox;
38
+ this.#wellKnownChains = new Set(Object.values(Sc.WellKnownChain));
39
+ }
40
+ get hasSubscriptions() {
41
+ // Indicates that subscriptions are supported
42
+ return !!true;
43
+ }
44
+ get isClonable() {
45
+ return !!false;
46
+ }
47
+ get isConnected() {
48
+ return !!this.#chain && this.#isChainReady;
49
+ }
50
+ clone() {
51
+ throw new Error('clone() is not supported.');
52
+ }
53
+ // Config details can be found in @bizinikiwi/connect repo following the link:
54
+ // https://github.com/pezkuwichain/bizinikiwi-connect/blob/main/packages/connect/src/connector/index.ts
55
+ async connect(config, checkerFactory = healthChecker) {
56
+ if (this.isConnected) {
57
+ throw new Error('Already connected!');
58
+ }
59
+ // it could happen that after emitting `disconnected` due to the fact that
60
+ // smoldot is syncing, the consumer tries to reconnect after a certain amount
61
+ // of time... In which case we want to make sure that we don't create a new
62
+ // chain.
63
+ if (this.#chain) {
64
+ await this.#chain;
65
+ return;
66
+ }
67
+ if (this.#sharedSandbox && !this.#sharedSandbox.isConnected) {
68
+ await this.#sharedSandbox.connect();
69
+ }
70
+ const client = this.#sharedSandbox
71
+ ? scClients.get(this.#sharedSandbox)
72
+ : this.#Sc.createScClient(config);
73
+ if (!client) {
74
+ throw new Error('Unknown ScProvider!');
75
+ }
76
+ scClients.set(this, client);
77
+ const hc = checkerFactory();
78
+ const onResponse = (res) => {
79
+ const hcRes = hc.responsePassThrough(res);
80
+ if (!hcRes) {
81
+ return;
82
+ }
83
+ const response = JSON.parse(hcRes);
84
+ let decodedResponse;
85
+ try {
86
+ decodedResponse = this.#coder.decodeResponse(response);
87
+ }
88
+ catch (e) {
89
+ decodedResponse = e;
90
+ }
91
+ // It's not a subscription message, but rather a standar RPC response
92
+ if (response.params?.subscription === undefined || !response.method) {
93
+ return this.#requests.get(response.id)?.(decodedResponse);
94
+ }
95
+ // We are dealing with a subscription message
96
+ const subscriptionId = `${response.method}::${response.params.subscription}`;
97
+ const callback = this.#subscriptions.get(subscriptionId)?.[0];
98
+ callback?.(decodedResponse);
99
+ };
100
+ const addChain = this.#sharedSandbox
101
+ ? (async (...args) => {
102
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
103
+ const source = this.#sharedSandbox;
104
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
105
+ return (await source.#chain).addChain(...args);
106
+ })
107
+ : this.#wellKnownChains.has(this.#spec)
108
+ ? client.addWellKnownChain
109
+ : client.addChain;
110
+ this.#chain = addChain(this.#spec).then((chain) => {
111
+ hc.setSendJsonRpc(chain.sendJsonRpc);
112
+ // Start async response processing loop
113
+ // This replaces the callback-based API from older @substrate/connect versions
114
+ (async () => {
115
+ try {
116
+ for await (const res of chain.jsonRpcResponses) {
117
+ onResponse(res);
118
+ }
119
+ }
120
+ catch {
121
+ // Chain was removed or connection closed - this is expected
122
+ }
123
+ })();
124
+ this.#isChainReady = false;
125
+ const cleanup = () => {
126
+ // If there are any callbacks left, we have to reject/error them.
127
+ // Otherwise, that would cause a memory leak.
128
+ const disconnectionError = new Error('Disconnected');
129
+ this.#requests.forEach((cb) => cb(disconnectionError));
130
+ this.#subscriptions.forEach(([cb]) => cb(disconnectionError));
131
+ this.#subscriptions.clear();
132
+ };
133
+ const staleSubscriptions = [];
134
+ const killStaleSubscriptions = () => {
135
+ if (staleSubscriptions.length === 0) {
136
+ return;
137
+ }
138
+ const stale = staleSubscriptions.pop();
139
+ if (!stale) {
140
+ throw new Error('Unable to get stale subscription');
141
+ }
142
+ const { id, unsubscribeMethod } = stale;
143
+ Promise
144
+ .race([
145
+ this.send(unsubscribeMethod, [id]).catch(noop),
146
+ new Promise((resolve) => setTimeout(resolve, 500))
147
+ ])
148
+ .then(killStaleSubscriptions)
149
+ .catch(noop);
150
+ };
151
+ hc.start((health) => {
152
+ const isReady = !health.isSyncing && (health.peers > 0 || !health.shouldHavePeers);
153
+ // if it's the same as before, then nothing has changed and we are done
154
+ if (this.#isChainReady === isReady) {
155
+ return;
156
+ }
157
+ this.#isChainReady = isReady;
158
+ if (!isReady) {
159
+ // If we've reached this point, that means that the chain used to be "ready"
160
+ // and now we are about to emit `disconnected`.
161
+ //
162
+ // This will cause the PezkuwiJs API think that the connection is
163
+ // actually dead. In reality the smoldot chain is not dead, of course.
164
+ // However, we have to cleanup all the existing callbacks because when
165
+ // the smoldot chain stops syncing, then we will emit `connected` and
166
+ // the PezkuwiJs API will try to re-create the previous
167
+ // subscriptions and requests. Although, now is not a good moment
168
+ // to be sending unsubscription messages to the smoldot chain, we
169
+ // should wait until is no longer syncing to send the unsubscription
170
+ // messages from the stale subscriptions of the previous connection.
171
+ //
172
+ // That's why -before we perform the cleanup of `this.#subscriptions`-
173
+ // we keep the necessary information that we will need later on to
174
+ // kill the stale subscriptions.
175
+ [...this.#subscriptions.values()].forEach((s) => {
176
+ staleSubscriptions.push(s[1]);
177
+ });
178
+ cleanup();
179
+ this.#eventemitter.emit('disconnected');
180
+ }
181
+ else {
182
+ killStaleSubscriptions();
183
+ this.#eventemitter.emit('connected');
184
+ if (this.#resubscribeMethods.size) {
185
+ this.#resubscribe();
186
+ }
187
+ }
188
+ });
189
+ return objectSpread({}, chain, {
190
+ remove: () => {
191
+ hc.stop();
192
+ chain.remove();
193
+ cleanup();
194
+ },
195
+ sendJsonRpc: hc.sendJsonRpc.bind(hc)
196
+ });
197
+ });
198
+ try {
199
+ await this.#chain;
200
+ }
201
+ catch (e) {
202
+ this.#chain = null;
203
+ this.#eventemitter.emit('error', e);
204
+ throw e;
205
+ }
206
+ }
207
+ #resubscribe = () => {
208
+ const promises = [];
209
+ this.#resubscribeMethods.forEach((subDetails) => {
210
+ // only re-create subscriptions which are not in author (only area where
211
+ // transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic'
212
+ // are not included (and will not be re-broadcast)
213
+ if (subDetails.type.startsWith('author_')) {
214
+ return;
215
+ }
216
+ try {
217
+ const promise = new Promise((resolve) => {
218
+ this.subscribe(subDetails.type, subDetails.method, subDetails.params, subDetails.callback).catch((error) => console.log(error));
219
+ resolve();
220
+ });
221
+ promises.push(promise);
222
+ }
223
+ catch (error) {
224
+ l.error(error);
225
+ }
226
+ });
227
+ Promise.all(promises).catch((err) => l.log(err));
228
+ };
229
+ async disconnect() {
230
+ if (!this.#chain) {
231
+ return;
232
+ }
233
+ const chain = await this.#chain;
234
+ this.#chain = null;
235
+ this.#isChainReady = false;
236
+ try {
237
+ chain.remove();
238
+ }
239
+ catch (_) { }
240
+ this.#eventemitter.emit('disconnected');
241
+ }
242
+ on(type, sub) {
243
+ // It's possible. Although, quite unlikely, that by the time that pezkuwi
244
+ // subscribes to the `connected` event, the Provider is already connected.
245
+ // In that case, we must emit to let the consumer know that we are connected.
246
+ if (type === 'connected' && this.isConnected) {
247
+ sub();
248
+ }
249
+ this.#eventemitter.on(type, sub);
250
+ return () => {
251
+ this.#eventemitter.removeListener(type, sub);
252
+ };
253
+ }
254
+ async send(method, params) {
255
+ if (!this.isConnected || !this.#chain) {
256
+ throw new Error('Provider is not connected');
257
+ }
258
+ const chain = await this.#chain;
259
+ const [id, json] = this.#coder.encodeJson(method, params);
260
+ const result = new Promise((resolve, reject) => {
261
+ this.#requests.set(id, (response) => {
262
+ (isError(response) ? reject : resolve)(response);
263
+ });
264
+ try {
265
+ chain.sendJsonRpc(json);
266
+ }
267
+ catch (e) {
268
+ this.#chain = null;
269
+ try {
270
+ chain.remove();
271
+ }
272
+ catch (_) { }
273
+ this.#eventemitter.emit('error', e);
274
+ }
275
+ });
276
+ try {
277
+ return await result;
278
+ }
279
+ finally {
280
+ // let's ensure that once the Promise is resolved/rejected, then we remove
281
+ // remove its entry from the internal #requests
282
+ this.#requests.delete(id);
283
+ }
284
+ }
285
+ async subscribe(type, method, params, callback) {
286
+ if (!subscriptionUnsubscriptionMethods.has(method)) {
287
+ throw new Error(`Unsupported subscribe method: ${method}`);
288
+ }
289
+ const id = await this.send(method, params);
290
+ const subscriptionId = `${type}::${id}`;
291
+ const cb = (response) => {
292
+ if (response instanceof Error) {
293
+ callback(response, undefined);
294
+ }
295
+ else {
296
+ callback(null, response);
297
+ }
298
+ };
299
+ const unsubscribeMethod = subscriptionUnsubscriptionMethods.get(method);
300
+ if (!unsubscribeMethod) {
301
+ throw new Error('Invalid unsubscribe method found');
302
+ }
303
+ this.#resubscribeMethods.set(subscriptionId, { callback, method, params, type });
304
+ this.#subscriptions.set(subscriptionId, [cb, { id, unsubscribeMethod }]);
305
+ return id;
306
+ }
307
+ unsubscribe(type, method, id) {
308
+ if (!this.isConnected) {
309
+ throw new Error('Provider is not connected');
310
+ }
311
+ const subscriptionId = `${type}::${id}`;
312
+ if (!this.#subscriptions.has(subscriptionId)) {
313
+ return Promise.reject(new Error(`Unable to find active subscription=${subscriptionId}`));
314
+ }
315
+ this.#resubscribeMethods.delete(subscriptionId);
316
+ this.#subscriptions.delete(subscriptionId);
317
+ return this.send(method, [id]);
318
+ }
319
+ }
@@ -0,0 +1 @@
1
+ export {};
package/build/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,68 @@
1
+ # @pezkuwi/rpc-provider
2
+
3
+ Generic transport providers to handle the transport of method calls to and from Pezkuwi clients from applications interacting with it. It provides an interface to making RPC calls and is generally, unless you are operating at a low-level and taking care of encoding and decoding of parameters/results, it won't be directly used, rather only passed to a higher-level interface.
4
+
5
+ ## Provider Selection
6
+
7
+ There are three flavours of the providers provided, one allowing for using HTTP as a transport mechanism, the other using WebSockets, and the third one uses bizinikiwi light-client through @bizinikiwi/connect. It is generally recommended to use the [[WsProvider]] since in addition to standard calls, it allows for subscriptions where all changes to state can be pushed from the node to the client.
8
+
9
+ All providers are usable (as is the API), in both browser-based and Node.js environments. Polyfills for unsupported functionality are automatically applied based on feature-detection.
10
+
11
+ ## Usage
12
+
13
+ Installation -
14
+
15
+ ```
16
+ yarn add @pezkuwi/rpc-provider
17
+ ```
18
+
19
+ WebSocket Initialization -
20
+
21
+ ```javascript
22
+ import { WsProvider } from '@pezkuwi/rpc-provider';
23
+
24
+ // this is the actual default endpoint
25
+ const provider = new WsProvider('ws://127.0.0.1:9944');
26
+ const version = await provider.send('client_version', []);
27
+
28
+ console.log('client version', version);
29
+ ```
30
+
31
+ HTTP Initialization -
32
+
33
+ ```javascript
34
+ import { HttpProvider } from '@pezkuwi/rpc-provider';
35
+
36
+ // this is the actual default endpoint
37
+ const provider = new HttpProvider('http://127.0.0.1:9933');
38
+ const version = await provider.send('chain_getBlockHash', []);
39
+
40
+ console.log('latest block Hash', hash);
41
+ ```
42
+
43
+ @bizinikiwi/connect Initialization -
44
+
45
+ Instantiating a Provider for the Pezkuwi Relay Chain:
46
+ ```javascript
47
+ import { ScProvider } from '@pezkuwi/rpc-provider';
48
+ import * as Sc from '@bizinikiwi/connect';
49
+
50
+ const provider = new ScProvider(Sc, Sc.WellKnownChain.pezkuwi);
51
+
52
+ await provider.connect();
53
+
54
+ const version = await provider.send('chain_getBlockHash', []);
55
+ ```
56
+
57
+ Instantiating a Provider for a Pezkuwi teyrchain:
58
+ ```javascript
59
+ import { ScProvider } from '@pezkuwi/rpc-provider';
60
+ import * as Sc from '@bizinikiwi/connect';
61
+
62
+ const pezkuwiProvider = new ScProvider(Sc, Sc.WellKnownChain.pezkuwi);
63
+ const teyrchainProvider = new ScProvider(Sc, teyrchainSpec, pezkuwiProvider);
64
+
65
+ await teyrchainProvider.connect();
66
+
67
+ const version = await teyrchainProvider.send('chain_getBlockHash', []);
68
+ ```
@@ -0,0 +1,7 @@
1
+ import type { HealthChecker } from './types.js';
2
+ export declare function healthChecker(): HealthChecker;
3
+ export declare class HealthCheckError extends Error {
4
+ #private;
5
+ getCause(): unknown;
6
+ constructor(response: unknown, message?: string);
7
+ }