@paraswap/dex-lib 3.11.4 → 3.11.5-cables.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.
@@ -0,0 +1,911 @@
1
+ import {
2
+ Address,
3
+ NumberAsString,
4
+ OptimalSwapExchange,
5
+ SwapSide,
6
+ } from '@paraswap/core';
7
+ import { AsyncOrSync } from 'ts-essentials';
8
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
9
+ import { assert } from 'ts-essentials';
10
+ import { Network, ETHER_ADDRESS, NULL_ADDRESS } from '../../constants';
11
+ import { IDexHelper } from '../../dex-helper';
12
+ import {
13
+ AdapterExchangeParam,
14
+ DexExchangeParam,
15
+ ExchangePrices,
16
+ ExchangeTxInfo,
17
+ Logger,
18
+ PoolLiquidity,
19
+ PoolPrices,
20
+ PreprocessTransactionOptions,
21
+ Token,
22
+ TransferFeeParams,
23
+ } from '../../types';
24
+ import { getDexKeysWithNetwork, Utils } from '../../utils';
25
+ import { IDex } from '../idex';
26
+ import { SimpleExchange } from '../simple-exchange';
27
+ import { CablesConfig } from './config';
28
+ import {
29
+ CABLES_API_BLACKLIST_POLLING_INTERVAL_MS,
30
+ CABLES_API_PAIRS_POLLING_INTERVAL_MS,
31
+ CABLES_API_PRICES_POLLING_INTERVAL_MS,
32
+ CABLES_API_TOKENS_POLLING_INTERVAL_MS,
33
+ CABLES_API_URL,
34
+ CABLES_BLACKLIST_CACHE_KEY,
35
+ CABLES_BLACKLIST_CACHES_TTL_S,
36
+ CABLES_ERRORS_CACHE_KEY,
37
+ CABLES_FIRM_QUOTE_TIMEOUT_MS,
38
+ CABLES_GAS_COST,
39
+ CABLES_PAIRS_CACHES_TTL_S,
40
+ CABLES_PRICES_CACHES_TTL_S,
41
+ CABLES_RESTRICT_CHECK_INTERVAL_MS,
42
+ CABLES_RESTRICT_COUNT_THRESHOLD,
43
+ CABLES_RESTRICT_TTL_S,
44
+ CABLES_RESTRICTED_CACHE_KEY,
45
+ CABLES_TOKENS_CACHES_TTL_S,
46
+ } from './constants';
47
+ import { CablesRateFetcher } from './rate-fetcher';
48
+ import {
49
+ CablesData,
50
+ CablesRFQResponse,
51
+ RestrictData,
52
+ SlippageError,
53
+ } from './types';
54
+ import mainnetRFQAbi from '../../abi/cables/CablesMainnetRFQ.json';
55
+ import { Interface } from 'ethers/lib/utils';
56
+ import BigNumber from 'bignumber.js';
57
+ import { ethers, utils } from 'ethers';
58
+ import { BI_MAX_UINT256 } from '../../bigint-constants';
59
+
60
+ export class Cables extends SimpleExchange implements IDex<any> {
61
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
62
+ getDexKeysWithNetwork(CablesConfig);
63
+
64
+ readonly isStatePollingDex = true;
65
+
66
+ private rateFetcher: CablesRateFetcher;
67
+
68
+ logger: Logger;
69
+ private tokensMap: { [address: string]: Token } = {};
70
+
71
+ hasConstantPriceLargeAmounts: boolean = false;
72
+
73
+ constructor(
74
+ readonly network: Network,
75
+ readonly dexKey: string,
76
+ readonly dexHelper: IDexHelper,
77
+ readonly mainnetRFQAddress: string = CablesConfig['Cables'][network]
78
+ .mainnetRFQAddress,
79
+ protected rfqInterface = new Interface(mainnetRFQAbi),
80
+ ) {
81
+ super(dexHelper, dexKey);
82
+ this.logger = dexHelper.getLogger(dexKey);
83
+
84
+ this.rateFetcher = new CablesRateFetcher(
85
+ this.dexHelper,
86
+ this.dexKey,
87
+ this.network,
88
+ this.logger,
89
+ {
90
+ rateConfig: {
91
+ pairsReqParams: {
92
+ url: CABLES_API_URL + '/pairs',
93
+ },
94
+ pricesReqParams: {
95
+ url: CABLES_API_URL + '/prices',
96
+ },
97
+ blacklistReqParams: {
98
+ url: CABLES_API_URL + '/blacklist',
99
+ },
100
+ tokensReqParams: {
101
+ url: CABLES_API_URL + '/tokens',
102
+ },
103
+
104
+ pricesIntervalMs: CABLES_API_PRICES_POLLING_INTERVAL_MS,
105
+ pricesCacheTTLSecs: CABLES_PRICES_CACHES_TTL_S,
106
+ pricesCacheKey: 'cablesPricesCacheKey',
107
+
108
+ pairsIntervalMs: CABLES_API_PAIRS_POLLING_INTERVAL_MS,
109
+ pairsCacheTTLSecs: CABLES_PAIRS_CACHES_TTL_S,
110
+ pairsCacheKey: 'cablesPairsCacheKey',
111
+
112
+ tokensIntervalMs: CABLES_API_TOKENS_POLLING_INTERVAL_MS,
113
+ tokensCacheTTLSecs: CABLES_TOKENS_CACHES_TTL_S,
114
+ tokensCacheKey: 'cablesTokensCacheKey',
115
+
116
+ blacklistIntervalMs: CABLES_API_BLACKLIST_POLLING_INTERVAL_MS,
117
+ blacklistCacheTTLSecs: CABLES_BLACKLIST_CACHES_TTL_S,
118
+ blacklistCacheKey: CABLES_BLACKLIST_CACHE_KEY,
119
+ },
120
+ },
121
+ );
122
+ }
123
+
124
+ async preProcessTransaction?(
125
+ optimalSwapExchange: OptimalSwapExchange<CablesData>,
126
+ srcToken: Token,
127
+ destToken: Token,
128
+ side: SwapSide,
129
+ options: PreprocessTransactionOptions,
130
+ ): Promise<[OptimalSwapExchange<CablesData>, ExchangeTxInfo]> {
131
+ if (await this.isBlacklisted(options.txOrigin)) {
132
+ this.logger.warn(
133
+ `${this.dexKey}-${this.network}: blacklisted TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`,
134
+ );
135
+ throw new Error(
136
+ `${this.dexKey}-${
137
+ this.network
138
+ }: user=${options.txOrigin.toLowerCase()} is blacklisted`,
139
+ );
140
+ }
141
+
142
+ if (BigInt(optimalSwapExchange.srcAmount) === 0n) {
143
+ throw new Error('getFirmRate failed with srcAmount === 0');
144
+ }
145
+
146
+ const normalizedSrcToken = this.normalizeToken(srcToken);
147
+ const normalizedDestToken = this.normalizeToken(destToken);
148
+ const swapIdentifier = `${this.dexKey}_${normalizedSrcToken.address}_${normalizedDestToken.address}_${side}`;
149
+
150
+ try {
151
+ const makerToken = normalizedDestToken;
152
+ const takerToken = normalizedSrcToken;
153
+
154
+ const isSell = side === SwapSide.SELL;
155
+ const isBuy = side === SwapSide.BUY;
156
+
157
+ const rfqParams = {
158
+ makerAsset: ethers.utils.getAddress(makerToken.address),
159
+ takerAsset: ethers.utils.getAddress(takerToken.address),
160
+ ...(isBuy && { makerAmount: optimalSwapExchange.destAmount }),
161
+ ...(isSell && { takerAmount: optimalSwapExchange.srcAmount }),
162
+ userAddress: options.executionContractAddress,
163
+ chainId: String(this.network),
164
+ };
165
+
166
+ const rfq: CablesRFQResponse = await this.dexHelper.httpRequest.post(
167
+ `${CABLES_API_URL}/quote`,
168
+ rfqParams,
169
+ CABLES_FIRM_QUOTE_TIMEOUT_MS,
170
+ );
171
+
172
+ if (!rfq) {
173
+ throw new Error(
174
+ 'Failed to fetch RFQ' +
175
+ swapIdentifier +
176
+ JSON.stringify(rfq + 'params' + rfqParams),
177
+ );
178
+ }
179
+
180
+ const { order } = rfq;
181
+
182
+ assert(
183
+ order.makerAsset.toLowerCase() === makerToken.address,
184
+ `QuoteData makerAsset=${order.makerAsset} is different from Paraswap makerAsset=${makerToken.address}`,
185
+ );
186
+ assert(
187
+ order.takerAsset.toLowerCase() === takerToken.address,
188
+ `QuoteData takerAsset=${order.takerAsset} is different from Paraswap takerAsset=${takerToken.address}`,
189
+ );
190
+ if (isSell) {
191
+ assert(
192
+ order.takerAmount === optimalSwapExchange.srcAmount,
193
+ `QuoteData takerAmount=${order.takerAmount} is different from Paraswap srcAmount=${optimalSwapExchange.srcAmount}`,
194
+ );
195
+ } else {
196
+ assert(
197
+ order.makerAmount === optimalSwapExchange.destAmount,
198
+ `QuoteData makerAmount=${order.makerAmount} is different from Paraswap destAmount=${optimalSwapExchange.destAmount}`,
199
+ );
200
+ }
201
+
202
+ const expiryAsBigInt = BigInt(order.expiry);
203
+ const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : BI_MAX_UINT256;
204
+
205
+ if (side === SwapSide.SELL) {
206
+ const requiredAmount = BigInt(optimalSwapExchange.destAmount);
207
+ const quoteAmount = BigInt(order.makerAmount);
208
+ const requiredAmountWithSlippage = new BigNumber(
209
+ requiredAmount.toString(),
210
+ )
211
+ .times(options.slippageFactor)
212
+ .toFixed(0);
213
+ if (quoteAmount < BigInt(requiredAmountWithSlippage)) {
214
+ throw new SlippageError(
215
+ `Slipped, factor: ${quoteAmount.toString()} < ${requiredAmountWithSlippage}`,
216
+ );
217
+ }
218
+ } else {
219
+ const requiredAmount = BigInt(optimalSwapExchange.srcAmount);
220
+ const quoteAmount = BigInt(order.takerAmount);
221
+ const requiredAmountWithSlippage = new BigNumber(
222
+ requiredAmount.toString(),
223
+ )
224
+ .times(options.slippageFactor)
225
+ .toFixed(0);
226
+ if (quoteAmount > BigInt(requiredAmountWithSlippage)) {
227
+ throw new SlippageError(
228
+ `Slipped, factor: ${
229
+ options.slippageFactor
230
+ } ${quoteAmount.toString()} > ${requiredAmountWithSlippage}`,
231
+ );
232
+ }
233
+ }
234
+
235
+ return [
236
+ {
237
+ ...optimalSwapExchange,
238
+ data: {
239
+ quoteData: order,
240
+ },
241
+ },
242
+ { deadline: minDeadline },
243
+ ];
244
+ } catch (e: any) {
245
+ const message = `${this.dexKey}-${this.network}: ${e}`;
246
+ this.logger.error(message);
247
+ if (!e?.isSlippageError) {
248
+ this.restrict();
249
+ }
250
+ throw new Error(message);
251
+ }
252
+ }
253
+
254
+ getDexParam(
255
+ srcToken: Address,
256
+ destToken: Address,
257
+ srcAmount: NumberAsString,
258
+ destAmount: NumberAsString,
259
+ recipient: Address,
260
+ data: CablesData,
261
+ side: SwapSide,
262
+ ): DexExchangeParam {
263
+ const { quoteData } = data;
264
+
265
+ assert(
266
+ quoteData !== undefined,
267
+ `${this.dexKey}-${this.network}: quoteData undefined`,
268
+ );
269
+
270
+ const swapFunction = 'simpleSwap';
271
+ const swapFunctionParams = [
272
+ [
273
+ quoteData.nonceAndMeta,
274
+ quoteData.expiry,
275
+ quoteData.makerAsset,
276
+ quoteData.takerAsset,
277
+ quoteData.maker,
278
+ quoteData.taker,
279
+ quoteData.makerAmount,
280
+ quoteData.takerAmount,
281
+ ],
282
+ quoteData.signature,
283
+ ];
284
+
285
+ const exchangeData = this.rfqInterface.encodeFunctionData(
286
+ swapFunction,
287
+ swapFunctionParams,
288
+ );
289
+
290
+ return {
291
+ exchangeData,
292
+ needWrapNative: this.needWrapNative,
293
+ dexFuncHasRecipient: false,
294
+ targetExchange: this.mainnetRFQAddress,
295
+ returnAmountPos: undefined,
296
+ };
297
+ }
298
+
299
+ getAdapterParam(
300
+ srcToken: string,
301
+ destToken: string,
302
+ srcAmount: string,
303
+ destAmount: string,
304
+ data: CablesData,
305
+ side: SwapSide,
306
+ ): AdapterExchangeParam {
307
+ const { quoteData } = data;
308
+
309
+ assert(
310
+ quoteData !== undefined,
311
+ `${this.dexKey}-${this.network}: quoteData undefined`,
312
+ );
313
+
314
+ const params = [
315
+ {
316
+ nonceAndMeta: quoteData.nonceAndMeta,
317
+ expiry: quoteData.expiry,
318
+ makerAsset: quoteData.makerAsset,
319
+ takerAsset: quoteData.takerAsset,
320
+ maker: quoteData.maker,
321
+ taker: quoteData.taker,
322
+ makerAmount: quoteData.makerAmount,
323
+ takerAmount: quoteData.takerAmount,
324
+ },
325
+ quoteData.signature,
326
+ ];
327
+
328
+ const payload = this.abiCoder.encodeParameter(
329
+ {
330
+ ParentStruct: {
331
+ order: {
332
+ nonceAndMeta: 'uint256',
333
+ expiry: 'uint128',
334
+ makerAsset: 'address',
335
+ takerAsset: 'address',
336
+ maker: 'address',
337
+ taker: 'address',
338
+ makerAmount: 'uint256',
339
+ takerAmount: 'uint256',
340
+ },
341
+ signature: 'bytes',
342
+ },
343
+ },
344
+ {
345
+ order: params[0],
346
+ signature: params[1],
347
+ },
348
+ );
349
+
350
+ return {
351
+ targetExchange: this.mainnetRFQAddress,
352
+ payload,
353
+ networkFee: '0',
354
+ };
355
+ }
356
+
357
+ normalizeToken(token: Token): Token {
358
+ return {
359
+ ...token,
360
+ address: this.normalizeTokenAddress(token.address),
361
+ };
362
+ }
363
+
364
+ normalizeTokenAddress(address: Address): Address {
365
+ return address.toLowerCase();
366
+ }
367
+
368
+ getTokenFromAddress(address: Address): Token {
369
+ return this.tokensMap[this.normalizeAddress(address)];
370
+ }
371
+
372
+ getPoolIdentifier(srcAddress: Address, destAddress: Address, mm?: string) {
373
+ return `${this.dexKey}_${srcAddress}_${destAddress}`.toLowerCase();
374
+ return `${this.dexKey}_${srcAddress}_${destAddress}_${mm}`.toLowerCase();
375
+ }
376
+
377
+ async getPoolIdentifiers(
378
+ srcToken: Token,
379
+ destToken: Token,
380
+ side: SwapSide,
381
+ blockNumber: number,
382
+ ): Promise<string[]> {
383
+ if (!srcToken || !destToken) {
384
+ return [];
385
+ }
386
+
387
+ if (srcToken.address.toLowerCase() === destToken.address.toLowerCase()) {
388
+ return [];
389
+ }
390
+
391
+ const pairData = await this.getPairData(srcToken, destToken);
392
+
393
+ if (!pairData) {
394
+ return [];
395
+ }
396
+
397
+ const tokensAddr = (await this.getCachedTokensAddr()) || {};
398
+
399
+ return [
400
+ this.getPoolIdentifier(
401
+ tokensAddr[pairData.base.toLowerCase()],
402
+ tokensAddr[pairData.quote.toLowerCase()],
403
+ ),
404
+ ];
405
+ }
406
+
407
+ calculateOrderPrice(
408
+ amounts: bigint[],
409
+ orderbook: string[][],
410
+ baseToken: Token,
411
+ quoteToken: Token,
412
+ isInputQuote: boolean,
413
+ ) {
414
+ let result = [];
415
+
416
+ for (let i = 0; i < amounts.length; i++) {
417
+ let amt = amounts[i];
418
+ if (amt === 0n) {
419
+ result.push(amt);
420
+ continue;
421
+ }
422
+
423
+ let decimals = baseToken.decimals;
424
+ if (isInputQuote) {
425
+ decimals = quoteToken.decimals;
426
+ }
427
+ let price = this.calculatePriceSwap(
428
+ orderbook,
429
+ Number(amt) / 10 ** decimals,
430
+ isInputQuote,
431
+ );
432
+ result.push(BigInt(Math.round(price * 10 ** decimals)));
433
+ }
434
+ return result;
435
+ }
436
+
437
+ calculatePriceSwap(
438
+ prices: string[][],
439
+ requiredQty: number,
440
+ qtyMode: Boolean,
441
+ ) {
442
+ let sumBaseQty = 0;
443
+ let sumQuoteQty = 0;
444
+ const selectedRows: string[][] = [];
445
+
446
+ const isBase = !qtyMode;
447
+ const isQuote = qtyMode;
448
+
449
+ for (const [price, volume] of prices) {
450
+ if (isBase) {
451
+ if (sumBaseQty >= requiredQty) {
452
+ break;
453
+ }
454
+ }
455
+
456
+ if (isQuote) {
457
+ if (sumQuoteQty >= requiredQty) {
458
+ break;
459
+ }
460
+ }
461
+
462
+ let currentBaseQty = Number(volume);
463
+ let currentQuoteQty = Number(volume) * Number(price);
464
+
465
+ const overQty = isBase
466
+ ? currentBaseQty + sumBaseQty > requiredQty
467
+ : currentQuoteQty + sumQuoteQty > requiredQty;
468
+
469
+ if (overQty) {
470
+ if (isBase) {
471
+ currentBaseQty = requiredQty - sumBaseQty;
472
+ currentQuoteQty = currentBaseQty * Number(price);
473
+ }
474
+
475
+ if (isQuote) {
476
+ currentQuoteQty = requiredQty - sumQuoteQty;
477
+ currentBaseQty =
478
+ currentQuoteQty *
479
+ new BigNumber(1).dividedBy(new BigNumber(price)).toNumber();
480
+ }
481
+ }
482
+
483
+ sumBaseQty += currentBaseQty;
484
+ sumQuoteQty += currentQuoteQty;
485
+ selectedRows.push([price, currentBaseQty.toString()]);
486
+ }
487
+
488
+ const vSumBase = selectedRows.reduce((sum: number, [price, volume]) => {
489
+ return sum + Number(price) * Number(volume);
490
+ }, 0);
491
+
492
+ if (isBase) {
493
+ return sumBaseQty;
494
+ } else {
495
+ return sumQuoteQty;
496
+ }
497
+ }
498
+
499
+ async getPricesVolume(
500
+ srcToken: Token,
501
+ destToken: Token,
502
+ amounts: bigint[],
503
+ side: SwapSide,
504
+ blockNumber: number,
505
+ limitPools?: string[],
506
+ transferFees?: TransferFeeParams,
507
+ isFirstSwap?: boolean,
508
+ ): Promise<ExchangePrices<CablesData> | null> {
509
+ const isRestricted = await this.isRestricted();
510
+ if (isRestricted) {
511
+ return null;
512
+ }
513
+
514
+ try {
515
+ const normalizedSrcToken = this.normalizeToken(srcToken);
516
+ const normalizedDestToken = this.normalizeToken(destToken);
517
+ // If: same token, return null
518
+ if (
519
+ normalizedSrcToken.address.toLowerCase() ===
520
+ normalizedDestToken.address.toLowerCase()
521
+ ) {
522
+ return null;
523
+ }
524
+
525
+ // Ensure that "symbol" is set
526
+ const tokens = await this.getCachedTokens();
527
+ this.tokensMap = Object.keys(tokens).reduce((acc, key) => {
528
+ //@ts-ignore
529
+ acc[tokens[key].address.toLowerCase()] = tokens[key];
530
+ return acc;
531
+ }, {});
532
+
533
+ for (const symbol of Object.keys(tokens)) {
534
+ const normalizedTokenAddress = tokens[symbol].address.toLowerCase();
535
+
536
+ if (normalizedSrcToken.address === normalizedTokenAddress) {
537
+ normalizedSrcToken.symbol = tokens[symbol].symbol;
538
+ }
539
+ if (normalizedDestToken.address === normalizedTokenAddress) {
540
+ normalizedDestToken.symbol = tokens[symbol].symbol;
541
+ }
542
+ }
543
+
544
+ // ---------- Pools ----------
545
+ let pools = await this.getPoolIdentifiers(
546
+ srcToken,
547
+ destToken,
548
+ side,
549
+ blockNumber,
550
+ );
551
+ if (pools.length === 0) return null;
552
+
553
+ // ---------- Prices ----------
554
+ const priceMap = await this.getCachedPrices();
555
+
556
+ if (!priceMap) return null;
557
+
558
+ let pairKey = `${normalizedSrcToken.symbol}/${normalizedDestToken.symbol}`;
559
+ const pairsKeys = Object.keys(priceMap);
560
+
561
+ if (!pairsKeys.includes(pairKey)) {
562
+ // Revert
563
+ pairKey = `${normalizedDestToken.symbol}/${normalizedSrcToken.symbol}`;
564
+ if (!pairsKeys.includes(pairKey)) {
565
+ return null;
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Orderbook
571
+ */
572
+ const priceData = priceMap[pairKey];
573
+
574
+ let orderbook: any[] = [];
575
+ if (side === SwapSide.BUY) {
576
+ orderbook = priceData.asks;
577
+ } else {
578
+ orderbook = priceData.bids;
579
+ }
580
+ if (orderbook?.length === 0) {
581
+ throw new Error(`Empty orderbook for ${pairKey}`);
582
+ }
583
+
584
+ const isInputQuote = side === SwapSide.BUY;
585
+
586
+ const prices = this.calculateOrderPrice(
587
+ amounts,
588
+ orderbook,
589
+ srcToken,
590
+ destToken,
591
+ isInputQuote,
592
+ );
593
+
594
+ const outDecimals =
595
+ side === SwapSide.BUY
596
+ ? normalizedSrcToken.decimals
597
+ : normalizedDestToken.decimals;
598
+ const result = [
599
+ {
600
+ prices: prices,
601
+ unit: BigInt(outDecimals),
602
+ exchange: this.dexKey,
603
+ gasCost: CABLES_GAS_COST,
604
+ poolAddresses: [this.mainnetRFQAddress],
605
+ data: {},
606
+ },
607
+ ];
608
+ return result;
609
+ } catch (e: unknown) {
610
+ this.logger.error(
611
+ `Error in getPricesVolume`,
612
+ {
613
+ srcToken: srcToken.address || srcToken.symbol,
614
+ destToken: destToken.address || destToken.symbol,
615
+ side,
616
+ },
617
+ e,
618
+ );
619
+ return null;
620
+ }
621
+ }
622
+
623
+ getCalldataGasCost(poolPrices: PoolPrices<CablesData>): number | number[] {
624
+ return (
625
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
626
+ // addresses: makerAsset, takerAsset, maker, taker
627
+ CALLDATA_GAS_COST.ADDRESS * 4 +
628
+ // uint256: expiry
629
+ CALLDATA_GAS_COST.wordNonZeroBytes(16) +
630
+ // uint256: nonceAndMeta, makerAmount, takerAmount
631
+ CALLDATA_GAS_COST.AMOUNT * 3 +
632
+ // bytes: _signature (65 bytes)
633
+ CALLDATA_GAS_COST.FULL_WORD * 2 +
634
+ CALLDATA_GAS_COST.OFFSET_SMALL
635
+ );
636
+ }
637
+
638
+ async initializePricing(blockNumber: number): Promise<void> {
639
+ if (!this.dexHelper.config.isSlave) {
640
+ this.rateFetcher.start();
641
+ }
642
+
643
+ return;
644
+ }
645
+
646
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
647
+ return null;
648
+ }
649
+
650
+ releaseResources?(): AsyncOrSync<void> {
651
+ if (this.rateFetcher) {
652
+ this.rateFetcher.stop();
653
+ }
654
+ }
655
+
656
+ normalizeAddress(address: string): string {
657
+ return address.toLowerCase() === ETHER_ADDRESS
658
+ ? NULL_ADDRESS
659
+ : address.toLowerCase();
660
+ }
661
+
662
+ async getTopPoolsForToken(
663
+ tokenAddress: Address,
664
+ limit: number,
665
+ ): Promise<PoolLiquidity[]> {
666
+ const tokens = (await this.getCachedTokens()) as { [key: string]: Token };
667
+ const token = Object.values(tokens).find(
668
+ token => token.address.toLowerCase() === tokenAddress.toLowerCase(),
669
+ );
670
+
671
+ if (!token) {
672
+ return [];
673
+ }
674
+
675
+ const tokenPriceUsd = await this.dexHelper.getTokenUSDPrice(
676
+ token,
677
+ BigInt(10 ** token.decimals),
678
+ );
679
+
680
+ const erc20BalanceCalldata = this.erc20Interface.encodeFunctionData(
681
+ 'balanceOf',
682
+ [this.mainnetRFQAddress],
683
+ );
684
+ const tokenBalanceMultiCall = [
685
+ {
686
+ target: token.address,
687
+ callData: erc20BalanceCalldata,
688
+ },
689
+ ];
690
+ const res = (
691
+ await this.dexHelper.multiContract.methods
692
+ .aggregate(tokenBalanceMultiCall)
693
+ .call()
694
+ ).returnData[0];
695
+
696
+ let tokenLiquidity = BigInt(res);
697
+
698
+ let tokenLiquidityUsd =
699
+ (tokenLiquidity * BigInt(tokenPriceUsd * 1_000_000)) /
700
+ BigInt(1_000_000 * 10 ** token.decimals);
701
+
702
+ let tokenWithLiquidity = [];
703
+
704
+ tokenWithLiquidity.push({
705
+ exchange: this.dexKey,
706
+ address: this.mainnetRFQAddress,
707
+ connectorTokens: [
708
+ {
709
+ address: token.address,
710
+ decimals: token.decimals,
711
+ },
712
+ ],
713
+ liquidityUSD: Number(tokenLiquidityUsd),
714
+ });
715
+
716
+ return tokenWithLiquidity;
717
+ }
718
+
719
+ /**
720
+ * CACHED UTILS
721
+ */
722
+ async getCachedTokens(): Promise<any> {
723
+ const cachedTokens = await this.dexHelper.cache.get(
724
+ this.dexKey,
725
+ this.network,
726
+ this.rateFetcher.tokensCacheKey,
727
+ );
728
+
729
+ return cachedTokens ? JSON.parse(cachedTokens) : {};
730
+ }
731
+
732
+ async getCachedPairs(): Promise<any> {
733
+ const cachedPairs = await this.dexHelper.cache.get(
734
+ this.dexKey,
735
+ this.network,
736
+ this.rateFetcher.pairsCacheKey,
737
+ );
738
+
739
+ return cachedPairs ? JSON.parse(cachedPairs) : {};
740
+ }
741
+
742
+ async getCachedPrices(): Promise<any> {
743
+ const cachedPrices = await this.dexHelper.cache.get(
744
+ this.dexKey,
745
+ this.network,
746
+ this.rateFetcher.pricesCacheKey,
747
+ );
748
+
749
+ return cachedPrices ? JSON.parse(cachedPrices) : {};
750
+ }
751
+
752
+ async getCachedTokensAddr(): Promise<any> {
753
+ const tokens = await this.getCachedTokens();
754
+ const tokensAddr: Record<string, Address> = {};
755
+ for (const key of Object.keys(tokens)) {
756
+ tokensAddr[tokens[key].symbol.toLowerCase()] = tokens[key].address;
757
+ }
758
+ return tokensAddr;
759
+ }
760
+
761
+ getPairString(baseToken: Token, quoteToken: Token): string {
762
+ return `${baseToken.symbol}/${quoteToken.symbol}`.toLowerCase();
763
+ }
764
+
765
+ // Function to find a key by address
766
+ private findKeyByAddress = (
767
+ jsonData: Record<string, { address: string }>,
768
+ targetAddress: string,
769
+ ): string | undefined => {
770
+ const entries = Object.entries(jsonData);
771
+ const foundEntry = entries.find(
772
+ ([_, value]) =>
773
+ value.address.toLowerCase() === targetAddress.toLowerCase(),
774
+ );
775
+ return foundEntry ? foundEntry[0] : undefined;
776
+ };
777
+
778
+ async getPairData(srcToken: Token, destToken: Token): Promise<any> {
779
+ const normalizedSrcToken = this.normalizeToken(srcToken);
780
+ const normalizedDestToken = this.normalizeToken(destToken);
781
+
782
+ if (normalizedSrcToken.address === normalizedDestToken.address) {
783
+ return null;
784
+ }
785
+
786
+ const cachedTokens = await this.getCachedTokens();
787
+
788
+ normalizedSrcToken.symbol = this.findKeyByAddress(
789
+ cachedTokens,
790
+ normalizedSrcToken.address,
791
+ );
792
+ normalizedDestToken.symbol = this.findKeyByAddress(
793
+ cachedTokens,
794
+ normalizedDestToken.address,
795
+ );
796
+
797
+ const cachedPairs = await this.getCachedPairs();
798
+
799
+ const potentialPairs = [
800
+ {
801
+ base: normalizedSrcToken.symbol,
802
+ quote: normalizedDestToken.symbol,
803
+ identifier: this.getPairString(normalizedSrcToken, normalizedDestToken),
804
+ isSrcBase: true,
805
+ },
806
+ {
807
+ base: normalizedDestToken.symbol,
808
+ quote: normalizedSrcToken.symbol,
809
+ identifier: this.getPairString(normalizedDestToken, normalizedSrcToken),
810
+ isSrcBase: false,
811
+ },
812
+ ];
813
+
814
+ for (const pair of potentialPairs) {
815
+ if (pair.identifier in cachedPairs) {
816
+ const pairData = cachedPairs[pair.identifier];
817
+ pairData.isSrcBase = pair.isSrcBase;
818
+ return pairData;
819
+ }
820
+ }
821
+ return null;
822
+ }
823
+
824
+ async isBlacklisted(txOrigin: Address): Promise<boolean> {
825
+ const cachedBlacklist = await this.dexHelper.cache.get(
826
+ this.dexKey,
827
+ this.network,
828
+ CABLES_BLACKLIST_CACHE_KEY,
829
+ );
830
+
831
+ if (cachedBlacklist) {
832
+ const blacklist = JSON.parse(cachedBlacklist) as string[];
833
+ return blacklist.includes(txOrigin.toLowerCase());
834
+ }
835
+
836
+ return false;
837
+ }
838
+
839
+ async isRestricted(): Promise<boolean> {
840
+ const result = await this.dexHelper.cache.get(
841
+ this.dexKey,
842
+ this.network,
843
+ CABLES_RESTRICTED_CACHE_KEY,
844
+ );
845
+
846
+ return result === 'true';
847
+ }
848
+
849
+ async restrict() {
850
+ const errorsDataRaw = await this.dexHelper.cache.get(
851
+ this.dexKey,
852
+ this.network,
853
+ CABLES_ERRORS_CACHE_KEY,
854
+ );
855
+
856
+ const errorsData: RestrictData = Utils.Parse(errorsDataRaw);
857
+ const ERRORS_TTL_S = Math.floor(CABLES_RESTRICT_CHECK_INTERVAL_MS / 1000);
858
+
859
+ if (
860
+ !errorsData ||
861
+ errorsData?.addedDatetimeMs + CABLES_RESTRICT_CHECK_INTERVAL_MS <
862
+ Date.now()
863
+ ) {
864
+ this.logger.warn(
865
+ `${this.dexKey}-${this.network}: First encounter of error OR error ocurred outside of threshold, setting up counter`,
866
+ );
867
+ const data: RestrictData = {
868
+ count: 1,
869
+ addedDatetimeMs: Date.now(),
870
+ };
871
+ await this.dexHelper.cache.setex(
872
+ this.dexKey,
873
+ this.network,
874
+ CABLES_ERRORS_CACHE_KEY,
875
+ ERRORS_TTL_S,
876
+ Utils.Serialize(data),
877
+ );
878
+ return;
879
+ } else {
880
+ if (errorsData.count + 1 >= CABLES_RESTRICT_COUNT_THRESHOLD) {
881
+ this.logger.warn(
882
+ `${this.dexKey}-${this.network}: Restricting due to error count=${
883
+ errorsData.count + 1
884
+ } within ${CABLES_RESTRICT_CHECK_INTERVAL_MS / 1000 / 60} minutes`,
885
+ );
886
+ await this.dexHelper.cache.setex(
887
+ this.dexKey,
888
+ this.network,
889
+ CABLES_RESTRICTED_CACHE_KEY,
890
+ CABLES_RESTRICT_TTL_S,
891
+ 'true',
892
+ );
893
+ } else {
894
+ this.logger.warn(
895
+ `${this.dexKey}-${this.network}: Error count increased`,
896
+ );
897
+ const data: RestrictData = {
898
+ count: errorsData.count + 1,
899
+ addedDatetimeMs: errorsData.addedDatetimeMs,
900
+ };
901
+ await this.dexHelper.cache.setex(
902
+ this.dexKey,
903
+ this.network,
904
+ CABLES_RESTRICTED_CACHE_KEY,
905
+ ERRORS_TTL_S,
906
+ Utils.Serialize(data),
907
+ );
908
+ }
909
+ }
910
+ }
911
+ }