@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,196 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MockProvider = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const eventemitter3_1 = require("eventemitter3");
6
+ const testing_1 = require("@pezkuwi/keyring/testing");
7
+ const types_1 = require("@pezkuwi/types");
8
+ const jsonrpc_1 = tslib_1.__importDefault(require("@pezkuwi/types/interfaces/jsonrpc"));
9
+ const Header_004_json_1 = tslib_1.__importDefault(require("@pezkuwi/types-support/json/Header.004.json"));
10
+ const SignedBlock_004_immortal_json_1 = tslib_1.__importDefault(require("@pezkuwi/types-support/json/SignedBlock.004.immortal.json"));
11
+ const static_bizinikiwi_1 = tslib_1.__importDefault(require("@pezkuwi/types-support/metadata/static-bizinikiwi"));
12
+ const util_1 = require("@pezkuwi/util");
13
+ const util_crypto_1 = require("@pezkuwi/util-crypto");
14
+ const INTERVAL = 1000;
15
+ const SUBSCRIPTIONS = Array.prototype.concat.apply([], Object.values(jsonrpc_1.default).map((section) => Object
16
+ .values(section)
17
+ .filter(({ isSubscription }) => isSubscription)
18
+ .map(({ jsonrpc }) => jsonrpc)
19
+ .concat('chain_subscribeNewHead')));
20
+ const keyring = (0, testing_1.createTestKeyring)({ type: 'ed25519' });
21
+ const l = (0, util_1.logger)('api-mock');
22
+ /**
23
+ * A mock provider mainly used for testing.
24
+ * @return {ProviderInterface} The mock provider
25
+ * @internal
26
+ */
27
+ class MockProvider {
28
+ db = {};
29
+ emitter = new eventemitter3_1.EventEmitter();
30
+ intervalId;
31
+ isUpdating = true;
32
+ registry;
33
+ prevNumber = new util_1.BN(-1);
34
+ requests = {
35
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
36
+ chain_getBlock: () => this.registry.createType('SignedBlock', SignedBlock_004_immortal_json_1.default.result).toJSON(),
37
+ chain_getBlockHash: () => '0x1234000000000000000000000000000000000000000000000000000000000000',
38
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
39
+ chain_getFinalizedHead: () => this.registry.createType('Header', Header_004_json_1.default.result).hash,
40
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
41
+ chain_getHeader: () => this.registry.createType('Header', Header_004_json_1.default.result).toJSON(),
42
+ rpc_methods: () => this.registry.createType('RpcMethods').toJSON(),
43
+ state_getKeys: () => [],
44
+ state_getKeysPaged: () => [],
45
+ state_getMetadata: () => static_bizinikiwi_1.default,
46
+ state_getRuntimeVersion: () => this.registry.createType('RuntimeVersion').toHex(),
47
+ state_getStorage: (storage, [key]) => (0, util_1.u8aToHex)(storage[key]),
48
+ system_chain: () => 'mockChain',
49
+ system_health: () => ({}),
50
+ system_name: () => 'mockClient',
51
+ system_properties: () => ({ ss58Format: 42 }),
52
+ system_upgradedToTripleRefCount: () => this.registry.createType('bool', true),
53
+ system_version: () => '9.8.7',
54
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return, sort-keys
55
+ dev_echo: (_, params) => params
56
+ };
57
+ subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
58
+ subs[name] = {
59
+ callbacks: {},
60
+ lastValue: null
61
+ };
62
+ return subs;
63
+ }, {});
64
+ subscriptionId = 0;
65
+ subscriptionMap = {};
66
+ constructor(registry) {
67
+ this.registry = registry;
68
+ this.init();
69
+ }
70
+ get hasSubscriptions() {
71
+ return !!true;
72
+ }
73
+ clone() {
74
+ throw new Error('Unimplemented');
75
+ }
76
+ async connect() {
77
+ // noop
78
+ }
79
+ // eslint-disable-next-line @typescript-eslint/require-await
80
+ async disconnect() {
81
+ if (this.intervalId) {
82
+ clearInterval(this.intervalId);
83
+ this.intervalId = null;
84
+ }
85
+ }
86
+ get isClonable() {
87
+ return !!false;
88
+ }
89
+ get isConnected() {
90
+ return !!true;
91
+ }
92
+ on(type, sub) {
93
+ this.emitter.on(type, sub);
94
+ return () => {
95
+ this.emitter.removeListener(type, sub);
96
+ };
97
+ }
98
+ // eslint-disable-next-line @typescript-eslint/require-await
99
+ async send(method, params) {
100
+ l.debug(() => ['send', method, params]);
101
+ if (!this.requests[method]) {
102
+ throw new Error(`provider.send: Invalid method '${method}'`);
103
+ }
104
+ return this.requests[method](this.db, params);
105
+ }
106
+ // eslint-disable-next-line @typescript-eslint/require-await
107
+ async subscribe(_type, method, ...params) {
108
+ l.debug(() => ['subscribe', method, params]);
109
+ if (!this.subscriptions[method]) {
110
+ throw new Error(`provider.subscribe: Invalid method '${method}'`);
111
+ }
112
+ const callback = params.pop();
113
+ const id = ++this.subscriptionId;
114
+ this.subscriptions[method].callbacks[id] = callback;
115
+ this.subscriptionMap[id] = method;
116
+ if (this.subscriptions[method].lastValue !== null) {
117
+ callback(null, this.subscriptions[method].lastValue);
118
+ }
119
+ return id;
120
+ }
121
+ // eslint-disable-next-line @typescript-eslint/require-await
122
+ async unsubscribe(_type, _method, id) {
123
+ const sub = this.subscriptionMap[id];
124
+ l.debug(() => ['unsubscribe', id, sub]);
125
+ if (!sub) {
126
+ throw new Error(`Unable to find subscription for ${id}`);
127
+ }
128
+ delete this.subscriptionMap[id];
129
+ delete this.subscriptions[sub].callbacks[id];
130
+ return true;
131
+ }
132
+ init() {
133
+ const emitEvents = ['connected', 'disconnected'];
134
+ let emitIndex = 0;
135
+ let newHead = this.makeBlockHeader();
136
+ let counter = -1;
137
+ const metadata = new types_1.Metadata(this.registry, static_bizinikiwi_1.default);
138
+ this.registry.setMetadata(metadata);
139
+ const query = (0, types_1.decorateStorage)(this.registry, metadata.asLatest, metadata.version);
140
+ // Do something every 1 seconds
141
+ this.intervalId = setInterval(() => {
142
+ if (!this.isUpdating) {
143
+ return;
144
+ }
145
+ // create a new header (next block)
146
+ newHead = this.makeBlockHeader();
147
+ // increment the balances and nonce for each account
148
+ keyring.getPairs().forEach(({ publicKey }, index) => {
149
+ this.setStateBn(query['system']['account'](publicKey), newHead.number.toBn().addn(index));
150
+ });
151
+ // set the timestamp for the current block
152
+ this.setStateBn(query['timestamp']['now'](), Math.floor(Date.now() / 1000));
153
+ this.updateSubs('chain_subscribeNewHead', newHead);
154
+ // We emit connected/disconnected at intervals
155
+ if (++counter % 2 === 1) {
156
+ if (++emitIndex === emitEvents.length) {
157
+ emitIndex = 0;
158
+ }
159
+ this.emitter.emit(emitEvents[emitIndex]);
160
+ }
161
+ }, INTERVAL);
162
+ }
163
+ makeBlockHeader() {
164
+ const blockNumber = this.prevNumber.addn(1);
165
+ const header = this.registry.createType('Header', {
166
+ digest: {
167
+ logs: []
168
+ },
169
+ extrinsicsRoot: (0, util_crypto_1.randomAsU8a)(),
170
+ number: blockNumber,
171
+ parentHash: blockNumber.isZero()
172
+ ? new Uint8Array(32)
173
+ : (0, util_1.bnToU8a)(this.prevNumber, { bitLength: 256, isLe: false }),
174
+ stateRoot: (0, util_1.bnToU8a)(blockNumber, { bitLength: 256, isLe: false })
175
+ });
176
+ this.prevNumber = blockNumber;
177
+ return header;
178
+ }
179
+ setStateBn(key, value) {
180
+ this.db[(0, util_1.u8aToHex)(key)] = (0, util_1.bnToU8a)(value, { bitLength: 64, isLe: true });
181
+ }
182
+ updateSubs(method, value) {
183
+ this.subscriptions[method].lastValue = value;
184
+ Object
185
+ .values(this.subscriptions[method].callbacks)
186
+ .forEach((cb) => {
187
+ try {
188
+ cb(null, value.toJSON());
189
+ }
190
+ catch (error) {
191
+ l.error(`Error on '${method}' subscription`, error);
192
+ }
193
+ });
194
+ }
195
+ }
196
+ exports.MockProvider = MockProvider;
@@ -0,0 +1,9 @@
1
+ import type { Mock } from './types.js';
2
+ interface Request {
3
+ code?: number;
4
+ method: string;
5
+ reply?: Record<string, unknown>;
6
+ }
7
+ export declare const TEST_HTTP_URL = "http://localhost:9944";
8
+ export declare function mockHttp(requests: Request[]): Mock;
9
+ export {};
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEST_HTTP_URL = void 0;
4
+ exports.mockHttp = mockHttp;
5
+ const tslib_1 = require("tslib");
6
+ const nock_1 = tslib_1.__importDefault(require("nock"));
7
+ exports.TEST_HTTP_URL = 'http://localhost:9944';
8
+ function mockHttp(requests) {
9
+ nock_1.default.cleanAll();
10
+ return requests.reduce((scope, request) => scope
11
+ .post('/')
12
+ .reply(request.code || 200, (_uri, body) => {
13
+ scope.body = scope.body || {};
14
+ scope.body[request.method] = body;
15
+ return Object.assign({ id: body.id, jsonrpc: '2.0' }, request.reply || {});
16
+ }), (0, nock_1.default)(exports.TEST_HTTP_URL));
17
+ }
@@ -0,0 +1,26 @@
1
+ import { Server } from 'mock-socket';
2
+ interface Scope {
3
+ body: Record<string, Record<string, unknown>>;
4
+ requests: number;
5
+ server: Server;
6
+ done: any;
7
+ }
8
+ interface ErrorDef {
9
+ id: number;
10
+ error: {
11
+ code: number;
12
+ message: string;
13
+ };
14
+ }
15
+ interface ReplyDef {
16
+ id: number;
17
+ reply: {
18
+ result: unknown;
19
+ };
20
+ }
21
+ export type Request = {
22
+ method: string;
23
+ } & (ErrorDef | ReplyDef);
24
+ export declare const TEST_WS_URL = "ws://localhost:9955";
25
+ export declare function mockWs(requests: Request[], wsUrl?: string): Scope;
26
+ export {};
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEST_WS_URL = void 0;
4
+ exports.mockWs = mockWs;
5
+ const mock_socket_1 = require("mock-socket");
6
+ const util_1 = require("@pezkuwi/util");
7
+ global.WebSocket = mock_socket_1.WebSocket;
8
+ exports.TEST_WS_URL = 'ws://localhost:9955';
9
+ function createError({ error: { code, message }, id }) {
10
+ return {
11
+ error: {
12
+ code,
13
+ message
14
+ },
15
+ id,
16
+ jsonrpc: '2.0'
17
+ };
18
+ }
19
+ function createReply({ id, reply: { result } }) {
20
+ return {
21
+ id,
22
+ jsonrpc: '2.0',
23
+ result
24
+ };
25
+ }
26
+ function mockWs(requests, wsUrl = exports.TEST_WS_URL) {
27
+ const server = new mock_socket_1.Server(wsUrl);
28
+ let requestCount = 0;
29
+ const scope = {
30
+ body: {},
31
+ done: () => new Promise((resolve) => server.stop(resolve)),
32
+ requests: 0,
33
+ server
34
+ };
35
+ server.on('connection', (socket) => {
36
+ socket.on('message', (body) => {
37
+ const request = requests[requestCount];
38
+ const response = request.error
39
+ ? createError(request)
40
+ : createReply(request);
41
+ scope.body[request.method] = body;
42
+ requestCount++;
43
+ socket.send((0, util_1.stringify)(response));
44
+ });
45
+ });
46
+ return scope;
47
+ }
@@ -0,0 +1,23 @@
1
+ import type { Server } from 'mock-socket';
2
+ export type Global = typeof globalThis & {
3
+ WebSocket: typeof WebSocket;
4
+ fetch: any;
5
+ };
6
+ export interface Mock {
7
+ body: Record<string, Record<string, unknown>>;
8
+ requests: number;
9
+ server: Server;
10
+ done: () => Promise<void>;
11
+ }
12
+ export type MockStateSubscriptionCallback = (error: Error | null, value: any) => void;
13
+ export interface MockStateSubscription {
14
+ callbacks: Record<number, MockStateSubscriptionCallback>;
15
+ lastValue: any;
16
+ }
17
+ export interface MockStateSubscriptions {
18
+ chain_subscribeNewHead: MockStateSubscription;
19
+ state_subscribeStorage: MockStateSubscription;
20
+ [key: string]: MockStateSubscription;
21
+ }
22
+ export type MockStateDb = Record<string, Uint8Array>;
23
+ export type MockStateRequests = Record<string, (db: MockStateDb, params: any[]) => string>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const packageInfo_1 = require("@pezkuwi/types/cjs/packageInfo");
4
+ const util_1 = require("@pezkuwi/util");
5
+ const packageInfo_js_1 = require("./packageInfo.js");
6
+ (0, util_1.detectPackage)(packageInfo_js_1.packageInfo, null, [packageInfo_1.packageInfo]);
@@ -0,0 +1,6 @@
1
+ export declare const packageInfo: {
2
+ name: string;
3
+ path: string;
4
+ type: string;
5
+ version: string;
6
+ };
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.packageInfo = void 0;
4
+ exports.packageInfo = { name: '@pezkuwi/rpc-provider', path: typeof __dirname === 'string' ? __dirname : 'auto', type: 'cjs', version: '16.5.8' };
package/cjs/types.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ export interface JsonRpcObject {
2
+ id: number;
3
+ jsonrpc: '2.0';
4
+ }
5
+ export interface JsonRpcRequest extends JsonRpcObject {
6
+ method: string;
7
+ params: unknown[];
8
+ }
9
+ export interface JsonRpcResponseBaseError {
10
+ code: number;
11
+ data?: number | string;
12
+ message: string;
13
+ }
14
+ export interface RpcErrorInterface<T> {
15
+ code: number;
16
+ data?: T;
17
+ message: string;
18
+ stack: string;
19
+ }
20
+ interface JsonRpcResponseSingle<T> {
21
+ error?: JsonRpcResponseBaseError;
22
+ result: T;
23
+ }
24
+ interface JsonRpcResponseSubscription<T> {
25
+ method?: string;
26
+ params: {
27
+ error?: JsonRpcResponseBaseError;
28
+ result: T;
29
+ subscription: number | string;
30
+ };
31
+ }
32
+ export type JsonRpcResponseBase<T> = JsonRpcResponseSingle<T> & JsonRpcResponseSubscription<T>;
33
+ export type JsonRpcResponse<T> = JsonRpcObject & JsonRpcResponseBase<T>;
34
+ export type ProviderInterfaceCallback = (error: Error | null, result: any) => void;
35
+ export type ProviderInterfaceEmitted = 'connected' | 'disconnected' | 'error';
36
+ export type ProviderInterfaceEmitCb = (value?: any) => any;
37
+ export interface ProviderInterface {
38
+ /** true if the provider supports subscriptions (not available for HTTP) */
39
+ readonly hasSubscriptions: boolean;
40
+ /** true if the clone() functionality is available on the provider */
41
+ readonly isClonable: boolean;
42
+ /** true if the provider is currently connected (ws/sc has connection logic) */
43
+ readonly isConnected: boolean;
44
+ /** (optional) stats for the provider with connections/bytes */
45
+ readonly stats?: ProviderStats;
46
+ /** (optional) stats for the provider with connections/bytes */
47
+ readonly ttl?: number | null;
48
+ clone(): ProviderInterface;
49
+ connect(): Promise<void>;
50
+ disconnect(): Promise<void>;
51
+ on(type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
52
+ send<T = any>(method: string, params: unknown[], isCacheable?: boolean): Promise<T>;
53
+ subscribe(type: string, method: string, params: unknown[], cb: ProviderInterfaceCallback): Promise<number | string>;
54
+ unsubscribe(type: string, method: string, id: number | string): Promise<boolean>;
55
+ }
56
+ /** Stats for a specific endpoint */
57
+ export interface EndpointStats {
58
+ /** The total number of bytes sent */
59
+ bytesRecv: number;
60
+ /** The total number of bytes received */
61
+ bytesSent: number;
62
+ /** The number of cached/in-progress requests made */
63
+ cached: number;
64
+ /** The number of errors found */
65
+ errors: number;
66
+ /** The number of requests */
67
+ requests: number;
68
+ /** The number of subscriptions */
69
+ subscriptions: number;
70
+ /** The number of request timeouts */
71
+ timeout: number;
72
+ }
73
+ /** Overall stats for the provider */
74
+ export interface ProviderStats {
75
+ /** Details for the active/open requests */
76
+ active: {
77
+ /** Number of active requests */
78
+ requests: number;
79
+ /** Number of active subscriptions */
80
+ subscriptions: number;
81
+ };
82
+ /** The total requests that have been made */
83
+ total: EndpointStats;
84
+ }
85
+ export {};
package/cjs/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export declare function getWSErrorString(code: number): string;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getWSErrorString = getWSErrorString;
4
+ const known = {
5
+ 1000: 'Normal Closure',
6
+ 1001: 'Going Away',
7
+ 1002: 'Protocol Error',
8
+ 1003: 'Unsupported Data',
9
+ 1004: '(For future)',
10
+ 1005: 'No Status Received',
11
+ 1006: 'Abnormal Closure',
12
+ 1007: 'Invalid frame payload data',
13
+ 1008: 'Policy Violation',
14
+ 1009: 'Message too big',
15
+ 1010: 'Missing Extension',
16
+ 1011: 'Internal Error',
17
+ 1012: 'Service Restart',
18
+ 1013: 'Try Again Later',
19
+ 1014: 'Bad Gateway',
20
+ 1015: 'TLS Handshake'
21
+ };
22
+ function getWSErrorString(code) {
23
+ if (code >= 0 && code <= 999) {
24
+ return '(Unused)';
25
+ }
26
+ else if (code >= 1016) {
27
+ if (code <= 1999) {
28
+ return '(For WebSocket standard)';
29
+ }
30
+ else if (code <= 2999) {
31
+ return '(For WebSocket extensions)';
32
+ }
33
+ else if (code <= 3999) {
34
+ return '(For libraries and frameworks)';
35
+ }
36
+ else if (code <= 4999) {
37
+ return '(For applications)';
38
+ }
39
+ }
40
+ return known[code] || '(Unknown)';
41
+ }
@@ -0,0 +1,121 @@
1
+ import type { EndpointStats, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types.js';
2
+ interface SubscriptionHandler {
3
+ callback: ProviderInterfaceCallback;
4
+ type: string;
5
+ }
6
+ /**
7
+ * # @pezkuwi/rpc-provider/ws
8
+ *
9
+ * @name WsProvider
10
+ *
11
+ * @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes.
12
+ *
13
+ * @example
14
+ * <BR>
15
+ *
16
+ * ```javascript
17
+ * import Api from '@pezkuwi/api/promise';
18
+ * import { WsProvider } from '@pezkuwi/rpc-provider/ws';
19
+ *
20
+ * const provider = new WsProvider('ws://127.0.0.1:9944');
21
+ * const api = new Api(provider);
22
+ * ```
23
+ *
24
+ * @see [[HttpProvider]]
25
+ */
26
+ export declare class WsProvider implements ProviderInterface {
27
+ #private;
28
+ /**
29
+ * @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
30
+ * @param {number | false} autoConnectMs Whether to connect automatically or not (default). Provided value is used as a delay between retries.
31
+ * @param {Record<string, string>} headers The headers provided to the underlying WebSocket
32
+ * @param {number} [timeout] Custom timeout value used per request . Defaults to `DEFAULT_TIMEOUT_MS`
33
+ * @param {number} [cacheCapacity] Custom size of the WsProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
34
+ * @param {number} [cacheTtl] Custom TTL of the WsProvider LRUCache. Determines how long an object can live in the cache. Defaults to DEFAULT_TTL` (30000)
35
+ */
36
+ constructor(endpoint?: string | string[], autoConnectMs?: number | false, headers?: Record<string, string>, timeout?: number, cacheCapacity?: number, cacheTtl?: number | null);
37
+ /**
38
+ * @summary `true` when this provider supports subscriptions
39
+ */
40
+ get hasSubscriptions(): boolean;
41
+ /**
42
+ * @summary `true` when this provider supports clone()
43
+ */
44
+ get isClonable(): boolean;
45
+ /**
46
+ * @summary Whether the node is connected or not.
47
+ * @return {boolean} true if connected
48
+ */
49
+ get isConnected(): boolean;
50
+ /**
51
+ * @description Promise that resolves the first time we are connected and loaded
52
+ */
53
+ get isReady(): Promise<WsProvider>;
54
+ get endpoint(): string;
55
+ /**
56
+ * @description Returns a clone of the object
57
+ */
58
+ clone(): WsProvider;
59
+ protected selectEndpointIndex(endpoints: string[]): number;
60
+ /**
61
+ * @summary Manually connect
62
+ * @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may
63
+ * connect manually using this method.
64
+ */
65
+ connect(): Promise<void>;
66
+ /**
67
+ * @description Connect, never throwing an error, but rather forcing a retry
68
+ */
69
+ connectWithRetry(): Promise<void>;
70
+ /**
71
+ * @description Manually disconnect from the connection, clearing auto-connect logic
72
+ */
73
+ disconnect(): Promise<void>;
74
+ /**
75
+ * @description Returns the connection stats
76
+ */
77
+ get stats(): ProviderStats;
78
+ /**
79
+ * @description Returns the connection stats
80
+ */
81
+ get ttl(): number | null | undefined;
82
+ get endpointStats(): EndpointStats;
83
+ /**
84
+ * @summary Listens on events after having subscribed using the [[subscribe]] function.
85
+ * @param {ProviderInterfaceEmitted} type Event
86
+ * @param {ProviderInterfaceEmitCb} sub Callback
87
+ * @return unsubscribe function
88
+ */
89
+ on(type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
90
+ /**
91
+ * @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue.
92
+ * @param method The RPC methods to execute
93
+ * @param params Encoded parameters as applicable for the method
94
+ * @param subscription Subscription details (internally used)
95
+ */
96
+ send<T = any>(method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise<T>;
97
+ /**
98
+ * @name subscribe
99
+ * @summary Allows subscribing to a specific event.
100
+ *
101
+ * @example
102
+ * <BR>
103
+ *
104
+ * ```javascript
105
+ * const provider = new WsProvider('ws://127.0.0.1:9944');
106
+ * const rpc = new Rpc(provider);
107
+ *
108
+ * rpc.state.subscribeStorage([[storage.system.account, <Address>]], (_, values) => {
109
+ * console.log(values)
110
+ * }).then((subscriptionId) => {
111
+ * console.log('balance changes subscription id: ', subscriptionId)
112
+ * })
113
+ * ```
114
+ */
115
+ subscribe(type: string, method: string, params: unknown[], callback: ProviderInterfaceCallback): Promise<number | string>;
116
+ /**
117
+ * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
118
+ */
119
+ unsubscribe(type: string, method: string, id: number | string): Promise<boolean>;
120
+ }
121
+ export {};