@pezkuwi/rpc-provider 16.5.8 → 16.5.10

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 (213) hide show
  1. package/cjs/packageInfo.js +1 -1
  2. package/mock/index.js +2 -2
  3. package/package.json +11 -11
  4. package/packageInfo.js +1 -1
  5. package/build/LICENSE +0 -201
  6. package/build/README.md +0 -68
  7. package/build/bizinikiwi-connect/Health.d.ts +0 -7
  8. package/build/bizinikiwi-connect/Health.js +0 -259
  9. package/build/bizinikiwi-connect/index.d.ts +0 -22
  10. package/build/bizinikiwi-connect/index.js +0 -319
  11. package/build/bizinikiwi-connect/types.d.ts +0 -12
  12. package/build/bizinikiwi-connect/types.js +0 -1
  13. package/build/bundle.d.ts +0 -5
  14. package/build/bundle.js +0 -5
  15. package/build/cjs/bizinikiwi-connect/Health.d.ts +0 -7
  16. package/build/cjs/bizinikiwi-connect/Health.js +0 -264
  17. package/build/cjs/bizinikiwi-connect/index.d.ts +0 -22
  18. package/build/cjs/bizinikiwi-connect/index.js +0 -323
  19. package/build/cjs/bizinikiwi-connect/types.d.ts +0 -12
  20. package/build/cjs/bizinikiwi-connect/types.js +0 -2
  21. package/build/cjs/bundle.d.ts +0 -5
  22. package/build/cjs/bundle.js +0 -14
  23. package/build/cjs/coder/error.d.ts +0 -29
  24. package/build/cjs/coder/error.js +0 -53
  25. package/build/cjs/coder/index.d.ts +0 -8
  26. package/build/cjs/coder/index.js +0 -63
  27. package/build/cjs/defaults.d.ts +0 -5
  28. package/build/cjs/defaults.js +0 -8
  29. package/build/cjs/http/index.d.ts +0 -81
  30. package/build/cjs/http/index.js +0 -196
  31. package/build/cjs/http/types.d.ts +0 -7
  32. package/build/cjs/http/types.js +0 -2
  33. package/build/cjs/index.d.ts +0 -2
  34. package/build/cjs/index.js +0 -5
  35. package/build/cjs/lru.d.ts +0 -15
  36. package/build/cjs/lru.js +0 -150
  37. package/build/cjs/mock/index.d.ts +0 -35
  38. package/build/cjs/mock/index.js +0 -196
  39. package/build/cjs/mock/mockHttp.d.ts +0 -9
  40. package/build/cjs/mock/mockHttp.js +0 -17
  41. package/build/cjs/mock/mockWs.d.ts +0 -26
  42. package/build/cjs/mock/mockWs.js +0 -47
  43. package/build/cjs/mock/types.d.ts +0 -23
  44. package/build/cjs/mock/types.js +0 -2
  45. package/build/cjs/package.json +0 -3
  46. package/build/cjs/packageDetect.d.ts +0 -1
  47. package/build/cjs/packageDetect.js +0 -6
  48. package/build/cjs/packageInfo.d.ts +0 -6
  49. package/build/cjs/packageInfo.js +0 -4
  50. package/build/cjs/types.d.ts +0 -85
  51. package/build/cjs/types.js +0 -2
  52. package/build/cjs/ws/errors.d.ts +0 -1
  53. package/build/cjs/ws/errors.js +0 -41
  54. package/build/cjs/ws/index.d.ts +0 -121
  55. package/build/cjs/ws/index.js +0 -529
  56. package/build/coder/error.d.ts +0 -29
  57. package/build/coder/error.js +0 -50
  58. package/build/coder/index.d.ts +0 -8
  59. package/build/coder/index.js +0 -58
  60. package/build/defaults.d.ts +0 -5
  61. package/build/defaults.js +0 -6
  62. package/build/http/index.d.ts +0 -81
  63. package/build/http/index.js +0 -191
  64. package/build/http/types.d.ts +0 -7
  65. package/build/http/types.js +0 -1
  66. package/build/index.d.ts +0 -2
  67. package/build/index.js +0 -2
  68. package/build/lru.d.ts +0 -15
  69. package/build/lru.js +0 -146
  70. package/build/mock/index.d.ts +0 -35
  71. package/build/mock/index.js +0 -191
  72. package/build/mock/mockHttp.d.ts +0 -9
  73. package/build/mock/mockHttp.js +0 -12
  74. package/build/mock/mockWs.d.ts +0 -26
  75. package/build/mock/mockWs.js +0 -43
  76. package/build/mock/types.d.ts +0 -23
  77. package/build/mock/types.js +0 -1
  78. package/build/package.json +0 -344
  79. package/build/packageDetect.d.ts +0 -1
  80. package/build/packageDetect.js +0 -4
  81. package/build/packageInfo.d.ts +0 -6
  82. package/build/packageInfo.js +0 -1
  83. package/build/types.d.ts +0 -85
  84. package/build/types.js +0 -1
  85. package/build/ws/errors.d.ts +0 -1
  86. package/build/ws/errors.js +0 -38
  87. package/build/ws/index.d.ts +0 -121
  88. package/build/ws/index.js +0 -524
  89. package/build-deno/README.md +0 -66
  90. package/build-deno/bizinikiwi-connect/Health.ts +0 -323
  91. package/build-deno/bizinikiwi-connect/index.ts +0 -417
  92. package/build-deno/bizinikiwi-connect/types.ts +0 -14
  93. package/build-deno/bundle.ts +0 -6
  94. package/build-deno/coder/error.ts +0 -64
  95. package/build-deno/coder/index.ts +0 -86
  96. package/build-deno/defaults.ts +0 -8
  97. package/build-deno/http/index.ts +0 -236
  98. package/build-deno/http/types.ts +0 -9
  99. package/build-deno/index.ts +0 -4
  100. package/build-deno/lru.ts +0 -189
  101. package/build-deno/mock/index.ts +0 -257
  102. package/build-deno/mock/mockHttp.ts +0 -33
  103. package/build-deno/mock/mockWs.ts +0 -87
  104. package/build-deno/mock/types.ts +0 -34
  105. package/build-deno/mod.ts +0 -2
  106. package/build-deno/packageDetect.ts +0 -8
  107. package/build-deno/packageInfo.ts +0 -3
  108. package/build-deno/types.ts +0 -99
  109. package/build-deno/ws/errors.ts +0 -38
  110. package/build-deno/ws/index.ts +0 -650
  111. package/build-tsc/bizinikiwi-connect/Health.d.ts +0 -7
  112. package/build-tsc/bizinikiwi-connect/index.d.ts +0 -22
  113. package/build-tsc/bizinikiwi-connect/types.d.ts +0 -12
  114. package/build-tsc/bundle.d.ts +0 -5
  115. package/build-tsc/coder/error.d.ts +0 -29
  116. package/build-tsc/coder/index.d.ts +0 -8
  117. package/build-tsc/defaults.d.ts +0 -5
  118. package/build-tsc/http/index.d.ts +0 -81
  119. package/build-tsc/http/types.d.ts +0 -7
  120. package/build-tsc/index.d.ts +0 -2
  121. package/build-tsc/lru.d.ts +0 -15
  122. package/build-tsc/mock/index.d.ts +0 -35
  123. package/build-tsc/mock/mockHttp.d.ts +0 -9
  124. package/build-tsc/mock/mockWs.d.ts +0 -26
  125. package/build-tsc/mock/types.d.ts +0 -23
  126. package/build-tsc/packageDetect.d.ts +0 -1
  127. package/build-tsc/packageInfo.d.ts +0 -6
  128. package/build-tsc/types.d.ts +0 -85
  129. package/build-tsc/ws/errors.d.ts +0 -1
  130. package/build-tsc/ws/index.d.ts +0 -121
  131. package/build-tsc-cjs/bizinikiwi-connect/Health.js +0 -264
  132. package/build-tsc-cjs/bizinikiwi-connect/index.js +0 -323
  133. package/build-tsc-cjs/bizinikiwi-connect/types.js +0 -2
  134. package/build-tsc-cjs/bundle.js +0 -14
  135. package/build-tsc-cjs/coder/error.js +0 -53
  136. package/build-tsc-cjs/coder/index.js +0 -63
  137. package/build-tsc-cjs/defaults.js +0 -8
  138. package/build-tsc-cjs/http/index.js +0 -196
  139. package/build-tsc-cjs/http/types.js +0 -2
  140. package/build-tsc-cjs/index.js +0 -5
  141. package/build-tsc-cjs/lru.js +0 -150
  142. package/build-tsc-cjs/mock/index.js +0 -196
  143. package/build-tsc-cjs/mock/mockHttp.js +0 -17
  144. package/build-tsc-cjs/mock/mockWs.js +0 -47
  145. package/build-tsc-cjs/mock/types.js +0 -2
  146. package/build-tsc-cjs/packageDetect.js +0 -6
  147. package/build-tsc-cjs/packageInfo.js +0 -4
  148. package/build-tsc-cjs/types.js +0 -2
  149. package/build-tsc-cjs/ws/errors.js +0 -41
  150. package/build-tsc-cjs/ws/index.js +0 -529
  151. package/build-tsc-esm/bizinikiwi-connect/Health.js +0 -259
  152. package/build-tsc-esm/bizinikiwi-connect/index.js +0 -319
  153. package/build-tsc-esm/bizinikiwi-connect/types.js +0 -1
  154. package/build-tsc-esm/bundle.js +0 -5
  155. package/build-tsc-esm/coder/error.js +0 -50
  156. package/build-tsc-esm/coder/index.js +0 -58
  157. package/build-tsc-esm/defaults.js +0 -6
  158. package/build-tsc-esm/http/index.js +0 -191
  159. package/build-tsc-esm/http/types.js +0 -1
  160. package/build-tsc-esm/index.js +0 -2
  161. package/build-tsc-esm/lru.js +0 -146
  162. package/build-tsc-esm/mock/index.js +0 -191
  163. package/build-tsc-esm/mock/mockHttp.js +0 -12
  164. package/build-tsc-esm/mock/mockWs.js +0 -43
  165. package/build-tsc-esm/mock/types.js +0 -1
  166. package/build-tsc-esm/packageDetect.js +0 -4
  167. package/build-tsc-esm/packageInfo.js +0 -1
  168. package/build-tsc-esm/types.js +0 -1
  169. package/build-tsc-esm/ws/errors.js +0 -38
  170. package/build-tsc-esm/ws/index.js +0 -524
  171. package/src/bizinikiwi-connect/Health.ts +0 -325
  172. package/src/bizinikiwi-connect/index.spec.ts +0 -671
  173. package/src/bizinikiwi-connect/index.ts +0 -427
  174. package/src/bizinikiwi-connect/types.ts +0 -16
  175. package/src/bundle.ts +0 -8
  176. package/src/coder/decodeResponse.spec.ts +0 -70
  177. package/src/coder/encodeJson.spec.ts +0 -20
  178. package/src/coder/encodeObject.spec.ts +0 -25
  179. package/src/coder/error.spec.ts +0 -111
  180. package/src/coder/error.ts +0 -66
  181. package/src/coder/index.ts +0 -88
  182. package/src/defaults.ts +0 -10
  183. package/src/http/index.spec.ts +0 -72
  184. package/src/http/index.ts +0 -238
  185. package/src/http/send.spec.ts +0 -61
  186. package/src/http/types.ts +0 -11
  187. package/src/index.ts +0 -6
  188. package/src/lru.spec.ts +0 -74
  189. package/src/lru.ts +0 -197
  190. package/src/mock/index.ts +0 -259
  191. package/src/mock/mockHttp.ts +0 -35
  192. package/src/mock/mockWs.ts +0 -92
  193. package/src/mock/on.spec.ts +0 -43
  194. package/src/mock/send.spec.ts +0 -38
  195. package/src/mock/subscribe.spec.ts +0 -81
  196. package/src/mock/types.ts +0 -36
  197. package/src/mock/unsubscribe.spec.ts +0 -57
  198. package/src/mod.ts +0 -4
  199. package/src/packageDetect.ts +0 -12
  200. package/src/packageInfo.ts +0 -6
  201. package/src/types.ts +0 -101
  202. package/src/ws/connect.spec.ts +0 -167
  203. package/src/ws/errors.ts +0 -41
  204. package/src/ws/index.spec.ts +0 -97
  205. package/src/ws/index.ts +0 -652
  206. package/src/ws/send.spec.ts +0 -126
  207. package/src/ws/state.spec.ts +0 -20
  208. package/src/ws/subscribe.spec.ts +0 -68
  209. package/src/ws/unsubscribe.spec.ts +0 -100
  210. package/tsconfig.build.json +0 -17
  211. package/tsconfig.build.tsbuildinfo +0 -1
  212. package/tsconfig.spec.json +0 -18
  213. package/tsconfig.spec.tsbuildinfo +0 -1
