@paraswap/dex-lib 2.18.5 → 2.18.6-swaap-v2.2

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 (66) 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/vcs.xml +6 -0
  8. package/build/abi/swaap-v2/vault.json +918 -0
  9. package/build/config.js +4 -2
  10. package/build/config.js.map +1 -1
  11. package/build/dex/index.js +2 -0
  12. package/build/dex/index.js.map +1 -1
  13. package/build/dex/pancakeswap-v3/types.d.ts +14 -0
  14. package/build/dex/{test-dex → pancakeswap-v3}/types.js.map +1 -1
  15. package/build/dex/{test-dex → swaap-v2}/config.d.ts +1 -1
  16. package/build/dex/swaap-v2/config.js +25 -0
  17. package/build/dex/swaap-v2/config.js.map +1 -0
  18. package/build/dex/swaap-v2/constants.d.ts +9 -0
  19. package/build/dex/swaap-v2/constants.js +13 -0
  20. package/build/dex/swaap-v2/constants.js.map +1 -0
  21. package/build/dex/swaap-v2/rate-fetcher.d.ts +16 -0
  22. package/build/dex/swaap-v2/rate-fetcher.js +100 -0
  23. package/build/dex/swaap-v2/rate-fetcher.js.map +1 -0
  24. package/build/dex/swaap-v2/swaap-v2.d.ts +55 -0
  25. package/build/dex/swaap-v2/swaap-v2.js +465 -0
  26. package/build/dex/swaap-v2/swaap-v2.js.map +1 -0
  27. package/build/dex/swaap-v2/types.d.ts +64 -0
  28. package/build/dex/swaap-v2/types.js +7 -0
  29. package/build/dex/swaap-v2/types.js.map +1 -0
  30. package/build/dex/swaap-v2/utils.d.ts +7 -0
  31. package/build/dex/swaap-v2/utils.js +34 -0
  32. package/build/dex/swaap-v2/utils.js.map +1 -0
  33. package/build/dex/swaap-v2/validators.d.ts +5 -0
  34. package/build/dex/swaap-v2/validators.js +120 -0
  35. package/build/dex/swaap-v2/validators.js.map +1 -0
  36. package/build/types.d.ts +1 -0
  37. package/package.json +1 -1
  38. package/src/abi/swaap-v2/vault.json +918 -0
  39. package/src/config.ts +5 -2
  40. package/src/dex/index.ts +2 -0
  41. package/src/dex/swaap-v2/config.ts +25 -0
  42. package/src/dex/swaap-v2/constants.ts +14 -0
  43. package/src/dex/swaap-v2/rate-fetcher.ts +163 -0
  44. package/src/dex/swaap-v2/swaap-v2-e2e.test.ts +199 -0
  45. package/src/dex/swaap-v2/swaap-v2-integration.test.ts +142 -0
  46. package/src/dex/swaap-v2/swaap-v2.ts +713 -0
  47. package/src/dex/swaap-v2/types.ts +74 -0
  48. package/src/dex/swaap-v2/utils.ts +44 -0
  49. package/src/dex/swaap-v2/validators.ts +123 -0
  50. package/src/types.ts +1 -0
  51. package/tests/constants-e2e.ts +1 -1
  52. package/tests/utils-e2e.ts +5 -0
  53. package/build/abi/DirectSwap.json +0 -1018
  54. package/build/dex/test-dex/config.js +0 -15
  55. package/build/dex/test-dex/config.js.map +0 -1
  56. package/build/dex/test-dex/test-dex-pool.d.ts +0 -39
  57. package/build/dex/test-dex/test-dex-pool.js +0 -63
  58. package/build/dex/test-dex/test-dex-pool.js.map +0 -1
  59. package/build/dex/test-dex/test-dex.d.ts +0 -37
  60. package/build/dex/test-dex/test-dex.js +0 -126
  61. package/build/dex/test-dex/test-dex.js.map +0 -1
  62. package/build/dex/test-dex/types.d.ts +0 -6
  63. package/build/dex/woo-fi-v2/woo-fi-math.d.ts +0 -16
  64. package/build/dex/woo-fi-v2/woo-fi-math.js +0 -137
  65. package/build/dex/woo-fi-v2/woo-fi-math.js.map +0 -1
  66. /package/build/dex/{test-dex → pancakeswap-v3}/types.js +0 -0
