@pezkuwi/rpc-provider 16.5.8 → 16.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/cjs/packageInfo.js +1 -1
  2. package/package.json +12 -12
  3. package/packageInfo.js +1 -1
  4. package/build/LICENSE +0 -201
  5. package/build/README.md +0 -68
  6. package/build/bizinikiwi-connect/Health.d.ts +0 -7
  7. package/build/bizinikiwi-connect/Health.js +0 -259
  8. package/build/bizinikiwi-connect/index.d.ts +0 -22
  9. package/build/bizinikiwi-connect/index.js +0 -319
  10. package/build/bizinikiwi-connect/types.d.ts +0 -12
  11. package/build/bizinikiwi-connect/types.js +0 -1
  12. package/build/bundle.d.ts +0 -5
  13. package/build/bundle.js +0 -5
  14. package/build/cjs/bizinikiwi-connect/Health.d.ts +0 -7
  15. package/build/cjs/bizinikiwi-connect/Health.js +0 -264
  16. package/build/cjs/bizinikiwi-connect/index.d.ts +0 -22
  17. package/build/cjs/bizinikiwi-connect/index.js +0 -323
  18. package/build/cjs/bizinikiwi-connect/types.d.ts +0 -12
  19. package/build/cjs/bizinikiwi-connect/types.js +0 -2
  20. package/build/cjs/bundle.d.ts +0 -5
  21. package/build/cjs/bundle.js +0 -14
  22. package/build/cjs/coder/error.d.ts +0 -29
  23. package/build/cjs/coder/error.js +0 -53
  24. package/build/cjs/coder/index.d.ts +0 -8
  25. package/build/cjs/coder/index.js +0 -63
  26. package/build/cjs/defaults.d.ts +0 -5
  27. package/build/cjs/defaults.js +0 -8
  28. package/build/cjs/http/index.d.ts +0 -81
  29. package/build/cjs/http/index.js +0 -196
  30. package/build/cjs/http/types.d.ts +0 -7
  31. package/build/cjs/http/types.js +0 -2
  32. package/build/cjs/index.d.ts +0 -2
  33. package/build/cjs/index.js +0 -5
  34. package/build/cjs/lru.d.ts +0 -15
  35. package/build/cjs/lru.js +0 -150
  36. package/build/cjs/mock/index.d.ts +0 -35
  37. package/build/cjs/mock/index.js +0 -196
  38. package/build/cjs/mock/mockHttp.d.ts +0 -9
  39. package/build/cjs/mock/mockHttp.js +0 -17
  40. package/build/cjs/mock/mockWs.d.ts +0 -26
  41. package/build/cjs/mock/mockWs.js +0 -47
  42. package/build/cjs/mock/types.d.ts +0 -23
  43. package/build/cjs/mock/types.js +0 -2
  44. package/build/cjs/package.json +0 -3
  45. package/build/cjs/packageDetect.d.ts +0 -1
  46. package/build/cjs/packageDetect.js +0 -6
  47. package/build/cjs/packageInfo.d.ts +0 -6
  48. package/build/cjs/packageInfo.js +0 -4
  49. package/build/cjs/types.d.ts +0 -85
  50. package/build/cjs/types.js +0 -2
  51. package/build/cjs/ws/errors.d.ts +0 -1
  52. package/build/cjs/ws/errors.js +0 -41
  53. package/build/cjs/ws/index.d.ts +0 -121
  54. package/build/cjs/ws/index.js +0 -529
  55. package/build/coder/error.d.ts +0 -29
  56. package/build/coder/error.js +0 -50
  57. package/build/coder/index.d.ts +0 -8
  58. package/build/coder/index.js +0 -58
  59. package/build/defaults.d.ts +0 -5
  60. package/build/defaults.js +0 -6
  61. package/build/http/index.d.ts +0 -81
  62. package/build/http/index.js +0 -191
  63. package/build/http/types.d.ts +0 -7
  64. package/build/http/types.js +0 -1
  65. package/build/index.d.ts +0 -2
  66. package/build/index.js +0 -2
  67. package/build/lru.d.ts +0 -15
  68. package/build/lru.js +0 -146
  69. package/build/mock/index.d.ts +0 -35
  70. package/build/mock/index.js +0 -191
  71. package/build/mock/mockHttp.d.ts +0 -9
  72. package/build/mock/mockHttp.js +0 -12
  73. package/build/mock/mockWs.d.ts +0 -26
  74. package/build/mock/mockWs.js +0 -43
  75. package/build/mock/types.d.ts +0 -23
  76. package/build/mock/types.js +0 -1
  77. package/build/package.json +0 -344
  78. package/build/packageDetect.d.ts +0 -1
  79. package/build/packageDetect.js +0 -4
  80. package/build/packageInfo.d.ts +0 -6
  81. package/build/packageInfo.js +0 -1
  82. package/build/types.d.ts +0 -85
  83. package/build/types.js +0 -1
  84. package/build/ws/errors.d.ts +0 -1
  85. package/build/ws/errors.js +0 -38
  86. package/build/ws/index.d.ts +0 -121
  87. package/build/ws/index.js +0 -524
  88. package/build-deno/README.md +0 -66
  89. package/build-deno/bizinikiwi-connect/Health.ts +0 -323
  90. package/build-deno/bizinikiwi-connect/index.ts +0 -417
  91. package/build-deno/bizinikiwi-connect/types.ts +0 -14
  92. package/build-deno/bundle.ts +0 -6
  93. package/build-deno/coder/error.ts +0 -64
  94. package/build-deno/coder/index.ts +0 -86
  95. package/build-deno/defaults.ts +0 -8
  96. package/build-deno/http/index.ts +0 -236
  97. package/build-deno/http/types.ts +0 -9
  98. package/build-deno/index.ts +0 -4
  99. package/build-deno/lru.ts +0 -189
  100. package/build-deno/mock/index.ts +0 -257
  101. package/build-deno/mock/mockHttp.ts +0 -33
  102. package/build-deno/mock/mockWs.ts +0 -87
  103. package/build-deno/mock/types.ts +0 -34
  104. package/build-deno/mod.ts +0 -2
  105. package/build-deno/packageDetect.ts +0 -8
  106. package/build-deno/packageInfo.ts +0 -3
  107. package/build-deno/types.ts +0 -99
  108. package/build-deno/ws/errors.ts +0 -38
  109. package/build-deno/ws/index.ts +0 -650
  110. package/build-tsc/bizinikiwi-connect/Health.d.ts +0 -7
  111. package/build-tsc/bizinikiwi-connect/index.d.ts +0 -22
  112. package/build-tsc/bizinikiwi-connect/types.d.ts +0 -12
  113. package/build-tsc/bundle.d.ts +0 -5
  114. package/build-tsc/coder/error.d.ts +0 -29
  115. package/build-tsc/coder/index.d.ts +0 -8
  116. package/build-tsc/defaults.d.ts +0 -5
  117. package/build-tsc/http/index.d.ts +0 -81
  118. package/build-tsc/http/types.d.ts +0 -7
  119. package/build-tsc/index.d.ts +0 -2
  120. package/build-tsc/lru.d.ts +0 -15
  121. package/build-tsc/mock/index.d.ts +0 -35
  122. package/build-tsc/mock/mockHttp.d.ts +0 -9
  123. package/build-tsc/mock/mockWs.d.ts +0 -26
  124. package/build-tsc/mock/types.d.ts +0 -23
  125. package/build-tsc/packageDetect.d.ts +0 -1
  126. package/build-tsc/packageInfo.d.ts +0 -6
  127. package/build-tsc/types.d.ts +0 -85
  128. package/build-tsc/ws/errors.d.ts +0 -1
  129. package/build-tsc/ws/index.d.ts +0 -121
  130. package/build-tsc-cjs/bizinikiwi-connect/Health.js +0 -264
  131. package/build-tsc-cjs/bizinikiwi-connect/index.js +0 -323
  132. package/build-tsc-cjs/bizinikiwi-connect/types.js +0 -2
  133. package/build-tsc-cjs/bundle.js +0 -14
  134. package/build-tsc-cjs/coder/error.js +0 -53
  135. package/build-tsc-cjs/coder/index.js +0 -63
  136. package/build-tsc-cjs/defaults.js +0 -8
  137. package/build-tsc-cjs/http/index.js +0 -196
  138. package/build-tsc-cjs/http/types.js +0 -2
  139. package/build-tsc-cjs/index.js +0 -5
  140. package/build-tsc-cjs/lru.js +0 -150
  141. package/build-tsc-cjs/mock/index.js +0 -196
  142. package/build-tsc-cjs/mock/mockHttp.js +0 -17
  143. package/build-tsc-cjs/mock/mockWs.js +0 -47
  144. package/build-tsc-cjs/mock/types.js +0 -2
  145. package/build-tsc-cjs/packageDetect.js +0 -6
  146. package/build-tsc-cjs/packageInfo.js +0 -4
  147. package/build-tsc-cjs/types.js +0 -2
  148. package/build-tsc-cjs/ws/errors.js +0 -41
  149. package/build-tsc-cjs/ws/index.js +0 -529
  150. package/build-tsc-esm/bizinikiwi-connect/Health.js +0 -259
  151. package/build-tsc-esm/bizinikiwi-connect/index.js +0 -319
  152. package/build-tsc-esm/bizinikiwi-connect/types.js +0 -1
  153. package/build-tsc-esm/bundle.js +0 -5
  154. package/build-tsc-esm/coder/error.js +0 -50
  155. package/build-tsc-esm/coder/index.js +0 -58
  156. package/build-tsc-esm/defaults.js +0 -6
  157. package/build-tsc-esm/http/index.js +0 -191
  158. package/build-tsc-esm/http/types.js +0 -1
  159. package/build-tsc-esm/index.js +0 -2
  160. package/build-tsc-esm/lru.js +0 -146
  161. package/build-tsc-esm/mock/index.js +0 -191
  162. package/build-tsc-esm/mock/mockHttp.js +0 -12
  163. package/build-tsc-esm/mock/mockWs.js +0 -43
  164. package/build-tsc-esm/mock/types.js +0 -1
  165. package/build-tsc-esm/packageDetect.js +0 -4
  166. package/build-tsc-esm/packageInfo.js +0 -1
  167. package/build-tsc-esm/types.js +0 -1
  168. package/build-tsc-esm/ws/errors.js +0 -38
  169. package/build-tsc-esm/ws/index.js +0 -524
  170. package/src/bizinikiwi-connect/Health.ts +0 -325
  171. package/src/bizinikiwi-connect/index.spec.ts +0 -671
  172. package/src/bizinikiwi-connect/index.ts +0 -427
  173. package/src/bizinikiwi-connect/types.ts +0 -16
  174. package/src/bundle.ts +0 -8
  175. package/src/coder/decodeResponse.spec.ts +0 -70
  176. package/src/coder/encodeJson.spec.ts +0 -20
  177. package/src/coder/encodeObject.spec.ts +0 -25
  178. package/src/coder/error.spec.ts +0 -111
  179. package/src/coder/error.ts +0 -66
  180. package/src/coder/index.ts +0 -88
  181. package/src/defaults.ts +0 -10
  182. package/src/http/index.spec.ts +0 -72
  183. package/src/http/index.ts +0 -238
  184. package/src/http/send.spec.ts +0 -61
  185. package/src/http/types.ts +0 -11
  186. package/src/index.ts +0 -6
  187. package/src/lru.spec.ts +0 -74
  188. package/src/lru.ts +0 -197
  189. package/src/mock/index.ts +0 -259
  190. package/src/mock/mockHttp.ts +0 -35
  191. package/src/mock/mockWs.ts +0 -92
  192. package/src/mock/on.spec.ts +0 -43
  193. package/src/mock/send.spec.ts +0 -38
  194. package/src/mock/subscribe.spec.ts +0 -81
  195. package/src/mock/types.ts +0 -36
  196. package/src/mock/unsubscribe.spec.ts +0 -57
  197. package/src/mod.ts +0 -4
  198. package/src/packageDetect.ts +0 -12
  199. package/src/packageInfo.ts +0 -6
  200. package/src/types.ts +0 -101
  201. package/src/ws/connect.spec.ts +0 -167
  202. package/src/ws/errors.ts +0 -41
  203. package/src/ws/index.spec.ts +0 -97
  204. package/src/ws/index.ts +0 -652
  205. package/src/ws/send.spec.ts +0 -126
  206. package/src/ws/state.spec.ts +0 -20
  207. package/src/ws/subscribe.spec.ts +0 -68
  208. package/src/ws/unsubscribe.spec.ts +0 -100
  209. package/tsconfig.build.json +0 -17
  210. package/tsconfig.build.tsbuildinfo +0 -1
  211. package/tsconfig.spec.json +0 -18
  212. package/tsconfig.spec.tsbuildinfo +0 -1