@@ -1,58 +0,0 @@
1
- import { isNumber, isString, isUndefined, stringify } from '@pezkuwi/util';
2
- import RpcError from './error.js';
3
- function formatErrorData(data) {
4
- if (isUndefined(data)) {
5
- return '';
6
- }
7
- const formatted = `: ${isString(data)
8
- ? data.replace(/Error\("/g, '').replace(/\("/g, '(').replace(/"\)/g, ')').replace(/\(/g, ', ').replace(/\)/g, '')
9
- : stringify(data)}`;
10
- // We need some sort of cut-off here since these can be very large and
11
- // very nested, pick a number and trim the result display to it
12
- return formatted.length <= 256
13
- ? formatted
14
- : `${formatted.substring(0, 255)}…`;
15
- }
16
- function checkError(error) {
17
- if (error) {
18
- const { code, data, message } = error;
19
- throw new RpcError(`${code}: ${message}${formatErrorData(data)}`, code, data);
20
- }
21
- }
22
- /** @internal */
23
- export class RpcCoder {
24
- #id = 0;
25
- decodeResponse(response) {
26
- if (!response || response.jsonrpc !== '2.0') {
27
- throw new Error('Invalid jsonrpc field in decoded object');
28
- }
29
- const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
30
- if (!isNumber(response.id) &&
31
- (!isSubscription || (!isNumber(response.params.subscription) &&
32
- !isString(response.params.subscription)))) {
33
- throw new Error('Invalid id field in decoded object');
34
- }
35
- checkError(response.error);
36
- if (response.result === undefined && !isSubscription) {
37
- throw new Error('No result found in jsonrpc response');
38
- }
39
- if (isSubscription) {
40
- checkError(response.params.error);
41
- return response.params.result;
42
- }
43
- return response.result;
44
- }
45
- encodeJson(method, params) {
46
- const [id, data] = this.encodeObject(method, params);
47
- return [id, stringify(data)];
48
- }
49
- encodeObject(method, params) {
50
- const id = ++this.#id;
51
- return [id, {
52
- id,
53
- jsonrpc: '2.0',
54
- method,
55
- params
56
- }];
57
- }
58
- }
@@ -1,6 +0,0 @@
1
- const HTTP_URL = 'http://127.0.0.1:9933';
2
- const WS_URL = 'ws://127.0.0.1:9944';
3
- export default {
4
- HTTP_URL,
5
- WS_URL
6
- };
@@ -1,191 +0,0 @@
1
- import { logger, noop, stringify } from '@pezkuwi/util';
2
- import { fetch } from '@pezkuwi/x-fetch';
3
- import { RpcCoder } from '../coder/index.js';
4
- import defaults from '../defaults.js';
5
- import { DEFAULT_CAPACITY, DEFAULT_TTL, LRUCache } from '../lru.js';
6
- const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
7
- const l = logger('api-http');
8
- /**
9
- * # @pezkuwi/rpc-provider
10
- *
11
- * @name HttpProvider
12
- *
13
- * @description The HTTP Provider allows sending requests using HTTP to a HTTP RPC server TCP port. It does not support subscriptions so you won't be able to listen to events such as new blocks or balance changes. It is usually preferable using the [[WsProvider]].
14
- *
15
- * @example
16
- * <BR>
17
- *
18
- * ```javascript
19
- * import Api from '@pezkuwi/api/promise';
20
- * import { HttpProvider } from '@pezkuwi/rpc-provider';
21
- *
22
- * const provider = new HttpProvider('http://127.0.0.1:9933');
23
- * const api = new Api(provider);
24
- * ```
25
- *
26
- * @see [[WsProvider]]
27
- */
28
- export class HttpProvider {
29
- #callCache;
30
- #cacheCapacity;
31
- #coder;
32
- #endpoint;
33
- #headers;
34
- #stats;
35
- #ttl;
36
- /**
37
- * @param {string} endpoint The endpoint url starting with http://
38
- * @param {Record<string, string>} headers The headers provided to the underlying Http Endpoint
39
- * @param {number} [cacheCapacity] Custom size of the HttpProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
40
- * @param {number} [cacheTtl] Custom TTL of the HttpProvider LRUCache. Determines how long an object can live in the cache. Defaults to `DEFAULT_TTL` (30000)
41
- */
42
- constructor(endpoint = defaults.HTTP_URL, headers = {}, cacheCapacity, cacheTtl) {
43
- if (!/^(https|http):\/\//.test(endpoint)) {
44
- throw new Error(`Endpoint should start with 'http://' or 'https://', received '${endpoint}'`);
45
- }
46
- this.#coder = new RpcCoder();
47
- this.#endpoint = endpoint;
48
- this.#headers = headers;
49
- this.#cacheCapacity = cacheCapacity === 0 ? 0 : cacheCapacity || DEFAULT_CAPACITY;
50
- const ttl = cacheTtl === undefined ? DEFAULT_TTL : cacheTtl;
51
- this.#callCache = new LRUCache(cacheCapacity === 0 ? 0 : cacheCapacity || DEFAULT_CAPACITY, ttl);
52
- this.#ttl = cacheTtl;
53
- this.#stats = {
54
- active: { requests: 0, subscriptions: 0 },
55
- total: { bytesRecv: 0, bytesSent: 0, cached: 0, errors: 0, requests: 0, subscriptions: 0, timeout: 0 }
56
- };
57
- }
58
- /**
59
- * @summary `true` when this provider supports subscriptions
60
- */
61
- get hasSubscriptions() {
62
- return !!false;
63
- }
64
- /**
65
- * @description Returns a clone of the object
66
- */
67
- clone() {
68
- return new HttpProvider(this.#endpoint, this.#headers);
69
- }
70
- /**
71
- * @description Manually connect from the connection
72
- */
73
- async connect() {
74
- // noop
75
- }
76
- /**
77
- * @description Manually disconnect from the connection
78
- */
79
- async disconnect() {
80
- // noop
81
- }
82
- /**
83
- * @description Returns the connection stats
84
- */
85
- get stats() {
86
- return this.#stats;
87
- }
88
- /**
89
- * @description Returns the connection stats
90
- */
91
- get ttl() {
92
- return this.#ttl;
93
- }
94
- /**
95
- * @summary `true` when this provider supports clone()
96
- */
97
- get isClonable() {
98
- return !!true;
99
- }
100
- /**
101
- * @summary Whether the node is connected or not.
102
- * @return {boolean} true if connected
103
- */
104
- get isConnected() {
105
- return !!true;
106
- }
107
- /**
108
- * @summary Events are not supported with the HttpProvider, see [[WsProvider]].
109
- * @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
110
- */
111
- on(_type, _sub) {
112
- l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
113
- return noop;
114
- }
115
- /**
116
- * @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
117
- */
118
- async send(method, params, isCacheable) {
119
- this.#stats.total.requests++;
120
- const [, body] = this.#coder.encodeJson(method, params);
121
- if (this.#cacheCapacity === 0) {
122
- return this.#send(body);
123
- }
124
- const cacheKey = isCacheable ? `${method}::${stringify(params)}` : '';
125
- let resultPromise = isCacheable
126
- ? this.#callCache.get(cacheKey)
127
- : null;
128
- if (!resultPromise) {
129
- resultPromise = this.#send(body);
130
- if (isCacheable) {
131
- this.#callCache.set(cacheKey, resultPromise);
132
- }
133
- }
134
- else {
135
- this.#stats.total.cached++;
136
- }
137
- return resultPromise;
138
- }
139
- async #send(body) {
140
- this.#stats.active.requests++;
141
- this.#stats.total.bytesSent += body.length;
142
- try {
143
- const response = await fetch(this.#endpoint, {
144
- body,
145
- headers: {
146
- Accept: 'application/json',
147
- 'Content-Length': `${body.length}`,
148
- 'Content-Type': 'application/json',
149
- ...this.#headers
150
- },
151
- method: 'POST'
152
- });
153
- if (!response.ok) {
154
- throw new Error(`[${response.status}]: ${response.statusText}`);
155
- }
156
- const result = await response.text();
157
- this.#stats.total.bytesRecv += result.length;
158
- const decoded = this.#coder.decodeResponse(JSON.parse(result));
159
- this.#stats.active.requests--;
160
- return decoded;
161
- }
162
- catch (e) {
163
- this.#stats.active.requests--;
164
- this.#stats.total.errors++;
165
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
166
- const { method, params } = JSON.parse(body);
167
- const rpcError = e;
168
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
169
- const failedRequest = `\nFailed HTTP Request: ${JSON.stringify({ method, params })}`;
170
- // Provide HTTP Request alongside the error
171
- rpcError.message = `${rpcError.message}${failedRequest}`;
172
- throw rpcError;
173
- }
174
- }
175
- /**
176
- * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
177
- */
178
- // eslint-disable-next-line @typescript-eslint/require-await
179
- async subscribe(_types, _method, _params, _cb) {
180
- l.error(ERROR_SUBSCRIBE);
181
- throw new Error(ERROR_SUBSCRIBE);
182
- }
183
- /**
184
- * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
185
- */
186
- // eslint-disable-next-line @typescript-eslint/require-await
187
- async unsubscribe(_type, _method, _id) {
188
- l.error(ERROR_SUBSCRIBE);
189
- throw new Error(ERROR_SUBSCRIBE);
190
- }
191
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- import './packageDetect.js';
2
- export * from './bundle.js';
@@ -1,146 +0,0 @@
1
- export const DEFAULT_CAPACITY = 1024;
2
- export const DEFAULT_TTL = 30000; // 30 seconds
3
- const MAX_TTL = 1800_000; // 30 minutes
4
- const DISABLED_TTL = 31_536_000_000;
5
- class LRUNode {
6
- key;
7
- #expires;
8
- #ttl;
9
- createdAt;
10
- next;
11
- prev;
12
- constructor(key, ttl) {
13
- this.key = key;
14
- this.#ttl = ttl;
15
- this.#expires = Date.now() + ttl;
16
- this.createdAt = Date.now();
17
- this.next = this.prev = this;
18
- }
19
- refresh() {
20
- this.#expires = Date.now() + this.#ttl;
21
- }
22
- get expiry() {
23
- return this.#expires;
24
- }
25
- }
26
- export class LRUCache {
27
- capacity;
28
- #data = new Map();
29
- #refs = new Map();
30
- #length = 0;
31
- #head;
32
- #tail;
33
- #ttl;
34
- constructor(capacity = DEFAULT_CAPACITY, ttl = DEFAULT_TTL) {
35
- // Validate capacity
36
- if (!Number.isInteger(capacity) || capacity < 0) {
37
- throw new Error(`LRUCache initialization error: 'capacity' must be a non-negative integer. Received: ${capacity}`);
38
- }
39
- // Validate ttl
40
- if (ttl !== null && (!Number.isFinite(ttl) || ttl < 0 || ttl > MAX_TTL)) {
41
- throw new Error(`LRUCache initialization error: 'ttl' must be between 0 and ${MAX_TTL} ms or null to disable. Received: ${ttl}`);
42
- }
43
- this.capacity = capacity;
44
- ttl ? this.#ttl = ttl : this.#ttl = DISABLED_TTL;
45
- this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
46
- }
47
- get ttl() {
48
- return this.#ttl;
49
- }
50
- get length() {
51
- return this.#length;
52
- }
53
- get lengthData() {
54
- return this.#data.size;
55
- }
56
- get lengthRefs() {
57
- return this.#refs.size;
58
- }
59
- entries() {
60
- const keys = this.keys();
61
- const count = keys.length;
62
- const entries = new Array(count);
63
- for (let i = 0; i < count; i++) {
64
- const key = keys[i];
65
- entries[i] = [key, this.#data.get(key)];
66
- }
67
- return entries;
68
- }
69
- keys() {
70
- const keys = [];
71
- if (this.#length) {
72
- let curr = this.#head;
73
- while (curr !== this.#tail) {
74
- keys.push(curr.key);
75
- curr = curr.next;
76
- }
77
- keys.push(curr.key);
78
- }
79
- return keys;
80
- }
81
- get(key) {
82
- const data = this.#data.get(key);
83
- if (data) {
84
- this.#toHead(key);
85
- // Evict TTL once data is refreshed
86
- this.#evictTTL();
87
- return data;
88
- }
89
- this.#evictTTL();
90
- return null;
91
- }
92
- set(key, value) {
93
- if (this.#data.has(key)) {
94
- this.#toHead(key);
95
- }
96
- else {
97
- const node = new LRUNode(key, this.#ttl);
98
- this.#refs.set(node.key, node);
99
- if (this.length === 0) {
100
- this.#head = this.#tail = node;
101
- }
102
- else {
103
- this.#head.prev = node;
104
- node.next = this.#head;
105
- this.#head = node;
106
- }
107
- if (this.#length === this.capacity) {
108
- this.#data.delete(this.#tail.key);
109
- this.#refs.delete(this.#tail.key);
110
- this.#tail = this.#tail.prev;
111
- this.#tail.next = this.#head;
112
- }
113
- else {
114
- this.#length += 1;
115
- }
116
- }
117
- // Evict TTL once data is refreshed or added
118
- this.#evictTTL();
119
- this.#data.set(key, value);
120
- }
121
- #evictTTL() {
122
- // Find last node to keep
123
- // traverse map to find the expired nodes
124
- while (this.#tail.expiry && this.#tail.expiry < Date.now() && this.#length > 0) {
125
- this.#refs.delete(this.#tail.key);
126
- this.#data.delete(this.#tail.key);
127
- this.#length -= 1;
128
- this.#tail = this.#tail.prev;
129
- this.#tail.next = this.#head;
130
- }
131
- if (this.#length === 0) {
132
- this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
133
- }
134
- }
135
- #toHead(key) {
136
- const ref = this.#refs.get(key);
137
- if (ref && ref !== this.#head) {
138
- ref.refresh();
139
- ref.prev.next = ref.next;
140
- ref.next.prev = ref.prev;
141
- ref.next = this.#head;
142
- this.#head.prev = ref;
143
- this.#head = ref;
144
- }
145
- }
146
- }
@@ -1,191 +0,0 @@
1
- import { EventEmitter } from 'eventemitter3';
2
- import { createTestKeyring } from '@pezkuwi/keyring/testing';
3
- import { decorateStorage, Metadata } from '@pezkuwi/types';
4
- import jsonrpc from '@pezkuwi/types/interfaces/jsonrpc';
5
- import rpcHeader from '@pezkuwi/types-support/json/Header.004.json' assert { type: 'json' };
6
- import rpcSignedBlock from '@pezkuwi/types-support/json/SignedBlock.004.immortal.json' assert { type: 'json' };
7
- import rpcMetadata from '@pezkuwi/types-support/metadata/static-bizinikiwi';
8
- import { BN, bnToU8a, logger, u8aToHex } from '@pezkuwi/util';
9
- import { randomAsU8a } from '@pezkuwi/util-crypto';
10
- const INTERVAL = 1000;
11
- const SUBSCRIPTIONS = Array.prototype.concat.apply([], Object.values(jsonrpc).map((section) => Object
12
- .values(section)
13
- .filter(({ isSubscription }) => isSubscription)
14
- .map(({ jsonrpc }) => jsonrpc)
15
- .concat('chain_subscribeNewHead')));
16
- const keyring = createTestKeyring({ type: 'ed25519' });
17
- const l = logger('api-mock');
18
- /**
19
- * A mock provider mainly used for testing.
20
- * @return {ProviderInterface} The mock provider
21
- * @internal
22
- */
23
- export class MockProvider {
24
- db = {};
25
- emitter = new EventEmitter();
26
- intervalId;
27
- isUpdating = true;
28
- registry;
29
- prevNumber = new BN(-1);
30
- requests = {
31
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
32
- chain_getBlock: () => this.registry.createType('SignedBlock', rpcSignedBlock.result).toJSON(),
33
- chain_getBlockHash: () => '0x1234000000000000000000000000000000000000000000000000000000000000',
34
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
35
- chain_getFinalizedHead: () => this.registry.createType('Header', rpcHeader.result).hash,
36
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
37
- chain_getHeader: () => this.registry.createType('Header', rpcHeader.result).toJSON(),
38
- rpc_methods: () => this.registry.createType('RpcMethods').toJSON(),
39
- state_getKeys: () => [],
40
- state_getKeysPaged: () => [],
41
- state_getMetadata: () => rpcMetadata,
42
- state_getRuntimeVersion: () => this.registry.createType('RuntimeVersion').toHex(),
43
- state_getStorage: (storage, [key]) => u8aToHex(storage[key]),
44
- system_chain: () => 'mockChain',
45
- system_health: () => ({}),
46
- system_name: () => 'mockClient',
47
- system_properties: () => ({ ss58Format: 42 }),
48
- system_upgradedToTripleRefCount: () => this.registry.createType('bool', true),
49
- system_version: () => '9.8.7',
50
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return, sort-keys
51
- dev_echo: (_, params) => params
52
- };
53
- subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
54
- subs[name] = {
55
- callbacks: {},
56
- lastValue: null
57
- };
58
- return subs;
59
- }, {});
60
- subscriptionId = 0;
61
- subscriptionMap = {};
62
- constructor(registry) {
63
- this.registry = registry;
64
- this.init();
65
- }
66
- get hasSubscriptions() {
67
- return !!true;
68
- }
69
- clone() {
70
- throw new Error('Unimplemented');
71
- }
72
- async connect() {
73
- // noop
74
- }
75
- // eslint-disable-next-line @typescript-eslint/require-await
76
- async disconnect() {
77
- if (this.intervalId) {
78
- clearInterval(this.intervalId);
79
- this.intervalId = null;
80
- }
81
- }
82
- get isClonable() {
83
- return !!false;
84
- }
85
- get isConnected() {
86
- return !!true;
87
- }
88
- on(type, sub) {
89
- this.emitter.on(type, sub);
90
- return () => {
91
- this.emitter.removeListener(type, sub);
92
- };
93
- }
94
- // eslint-disable-next-line @typescript-eslint/require-await
95
- async send(method, params) {
96
- l.debug(() => ['send', method, params]);
97
- if (!this.requests[method]) {
98
- throw new Error(`provider.send: Invalid method '${method}'`);
99
- }
100
- return this.requests[method](this.db, params);
101
- }
102
- // eslint-disable-next-line @typescript-eslint/require-await
103
- async subscribe(_type, method, ...params) {
104
- l.debug(() => ['subscribe', method, params]);
105
- if (!this.subscriptions[method]) {
106
- throw new Error(`provider.subscribe: Invalid method '${method}'`);
107
- }
108
- const callback = params.pop();
109
- const id = ++this.subscriptionId;
110
- this.subscriptions[method].callbacks[id] = callback;
111
- this.subscriptionMap[id] = method;
112
- if (this.subscriptions[method].lastValue !== null) {
113
- callback(null, this.subscriptions[method].lastValue);
114
- }
115
- return id;
116
- }
117
- // eslint-disable-next-line @typescript-eslint/require-await
118
- async unsubscribe(_type, _method, id) {
119
- const sub = this.subscriptionMap[id];
120
- l.debug(() => ['unsubscribe', id, sub]);
121
- if (!sub) {
122
- throw new Error(`Unable to find subscription for ${id}`);
123
- }
124
- delete this.subscriptionMap[id];
125
- delete this.subscriptions[sub].callbacks[id];
126
- return true;
127
- }
128
- init() {
129
- const emitEvents = ['connected', 'disconnected'];
130
- let emitIndex = 0;
131
- let newHead = this.makeBlockHeader();
132
- let counter = -1;
133
- const metadata = new Metadata(this.registry, rpcMetadata);
134
- this.registry.setMetadata(metadata);
135
- const query = decorateStorage(this.registry, metadata.asLatest, metadata.version);
136
- // Do something every 1 seconds
137
- this.intervalId = setInterval(() => {
138
- if (!this.isUpdating) {
139
- return;
140
- }
141
- // create a new header (next block)
142
- newHead = this.makeBlockHeader();
143
- // increment the balances and nonce for each account
144
- keyring.getPairs().forEach(({ publicKey }, index) => {
145
- this.setStateBn(query['system']['account'](publicKey), newHead.number.toBn().addn(index));
146
- });
147
- // set the timestamp for the current block
148
- this.setStateBn(query['timestamp']['now'](), Math.floor(Date.now() / 1000));
149
- this.updateSubs('chain_subscribeNewHead', newHead);
150
- // We emit connected/disconnected at intervals
151
- if (++counter % 2 === 1) {
152
- if (++emitIndex === emitEvents.length) {
153
- emitIndex = 0;
154
- }
155
- this.emitter.emit(emitEvents[emitIndex]);
156
- }
157
- }, INTERVAL);
158
- }
159
- makeBlockHeader() {
160
- const blockNumber = this.prevNumber.addn(1);
161
- const header = this.registry.createType('Header', {
162
- digest: {
163
- logs: []
164
- },
165
- extrinsicsRoot: randomAsU8a(),
166
- number: blockNumber,
167
- parentHash: blockNumber.isZero()
168
- ? new Uint8Array(32)
169
- : bnToU8a(this.prevNumber, { bitLength: 256, isLe: false }),
170
- stateRoot: bnToU8a(blockNumber, { bitLength: 256, isLe: false })
171
- });
172
- this.prevNumber = blockNumber;
173
- return header;
174
- }
175
- setStateBn(key, value) {
176
- this.db[u8aToHex(key)] = bnToU8a(value, { bitLength: 64, isLe: true });
177
- }
178
- updateSubs(method, value) {
179
- this.subscriptions[method].lastValue = value;
180
- Object
181
- .values(this.subscriptions[method].callbacks)
182
- .forEach((cb) => {
183
- try {
184
- cb(null, value.toJSON());
185
- }
186
- catch (error) {
187
- l.error(`Error on '${method}' subscription`, error);
188
- }
189
- });
190
- }
191
- }
@@ -1,12 +0,0 @@
1
- import nock from 'nock';
2
- export const TEST_HTTP_URL = 'http://localhost:9944';
3
- export function mockHttp(requests) {
4
- nock.cleanAll();
5
- return requests.reduce((scope, request) => scope
6
- .post('/')
7
- .reply(request.code || 200, (_uri, body) => {
8
- scope.body = scope.body || {};
9
- scope.body[request.method] = body;
10
- return Object.assign({ id: body.id, jsonrpc: '2.0' }, request.reply || {});
11
- }), nock(TEST_HTTP_URL));
12
- }
@@ -1,43 +0,0 @@
1
- import { Server, WebSocket } from 'mock-socket';
2
- import { stringify } from '@pezkuwi/util';
3
- global.WebSocket = WebSocket;
4
- export const TEST_WS_URL = 'ws://localhost:9955';
5
- function createError({ error: { code, message }, id }) {
6
- return {
7
- error: {
8
- code,
9
- message
10
- },
11
- id,
12
- jsonrpc: '2.0'
13
- };
14
- }
15
- function createReply({ id, reply: { result } }) {
16
- return {
17
- id,
18
- jsonrpc: '2.0',
19
- result
20
- };
21
- }
22
- export function mockWs(requests, wsUrl = TEST_WS_URL) {
23
- const server = new Server(wsUrl);
24
- let requestCount = 0;
25
- const scope = {
26
- body: {},
27
- done: () => new Promise((resolve) => server.stop(resolve)),
28
- requests: 0,
29
- server
30
- };
31
- server.on('connection', (socket) => {
32
- socket.on('message', (body) => {
33
- const request = requests[requestCount];
34
- const response = request.error
35
- ? createError(request)
36
- : createReply(request);
37
- scope.body[request.method] = body;
38
- requestCount++;
39
- socket.send(stringify(response));
40
- });
41
- });
42
- return scope;
43
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,4 +0,0 @@
1
- import { packageInfo as typesInfo } from '@pezkuwi/types/packageInfo';
2
- import { detectPackage } from '@pezkuwi/util';
3
- import { packageInfo } from './packageInfo.js';
4
- detectPackage(packageInfo, null, [typesInfo]);
@@ -1 +0,0 @@
1
- export const packageInfo = { name: '@pezkuwi/rpc-provider', path: (import.meta && import.meta.url) ? new URL(import.meta.url).pathname.substring(0, new URL(import.meta.url).pathname.lastIndexOf('/') + 1) : 'auto', type: 'esm', version: '16.5.8' };
@@ -1 +0,0 @@
1
- export {};