@paraswap/dex-lib 3.4.2-balancer-v2-single-swap.0 → 3.4.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 (110) hide show
  1. package/README.md +377 -377
  2. package/build/config.js +9 -5
  3. package/build/config.js.map +1 -1
  4. package/build/dex/algebra/algebra.js +25 -25
  5. package/build/dex/balancer-v1/balancer-v1.js +34 -34
  6. package/build/dex/balancer-v2/balancer-v2.d.ts +1 -1
  7. package/build/dex/balancer-v2/balancer-v2.js +65 -78
  8. package/build/dex/balancer-v2/balancer-v2.js.map +1 -1
  9. package/build/dex/camelot/camelot.js +27 -27
  10. package/build/dex/kyberdmm/kyberdmm.js +27 -27
  11. package/build/dex/pancakeswap-v3/pancakeswap-v3.js +25 -25
  12. package/build/dex/solidly/solidly.js +27 -27
  13. package/build/dex/solidly-v3/solidly-v3.js +25 -25
  14. package/build/dex/swaap-v2/config.js +15 -0
  15. package/build/dex/swaap-v2/config.js.map +1 -1
  16. package/build/dex/uniswap-v2/uniswap-v2.js +26 -26
  17. package/build/dex/uniswap-v3/uniswap-v3.js +25 -25
  18. package/funding.json +5 -5
  19. package/package.json +1 -1
  20. package/src/config.ts +500 -496
  21. package/src/constants.ts +67 -67
  22. package/src/dex/aave-v2/aave-v2.ts +409 -409
  23. package/src/dex/aave-v3/aave-v3.ts +320 -320
  24. package/src/dex/algebra/algebra.ts +1180 -1180
  25. package/src/dex/angle-staked-stable/angle-staked-stable.ts +347 -347
  26. package/src/dex/augustus-rfq.ts +180 -180
  27. package/src/dex/bProtocol/bProtocol.ts +108 -108
  28. package/src/dex/balancer-v1/balancer-v1.ts +572 -572
  29. package/src/dex/balancer-v2/balancer-v2-e2e.test.ts +1699 -1699
  30. package/src/dex/balancer-v2/balancer-v2.ts +1669 -1701
  31. package/src/dex/bancor/bancor.ts +128 -128
  32. package/src/dex/camelot/camelot.ts +873 -873
  33. package/src/dex/compound/compound.ts +107 -107
  34. package/src/dex/curve-v1/config.ts +1179 -1179
  35. package/src/dex/curve-v1/curve-v1-e2e.test.ts +507 -507
  36. package/src/dex/curve-v1/curve-v1.ts +1315 -1315
  37. package/src/dex/curve-v1-factory/config.ts +1018 -1018
  38. package/src/dex/curve-v1-factory/curve-v1-factory.ts +1288 -1288
  39. package/src/dex/curve-v2/curve-v2.ts +440 -440
  40. package/src/dex/dexalot/dexalot.ts +1100 -1100
  41. package/src/dex/dodo-v1/dodo-v1.ts +132 -132
  42. package/src/dex/dodo-v2.ts +266 -266
  43. package/src/dex/etherfi.ts +239 -239
  44. package/src/dex/generic-rfq/generic-rfq.ts +431 -431
  45. package/src/dex/gmx/gmx.ts +321 -321
  46. package/src/dex/hashflow/hashflow.ts +1135 -1135
  47. package/src/dex/idex.ts +254 -254
  48. package/src/dex/index.ts +357 -357
  49. package/src/dex/jarvis-v6/jarvis-v6.ts +509 -509
  50. package/src/dex/jarvis.ts +262 -262
  51. package/src/dex/kyberdmm/kyberdmm.ts +649 -649
  52. package/src/dex/lido/lido.ts +110 -110
  53. package/src/dex/maker-psm/maker-psm.ts +592 -592
  54. package/src/dex/maverick-v1/maverick-v1.ts +537 -537
  55. package/src/dex/nerve/config.ts +635 -635
  56. package/src/dex/nerve/nerve-e2e.test.ts +731 -731
  57. package/src/dex/nerve/nerve-events.test.ts +911 -911
  58. package/src/dex/nerve/nerve.ts +467 -467
  59. package/src/dex/onebit/onebit.ts +113 -113
  60. package/src/dex/pancakeswap-v3/pancakeswap-v3.ts +1150 -1150
  61. package/src/dex/paraswap-limit-orders/config.ts +60 -60
  62. package/src/dex/paraswap-limit-orders/paraswap-limit-orders-e2e.test.ts +137 -137
  63. package/src/dex/paraswap-limit-orders/paraswap-limit-orders-integration.test.ts +328 -328
  64. package/src/dex/paraswap-limit-orders/paraswap-limit-orders.ts +631 -631
  65. package/src/dex/polygon-migrator/polygon-migrator.ts +194 -194
  66. package/src/dex/quick-perps/quick-perps.ts +337 -337
  67. package/src/dex/quickswap/config.ts +16 -16
  68. package/src/dex/quickswap/quickswap-e2e.test.ts +384 -384
  69. package/src/dex/smoothy/smoothy.ts +110 -110
  70. package/src/dex/solidly/config.ts +225 -225
  71. package/src/dex/solidly/solidly-e2e.test.ts +1421 -1421
  72. package/src/dex/solidly/solidly-integration.test.ts +1753 -1753
  73. package/src/dex/solidly/solidly.ts +687 -687
  74. package/src/dex/solidly-v3/solidly-v3.ts +968 -968
  75. package/src/dex/spark/spark.ts +284 -284
  76. package/src/dex/stable-pool/stable-pool.ts +129 -129
  77. package/src/dex/swaap-v2/config.ts +15 -0
  78. package/src/dex/swaap-v2/swaap-v2-e2e.test.ts +233 -17
  79. package/src/dex/swaap-v2/swaap-v2-integration.test.ts +1 -1
  80. package/src/dex/swaap-v2/swaap-v2.ts +1056 -1056
  81. package/src/dex/swell/swell.ts +312 -312
  82. package/src/dex/synthetix/synthetix.ts +420 -420
  83. package/src/dex/trader-joe-v2.1/trader-joe-v2.1.ts +180 -180
  84. package/src/dex/uniswap-v2/config.ts +637 -637
  85. package/src/dex/uniswap-v2/constants.ts +58 -58
  86. package/src/dex/uniswap-v2/uniswap-v2-e2e-avalanche.test.ts +1257 -1257
  87. package/src/dex/uniswap-v2/uniswap-v2-e2e-base.test.ts +42 -42
  88. package/src/dex/uniswap-v2/uniswap-v2-e2e-bsc.test.ts +1295 -1295
  89. package/src/dex/uniswap-v2/uniswap-v2-e2e-mainnet.test.ts +1834 -1834
  90. package/src/dex/uniswap-v2/uniswap-v2-e2e-polygon.test.ts +871 -871
  91. package/src/dex/uniswap-v2/uniswap-v2.ts +1117 -1117
  92. package/src/dex/uniswap-v3/uniswap-v3.ts +1501 -1501
  93. package/src/dex/uniswap-v3.ts +242 -242
  94. package/src/dex/weth/config.ts +73 -73
  95. package/src/dex/weth/weth.ts +230 -230
  96. package/src/dex/wombat/wombat.ts +467 -467
  97. package/src/dex/woo-fi-v2/woo-fi-v2.ts +529 -529
  98. package/src/dex/wsteth/wsteth.ts +304 -304
  99. package/src/dex/zerox/index.ts +328 -328
  100. package/src/executor/Executor01BytecodeBuilder.ts +474 -474
  101. package/src/executor/Executor02BytecodeBuilder.ts +1392 -1392
  102. package/src/executor/ExecutorBytecodeBuilder.ts +390 -390
  103. package/src/executor/ExecutorDetector.ts +131 -131
  104. package/src/executor/constants.ts +66 -66
  105. package/src/executor/executor01-bytecode-builder-e2e.test.ts +1478 -1478
  106. package/src/executor/utils.ts +62 -62
  107. package/src/router/simpleswap.ts +366 -366
  108. package/src/types.ts +342 -342
  109. package/tests/constants-e2e.ts +1632 -1622
  110. package/tests/generate-new-limit-order.ts +107 -107
