@paraswap/dex-lib 2.24.0 → 2.24.1-algebra-event-based-quickswapv3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/build/constants.d.ts +1 -0
  2. package/build/constants.js +1 -0
  3. package/build/constants.js.map +1 -1
  4. package/build/dex/index.js +2 -0
  5. package/build/dex/index.js.map +1 -1
  6. package/build/dex/pancakeswap-v3/pancakeswap-v3-pool.d.ts +0 -2
  7. package/build/dex/pancakeswap-v3/pancakeswap-v3-pool.js +3 -23
  8. package/build/dex/pancakeswap-v3/pancakeswap-v3-pool.js.map +1 -1
  9. package/build/dex/quickswap/config.js +1 -8
  10. package/build/dex/quickswap/config.js.map +1 -1
  11. package/build/dex/quickswap/quickswap-v3.js +2 -1
  12. package/build/dex/quickswap/quickswap-v3.js.map +1 -1
  13. package/build/dex/uniswap-v3/config.js +18 -1
  14. package/build/dex/uniswap-v3/config.js.map +1 -1
  15. package/build/dex/uniswap-v3/contract-math/Tick.d.ts +2 -2
  16. package/build/dex/uniswap-v3/contract-math/Tick.js.map +1 -1
  17. package/build/dex/uniswap-v3/contract-math/TickBitMap.d.ts +2 -2
  18. package/build/dex/uniswap-v3/contract-math/TickBitMap.js.map +1 -1
  19. package/build/dex/uniswap-v3/contract-math/uniswap-v3-math.d.ts +19 -0
  20. package/build/dex/uniswap-v3/contract-math/uniswap-v3-math.js +2 -1
  21. package/build/dex/uniswap-v3/contract-math/uniswap-v3-math.js.map +1 -1
  22. package/build/dex/uniswap-v3/contract-math/utils.d.ts +4 -0
  23. package/build/dex/uniswap-v3/contract-math/utils.js +25 -1
  24. package/build/dex/uniswap-v3/contract-math/utils.js.map +1 -1
  25. package/build/dex/uniswap-v3/uniswap-v3-pool.d.ts +0 -2
  26. package/build/dex/uniswap-v3/uniswap-v3-pool.js +3 -23
  27. package/build/dex/uniswap-v3/uniswap-v3-pool.js.map +1 -1
  28. package/build/dex/uniswap-v3/uniswap-v3.js +5 -3
  29. package/build/dex/uniswap-v3/uniswap-v3.js.map +1 -1
  30. package/build/dex/weth/config.js +3 -0
  31. package/build/dex/weth/config.js.map +1 -1
  32. package/build/utils.d.ts +10 -0
  33. package/build/utils.js +15 -1
  34. package/build/utils.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/abi/algebra/AlgebraPool.abi.json +727 -0
  37. package/src/abi/algebra/AlgebraQuoter.abi.json +138 -0
  38. package/src/abi/algebra/AlgebraStateMulticall.abi.json +801 -0
  39. package/src/constants.ts +1 -0
  40. package/src/dex/algebra/algebra-e2e.test.ts +158 -0
  41. package/src/dex/algebra/algebra-events.test.ts +120 -0
  42. package/src/dex/algebra/algebra-integration.test.ts +257 -0
  43. package/src/dex/algebra/algebra-pool.ts +454 -0
  44. package/src/dex/algebra/algebra.ts +709 -0
  45. package/src/dex/algebra/config.ts +45 -0
  46. package/src/dex/algebra/lib/AlgebraMath.ts +676 -0
  47. package/src/dex/algebra/lib/Constants.ts +5 -0
  48. package/src/dex/algebra/types.ts +82 -0
  49. package/src/dex/algebra/utils.ts +68 -0
  50. package/src/dex/index.ts +2 -0
  51. package/src/dex/pancakeswap-v3/pancakeswap-v3-pool.ts +6 -41
  52. package/src/dex/quickswap/config.ts +1 -9
  53. package/src/dex/quickswap/quickswap-v3.ts +2 -1
  54. package/src/dex/uniswap-v3/config.ts +19 -1
  55. package/src/dex/uniswap-v3/contract-math/Tick.ts +2 -2
  56. package/src/dex/uniswap-v3/contract-math/TickBitMap.ts +6 -2
  57. package/src/dex/uniswap-v3/contract-math/uniswap-v3-math.ts +3 -3
  58. package/src/dex/uniswap-v3/contract-math/utils.ts +42 -0
  59. package/src/dex/uniswap-v3/uniswap-v3-e2e.test.ts +35 -11
  60. package/src/dex/uniswap-v3/uniswap-v3-pool.ts +3 -41
  61. package/src/dex/uniswap-v3/uniswap-v3.ts +9 -3
  62. package/src/dex/weth/config.ts +3 -0
  63. package/src/utils.ts +17 -0
  64. package/build/abi/uniswap-v3/pancakeswap-v3/PancakeswapV3QuoterV2.abi.json +0 -285
  65. package/build/abi/uniswap-v3/pancakeswap-v3/PancakeswapV3Router.abi.json +0 -583
  66. package/build/abi/woo-fi/WooFeeManager.abi.json +0 -318
  67. package/build/abi/woo-fi/WooPP.abi.json +0 -548
  68. package/build/abi/woo-fi/Wooracle.abi.json +0 -260
  69. package/build/dex/algebra/lib/AlgebraXUniV3.d.ts +0 -5
  70. package/build/dex/algebra/lib/AlgebraXUniV3.js +0 -45
  71. package/build/dex/algebra/lib/AlgebraXUniV3.js.map +0 -1
  72. package/build/dex/algebra/lib/DataStorage.d.ts +0 -19
  73. package/build/dex/algebra/lib/DataStorage.js +0 -466
  74. package/build/dex/algebra/lib/DataStorage.js.map +0 -1
  75. package/build/dex/algebra/lib/DataStorageOperator.d.ts +0 -10
  76. package/build/dex/algebra/lib/DataStorageOperator.js +0 -93
  77. package/build/dex/algebra/lib/DataStorageOperator.js.map +0 -1
  78. package/build/dex/algebra/lib/Sqrt.d.ts +0 -3
  79. package/build/dex/algebra/lib/Sqrt.js +0 -60
  80. package/build/dex/algebra/lib/Sqrt.js.map +0 -1
  81. package/build/dex/algebra/lib/TickManager.d.ts +0 -10
  82. package/build/dex/algebra/lib/TickManager.js +0 -3
  83. package/build/dex/algebra/lib/TickManager.js.map +0 -1
  84. package/build/dex/balancer-v2/LinearMath.d.ts +0 -19
  85. package/build/dex/balancer-v2/LinearMath.js +0 -179
  86. package/build/dex/balancer-v2/LinearMath.js.map +0 -1
  87. package/build/dex/balancer-v2/LinearPool.d.ts +0 -47
  88. package/build/dex/balancer-v2/LinearPool.js +0 -324
  89. package/build/dex/balancer-v2/LinearPool.js.map +0 -1
  90. package/build/dex/balancer-v2/PhantomStablePool.d.ts +0 -47
  91. package/build/dex/balancer-v2/PhantomStablePool.js +0 -294
  92. package/build/dex/balancer-v2/PhantomStablePool.js.map +0 -1
  93. package/build/dex/balancer-v2/StableMath.d.ts +0 -9
  94. package/build/dex/balancer-v2/StableMath.js +0 -272
  95. package/build/dex/balancer-v2/StableMath.js.map +0 -1
  96. package/build/dex/balancer-v2/balancer-v2-pool.d.ts +0 -75
  97. package/build/dex/balancer-v2/balancer-v2-pool.js +0 -417
  98. package/build/dex/balancer-v2/balancer-v2-pool.js.map +0 -1
  99. package/build/dex/quickswap-v3.d.ts +0 -21
  100. package/build/dex/quickswap-v3.js +0 -40
  101. package/build/dex/quickswap-v3.js.map +0 -1
  102. package/build/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.d.ts +0 -12
  103. package/build/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.js +0 -23
  104. package/build/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.js.map +0 -1
  105. package/build/dex/woo-fi/config.d.ts +0 -4
  106. package/build/dex/woo-fi/config.js +0 -141
  107. package/build/dex/woo-fi/config.js.map +0 -1
  108. package/build/dex/woo-fi/constants.d.ts +0 -5
  109. package/build/dex/woo-fi/constants.js +0 -20
  110. package/build/dex/woo-fi/constants.js.map +0 -1
  111. package/build/dex/woo-fi/types.d.ts +0 -48
  112. package/build/dex/woo-fi/types.js +0 -3
  113. package/build/dex/woo-fi/types.js.map +0 -1
  114. package/build/dex/woo-fi/woo-fi-decimal-math.d.ts +0 -14
  115. package/build/dex/woo-fi/woo-fi-decimal-math.js +0 -42
  116. package/build/dex/woo-fi/woo-fi-decimal-math.js.map +0 -1
  117. package/build/dex/woo-fi/woo-fi-math.d.ts +0 -31
  118. package/build/dex/woo-fi/woo-fi-math.js +0 -300
  119. package/build/dex/woo-fi/woo-fi-math.js.map +0 -1
  120. package/build/dex/woo-fi/woo-fi.d.ts +0 -65
  121. package/build/dex/woo-fi/woo-fi.js +0 -480
  122. package/build/dex/woo-fi/woo-fi.js.map +0 -1
