@pezkuwi/rpc-provider 16.5.5 → 16.5.6
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.
- package/LICENSE +201 -0
- package/README.md +10 -10
- package/bizinikiwi-connect/Health.js +259 -0
- package/{build/substrate-connect → bizinikiwi-connect}/index.d.ts +3 -3
- package/bizinikiwi-connect/index.js +319 -0
- package/{build/bundle.d.ts → bundle.d.ts} +1 -1
- package/{src/bundle.ts → bundle.js} +1 -4
- package/cjs/bizinikiwi-connect/Health.d.ts +7 -0
- package/cjs/bizinikiwi-connect/Health.js +264 -0
- package/cjs/bizinikiwi-connect/index.d.ts +22 -0
- package/cjs/bizinikiwi-connect/index.js +323 -0
- package/cjs/bizinikiwi-connect/types.d.ts +12 -0
- package/cjs/bizinikiwi-connect/types.js +2 -0
- package/cjs/bundle.d.ts +5 -0
- package/cjs/bundle.js +14 -0
- package/cjs/coder/error.js +53 -0
- package/cjs/coder/index.js +63 -0
- package/cjs/defaults.js +8 -0
- package/{build → cjs}/http/index.d.ts +1 -1
- package/cjs/http/index.js +196 -0
- package/cjs/http/types.js +2 -0
- package/cjs/index.js +5 -0
- package/cjs/lru.js +150 -0
- package/cjs/mock/index.js +196 -0
- package/cjs/mock/mockHttp.js +17 -0
- package/cjs/mock/mockWs.js +47 -0
- package/cjs/mock/types.js +2 -0
- package/cjs/package.json +3 -0
- package/cjs/packageDetect.d.ts +1 -0
- package/cjs/packageDetect.js +6 -0
- package/cjs/packageInfo.js +4 -0
- package/cjs/types.js +2 -0
- package/cjs/ws/errors.js +41 -0
- package/{build → cjs}/ws/index.d.ts +1 -1
- package/cjs/ws/index.js +529 -0
- package/coder/error.d.ts +29 -0
- package/coder/error.js +50 -0
- package/coder/index.d.ts +8 -0
- package/coder/index.js +58 -0
- package/defaults.d.ts +5 -0
- package/defaults.js +6 -0
- package/http/index.d.ts +81 -0
- package/http/index.js +191 -0
- package/http/types.d.ts +7 -0
- package/http/types.js +1 -0
- package/index.d.ts +2 -0
- package/index.js +2 -0
- package/lru.d.ts +15 -0
- package/lru.js +146 -0
- package/mock/index.d.ts +35 -0
- package/mock/index.js +191 -0
- package/mock/mockHttp.d.ts +9 -0
- package/mock/mockHttp.js +12 -0
- package/mock/mockWs.d.ts +26 -0
- package/mock/mockWs.js +43 -0
- package/mock/types.d.ts +23 -0
- package/mock/types.js +1 -0
- package/package.json +316 -15
- package/packageDetect.d.ts +1 -0
- package/packageDetect.js +4 -0
- package/packageInfo.d.ts +6 -0
- package/packageInfo.js +1 -0
- package/types.d.ts +85 -0
- package/types.js +1 -0
- package/ws/errors.d.ts +1 -0
- package/ws/errors.js +38 -0
- package/ws/index.d.ts +121 -0
- package/ws/index.js +524 -0
- package/src/coder/decodeResponse.spec.ts +0 -70
- package/src/coder/encodeJson.spec.ts +0 -20
- package/src/coder/encodeObject.spec.ts +0 -25
- package/src/coder/error.spec.ts +0 -111
- package/src/coder/error.ts +0 -66
- package/src/coder/index.ts +0 -88
- package/src/defaults.ts +0 -10
- package/src/http/index.spec.ts +0 -72
- package/src/http/index.ts +0 -238
- package/src/http/send.spec.ts +0 -61
- package/src/http/types.ts +0 -11
- package/src/index.ts +0 -6
- package/src/lru.spec.ts +0 -74
- package/src/lru.ts +0 -197
- package/src/mock/index.ts +0 -259
- package/src/mock/mockHttp.ts +0 -35
- package/src/mock/mockWs.ts +0 -92
- package/src/mock/on.spec.ts +0 -43
- package/src/mock/send.spec.ts +0 -38
- package/src/mock/subscribe.spec.ts +0 -81
- package/src/mock/types.ts +0 -36
- package/src/mock/unsubscribe.spec.ts +0 -57
- package/src/mod.ts +0 -4
- package/src/packageDetect.ts +0 -12
- package/src/packageInfo.ts +0 -6
- package/src/substrate-connect/Health.ts +0 -325
- package/src/substrate-connect/index.spec.ts +0 -638
- package/src/substrate-connect/index.ts +0 -415
- package/src/substrate-connect/types.ts +0 -16
- package/src/types.ts +0 -101
- package/src/ws/connect.spec.ts +0 -167
- package/src/ws/errors.ts +0 -41
- package/src/ws/index.spec.ts +0 -97
- package/src/ws/index.ts +0 -652
- package/src/ws/send.spec.ts +0 -126
- package/src/ws/state.spec.ts +0 -20
- package/src/ws/subscribe.spec.ts +0 -68
- package/src/ws/unsubscribe.spec.ts +0 -100
- package/tsconfig.build.json +0 -17
- package/tsconfig.build.tsbuildinfo +0 -1
- package/tsconfig.spec.json +0 -18
- /package/{build/substrate-connect → bizinikiwi-connect}/Health.d.ts +0 -0
- /package/{build/substrate-connect → bizinikiwi-connect}/types.d.ts +0 -0
- /package/{build/packageDetect.d.ts → bizinikiwi-connect/types.js} +0 -0
- /package/{build → cjs}/coder/error.d.ts +0 -0
- /package/{build → cjs}/coder/index.d.ts +0 -0
- /package/{build → cjs}/defaults.d.ts +0 -0
- /package/{build → cjs}/http/types.d.ts +0 -0
- /package/{build → cjs}/index.d.ts +0 -0
- /package/{build → cjs}/lru.d.ts +0 -0
- /package/{build → cjs}/mock/index.d.ts +0 -0
- /package/{build → cjs}/mock/mockHttp.d.ts +0 -0
- /package/{build → cjs}/mock/mockWs.d.ts +0 -0
- /package/{build → cjs}/mock/types.d.ts +0 -0
- /package/{build → cjs}/packageInfo.d.ts +0 -0
- /package/{build → cjs}/types.d.ts +0 -0
- /package/{build → cjs}/ws/errors.d.ts +0 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.HttpProvider = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const util_1 = require("@pezkuwi/util");
|
|
6
|
+
const x_fetch_1 = require("@pezkuwi/x-fetch");
|
|
7
|
+
const index_js_1 = require("../coder/index.js");
|
|
8
|
+
const defaults_js_1 = tslib_1.__importDefault(require("../defaults.js"));
|
|
9
|
+
const lru_js_1 = require("../lru.js");
|
|
10
|
+
const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
|
|
11
|
+
const l = (0, util_1.logger)('api-http');
|
|
12
|
+
/**
|
|
13
|
+
* # @pezkuwi/rpc-provider
|
|
14
|
+
*
|
|
15
|
+
* @name HttpProvider
|
|
16
|
+
*
|
|
17
|
+
* @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]].
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* <BR>
|
|
21
|
+
*
|
|
22
|
+
* ```javascript
|
|
23
|
+
* import Api from '@pezkuwi/api/promise';
|
|
24
|
+
* import { HttpProvider } from '@pezkuwi/rpc-provider';
|
|
25
|
+
*
|
|
26
|
+
* const provider = new HttpProvider('http://127.0.0.1:9933');
|
|
27
|
+
* const api = new Api(provider);
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @see [[WsProvider]]
|
|
31
|
+
*/
|
|
32
|
+
class HttpProvider {
|
|
33
|
+
#callCache;
|
|
34
|
+
#cacheCapacity;
|
|
35
|
+
#coder;
|
|
36
|
+
#endpoint;
|
|
37
|
+
#headers;
|
|
38
|
+
#stats;
|
|
39
|
+
#ttl;
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} endpoint The endpoint url starting with http://
|
|
42
|
+
* @param {Record<string, string>} headers The headers provided to the underlying Http Endpoint
|
|
43
|
+
* @param {number} [cacheCapacity] Custom size of the HttpProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
|
|
44
|
+
* @param {number} [cacheTtl] Custom TTL of the HttpProvider LRUCache. Determines how long an object can live in the cache. Defaults to `DEFAULT_TTL` (30000)
|
|
45
|
+
*/
|
|
46
|
+
constructor(endpoint = defaults_js_1.default.HTTP_URL, headers = {}, cacheCapacity, cacheTtl) {
|
|
47
|
+
if (!/^(https|http):\/\//.test(endpoint)) {
|
|
48
|
+
throw new Error(`Endpoint should start with 'http://' or 'https://', received '${endpoint}'`);
|
|
49
|
+
}
|
|
50
|
+
this.#coder = new index_js_1.RpcCoder();
|
|
51
|
+
this.#endpoint = endpoint;
|
|
52
|
+
this.#headers = headers;
|
|
53
|
+
this.#cacheCapacity = cacheCapacity === 0 ? 0 : cacheCapacity || lru_js_1.DEFAULT_CAPACITY;
|
|
54
|
+
const ttl = cacheTtl === undefined ? lru_js_1.DEFAULT_TTL : cacheTtl;
|
|
55
|
+
this.#callCache = new lru_js_1.LRUCache(cacheCapacity === 0 ? 0 : cacheCapacity || lru_js_1.DEFAULT_CAPACITY, ttl);
|
|
56
|
+
this.#ttl = cacheTtl;
|
|
57
|
+
this.#stats = {
|
|
58
|
+
active: { requests: 0, subscriptions: 0 },
|
|
59
|
+
total: { bytesRecv: 0, bytesSent: 0, cached: 0, errors: 0, requests: 0, subscriptions: 0, timeout: 0 }
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* @summary `true` when this provider supports subscriptions
|
|
64
|
+
*/
|
|
65
|
+
get hasSubscriptions() {
|
|
66
|
+
return !!false;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* @description Returns a clone of the object
|
|
70
|
+
*/
|
|
71
|
+
clone() {
|
|
72
|
+
return new HttpProvider(this.#endpoint, this.#headers);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* @description Manually connect from the connection
|
|
76
|
+
*/
|
|
77
|
+
async connect() {
|
|
78
|
+
// noop
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* @description Manually disconnect from the connection
|
|
82
|
+
*/
|
|
83
|
+
async disconnect() {
|
|
84
|
+
// noop
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* @description Returns the connection stats
|
|
88
|
+
*/
|
|
89
|
+
get stats() {
|
|
90
|
+
return this.#stats;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* @description Returns the connection stats
|
|
94
|
+
*/
|
|
95
|
+
get ttl() {
|
|
96
|
+
return this.#ttl;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* @summary `true` when this provider supports clone()
|
|
100
|
+
*/
|
|
101
|
+
get isClonable() {
|
|
102
|
+
return !!true;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* @summary Whether the node is connected or not.
|
|
106
|
+
* @return {boolean} true if connected
|
|
107
|
+
*/
|
|
108
|
+
get isConnected() {
|
|
109
|
+
return !!true;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* @summary Events are not supported with the HttpProvider, see [[WsProvider]].
|
|
113
|
+
* @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
|
|
114
|
+
*/
|
|
115
|
+
on(_type, _sub) {
|
|
116
|
+
l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
|
|
117
|
+
return util_1.noop;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
|
|
121
|
+
*/
|
|
122
|
+
async send(method, params, isCacheable) {
|
|
123
|
+
this.#stats.total.requests++;
|
|
124
|
+
const [, body] = this.#coder.encodeJson(method, params);
|
|
125
|
+
if (this.#cacheCapacity === 0) {
|
|
126
|
+
return this.#send(body);
|
|
127
|
+
}
|
|
128
|
+
const cacheKey = isCacheable ? `${method}::${(0, util_1.stringify)(params)}` : '';
|
|
129
|
+
let resultPromise = isCacheable
|
|
130
|
+
? this.#callCache.get(cacheKey)
|
|
131
|
+
: null;
|
|
132
|
+
if (!resultPromise) {
|
|
133
|
+
resultPromise = this.#send(body);
|
|
134
|
+
if (isCacheable) {
|
|
135
|
+
this.#callCache.set(cacheKey, resultPromise);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
this.#stats.total.cached++;
|
|
140
|
+
}
|
|
141
|
+
return resultPromise;
|
|
142
|
+
}
|
|
143
|
+
async #send(body) {
|
|
144
|
+
this.#stats.active.requests++;
|
|
145
|
+
this.#stats.total.bytesSent += body.length;
|
|
146
|
+
try {
|
|
147
|
+
const response = await (0, x_fetch_1.fetch)(this.#endpoint, {
|
|
148
|
+
body,
|
|
149
|
+
headers: {
|
|
150
|
+
Accept: 'application/json',
|
|
151
|
+
'Content-Length': `${body.length}`,
|
|
152
|
+
'Content-Type': 'application/json',
|
|
153
|
+
...this.#headers
|
|
154
|
+
},
|
|
155
|
+
method: 'POST'
|
|
156
|
+
});
|
|
157
|
+
if (!response.ok) {
|
|
158
|
+
throw new Error(`[${response.status}]: ${response.statusText}`);
|
|
159
|
+
}
|
|
160
|
+
const result = await response.text();
|
|
161
|
+
this.#stats.total.bytesRecv += result.length;
|
|
162
|
+
const decoded = this.#coder.decodeResponse(JSON.parse(result));
|
|
163
|
+
this.#stats.active.requests--;
|
|
164
|
+
return decoded;
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
this.#stats.active.requests--;
|
|
168
|
+
this.#stats.total.errors++;
|
|
169
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
170
|
+
const { method, params } = JSON.parse(body);
|
|
171
|
+
const rpcError = e;
|
|
172
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
173
|
+
const failedRequest = `\nFailed HTTP Request: ${JSON.stringify({ method, params })}`;
|
|
174
|
+
// Provide HTTP Request alongside the error
|
|
175
|
+
rpcError.message = `${rpcError.message}${failedRequest}`;
|
|
176
|
+
throw rpcError;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
|
|
181
|
+
*/
|
|
182
|
+
// eslint-disable-next-line @typescript-eslint/require-await
|
|
183
|
+
async subscribe(_types, _method, _params, _cb) {
|
|
184
|
+
l.error(ERROR_SUBSCRIBE);
|
|
185
|
+
throw new Error(ERROR_SUBSCRIBE);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
|
|
189
|
+
*/
|
|
190
|
+
// eslint-disable-next-line @typescript-eslint/require-await
|
|
191
|
+
async unsubscribe(_type, _method, _id) {
|
|
192
|
+
l.error(ERROR_SUBSCRIBE);
|
|
193
|
+
throw new Error(ERROR_SUBSCRIBE);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
exports.HttpProvider = HttpProvider;
|
package/cjs/index.js
ADDED
package/cjs/lru.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LRUCache = exports.DEFAULT_TTL = exports.DEFAULT_CAPACITY = void 0;
|
|
4
|
+
exports.DEFAULT_CAPACITY = 1024;
|
|
5
|
+
exports.DEFAULT_TTL = 30000; // 30 seconds
|
|
6
|
+
const MAX_TTL = 1800_000; // 30 minutes
|
|
7
|
+
const DISABLED_TTL = 31_536_000_000;
|
|
8
|
+
class LRUNode {
|
|
9
|
+
key;
|
|
10
|
+
#expires;
|
|
11
|
+
#ttl;
|
|
12
|
+
createdAt;
|
|
13
|
+
next;
|
|
14
|
+
prev;
|
|
15
|
+
constructor(key, ttl) {
|
|
16
|
+
this.key = key;
|
|
17
|
+
this.#ttl = ttl;
|
|
18
|
+
this.#expires = Date.now() + ttl;
|
|
19
|
+
this.createdAt = Date.now();
|
|
20
|
+
this.next = this.prev = this;
|
|
21
|
+
}
|
|
22
|
+
refresh() {
|
|
23
|
+
this.#expires = Date.now() + this.#ttl;
|
|
24
|
+
}
|
|
25
|
+
get expiry() {
|
|
26
|
+
return this.#expires;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
class LRUCache {
|
|
30
|
+
capacity;
|
|
31
|
+
#data = new Map();
|
|
32
|
+
#refs = new Map();
|
|
33
|
+
#length = 0;
|
|
34
|
+
#head;
|
|
35
|
+
#tail;
|
|
36
|
+
#ttl;
|
|
37
|
+
constructor(capacity = exports.DEFAULT_CAPACITY, ttl = exports.DEFAULT_TTL) {
|
|
38
|
+
// Validate capacity
|
|
39
|
+
if (!Number.isInteger(capacity) || capacity < 0) {
|
|
40
|
+
throw new Error(`LRUCache initialization error: 'capacity' must be a non-negative integer. Received: ${capacity}`);
|
|
41
|
+
}
|
|
42
|
+
// Validate ttl
|
|
43
|
+
if (ttl !== null && (!Number.isFinite(ttl) || ttl < 0 || ttl > MAX_TTL)) {
|
|
44
|
+
throw new Error(`LRUCache initialization error: 'ttl' must be between 0 and ${MAX_TTL} ms or null to disable. Received: ${ttl}`);
|
|
45
|
+
}
|
|
46
|
+
this.capacity = capacity;
|
|
47
|
+
ttl ? this.#ttl = ttl : this.#ttl = DISABLED_TTL;
|
|
48
|
+
this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
|
|
49
|
+
}
|
|
50
|
+
get ttl() {
|
|
51
|
+
return this.#ttl;
|
|
52
|
+
}
|
|
53
|
+
get length() {
|
|
54
|
+
return this.#length;
|
|
55
|
+
}
|
|
56
|
+
get lengthData() {
|
|
57
|
+
return this.#data.size;
|
|
58
|
+
}
|
|
59
|
+
get lengthRefs() {
|
|
60
|
+
return this.#refs.size;
|
|
61
|
+
}
|
|
62
|
+
entries() {
|
|
63
|
+
const keys = this.keys();
|
|
64
|
+
const count = keys.length;
|
|
65
|
+
const entries = new Array(count);
|
|
66
|
+
for (let i = 0; i < count; i++) {
|
|
67
|
+
const key = keys[i];
|
|
68
|
+
entries[i] = [key, this.#data.get(key)];
|
|
69
|
+
}
|
|
70
|
+
return entries;
|
|
71
|
+
}
|
|
72
|
+
keys() {
|
|
73
|
+
const keys = [];
|
|
74
|
+
if (this.#length) {
|
|
75
|
+
let curr = this.#head;
|
|
76
|
+
while (curr !== this.#tail) {
|
|
77
|
+
keys.push(curr.key);
|
|
78
|
+
curr = curr.next;
|
|
79
|
+
}
|
|
80
|
+
keys.push(curr.key);
|
|
81
|
+
}
|
|
82
|
+
return keys;
|
|
83
|
+
}
|
|
84
|
+
get(key) {
|
|
85
|
+
const data = this.#data.get(key);
|
|
86
|
+
if (data) {
|
|
87
|
+
this.#toHead(key);
|
|
88
|
+
// Evict TTL once data is refreshed
|
|
89
|
+
this.#evictTTL();
|
|
90
|
+
return data;
|
|
91
|
+
}
|
|
92
|
+
this.#evictTTL();
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
set(key, value) {
|
|
96
|
+
if (this.#data.has(key)) {
|
|
97
|
+
this.#toHead(key);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
const node = new LRUNode(key, this.#ttl);
|
|
101
|
+
this.#refs.set(node.key, node);
|
|
102
|
+
if (this.length === 0) {
|
|
103
|
+
this.#head = this.#tail = node;
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
this.#head.prev = node;
|
|
107
|
+
node.next = this.#head;
|
|
108
|
+
this.#head = node;
|
|
109
|
+
}
|
|
110
|
+
if (this.#length === this.capacity) {
|
|
111
|
+
this.#data.delete(this.#tail.key);
|
|
112
|
+
this.#refs.delete(this.#tail.key);
|
|
113
|
+
this.#tail = this.#tail.prev;
|
|
114
|
+
this.#tail.next = this.#head;
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
this.#length += 1;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
// Evict TTL once data is refreshed or added
|
|
121
|
+
this.#evictTTL();
|
|
122
|
+
this.#data.set(key, value);
|
|
123
|
+
}
|
|
124
|
+
#evictTTL() {
|
|
125
|
+
// Find last node to keep
|
|
126
|
+
// traverse map to find the expired nodes
|
|
127
|
+
while (this.#tail.expiry && this.#tail.expiry < Date.now() && this.#length > 0) {
|
|
128
|
+
this.#refs.delete(this.#tail.key);
|
|
129
|
+
this.#data.delete(this.#tail.key);
|
|
130
|
+
this.#length -= 1;
|
|
131
|
+
this.#tail = this.#tail.prev;
|
|
132
|
+
this.#tail.next = this.#head;
|
|
133
|
+
}
|
|
134
|
+
if (this.#length === 0) {
|
|
135
|
+
this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
#toHead(key) {
|
|
139
|
+
const ref = this.#refs.get(key);
|
|
140
|
+
if (ref && ref !== this.#head) {
|
|
141
|
+
ref.refresh();
|
|
142
|
+
ref.prev.next = ref.next;
|
|
143
|
+
ref.next.prev = ref.prev;
|
|
144
|
+
ref.next = this.#head;
|
|
145
|
+
this.#head.prev = ref;
|
|
146
|
+
this.#head = ref;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.LRUCache = LRUCache;
|
|
@@ -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,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,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
|
+
}
|
package/cjs/package.json
ADDED
|
@@ -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]);
|
package/cjs/types.js
ADDED
package/cjs/ws/errors.js
ADDED
|
@@ -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
|
+
}
|