@paraswap/dex-lib 3.11.1 → 3.11.3-remove-data-fluid-dex.0

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 (198) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/codeStyles/Project.xml +19 -0
  3. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  4. package/.idea/misc.xml +6 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/paraswap-dex-lib.iml +9 -0
  7. package/.idea/prettier.xml +7 -0
  8. package/.idea/vcs.xml +6 -0
  9. package/build/abi/{inception/inception-ineth-pool.json → cables/CablesMainnetRFQ.json} +511 -490
  10. package/build/abi/integral/factory.json +333 -0
  11. package/build/abi/integral/oracle.json +501 -0
  12. package/build/abi/integral/pool.json +1041 -0
  13. package/build/abi/{wombat/pool.json → integral/relayer.json} +720 -473
  14. package/build/config.js +1 -0
  15. package/build/config.js.map +1 -1
  16. package/build/dex/aave-v1/aave-v1.d.ts +1 -2
  17. package/build/dex/aave-v1/aave-v1.js +0 -23
  18. package/build/dex/aave-v1/aave-v1.js.map +1 -1
  19. package/build/dex/bebop/bebop.js +1 -1
  20. package/build/dex/bebop/bebop.js.map +1 -1
  21. package/build/dex/bebop/config.js +5 -0
  22. package/build/dex/bebop/config.js.map +1 -1
  23. package/build/dex/bebop/rate-fetcher.d.ts +3 -1
  24. package/build/dex/bebop/rate-fetcher.js +42 -2
  25. package/build/dex/bebop/rate-fetcher.js.map +1 -1
  26. package/build/dex/bebop/validators.d.ts +2 -0
  27. package/build/dex/bebop/validators.js +9 -1
  28. package/build/dex/bebop/validators.js.map +1 -1
  29. package/build/dex/cables/cables.d.ts +57 -0
  30. package/build/dex/cables/cables.js +471 -0
  31. package/build/dex/cables/cables.js.map +1 -0
  32. package/build/dex/cables/config.d.ts +4 -0
  33. package/build/dex/cables/config.js +15 -0
  34. package/build/dex/cables/config.js.map +1 -0
  35. package/build/dex/cables/constants.d.ts +19 -0
  36. package/build/dex/cables/constants.js +26 -0
  37. package/build/dex/cables/constants.js.map +1 -0
  38. package/build/dex/cables/rate-fetcher.d.ts +34 -0
  39. package/build/dex/cables/rate-fetcher.js +106 -0
  40. package/build/dex/cables/rate-fetcher.js.map +1 -0
  41. package/build/dex/cables/types.d.ts +106 -0
  42. package/build/dex/cables/types.js +12 -0
  43. package/build/dex/cables/types.js.map +1 -0
  44. package/build/dex/cables/validators.d.ts +5 -0
  45. package/build/dex/cables/validators.js +49 -0
  46. package/build/dex/cables/validators.js.map +1 -0
  47. package/build/dex/fluid-dex/fluid-dex-generate-pool.d.ts +49 -0
  48. package/build/dex/fluid-dex/fluid-dex-generate-pool.js +104 -0
  49. package/build/dex/fluid-dex/fluid-dex-generate-pool.js.map +1 -0
  50. package/build/dex/fluid-dex/fluid-dex.d.ts +1 -1
  51. package/build/dex/fluid-dex/fluid-dex.js +6 -10
  52. package/build/dex/fluid-dex/fluid-dex.js.map +1 -1
  53. package/build/dex/fluid-dex/types.d.ts +1 -5
  54. package/build/dex/integral/config.d.ts +4 -0
  55. package/build/dex/integral/config.js +20 -0
  56. package/build/dex/integral/config.js.map +1 -0
  57. package/build/dex/integral/context.d.ts +40 -0
  58. package/build/dex/integral/context.js +158 -0
  59. package/build/dex/integral/context.js.map +1 -0
  60. package/build/dex/integral/integral-factory.d.ts +24 -0
  61. package/build/dex/integral/integral-factory.js +95 -0
  62. package/build/dex/integral/integral-factory.js.map +1 -0
  63. package/build/dex/integral/integral-pool.d.ts +50 -0
  64. package/build/dex/integral/integral-pool.js +149 -0
  65. package/build/dex/integral/integral-pool.js.map +1 -0
  66. package/build/dex/integral/integral-pricing.d.ts +18 -0
  67. package/build/dex/integral/integral-pricing.js +114 -0
  68. package/build/dex/integral/integral-pricing.js.map +1 -0
  69. package/build/dex/integral/integral-relayer.d.ts +42 -0
  70. package/build/dex/integral/integral-relayer.js +192 -0
  71. package/build/dex/integral/integral-relayer.js.map +1 -0
  72. package/build/dex/integral/integral-token.d.ts +27 -0
  73. package/build/dex/integral/integral-token.js +59 -0
  74. package/build/dex/integral/integral-token.js.map +1 -0
  75. package/build/dex/integral/integral.d.ts +41 -0
  76. package/build/dex/integral/integral.js +376 -0
  77. package/build/dex/integral/integral.js.map +1 -0
  78. package/build/dex/integral/types.d.ts +85 -0
  79. package/build/dex/integral/types.js +9 -0
  80. package/build/dex/integral/types.js.map +1 -0
  81. package/build/dex/integral/utils-e2e.d.ts +9 -0
  82. package/build/dex/integral/utils-e2e.js +131 -0
  83. package/build/dex/integral/utils-e2e.js.map +1 -0
  84. package/build/dex/integral/utils.d.ts +17 -0
  85. package/build/dex/integral/utils.js +94 -0
  86. package/build/dex/integral/utils.js.map +1 -0
  87. package/build/dex/jarvis.d.ts +1 -2
  88. package/build/dex/jarvis.js +0 -58
  89. package/build/dex/jarvis.js.map +1 -1
  90. package/build/dex/platypus/platypus.d.ts +1 -2
  91. package/build/dex/platypus/platypus.js +0 -45
  92. package/build/dex/platypus/platypus.js.map +1 -1
  93. package/build/dex/stable-pool.js +8 -1
  94. package/build/dex/stable-pool.js.map +1 -1
  95. package/build/dex/swaap-v1/swaap-v1.d.ts +1 -2
  96. package/build/dex/swaap-v1/swaap-v1.js +0 -14
  97. package/build/dex/swaap-v1/swaap-v1.js.map +1 -1
  98. package/build/dex/trader-joe-v2.1/optimizer.d.ts +2 -0
  99. package/build/dex/trader-joe-v2.1/optimizer.js +47 -0
  100. package/build/dex/trader-joe-v2.1/optimizer.js.map +1 -0
  101. package/build/dex/zerox/index.d.ts +26 -4
  102. package/build/dex/zerox/index.js +42 -50
  103. package/build/dex/zerox/index.js.map +1 -1
  104. package/build/dex/zerox/types.d.ts +0 -29
  105. package/build/dex/zerox/types.js +1 -8
  106. package/build/dex/zerox/types.js.map +1 -1
  107. package/build/lib/fetcher/wsFetcher.d.ts +7 -3
  108. package/build/lib/fetcher/wsFetcher.js +64 -51
  109. package/build/lib/fetcher/wsFetcher.js.map +1 -1
  110. package/package.json +4 -2
  111. package/src/config.ts +1 -0
  112. package/src/dex/bebop/bebop-e2e.test.ts +21 -0
  113. package/src/dex/bebop/bebop.json +72 -0
  114. package/src/dex/bebop/bebop.proto +15 -0
  115. package/src/dex/bebop/bebop.ts +1 -1
  116. package/src/dex/bebop/config.ts +5 -0
  117. package/src/dex/bebop/rate-fetcher.ts +51 -6
  118. package/src/dex/bebop/validators.ts +10 -0
  119. package/src/dex/fluid-dex/fluid-dex.ts +7 -14
  120. package/src/dex/fluid-dex/types.ts +1 -5
  121. package/src/lib/fetcher/wsFetcher.ts +79 -66
  122. package/.vscode/launch.json +0 -53
  123. package/.vscode/settings.json +0 -2
  124. package/.vscode/tasks.json +0 -15
  125. package/build/abi/inception/inception-ratio-feed.json +0 -329
  126. package/build/abi/inception/inception-vault.json +0 -991
  127. package/build/abi/uniswap-v3/AlienBaseV3Router.abi.json +0 -52
  128. package/build/dex/aave-v2/tokens-avalanche.json +0 -44
  129. package/build/dex/aave-v2/tokens-mainnet.json +0 -188
  130. package/build/dex/aave-v2/tokens-polygon.json +0 -44
  131. package/build/dex/balancer-v3/abi/balancerBatchRouter.d.ts +0 -729
  132. package/build/dex/balancer-v3/abi/balancerBatchRouter.js +0 -732
  133. package/build/dex/balancer-v3/abi/balancerBatchRouter.js.map +0 -1
  134. package/build/dex/balancer-v3/abi/balancerRouter.d.ts +0 -1406
  135. package/build/dex/balancer-v3/abi/balancerRouter.js +0 -1175
  136. package/build/dex/balancer-v3/abi/balancerRouter.js.map +0 -1
  137. package/build/dex/balancer-v3/abi/vaultExtension.V3.d.ts +0 -2081
  138. package/build/dex/balancer-v3/abi/vaultExtension.V3.js +0 -1851
  139. package/build/dex/balancer-v3/abi/vaultExtension.V3.js.map +0 -1
  140. package/build/dex/balancer-v3/balancer-v3-pool.d.ts +0 -76
  141. package/build/dex/balancer-v3/balancer-v3-pool.js +0 -383
  142. package/build/dex/balancer-v3/balancer-v3-pool.js.map +0 -1
  143. package/build/dex/balancer-v3/balancer-v3.d.ts +0 -57
  144. package/build/dex/balancer-v3/balancer-v3.js +0 -373
  145. package/build/dex/balancer-v3/balancer-v3.js.map +0 -1
  146. package/build/dex/balancer-v3/config.d.ts +0 -8
  147. package/build/dex/balancer-v3/config.js +0 -24
  148. package/build/dex/balancer-v3/config.js.map +0 -1
  149. package/build/dex/balancer-v3/getOnChainState.d.ts +0 -10
  150. package/build/dex/balancer-v3/getOnChainState.js +0 -158
  151. package/build/dex/balancer-v3/getOnChainState.js.map +0 -1
  152. package/build/dex/balancer-v3/getPoolsApi.d.ts +0 -2
  153. package/build/dex/balancer-v3/getPoolsApi.js +0 -81
  154. package/build/dex/balancer-v3/getPoolsApi.js.map +0 -1
  155. package/build/dex/balancer-v3/getTopPoolsApi.d.ts +0 -13
  156. package/build/dex/balancer-v3/getTopPoolsApi.js +0 -62
  157. package/build/dex/balancer-v3/getTopPoolsApi.js.map +0 -1
  158. package/build/dex/balancer-v3/types.d.ts +0 -63
  159. package/build/dex/balancer-v3/types.js +0 -3
  160. package/build/dex/balancer-v3/types.js.map +0 -1
  161. package/build/dex/inception/config.d.ts +0 -4
  162. package/build/dex/inception/config.js +0 -109
  163. package/build/dex/inception/config.js.map +0 -1
  164. package/build/dex/inception/inception-event-pool.d.ts +0 -16
  165. package/build/dex/inception/inception-event-pool.js +0 -49
  166. package/build/dex/inception/inception-event-pool.js.map +0 -1
  167. package/build/dex/inception/inception.d.ts +0 -43
  168. package/build/dex/inception/inception.js +0 -180
  169. package/build/dex/inception/inception.js.map +0 -1
  170. package/build/dex/inception/tokens.d.ts +0 -9
  171. package/build/dex/inception/tokens.js +0 -28
  172. package/build/dex/inception/tokens.js.map +0 -1
  173. package/build/dex/inception/types.d.ts +0 -22
  174. package/build/dex/inception/types.js +0 -3
  175. package/build/dex/inception/types.js.map +0 -1
  176. package/build/dex/inception/utils.d.ts +0 -7
  177. package/build/dex/inception/utils.js +0 -58
  178. package/build/dex/inception/utils.js.map +0 -1
  179. package/build/dex/maker-psm/scripts/gem.abi.json +0 -136
  180. package/build/dex/maker-psm/scripts/validate-state.d.ts +0 -0
  181. package/build/dex/maker-psm/scripts/validate-state.js +0 -185
  182. package/build/dex/maker-psm/scripts/validate-state.js.map +0 -1
  183. package/build/dex/maker-psm/scripts/vat.abi.json +0 -243
  184. package/build/dex/solidly-v3/scripts/check-event-pool-event.d.ts +0 -1
  185. package/build/dex/solidly-v3/scripts/check-event-pool-event.js +0 -53
  186. package/build/dex/solidly-v3/scripts/check-event-pool-event.js.map +0 -1
  187. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.d.ts +0 -17
  188. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js +0 -64
  189. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js.map +0 -1
  190. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.d.ts +0 -17
  191. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js +0 -79
  192. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js.map +0 -1
  193. package/build/dex/uniswap-v3/uniswap-v3-pricing.d.ts +0 -4
  194. package/build/dex/uniswap-v3/uniswap-v3-pricing.js +0 -43
  195. package/build/dex/uniswap-v3/uniswap-v3-pricing.js.map +0 -1
  196. package/build/dex/uniswap-v3/uniswap-v3-worker.d.ts +0 -1
  197. package/build/dex/uniswap-v3/uniswap-v3-worker.js +0 -10
  198. package/build/dex/uniswap-v3/uniswap-v3-worker.js.map +0 -1