@@ -1,649 +1,649 @@
1
- import { Interface, AbiCoder } from '@ethersproject/abi';
2
- import { SimpleExchange } from '../simple-exchange';
3
- import { IDex } from '../idex';
4
- import _ from 'lodash';
5
- import { Network, SUBGRAPH_TIMEOUT, SwapSide } from '../../constants';
6
- import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
7
- import { PRECISION } from './fee-formula';
8
- import {
9
- getTradeInfo,
10
- KyberDmmPair,
11
- KyberDmmPool,
12
- KyberDmmPoolOrderedParams,
13
- KyberDmmPoolState,
14
- } from './pool';
15
- import {
16
- AdapterExchangeParam,
17
- ExchangePrices,
18
- PoolPrices,
19
- PoolLiquidity,
20
- SimpleExchangeParam,
21
- Token,
22
- NumberAsString,
23
- Address,
24
- DexExchangeParam,
25
- } from '../../types';
26
- import {
27
- KyberDmmData,
28
- KyberDMMFunctions,
29
- KyberDmmParam,
30
- TradeInfo,
31
- } from './types';
32
- import { IDexHelper } from '../../dex-helper';
33
- import { Adapters, KyberDmmConfig } from './config';
34
- import { Logger } from 'log4js';
35
- import { Contract } from 'web3-eth-contract';
36
-
37
- import kyberDmmFactoryABI from '../../abi/kyberdmm/kyber-dmm-factory.abi.json';
38
- import kyberDmmPoolABI from '../../abi/kyberdmm/kyber-dmm-pool.abi.json';
39
- import KyberDmmExchangeRouterABI from '../../abi/kyberdmm/kyber-dmm-exchange-router.abi.json';
40
- import { getBigIntPow, getDexKeysWithNetwork } from '../../utils';
41
- import { extractReturnAmountPosition } from '../../executor/utils';
42
-
43
- const MAX_TRACKED_PAIR_POOLS = 3;
44
-
45
- const iface = new Interface(kyberDmmPoolABI);
46
- const coder = new AbiCoder();
47
-
48
- export class KyberDmm
49
- extends SimpleExchange
50
- implements IDex<KyberDmmData, KyberDmmParam>
51
- {
52
- pairs: { [key: string]: KyberDmmPair } = {};
53
- needWrapNative = true;
54
- factory: Contract;
55
- logger: Logger;
56
-
57
- exchangeRouterInterface: Interface;
58
-
59
- readonly hasConstantPriceLargeAmounts = false;
60
- readonly isFeeOnTransferSupported = false;
61
-
62
- public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
63
- getDexKeysWithNetwork(KyberDmmConfig);
64
-
65
- constructor(
66
- protected network: Network,
67
- dexKey: string,
68
- protected dexHelper: IDexHelper,
69
- protected config = KyberDmmConfig[dexKey][network],
70
- protected adapters = Adapters[network],
71
- ) {
72
- super(dexHelper, dexKey);
73
-
74
- this.logger = dexHelper.getLogger(dexKey);
75
-
76
- this.factory = new this.dexHelper.web3Provider.eth.Contract(
77
- kyberDmmFactoryABI as any,
78
- config.factoryAddress,
79
- );
80
-
81
- this.exchangeRouterInterface = new Interface(KyberDmmExchangeRouterABI);
82
- }
83
-
84
- async getPoolIdentifiers(
85
- from: Token,
86
- to: Token,
87
- side: SwapSide,
88
- blockNumber: number,
89
- ): Promise<string[]> {
90
- from = this.dexHelper.config.wrapETH(from);
91
- to = this.dexHelper.config.wrapETH(to);
92
-
93
- const pair = await this.findPair(from, to);
94
-
95
- if (pair && pair.exchanges.length > 0) {
96
- const z = pair.exchanges.map(poolAddress => {
97
- return `${this.dexKey}_${poolAddress.toLowerCase()}`;
98
- });
99
-
100
- return z;
101
- } else return [];
102
- }
103
-
104
- getAdapters(side: SwapSide): { name: string; index: number }[] | null {
105
- if (side === SwapSide.BUY) return null;
106
- return this.adapters;
107
- }
108
-
109
- async getTopPoolsForToken(
110
- tokenAddress: string,
111
- count: number,
112
- ): Promise<PoolLiquidity[]> {
113
- if (!this.config.subgraphURL) return [];
114
-
115
- const query = `
116
- query ($token: Bytes!, $count: Int) {
117
- pools0: pairs(first: $count, orderBy: reserveUSD, orderDirection: desc, where: {token0: $token}) {
118
- id
119
- reserveUSD
120
- token0{
121
- id
122
- decimals
123
- }
124
- token1{
125
- id
126
- decimals
127
- }
128
- }
129
- pools1: pairs(first: $count, orderBy: reserveUSD, orderDirection: desc, where: {token1: $token}) {
130
- id
131
- reserveUSD
132
- token1{
133
- id
134
- decimals
135
- }
136
- token0{
137
- id
138
- decimals
139
- }
140
- }
141
- }
142
- `;
143
-
144
- const { data } = await this.dexHelper.httpRequest.post(
145
- this.config.subgraphURL,
146
- {
147
- query,
148
- variables: { token: tokenAddress.toLowerCase(), count },
149
- },
150
- SUBGRAPH_TIMEOUT,
151
- );
152
-
153
- if (!(data && data.pools0 && data.pools1))
154
- throw new Error(
155
- `Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`,
156
- );
157
-
158
- const pools = _.map(_.concat(data.pools0, data.pools1), pool => ({
159
- exchange: this.dexKey,
160
- address: pool.id.toLowerCase(),
161
- connectorTokens: [pool.token0, pool.token1].reduce(
162
- (acc, { decimals, id }) => {
163
- if (id.toLowerCase() != tokenAddress.toLowerCase())
164
- acc.push({
165
- decimals: parseInt(decimals),
166
- address: id.toLowerCase(),
167
- });
168
- return acc;
169
- },
170
- [],
171
- ),
172
- liquidityUSD: parseFloat(pool.reserveUSD),
173
- }));
174
-
175
- return _.slice(_.sortBy(pools, [pool => -1 * pool.liquidityUSD]), 0, count);
176
- }
177
-
178
- getAdapterParam(
179
- srcToken: string,
180
- destToken: string,
181
- srcAmount: string,
182
- destAmount: string,
183
- data: KyberDmmData,
184
- side: SwapSide,
185
- ): AdapterExchangeParam {
186
- const payload = this.abiCoder.encodeParameter(
187
- {
188
- ParentStruct: {
189
- poolPath: 'address[]',
190
- path: 'address[]',
191
- },
192
- },
193
- { poolPath: data.pools.map(p => p.address), path: data.path },
194
- );
195
- return {
196
- targetExchange: data.router,
197
- payload,
198
- networkFee: '0',
199
- };
200
- }
201
-
202
- async getSimpleParam(
203
- srcToken: string,
204
- destToken: string,
205
- srcAmount: string,
206
- destAmount: string,
207
- data: KyberDmmData,
208
- side: SwapSide,
209
- ): Promise<SimpleExchangeParam> {
210
- const isSell = side === SwapSide.SELL;
211
- const swapFunctionParams: KyberDmmParam = [
212
- isSell ? srcAmount : destAmount,
213
- isSell ? destAmount : srcAmount,
214
- data.pools.map(p => p.address),
215
- data.path,
216
- this.augustusAddress,
217
- Number.MAX_SAFE_INTEGER.toString(),
218
- ];
219
- const swapData = this.exchangeRouterInterface.encodeFunctionData(
220
- isSell
221
- ? KyberDMMFunctions.swapExactTokensForTokens
222
- : KyberDMMFunctions.swapTokensForExactTokens,
223
- swapFunctionParams,
224
- );
225
-
226
- return this.buildSimpleParamWithoutWETHConversion(
227
- srcToken,
228
- srcAmount,
229
- destToken,
230
- destAmount,
231
- swapData,
232
- data.router,
233
- );
234
- }
235
-
236
- getDexParam(
237
- srcToken: Address,
238
- destToken: Address,
239
- srcAmount: NumberAsString,
240
- destAmount: NumberAsString,
241
- recipient: Address,
242
- data: KyberDmmData,
243
- side: SwapSide,
244
- ): DexExchangeParam {
245
- const isSell = side === SwapSide.SELL;
246
- const swapFunctionParams: KyberDmmParam = [
247
- isSell ? srcAmount : destAmount,
248
- isSell ? destAmount : srcAmount,
249
- data.pools.map(p => p.address),
250
- data.path,
251
- recipient,
252
- Number.MAX_SAFE_INTEGER.toString(),
253
- ];
254
- const exchangeData = this.exchangeRouterInterface.encodeFunctionData(
255
- isSell
256
- ? KyberDMMFunctions.swapExactTokensForTokens
257
- : KyberDMMFunctions.swapTokensForExactTokens,
258
- swapFunctionParams,
259
- );
260
-
261
- return {
262
- needWrapNative: this.needWrapNative,
263
- dexFuncHasRecipient: true,
264
- exchangeData,
265
- targetExchange: data.router,
266
- returnAmountPos:
267
- side === SwapSide.SELL
268
- ? extractReturnAmountPosition(
269
- this.exchangeRouterInterface,
270
- KyberDMMFunctions.swapExactTokensForTokens,
271
- 'amounts',
272
- data.path.length - 1, // last element is amount out
273
- )
274
- : undefined,
275
- };
276
- }
277
-
278
- private async addPool(
279
- pair: KyberDmmPair,
280
- poolAddress: string,
281
- poolData: KyberDmmPoolState,
282
- blockNumber: number,
283
- ) {
284
- if (
285
- pair.exchanges.find(p => p === poolAddress) &&
286
- !(poolAddress in pair.pools)
287
- ) {
288
- const pool = new KyberDmmPool(
289
- this.dexKey,
290
- this.dexHelper,
291
- poolAddress,
292
- pair.token0,
293
- pair.token1,
294
- poolData.ampBps,
295
- this.logger,
296
- );
297
- pair.pools[poolAddress] = pool;
298
- pool.addressesSubscribed.push(poolAddress);
299
- await pool.initialize(blockNumber, {
300
- state: poolData,
301
- });
302
- }
303
- }
304
-
305
- async getPricesVolume(
306
- from: Token,
307
- to: Token,
308
- amounts: bigint[],
309
- side: SwapSide,
310
- blockNumber: number,
311
- limitPools?: string[],
312
- ): Promise<ExchangePrices<KyberDmmData> | null> {
313
- try {
314
- if (!this.factory) {
315
- return null;
316
- }
317
-
318
- from = this.dexHelper.config.wrapETH(from);
319
- to = this.dexHelper.config.wrapETH(to);
320
-
321
- if (from.address.toLowerCase() === to.address.toLowerCase()) {
322
- return null;
323
- }
324
-
325
- await this.catchUpPair(from, to, blockNumber);
326
- const pairParam = await this.getPairOrderedParams(from, to, blockNumber);
327
-
328
- if (!pairParam) return null;
329
-
330
- pairParam.poolData = pairParam.poolData.filter(pool => {
331
- const poolIdentifier = `${
332
- this.dexKey
333
- }_${pool.poolAddress.toLowerCase()}`;
334
- return !limitPools || limitPools.includes(poolIdentifier);
335
- });
336
-
337
- if (!pairParam.poolData.length) return null;
338
-
339
- return Promise.all(
340
- pairParam.poolData.map(pool => {
341
- return this.getPoolPrice(
342
- from,
343
- to,
344
- side,
345
- amounts,
346
- pool,
347
- pairParam.direction,
348
- `${this.dexKey}_${pool.poolAddress.toLowerCase()}`,
349
- blockNumber,
350
- );
351
- }),
352
- );
353
- } catch (e) {
354
- if (blockNumber === 0)
355
- this.logger.error(
356
- `${this.dexKey}_getPricesVolume: Aurelius block manager not yet instantiated`,
357
- );
358
- this.logger.error(`${this.dexKey}_getPrices`, e);
359
- return null;
360
- }
361
- }
362
-
363
- // Returns estimated gas cost of calldata for this DEX in multiSwap
364
- getCalldataGasCost(poolPrices: PoolPrices<KyberDmmData>): number | number[] {
365
- return (
366
- CALLDATA_GAS_COST.DEX_OVERHEAD +
367
- CALLDATA_GAS_COST.LENGTH_LARGE +
368
- CALLDATA_GAS_COST.OFFSET_SMALL +
369
- CALLDATA_GAS_COST.OFFSET_SMALL +
370
- CALLDATA_GAS_COST.OFFSET_SMALL +
371
- CALLDATA_GAS_COST.LENGTH_SMALL +
372
- CALLDATA_GAS_COST.ADDRESS +
373
- CALLDATA_GAS_COST.LENGTH_SMALL +
374
- CALLDATA_GAS_COST.ADDRESS * 2
375
- );
376
- }
377
-
378
- private async getPoolPrice(
379
- from: Token,
380
- to: Token,
381
- side: SwapSide,
382
- amounts: bigint[],
383
- pool: { poolAddress: string; state: KyberDmmPoolState },
384
- direction: boolean,
385
- poolIdentifier: string,
386
- blockNumber: number,
387
- ): Promise<any> {
388
- // const [tokenA] = [
389
- // from.address.toLowerCase(),
390
- // to.address.toLowerCase(),
391
- // ].sort((a, b) => (a > b ? 1 : -1));
392
-
393
- const unitAmount = getBigIntPow(
394
- side == SwapSide.BUY ? to.decimals : from.decimals,
395
- ).toString();
396
-
397
- const tradeInfo = getTradeInfo(pool.state, blockNumber, direction);
398
-
399
- const unit =
400
- side == SwapSide.BUY
401
- ? await this.getBuyPrice(tradeInfo, BigInt(unitAmount))
402
- : await this.getSellPrice(tradeInfo, BigInt(unitAmount));
403
-
404
- const prices =
405
- side == SwapSide.BUY
406
- ? await Promise.all(
407
- amounts.map(amount =>
408
- this.getBuyPrice(tradeInfo, BigInt(amount.toString())),
409
- ),
410
- )
411
- : await Promise.all(
412
- amounts.map(amount =>
413
- this.getSellPrice(tradeInfo, BigInt(amount.toString())),
414
- ),
415
- );
416
-
417
- return {
418
- prices: prices.map(p => BigInt(p.toString())),
419
- unit: BigInt(unit.toString()),
420
- data: {
421
- router: this.config.routerAddress,
422
- path: [from.address.toLowerCase(), to.address.toLowerCase()],
423
- factory: this.config.factoryAddress,
424
- pools: [
425
- {
426
- address: pool.poolAddress,
427
- fee: tradeInfo.feeInPrecision.toString(),
428
- direction,
429
- },
430
- ],
431
- },
432
- exchange: this.dexKey,
433
- poolIdentifier,
434
- gasCost: this.config.poolGasCost,
435
- poolAddresses: [pool.poolAddress],
436
- };
437
- }
438
-
439
- private async getManyPoolReserves(
440
- pair: KyberDmmPair,
441
- blockNumber: number,
442
- ): Promise<{ [poolAddress: string]: KyberDmmPoolState }> {
443
- try {
444
- const calldata = pair.exchanges
445
- .map(poolAddress => [
446
- {
447
- target: poolAddress,
448
- callData: iface.encodeFunctionData('getTradeInfo', []),
449
- },
450
- {
451
- target: poolAddress,
452
- callData: iface.encodeFunctionData('getVolumeTrendData', []),
453
- },
454
- {
455
- target: poolAddress,
456
- callData: iface.encodeFunctionData('ampBps', []),
457
- },
458
- ])
459
- .flat();
460
-
461
- const data: { returnData: any[] } =
462
- await this.dexHelper.multiContract.methods
463
- .aggregate(calldata)
464
- .call({}, blockNumber);
465
-
466
- return pair.exchanges.reduce(
467
- (acc: { [key: string]: KyberDmmPoolState }, poolAddress, poolIndex) => {
468
- const poolData = data.returnData.slice(
469
- poolIndex * 3,
470
- (poolIndex + 1) * 3,
471
- );
472
- const [reserves0, reserves1, vReserves0, vReserves1] = coder
473
- .decode(['uint256', 'uint256', 'uint256', 'uint256'], poolData[0])
474
- .map(n => BigInt(n.toString()));
475
- const [shortEMA, longEMA, lastBlockVolume, lastTradeBlock] = coder
476
- .decode(['uint256', 'uint256', 'uint128', 'uint256'], poolData[1])
477
- .map(n => BigInt(n.toString()));
478
- const ampBps = BigInt(
479
- coder.decode(['uint256'], poolData[2]).toString(),
480
- );
481
- acc[poolAddress] = {
482
- reserves: {
483
- reserves0,
484
- reserves1,
485
- vReserves0,
486
- vReserves1,
487
- },
488
- trendData: {
489
- shortEMA,
490
- longEMA,
491
- lastBlockVolume,
492
- lastTradeBlock,
493
- },
494
- ampBps,
495
- };
496
- return acc;
497
- },
498
- {},
499
- );
500
- } catch (e) {
501
- this.logger.error(
502
- `${this.dexKey}_getManyPoolReserves could not get reserves`,
503
- e,
504
- );
505
- return {};
506
- }
507
- }
508
-
509
- private async catchUpPair(from: Token, to: Token, blockNumber: number) {
510
- if (!blockNumber) return;
511
-
512
- const pair = await this.findPair(from, to);
513
-
514
- if (!pair || !pair.exchanges.length) return;
515
- if (
516
- Object.keys(pair.pools).length &&
517
- !Object.values(pair.pools).find(pool => !pool.getState(blockNumber))
518
- )
519
- return;
520
-
521
- let poolsState = await this.getManyPoolReserves(pair, blockNumber);
522
-
523
- if (!Object.keys(poolsState).length) {
524
- this.logger.error(
525
- `${this.dexKey}_getManyPoolReserves didn't get any pool reserves`,
526
- );
527
- return;
528
- }
529
-
530
- // Filter out pools
531
- if (pair.exchanges.length > MAX_TRACKED_PAIR_POOLS) {
532
- poolsState = Object.fromEntries(
533
- Object.entries(poolsState)
534
- .sort(([, stateA], [, stateB]) =>
535
- stateA.reserves.reserves0 < stateB.reserves.reserves0 ? 1 : -1,
536
- )
537
- .slice(0, MAX_TRACKED_PAIR_POOLS),
538
- );
539
- pair.exchanges = pair.exchanges.filter(pool => poolsState[pool]);
540
- }
541
-
542
- await Promise.all(
543
- Object.entries(poolsState).map(async ([poolAddress, state]) => {
544
- if (!pair.pools[poolAddress]) {
545
- await this.addPool(pair, poolAddress, state, blockNumber);
546
- } else pair.pools[poolAddress].setState(state, blockNumber);
547
- }),
548
- );
549
- }
550
-
551
- private async getPairOrderedParams(
552
- from: Token,
553
- to: Token,
554
- blockNumber: number,
555
- ): Promise<KyberDmmPoolOrderedParams | null> {
556
- const pair = await this.findPair(from, to);
557
- if (!(pair && Object.keys(pair.pools).length && pair.exchanges.length))
558
- return null;
559
-
560
- const pairState = Object.entries(pair.pools)
561
- .map(([poolAddress, pool]) => ({
562
- poolAddress,
563
- state: pool.getState(blockNumber) as KyberDmmPoolState,
564
- ampBps: pool.ampBps,
565
- }))
566
- .filter(s => s.state);
567
-
568
- if (!pairState.length) {
569
- this.logger.error(
570
- `${this.dexKey}_orderPairParams expected reserves, got none (maybe the pool doesn't exist)`,
571
- from.symbol || from.address,
572
- to.symbol || to.address,
573
- );
574
- return null;
575
- }
576
- const pairReversed =
577
- pair.token1.address.toLowerCase() === from.address.toLowerCase();
578
-
579
- return {
580
- tokenIn: from.address,
581
- tokenOut: to.address,
582
- poolData: pairState,
583
- exchanges: pair.exchanges,
584
- direction: !pairReversed,
585
- };
586
- }
587
-
588
- private async findPair(from: Token, to: Token) {
589
- if (from.address.toLowerCase() === to.address.toLowerCase()) return null;
590
- const [token0, token1] =
591
- from.address.toLowerCase() < to.address.toLowerCase()
592
- ? [from, to]
593
- : [to, from];
594
-
595
- const key = `${token0.address.toLowerCase()}-${token1.address.toLowerCase()}`;
596
- let pair = this.pairs[key];
597
- if (pair) return pair;
598
- const exchanges = await this.factory.methods
599
- .getPools(token0.address, token1.address)
600
- .call();
601
- if (!exchanges || !exchanges.length) {
602
- pair = { token0, token1, exchanges: [], pools: {} };
603
- } else {
604
- pair = { token0, token1, exchanges, pools: {} };
605
- }
606
- this.pairs[key] = pair;
607
- return pair;
608
- }
609
-
610
- private async getBuyPrice(priceParams: TradeInfo, amountOut: bigint) {
611
- const {
612
- reserves0: reserveIn,
613
- reserves1: reserveOut,
614
- vReserves0: vReserveIn,
615
- vReserves1: vReserveOut,
616
- feeInPrecision,
617
- } = priceParams;
618
- if (amountOut <= 0) return 0;
619
- if (reserveIn <= 0n || reserveOut <= amountOut) return 0;
620
-
621
- let numerator = vReserveIn * amountOut;
622
- let denominator = vReserveOut - amountOut;
623
- const amountIn = numerator / denominator + 1n;
624
- // amountIn = floor(amountIN *PRECISION / (PRECISION - feeInPrecision));
625
- numerator = amountIn * PRECISION;
626
- denominator = PRECISION - feeInPrecision;
627
- return (numerator + denominator - 1n) / denominator;
628
- }
629
-
630
- private async getSellPrice(priceParams: TradeInfo, amountIn: bigint) {
631
- const {
632
- reserves0: reserveIn,
633
- reserves1: reserveOut,
634
- vReserves0: vReserveIn,
635
- vReserves1: vReserveOut,
636
- feeInPrecision,
637
- } = priceParams;
638
- if (amountIn <= 0) return 0;
639
- if (reserveIn <= 0 || reserveOut <= 0) return 0;
640
-
641
- const amountInWithFee =
642
- (amountIn * (PRECISION - feeInPrecision)) / PRECISION;
643
- const numerator = amountInWithFee * vReserveOut;
644
- const denominator = vReserveIn + amountInWithFee;
645
- const amountOut = numerator / denominator;
646
- if (reserveOut <= amountOut) return 0;
647
- return amountOut;
648
- }
649
- }
1
+ import { Interface, AbiCoder } from '@ethersproject/abi';
2
+ import { SimpleExchange } from '../simple-exchange';
3
+ import { IDex } from '../idex';
4
+ import _ from 'lodash';
5
+ import { Network, SUBGRAPH_TIMEOUT, SwapSide } from '../../constants';
6
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
7
+ import { PRECISION } from './fee-formula';
8
+ import {
9
+ getTradeInfo,
10
+ KyberDmmPair,
11
+ KyberDmmPool,
12
+ KyberDmmPoolOrderedParams,
13
+ KyberDmmPoolState,
14
+ } from './pool';
15
+ import {
16
+ AdapterExchangeParam,
17
+ ExchangePrices,
18
+ PoolPrices,
19
+ PoolLiquidity,
20
+ SimpleExchangeParam,
21
+ Token,
22
+ NumberAsString,
23
+ Address,
24
+ DexExchangeParam,
25
+ } from '../../types';
26
+ import {
27
+ KyberDmmData,
28
+ KyberDMMFunctions,
29
+ KyberDmmParam,
30
+ TradeInfo,
31
+ } from './types';
32
+ import { IDexHelper } from '../../dex-helper';
33
+ import { Adapters, KyberDmmConfig } from './config';
34
+ import { Logger } from 'log4js';
35
+ import { Contract } from 'web3-eth-contract';
36
+
37
+ import kyberDmmFactoryABI from '../../abi/kyberdmm/kyber-dmm-factory.abi.json';
38
+ import kyberDmmPoolABI from '../../abi/kyberdmm/kyber-dmm-pool.abi.json';
39
+ import KyberDmmExchangeRouterABI from '../../abi/kyberdmm/kyber-dmm-exchange-router.abi.json';
40
+ import { getBigIntPow, getDexKeysWithNetwork } from '../../utils';
41
+ import { extractReturnAmountPosition } from '../../executor/utils';
42
+
43
+ const MAX_TRACKED_PAIR_POOLS = 3;
44
+
45
+ const iface = new Interface(kyberDmmPoolABI);
46
+ const coder = new AbiCoder();
47
+
48
+ export class KyberDmm
49
+ extends SimpleExchange
50
+ implements IDex<KyberDmmData, KyberDmmParam>
51
+ {
52
+ pairs: { [key: string]: KyberDmmPair } = {};
53
+ needWrapNative = true;
54
+ factory: Contract;
55
+ logger: Logger;
56
+
57
+ exchangeRouterInterface: Interface;
58
+
59
+ readonly hasConstantPriceLargeAmounts = false;
60
+ readonly isFeeOnTransferSupported = false;
61
+
62
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
63
+ getDexKeysWithNetwork(KyberDmmConfig);
64
+
65
+ constructor(
66
+ protected network: Network,
67
+ dexKey: string,
68
+ protected dexHelper: IDexHelper,
69
+ protected config = KyberDmmConfig[dexKey][network],
70
+ protected adapters = Adapters[network],
71
+ ) {
72
+ super(dexHelper, dexKey);
73
+
74
+ this.logger = dexHelper.getLogger(dexKey);
75
+
76
+ this.factory = new this.dexHelper.web3Provider.eth.Contract(
77
+ kyberDmmFactoryABI as any,
78
+ config.factoryAddress,
79
+ );
80
+
81
+ this.exchangeRouterInterface = new Interface(KyberDmmExchangeRouterABI);
82
+ }
83
+
84
+ async getPoolIdentifiers(
85
+ from: Token,
86
+ to: Token,
87
+ side: SwapSide,
88
+ blockNumber: number,
89
+ ): Promise<string[]> {
90
+ from = this.dexHelper.config.wrapETH(from);
91
+ to = this.dexHelper.config.wrapETH(to);
92
+
93
+ const pair = await this.findPair(from, to);
94
+
95
+ if (pair && pair.exchanges.length > 0) {
96
+ const z = pair.exchanges.map(poolAddress => {
97
+ return `${this.dexKey}_${poolAddress.toLowerCase()}`;
98
+ });
99
+
100
+ return z;
101
+ } else return [];
102
+ }
103
+
104
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
105
+ if (side === SwapSide.BUY) return null;
106
+ return this.adapters;
107
+ }
108
+
109
+ async getTopPoolsForToken(
110
+ tokenAddress: string,
111
+ count: number,
112
+ ): Promise<PoolLiquidity[]> {
113
+ if (!this.config.subgraphURL) return [];
114
+
115
+ const query = `
116
+ query ($token: Bytes!, $count: Int) {
117
+ pools0: pairs(first: $count, orderBy: reserveUSD, orderDirection: desc, where: {token0: $token}) {
118
+ id
119
+ reserveUSD
120
+ token0{
121
+ id
122
+ decimals
123
+ }
124
+ token1{
125
+ id
126
+ decimals
127
+ }
128
+ }
129
+ pools1: pairs(first: $count, orderBy: reserveUSD, orderDirection: desc, where: {token1: $token}) {
130
+ id
131
+ reserveUSD
132
+ token1{
133
+ id
134
+ decimals
135
+ }
136
+ token0{
137
+ id
138
+ decimals
139
+ }
140
+ }
141
+ }
142
+ `;
143
+
144
+ const { data } = await this.dexHelper.httpRequest.post(
145
+ this.config.subgraphURL,
146
+ {
147
+ query,
148
+ variables: { token: tokenAddress.toLowerCase(), count },
149
+ },
150
+ SUBGRAPH_TIMEOUT,
151
+ );
152
+
153
+ if (!(data && data.pools0 && data.pools1))
154
+ throw new Error(
155
+ `Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`,
156
+ );
157
+
158
+ const pools = _.map(_.concat(data.pools0, data.pools1), pool => ({
159
+ exchange: this.dexKey,
160
+ address: pool.id.toLowerCase(),
161
+ connectorTokens: [pool.token0, pool.token1].reduce(
162
+ (acc, { decimals, id }) => {
163
+ if (id.toLowerCase() != tokenAddress.toLowerCase())
164
+ acc.push({
165
+ decimals: parseInt(decimals),
166
+ address: id.toLowerCase(),
167
+ });
168
+ return acc;
169
+ },
170
+ [],
171
+ ),
172
+ liquidityUSD: parseFloat(pool.reserveUSD),
173
+ }));
174
+
175
+ return _.slice(_.sortBy(pools, [pool => -1 * pool.liquidityUSD]), 0, count);
176
+ }
177
+
178
+ getAdapterParam(
179
+ srcToken: string,
180
+ destToken: string,
181
+ srcAmount: string,
182
+ destAmount: string,
183
+ data: KyberDmmData,
184
+ side: SwapSide,
185
+ ): AdapterExchangeParam {
186
+ const payload = this.abiCoder.encodeParameter(
187
+ {
188
+ ParentStruct: {
189
+ poolPath: 'address[]',
190
+ path: 'address[]',
191
+ },
192
+ },
193
+ { poolPath: data.pools.map(p => p.address), path: data.path },
194
+ );
195
+ return {
196
+ targetExchange: data.router,
197
+ payload,
198
+ networkFee: '0',
199
+ };
200
+ }
201
+
202
+ async getSimpleParam(
203
+ srcToken: string,
204
+ destToken: string,
205
+ srcAmount: string,
206
+ destAmount: string,
207
+ data: KyberDmmData,
208
+ side: SwapSide,
209
+ ): Promise<SimpleExchangeParam> {
210
+ const isSell = side === SwapSide.SELL;
211
+ const swapFunctionParams: KyberDmmParam = [
212
+ isSell ? srcAmount : destAmount,
213
+ isSell ? destAmount : srcAmount,
214
+ data.pools.map(p => p.address),
215
+ data.path,
216
+ this.augustusAddress,
217
+ Number.MAX_SAFE_INTEGER.toString(),
218
+ ];
219
+ const swapData = this.exchangeRouterInterface.encodeFunctionData(
220
+ isSell
221
+ ? KyberDMMFunctions.swapExactTokensForTokens
222
+ : KyberDMMFunctions.swapTokensForExactTokens,
223
+ swapFunctionParams,
224
+ );
225
+
226
+ return this.buildSimpleParamWithoutWETHConversion(
227
+ srcToken,
228
+ srcAmount,
229
+ destToken,
230
+ destAmount,
231
+ swapData,
232
+ data.router,
233
+ );
234
+ }
235
+
236
+ getDexParam(
237
+ srcToken: Address,
238
+ destToken: Address,
239
+ srcAmount: NumberAsString,
240
+ destAmount: NumberAsString,
241
+ recipient: Address,
242
+ data: KyberDmmData,
243
+ side: SwapSide,
244
+ ): DexExchangeParam {
245
+ const isSell = side === SwapSide.SELL;
246
+ const swapFunctionParams: KyberDmmParam = [
247
+ isSell ? srcAmount : destAmount,
248
+ isSell ? destAmount : srcAmount,
249
+ data.pools.map(p => p.address),
250
+ data.path,
251
+ recipient,
252
+ Number.MAX_SAFE_INTEGER.toString(),
253
+ ];
254
+ const exchangeData = this.exchangeRouterInterface.encodeFunctionData(
255
+ isSell
256
+ ? KyberDMMFunctions.swapExactTokensForTokens
257
+ : KyberDMMFunctions.swapTokensForExactTokens,
258
+ swapFunctionParams,
259
+ );
260
+
261
+ return {
262
+ needWrapNative: this.needWrapNative,
263
+ dexFuncHasRecipient: true,
264
+ exchangeData,
265
+ targetExchange: data.router,
266
+ returnAmountPos:
267
+ side === SwapSide.SELL
268
+ ? extractReturnAmountPosition(
269
+ this.exchangeRouterInterface,
270
+ KyberDMMFunctions.swapExactTokensForTokens,
271
+ 'amounts',
272
+ data.path.length - 1, // last element is amount out
273
+ )
274
+ : undefined,
275
+ };
276
+ }
277
+
278
+ private async addPool(
279
+ pair: KyberDmmPair,
280
+ poolAddress: string,
281
+ poolData: KyberDmmPoolState,
282
+ blockNumber: number,
283
+ ) {
284
+ if (
285
+ pair.exchanges.find(p => p === poolAddress) &&
286
+ !(poolAddress in pair.pools)
287
+ ) {
288
+ const pool = new KyberDmmPool(
289
+ this.dexKey,
290
+ this.dexHelper,
291
+ poolAddress,
292
+ pair.token0,
293
+ pair.token1,
294
+ poolData.ampBps,
295
+ this.logger,
296
+ );
297
+ pair.pools[poolAddress] = pool;
298
+ pool.addressesSubscribed.push(poolAddress);
299
+ await pool.initialize(blockNumber, {
300
+ state: poolData,
301
+ });
302
+ }
303
+ }
304
+
305
+ async getPricesVolume(
306
+ from: Token,
307
+ to: Token,
308
+ amounts: bigint[],
309
+ side: SwapSide,
310
+ blockNumber: number,
311
+ limitPools?: string[],
312
+ ): Promise<ExchangePrices<KyberDmmData> | null> {
313
+ try {
314
+ if (!this.factory) {
315
+ return null;
316
+ }
317
+
318
+ from = this.dexHelper.config.wrapETH(from);
319
+ to = this.dexHelper.config.wrapETH(to);
320
+
321
+ if (from.address.toLowerCase() === to.address.toLowerCase()) {
322
+ return null;
323
+ }
324
+
325
+ await this.catchUpPair(from, to, blockNumber);
326
+ const pairParam = await this.getPairOrderedParams(from, to, blockNumber);
327
+
328
+ if (!pairParam) return null;
329
+
330
+ pairParam.poolData = pairParam.poolData.filter(pool => {
331
+ const poolIdentifier = `${
332
+ this.dexKey
333
+ }_${pool.poolAddress.toLowerCase()}`;
334
+ return !limitPools || limitPools.includes(poolIdentifier);
335
+ });
336
+
337
+ if (!pairParam.poolData.length) return null;
338
+
339
+ return Promise.all(
340
+ pairParam.poolData.map(pool => {
341
+ return this.getPoolPrice(
342
+ from,
343
+ to,
344
+ side,
345
+ amounts,
346
+ pool,
347
+ pairParam.direction,
348
+ `${this.dexKey}_${pool.poolAddress.toLowerCase()}`,
349
+ blockNumber,
350
+ );
351
+ }),
352
+ );
353
+ } catch (e) {
354
+ if (blockNumber === 0)
355
+ this.logger.error(
356
+ `${this.dexKey}_getPricesVolume: Aurelius block manager not yet instantiated`,
357
+ );
358
+ this.logger.error(`${this.dexKey}_getPrices`, e);
359
+ return null;
360
+ }
361
+ }
362
+
363
+ // Returns estimated gas cost of calldata for this DEX in multiSwap
364
+ getCalldataGasCost(poolPrices: PoolPrices<KyberDmmData>): number | number[] {
365
+ return (
366
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
367
+ CALLDATA_GAS_COST.LENGTH_LARGE +
368
+ CALLDATA_GAS_COST.OFFSET_SMALL +
369
+ CALLDATA_GAS_COST.OFFSET_SMALL +
370
+ CALLDATA_GAS_COST.OFFSET_SMALL +
371
+ CALLDATA_GAS_COST.LENGTH_SMALL +
372
+ CALLDATA_GAS_COST.ADDRESS +
373
+ CALLDATA_GAS_COST.LENGTH_SMALL +
374
+ CALLDATA_GAS_COST.ADDRESS * 2
375
+ );
376
+ }
377
+
378
+ private async getPoolPrice(
379
+ from: Token,
380
+ to: Token,
381
+ side: SwapSide,
382
+ amounts: bigint[],
383
+ pool: { poolAddress: string; state: KyberDmmPoolState },
384
+ direction: boolean,
385
+ poolIdentifier: string,
386
+ blockNumber: number,
387
+ ): Promise<any> {
388
+ // const [tokenA] = [
389
+ // from.address.toLowerCase(),
390
+ // to.address.toLowerCase(),
391
+ // ].sort((a, b) => (a > b ? 1 : -1));
392
+
393
+ const unitAmount = getBigIntPow(
394
+ side == SwapSide.BUY ? to.decimals : from.decimals,
395
+ ).toString();
396
+
397
+ const tradeInfo = getTradeInfo(pool.state, blockNumber, direction);
398
+
399
+ const unit =
400
+ side == SwapSide.BUY
401
+ ? await this.getBuyPrice(tradeInfo, BigInt(unitAmount))
402
+ : await this.getSellPrice(tradeInfo, BigInt(unitAmount));
403
+
404
+ const prices =
405
+ side == SwapSide.BUY
406
+ ? await Promise.all(
407
+ amounts.map(amount =>
408
+ this.getBuyPrice(tradeInfo, BigInt(amount.toString())),
409
+ ),
410
+ )
411
+ : await Promise.all(
412
+ amounts.map(amount =>
413
+ this.getSellPrice(tradeInfo, BigInt(amount.toString())),
414
+ ),
415
+ );
416
+
417
+ return {
418
+ prices: prices.map(p => BigInt(p.toString())),
419
+ unit: BigInt(unit.toString()),
420
+ data: {
421
+ router: this.config.routerAddress,
422
+ path: [from.address.toLowerCase(), to.address.toLowerCase()],
423
+ factory: this.config.factoryAddress,
424
+ pools: [
425
+ {
426
+ address: pool.poolAddress,
427
+ fee: tradeInfo.feeInPrecision.toString(),
428
+ direction,
429
+ },
430
+ ],
431
+ },
432
+ exchange: this.dexKey,
433
+ poolIdentifier,
434
+ gasCost: this.config.poolGasCost,
435
+ poolAddresses: [pool.poolAddress],
436
+ };
437
+ }
438
+
439
+ private async getManyPoolReserves(
440
+ pair: KyberDmmPair,
441
+ blockNumber: number,
442
+ ): Promise<{ [poolAddress: string]: KyberDmmPoolState }> {
443
+ try {
444
+ const calldata = pair.exchanges
445
+ .map(poolAddress => [
446
+ {
447
+ target: poolAddress,
448
+ callData: iface.encodeFunctionData('getTradeInfo', []),
449
+ },
450
+ {
451
+ target: poolAddress,
452
+ callData: iface.encodeFunctionData('getVolumeTrendData', []),
453
+ },
454
+ {
455
+ target: poolAddress,
456
+ callData: iface.encodeFunctionData('ampBps', []),
457
+ },
458
+ ])
459
+ .flat();
460
+
461
+ const data: { returnData: any[] } =
462
+ await this.dexHelper.multiContract.methods
463
+ .aggregate(calldata)
464
+ .call({}, blockNumber);
465
+
466
+ return pair.exchanges.reduce(
467
+ (acc: { [key: string]: KyberDmmPoolState }, poolAddress, poolIndex) => {
468
+ const poolData = data.returnData.slice(
469
+ poolIndex * 3,
470
+ (poolIndex + 1) * 3,
471
+ );
472
+ const [reserves0, reserves1, vReserves0, vReserves1] = coder
473
+ .decode(['uint256', 'uint256', 'uint256', 'uint256'], poolData[0])
474
+ .map(n => BigInt(n.toString()));
475
+ const [shortEMA, longEMA, lastBlockVolume, lastTradeBlock] = coder
476
+ .decode(['uint256', 'uint256', 'uint128', 'uint256'], poolData[1])
477
+ .map(n => BigInt(n.toString()));
478
+ const ampBps = BigInt(
479
+ coder.decode(['uint256'], poolData[2]).toString(),
480
+ );
481
+ acc[poolAddress] = {
482
+ reserves: {
483
+ reserves0,
484
+ reserves1,
485
+ vReserves0,
486
+ vReserves1,
487
+ },
488
+ trendData: {
489
+ shortEMA,
490
+ longEMA,
491
+ lastBlockVolume,
492
+ lastTradeBlock,
493
+ },
494
+ ampBps,
495
+ };
496
+ return acc;
497
+ },
498
+ {},
499
+ );
500
+ } catch (e) {
501
+ this.logger.error(
502
+ `${this.dexKey}_getManyPoolReserves could not get reserves`,
503
+ e,
504
+ );
505
+ return {};
506
+ }
507
+ }
508
+
509
+ private async catchUpPair(from: Token, to: Token, blockNumber: number) {
510
+ if (!blockNumber) return;
511
+
512
+ const pair = await this.findPair(from, to);
513
+
514
+ if (!pair || !pair.exchanges.length) return;
515
+ if (
516
+ Object.keys(pair.pools).length &&
517
+ !Object.values(pair.pools).find(pool => !pool.getState(blockNumber))
518
+ )
519
+ return;
520
+
521
+ let poolsState = await this.getManyPoolReserves(pair, blockNumber);
522
+
523
+ if (!Object.keys(poolsState).length) {
524
+ this.logger.error(
525
+ `${this.dexKey}_getManyPoolReserves didn't get any pool reserves`,
526
+ );
527
+ return;
528
+ }
529
+
530
+ // Filter out pools
531
+ if (pair.exchanges.length > MAX_TRACKED_PAIR_POOLS) {
532
+ poolsState = Object.fromEntries(
533
+ Object.entries(poolsState)
534
+ .sort(([, stateA], [, stateB]) =>
535
+ stateA.reserves.reserves0 < stateB.reserves.reserves0 ? 1 : -1,
536
+ )
537
+ .slice(0, MAX_TRACKED_PAIR_POOLS),
538
+ );
539
+ pair.exchanges = pair.exchanges.filter(pool => poolsState[pool]);
540
+ }
541
+
542
+ await Promise.all(
543
+ Object.entries(poolsState).map(async ([poolAddress, state]) => {
544
+ if (!pair.pools[poolAddress]) {
545
+ await this.addPool(pair, poolAddress, state, blockNumber);
546
+ } else pair.pools[poolAddress].setState(state, blockNumber);
547
+ }),
548
+ );
549
+ }
550
+
551
+ private async getPairOrderedParams(
552
+ from: Token,
553
+ to: Token,
554
+ blockNumber: number,
555
+ ): Promise<KyberDmmPoolOrderedParams | null> {
556
+ const pair = await this.findPair(from, to);
557
+ if (!(pair && Object.keys(pair.pools).length && pair.exchanges.length))
558
+ return null;
559
+
560
+ const pairState = Object.entries(pair.pools)
561
+ .map(([poolAddress, pool]) => ({
562
+ poolAddress,
563
+ state: pool.getState(blockNumber) as KyberDmmPoolState,
564
+ ampBps: pool.ampBps,
565
+ }))
566
+ .filter(s => s.state);
567
+
568
+ if (!pairState.length) {
569
+ this.logger.error(
570
+ `${this.dexKey}_orderPairParams expected reserves, got none (maybe the pool doesn't exist)`,
571
+ from.symbol || from.address,
572
+ to.symbol || to.address,
573
+ );
574
+ return null;
575
+ }
576
+ const pairReversed =
577
+ pair.token1.address.toLowerCase() === from.address.toLowerCase();
578
+
579
+ return {
580
+ tokenIn: from.address,
581
+ tokenOut: to.address,
582
+ poolData: pairState,
583
+ exchanges: pair.exchanges,
584
+ direction: !pairReversed,
585
+ };
586
+ }
587
+
588
+ private async findPair(from: Token, to: Token) {
589
+ if (from.address.toLowerCase() === to.address.toLowerCase()) return null;
590
+ const [token0, token1] =
591
+ from.address.toLowerCase() < to.address.toLowerCase()
592
+ ? [from, to]
593
+ : [to, from];
594
+
595
+ const key = `${token0.address.toLowerCase()}-${token1.address.toLowerCase()}`;
596
+ let pair = this.pairs[key];
597
+ if (pair) return pair;
598
+ const exchanges = await this.factory.methods
599
+ .getPools(token0.address, token1.address)
600
+ .call();
601
+ if (!exchanges || !exchanges.length) {
602
+ pair = { token0, token1, exchanges: [], pools: {} };
603
+ } else {
604
+ pair = { token0, token1, exchanges, pools: {} };
605
+ }
606
+ this.pairs[key] = pair;
607
+ return pair;
608
+ }
609
+
610
+ private async getBuyPrice(priceParams: TradeInfo, amountOut: bigint) {
611
+ const {
612
+ reserves0: reserveIn,
613
+ reserves1: reserveOut,
614
+ vReserves0: vReserveIn,
615
+ vReserves1: vReserveOut,
616
+ feeInPrecision,
617
+ } = priceParams;
618
+ if (amountOut <= 0) return 0;
619
+ if (reserveIn <= 0n || reserveOut <= amountOut) return 0;
620
+
621
+ let numerator = vReserveIn * amountOut;
622
+ let denominator = vReserveOut - amountOut;
623
+ const amountIn = numerator / denominator + 1n;
624
+ // amountIn = floor(amountIN *PRECISION / (PRECISION - feeInPrecision));
625
+ numerator = amountIn * PRECISION;
626
+ denominator = PRECISION - feeInPrecision;
627
+ return (numerator + denominator - 1n) / denominator;
628
+ }
629
+
630
+ private async getSellPrice(priceParams: TradeInfo, amountIn: bigint) {
631
+ const {
632
+ reserves0: reserveIn,
633
+ reserves1: reserveOut,
634
+ vReserves0: vReserveIn,
635
+ vReserves1: vReserveOut,
636
+ feeInPrecision,
637
+ } = priceParams;
638
+ if (amountIn <= 0) return 0;
639
+ if (reserveIn <= 0 || reserveOut <= 0) return 0;
640
+
641
+ const amountInWithFee =
642
+ (amountIn * (PRECISION - feeInPrecision)) / PRECISION;
643
+ const numerator = amountInWithFee * vReserveOut;
644
+ const denominator = vReserveIn + amountInWithFee;
645
+ const amountOut = numerator / denominator;
646
+ if (reserveOut <= amountOut) return 0;
647
+ return amountOut;
648
+ }
649
+ }