package/src/lru.ts DELETED
@@ -1,197 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- // Assuming all 1.5MB responses, we apply a default allowing for 192MB
5
- // cache space (depending on the historic queries this would vary, metadata
6
- // for Zagros/Pezkuwi/Bizinikiwi falls between 600-750K, 2x for estimate)
7
-
8
- export const DEFAULT_CAPACITY = 1024;
9
- export const DEFAULT_TTL = 30000; // 30 seconds
10
- const MAX_TTL = 1800_000; // 30 minutes
11
-
12
- // If the user decides to disable the TTL we set the value
13
- // to a very high number (A year = 365 * 24 * 60 * 60 * 1000).
14
- const DISABLED_TTL = 31_536_000_000;
15
-
16
- class LRUNode {
17
- readonly key: string;
18
- #expires: number;
19
- #ttl: number;
20
- readonly createdAt: number;
21
-
22
- public next: LRUNode;
23
- public prev: LRUNode;
24
-
25
- constructor (key: string, ttl: number) {
26
- this.key = key;
27
- this.#ttl = ttl;
28
- this.#expires = Date.now() + ttl;
29
- this.createdAt = Date.now();
30
- this.next = this.prev = this;
31
- }
32
-
33
- public refresh (): void {
34
- this.#expires = Date.now() + this.#ttl;
35
- }
36
-
37
- public get expiry (): number {
38
- return this.#expires;
39
- }
40
- }
41
-
42
- // https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
43
- export class LRUCache {
44
- readonly capacity: number;
45
-
46
- readonly #data = new Map<string, unknown>();
47
- readonly #refs = new Map<string, LRUNode>();
48
-
49
- #length = 0;
50
- #head: LRUNode;
51
- #tail: LRUNode;
52
-
53
- readonly #ttl: number;
54
-
55
- constructor (capacity = DEFAULT_CAPACITY, ttl: number | null = DEFAULT_TTL) {
56
- // Validate capacity
57
- if (!Number.isInteger(capacity) || capacity < 0) {
58
- throw new Error(`LRUCache initialization error: 'capacity' must be a non-negative integer. Received: ${capacity}`);
59
- }
60
-
61
- // Validate ttl
62
- if (ttl !== null && (!Number.isFinite(ttl) || ttl < 0 || ttl > MAX_TTL)) {
63
- throw new Error(`LRUCache initialization error: 'ttl' must be between 0 and ${MAX_TTL} ms or null to disable. Received: ${ttl}`);
64
- }
65
-
66
- this.capacity = capacity;
67
- ttl ? this.#ttl = ttl : this.#ttl = DISABLED_TTL;
68
- this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
69
- }
70
-
71
- get ttl (): number | null {
72
- return this.#ttl;
73
- }
74
-
75
- get length (): number {
76
- return this.#length;
77
- }
78
-
79
- get lengthData (): number {
80
- return this.#data.size;
81
- }
82
-
83
- get lengthRefs (): number {
84
- return this.#refs.size;
85
- }
86
-
87
- entries (): [string, unknown][] {
88
- const keys = this.keys();
89
- const count = keys.length;
90
- const entries = new Array<[string, unknown]>(count);
91
-
92
- for (let i = 0; i < count; i++) {
93
- const key = keys[i];
94
-
95
- entries[i] = [key, this.#data.get(key)];
96
- }
97
-
98
- return entries;
99
- }
100
-
101
- keys (): string[] {
102
- const keys: string[] = [];
103
-
104
- if (this.#length) {
105
- let curr = this.#head;
106
-
107
- while (curr !== this.#tail) {
108
- keys.push(curr.key);
109
- curr = curr.next;
110
- }
111
-
112
- keys.push(curr.key);
113
- }
114
-
115
- return keys;
116
- }
117
-
118
- get <T> (key: string): T | null {
119
- const data = this.#data.get(key);
120
-
121
- if (data) {
122
- this.#toHead(key);
123
-
124
- // Evict TTL once data is refreshed
125
- this.#evictTTL();
126
-
127
- return data as T;
128
- }
129
-
130
- this.#evictTTL();
131
-
132
- return null;
133
- }
134
-
135
- set <T> (key: string, value: T): void {
136
- if (this.#data.has(key)) {
137
- this.#toHead(key);
138
- } else {
139
- const node = new LRUNode(key, this.#ttl);
140
-
141
- this.#refs.set(node.key, node);
142
-
143
- if (this.length === 0) {
144
- this.#head = this.#tail = node;
145
- } else {
146
- this.#head.prev = node;
147
- node.next = this.#head;
148
- this.#head = node;
149
- }
150
-
151
- if (this.#length === this.capacity) {
152
- this.#data.delete(this.#tail.key);
153
- this.#refs.delete(this.#tail.key);
154
-
155
- this.#tail = this.#tail.prev;
156
- this.#tail.next = this.#head;
157
- } else {
158
- this.#length += 1;
159
- }
160
- }
161
-
162
- // Evict TTL once data is refreshed or added
163
- this.#evictTTL();
164
-
165
- this.#data.set(key, value);
166
- }
167
-
168
- #evictTTL () {
169
- // Find last node to keep
170
- // traverse map to find the expired nodes
171
- while (this.#tail.expiry && this.#tail.expiry < Date.now() && this.#length > 0) {
172
- this.#refs.delete(this.#tail.key);
173
- this.#data.delete(this.#tail.key);
174
- this.#length -= 1;
175
- this.#tail = this.#tail.prev;
176
- this.#tail.next = this.#head;
177
- }
178
-
179
- if (this.#length === 0) {
180
- this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
181
- }
182
- }
183
-
184
- #toHead (key: string): void {
185
- const ref = this.#refs.get(key);
186
-
187
- if (ref && ref !== this.#head) {
188
- ref.refresh();
189
- ref.prev.next = ref.next;
190
- ref.next.prev = ref.prev;
191
- ref.next = this.#head;
192
-
193
- this.#head.prev = ref;
194
- this.#head = ref;
195
- }
196
- }
197
- }
package/src/mock/index.ts DELETED
@@ -1,259 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /* eslint-disable camelcase */
5
-
6
- import type { Header } from '@pezkuwi/types/interfaces';
7
- import type { Codec, Registry } from '@pezkuwi/types/types';
8
- import type { ProviderInterface, ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '../types.js';
9
- import type { MockStateDb, MockStateSubscriptionCallback, MockStateSubscriptions } from './types.js';
10
-
11
- import { EventEmitter } from 'eventemitter3';
12
-
13
- import { createTestKeyring } from '@pezkuwi/keyring/testing';
14
- import { decorateStorage, Metadata } from '@pezkuwi/types';
15
- import jsonrpc from '@pezkuwi/types/interfaces/jsonrpc';
16
- import rpcHeader from '@pezkuwi/types-support/json/Header.004.json' assert { type: 'json' };
17
- import rpcSignedBlock from '@pezkuwi/types-support/json/SignedBlock.004.immortal.json' assert { type: 'json' };
18
- import rpcMetadata from '@pezkuwi/types-support/metadata/static-bizinikiwi';
19
- import { BN, bnToU8a, logger, u8aToHex } from '@pezkuwi/util';
20
- import { randomAsU8a } from '@pezkuwi/util-crypto';
21
-
22
- const INTERVAL = 1000;
23
- const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
24
- [],
25
- Object.values(jsonrpc).map((section): string[] =>
26
- Object
27
- .values(section)
28
- .filter(({ isSubscription }) => isSubscription)
29
- .map(({ jsonrpc }) => jsonrpc)
30
- .concat('chain_subscribeNewHead')
31
- )
32
- ) as string[];
33
-
34
- const keyring = createTestKeyring({ type: 'ed25519' });
35
- const l = logger('api-mock');
36
-
37
- /**
38
- * A mock provider mainly used for testing.
39
- * @return {ProviderInterface} The mock provider
40
- * @internal
41
- */
42
- export class MockProvider implements ProviderInterface {
43
- private db: MockStateDb = {};
44
-
45
- private emitter = new EventEmitter();
46
-
47
- private intervalId?: ReturnType<typeof setInterval> | null;
48
-
49
- public isUpdating = true;
50
-
51
- private registry: Registry;
52
-
53
- private prevNumber = new BN(-1);
54
-
55
- private requests: Record<string, (...params: any[]) => unknown> = {
56
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
57
- chain_getBlock: () => this.registry.createType('SignedBlock', rpcSignedBlock.result).toJSON(),
58
- chain_getBlockHash: () => '0x1234000000000000000000000000000000000000000000000000000000000000',
59
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
60
- chain_getFinalizedHead: () => this.registry.createType('Header', rpcHeader.result).hash,
61
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
62
- chain_getHeader: () => this.registry.createType('Header', rpcHeader.result).toJSON(),
63
- rpc_methods: () => this.registry.createType('RpcMethods').toJSON(),
64
- state_getKeys: () => [],
65
- state_getKeysPaged: () => [],
66
- state_getMetadata: () => rpcMetadata,
67
- state_getRuntimeVersion: () => this.registry.createType('RuntimeVersion').toHex(),
68
- state_getStorage: (storage: MockStateDb, [key]: string[]) => u8aToHex(storage[key]),
69
- system_chain: () => 'mockChain',
70
- system_health: () => ({}),
71
- system_name: () => 'mockClient',
72
- system_properties: () => ({ ss58Format: 42 }),
73
- system_upgradedToTripleRefCount: () => this.registry.createType('bool', true),
74
- system_version: () => '9.8.7',
75
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return, sort-keys
76
- dev_echo: (_, params: any) => params
77
- };
78
-
79
- public subscriptions: MockStateSubscriptions = SUBSCRIPTIONS.reduce((subs, name): MockStateSubscriptions => {
80
- subs[name] = {
81
- callbacks: {},
82
- lastValue: null
83
- };
84
-
85
- return subs;
86
- }, ({} as MockStateSubscriptions));
87
-
88
- private subscriptionId = 0;
89
-
90
- private subscriptionMap: Record<number, string> = {};
91
-
92
- constructor (registry: Registry) {
93
- this.registry = registry;
94
-
95
- this.init();
96
- }
97
-
98
- public get hasSubscriptions (): boolean {
99
- return !!true;
100
- }
101
-
102
- public clone (): MockProvider {
103
- throw new Error('Unimplemented');
104
- }
105
-
106
- public async connect (): Promise<void> {
107
- // noop
108
- }
109
-
110
- // eslint-disable-next-line @typescript-eslint/require-await
111
- public async disconnect (): Promise<void> {
112
- if (this.intervalId) {
113
- clearInterval(this.intervalId);
114
- this.intervalId = null;
115
- }
116
- }
117
-
118
- public get isClonable (): boolean {
119
- return !!false;
120
- }
121
-
122
- public get isConnected (): boolean {
123
- return !!true;
124
- }
125
-
126
- public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void {
127
- this.emitter.on(type, sub);
128
-
129
- return (): void => {
130
- this.emitter.removeListener(type, sub);
131
- };
132
- }
133
-
134
- // eslint-disable-next-line @typescript-eslint/require-await
135
- public async send <T = any> (method: string, params: unknown[]): Promise<T> {
136
- l.debug(() => ['send', method, params]);
137
-
138
- if (!this.requests[method]) {
139
- throw new Error(`provider.send: Invalid method '${method}'`);
140
- }
141
-
142
- return this.requests[method](this.db, params) as T;
143
- }
144
-
145
- // eslint-disable-next-line @typescript-eslint/require-await
146
- public async subscribe (_type: string, method: string, ...params: unknown[]): Promise<number> {
147
- l.debug(() => ['subscribe', method, params]);
148
-
149
- if (!this.subscriptions[method]) {
150
- throw new Error(`provider.subscribe: Invalid method '${method}'`);
151
- }
152
-
153
- const callback = params.pop() as MockStateSubscriptionCallback;
154
- const id = ++this.subscriptionId;
155
-
156
- this.subscriptions[method].callbacks[id] = callback;
157
- this.subscriptionMap[id] = method;
158
-
159
- if (this.subscriptions[method].lastValue !== null) {
160
- callback(null, this.subscriptions[method].lastValue);
161
- }
162
-
163
- return id;
164
- }
165
-
166
- // eslint-disable-next-line @typescript-eslint/require-await
167
- public async unsubscribe (_type: string, _method: string, id: number): Promise<boolean> {
168
- const sub = this.subscriptionMap[id];
169
-
170
- l.debug(() => ['unsubscribe', id, sub]);
171
-
172
- if (!sub) {
173
- throw new Error(`Unable to find subscription for ${id}`);
174
- }
175
-
176
- delete this.subscriptionMap[id];
177
- delete this.subscriptions[sub].callbacks[id];
178
-
179
- return true;
180
- }
181
-
182
- private init (): void {
183
- const emitEvents: ProviderInterfaceEmitted[] = ['connected', 'disconnected'];
184
- let emitIndex = 0;
185
- let newHead = this.makeBlockHeader();
186
- let counter = -1;
187
-
188
- const metadata = new Metadata(this.registry, rpcMetadata);
189
-
190
- this.registry.setMetadata(metadata);
191
-
192
- const query = decorateStorage(this.registry, metadata.asLatest, metadata.version);
193
-
194
- // Do something every 1 seconds
195
- this.intervalId = setInterval((): void => {
196
- if (!this.isUpdating) {
197
- return;
198
- }
199
-
200
- // create a new header (next block)
201
- newHead = this.makeBlockHeader();
202
-
203
- // increment the balances and nonce for each account
204
- keyring.getPairs().forEach(({ publicKey }, index): void => {
205
- this.setStateBn(query['system']['account'](publicKey), newHead.number.toBn().addn(index));
206
- });
207
-
208
- // set the timestamp for the current block
209
- this.setStateBn(query['timestamp']['now'](), Math.floor(Date.now() / 1000));
210
- this.updateSubs('chain_subscribeNewHead', newHead);
211
-
212
- // We emit connected/disconnected at intervals
213
- if (++counter % 2 === 1) {
214
- if (++emitIndex === emitEvents.length) {
215
- emitIndex = 0;
216
- }
217
-
218
- this.emitter.emit(emitEvents[emitIndex]);
219
- }
220
- }, INTERVAL);
221
- }
222
-
223
- private makeBlockHeader (): Header {
224
- const blockNumber = this.prevNumber.addn(1);
225
- const header = this.registry.createType('Header', {
226
- digest: {
227
- logs: []
228
- },
229
- extrinsicsRoot: randomAsU8a(),
230
- number: blockNumber,
231
- parentHash: blockNumber.isZero()
232
- ? new Uint8Array(32)
233
- : bnToU8a(this.prevNumber, { bitLength: 256, isLe: false }),
234
- stateRoot: bnToU8a(blockNumber, { bitLength: 256, isLe: false })
235
- });
236
-
237
- this.prevNumber = blockNumber;
238
-
239
- return header as unknown as Header;
240
- }
241
-
242
- private setStateBn (key: Uint8Array, value: BN | number): void {
243
- this.db[u8aToHex(key)] = bnToU8a(value, { bitLength: 64, isLe: true });
244
- }
245
-
246
- private updateSubs (method: string, value: Codec): void {
247
- this.subscriptions[method].lastValue = value;
248
-
249
- Object
250
- .values(this.subscriptions[method].callbacks)
251
- .forEach((cb): void => {
252
- try {
253
- cb(null, value.toJSON());
254
- } catch (error) {
255
- l.error(`Error on '${method}' subscription`, error);
256
- }
257
- });
258
- }
259
- }
@@ -1,35 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { Mock } from './types.js';
5
-
6
- import nock from 'nock';
7
-
8
- interface Request {
9
- code?: number;
10
- method: string;
11
- reply?: Record<string, unknown>;
12
- }
13
-
14
- interface HttpMock extends Mock {
15
- post: (uri: string) => {
16
- reply: (code: number, handler: (uri: string, body: { id: string }) => unknown) => HttpMock
17
- }
18
- }
19
-
20
- export const TEST_HTTP_URL = 'http://localhost:9944';
21
-
22
- export function mockHttp (requests: Request[]): Mock {
23
- nock.cleanAll();
24
-
25
- return requests.reduce((scope: HttpMock, request: Request) =>
26
- scope
27
- .post('/')
28
- .reply(request.code || 200, (_uri: string, body: { id: string }) => {
29
- scope.body = scope.body || {};
30
- scope.body[request.method] = body;
31
-
32
- return Object.assign({ id: body.id, jsonrpc: '2.0' }, request.reply || {}) as unknown;
33
- }),
34
- nock(TEST_HTTP_URL) as unknown as HttpMock);
35
- }
@@ -1,92 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import { Server, WebSocket } from 'mock-socket';
5
-
6
- import { stringify } from '@pezkuwi/util';
7
-
8
- interface Scope {
9
- body: Record<string, Record<string, unknown>>;
10
- requests: number;
11
- server: Server;
12
- done: any;
13
- }
14
-
15
- interface ErrorDef {
16
- id: number;
17
- error: {
18
- code: number;
19
- message: string;
20
- };
21
- }
22
-
23
- interface ReplyDef {
24
- id: number;
25
- reply: {
26
- result: unknown;
27
- };
28
- }
29
-
30
- interface RpcBase {
31
- id: number;
32
- jsonrpc: '2.0';
33
- }
34
-
35
- type RpcError = RpcBase & ErrorDef;
36
- type RpcReply = RpcBase & { result: unknown };
37
-
38
- export type Request = { method: string } & (ErrorDef | ReplyDef);
39
-
40
- global.WebSocket = WebSocket as typeof global.WebSocket;
41
-
42
- export const TEST_WS_URL = 'ws://localhost:9955';
43
-
44
- // should be JSONRPC def return
45
- function createError ({ error: { code, message }, id }: ErrorDef): RpcError {
46
- return {
47
- error: {
48
- code,
49
- message
50
- },
51
- id,
52
- jsonrpc: '2.0'
53
- };
54
- }
55
-
56
- // should be JSONRPC def return
57
- function createReply ({ id, reply: { result } }: ReplyDef): RpcReply {
58
- return {
59
- id,
60
- jsonrpc: '2.0',
61
- result
62
- };
63
- }
64
-
65
- // scope definition returned
66
- export function mockWs (requests: Request[], wsUrl: string = TEST_WS_URL): Scope {
67
- const server = new Server(wsUrl);
68
-
69
- let requestCount = 0;
70
- const scope: Scope = {
71
- body: {},
72
- done: () => new Promise<void>((resolve) => server.stop(resolve)),
73
- requests: 0,
74
- server
75
- };
76
-
77
- server.on('connection', (socket): void => {
78
- socket.on('message', (body): void => {
79
- const request = requests[requestCount];
80
- const response = (request as ErrorDef).error
81
- ? createError(request as ErrorDef)
82
- : createReply(request as ReplyDef);
83
-
84
- scope.body[request.method] = body as unknown as Record<string, unknown>;
85
- requestCount++;
86
-
87
- socket.send(stringify(response));
88
- });
89
- });
90
-
91
- return scope;
92
- }
@@ -1,43 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
-
6
- import type { ProviderInterfaceEmitted } from '../types.js';
7
-
8
- import { TypeRegistry } from '@pezkuwi/types/create';
9
-
10
- import { MockProvider } from './index.js';
11
-
12
- describe('on', (): void => {
13
- const registry = new TypeRegistry();
14
- let mock: MockProvider;
15
-
16
- beforeEach((): void => {
17
- mock = new MockProvider(registry);
18
- });
19
-
20
- afterEach(async () => {
21
- await mock.disconnect();
22
- });
23
-
24
- // eslint-disable-next-line jest/expect-expect
25
- it('emits both connected and disconnected events', async (): Promise<void> => {
26
- const events: Record<string, boolean> = { connected: false, disconnected: false };
27
-
28
- await new Promise<boolean>((resolve) => {
29
- const handler = (type: ProviderInterfaceEmitted): void => {
30
- mock.on(type, (): void => {
31
- events[type] = true;
32
-
33
- if (Object.values(events).filter((value): boolean => value).length === 2) {
34
- resolve(true);
35
- }
36
- });
37
- };
38
-
39
- handler('connected');
40
- handler('disconnected');
41
- });
42
- });
43
- });
@@ -1,38 +0,0 @@
1
- // Copyright 2017-2025 @pezkuwi/rpc-provider authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /// <reference types="@pezkuwi/dev-test/globals.d.ts" />
5
-
6
- import { TypeRegistry } from '@pezkuwi/types/create';
7
-
8
- import { MockProvider } from './index.js';
9
-
10
- describe('send', (): void => {
11
- const registry = new TypeRegistry();
12
- let mock: MockProvider;
13
-
14
- beforeEach((): void => {
15
- mock = new MockProvider(registry);
16
- });
17
-
18
- afterEach(async () => {
19
- await mock.disconnect();
20
- });
21
-
22
- it('fails on non-supported methods', (): Promise<any> => {
23
- return mock
24
- .send('something_invalid', [])
25
- .catch((error): void => {
26
- // eslint-disable-next-line jest/no-conditional-expect
27
- expect((error as Error).message).toMatch(/Invalid method/);
28
- });
29
- });
30
-
31
- it('returns values for mocked requests', (): Promise<void> => {
32
- return mock
33
- .send('system_name', [])
34
- .then((result): void => {
35
- expect(result).toBe('mockClient');
36
- });
37
- });
38
- });