@@ -1,15 +1,30 @@
1
1
  import { ETHER_ADDRESS, Network } from '../../constants';
2
2
  import { IDexHelper } from '../../dex-helper';
3
3
  import { Fetcher } from '../../lib/fetcher/fetcher';
4
- import { validateAndCast } from '../../lib/validators';
4
+ import { validateAndCast, ValidationError } from '../../lib/validators';
5
5
  import { Logger, Token } from '../../types';
6
6
  import {
7
+ BebopLevel,
8
+ BebopPair,
7
9
  BebopPricingResponse,
8
10
  BebopRateFetcherConfig,
9
11
  BebopTokensResponse,
10
12
  } from './types';
11
- import { pricesResponseValidator, tokensResponseValidator } from './validators';
13
+ import {
14
+ BebopPricingUpdate,
15
+ pricesResponseValidator,
16
+ tokensResponseValidator,
17
+ } from './validators';
12
18
  import { WebSocketFetcher } from '../../lib/fetcher/wsFetcher';
19
+ import { utils } from 'ethers';
20
+
21
+ export function levels_from_flat_array(values: number[]): BebopLevel[] {
22
+ const levels: BebopLevel[] = [];
23
+ for (let i = 0; i < values.length; i += 2) {
24
+ levels.push([values[i], values[i + 1]]);
25
+ }
26
+ return levels;
27
+ }
13
28
 
