@paraswap/dex-lib 2.36.3-dexalot.5 → 2.36.3-retro

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 (36) hide show
  1. package/build/config.js +0 -2
  2. package/build/config.js.map +1 -1
  3. package/build/dex/idex.d.ts +1 -1
  4. package/build/dex/index.js +0 -2
  5. package/build/dex/index.js.map +1 -1
  6. package/build/dex/uniswap-v3/config.js +14 -0
  7. package/build/dex/uniswap-v3/config.js.map +1 -1
  8. package/build/dex/uniswap-v3/uniswap-v3.js +1 -0
  9. package/build/dex/uniswap-v3/uniswap-v3.js.map +1 -1
  10. package/build/implementations/local-paraswap-sdk.js +1 -1
  11. package/build/implementations/local-paraswap-sdk.js.map +1 -1
  12. package/build/pricing-helper.d.ts +1 -1
  13. package/build/pricing-helper.js +2 -2
  14. package/build/pricing-helper.js.map +1 -1
  15. package/build/types.d.ts +0 -1
  16. package/package.json +1 -1
  17. package/src/config.ts +0 -3
  18. package/src/dex/idex.ts +0 -2
  19. package/src/dex/index.ts +0 -2
  20. package/src/dex/uniswap-v3/config.ts +15 -0
  21. package/src/dex/uniswap-v3/uniswap-v3-e2e.test.ts +25 -0
  22. package/src/dex/uniswap-v3/uniswap-v3-integration.test.ts +144 -0
  23. package/src/dex/uniswap-v3/uniswap-v3.ts +1 -0
  24. package/src/implementations/local-paraswap-sdk.ts +0 -1
  25. package/src/pricing-helper.ts +0 -2
  26. package/src/types.ts +0 -1
  27. package/tests/constants-e2e.ts +1 -1
  28. package/src/abi/dexalot/DexalotMainnetRFQ.json +0 -887
  29. package/src/dex/dexalot/config.ts +0 -18
  30. package/src/dex/dexalot/constants.ts +0 -29
  31. package/src/dex/dexalot/dexalot-e2e.test.ts +0 -192
  32. package/src/dex/dexalot/dexalot-integration.test.ts +0 -188
  33. package/src/dex/dexalot/dexalot.ts +0 -1005
  34. package/src/dex/dexalot/rate-fetcher.ts +0 -197
  35. package/src/dex/dexalot/types.ts +0 -131
  36. package/src/dex/dexalot/validators.ts +0 -46
