@chainflip/rpc 1.8.8 → 1.9.0-assethub.1

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/dist/WsClient.cjs CHANGED
@@ -1,124 +1,113 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// src/WsClient.ts
2
2
  var _async = require('@chainflip/utils/async');
3
- var _zod = require('zod');
4
3
  var _Clientcjs = require('./Client.cjs'); var _Clientcjs2 = _interopRequireDefault(_Clientcjs);
5
4
  var _commoncjs = require('./common.cjs');
6
- var CONNECTING = "CONNECTING";
7
5
  var READY = "READY";
8
6
  var DISCONNECT = "DISCONNECT";
9
7
  var WsClient = (_class = class extends _Clientcjs2.default {
8
+ constructor(url, WebSocket = globalThis.WebSocket) {
9
+ super(url);_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);;
10
+ this.WebSocket = WebSocket;
11
+ }
10
12
 
11
13
  __init() {this.reconnectAttempts = 0}
12
14
  __init2() {this.emitter = new EventTarget()}
13
- __init3() {this.inFlightRequestMap = /* @__PURE__ */ new Map()}
14
-
15
- __init4() {this.shouldConnect = true}
16
- constructor(url, { timeout = 3e4 } = {}) {
17
- super(url);_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);;
18
- this.timeout = timeout;
19
- }
15
+ __init3() {this.requestMap = /* @__PURE__ */ new Map()}
20
16
  async close() {
21
- this.shouldConnect = false;
22
- if (!this.ws) return;
23
- await this.handleDisconnect();
24
- const waitForClose = this.ws.readyState === WebSocket.OPEN;
17
+ await this.handleClose();
18
+ }
19
+ async handleClose() {
20
+ if (!this.ws)
21
+ return;
22
+ this.ws.removeEventListener("close", this.handleDisconnect);
25
23
  this.ws.close();
26
- if (waitForClose) await _async.once.call(void 0, this.ws, "close");
27
- this.ws = void 0;
24
+ if (this.ws.readyState !== this.WebSocket.CLOSED) {
25
+ await _async.once.call(void 0, this.ws, "close");
26
+ }
28
27
  }