14
29
  export class RateFetcher {
15
30
  private pricesFetcher: WebSocketFetcher<BebopPricingResponse>;
@@ -35,10 +50,16 @@ export class RateFetcher {
35
50
  info: {
36
51
  requestOptions: config.rateConfig.pricesReqParams,
37
52
  caster: (data: unknown) => {
38
- return validateAndCast<BebopPricingResponse>(
39
- data,
40
- pricesResponseValidator,
41
- );
53
+ const dataBuffer = data as any;
54
+ const invalid = BebopPricingUpdate.verify(dataBuffer);
55
+ if (invalid) {
56
+ throw new ValidationError(invalid);
57
+ }
58
+ const update = BebopPricingUpdate.decode(dataBuffer);
59
+ const updateObject = BebopPricingUpdate.toObject(update, {
60
+ longs: Number,
61
+ });
62
+ return this.parsePricingUpdate(updateObject);
42
63
  },
43
64
  },
44
65
  handler: this.handlePricesResponse.bind(this),
@@ -68,6 +89,30 @@ export class RateFetcher {
68
89
  );
69
90
  }
70
91
 
92
+ parsePricingUpdate(updateObject: any): BebopPricingResponse {
93
+ const pricingResponse: BebopPricingResponse = {};
94
+ if (!updateObject.pairs || !updateObject.pairs.length) {
95
+ this.logger.warn('Update message did not include pairs', updateObject);
96
+ return pricingResponse;
97
+ }
98
+ for (const pairBook of updateObject.pairs) {
99
+ const pair =
100
+ utils.getAddress('0x' + pairBook.base.toString('hex')) +
101
+ '/' +
102
+ utils.getAddress('0x' + pairBook.quote.toString('hex'));
103
+ const lastUpdateTs = pairBook.lastUpdateTs;
104
+ const bids = pairBook.bids ? levels_from_flat_array(pairBook.bids) : [];
105
+ const asks = pairBook.asks ? levels_from_flat_array(pairBook.asks) : [];
106
+ const bebopPair: BebopPair = {
107
+ bids,
108
+ asks,
109
+ last_update_ts: lastUpdateTs,
110
+ };
111
+ pricingResponse[pair] = bebopPair;
112
+ }
113
+ return pricingResponse;
114
+ }
115
+
71
116
  start() {
72
117
  this.pricesFetcher.startPolling();
73
118
  this.tokensFetcher.startPolling();
@@ -1,4 +1,6 @@
1
1
  import joi from 'joi';
2
+ import protobuf from 'protobufjs';
3
+ import JSONDescriptor from './bebop.json';
2
4
 
3
5
  const levelValidator = joi.array().items(joi.number()).length(2);
4
6
 
@@ -27,3 +29,11 @@ export const tokensResponseValidator = joi.object({
27
29
  export const blacklistResponseValidator = joi.object({
28
30
  blacklist: joi.array().items(joi.string().min(1)).required(),
29
31
  });
32
+
33
+ // Original .proto def
34
+ // const root = protobuf.loadSync(__dirname + '/bebop.proto');
35
+ // Use .json to not change build step to include .proto files
36
+ // console.log(JSON.stringify(root.toJSON(), null, 4));
37
+
38
+ const root = protobuf.Root.fromJSON(JSONDescriptor);
39
+ export const BebopPricingUpdate = root.lookupType('bebop.BebopPricingUpdate');
@@ -154,10 +154,10 @@ export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
154
154
  return pool ? [pool.id] : [];
155
155
  }
156
156
 
157
- async getPoolByTokenPair(
157
+ getPoolByTokenPair(
158
158
  srcToken: Address,
159
159
  destToken: Address,
160
- ): Promise<FluidDexPool | null> {
160
+ ): FluidDexPool | null {
161
161
  const srcAddress = srcToken.toLowerCase();
162
162
  const destAddress = destToken.toLowerCase();
163
163
 
@@ -193,10 +193,7 @@ export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
193
193
 
194
194
  if (side === SwapSide.BUY) return null;
195
195
  // Get the pool to use.
196
- const pool = await this.getPoolByTokenPair(
197
- srcToken.address,
198
- destToken.address,
199
- );
196
+ const pool = this.getPoolByTokenPair(srcToken.address, destToken.address);
200
197
  if (!pool) return null;
201
198
 
202
199
  // Make sure the pool meets the optional limitPools filter.
@@ -229,11 +226,7 @@ export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
229
226
  unit: getBigIntPow(
230
227
  (side === SwapSide.SELL ? destToken : srcToken).decimals,
231
228
  ),
232
- data: {
233
- colReserves: currentPoolReserves.collateralReserves,
234
- debtReserves: currentPoolReserves.debtReserves,
235
- exchange: this.dexKey,
236
- },
229
+ data: {},
237
230
  exchange: this.dexKey,
238
231
  poolIdentifier: pool.id,
239
232
  gasCost: FLUID_DEX_GAS_COST,
@@ -270,13 +263,13 @@ export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
270
263
  side: SwapSide,
271
264
  ): AdapterExchangeParam {
272
265
  if (side === SwapSide.BUY) throw new Error(`Buy not supported`);
273
- const { exchange } = data;
274
266
 
275
267
  // Encode here the payload for adapter
276
268
  const payload = '';
269
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
277
270
 
278
271
  return {
279
- targetExchange: exchange,
272
+ targetExchange: pool!.address,
280
273
  payload,
281
274
  networkFee: '0',
282
275
  };
@@ -316,7 +309,7 @@ export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
316
309
  'amountOut_',
317
310
  );
318
311
 
319
- const pool = await this.getPoolByTokenPair(srcToken, destToken);
312
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
320
313
 
321
314
  if (pool!.token0.toLowerCase() !== srcToken.toLowerCase()) {
322
315
  args = [false, BigInt(srcAmount), BigInt(destAmount), recipient];
@@ -48,11 +48,7 @@ export interface PoolWithReserves {
48
48
  debtReserves: DebtReserves;
49
49
  }
50
50
 
51
- export type FluidDexData = {
52
- colReserves: CollateralReserves;
53
- debtReserves: DebtReserves;
54
- exchange: Address;
55
- };
51
+ export type FluidDexData = {};
56
52
 
57
53
  // Each pool has a contract address and token pairs.
58
54
  export type FluidDexPool = {
@@ -1,10 +1,6 @@
1
1
  import { Logger } from 'log4js';
2
2
  import { RequestConfig, Response } from '../../dex-helper/irequest-wrapper';
3
- import {
4
- connection as WebSocketConnection,
5
- client as WebSocketClient,
6
- } from 'websocket';
7
-
3
+ import WebSocket from 'ws';
8
4
  export class SkippingRequest {
9
5
  constructor(public message = '') {}
10
6
  }
@@ -26,74 +22,77 @@ export type RequestInfoWithHandler<T> = {
26
22
 
27
23
  export class WebSocketFetcher<T> {
28
24
  private requests: RequestInfoWithHandler<T>;
25
+ // Time to wait before declaring connection as broken and restarting it
26
+ private timeoutInterval: number;
27
+ // Time to wait after disconnection before reconnecting
28
+ private reconnectDelay: number;
29
+ private pingTimeout: NodeJS.Timeout | undefined = undefined;
29
30
  public lastFetchSucceeded: boolean = false;
30
31
  private stop: boolean = true;
31
- private ws: WebSocketClient = new WebSocketClient();
32
- private connection: WebSocketConnection | null = null;
33
-
34
- constructor(requestsInfo: RequestInfoWithHandler<T>, private logger: Logger) {
32
+ private connection: WebSocket | null = null;
33
+
34
+ constructor(
35
+ requestsInfo: RequestInfoWithHandler<T>,
36
+ private logger: Logger,
37
+ timeoutInterval: number = 10000,
38
+ reconnectDelay: number = 5000,
39
+ ) {
35
40
  this.requests = requestsInfo;
36
- this.ws.on('connect', this.connected.bind(this));
37
- this.ws.on('connectFailed', this.connectFailed.bind(this));
41
+ this.timeoutInterval = timeoutInterval;
42
+ this.reconnectDelay = reconnectDelay;
38
43
  }
39
44
 
40
- private connected(connection: WebSocketConnection) {
41
- this.connection = connection;
45
+ private connected() {
42
46
  this.logger.info(`Connected to ${this.requests.info.requestOptions.url}`);
43
- this.connection.on('error', this.onError.bind(this));
44
- this.connection.on('close', this.onClose.bind(this));
45
- this.connection.on('message', this.onMessage.bind(this));
47
+ this.heartbeat();
46
48
  }
47
49
 
48
- private connectFailed(error: any) {
49
- this.logger.error(`Connect Error: ${error.toString()}. Reconnecting...`);
50
- // reconnect on errors / failures
51
- setTimeout(() => {
52
- this.startPolling();
53
- }, 3000);
50
+ private heartbeat() {
51
+ clearTimeout(this.pingTimeout);
52
+ this.pingTimeout = setTimeout(() => {
53
+ this.logger.warn('No heartbeat. Terminating Connection...');
54
+ this?.connection?.terminate();
55
+ }, this.timeoutInterval);
54
56
  }
55
57
 
56
58
  private onClose() {
57
- this.logger.info(`Connection closed. Reconnecting...`);
58
- // reconnect on errors / failures
59
- setTimeout(() => {
60
- this.startPolling();
61
- }, 3000);
59
+ this.logger.info(`Connection closed.`);
60
+ // Do not reconnect if polling is stopped
61
+ if (this.stop) {
62
+ clearTimeout(this.pingTimeout);
63
+ return;
64
+ }
65
+
66
+ this.logger.info(`Unexpected closure, Reconnecting...`);
67
+ this.reconnectWithDelay();
62
68
  }
63
69
 
64
70
  private onError(error: any) {
65
71
  this.logger.error(
66
- `Connection Error: ${error.toString()}. Stopping & Reconnecting...`,
72
+ `Websocket Error: ${error.toString()}. Stopping & Reconnecting...`,
67
73
  );
68
- this.stopPolling();
69
-
70
- // reconnect on errors / failures
71
- setTimeout(() => {
72
- this.startPolling();
73
- }, 3000);
74
+ this?.connection?.terminate();
74
75
  }
75
76
 
76
- private onMessage(message: any) {
77
- if (message.type === 'utf8') {
78
- const response = JSON.parse(message.utf8Data) as Response<T>;
79
- const reqInfo = this.requests;
80
- const info = reqInfo.info;
81
- const options = reqInfo.info.requestOptions;
82
- this.logger.debug(`(${options.url}) received new data`);
83
-
84
- try {
85
- const parsedData = info.caster(response);
86
- reqInfo.handler(parsedData);
87
- } catch (e) {
88
- this.logger.info(e);
89
- this.logger.info(
90
- `(${options.url}) received incorrect data ${JSON.stringify(
91
- response,
92
- ).replace(/(?:\r\n|\r|\n)/g, ' ')}`,
93
- e,
94
- );
95
- return;
96
- }
77
+ private onMessage(data: WebSocket.RawData) {
78
+ this.heartbeat();
79
+ const reqInfo = this.requests;
80
+ const info = reqInfo.info;
81
+ const options = reqInfo.info.requestOptions;
82
+ this.logger.debug(`(${options.url}) received new data`);
83
+
84
+ try {
85
+ const parsedData = info.caster(data);
86
+ reqInfo.handler(parsedData);
87
+ } catch (e) {
88
+ this.logger.info(e);
89
+ this.logger.info(
90
+ `(${options.url}) received incorrect data ${JSON.stringify(
91
+ data,
92
+ ).replace(/(?:\r\n|\r|\n)/g, ' ')}`,
93
+ e,
94
+ );
95
+ return;
97
96
  }
98
97
  }
99
98
 
@@ -110,30 +109,44 @@ export class WebSocketFetcher<T> {
110
109
  this.logger.info(
111
110
  `Connecting to ${this.requests.info.requestOptions.url}...`,
112
111
  );
113
- this.ws.connect(
114
- this.requests.info.requestOptions.url!,
115
- undefined,
116
- undefined,
117
- {
112
+ const ws = new WebSocket(this.requests.info.requestOptions.url!, {
113
+ headers: {
118
114
  Authorization: authorization,
119
115
  name: name,
120
116
  },
121
- );
117
+ });
118
+
119
+ ws.on('open', this.connected.bind(this));
120
+ ws.on('message', this.onMessage.bind(this));
121
+ ws.on('error', this.onError.bind(this));
122
+ ws.on('close', this.onClose.bind(this));
123
+ this.connection = ws;
122
124
  }
123
125
 
124
- startPolling(): void {
125
- this.stop = false;
126
+ reconnectWithDelay() {
127
+ this.logger.info(`Waiting ${this.reconnectDelay}ms before reconnecting...`);
128
+ clearTimeout(this.pingTimeout);
129
+ setTimeout(() => {
130
+ this.reconnect();
131
+ }, this.reconnectDelay);
132
+ }
133
+
134
+ reconnect() {
135
+ clearTimeout(this.pingTimeout);
126
136
  this.connect();
127
137
  this.logger.info(
128
138
  `Connection started for ${this.requests.info.requestOptions.url}`,
129
139
  );
130
140
  }
131
141
 
142
+ startPolling(): void {
143
+ this.stop = false;
144
+ this.reconnect();
145
+ }
146
+
132
147
  stopPolling() {
133
- if (this.connection) {
134
- this.connection.close();
135
- }
136
148
  this.stop = true;
149
+ this.connection?.terminate();
137
150
  this.logger.info(
138
151
  `Connection stopped for ${this.requests.info.requestOptions.url}`,
139
152
  );
@@ -1,53 +0,0 @@
1
- {
2
- "version": "0.2.0",
3
- "configurations": [
4
- {
5
- "type": "node",
6
- "request": "launch",
7
- "name": "Current",
8
- "program": "${file}",
9
- "preLaunchTask": "npm: build",
10
- "sourceMaps": true,
11
- "smartStep": true,
12
- "internalConsoleOptions": "openOnSessionStart",
13
- "outFiles": ["${workspaceFolder}/build/**/*.js"]
14
- },
15
- {
16
- "type": "node",
17
- "request": "launch",
18
- "name": "Debug dex integration",
19
- "program": "${workspaceFolder}/node_modules/ts-node/dist/bin.js",
20
- "args": [
21
- "--project",
22
- "tsconfig.json",
23
- // "${workspaceFolder}/src/dex/algebra/scripts/validate-state.ts",
24
- "${workspaceFolder}/src/dex/camelot/camelot-pool-discovery.test.ts",
25
- // "${workspaceFolder}/src/dex/solidly-v3/scripts/check-event-pool-event.ts",
26
- // "${workspaceFolder}/scripts/dex-integration.ts",
27
- "test",
28
- "wombat"
29
- ],
30
- "console": "integratedTerminal",
31
- "internalConsoleOptions": "neverOpen",
32
- "runtimeArgs": ["--nolazy"],
33
- "sourceMaps": true,
34
- "smartStep": true,
35
- "skipFiles": ["<node_internals>/**"],
36
- "cwd": "${workspaceFolder}"
37
- },
38
- {
39
- "type": "node",
40
- "name": "Jest file",
41
- "request": "launch",
42
- "program": "${workspaceFolder}/node_modules/jest/bin/jest.js",
43
- // "program": "${workspaceFolder}/src/dex/camelot/scripts/validate-state.ts",
44
- // "args": ["src/dex/balancer-v1/balancer-v1-e2e.test.ts"],
45
- // "args": ["${relativeFile}"],
46
- "args": ["${file}"],
47
- "cwd": "${workspaceRoot}",
48
- "console": "integratedTerminal",
49
- "internalConsoleOptions": "neverOpen",
50
- "sourceMaps": true
51
- }
52
- ]
53
- }
@@ -1,2 +0,0 @@
1
- {
2
- }
@@ -1,15 +0,0 @@
1
- {
2
- "version": "2.0.0",
3
- "tasks": [
4
- {
5
- "label": "tsc: build - tsconfig.json",
6
- "type": "typescript",
7
- "tsconfig": "tsconfig.json",
8
- "problemMatcher": ["$tsc"],
9
- "group": {
10
- "kind": "build",
11
- "isDefault": true
12
- }
13
- }
14
- ]
15
- }