@@ -1,1005 +0,0 @@
1
- import {
2
- Token,
3
- Address,
4
- ExchangePrices,
5
- PoolPrices,
6
- AdapterExchangeParam,
7
- SimpleExchangeParam,
8
- PoolLiquidity,
9
- Logger,
10
- ExchangeTxInfo,
11
- OptimalSwapExchange,
12
- PreprocessTransactionOptions, TransferFeeParams,
13
- } from '../../types';
14
- import {
15
- SwapSide,
16
- Network,
17
- ETHER_ADDRESS,
18
- NULL_ADDRESS,
19
- } from '../../constants';
20
- import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
21
- import { getDexKeysWithNetwork, isAxiosError } from '../../utils';
22
- import { IDex } from '../idex';
23
- import { IDexHelper } from '../../dex-helper/idex-helper';
24
- import {
25
- ClobSide,
26
- DexalotData,
27
- PairData,
28
- PairDataMap,
29
- PriceDataMap,
30
- DexalotRfqError,
31
- DexalotAPIParameters,
32
- RFQResponse,
33
- RFQResponseError,
34
- TokenAddrDataMap,
35
- TokenDataMap,
36
- } from './types';
37
- import { SlippageCheckError, TooStrictSlippageCheckError } from '../generic-rfq/types';
38
- import { SimpleExchange } from '../simple-exchange';
39
- import { Adapters, DexalotConfig } from './config';
40
- import { RateFetcher } from './rate-fetcher';
41
- import mainnetRFQAbi from '../../abi/dexalot/DexalotMainnetRFQ.json';
42
- import { Interface } from 'ethers/lib/utils';
43
- import { assert } from 'ts-essentials';
44
- import {
45
- DEXALOT_API_URL,
46
- DEXALOT_API_PRICES_POLLING_INTERVAL_MS,
47
- DEXALOT_PRICES_CACHES_TTL_S,
48
- DEXALOT_GAS_COST,
49
- DEXALOT_PAIRS_CACHES_TTL_S,
50
- DEXALOT_API_PAIRS_POLLING_INTERVAL_MS,
51
- DEXALOT_TOKENS_CACHES_TTL_S,
52
- DEXALOT_API_BLACKLIST_POLLING_INTERVAL_MS,
53
- DEXALOT_RATE_LIMITED_TTL_S,
54
- DEXALOT_MIN_SLIPPAGE_FACTOR_THRESHOLD_FOR_RESTRICTION,
55
- DEXALOT_RESTRICTED_CACHE_KEY,
56
- DEXALOT_RESTRICT_TTL_S,
57
- DEXALOT_RATELIMIT_CACHE_VALUE,
58
- DEXALOT_BLACKLIST_CACHES_TTL_S,
59
- } from './constants';
60
- import { BI_MAX_UINT256 } from '../../bigint-constants';
61
- import { ethers } from 'ethers';
62
- import BigNumber from 'bignumber.js';
63
- import { Method } from '../../dex-helper/irequest-wrapper';
64
-
65
- export class Dexalot extends SimpleExchange implements IDex<DexalotData> {
66
- readonly isStatePollingDex = true;
67
- readonly hasConstantPriceLargeAmounts = false;
68
- readonly needWrapNative = false;
69
- readonly isFeeOnTransferSupported = false;
70
- private rateFetcher: RateFetcher;
71
-
72
- private dexalotAuthToken: string;
73
-
74
- private pricesCacheKey: string;
75
- private pairsCacheKey: string;
76
- private tokensAddrCacheKey: string;
77
- private tokensCacheKey: string;
78
- private blacklistCacheKey: string;
79
- private tokensMap: TokenDataMap = {};
80
-
81
- public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
82
- getDexKeysWithNetwork(DexalotConfig);
83
-
84
- logger: Logger;
85
-
86
- constructor(
87
- readonly network: Network,
88
- readonly dexKey: string,
89
- readonly dexHelper: IDexHelper,
90
- protected adapters = Adapters[network] || {},
91
- readonly mainnetRFQAddress: string = DexalotConfig['Dexalot'][network]
92
- .mainnetRFQAddress,
93
- protected rfqInterface = new Interface(mainnetRFQAbi),
94
- ) {
95
- super(dexHelper, dexKey);
96
- this.logger = dexHelper.getLogger(dexKey);
97
-
98
- const authToken = dexHelper.config.data.dexalotAuthToken;
99
- assert(
100
- authToken !== undefined,
101
- 'Dexalot auth token is not specified with env variable',
102
- );
103
- this.dexalotAuthToken = authToken;
104
-
105
- this.pricesCacheKey = 'prices';
106
- this.pairsCacheKey = 'pairs';
107
- this.tokensAddrCacheKey = 'tokens_addr';
108
- this.tokensCacheKey = 'tokens';
109
- this.blacklistCacheKey = 'blacklist';
110
-
111
- this.rateFetcher = new RateFetcher(
112
- this.dexHelper,
113
- this.dexKey,
114
- this.network,
115
- this.logger,
116
- {
117
- rateConfig: {
118
- pairsIntervalMs: DEXALOT_API_PAIRS_POLLING_INTERVAL_MS,
119
- pricesIntervalMs: DEXALOT_API_PRICES_POLLING_INTERVAL_MS,
120
- blacklistIntervalMs: DEXALOT_API_BLACKLIST_POLLING_INTERVAL_MS,
121
- pairsReqParams: this.getAPIReqParams('api/rfq/pairs', 'GET'),
122
- pricesReqParams: this.getAPIReqParams('api/rfq/prices', 'GET'),
123
- blacklistReqParams: this.getAPIReqParams('api/rfq/blacklist', 'GET'),
124
- pairsCacheKey: this.pairsCacheKey,
125
- pairsCacheTTLSecs: DEXALOT_PAIRS_CACHES_TTL_S,
126
- pricesCacheKey: this.pricesCacheKey,
127
- pricesCacheTTLSecs: DEXALOT_PRICES_CACHES_TTL_S,
128
- tokensAddrCacheKey: this.tokensAddrCacheKey,
129
- tokensCacheKey: this.tokensCacheKey,
130
- tokensCacheTTLSecs: DEXALOT_TOKENS_CACHES_TTL_S,
131
- blacklistCacheKey: this.blacklistCacheKey,
132
- blacklistCacheTTLSecs: DEXALOT_BLACKLIST_CACHES_TTL_S,
133
- },
134
- },
135
- );
136
- }
137
-
138
- async initializePricing(blockNumber: number): Promise<void> {
139
- if (!this.dexHelper.config.isSlave) {
140
- this.rateFetcher.start();
141
- }
142
-
143
- return;
144
- }
145
-
146
- getAdapters(side: SwapSide): { name: string; index: number }[] | null {
147
- return this.adapters[side] ? this.adapters[side] : null;
148
- }
149
-
150
- getPairString(baseToken: Token, quoteToken: Token): string {
151
- return `${baseToken.symbol}/${quoteToken.symbol}`.toLowerCase();
152
- }
153
-
154
- async getPairData(
155
- srcToken: Token,
156
- destToken: Token,
157
- ): Promise<PairData | null> {
158
- const normalizedSrcToken = this.normalizeToken(srcToken);
159
- const normalizedDestToken = this.normalizeToken(destToken);
160
- if (normalizedSrcToken.address === normalizedDestToken.address) {
161
- return null;
162
- }
163
-
164
- const cachedTokens = (await this.getCachedTokens()) || {};
165
- if (
166
- !(normalizedSrcToken.address in cachedTokens) ||
167
- !(normalizedDestToken.address in cachedTokens)
168
- ) {
169
- return null;
170
- }
171
- normalizedSrcToken.symbol = cachedTokens[normalizedSrcToken.address].symbol;
172
- normalizedDestToken.symbol =
173
- cachedTokens[normalizedDestToken.address].symbol;
174
-
175
- const cachedPairs = (await this.getCachedPairs()) || {};
176
-
177
- const potentialPairs = [
178
- {
179
- identifier: this.getPairString(normalizedSrcToken, normalizedDestToken),
180
- isSrcBase: true,
181
- },
182
- {
183
- identifier: this.getPairString(normalizedDestToken, normalizedSrcToken),
184
- isSrcBase: false,
185
- },
186
- ];
187
-
188
- for (const pair of potentialPairs) {
189
- if (pair.identifier in cachedPairs) {
190
- const pairData = cachedPairs[pair.identifier];
191
- pairData.isSrcBase = pair.isSrcBase;
192
- return pairData;
193
- }
194
- }
195
- return null;
196
- }
197
-
198
- getIdentifier(srcAddress: Address, destAddress: Address) {
199
- const sortedAddresses =
200
- srcAddress < destAddress
201
- ? [srcAddress, destAddress]
202
- : [destAddress, srcAddress];
203
-
204
- return `${this.dexKey}_${sortedAddresses[0].toLowerCase()}_${sortedAddresses[1].toLowerCase()}`;
205
- }
206
-
207
- async getPoolIdentifiers(
208
- srcToken: Token,
209
- destToken: Token,
210
- side: SwapSide,
211
- blockNumber: number,
212
- ): Promise<string[]> {
213
- if (!srcToken || !destToken) {
214
- return [];
215
- }
216
- const pairData = await this.getPairData(srcToken, destToken);
217
- if (!pairData) {
218
- return [];
219
- }
220
-
221
- const tokensAddr = (await this.getCachedTokensAddr()) || {};
222
-
223
- return [this.getIdentifier(
224
- tokensAddr[pairData.base.toLowerCase()],
225
- tokensAddr[pairData.quote.toLowerCase()],
226
- )];
227
- }
228
-
229
- async getCachedPairs(): Promise<PairDataMap | null> {
230
- const cachedPairs = await this.dexHelper.cache.get(
231
- this.dexKey,
232
- this.network,
233
- this.pairsCacheKey,
234
- );
235
-
236
- if (cachedPairs) {
237
- return JSON.parse(cachedPairs) as PairDataMap;
238
- }
239
-
240
- return null;
241
- }
242
-
243
- async getCachedPrices(): Promise<PriceDataMap | null> {
244
- const cachedPrices = await this.dexHelper.cache.get(
245
- this.dexKey,
246
- this.network,
247
- this.pricesCacheKey,
248
- );
249
-
250
- if (cachedPrices) {
251
- return JSON.parse(cachedPrices) as PriceDataMap;
252
- }
253
-
254
- return null;
255
- }
256
-
257
- async getCachedTokensAddr(): Promise<TokenAddrDataMap | null> {
258
- const cachedTokensAddr = await this.dexHelper.cache.get(
259
- this.dexKey,
260
- this.network,
261
- this.tokensAddrCacheKey,
262
- );
263
-
264
- if (cachedTokensAddr) {
265
- return JSON.parse(cachedTokensAddr) as TokenAddrDataMap;
266
- }
267
-
268
- return null;
269
- }
270
-
271
- async getCachedTokens(): Promise<TokenDataMap | null> {
272
- const cachedTokens = await this.dexHelper.cache.get(
273
- this.dexKey,
274
- this.network,
275
- this.tokensCacheKey,
276
- );
277
-
278
- if (cachedTokens) {
279
- return JSON.parse(cachedTokens) as TokenDataMap;
280
- }
281
-
282
- return null;
283
- }
284
-
285
- normalizeAddress(address: string): string {
286
- return address.toLowerCase() === ETHER_ADDRESS
287
- ? NULL_ADDRESS
288
- : address.toLowerCase();
289
- }
290
-
291
- denormalizeAddress(address: string): string {
292
- return address.toLowerCase() === NULL_ADDRESS
293
- ? ETHER_ADDRESS
294
- : address.toLowerCase();
295
- }
296
-
297
- // Dexalot protocol for native token expects 0x00000... instead of 0xeeeee...
298
- normalizeToken(token: Token): Token {
299
- return {
300
- address: this.normalizeAddress(token.address),
301
- decimals: token.decimals,
302
- };
303
- }
304
-
305
- denormalizeToken(token: Token): Token {
306
- return {
307
- address: this.denormalizeAddress(token.address),
308
- decimals: token.decimals,
309
- };
310
- }
311
-
312
- calculateOrderPrice(
313
- amounts: bigint[],
314
- orderbook: string[][],
315
- baseToken: Token,
316
- quoteToken: Token,
317
- side: ClobSide,
318
- ) {
319
- let result = [];
320
-
321
- for (let i = 0; i < amounts.length; i++) {
322
- let amt = amounts[i];
323
- if (amt === 0n) {
324
- result.push(amt);
325
- continue;
326
- }
327
-
328
- let left = 0,
329
- right = orderbook.length;
330
- let qty = BigInt(0);
331
-
332
- while (left < right) {
333
- let mid = Math.floor((left + right) / 2);
334
- qty = BigInt(
335
- ethers.utils
336
- .parseUnits(orderbook[mid][1], quoteToken.decimals)
337
- .toString(),
338
- );
339
- if (side === ClobSide.ASK) {
340
- const price = BigInt(
341
- ethers.utils
342
- .parseUnits(orderbook[mid][0], baseToken.decimals)
343
- .toString(),
344
- );
345
- qty =
346
- (qty * BigInt(10 ** (baseToken.decimals * 2))) /
347
- (price * BigInt(10 ** quoteToken.decimals));
348
- }
349
- if (qty <= amt) {
350
- left = mid + 1;
351
- } else {
352
- right = mid;
353
- }
354
- }
355
-
356
- let price,
357
- amount = BigInt(0);
358
- if (left === orderbook.length) {
359
- price = BigInt(
360
- ethers.utils
361
- .parseUnits(orderbook[left - 1][0], baseToken.decimals)
362
- .toString(),
363
- );
364
- amount = qty;
365
- } else if (amounts[i] === qty) {
366
- price = BigInt(
367
- ethers.utils
368
- .parseUnits(orderbook[left][0], baseToken.decimals)
369
- .toString(),
370
- );
371
- amount = amounts[i];
372
- } else {
373
- const lPrice = BigInt(
374
- ethers.utils
375
- .parseUnits(orderbook[left][0], baseToken.decimals)
376
- .toString(),
377
- );
378
- const rPrice = BigInt(
379
- ethers.utils
380
- .parseUnits(orderbook[left + 1][0], baseToken.decimals)
381
- .toString(),
382
- );
383
- const lQty = qty;
384
- let rQty = BigInt(
385
- ethers.utils
386
- .parseUnits(orderbook[left + 1][1], quoteToken.decimals)
387
- .toString(),
388
- );
389
- if (side === ClobSide.ASK) {
390
- rQty = (rQty * rPrice) / BigInt(10 ** quoteToken.decimals);
391
- }
392
- price = lPrice + ((rPrice - lPrice) * (amt - lQty)) / (rQty - lQty);
393
- amount = amounts[i];
394
- }
395
-
396
- if (side === ClobSide.BID) {
397
- result.push(
398
- (amount * BigInt(10 ** (baseToken.decimals * 2))) /
399
- (price * BigInt(10 ** quoteToken.decimals)),
400
- );
401
- } else {
402
- result.push(
403
- (price * amount * BigInt(10 ** quoteToken.decimals)) /
404
- BigInt(10 ** (baseToken.decimals * 2)),
405
- );
406
- }
407
- }
408
- return result;
409
- }
410
-
411
- async getPricesVolume(
412
- srcToken: Token,
413
- destToken: Token,
414
- amounts: bigint[],
415
- side: SwapSide,
416
- blockNumber: number,
417
- limitPools?: string[],
418
- transferFees?: TransferFeeParams,
419
- isFirstSwap?: boolean,
420
- ): Promise<null | ExchangePrices<DexalotData>> {
421
- try {
422
-
423
- // Disable multi/mega routes
424
- if(!isFirstSwap) {
425
- return null;
426
- }
427
-
428
- if (await this.isRestricted()) {
429
- return null;
430
- }
431
-
432
- const normalizedSrcToken = this.normalizeToken(srcToken);
433
- const normalizedDestToken = this.normalizeToken(destToken);
434
-
435
- this.tokensMap = (await this.getCachedTokens()) || {};
436
- if (normalizedSrcToken.address === normalizedDestToken.address) {
437
- return null;
438
- }
439
-
440
- const pools = limitPools
441
- ? limitPools.filter(
442
- p =>
443
- p ===
444
- this.getIdentifier(
445
- normalizedSrcToken.address,
446
- normalizedDestToken.address,
447
- ),
448
- )
449
- : await this.getPoolIdentifiers(srcToken, destToken, side, blockNumber);
450
-
451
- if (pools.length === 0) {
452
- return null;
453
- }
454
-
455
- const pairData = await this.getPairData(
456
- normalizedSrcToken,
457
- normalizedDestToken,
458
- );
459
- if (!pairData) {
460
- return null;
461
- }
462
-
463
- const priceMap = await this.getCachedPrices();
464
- if (!priceMap) {
465
- return null;
466
- }
467
-
468
- const tokensAddr = (await this.getCachedTokensAddr()) || {};
469
- const pairKey = `${pairData.base}/${pairData.quote}`.toLowerCase();
470
- if (
471
- !(pairKey in priceMap)
472
- || !pools.includes(this.getIdentifier(
473
- tokensAddr[pairData.base.toLowerCase()],
474
- tokensAddr[pairData.quote.toLowerCase()],
475
- ))
476
- ) {
477
- return null;
478
- }
479
-
480
- const priceData = priceMap[pairKey];
481
- const baseToken = pairData.isSrcBase
482
- ? normalizedSrcToken
483
- : normalizedDestToken;
484
- const quoteToken = pairData.isSrcBase
485
- ? normalizedDestToken
486
- : normalizedSrcToken;
487
-
488
- // convert from swap to clob side
489
- let orderbook = priceData.asks;
490
- let clobSide = ClobSide.BID;
491
- if (
492
- (side === SwapSide.SELL && pairData.isSrcBase) ||
493
- (side === SwapSide.BUY && !pairData.isSrcBase)
494
- ) {
495
- orderbook = priceData.bids;
496
- clobSide = ClobSide.ASK;
497
- }
498
- if (orderbook.length === 0) {
499
- throw new Error(`Empty orderbook for ${pairKey}`);
500
- }
501
-
502
- const prices = this.calculateOrderPrice(
503
- amounts,
504
- orderbook,
505
- baseToken,
506
- quoteToken,
507
- clobSide,
508
- );
509
- const outDecimals =
510
- clobSide === ClobSide.BID ? baseToken.decimals : quoteToken.decimals;
511
- const poolIdentifier = this.getIdentifier(pairData.base, pairData.quote);
512
-
513
- return [
514
- {
515
- prices,
516
- unit: BigInt(outDecimals),
517
- data: {},
518
- poolIdentifier: poolIdentifier,
519
- exchange: this.dexKey,
520
- gasCost: DEXALOT_GAS_COST,
521
- poolAddresses: [this.mainnetRFQAddress],
522
- },
523
- ];
524
- } catch (e: unknown) {
525
- this.logger.error(
526
- `Error_getPricesVolume ${srcToken.address || srcToken.symbol}, ${
527
- destToken.address || destToken.symbol
528
- }, ${side}:`,
529
- e,
530
- );
531
- return null;
532
- }
533
- }
534
-
535
- generateRFQError(errorStr: string, swapIdentifier: string) {
536
- const message = `${this.dexKey}-${this.network}: Failed to fetch RFQ for ${swapIdentifier}. ${errorStr}`;
537
- this.logger.warn(message);
538
- throw new DexalotRfqError(message);
539
- }
540
-
541
- async preProcessTransaction(
542
- optimalSwapExchange: OptimalSwapExchange<DexalotData>,
543
- srcToken: Token,
544
- destToken: Token,
545
- side: SwapSide,
546
- options: PreprocessTransactionOptions,
547
- ): Promise<[OptimalSwapExchange<DexalotData>, ExchangeTxInfo]> {
548
- if (await this.isBlacklisted(options.txOrigin)) {
549
- this.logger.warn(
550
- `${this.dexKey}-${this.network}: blacklisted TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`,
551
- );
552
- throw new Error(
553
- `${this.dexKey}-${
554
- this.network
555
- }: user=${options.txOrigin.toLowerCase()} is blacklisted`,
556
- );
557
- }
558
-
559
- if (BigInt(optimalSwapExchange.srcAmount) === 0n) {
560
- throw new Error('getFirmRate failed with srcAmount === 0');
561
- }
562
-
563
- const normalizedSrcToken = this.normalizeToken(srcToken);
564
- const normalizedDestToken = this.normalizeToken(destToken);
565
- const swapIdentifier = `${this.getIdentifier(
566
- normalizedSrcToken.address,
567
- normalizedDestToken.address,
568
- )}_${side}`;
569
-
570
- try {
571
- const makerToken = normalizedDestToken;
572
- const takerToken = normalizedSrcToken;
573
-
574
- const rfqParams = {
575
- makerAsset: ethers.utils.getAddress(makerToken.address),
576
- takerAsset: ethers.utils.getAddress(takerToken.address),
577
- makerAmount:
578
- side === SwapSide.BUY ? optimalSwapExchange.destAmount : undefined,
579
- takerAmount:
580
- side === SwapSide.SELL ? optimalSwapExchange.srcAmount : undefined,
581
- userAddress: options.txOrigin,
582
- chainid: this.network,
583
- };
584
-
585
- const rfq: RFQResponse = await this.dexHelper.httpRequest.post(
586
- `${DEXALOT_API_URL}/api/rfq/firm`,
587
- rfqParams,
588
- undefined,
589
- { 'x-apikey': this.dexalotAuthToken },
590
- );
591
- if (!rfq) {
592
- this.generateRFQError(
593
- 'Missing quote data',
594
- `RFQ ${swapIdentifier} ${JSON.stringify(rfq)}`,
595
- );
596
- } else if (!rfq.signature) {
597
- this.generateRFQError('Missing signature', swapIdentifier);
598
- }
599
- rfq.order.signature = rfq.signature;
600
-
601
- const { order } = rfq;
602
-
603
- assert(
604
- order.makerAsset.toLowerCase() === makerToken.address,
605
- `QuoteData makerAsset=${order.makerAsset} is different from Paraswap makerAsset=${makerToken.address}`,
606
- );
607
- assert(
608
- order.takerAsset.toLowerCase() === takerToken.address,
609
- `QuoteData takerAsset=${order.takerAsset} is different from Paraswap takerAsset=${takerToken.address}`,
610
- );
611
- if (side === SwapSide.SELL) {
612
- assert(
613
- order.takerAmount === optimalSwapExchange.srcAmount,
614
- `QuoteData takerAmount=${order.takerAmount} is different from Paraswap srcAmount=${optimalSwapExchange.srcAmount}`,
615
- );
616
- } else {
617
- assert(
618
- order.makerAmount === optimalSwapExchange.destAmount,
619
- `QuoteData makerAmount=${order.makerAmount} is different from Paraswap destAmount=${optimalSwapExchange.destAmount}`,
620
- );
621
- }
622
-
623
- const expiryAsBigInt = BigInt(order.expiry);
624
- const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : BI_MAX_UINT256;
625
-
626
- const slippageFactor = options.slippageFactor;
627
- let isFailOnSlippage = false;
628
- let slippageErrorMessage = '';
629
-
630
- if (side === SwapSide.SELL) {
631
- if (
632
- BigInt(order.makerAmount) <
633
- BigInt(
634
- new BigNumber(optimalSwapExchange.destAmount.toString())
635
- .times(slippageFactor)
636
- .toFixed(0),
637
- )
638
- ) {
639
- isFailOnSlippage = true;
640
- const message = `${this.dexKey}-${this.network}: too much slippage on quote ${side} quoteTokenAmount ${order.makerAmount} / destAmount ${optimalSwapExchange.destAmount} < ${slippageFactor}`;
641
- slippageErrorMessage = message;
642
- this.logger.warn(message);
643
- }
644
- } else {
645
- if (
646
- BigInt(order.takerAmount) >
647
- BigInt(slippageFactor.times(optimalSwapExchange.srcAmount.toString()).toFixed(0))
648
- ) {
649
- isFailOnSlippage = true;
650
- const message = `${this.dexKey}-${
651
- this.network
652
- }: too much slippage on quote ${side} baseTokenAmount ${order.takerAmount} / srcAmount ${optimalSwapExchange.srcAmount} > ${slippageFactor.toFixed()}`;
653
- slippageErrorMessage = message;
654
- this.logger.warn(message);
655
- }
656
- }
657
-
658
- let isTooStrictSlippage = false;
659
- if (
660
- isFailOnSlippage &&
661
- side === SwapSide.SELL &&
662
- new BigNumber(1)
663
- .minus(slippageFactor)
664
- .lt(DEXALOT_MIN_SLIPPAGE_FACTOR_THRESHOLD_FOR_RESTRICTION)
665
- ) {
666
- isTooStrictSlippage = true;
667
- } else if (
668
- isFailOnSlippage &&
669
- side === SwapSide.BUY &&
670
- slippageFactor
671
- .minus(1)
672
- .lt(DEXALOT_MIN_SLIPPAGE_FACTOR_THRESHOLD_FOR_RESTRICTION)
673
- ) {
674
- isTooStrictSlippage = true;
675
- }
676
-
677
- if (isFailOnSlippage && isTooStrictSlippage) {
678
- throw new TooStrictSlippageCheckError(slippageErrorMessage);
679
- } else if (isFailOnSlippage && !isTooStrictSlippage) {
680
- throw new SlippageCheckError(slippageErrorMessage);
681
- }
682
-
683
- return [
684
- {
685
- ...optimalSwapExchange,
686
- data: {
687
- quoteData: order,
688
- },
689
- },
690
- { deadline: minDeadline },
691
- ];
692
- } catch (e) {
693
- if (isAxiosError(e) && e.response && e.response.data) {
694
- const errorData: RFQResponseError = e.response.data;
695
- if (errorData.ReasonCode === 'FQ-009') {
696
- this.logger.warn(
697
- `${this.dexKey}-${this.network}: Encountered rate limited user=${options.txOrigin}. Adding to local rate limit cache`,
698
- );
699
- await this.setRateLimited(options.txOrigin, errorData.RetryAfter);
700
- } else {
701
- await this.setBlacklist(options.txOrigin);
702
- this.logger.error(
703
- `${this.dexKey}-${this.network}: Failed to fetch RFQ for ${swapIdentifier}: ${errorData.Reason}`,
704
- );
705
- }
706
- } else {
707
- if(e instanceof TooStrictSlippageCheckError) {
708
- this.logger.warn(
709
- `${this.dexKey}-${this.network}: failed to build transaction on side ${side} with too strict slippage. Skipping restriction`,
710
- );
711
- } else {
712
- this.logger.warn(
713
- `${this.dexKey}-${this.network}: protocol is restricted`,
714
- );
715
- await this.restrict();
716
- }
717
- }
718
-
719
- throw e;
720
- }
721
- }
722
-
723
- getCalldataGasCost(poolPrices: PoolPrices<DexalotData>): number | number[] {
724
- return (
725
- CALLDATA_GAS_COST.DEX_OVERHEAD +
726
- // addresses: makerAsset, takerAsset, maker, taker
727
- CALLDATA_GAS_COST.ADDRESS * 4 +
728
- // uint256: expiry
729
- CALLDATA_GAS_COST.wordNonZeroBytes(16) +
730
- // uint256: nonceAndMeta, makerAmount, takerAmount
731
- CALLDATA_GAS_COST.AMOUNT * 3 +
732
- // bytes: _signature (65 bytes)
733
- CALLDATA_GAS_COST.FULL_WORD * 2 +
734
- CALLDATA_GAS_COST.OFFSET_SMALL
735
- );
736
- }
737
-
738
- getTokenFromAddress(address: Address): Token {
739
- return this.tokensMap[this.normalizeAddress(address)];
740
- }
741
-
742
- getAdapterParam(
743
- srcToken: string,
744
- destToken: string,
745
- srcAmount: string,
746
- destAmount: string,
747
- data: DexalotData,
748
- side: SwapSide,
749
- ): AdapterExchangeParam {
750
- const { quoteData } = data;
751
-
752
- assert(
753
- quoteData !== undefined,
754
- `${this.dexKey}-${this.network}: quoteData undefined`,
755
- );
756
-
757
- const params = [
758
- {
759
- nonceAndMeta: quoteData.nonceAndMeta,
760
- expiry: quoteData.expiry,
761
- makerAsset: quoteData.makerAsset,
762
- takerAsset: quoteData.takerAsset,
763
- maker: quoteData.maker,
764
- taker: quoteData.taker,
765
- makerAmount: quoteData.makerAmount,
766
- takerAmount: quoteData.takerAmount,
767
- },
768
- quoteData.signature,
769
- ];
770
-
771
- const payload = this.abiCoder.encodeParameter(
772
- {
773
- ParentStruct: {
774
- order: {
775
- nonceAndMeta: 'uint256',
776
- expiry: 'uint128',
777
- makerAsset: 'address',
778
- takerAsset: 'address',
779
- maker: 'address',
780
- taker: 'address',
781
- makerAmount: 'uint256',
782
- takerAmount: 'uint256',
783
- },
784
- signature: 'bytes',
785
- },
786
- },
787
- {
788
- order: params[0],
789
- signature: params[1],
790
- },
791
- );
792
-
793
- return {
794
- targetExchange: this.mainnetRFQAddress,
795
- payload,
796
- networkFee: '0',
797
- };
798
- }
799
-
800
- async restrict(ttl: number = DEXALOT_RESTRICT_TTL_S): Promise<boolean> {
801
- await this.dexHelper.cache.setex(
802
- this.dexKey,
803
- this.network,
804
- DEXALOT_RESTRICTED_CACHE_KEY,
805
- ttl,
806
- 'true',
807
- );
808
- return true;
809
- }
810
-
811
- async isRestricted(): Promise<boolean> {
812
- const result = await this.dexHelper.cache.get(
813
- this.dexKey,
814
- this.network,
815
- DEXALOT_RESTRICTED_CACHE_KEY,
816
- );
817
-
818
- return result === 'true';
819
- }
820
-
821
- async setBlacklist(txOrigin: Address, ttl: number = DEXALOT_BLACKLIST_CACHES_TTL_S,): Promise<boolean> {
822
- const cachedBlacklist = await this.dexHelper.cache.get(
823
- this.dexKey,
824
- this.network,
825
- this.blacklistCacheKey,
826
- );
827
-
828
- let blacklist: string[] = [];
829
- if (cachedBlacklist) {
830
- blacklist = JSON.parse(cachedBlacklist);
831
- }
832
-
833
- blacklist.push(txOrigin.toLowerCase());
834
-
835
- this.dexHelper.cache.setex(
836
- this.dexKey,
837
- this.network,
838
- this.blacklistCacheKey,
839
- ttl,
840
- JSON.stringify(blacklist),
841
- );
842
-
843
- return true;
844
- }
845
-
846
- async isBlacklisted(txOrigin: Address): Promise<boolean> {
847
- const cachedBlacklist = await this.dexHelper.cache.get(
848
- this.dexKey,
849
- this.network,
850
- this.blacklistCacheKey,
851
- );
852
-
853
- if (cachedBlacklist) {
854
- const blacklist = JSON.parse(cachedBlacklist) as string[];
855
- return blacklist.includes(txOrigin.toLowerCase());
856
- }
857
-
858
- // To not show pricing for rate limited users
859
- if(await this.isRateLimited(txOrigin)) {
860
- return true;
861
- }
862
-
863
- return false;
864
- }
865
-
866
- getRateLimitedKey(address: Address) {
867
- return `rate_limited_${address}`.toLowerCase();
868
- }
869
-
870
- async isRateLimited(txOrigin: Address): Promise<boolean> {
871
- const result = await this.dexHelper.cache.get(
872
- this.dexKey,
873
- this.network,
874
- this.getRateLimitedKey(txOrigin),
875
- );
876
- return result === DEXALOT_RATELIMIT_CACHE_VALUE;
877
- }
878
-
879
- async setRateLimited(txOrigin: Address, ttl = DEXALOT_RATE_LIMITED_TTL_S) {
880
- await this.dexHelper.cache.setex(
881
- this.dexKey,
882
- this.network,
883
- this.getRateLimitedKey(txOrigin),
884
- ttl,
885
- DEXALOT_RATELIMIT_CACHE_VALUE,
886
- );
887
- return true;
888
- }
889
-
890
- async getSimpleParam(
891
- srcToken: string,
892
- destToken: string,
893
- srcAmount: string,
894
- destAmount: string,
895
- data: DexalotData,
896
- side: SwapSide,
897
- ): Promise<SimpleExchangeParam> {
898
- const { quoteData } = data;
899
-
900
- assert(
901
- quoteData !== undefined,
902
- `${this.dexKey}-${this.network}: quoteData undefined`,
903
- );
904
-
905
- const swapFunction = 'simpleSwap';
906
- const swapFunctionParams = [
907
- [
908
- quoteData.nonceAndMeta,
909
- quoteData.expiry,
910
- quoteData.makerAsset,
911
- quoteData.takerAsset,
912
- quoteData.maker,
913
- quoteData.taker,
914
- quoteData.makerAmount,
915
- quoteData.takerAmount,
916
- ],
917
- quoteData.signature,
918
- ];
919
-
920
- const swapData = this.rfqInterface.encodeFunctionData(
921
- swapFunction,
922
- swapFunctionParams,
923
- );
924
-
925
- return this.buildSimpleParamWithoutWETHConversion(
926
- srcToken,
927
- srcAmount,
928
- destToken,
929
- destAmount,
930
- swapData,
931
- this.mainnetRFQAddress,
932
- );
933
- }
934
-
935
- async getTopPoolsForToken(
936
- tokenAddress: Address,
937
- limit: number,
938
- ): Promise<PoolLiquidity[]> {
939
- const normalizedTokenAddress = this.normalizeAddress(tokenAddress);
940
- const pairs = (await this.getCachedPairs()) || {};
941
- this.tokensMap = (await this.getCachedTokens()) || {};
942
- const tokensAddr = (await this.getCachedTokensAddr()) || {};
943
- const token = this.getTokenFromAddress(normalizedTokenAddress);
944
- if (!token) {
945
- return [];
946
- }
947
-
948
- const tokenSymbol = token.symbol?.toLowerCase() || '';
949
-
950
- let pairsByLiquidity = [];
951
- for (const pairName of Object.keys(pairs)) {
952
- if (!pairName.includes(tokenSymbol)) {
953
- continue;
954
- }
955
-
956
- const tokensInPair = pairName.split('/');
957
- if (tokensInPair.length !== 2) {
958
- continue;
959
- }
960
-
961
- const [ baseToken, quoteToken ] = tokensInPair;
962
- const addr = tokensAddr[baseToken.toLowerCase()];
963
- let outputToken = this.getTokenFromAddress(addr);
964
- if (baseToken === tokenSymbol) {
965
- const addr = tokensAddr[quoteToken.toLowerCase()];
966
- outputToken = this.getTokenFromAddress(addr);
967
- }
968
-
969
- const denormalizedToken = this.denormalizeToken(outputToken);
970
-
971
- pairsByLiquidity.push({
972
- exchange: this.dexKey,
973
- address: this.mainnetRFQAddress,
974
- connectorTokens: [{
975
- address: denormalizedToken.address,
976
- decimals: denormalizedToken.decimals,
977
- }],
978
- liquidityUSD: pairs[pairName].liquidityUSD,
979
- });
980
- }
981
-
982
- pairsByLiquidity.sort(
983
- (a: PoolLiquidity, b: PoolLiquidity) => b.liquidityUSD - a.liquidityUSD,
984
- );
985
-
986
- return pairsByLiquidity.slice(0, limit);
987
- }
988
-
989
- getAPIReqParams(endpoint: string, method: Method): DexalotAPIParameters {
990
- return {
991
- url: `${DEXALOT_API_URL}/${endpoint}`,
992
- headers: { 'x-apikey': this.dexalotAuthToken },
993
- params: {
994
- chainid: this.network,
995
- },
996
- method: method,
997
- };
998
- }
999
-
1000
- releaseResources(): void {
1001
- if (this.rateFetcher) {
1002
- this.rateFetcher.stop();
1003
- }
1004
- }
1005
- }