29
28
  async connectionReady() {
30
29
  if (!this.ws) {
31
30
  return this.connect();
32
31
  }
33
- if (this.ws.readyState !== WebSocket.OPEN) {
32
+ if (this.ws.readyState !== this.WebSocket.OPEN) {
34
33
  await _async.once.call(void 0, this.emitter, READY, { timeout: 3e4 });
35
34
  }
36
35
  return this.ws;
37
36
  }
38
- __init5() {this.handleDisconnect = async () => {
37
+ __init4() {this.handleDisconnect = async () => {
39
38
  this.emitter.dispatchEvent(new Event(DISCONNECT));
40
- this.inFlightRequestMap.forEach((request) => {
39
+ this.requestMap.forEach((request) => {
41
40
  request.reject(new Error("disconnected"));
42
41
  });
43
- this.inFlightRequestMap.clear();
44
- if (!this.shouldConnect) return;
42
+ this.requestMap.clear();
45
43
  const backoff = 250 * 2 ** this.reconnectAttempts;
46
44
  await _async.sleep.call(void 0, backoff);
47
45
  await this.connect().catch(() => {
48
46
  this.reconnectAttempts = Math.min(this.reconnectAttempts + 1, 6);
49
47
  });
50
48
  }}
51
- __init6() {this.handleMessage = (data) => {
49
+ __init5() {this.handleMessage = (data) => {
52
50
  const parsedData = JSON.parse(data.data);
53
- const responses = _zod.z.array(_commoncjs.rpcResponse).safeParse(parsedData);
54
- if (!responses.success) return;
55
- for (const response of responses.data) {
56
- const { id } = response;
57
- _optionalChain([this, 'access', _6 => _6.inFlightRequestMap, 'access', _7 => _7.get, 'call', _8 => _8(id), 'optionalAccess', _9 => _9.resolve, 'call', _10 => _10(response)]);
58
- }
51
+ const response = _commoncjs.rpcResponse.safeParse(parsedData);
52
+ if (!response.success)
53
+ return;
54
+ const { id } = response.data;
55
+ _optionalChain([this, 'access', _6 => _6.requestMap, 'access', _7 => _7.get, 'call', _8 => _8(id), 'optionalAccess', _9 => _9.resolve, 'call', _10 => _10(response.data)]);
59
56
  }}
60
57
  async connect() {
61
- this.shouldConnect = true;
62
- this.emitter.dispatchEvent(new Event(CONNECTING));
63
- const socket = new WebSocket(this.url);
58
+ const socket = new this.WebSocket(this.url);
64
59
  this.ws = socket;
65
60
  this.ws.addEventListener("message", this.handleMessage);
66
- let connected = false;
67
- const handleConnectionError = () => {
68
- if (!connected) {
69
- void this.handleDisconnect();
70
- }
71
- };
72
61
  this.ws.addEventListener("close", this.handleDisconnect, { once: true });
73
- this.ws.addEventListener("error", handleConnectionError, { once: true });
74
- await _async.once.call(void 0, this.ws, "open", { timeout: this.timeout });
75
- connected = true;
62
+ await _async.once.call(void 0, this.ws, "open", { timeout: 3e4 });
76
63
  this.ws.addEventListener("error", () => {
77
64
  socket.close();
78
65
  });
79
66
  this.emitter.dispatchEvent(new Event(READY));
80
- this.ws.removeEventListener("error", handleConnectionError);
81
67
  this.reconnectAttempts = 0;
82
68
  return socket;
83
69
  }
84
- async send(requests, requestMap) {
85
- const MAX_RETRIES = 5;
86
- let socket;
87
- for (let i = 0; i < MAX_RETRIES; i += 1) {
88
- try {
89
- socket = await this.connectionReady();
90
- } catch (e) {
91
- continue;
92
- }
93
- }
94
- if (!socket) {
95
- this.handleErrorResponse(new Error("failed to connect"), requestMap);
96
- return;
97
- }
98
- socket.send(JSON.stringify(requests));
99
- const promises = [];
100
- for (const [id] of requestMap) {
101
- const result = _async.deferredPromise.call(void 0, );
102
- const controller = new AbortController();
103
- this.inFlightRequestMap.set(id, result);
104
- promises.push(
105
- Promise.race([
106
- _async.sleep.call(void 0, this.timeout, { signal: controller.signal }).then(
107
- () => ({ id, success: false, error: new Error("timeout") })
70
+ async send(requests) {
71
+ const responses = [];
72
+ for (const data of requests) {
73
+ const MAX_RETRIES = 5;
74
+ for (let i = 0; i < MAX_RETRIES; i += 1) {
75
+ let socket;
76
+ try {
77
+ socket = await this.connectionReady();
78
+ } catch (e) {
79
+ continue;
80
+ }
81
+ socket.send(JSON.stringify(data));
82
+ const request = _async.deferredPromise.call(void 0, );
83
+ this.requestMap.set(data.id, request);
84
+ const controller = new AbortController();
85
+ const result = await Promise.race([
86
+ _async.sleep.call(void 0, 3e4, { signal: controller.signal }).then(
87
+ () => ({ success: false, retry: false, error: new Error("timeout") })
108
88
  ),
109
- result.promise.then(
110
- (r) => ({ id, success: true, result: r }),
111
- (error) => ({ id, success: false, error })
89
+ request.promise.then(
90
+ (result2) => ({ success: true, result: result2 }),
91
+ (error) => ({ success: false, error, retry: true })
112
92
  )
113
- ]).then((response) => {
114
- this.handleResponse(response, requestMap);
115
- }).finally(() => {
116
- this.inFlightRequestMap.delete(id);
93
+ ]).finally(() => {
94
+ this.requestMap.delete(data.id);
117
95
  controller.abort();
118
- })
119
- );
96
+ });
97
+ if (result.success || !result.retry) {
98
+ responses.push({ ...result, id: data.id });
99
+ break;
100
+ }
101
+ if (i === MAX_RETRIES - 1) {
102
+ responses.push({
103
+ success: false,
104
+ error: new Error("max retries exceeded"),
105
+ id: data.id
106
+ });
107
+ }
108
+ }
120
109
  }
121
- await Promise.all(promises);
110
+ return responses;
122
111
  }
123
112
  }, _class);
124
113
 
@@ -1,26 +1,23 @@
1
- import Client, { RequestMap } from './Client.cjs';
2
- import { JsonRpcRequest, RpcMethod } from './common.cjs';
3
- import '@chainflip/utils/async';
1
+ import Client, { Response } from './Client.cjs';
2
+ import { RpcMethod, JsonRpcRequest } from './common.cjs';
4
3
  import '@chainflip/utils/types';
5
4
  import 'zod';
6
5
  import './parsers.cjs';
7
6
 
8
7
  declare class WsClient extends Client {
8
+ private readonly WebSocket;
9
9
  private ws?;
10
10
  private reconnectAttempts;
11
11
  private emitter;
12
- private inFlightRequestMap;
13
- private readonly timeout;
14
- private shouldConnect;
15
- constructor(url: string, { timeout }?: {
16
- timeout?: number;
17
- });
12
+ private requestMap;
13
+ constructor(url: string, WebSocket?: typeof globalThis.WebSocket);
18
14
  close(): Promise<void>;
15
+ private handleClose;
19
16
  private connectionReady;
20
17
  private handleDisconnect;
21
18
  private handleMessage;
22
19
  private connect;
23
- protected send(requests: JsonRpcRequest<RpcMethod>[], requestMap: RequestMap): Promise<void>;
20
+ protected send<const T extends RpcMethod>(requests: JsonRpcRequest<T>[]): Promise<Response[]>;
24
21
  }
25
22
 
26
23
  export { WsClient as default };
@@ -1,26 +1,23 @@
1
- import Client, { RequestMap } from './Client.js';
2
- import { JsonRpcRequest, RpcMethod } from './common.js';
3
- import '@chainflip/utils/async';
1
+ import Client, { Response } from './Client.js';
2
+ import { RpcMethod, JsonRpcRequest } from './common.js';
4
3
  import '@chainflip/utils/types';
5
4
  import 'zod';
6
5
  import './parsers.js';
7
6
 
8
7
  declare class WsClient extends Client {
8
+ private readonly WebSocket;
9
9
  private ws?;
10
10
  private reconnectAttempts;
11
11
  private emitter;
12
- private inFlightRequestMap;
13
- private readonly timeout;
14
- private shouldConnect;
15
- constructor(url: string, { timeout }?: {
16
- timeout?: number;
17
- });
12
+ private requestMap;
13
+ constructor(url: string, WebSocket?: typeof globalThis.WebSocket);
18
14
  close(): Promise<void>;
15
+ private handleClose;
19
16
  private connectionReady;
20
17
  private handleDisconnect;
21
18
  private handleMessage;
22
19
  private connect;
23
- protected send(requests: JsonRpcRequest<RpcMethod>[], requestMap: RequestMap): Promise<void>;
20
+ protected send<const T extends RpcMethod>(requests: JsonRpcRequest<T>[]): Promise<Response[]>;
24
21
  }
25
22
 
26
23
  export { WsClient as default };
package/dist/WsClient.mjs CHANGED
@@ -1,47 +1,45 @@
1
1
  // src/WsClient.ts
2
2
  import { deferredPromise, once, sleep } from "@chainflip/utils/async";
3
- import { z } from "zod";
4
3
  import Client from "./Client.mjs";
5
4
  import { rpcResponse } from "./common.mjs";
6
- var CONNECTING = "CONNECTING";
7
5
  var READY = "READY";
8
6
  var DISCONNECT = "DISCONNECT";
9
7
  var WsClient = class extends Client {
8
+ constructor(url, WebSocket = globalThis.WebSocket) {
9
+ super(url);
10
+ this.WebSocket = WebSocket;
11
+ }
10
12
  ws;
11
13
  reconnectAttempts = 0;
12
14
  emitter = new EventTarget();
13
- inFlightRequestMap = /* @__PURE__ */ new Map();
14
- timeout;
15
- shouldConnect = true;
16
- constructor(url, { timeout = 3e4 } = {}) {
17
- super(url);
18
- this.timeout = timeout;
19
- }
15
+ requestMap = /* @__PURE__ */ new Map();
20
16
  async close() {
21
- this.shouldConnect = false;
22
- if (!this.ws) return;
23
- await this.handleDisconnect();
24
- const waitForClose = this.ws.readyState === WebSocket.OPEN;
17
+ await this.handleClose();
18
+ }
19
+ async handleClose() {
20
+ if (!this.ws)
21
+ return;
22
+ this.ws.removeEventListener("close", this.handleDisconnect);
25
23
  this.ws.close();
26
- if (waitForClose) await once(this.ws, "close");
27
- this.ws = void 0;
24
+ if (this.ws.readyState !== this.WebSocket.CLOSED) {
25
+ await once(this.ws, "close");
26
+ }
28
27
  }
29
28
  async connectionReady() {
30
29
  if (!this.ws) {
31
30
  return this.connect();
32
31
  }
33
- if (this.ws.readyState !== WebSocket.OPEN) {
32
+ if (this.ws.readyState !== this.WebSocket.OPEN) {
34
33
  await once(this.emitter, READY, { timeout: 3e4 });
35
34
  }
36
35
  return this.ws;
37
36
  }
38
37
  handleDisconnect = async () => {
39
38
  this.emitter.dispatchEvent(new Event(DISCONNECT));
40
- this.inFlightRequestMap.forEach((request) => {
39
+ this.requestMap.forEach((request) => {
41
40
  request.reject(new Error("disconnected"));
42
41
  });
43
- this.inFlightRequestMap.clear();
44
- if (!this.shouldConnect) return;
42
+ this.requestMap.clear();
45
43
  const backoff = 250 * 2 ** this.reconnectAttempts;
46
44
  await sleep(backoff);
47
45
  await this.connect().catch(() => {
@@ -50,75 +48,66 @@ var WsClient = class extends Client {
50
48
  };
51
49
  handleMessage = (data) => {
52
50
  const parsedData = JSON.parse(data.data);
53
- const responses = z.array(rpcResponse).safeParse(parsedData);
54
- if (!responses.success) return;
55
- for (const response of responses.data) {
56
- const { id } = response;
57
- this.inFlightRequestMap.get(id)?.resolve(response);
58
- }
51
+ const response = rpcResponse.safeParse(parsedData);
52
+ if (!response.success)
53
+ return;
54
+ const { id } = response.data;
55
+ this.requestMap.get(id)?.resolve(response.data);
59
56
  };
60
57
  async connect() {
61
- this.shouldConnect = true;
62
- this.emitter.dispatchEvent(new Event(CONNECTING));
63
- const socket = new WebSocket(this.url);
58
+ const socket = new this.WebSocket(this.url);
64
59
  this.ws = socket;
65
60
  this.ws.addEventListener("message", this.handleMessage);
66
- let connected = false;
67
- const handleConnectionError = () => {
68
- if (!connected) {
69
- void this.handleDisconnect();
70
- }
71
- };
72
61
  this.ws.addEventListener("close", this.handleDisconnect, { once: true });
73
- this.ws.addEventListener("error", handleConnectionError, { once: true });
74
- await once(this.ws, "open", { timeout: this.timeout });
75
- connected = true;
62
+ await once(this.ws, "open", { timeout: 3e4 });
76
63
  this.ws.addEventListener("error", () => {
77
64
  socket.close();
78
65
  });
79
66
  this.emitter.dispatchEvent(new Event(READY));
80
- this.ws.removeEventListener("error", handleConnectionError);
81
67
  this.reconnectAttempts = 0;
82
68
  return socket;
83
69
  }
84
- async send(requests, requestMap) {
85
- const MAX_RETRIES = 5;
86
- let socket;
87
- for (let i = 0; i < MAX_RETRIES; i += 1) {
88
- try {
89
- socket = await this.connectionReady();
90
- } catch {
91
- continue;
92
- }
93
- }
94
- if (!socket) {
95
- this.handleErrorResponse(new Error("failed to connect"), requestMap);
96
- return;
97
- }
98
- socket.send(JSON.stringify(requests));
99
- const promises = [];
100
- for (const [id] of requestMap) {
101
- const result = deferredPromise();
102
- const controller = new AbortController();
103
- this.inFlightRequestMap.set(id, result);
104
- promises.push(
105
- Promise.race([
106
- sleep(this.timeout, { signal: controller.signal }).then(
107
- () => ({ id, success: false, error: new Error("timeout") })
70
+ async send(requests) {
71
+ const responses = [];
72
+ for (const data of requests) {
73
+ const MAX_RETRIES = 5;
74
+ for (let i = 0; i < MAX_RETRIES; i += 1) {
75
+ let socket;
76
+ try {
77
+ socket = await this.connectionReady();
78
+ } catch {
79
+ continue;
80
+ }
81
+ socket.send(JSON.stringify(data));
82
+ const request = deferredPromise();
83
+ this.requestMap.set(data.id, request);
84
+ const controller = new AbortController();
85
+ const result = await Promise.race([
86
+ sleep(3e4, { signal: controller.signal }).then(
87
+ () => ({ success: false, retry: false, error: new Error("timeout") })
108
88
  ),
109
- result.promise.then(
110
- (r) => ({ id, success: true, result: r }),
111
- (error) => ({ id, success: false, error })
89
+ request.promise.then(
90
+ (result2) => ({ success: true, result: result2 }),
91
+ (error) => ({ success: false, error, retry: true })
112
92
  )
113
- ]).then((response) => {
114
- this.handleResponse(response, requestMap);
115
- }).finally(() => {
116
- this.inFlightRequestMap.delete(id);
93
+ ]).finally(() => {
94
+ this.requestMap.delete(data.id);
117
95
  controller.abort();
118
- })
119
- );
96
+ });
97
+ if (result.success || !result.retry) {
98
+ responses.push({ ...result, id: data.id });
99
+ break;
100
+ }
101
+ if (i === MAX_RETRIES - 1) {
102
+ responses.push({
103
+ success: false,
104
+ error: new Error("max retries exceeded"),
105
+ id: data.id
106
+ });
107
+ }
108
+ }
120
109
  }
121
- await Promise.all(promises);
110
+ return responses;
122
111
  }
123
112
  };
124
113
  export {
package/dist/common.cjs CHANGED
@@ -16,9 +16,6 @@
16
16
 
17
17
 
18
18
 
19
-
20
-
21
-
22
19
 
23
20
 
24
21
 
@@ -26,9 +23,7 @@
26
23
  var _parserscjs = require('./parsers.cjs');
27
24
 
28
25
  var rpcResult = {
29
- broker_request_swap_deposit_address: _parserscjs.brokerRequestSwapDepositAddress,
30
- broker_request_swap_parameter_encoding: _parserscjs.requestSwapParameterEncoding,
31
- cf_request_swap_parameter_encoding: _parserscjs.requestSwapParameterEncoding,
26
+ broker_requestSwapDepositAddress: _parserscjs.brokerRequestSwapDepositAddress,
32
27
  cf_accounts: _parserscjs.cfAccounts,
33
28
  cf_account_info: _parserscjs.cfAccountInfo,
34
29
  cf_pool_depth: _parserscjs.cfPoolDepth,
@@ -42,14 +37,12 @@ var rpcResult = {
42
37
  cf_supported_assets: _parserscjs.cfSupportedAssets,
43
38
  cf_swap_rate: _parserscjs.cfSwapRate,
44
39
  cf_swap_rate_v2: _parserscjs.cfSwapRateV2,
45
- cf_swap_rate_v3: _parserscjs.cfSwapRateV3,
46
40
  cf_swapping_environment: _parserscjs.cfSwappingEnvironment,
47
41
  chain_getBlockHash: _parserscjs.chainGetBlockHash,
48
42
  cf_boost_pool_details: _parserscjs.cfBoostPoolDetails,
49
43
  cf_boost_pool_pending_fees: _parserscjs.cfBoostPoolPendingFees,
50
44
  state_getMetadata: _parserscjs.stateGetMetadata,
51
- state_getRuntimeVersion: _parserscjs.stateGetRuntimeVersion,
52
- lp_total_balances: _parserscjs.lpTotalBalances
45
+ state_getRuntimeVersion: _parserscjs.stateGetRuntimeVersion
53
46
  };
54
47
 
55
48