@@ -0,0 +1,709 @@
1
+ import { DeepReadonly } from 'ts-essentials';
2
+ import { AbiItem } from 'web3-utils';
3
+ import { pack } from '@ethersproject/solidity';
4
+ import _ from 'lodash';
5
+ import {
6
+ Token,
7
+ Address,
8
+ ExchangePrices,
9
+ PoolPrices,
10
+ AdapterExchangeParam,
11
+ SimpleExchangeParam,
12
+ PoolLiquidity,
13
+ Logger,
14
+ } from '../../types';
15
+ import { SwapSide, Network, CACHE_PREFIX } from '../../constants';
16
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
17
+ import { getBigIntPow, getDexKeysWithNetwork } from '../../utils';
18
+ import { IDex } from '../../dex/idex';
19
+ import { IDexHelper } from '../../dex-helper/idex-helper';
20
+ import { AlgebraData, DexParams, PoolState } from './types';
21
+ import {
22
+ SimpleExchange,
23
+ getLocalDeadlineAsFriendlyPlaceholder,
24
+ } from '../simple-exchange';
25
+ import { AlgebraConfig, Adapters } from './config';
26
+ import { AlgebraEventPool } from './algebra-pool';
27
+ import { Contract } from 'web3-eth-contract';
28
+ import { Interface } from 'ethers/lib/utils';
29
+ import UniswapV3RouterABI from '../../abi/uniswap-v3/UniswapV3Router.abi.json';
30
+ import AlgebraQuoterABI from '../../abi/algebra/AlgebraQuoter.abi.json';
31
+ import UniswapV3MultiABI from '../../abi/uniswap-v3/UniswapMulti.abi.json';
32
+ import AlgebraStateMulticallABI from '../../abi/algebra/AlgebraStateMulticall.abi.json';
33
+ import {
34
+ OutputResult,
35
+ UniswapV3Functions,
36
+ UniswapV3SimpleSwapParams,
37
+ } from '../uniswap-v3/types';
38
+ import { AlgebraMath } from './lib/AlgebraMath';
39
+
40
+ type PoolPairsInfo = {
41
+ token0: Address;
42
+ token1: Address;
43
+ };
44
+
45
+ const ALGEBRA_CLEAN_NOT_EXISTING_POOL_TTL_MS = 3 * 60 * 60 * 1000; // 3 hours
46
+ const ALGEBRA_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS = 30 * 60 * 1000; // Once in 30 minutes
47
+ const ALGEBRA_EFFICIENCY_FACTOR = 3;
48
+ const ALGEBRA_TICK_GAS_COST = 24_000; // Ceiled
49
+ const ALGEBRA_TICK_BASE_OVERHEAD = 75_000;
50
+ const ALGEBRA_POOL_SEARCH_OVERHEAD = 10_000;
51
+
52
+ export class Algebra extends SimpleExchange implements IDex<AlgebraData> {
53
+ readonly isFeeOnTransferSupported: boolean = false;
54
+ protected eventPools: Record<string, AlgebraEventPool | null> = {};
55
+
56
+ readonly hasConstantPriceLargeAmounts = false;
57
+ readonly needWrapNative = true;
58
+
59
+ intervalTask?: NodeJS.Timeout;
60
+
61
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
62
+ getDexKeysWithNetwork(AlgebraConfig);
63
+
64
+ logger: Logger;
65
+
66
+ private uniswapMulti: Contract;
67
+ private stateMultiContract: Contract;
68
+
69
+ private notExistingPoolSetKey: string;
70
+
71
+ constructor(
72
+ protected network: Network,
73
+ dexKey: string,
74
+ protected dexHelper: IDexHelper,
75
+ protected adapters = Adapters[network] || {},
76
+ readonly routerIface = new Interface(UniswapV3RouterABI), // same abi as uniswapV3
77
+ readonly quoterIface = new Interface(AlgebraQuoterABI),
78
+ protected config = AlgebraConfig[dexKey][network],
79
+ ) {
80
+ super(dexHelper, dexKey);
81
+ this.logger = dexHelper.getLogger(dexKey + '-' + network);
82
+ this.uniswapMulti = new this.dexHelper.web3Provider.eth.Contract(
83
+ UniswapV3MultiABI as AbiItem[],
84
+ this.config.uniswapMulticall,
85
+ );
86
+ this.stateMultiContract = new this.dexHelper.web3Provider.eth.Contract(
87
+ AlgebraStateMulticallABI as AbiItem[],
88
+ this.config.algebraStateMulticall,
89
+ );
90
+
91
+ this.dexHelper.web3Provider.eth.handleRevert = false;
92
+
93
+ this.config = this._toLowerForAllConfigAddresses();
94
+
95
+ this.notExistingPoolSetKey =
96
+ `${CACHE_PREFIX}_${network}_${dexKey}_not_existings_pool_set`.toLowerCase();
97
+ }
98
+
99
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
100
+ return this.adapters[side] ? this.adapters[side] : null;
101
+ }
102
+
103
+ getPoolIdentifier(srcAddress: Address, destAddress: Address) {
104
+ const tokenAddresses = this._sortTokens(srcAddress, destAddress).join('_');
105
+ return `${this.dexKey}_${tokenAddresses}`;
106
+ }
107
+
108
+ async initializePricing(blockNumber: number) {
109
+ if (!this.dexHelper.config.isSlave) {
110
+ const cleanExpiredNotExistingPoolsKeys = async () => {
111
+ const maxTimestamp =
112
+ Date.now() - ALGEBRA_CLEAN_NOT_EXISTING_POOL_TTL_MS;
113
+ await this.dexHelper.cache.zremrangebyscore(
114
+ this.notExistingPoolSetKey,
115
+ 0,
116
+ maxTimestamp,
117
+ );
118
+ };
119
+
120
+ this.intervalTask = setInterval(
121
+ cleanExpiredNotExistingPoolsKeys.bind(this),
122
+ ALGEBRA_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS,
123
+ );
124
+ }
125
+ }
126
+
127
+ async getPool(
128
+ srcAddress: Address,
129
+ destAddress: Address,
130
+ blockNumber: number,
131
+ ): Promise<AlgebraEventPool | null> {
132
+ let pool = this.eventPools[this.getPoolIdentifier(srcAddress, destAddress)];
133
+
134
+ if (pool === undefined) {
135
+ const [token0, token1] = this._sortTokens(srcAddress, destAddress);
136
+
137
+ const key = `${token0}_${token1}`.toLowerCase();
138
+
139
+ const notExistingPoolScore = await this.dexHelper.cache.zscore(
140
+ this.notExistingPoolSetKey,
141
+ key,
142
+ );
143
+
144
+ const poolDoesNotExist = notExistingPoolScore !== null;
145
+
146
+ if (poolDoesNotExist) {
147
+ this.eventPools[this.getPoolIdentifier(srcAddress, destAddress)] = null;
148
+ return null;
149
+ }
150
+
151
+ await this.dexHelper.cache.hset(
152
+ this.dexmapKey,
153
+ key,
154
+ JSON.stringify({
155
+ token0,
156
+ token1,
157
+ }),
158
+ );
159
+
160
+ this.logger.trace(`starting to listen to new pool: ${key}`);
161
+ pool = new AlgebraEventPool(
162
+ this.dexHelper,
163
+ this.dexKey,
164
+ this.stateMultiContract,
165
+ this.erc20Interface,
166
+ this.config.factory,
167
+ token0,
168
+ token1,
169
+ this.logger,
170
+ this.cacheStateKey,
171
+ this.config.initHash,
172
+ this.config.deployer,
173
+ );
174
+
175
+ try {
176
+ await pool.initialize(blockNumber, {
177
+ initCallback: (state: DeepReadonly<PoolState>) => {
178
+ //really hacky, we need to push poolAddress so that we subscribeToLogs in StatefulEventSubscriber
179
+ pool!.addressesSubscribed[0] = state.pool;
180
+ pool!.poolAddress = state.pool;
181
+ },
182
+ });
183
+ } catch (e) {
184
+ if (
185
+ // most zkEVM rpcs fails with "cannot execute unsigned transaction" issue. Prefer to flag pool as non existing instaed of trying to generateState on earch round
186
+ this.network === Network.ZKEVM ||
187
+ (e instanceof Error && e.message.endsWith('Pool does not exist'))
188
+ ) {
189
+ // no need to await we want the set to have the pool key but it's not blocking
190
+ this.dexHelper.cache.zadd(
191
+ this.notExistingPoolSetKey,
192
+ [Date.now(), key],
193
+ 'NX',
194
+ );
195
+
196
+ // Pool does not exist for this pair, so we can set it to null
197
+ // to prevent more requests for this pool
198
+ pool = null;
199
+ this.logger.trace(
200
+ `${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress} not found`,
201
+ e,
202
+ );
203
+ } else {
204
+ // Unexpected Error. Break execution. Do not save the pool in this.eventPools
205
+ this.logger.error(
206
+ `${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress}pool`,
207
+ e,
208
+ );
209
+ throw new Error('Cannot generate pool state');
210
+ }
211
+ }
212
+
213
+ if (pool !== null) {
214
+ const allEventPools = Object.values(this.eventPools);
215
+ this.logger.info(
216
+ `starting to listen to new non-null pool: ${key}. Already following ${allEventPools
217
+ // Not that I like this reduce, but since it is done only on initialization, expect this to be ok
218
+ .reduce(
219
+ (acc, curr) => (curr !== null ? ++acc : acc),
220
+ 0,
221
+ )} non-null pools or ${allEventPools.length} total pools`,
222
+ );
223
+ }
224
+
225
+ this.eventPools[this.getPoolIdentifier(srcAddress, destAddress)] = pool;
226
+ }
227
+ return pool;
228
+ }
229
+
230
+ async addMasterPool(poolKey: string, blockNumber: number): Promise<boolean> {
231
+ const _pairs = await this.dexHelper.cache.hget(this.dexmapKey, poolKey);
232
+ if (!_pairs) {
233
+ this.logger.warn(
234
+ `did not find poolConfig in for key ${this.dexmapKey} ${poolKey}`,
235
+ );
236
+ return false;
237
+ }
238
+
239
+ const poolInfo: PoolPairsInfo = JSON.parse(_pairs);
240
+
241
+ const pool = await this.getPool(
242
+ poolInfo.token0,
243
+ poolInfo.token1,
244
+ blockNumber,
245
+ );
246
+
247
+ if (!pool) {
248
+ return false;
249
+ }
250
+
251
+ return true;
252
+ }
253
+
254
+ async getPoolIdentifiers(
255
+ srcToken: Token,
256
+ destToken: Token,
257
+ side: SwapSide,
258
+ blockNumber: number,
259
+ ): Promise<string[]> {
260
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
261
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
262
+
263
+ const [_srcAddress, _destAddress] = this._getLoweredAddresses(
264
+ _srcToken,
265
+ _destToken,
266
+ );
267
+
268
+ if (_srcAddress === _destAddress) return [];
269
+
270
+ const pool = await this.getPool(_srcAddress, _destAddress, blockNumber);
271
+ if (!pool) return [];
272
+ return [this.getPoolIdentifier(_srcAddress, _destAddress)];
273
+ }
274
+
275
+ async getPricesVolume(
276
+ srcToken: Token,
277
+ destToken: Token,
278
+ amounts: bigint[],
279
+ side: SwapSide,
280
+ blockNumber: number,
281
+ limitPools?: string[],
282
+ ): Promise<null | ExchangePrices<AlgebraData>> {
283
+ try {
284
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
285
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
286
+
287
+ const [_srcAddress, _destAddress] = this._getLoweredAddresses(
288
+ _srcToken,
289
+ _destToken,
290
+ );
291
+
292
+ if (_srcAddress === _destAddress) return null;
293
+
294
+ if (
295
+ !limitPools?.includes(this.getPoolIdentifier(_srcAddress, _destAddress))
296
+ )
297
+ return null;
298
+
299
+ const pool = await this.getPool(_srcAddress, _destAddress, blockNumber);
300
+
301
+ if (!pool) return null;
302
+ // TODO handle fallack to rpc
303
+
304
+ const state = pool.getState(blockNumber);
305
+
306
+ if (!state) return null;
307
+
308
+ const unitAmount = getBigIntPow(
309
+ side == SwapSide.SELL ? _srcToken.decimals : _destToken.decimals,
310
+ );
311
+
312
+ const _amounts = [...amounts.slice(1)];
313
+
314
+ const [token0] = this._sortTokens(_srcAddress, _destAddress);
315
+
316
+ const zeroForOne = token0 === _srcAddress ? true : false;
317
+
318
+ if (state.liquidity <= 0n) {
319
+ this.logger.trace(`pool have 0 liquidity`);
320
+ return null;
321
+ }
322
+
323
+ const balanceDestToken =
324
+ _destAddress === pool.token0 ? state.balance0 : state.balance1;
325
+
326
+ const unitResult = this._getOutputs(
327
+ state,
328
+ [unitAmount],
329
+ zeroForOne,
330
+ side,
331
+ balanceDestToken,
332
+ );
333
+ const pricesResult = this._getOutputs(
334
+ state,
335
+ _amounts,
336
+ zeroForOne,
337
+ side,
338
+ balanceDestToken,
339
+ );
340
+
341
+ if (!unitResult || !pricesResult) {
342
+ this.logger.debug('Prices or unit is not calculated');
343
+ return null;
344
+ }
345
+
346
+ const prices = [0n, ...pricesResult.outputs];
347
+ const gasCost = [
348
+ 0,
349
+ ...pricesResult.outputs.map((p, index) => {
350
+ if (p == 0n) {
351
+ return 0;
352
+ } else {
353
+ return (
354
+ ALGEBRA_POOL_SEARCH_OVERHEAD +
355
+ ALGEBRA_TICK_BASE_OVERHEAD +
356
+ pricesResult.tickCounts[index] * ALGEBRA_TICK_GAS_COST
357
+ );
358
+ }
359
+ }),
360
+ ];
361
+
362
+ return [
363
+ {
364
+ unit: unitResult.outputs[0],
365
+ prices,
366
+ data: {
367
+ path: [
368
+ {
369
+ tokenIn: _srcAddress,
370
+ tokenOut: _destAddress,
371
+ },
372
+ ],
373
+ },
374
+ poolIdentifier: this.getPoolIdentifier(pool.token0, pool.token1),
375
+ exchange: this.dexKey,
376
+ gasCost: gasCost,
377
+ poolAddresses: [pool.poolAddress],
378
+ },
379
+ ];
380
+ } catch (e) {
381
+ this.logger.error(
382
+ `Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
383
+ destToken.symbol || destToken.address
384
+ }, ${side}:`,
385
+ e,
386
+ );
387
+ return null;
388
+ }
389
+ }
390
+
391
+ getAdapterParam(
392
+ srcToken: string,
393
+ destToken: string,
394
+ srcAmount: string,
395
+ destAmount: string,
396
+ data: AlgebraData,
397
+ side: SwapSide,
398
+ ): AdapterExchangeParam {
399
+ const { path: rawPath } = data;
400
+ const path = this._encodePath(rawPath, side);
401
+
402
+ const payload = this.abiCoder.encodeParameter(
403
+ {
404
+ ParentStruct: {
405
+ path: 'bytes',
406
+ deadline: 'uint256',
407
+ },
408
+ },
409
+ {
410
+ path,
411
+ deadline: getLocalDeadlineAsFriendlyPlaceholder(), // FIXME: more gas efficient to pass block.timestamp in adapter
412
+ },
413
+ );
414
+
415
+ return {
416
+ targetExchange: this.config.router,
417
+ payload,
418
+ networkFee: '0',
419
+ };
420
+ }
421
+
422
+ getCalldataGasCost(poolPrices: PoolPrices<AlgebraData>): number | number[] {
423
+ const gasCost =
424
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
425
+ CALLDATA_GAS_COST.LENGTH_SMALL +
426
+ // ParentStruct header
427
+ CALLDATA_GAS_COST.OFFSET_SMALL +
428
+ // ParentStruct -> path header
429
+ CALLDATA_GAS_COST.OFFSET_SMALL +
430
+ // ParentStruct -> deadline
431
+ CALLDATA_GAS_COST.TIMESTAMP +
432
+ // ParentStruct -> path (20+3+20 = 43 = 32+11 bytes)
433
+ CALLDATA_GAS_COST.LENGTH_SMALL +
434
+ CALLDATA_GAS_COST.FULL_WORD +
435
+ CALLDATA_GAS_COST.wordNonZeroBytes(11);
436
+ const arr = new Array(poolPrices.prices.length);
437
+ poolPrices.prices.forEach((p, index) => {
438
+ if (p == 0n) {
439
+ arr[index] = 0;
440
+ } else {
441
+ arr[index] = gasCost;
442
+ }
443
+ });
444
+ return arr;
445
+ }
446
+
447
+ async getSimpleParam(
448
+ srcToken: string,
449
+ destToken: string,
450
+ srcAmount: string,
451
+ destAmount: string,
452
+ data: AlgebraData,
453
+ side: SwapSide,
454
+ ): Promise<SimpleExchangeParam> {
455
+ const swapFunction =
456
+ side === SwapSide.SELL
457
+ ? UniswapV3Functions.exactInput
458
+ : UniswapV3Functions.exactOutput;
459
+
460
+ const path = this._encodePath(data.path, side);
461
+ const swapFunctionParams: UniswapV3SimpleSwapParams =
462
+ side === SwapSide.SELL
463
+ ? {
464
+ recipient: this.augustusAddress,
465
+ deadline: getLocalDeadlineAsFriendlyPlaceholder(),
466
+ amountIn: srcAmount,
467
+ amountOutMinimum: destAmount,
468
+ path,
469
+ }
470
+ : {
471
+ recipient: this.augustusAddress,
472
+ deadline: getLocalDeadlineAsFriendlyPlaceholder(),
473
+ amountOut: destAmount,
474
+ amountInMaximum: srcAmount,
475
+ path,
476
+ };
477
+ const swapData = this.routerIface.encodeFunctionData(swapFunction, [
478
+ swapFunctionParams,
479
+ ]);
480
+
481
+ return this.buildSimpleParamWithoutWETHConversion(
482
+ srcToken,
483
+ srcAmount,
484
+ destToken,
485
+ destAmount,
486
+ swapData,
487
+ this.config.router,
488
+ );
489
+ }
490
+
491
+ async getTopPoolsForToken(
492
+ tokenAddress: Address,
493
+ limit: number,
494
+ ): Promise<PoolLiquidity[]> {
495
+ const _tokenAddress = tokenAddress.toLowerCase();
496
+
497
+ const res = await this._querySubgraph(
498
+ `query ($token: Bytes!, $count: Int) {
499
+ pools0: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token0: $token}) {
500
+ id
501
+ token0 {
502
+ id
503
+ decimals
504
+ }
505
+ token1 {
506
+ id
507
+ decimals
508
+ }
509
+ totalValueLockedUSD
510
+ }
511
+ pools1: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token1: $token}) {
512
+ id
513
+ token0 {
514
+ id
515
+ decimals
516
+ }
517
+ token1 {
518
+ id
519
+ decimals
520
+ }
521
+ totalValueLockedUSD
522
+ }
523
+ }`,
524
+ {
525
+ token: _tokenAddress,
526
+ count: limit,
527
+ },
528
+ );
529
+
530
+ if (!(res && res.pools0 && res.pools1)) {
531
+ this.logger.error(
532
+ `Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`,
533
+ );
534
+ return [];
535
+ }
536
+
537
+ const pools0 = _.map(res.pools0, pool => ({
538
+ exchange: this.dexKey,
539
+ address: pool.id.toLowerCase(),
540
+ connectorTokens: [
541
+ {
542
+ address: pool.token1.id.toLowerCase(),
543
+ decimals: parseInt(pool.token1.decimals),
544
+ },
545
+ ],
546
+ liquidityUSD:
547
+ parseFloat(pool.totalValueLockedUSD) * ALGEBRA_EFFICIENCY_FACTOR,
548
+ }));
549
+
550
+ const pools1 = _.map(res.pools1, pool => ({
551
+ exchange: this.dexKey,
552
+ address: pool.id.toLowerCase(),
553
+ connectorTokens: [
554
+ {
555
+ address: pool.token0.id.toLowerCase(),
556
+ decimals: parseInt(pool.token0.decimals),
557
+ },
558
+ ],
559
+ liquidityUSD:
560
+ parseFloat(pool.totalValueLockedUSD) * ALGEBRA_EFFICIENCY_FACTOR,
561
+ }));
562
+
563
+ const pools = _.slice(
564
+ _.sortBy(_.concat(pools0, pools1), [pool => -1 * pool.liquidityUSD]),
565
+ 0,
566
+ limit,
567
+ );
568
+ return pools;
569
+ }
570
+
571
+ private _getLoweredAddresses(srcToken: Token, destToken: Token) {
572
+ return [srcToken.address.toLowerCase(), destToken.address.toLowerCase()];
573
+ }
574
+
575
+ private _sortTokens(srcAddress: Address, destAddress: Address) {
576
+ return [srcAddress, destAddress].sort((a, b) => (a < b ? -1 : 1));
577
+ }
578
+
579
+ private _toLowerForAllConfigAddresses() {
580
+ // If new config property will be added, the TS will throw compile error
581
+ const newConfig: DexParams = {
582
+ router: this.config.router.toLowerCase(),
583
+ quoter: this.config.quoter.toLowerCase(),
584
+ factory: this.config.factory.toLowerCase(),
585
+ algebraStateMulticall: this.config.algebraStateMulticall.toLowerCase(),
586
+ chunksCount: this.config.chunksCount,
587
+ uniswapMulticall: this.config.uniswapMulticall,
588
+ deployer: this.config.deployer?.toLowerCase(),
589
+ initHash: this.config.initHash,
590
+ subgraphURL: this.config.subgraphURL,
591
+ };
592
+ return newConfig;
593
+ }
594
+
595
+ private _getOutputs(
596
+ state: DeepReadonly<PoolState>,
597
+ amounts: bigint[],
598
+ zeroForOne: boolean,
599
+ side: SwapSide,
600
+ destTokenBalance: bigint,
601
+ ): OutputResult | null {
602
+ try {
603
+ const outputsResult = AlgebraMath.queryOutputs(
604
+ state,
605
+ amounts,
606
+ zeroForOne,
607
+ side,
608
+ );
609
+
610
+ if (side === SwapSide.SELL) {
611
+ if (outputsResult.outputs[0] > destTokenBalance) {
612
+ return null;
613
+ }
614
+
615
+ for (let i = 0; i < outputsResult.outputs.length; i++) {
616
+ if (outputsResult.outputs[i] > destTokenBalance) {
617
+ outputsResult.outputs[i] = 0n;
618
+ outputsResult.tickCounts[i] = 0;
619
+ }
620
+ }
621
+ } else {
622
+ if (amounts[0] > destTokenBalance) {
623
+ return null;
624
+ }
625
+
626
+ // This may be improved by first checking outputs and requesting outputs
627
+ // only for amounts that makes more sense, but I don't think this is really
628
+ // important now
629
+ for (let i = 0; i < amounts.length; i++) {
630
+ if (amounts[i] > destTokenBalance) {
631
+ outputsResult.outputs[i] = 0n;
632
+ outputsResult.tickCounts[i] = 0;
633
+ }
634
+ }
635
+ }
636
+
637
+ return outputsResult;
638
+ } catch (e) {
639
+ this.logger.debug(
640
+ `${this.dexKey}: received error in _getOutputs while calculating outputs`,
641
+ e,
642
+ );
643
+ return null;
644
+ }
645
+ }
646
+
647
+ private async _querySubgraph(
648
+ query: string,
649
+ variables: Object,
650
+ timeout = 30000,
651
+ ) {
652
+ try {
653
+ const res = await this.dexHelper.httpRequest.post(
654
+ this.config.subgraphURL,
655
+ { query, variables },
656
+ undefined,
657
+ { timeout: timeout },
658
+ );
659
+ return res.data;
660
+ } catch (e) {
661
+ this.logger.error(`${this.dexKey}: can not query subgraph: `, e);
662
+ return {};
663
+ }
664
+ }
665
+
666
+ private _encodePath(
667
+ path: {
668
+ tokenIn: Address;
669
+ tokenOut: Address;
670
+ }[],
671
+ side: SwapSide,
672
+ ): string {
673
+ if (path.length === 0) {
674
+ return '0x';
675
+ }
676
+
677
+ const { _path, types } = path.reduce(
678
+ (
679
+ { _path, types }: { _path: string[]; types: string[] },
680
+ curr,
681
+ index,
682
+ ): { _path: string[]; types: string[] } => {
683
+ if (index === 0) {
684
+ return {
685
+ types: ['address', 'address'],
686
+ _path: [curr.tokenIn, curr.tokenOut],
687
+ };
688
+ } else {
689
+ return {
690
+ types: [...types, 'address'],
691
+ _path: [..._path, curr.tokenOut],
692
+ };
693
+ }
694
+ },
695
+ { _path: [], types: [] },
696
+ );
697
+
698
+ return side === SwapSide.BUY
699
+ ? pack(types.reverse(), _path.reverse())
700
+ : pack(types, _path);
701
+ }
702
+
703
+ releaseResources() {
704
+ if (this.intervalTask !== undefined) {
705
+ clearInterval(this.intervalTask);
706
+ this.intervalTask = undefined;
707
+ }
708
+ }
709
+ }