@@ -0,0 +1,713 @@
1
+ import {
2
+ Token,
3
+ Address,
4
+ ExchangePrices,
5
+ PoolPrices,
6
+ AdapterExchangeParam,
7
+ SimpleExchangeParam,
8
+ PoolLiquidity,
9
+ Logger,
10
+ ExchangeTxInfo,
11
+ OptimalSwapExchange,
12
+ PreprocessTransactionOptions,
13
+ } from '../../types';
14
+ import { SwapSide, Network, MAX_INT, MAX_UINT } from '../../constants';
15
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
16
+ import { getDexKeysWithNetwork } from '../../utils';
17
+ import { IDex } from '../idex';
18
+ import { IDexHelper } from '../../dex-helper/idex-helper';
19
+ import {
20
+ SwaapV2Data,
21
+ SwaapV2PriceLevel,
22
+ SwaapV2PriceLevels,
23
+ SwaapV2APIParameters,
24
+ SwaapV2QuoteError,
25
+ } from './types';
26
+ import { getLocalDeadlineAsFriendlyPlaceholder, SimpleExchange } from '../simple-exchange';
27
+ import { Adapters, SwaapV2Config } from './config';
28
+ import { RateFetcher } from './rate-fetcher';
29
+ import routerAbi from '../../abi/swaap-v2/vault.json';
30
+ import BigNumber from 'bignumber.js';
31
+ import { BN_0, BN_1, getBigNumberPow } from '../../bignumber-constants';
32
+ import { Interface } from 'ethers/lib/utils';
33
+ import { assert } from 'ts-essentials';
34
+ import {
35
+ SWAAP_RFQ_API_URL,
36
+ SWAAP_RFQ_PRICES_ENDPOINT,
37
+ SWAAP_RFQ_QUOTE_ENDPOINT,
38
+ SWAAP_RFQ_API_PRICES_POLLING_INTERVAL_MS,
39
+ SWAAP_RFQ_PRICES_CACHES_TTL_S,
40
+ GAS_COST_ESTIMATION,
41
+ BATCH_SWAP_SELECTOR,
42
+ CALLER_SLOT,
43
+ } from './constants';
44
+ import {
45
+ getPoolIdentifier,
46
+ getPriceLevelsCacheKey,
47
+ normalizeTokenAddress,
48
+ getPairName,
49
+ } from './utils';
50
+ import { Method } from '../../dex-helper/irequest-wrapper';
51
+
52
+ export class SwaapV2 extends SimpleExchange implements IDex<SwaapV2Data> {
53
+ readonly isStatePollingDex = true;
54
+ readonly hasConstantPriceLargeAmounts = false;
55
+ readonly needWrapNative = false;
56
+ readonly isFeeOnTransferSupported = false;
57
+ private rateFetcher: RateFetcher;
58
+ private swaapV2AuthToken: string;
59
+
60
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
61
+ getDexKeysWithNetwork(SwaapV2Config);
62
+
63
+ logger: Logger;
64
+
65
+ constructor(
66
+ readonly network: Network,
67
+ readonly dexKey: string,
68
+ readonly dexHelper: IDexHelper,
69
+ protected adapters = Adapters[network] || {},
70
+ readonly routerAddressPlaceholder: string = SwaapV2Config['SwaapV2'][
71
+ network
72
+ ].routerAddress,
73
+ protected routerInterface = new Interface(routerAbi),
74
+ ) {
75
+ super(dexHelper, dexKey);
76
+ this.logger = dexHelper.getLogger(dexKey);
77
+ const token = dexHelper.config.data.swaapV2AuthToken;
78
+ assert(
79
+ token !== undefined,
80
+ 'SwaapV2 auth token is not specified with env variable',
81
+ );
82
+
83
+ this.swaapV2AuthToken = token;
84
+
85
+ this.rateFetcher = new RateFetcher(
86
+ this.dexHelper,
87
+ this.dexKey,
88
+ this.logger,
89
+ {
90
+ rateConfig: {
91
+ pricesIntervalMs: SWAAP_RFQ_API_PRICES_POLLING_INTERVAL_MS,
92
+ pricesReqParams: this.getPriceLevelsReqParams(),
93
+ pricesCacheTTLSecs: SWAAP_RFQ_PRICES_CACHES_TTL_S,
94
+ },
95
+ },
96
+ );
97
+ }
98
+
99
+ async initializePricing(blockNumber: number): Promise<void> {
100
+ if (!this.dexHelper.config.isSlave) {
101
+ await this.rateFetcher.start();
102
+ }
103
+ return;
104
+ }
105
+
106
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
107
+ return this.adapters[side] ? this.adapters[side] : null;
108
+ }
109
+
110
+ async getPoolIdentifiers(
111
+ srcToken: Token,
112
+ destToken: Token,
113
+ side: SwapSide,
114
+ blockNumber: number,
115
+ ): Promise<string[]> {
116
+ const normalizedSrcToken = this.normalizeToken(srcToken);
117
+ const normalizedDestToken = this.normalizeToken(destToken);
118
+
119
+ if (normalizedSrcToken.address === normalizedDestToken.address) {
120
+ return [];
121
+ }
122
+
123
+ const poolIdentifier = getPoolIdentifier(
124
+ this.dexKey,
125
+ normalizedSrcToken.address,
126
+ normalizedDestToken.address,
127
+ );
128
+
129
+ const levels = await this.getCachedLevels();
130
+ if (levels === null) {
131
+ return [];
132
+ }
133
+
134
+ return Object.keys(levels)
135
+ .map((pair: string) => {
136
+ return getPoolIdentifier(
137
+ this.dexKey,
138
+ levels[pair].base!,
139
+ levels[pair].quote!,
140
+ );
141
+ })
142
+ .filter((pi: string) => pi === poolIdentifier);
143
+ }
144
+
145
+ computePricesFromLevelsBis(
146
+ amounts: BigNumber[],
147
+ asksAndBids: SwaapV2PriceLevels,
148
+ srcToken: Token,
149
+ destToken: Token,
150
+ side: SwapSide,
151
+ ): bigint[] {
152
+ let levels: SwaapV2PriceLevel[] = [];
153
+ if (side === SwapSide.BUY) {
154
+ if (destToken.address === asksAndBids.base!) {
155
+ levels = asksAndBids.asks;
156
+ } else {
157
+ levels = this.invertPrices(asksAndBids.bids);
158
+ }
159
+ } else {
160
+ if (srcToken.address === asksAndBids.base!) {
161
+ levels = asksAndBids.bids;
162
+ } else {
163
+ levels = this.invertPrices(asksAndBids.asks);
164
+ }
165
+ }
166
+ return this.computeLevelsQuote(amounts, levels, srcToken, destToken, side);
167
+ }
168
+
169
+ inversePrice(priceLevel: SwaapV2PriceLevel): SwaapV2PriceLevel {
170
+ return {
171
+ level: priceLevel.level * priceLevel.price,
172
+ price: 1 / priceLevel.price,
173
+ };
174
+ }
175
+
176
+ invertPrices(levels: SwaapV2PriceLevel[]): SwaapV2PriceLevel[] {
177
+ return levels.map(pl => this.inversePrice(pl));
178
+ }
179
+
180
+ computeLevelsQuote(
181
+ amounts: BigNumber[],
182
+ levels: SwaapV2PriceLevel[],
183
+ srcToken: Token,
184
+ destToken: Token,
185
+ side: SwapSide,
186
+ ): bigint[] {
187
+ const size = levels.length;
188
+ if (size === 0) {
189
+ return amounts.map(_ => BigInt(0));
190
+ }
191
+ return amounts.map((amount: BigNumber) => {
192
+ if (amount.isZero() || amount.lt(BigNumber(levels[0].level))) {
193
+ return BigInt(0);
194
+ }
195
+
196
+ let i = 0;
197
+ let output = BN_0;
198
+ let previousLevel = BN_0;
199
+ let remaininig = BigNumber(amount);
200
+ let enoughLiquidity = false;
201
+ while (i < size) {
202
+ const levelDelta = BigNumber(levels[i].level).minus(previousLevel);
203
+ if (levelDelta.lte(remaininig)) {
204
+ output = output.plus(levelDelta.times(levels[i].price));
205
+ remaininig = remaininig.minus(levelDelta);
206
+ previousLevel = BigNumber(levels[i].level);
207
+ i += 1;
208
+ } else {
209
+ output = output.plus(remaininig.times(levels[i].price));
210
+ enoughLiquidity = true;
211
+ break;
212
+ }
213
+ }
214
+ if (enoughLiquidity) {
215
+ return BigInt(
216
+ output
217
+ .multipliedBy(
218
+ getBigNumberPow(
219
+ side === SwapSide.BUY ? srcToken.decimals : destToken.decimals,
220
+ ),
221
+ )
222
+ .toFixed(0),
223
+ );
224
+ }
225
+ return BigInt(0); // not enough liquidity
226
+ });
227
+ }
228
+
229
+ async getCachedLevels(): Promise<Record<string, SwaapV2PriceLevels> | null> {
230
+ const cachedLevels = await this.dexHelper.cache.get(
231
+ this.dexKey,
232
+ this.network,
233
+ getPriceLevelsCacheKey(this.dexKey),
234
+ );
235
+
236
+ if (cachedLevels) {
237
+ return JSON.parse(cachedLevels) as Record<string, SwaapV2PriceLevels>;
238
+ }
239
+
240
+ return null;
241
+ }
242
+
243
+ normalizeToken(token: Token): Token {
244
+ return {
245
+ address: normalizeTokenAddress(token.address),
246
+ decimals: token.decimals,
247
+ };
248
+ }
249
+
250
+ async getPricesVolume(
251
+ srcToken: Token,
252
+ destToken: Token,
253
+ amounts: bigint[],
254
+ side: SwapSide,
255
+ blockNumber: number,
256
+ limitPools?: string[],
257
+ ): Promise<null | ExchangePrices<SwaapV2Data>> {
258
+ const normalizedSrcToken = this.normalizeToken(srcToken);
259
+ const normalizedDestToken = this.normalizeToken(destToken);
260
+
261
+ const requestedPoolIdentifier: string = getPoolIdentifier(
262
+ this.dexKey,
263
+ normalizedSrcToken.address,
264
+ normalizedDestToken.address,
265
+ );
266
+
267
+ if (normalizedSrcToken.address === normalizedDestToken.address) {
268
+ return null;
269
+ }
270
+
271
+ const pools =
272
+ limitPools ??
273
+ (await this.getPoolIdentifiers(srcToken, destToken, side, blockNumber));
274
+
275
+ const levels = await this.getCachedLevels();
276
+ if (levels === null) {
277
+ return null;
278
+ }
279
+
280
+ const levelEntries: SwaapV2PriceLevels[] = Object.keys(levels)
281
+ .map((pair: string) => {
282
+ if (
283
+ pools.includes(
284
+ getPoolIdentifier(
285
+ this.dexKey,
286
+ normalizedSrcToken.address,
287
+ normalizedDestToken.address,
288
+ ),
289
+ )
290
+ ) {
291
+ return levels[pair];
292
+ }
293
+ return undefined;
294
+ })
295
+ .filter(o => o !== undefined)
296
+ .map(o => o!);
297
+
298
+ const prices = levelEntries.map((askAndBids: SwaapV2PriceLevels) => {
299
+ const divider = getBigNumberPow(
300
+ (side === SwapSide.SELL ? normalizedSrcToken : normalizedDestToken)
301
+ .decimals,
302
+ );
303
+
304
+ const amountsFloat = amounts.map(a =>
305
+ new BigNumber(a.toString()).dividedBy(divider),
306
+ );
307
+
308
+ const unitPrice = this.computePricesFromLevelsBis(
309
+ [BN_1],
310
+ askAndBids,
311
+ normalizedSrcToken,
312
+ normalizedDestToken,
313
+ side,
314
+ )[0];
315
+ const prices = this.computePricesFromLevelsBis(
316
+ amountsFloat,
317
+ askAndBids,
318
+ normalizedSrcToken,
319
+ normalizedDestToken,
320
+ side,
321
+ );
322
+
323
+ return {
324
+ gasCost: GAS_COST_ESTIMATION,
325
+ exchange: this.dexKey,
326
+ data: {},
327
+ prices,
328
+ unit: unitPrice,
329
+ poolIdentifier: requestedPoolIdentifier,
330
+ poolAddresses: [this.routerAddressPlaceholder],
331
+ } as PoolPrices<SwaapV2Data>;
332
+ });
333
+
334
+ return prices;
335
+ }
336
+
337
+ getBaseToken(poolIdentifier: string): string {
338
+ return poolIdentifier.split('_')[1];
339
+ }
340
+
341
+ getLevels(
342
+ askAndBids: SwaapV2PriceLevels,
343
+ side: SwapSide,
344
+ poolIdentifier: string,
345
+ ) {
346
+ const baseToken: string = this.getBaseToken(poolIdentifier);
347
+ if (side === SwapSide.SELL) {
348
+ return askAndBids.asks;
349
+ }
350
+ return askAndBids.asks;
351
+ }
352
+
353
+ async preProcessTransaction(
354
+ optimalSwapExchange: OptimalSwapExchange<SwaapV2Data>,
355
+ srcToken: Token,
356
+ destToken: Token,
357
+ side: SwapSide,
358
+ options: PreprocessTransactionOptions,
359
+ ): Promise<[OptimalSwapExchange<SwaapV2Data>, ExchangeTxInfo]> {
360
+ const isSell = side === SwapSide.SELL;
361
+
362
+ const normalizedSrcToken = this.normalizeToken(srcToken);
363
+ const normalizedDestToken = this.normalizeToken(destToken);
364
+
365
+ const tolerance = (
366
+ options.slippageFactor > BN_1
367
+ ? options.slippageFactor.minus(BN_1)
368
+ : BN_1.minus(options.slippageFactor)
369
+ ).toNumber();
370
+
371
+ const quote = await this.rateFetcher.getQuote(
372
+ this.network,
373
+ normalizedSrcToken,
374
+ normalizedDestToken,
375
+ isSell ? optimalSwapExchange.srcAmount : optimalSwapExchange.destAmount,
376
+ isSell ? 1 : 2,
377
+ options.txOrigin,
378
+ this.augustusAddress,
379
+ tolerance,
380
+ this.getQuoteReqParams(),
381
+ );
382
+
383
+ if (!quote.success) {
384
+ const message = `${this.dexKey}-${
385
+ this.network
386
+ }: Failed to fetch RFQ for ${getPairName(
387
+ normalizedSrcToken.address,
388
+ normalizedDestToken.address,
389
+ )}: ${JSON.stringify(quote)}`;
390
+ this.logger.warn(message);
391
+ throw new SwaapV2QuoteError(message);
392
+ } else if (!quote.calldata) {
393
+ const message = `${this.dexKey}-${
394
+ this.network
395
+ }: Failed to fetch RFQ for ${getPairName(
396
+ normalizedSrcToken.address,
397
+ normalizedDestToken.address,
398
+ )}. Missing quote data`;
399
+ this.logger.warn(message);
400
+ throw new SwaapV2QuoteError(message);
401
+ } else if (!quote.router) {
402
+ const message = `${this.dexKey}-${
403
+ this.network
404
+ }: Failed to fetch RFQ for ${getPairName(
405
+ normalizedSrcToken.address,
406
+ normalizedDestToken.address,
407
+ )}. Missing router address`;
408
+ this.logger.warn(message);
409
+ throw new SwaapV2QuoteError(message);
410
+ }
411
+
412
+ return [
413
+ {
414
+ ...optimalSwapExchange,
415
+ data: {
416
+ router: quote.router,
417
+ callData: quote.calldata,
418
+ },
419
+ },
420
+ { deadline: BigInt(getLocalDeadlineAsFriendlyPlaceholder()) },
421
+ ];
422
+ }
423
+
424
+ // Returns estimated gas cost of calldata for this DEX in multiSwap
425
+ getCalldataGasCost(poolPrices: PoolPrices<SwaapV2Data>): number | number[] {
426
+ return (
427
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
428
+ CALLDATA_GAS_COST.LENGTH_LARGE +
429
+ // ParentStruct header
430
+ CALLDATA_GAS_COST.OFFSET_SMALL +
431
+ // ParentStruct -> swaps[] header
432
+ CALLDATA_GAS_COST.OFFSET_LARGE +
433
+ // ParentStruct -> assets[] header
434
+ CALLDATA_GAS_COST.OFFSET_LARGE +
435
+ // ParentStruct -> funds
436
+ CALLDATA_GAS_COST.ADDRESS +
437
+ CALLDATA_GAS_COST.BOOL +
438
+ CALLDATA_GAS_COST.ADDRESS +
439
+ CALLDATA_GAS_COST.BOOL +
440
+ // ParentStruct -> limits[] header
441
+ CALLDATA_GAS_COST.OFFSET_LARGE +
442
+ // ParentStruct -> deadline
443
+ CALLDATA_GAS_COST.TIMESTAMP +
444
+ // ParentStruct -> swaps[]
445
+ CALLDATA_GAS_COST.LENGTH_SMALL +
446
+ // ParentStruct -> swaps[0] header
447
+ CALLDATA_GAS_COST.OFFSET_SMALL +
448
+ // ParentStruct -> swaps[0] -> poolId
449
+ CALLDATA_GAS_COST.FULL_WORD +
450
+ // ParentStruct -> swaps[0] -> assetInIndex
451
+ CALLDATA_GAS_COST.INDEX +
452
+ // ParentStruct -> swaps[0] -> assetOutIndex
453
+ CALLDATA_GAS_COST.INDEX +
454
+ // ParentStruct -> swaps[0] -> amount
455
+ CALLDATA_GAS_COST.AMOUNT +
456
+ // ParentStruct -> swaps[0] -> userData header
457
+ CALLDATA_GAS_COST.OFFSET_SMALL +
458
+ // ParentStruct -> swaps[0] -> userData
459
+ CALLDATA_GAS_COST.ZERO +
460
+ // ParentStruct -> assets[]
461
+ CALLDATA_GAS_COST.LENGTH_SMALL +
462
+ // ParentStruct -> assets[0:2]
463
+ CALLDATA_GAS_COST.ADDRESS * 2 +
464
+ // ParentStruct -> limits[]
465
+ CALLDATA_GAS_COST.LENGTH_SMALL +
466
+ // ParentStruct -> limits[0:2]
467
+ CALLDATA_GAS_COST.FULL_WORD * 2 +
468
+ // Bool -> IsBatchSwap
469
+ CALLDATA_GAS_COST.BOOL
470
+ );
471
+ }
472
+
473
+ getAdapterParam(
474
+ srcToken: string,
475
+ destToken: string,
476
+ srcAmount: string,
477
+ destAmount: string,
478
+ data: SwaapV2Data,
479
+ side: SwapSide,
480
+ ): AdapterExchangeParam {
481
+ const { router, callData } = data;
482
+
483
+ assert(
484
+ router !== undefined,
485
+ `${this.dexKey}-${this.network}: router undefined`,
486
+ );
487
+
488
+ assert(
489
+ callData !== undefined,
490
+ `${this.dexKey}-${this.network}: callData undefined`,
491
+ );
492
+
493
+ let payload: string;
494
+ const truncatedCalldata = '0x' + callData.slice(10); // droping the function selector
495
+ const isBatchSwap = callData.slice(0, 10) === BATCH_SWAP_SELECTOR;
496
+
497
+ if (isBatchSwap) {
498
+ const batchswapAbi = routerAbi.filter(abi => abi.name === 'batchSwap');
499
+
500
+ const callDataStruct = this.abiCoder.decodeParameters(
501
+ batchswapAbi[0].inputs!,
502
+ truncatedCalldata,
503
+ );
504
+
505
+ const callerSlots = Array(callDataStruct.swaps.length).fill(160);
506
+
507
+ payload = this.abiCoder.encodeParameters(
508
+ [
509
+ 'bool',
510
+ 'uint256[]',
511
+ {
512
+ ParentStruct: {
513
+ 'swaps[]': {
514
+ poolId: 'bytes32',
515
+ assetInIndex: 'uint256',
516
+ assetOutIndex: 'uint256',
517
+ amount: 'uint256',
518
+ userData: 'bytes',
519
+ },
520
+ assets: 'address[]',
521
+ funds: {
522
+ sender: 'address',
523
+ fromInternalBalance: 'bool',
524
+ recipient: 'address',
525
+ toInternalBalance: 'bool',
526
+ },
527
+ limits: 'int256[]',
528
+ },
529
+ },
530
+ ],
531
+ [
532
+ isBatchSwap,
533
+ callerSlots,
534
+ {
535
+ swaps: callDataStruct.swaps,
536
+ assets: callDataStruct.assets,
537
+ funds: callDataStruct.funds,
538
+ limits: callDataStruct.limits.map((_: any) => MAX_INT),
539
+ },
540
+ ],
541
+ );
542
+ } else {
543
+ const swapAbi = routerAbi.filter(abi => abi.name === 'swap');
544
+
545
+ const callDataStruct = this.abiCoder.decodeParameters(
546
+ swapAbi[0].inputs!,
547
+ truncatedCalldata,
548
+ );
549
+
550
+ const callerSlot = CALLER_SLOT;
551
+
552
+ payload = this.abiCoder.encodeParameters(
553
+ [
554
+ 'bool',
555
+ 'uint256',
556
+ {
557
+ ParentStruct: {
558
+ swap: {
559
+ poolId: 'bytes32',
560
+ kind: 'uint8',
561
+ assetIn: 'address',
562
+ assetOut: 'address',
563
+ amount: 'uint256',
564
+ userData: 'bytes',
565
+ },
566
+ funds: {
567
+ sender: 'address',
568
+ fromInternalBalance: 'bool',
569
+ recipient: 'address',
570
+ toInternalBalance: 'bool',
571
+ },
572
+ limit: 'uint256',
573
+ },
574
+ },
575
+ ],
576
+ [
577
+ isBatchSwap,
578
+ callerSlot,
579
+ {
580
+ swap: {
581
+ poolId: callDataStruct.singleSwap.poolId,
582
+ kind: callDataStruct.singleSwap.kind,
583
+ assetIn: callDataStruct.singleSwap.assetIn,
584
+ assetOut: callDataStruct.singleSwap.assetOut,
585
+ amount: callDataStruct.singleSwap.amount,
586
+ userData: callDataStruct.singleSwap.userData,
587
+ },
588
+ funds: {
589
+ sender: callDataStruct.funds.sender,
590
+ fromInternalBalance: callDataStruct.funds.fromInternalBalance,
591
+ recipient: callDataStruct.funds.recipient,
592
+ toInternalBalance: callDataStruct.funds.toInternalBalance,
593
+ },
594
+ limit: side === SwapSide.BUY ? MAX_UINT : '0',
595
+ },
596
+ ],
597
+ );
598
+ }
599
+
600
+ return {
601
+ targetExchange: router,
602
+ payload: payload,
603
+ networkFee: '0',
604
+ };
605
+ }
606
+
607
+ async getSimpleParam(
608
+ srcToken: string,
609
+ destToken: string,
610
+ srcAmount: string,
611
+ destAmount: string,
612
+ data: SwaapV2Data,
613
+ side: SwapSide,
614
+ ): Promise<SimpleExchangeParam> {
615
+ const { router, callData } = data;
616
+
617
+ assert(
618
+ router !== undefined,
619
+ `${this.dexKey}-${this.network}: router undefined`,
620
+ );
621
+
622
+ assert(
623
+ callData !== undefined,
624
+ `${this.dexKey}-${this.network}: callData undefined`,
625
+ );
626
+
627
+ return this.buildSimpleParamWithoutWETHConversion(
628
+ srcToken,
629
+ srcAmount,
630
+ destToken,
631
+ destAmount,
632
+ callData,
633
+ router,
634
+ );
635
+ }
636
+
637
+ computeMaxLiquidity = (
638
+ levels: SwaapV2PriceLevels,
639
+ tokenAddress: string,
640
+ ): number => {
641
+ if (tokenAddress === levels.base!) {
642
+ return (
643
+ (levels.asks[levels.asks.length - 1]?.level ?? 0) *
644
+ levels.asks[0]?.price
645
+ );
646
+ }
647
+ return (
648
+ (levels.asks[levels.bids.length - 1]?.level ?? 0) * levels.asks[0]?.price
649
+ );
650
+ };
651
+
652
+ async getTopPoolsForToken(
653
+ tokenAddress: Address,
654
+ limit: number,
655
+ ): Promise<PoolLiquidity[]> {
656
+ const normalizedTokenAddress = normalizeTokenAddress(tokenAddress);
657
+
658
+ const pLevels = await this.getCachedLevels();
659
+
660
+ if (pLevels === null) {
661
+ return [];
662
+ }
663
+
664
+ return Object.keys(pLevels)
665
+ .filter((pair: string) => {
666
+ return (
667
+ normalizedTokenAddress === pLevels[pair].base ||
668
+ normalizedTokenAddress === pLevels[pair].quote
669
+ );
670
+ })
671
+ .map((pair: string) => {
672
+ return {
673
+ exchange: this.dexKey,
674
+ address: this.routerAddressPlaceholder,
675
+ connectorTokens: [this.getTokenFromAddress(pLevels[pair].quote!)],
676
+ liquidityUSD: this.computeMaxLiquidity(pLevels[pair], tokenAddress),
677
+ } as PoolLiquidity;
678
+ })
679
+ .sort((pl: PoolLiquidity) => {
680
+ return -pl.liquidityUSD;
681
+ })
682
+ .slice(0, limit);
683
+ }
684
+
685
+ getTokenFromAddress(address: Address): Token {
686
+ return { address, decimals: 0 };
687
+ }
688
+
689
+ releaseResources(): void {
690
+ if (this.rateFetcher) {
691
+ this.rateFetcher.stop();
692
+ }
693
+ }
694
+
695
+ getPriceLevelsReqParams(): SwaapV2APIParameters {
696
+ return this.geAPIReqParams(SWAAP_RFQ_PRICES_ENDPOINT, 'GET');
697
+ }
698
+
699
+ getQuoteReqParams(): SwaapV2APIParameters {
700
+ return this.geAPIReqParams(SWAAP_RFQ_QUOTE_ENDPOINT, 'POST');
701
+ }
702
+
703
+ geAPIReqParams(endpoint: string, method: Method): SwaapV2APIParameters {
704
+ return {
705
+ url: `${SWAAP_RFQ_API_URL}/${endpoint}`,
706
+ params: {
707
+ networkId: this.network,
708
+ },
709
+ headers: { 'x-api-key': this.swaapV2AuthToken },
710
+ method: method,
711
+ };
712
+ }
713
+ }