@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,968 +1,968 @@
1
- import { Interface } from '@ethersproject/abi';
2
- import _ from 'lodash';
3
- import { pack } from '@ethersproject/solidity';
4
- import {
5
- Token,
6
- Address,
7
- ExchangePrices,
8
- AdapterExchangeParam,
9
- SimpleExchangeParam,
10
- PoolLiquidity,
11
- Logger,
12
- NumberAsString,
13
- PoolPrices,
14
- PreprocessTransactionOptions,
15
- ExchangeTxInfo,
16
- DexExchangeParam,
17
- } from '../../types';
18
- import { SwapSide, Network, CACHE_PREFIX } from '../../constants';
19
- import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
20
- import { getBigIntPow, getDexKeysWithNetwork, isTruthy } from '../../utils';
21
- import { IDex } from '../../dex/idex';
22
- import { IDexHelper } from '../../dex-helper/idex-helper';
23
- import {
24
- DexParams,
25
- OutputResult,
26
- PoolState,
27
- SolidlyV3Data,
28
- SolidlyV3SimpleSwapParams,
29
- UniswapV3Param,
30
- } from './types';
31
- import {
32
- getLocalDeadlineAsFriendlyPlaceholder,
33
- SimpleExchange,
34
- } from '../simple-exchange';
35
- import { SolidlyV3Config, Adapters, PoolsToPreload } from './config';
36
- import { SolidlyV3EventPool } from './solidly-v3-pool';
37
- import DirectSwapABI from '../../abi/DirectSwap.json';
38
- import SolidlyV3StateMulticallABI from '../../abi/solidly-v3/SolidlyV3StateMulticall.abi.json';
39
- import SolidlyV3PoolABI from '../../abi/solidly-v3/SolidlyV3Pool.abi.json';
40
- import {
41
- UNISWAPV3_EFFICIENCY_FACTOR,
42
- UNISWAPV3_POOL_SEARCH_OVERHEAD,
43
- UNISWAPV3_TICK_BASE_OVERHEAD,
44
- UNISWAPV3_TICK_GAS_COST,
45
- } from './constants';
46
- import { assert, DeepReadonly } from 'ts-essentials';
47
- import { uniswapV3Math } from './contract-math/uniswap-v3-math';
48
- import { Contract } from 'web3-eth-contract';
49
- import { AbiItem } from 'web3-utils';
50
- import { TickMath } from './contract-math/TickMath';
51
- import { OnPoolCreatedCallback, SolidlyV3Factory } from './solidly-v3-factory';
52
-
53
- type PoolPairsInfo = {
54
- token0: Address;
55
- token1: Address;
56
- fee: string;
57
- };
58
-
59
- const PoolsRegistryHashKey = `${CACHE_PREFIX}_poolsRegistry`;
60
-
61
- const UNISWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS = 60 * 60 * 24 * 1000; // 24 hours
62
- const UNISWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS = 30 * 60 * 1000; // Once in 30 minutes
63
-
64
- export class SolidlyV3
65
- extends SimpleExchange
66
- implements IDex<SolidlyV3Data, UniswapV3Param>
67
- {
68
- readonly isFeeOnTransferSupported: boolean = false;
69
- readonly eventPools: Record<string, SolidlyV3EventPool | null> = {};
70
-
71
- readonly hasConstantPriceLargeAmounts = false;
72
- readonly needWrapNative = true;
73
-
74
- readonly directSwapIface = new Interface(DirectSwapABI);
75
-
76
- intervalTask?: NodeJS.Timeout;
77
-
78
- public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
79
- getDexKeysWithNetwork(_.pick(SolidlyV3Config, ['SolidlyV3']));
80
-
81
- logger: Logger;
82
-
83
- private stateMultiContract: Contract;
84
-
85
- private notExistingPoolSetKey: string;
86
-
87
- private readonly factory: SolidlyV3Factory;
88
-
89
- constructor(
90
- protected network: Network,
91
- dexKey: string,
92
- protected dexHelper: IDexHelper,
93
- protected adapters = Adapters[network] || {},
94
- readonly poolIface = new Interface(SolidlyV3PoolABI),
95
- protected config = SolidlyV3Config[dexKey][network],
96
- protected poolsToPreload = PoolsToPreload[dexKey]?.[network] || [],
97
- ) {
98
- super(dexHelper, dexKey);
99
- this.logger = dexHelper.getLogger(dexKey + '-' + network);
100
- this.stateMultiContract = new this.dexHelper.web3Provider.eth.Contract(
101
- this.config.stateMultiCallAbi !== undefined
102
- ? this.config.stateMultiCallAbi
103
- : (SolidlyV3StateMulticallABI as AbiItem[]),
104
- this.config.stateMulticall,
105
- );
106
-
107
- // To receive revert reasons
108
- this.dexHelper.web3Provider.eth.handleRevert = false;
109
-
110
- // Normalize once all config addresses and use across all scenarios
111
- this.config = this._toLowerForAllConfigAddresses();
112
-
113
- this.factory = new SolidlyV3Factory(
114
- dexHelper,
115
- dexKey,
116
- this.config.factory,
117
- this.logger,
118
- this.onPoolCreatedDeleteFromNonExistingSet,
119
- );
120
-
121
- this.notExistingPoolSetKey =
122
- `${CACHE_PREFIX}_${network}_${dexKey}_not_existings_pool_set`.toLowerCase();
123
- }
124
-
125
- get supportedTickSpacings() {
126
- return this.config.supportedTickSpacings;
127
- }
128
-
129
- getAdapters(side: SwapSide): { name: string; index: number }[] | null {
130
- return this.adapters[side] ? this.adapters[side] : null;
131
- }
132
-
133
- getPoolIdentifier(
134
- srcAddress: Address,
135
- destAddress: Address,
136
- tickSpacing: bigint,
137
- ) {
138
- const tokenAddresses = this._sortTokens(srcAddress, destAddress).join('_');
139
- return `${this.dexKey}_${tokenAddresses}_${tickSpacing}`;
140
- }
141
-
142
- async initializePricing(blockNumber: number) {
143
- // Init listening to new pools creation
144
- await this.factory.initialize(blockNumber);
145
-
146
- // This is only for testing, because cold pool fetching is goes out of
147
- // FETCH_POOL_INDENTIFIER_TIMEOUT range
148
- await Promise.all(
149
- this.poolsToPreload.map(async pool =>
150
- Promise.all(
151
- this.config.supportedTickSpacings.map(async tickSpacing =>
152
- this.getPool(pool.token0, pool.token1, tickSpacing, blockNumber),
153
- ),
154
- ),
155
- ),
156
- );
157
-
158
- if (!this.dexHelper.config.isSlave) {
159
- const cleanExpiredNotExistingPoolsKeys = async () => {
160
- const maxTimestamp =
161
- Date.now() - UNISWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS;
162
- await this.dexHelper.cache.zremrangebyscore(
163
- this.notExistingPoolSetKey,
164
- 0,
165
- maxTimestamp,
166
- );
167
- };
168
-
169
- this.intervalTask = setInterval(
170
- cleanExpiredNotExistingPoolsKeys.bind(this),
171
- UNISWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS,
172
- );
173
- }
174
- }
175
-
176
- /*
177
- * When a non existing pool is queried, it's blacklisted for an arbitrary long period in order to prevent issuing too many rpc calls
178
- * Once the pool is created, it gets immediately flagged
179
- */
180
- onPoolCreatedDeleteFromNonExistingSet: OnPoolCreatedCallback = async ({
181
- token0,
182
- token1,
183
- tickSpacing,
184
- }) => {
185
- const logPrefix = '[onPoolCreatedDeleteFromNonExistingSet]';
186
- const [_token0, _token1] = this._sortTokens(token0, token1);
187
- const poolKey = `${_token0}_${_token1}_${tickSpacing}`;
188
-
189
- // consider doing it only from master pool for less calls to distant cache
190
-
191
- // delete entry locally to let local instance discover the pool
192
- delete this.eventPools[
193
- this.getPoolIdentifier(_token0, _token1, tickSpacing)
194
- ];
195
-
196
- try {
197
- this.logger.info(
198
- `${logPrefix} delete pool from not existing set=${this.notExistingPoolSetKey}; key=${poolKey}`,
199
- );
200
- // delete pool record from set
201
- const result = await this.dexHelper.cache.zrem(
202
- this.notExistingPoolSetKey,
203
- [poolKey],
204
- );
205
- this.logger.info(
206
- `${logPrefix} delete pool from not existing set=${this.notExistingPoolSetKey}; key=${poolKey}; result: ${result}`,
207
- );
208
- } catch (error) {
209
- this.logger.error(
210
- `${logPrefix} ERROR: failed to delete pool from set: set=${this.notExistingPoolSetKey}; key=${poolKey}`,
211
- error,
212
- );
213
- }
214
- };
215
-
216
- async getPool(
217
- srcAddress: Address,
218
- destAddress: Address,
219
- tickSpacing: bigint,
220
- blockNumber: number,
221
- ): Promise<SolidlyV3EventPool | null> {
222
- let pool = this.eventPools[
223
- this.getPoolIdentifier(srcAddress, destAddress, tickSpacing)
224
- ] as SolidlyV3EventPool | null | undefined;
225
-
226
- if (pool === null) return null;
227
-
228
- if (pool) {
229
- if (!pool.initFailed) {
230
- return pool;
231
- } else {
232
- // if init failed then prefer to early return pool with empty state to fallback to rpc call
233
- if (
234
- ++pool.initRetryAttemptCount % this.config.initRetryFrequency !==
235
- 0
236
- ) {
237
- return pool;
238
- }
239
- // else pursue with re-try initialization
240
- }
241
- }
242
-
243
- const [token0, token1] = this._sortTokens(srcAddress, destAddress);
244
-
245
- const key = `${token0}_${token1}_${tickSpacing}`.toLowerCase();
246
-
247
- if (!pool) {
248
- const notExistingPoolScore = await this.dexHelper.cache.zscore(
249
- this.notExistingPoolSetKey,
250
- key,
251
- );
252
-
253
- const poolDoesNotExist = notExistingPoolScore !== null;
254
-
255
- if (poolDoesNotExist) {
256
- this.eventPools[
257
- this.getPoolIdentifier(srcAddress, destAddress, tickSpacing)
258
- ] = null;
259
- return null;
260
- }
261
- }
262
-
263
- this.logger.trace(`starting to listen to new pool: ${key}`);
264
- pool =
265
- pool ||
266
- new SolidlyV3EventPool(
267
- this.dexHelper,
268
- this.dexKey,
269
- this.stateMultiContract,
270
- this.config.decodeStateMultiCallResultWithRelativeBitmaps,
271
- this.erc20Interface,
272
- this.config.factory,
273
- tickSpacing,
274
- token0,
275
- token1,
276
- this.logger,
277
- this.cacheStateKey,
278
- this.config.initHash,
279
- );
280
-
281
- try {
282
- await pool.initialize(blockNumber, {
283
- initCallback: (state: DeepReadonly<PoolState>) => {
284
- //really hacky, we need to push poolAddress so that we subscribeToLogs in StatefulEventSubscriber
285
- pool!.addressesSubscribed[0] = state.pool;
286
- pool!.poolAddress = state.pool;
287
- pool!.initFailed = false;
288
- pool!.initRetryAttemptCount = 0;
289
- },
290
- });
291
- } catch (e) {
292
- if (e instanceof Error && e.message.endsWith('Pool does not exist')) {
293
- // no need to await we want the set to have the pool key but it's not blocking
294
- this.dexHelper.cache.zadd(
295
- this.notExistingPoolSetKey,
296
- [Date.now(), key],
297
- 'NX',
298
- );
299
-
300
- // Pool does not exist for this feeCode, so we can set it to null
301
- // to prevent more requests for this pool
302
- pool = null;
303
- this.logger.trace(
304
- `${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${tickSpacing} not found`,
305
- e,
306
- );
307
- } else {
308
- // on unknown error mark as failed and increase retryCount for retry init strategy
309
- // note: state would be null by default which allows to fallback
310
- this.logger.warn(
311
- `${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${tickSpacing} pool fallback to rpc and retry every ${this.config.initRetryFrequency} times, initRetryAttemptCount=${pool.initRetryAttemptCount}`,
312
- e,
313
- );
314
- pool.initFailed = true;
315
- }
316
- }
317
-
318
- if (pool !== null) {
319
- const allEventPools = Object.values(this.eventPools);
320
- this.logger.info(
321
- `starting to listen to new non-null pool: ${key}. Already following ${allEventPools
322
- // Not that I like this reduce, but since it is done only on initialization, expect this to be ok
323
- .reduce(
324
- (acc, curr) => (curr !== null ? ++acc : acc),
325
- 0,
326
- )} non-null pools or ${allEventPools.length} total pools`,
327
- );
328
- }
329
-
330
- this.eventPools[
331
- this.getPoolIdentifier(srcAddress, destAddress, tickSpacing)
332
- ] = pool;
333
- return pool;
334
- }
335
-
336
- async addMasterPool(poolKey: string, blockNumber: number): Promise<boolean> {
337
- const _pairs = await this.dexHelper.cache.hget(
338
- PoolsRegistryHashKey,
339
- `${this.cacheStateKey}_${poolKey}`,
340
- );
341
- if (!_pairs) {
342
- this.logger.warn(
343
- `did not find poolConfig in for key ${PoolsRegistryHashKey} ${this.cacheStateKey}_${poolKey}`,
344
- );
345
- return false;
346
- }
347
-
348
- const poolInfo: PoolPairsInfo = JSON.parse(_pairs);
349
-
350
- const pool = await this.getPool(
351
- poolInfo.token0,
352
- poolInfo.token1,
353
- BigInt(poolInfo.fee),
354
- blockNumber,
355
- );
356
-
357
- if (!pool) {
358
- return false;
359
- }
360
-
361
- return true;
362
- }
363
-
364
- async getPoolIdentifiers(
365
- srcToken: Token,
366
- destToken: Token,
367
- side: SwapSide,
368
- blockNumber: number,
369
- ): Promise<string[]> {
370
- const _srcToken = this.dexHelper.config.wrapETH(srcToken);
371
- const _destToken = this.dexHelper.config.wrapETH(destToken);
372
-
373
- const [_srcAddress, _destAddress] = this._getLoweredAddresses(
374
- _srcToken,
375
- _destToken,
376
- );
377
-
378
- if (_srcAddress === _destAddress) return [];
379
-
380
- const pools = (
381
- await Promise.all(
382
- this.supportedTickSpacings.map(async tickSpacing =>
383
- this.getPool(_srcAddress, _destAddress, tickSpacing, blockNumber),
384
- ),
385
- )
386
- ).filter(pool => pool);
387
-
388
- if (pools.length === 0) return [];
389
-
390
- return pools.map(pool =>
391
- this.getPoolIdentifier(_srcAddress, _destAddress, pool!.tickSpacing),
392
- );
393
- }
394
-
395
- async getPricesVolume(
396
- srcToken: Token,
397
- destToken: Token,
398
- amounts: bigint[],
399
- side: SwapSide,
400
- blockNumber: number,
401
- limitPools?: string[],
402
- ): Promise<null | ExchangePrices<SolidlyV3Data>> {
403
- try {
404
- const _srcToken = this.dexHelper.config.wrapETH(srcToken);
405
- const _destToken = this.dexHelper.config.wrapETH(destToken);
406
-
407
- const [_srcAddress, _destAddress] = this._getLoweredAddresses(
408
- _srcToken,
409
- _destToken,
410
- );
411
-
412
- if (_srcAddress === _destAddress) return null;
413
-
414
- let selectedPools: SolidlyV3EventPool[] = [];
415
-
416
- if (!limitPools) {
417
- selectedPools = (
418
- await Promise.all(
419
- this.supportedTickSpacings.map(async tickSpacing => {
420
- const locallyFoundPool =
421
- this.eventPools[
422
- this.getPoolIdentifier(_srcAddress, _destAddress, tickSpacing)
423
- ];
424
- if (locallyFoundPool) return locallyFoundPool;
425
-
426
- const newlyFetchedPool = await this.getPool(
427
- _srcAddress,
428
- _destAddress,
429
- tickSpacing,
430
- blockNumber,
431
- );
432
- return newlyFetchedPool;
433
- }),
434
- )
435
- ).filter(isTruthy);
436
- } else {
437
- const pairIdentifierWithoutFee = this.getPoolIdentifier(
438
- _srcAddress,
439
- _destAddress,
440
- 0n,
441
- // Trim from 0 fee postfix, so it become comparable
442
- ).slice(0, -1);
443
-
444
- const poolIdentifiers = limitPools.filter(identifier =>
445
- identifier.startsWith(pairIdentifierWithoutFee),
446
- );
447
-
448
- selectedPools = (
449
- await Promise.all(
450
- poolIdentifiers.map(async identifier => {
451
- let locallyFoundPool = this.eventPools[identifier];
452
- if (locallyFoundPool) return locallyFoundPool;
453
-
454
- const [, srcAddress, destAddress, tickSpacing] =
455
- identifier.split('_');
456
- const newlyFetchedPool = await this.getPool(
457
- srcAddress,
458
- destAddress,
459
- BigInt(tickSpacing),
460
- blockNumber,
461
- );
462
- return newlyFetchedPool;
463
- }),
464
- )
465
- ).filter(isTruthy);
466
- }
467
-
468
- if (selectedPools.length === 0) return null;
469
-
470
- const poolsToUse = selectedPools.reduce(
471
- (acc, pool) => {
472
- let state = pool.getState(blockNumber);
473
- if (state === null) {
474
- throw new Error('Unable to retrieve pool state.');
475
- } else {
476
- acc.poolWithState.push(pool);
477
- }
478
- return acc;
479
- },
480
- {
481
- poolWithState: [] as SolidlyV3EventPool[],
482
- poolWithoutState: [] as SolidlyV3EventPool[],
483
- },
484
- );
485
-
486
- const states = poolsToUse.poolWithState.map(
487
- p => p.getState(blockNumber)!,
488
- );
489
-
490
- const unitAmount = getBigIntPow(
491
- side == SwapSide.SELL ? _srcToken.decimals : _destToken.decimals,
492
- );
493
-
494
- const _amounts = [...amounts.slice(1)];
495
-
496
- const [token0] = this._sortTokens(_srcAddress, _destAddress);
497
-
498
- const zeroForOne = token0 === _srcAddress ? true : false;
499
-
500
- const result = await Promise.all(
501
- poolsToUse.poolWithState.map(async (pool, i) => {
502
- const state = states[i];
503
-
504
- if (state.liquidity <= 0n) {
505
- if (state.liquidity < 0) {
506
- this.logger.error(
507
- `${this.dexKey}-${this.network}: ${pool.poolAddress} pool has negative liquidity: ${state.liquidity}. Find with key: ${pool.mapKey}`,
508
- );
509
- }
510
- this.logger.trace(`pool have 0 liquidity`);
511
- return null;
512
- }
513
-
514
- const balanceDestToken =
515
- _destAddress === pool.token0 ? state.balance0 : state.balance1;
516
-
517
- const unitResult = this._getOutputs(
518
- state,
519
- [unitAmount],
520
- zeroForOne,
521
- side,
522
- balanceDestToken,
523
- );
524
- const pricesResult = this._getOutputs(
525
- state,
526
- _amounts,
527
- zeroForOne,
528
- side,
529
- balanceDestToken,
530
- );
531
-
532
- if (!unitResult || !pricesResult) {
533
- this.logger.debug('Prices or unit is not calculated');
534
- return null;
535
- }
536
-
537
- const prices = [0n, ...pricesResult.outputs];
538
- const gasCost = [
539
- 0,
540
- ...pricesResult.outputs.map((p, index) => {
541
- if (p == 0n) {
542
- return 0;
543
- } else {
544
- return (
545
- UNISWAPV3_POOL_SEARCH_OVERHEAD +
546
- UNISWAPV3_TICK_BASE_OVERHEAD +
547
- pricesResult.tickCounts[index] * UNISWAPV3_TICK_GAS_COST
548
- );
549
- }
550
- }),
551
- ];
552
- return {
553
- unit: unitResult.outputs[0],
554
- prices,
555
- data: {
556
- zeroForOne,
557
- poolAddress: pool.poolAddress,
558
- },
559
- poolIdentifier: this.getPoolIdentifier(
560
- pool.token0,
561
- pool.token1,
562
- pool.tickSpacing,
563
- ),
564
- exchange: this.dexKey,
565
- gasCost: gasCost,
566
- poolAddresses: [pool.poolAddress],
567
- };
568
- }),
569
- );
570
-
571
- const notNullResult = result.filter(
572
- res => res !== null,
573
- ) as ExchangePrices<SolidlyV3Data>;
574
-
575
- return notNullResult;
576
- } catch (e) {
577
- this.logger.error(
578
- `Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
579
- destToken.symbol || destToken.address
580
- }, ${side}:`,
581
- e,
582
- );
583
- return null;
584
- }
585
- }
586
-
587
- getAdapterParam(
588
- srcToken: string,
589
- destToken: string,
590
- srcAmount: string,
591
- destAmount: string,
592
- data: SolidlyV3Data,
593
- side: SwapSide,
594
- ): AdapterExchangeParam {
595
- const sqrtPriceLimitX96 = data.zeroForOne
596
- ? (TickMath.MIN_SQRT_RATIO + BigInt(1)).toString()
597
- : (TickMath.MAX_SQRT_RATIO - BigInt(1)).toString();
598
-
599
- const payload = this.abiCoder.encodeParameter(
600
- {
601
- ParentStruct: {
602
- recipient: 'address',
603
- zeroForOne: 'bool',
604
- sqrtPriceLimitX96: 'uint160',
605
- },
606
- },
607
- {
608
- recipient: this.augustusAddress,
609
- zeroForOne: data.zeroForOne,
610
- sqrtPriceLimitX96,
611
- },
612
- );
613
-
614
- return {
615
- targetExchange: data.poolAddress,
616
- payload,
617
- networkFee: '0',
618
- };
619
- }
620
-
621
- getCalldataGasCost(poolPrices: PoolPrices<SolidlyV3Data>): number | number[] {
622
- const gasCost =
623
- CALLDATA_GAS_COST.DEX_OVERHEAD +
624
- CALLDATA_GAS_COST.LENGTH_SMALL +
625
- // ParentStruct header
626
- CALLDATA_GAS_COST.OFFSET_SMALL +
627
- // ParentStruct -> path header
628
- CALLDATA_GAS_COST.OFFSET_SMALL +
629
- // ParentStruct -> deadline
630
- CALLDATA_GAS_COST.TIMESTAMP +
631
- // ParentStruct -> path (20+3+20 = 43 = 32+11 bytes)
632
- CALLDATA_GAS_COST.LENGTH_SMALL +
633
- CALLDATA_GAS_COST.FULL_WORD +
634
- CALLDATA_GAS_COST.wordNonZeroBytes(11);
635
- const arr = new Array(poolPrices.prices.length);
636
- poolPrices.prices.forEach((p, index) => {
637
- if (p == 0n) {
638
- arr[index] = 0;
639
- } else {
640
- arr[index] = gasCost;
641
- }
642
- });
643
- return arr;
644
- }
645
-
646
- getTokenFromAddress(address: Address): Token {
647
- // In this Dex decimals are not used
648
- return { address, decimals: 0 };
649
- }
650
-
651
- async getSimpleParam(
652
- srcToken: string,
653
- destToken: string,
654
- srcAmount: string,
655
- destAmount: string,
656
- data: SolidlyV3Data,
657
- side: SwapSide,
658
- ): Promise<SimpleExchangeParam> {
659
- const swapFunction = this.poolIface.getFunction(
660
- 'swap(address,bool,int256,uint160)',
661
- );
662
-
663
- const swapFunctionParams: SolidlyV3SimpleSwapParams = {
664
- recipient: this.augustusAddress,
665
- zeroForOne: data.zeroForOne,
666
- amountSpecified:
667
- side === SwapSide.SELL
668
- ? srcAmount.toString()
669
- : (-destAmount).toString(),
670
- sqrtPriceLimitX96: data.zeroForOne
671
- ? (TickMath.MIN_SQRT_RATIO + BigInt(1)).toString()
672
- : (TickMath.MAX_SQRT_RATIO - BigInt(1)).toString(),
673
- };
674
- const swapData = this.poolIface.encodeFunctionData(swapFunction, [
675
- swapFunctionParams.recipient,
676
- swapFunctionParams.zeroForOne,
677
- swapFunctionParams.amountSpecified,
678
- swapFunctionParams.sqrtPriceLimitX96,
679
- ]);
680
-
681
- return this.buildSimpleParamWithoutWETHConversion(
682
- srcToken,
683
- srcAmount,
684
- destToken,
685
- destAmount,
686
- swapData,
687
- data.poolAddress,
688
- );
689
- }
690
-
691
- getDexParam(
692
- srcToken: Address,
693
- destToken: Address,
694
- srcAmount: NumberAsString,
695
- destAmount: NumberAsString,
696
- recipient: Address,
697
- data: SolidlyV3Data,
698
- side: SwapSide,
699
- ): DexExchangeParam {
700
- const swapFunction = this.poolIface.getFunction(
701
- 'swap(address,bool,int256,uint160)',
702
- );
703
-
704
- const swapFunctionParams: SolidlyV3SimpleSwapParams = {
705
- recipient,
706
- zeroForOne: data.zeroForOne,
707
- amountSpecified:
708
- side === SwapSide.SELL
709
- ? srcAmount.toString()
710
- : (-destAmount).toString(),
711
- sqrtPriceLimitX96: data.zeroForOne
712
- ? (TickMath.MIN_SQRT_RATIO + BigInt(1)).toString()
713
- : (TickMath.MAX_SQRT_RATIO - BigInt(1)).toString(),
714
- };
715
- const swapData = this.poolIface.encodeFunctionData(swapFunction, [
716
- swapFunctionParams.recipient,
717
- swapFunctionParams.zeroForOne,
718
- swapFunctionParams.amountSpecified,
719
- swapFunctionParams.sqrtPriceLimitX96,
720
- ]);
721
-
722
- return {
723
- needWrapNative: this.needWrapNative,
724
- dexFuncHasRecipient: true,
725
- exchangeData: swapData,
726
- targetExchange: data.poolAddress,
727
- returnAmountPos: undefined,
728
- };
729
- }
730
-
731
- async getTopPoolsForToken(
732
- tokenAddress: Address,
733
- limit: number,
734
- ): Promise<PoolLiquidity[]> {
735
- const _tokenAddress = tokenAddress.toLowerCase();
736
-
737
- const res = await this._querySubgraph(
738
- `query ($token: Bytes!, $count: Int) {
739
- pools0: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token0: $token, liquidity_gt: "0"}) {
740
- id
741
- token0 {
742
- id
743
- decimals
744
- }
745
- token1 {
746
- id
747
- decimals
748
- }
749
- totalValueLockedUSD
750
- }
751
- pools1: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token1: $token, liquidity_gt: "0"}) {
752
- id
753
- token0 {
754
- id
755
- decimals
756
- }
757
- token1 {
758
- id
759
- decimals
760
- }
761
- totalValueLockedUSD
762
- }
763
- }`,
764
- {
765
- token: _tokenAddress,
766
- count: limit,
767
- },
768
- );
769
-
770
- if (!(res && res.pools0 && res.pools1)) {
771
- this.logger.error(
772
- `Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`,
773
- );
774
- return [];
775
- }
776
-
777
- const pools0 = _.map(res.pools0, pool => ({
778
- exchange: this.dexKey,
779
- address: pool.id.toLowerCase(),
780
- connectorTokens: [
781
- {
782
- address: pool.token1.id.toLowerCase(),
783
- decimals: parseInt(pool.token1.decimals),
784
- },
785
- ],
786
- liquidityUSD:
787
- parseFloat(pool.totalValueLockedUSD) * UNISWAPV3_EFFICIENCY_FACTOR,
788
- }));
789
-
790
- const pools1 = _.map(res.pools1, pool => ({
791
- exchange: this.dexKey,
792
- address: pool.id.toLowerCase(),
793
- connectorTokens: [
794
- {
795
- address: pool.token0.id.toLowerCase(),
796
- decimals: parseInt(pool.token0.decimals),
797
- },
798
- ],
799
- liquidityUSD:
800
- parseFloat(pool.totalValueLockedUSD) * UNISWAPV3_EFFICIENCY_FACTOR,
801
- }));
802
-
803
- const pools = _.slice(
804
- _.sortBy(_.concat(pools0, pools1), [pool => -1 * pool.liquidityUSD]),
805
- 0,
806
- limit,
807
- );
808
- return pools;
809
- }
810
-
811
- private async _getPoolsFromIdentifiers(
812
- poolIdentifiers: string[],
813
- blockNumber: number,
814
- ): Promise<SolidlyV3EventPool[]> {
815
- const pools = await Promise.all(
816
- poolIdentifiers.map(async identifier => {
817
- const [, srcAddress, destAddress, fee] = identifier.split('_');
818
- return this.getPool(srcAddress, destAddress, BigInt(fee), blockNumber);
819
- }),
820
- );
821
- return pools.filter(pool => pool) as SolidlyV3EventPool[];
822
- }
823
-
824
- private _getLoweredAddresses(srcToken: Token, destToken: Token) {
825
- return [srcToken.address.toLowerCase(), destToken.address.toLowerCase()];
826
- }
827
-
828
- private _sortTokens(srcAddress: Address, destAddress: Address) {
829
- return [srcAddress, destAddress].sort((a, b) => (a < b ? -1 : 1));
830
- }
831
-
832
- private _toLowerForAllConfigAddresses() {
833
- // If new config property will be added, the TS will throw compile error
834
- const newConfig: DexParams = {
835
- factory: this.config.factory.toLowerCase(),
836
- supportedTickSpacings: this.config.supportedTickSpacings,
837
- stateMulticall: this.config.stateMulticall.toLowerCase(),
838
- chunksCount: this.config.chunksCount,
839
- initRetryFrequency: this.config.initRetryFrequency,
840
- deployer: this.config.deployer?.toLowerCase(),
841
- initHash: this.config.initHash,
842
- subgraphURL: this.config.subgraphURL,
843
- stateMultiCallAbi: this.config.stateMultiCallAbi,
844
- decodeStateMultiCallResultWithRelativeBitmaps:
845
- this.config.decodeStateMultiCallResultWithRelativeBitmaps,
846
- };
847
- return newConfig;
848
- }
849
-
850
- private _getOutputs(
851
- state: DeepReadonly<PoolState>,
852
- amounts: bigint[],
853
- zeroForOne: boolean,
854
- side: SwapSide,
855
- destTokenBalance: bigint,
856
- ): OutputResult | null {
857
- try {
858
- const outputsResult = uniswapV3Math.queryOutputs(
859
- state,
860
- amounts,
861
- zeroForOne,
862
- side,
863
- );
864
-
865
- if (side === SwapSide.SELL) {
866
- if (outputsResult.outputs[0] > destTokenBalance) {
867
- return null;
868
- }
869
-
870
- for (let i = 0; i < outputsResult.outputs.length; i++) {
871
- if (outputsResult.outputs[i] > destTokenBalance) {
872
- outputsResult.outputs[i] = 0n;
873
- outputsResult.tickCounts[i] = 0;
874
- }
875
- }
876
- } else {
877
- if (amounts[0] > destTokenBalance) {
878
- return null;
879
- }
880
-
881
- // This may be improved by first checking outputs and requesting outputs
882
- // only for amounts that makes more sense, but I don't think this is really
883
- // important now
884
- for (let i = 0; i < amounts.length; i++) {
885
- if (amounts[i] > destTokenBalance) {
886
- outputsResult.outputs[i] = 0n;
887
- outputsResult.tickCounts[i] = 0;
888
- }
889
- }
890
- }
891
-
892
- return outputsResult;
893
- } catch (e) {
894
- this.logger.debug(
895
- `${this.dexKey}: received error in _getOutputs while calculating outputs`,
896
- e,
897
- );
898
- return null;
899
- }
900
- }
901
-
902
- private async _querySubgraph(
903
- query: string,
904
- variables: Object,
905
- timeout = 30000,
906
- ) {
907
- try {
908
- const res = await this.dexHelper.httpRequest.post(
909
- this.config.subgraphURL,
910
- { query, variables },
911
- undefined,
912
- { timeout: timeout },
913
- );
914
- return res.data;
915
- } catch (e) {
916
- this.logger.error(`${this.dexKey}: can not query subgraph: `, e);
917
- return {};
918
- }
919
- }
920
-
921
- private _encodePath(
922
- path: {
923
- tokenIn: Address;
924
- tokenOut: Address;
925
- fee: NumberAsString;
926
- }[],
927
- side: SwapSide,
928
- ): string {
929
- if (path.length === 0) {
930
- this.logger.error(
931
- `${this.dexKey}: Received invalid path=${path} for side=${side} to encode`,
932
- );
933
- return '0x';
934
- }
935
-
936
- const { _path, types } = path.reduce(
937
- (
938
- { _path, types }: { _path: string[]; types: string[] },
939
- curr,
940
- index,
941
- ): { _path: string[]; types: string[] } => {
942
- if (index === 0) {
943
- return {
944
- types: ['address', 'uint24', 'address'],
945
- _path: [curr.tokenIn, curr.fee, curr.tokenOut],
946
- };
947
- } else {
948
- return {
949
- types: [...types, 'uint24', 'address'],
950
- _path: [..._path, curr.fee, curr.tokenOut],
951
- };
952
- }
953
- },
954
- { _path: [], types: [] },
955
- );
956
-
957
- return side === SwapSide.BUY
958
- ? pack(types.reverse(), _path.reverse())
959
- : pack(types, _path);
960
- }
961
-
962
- releaseResources() {
963
- if (this.intervalTask !== undefined) {
964
- clearInterval(this.intervalTask);
965
- this.intervalTask = undefined;
966
- }
967
- }
968
- }
1
+ import { Interface } from '@ethersproject/abi';
2
+ import _ from 'lodash';
3
+ import { pack } from '@ethersproject/solidity';
4
+ import {
5
+ Token,
6
+ Address,
7
+ ExchangePrices,
8
+ AdapterExchangeParam,
9
+ SimpleExchangeParam,
10
+ PoolLiquidity,
11
+ Logger,
12
+ NumberAsString,
13
+ PoolPrices,
14
+ PreprocessTransactionOptions,
15
+ ExchangeTxInfo,
16
+ DexExchangeParam,
17
+ } from '../../types';
18
+ import { SwapSide, Network, CACHE_PREFIX } from '../../constants';
19
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
20
+ import { getBigIntPow, getDexKeysWithNetwork, isTruthy } from '../../utils';
21
+ import { IDex } from '../../dex/idex';
22
+ import { IDexHelper } from '../../dex-helper/idex-helper';
23
+ import {
24
+ DexParams,
25
+ OutputResult,
26
+ PoolState,
27
+ SolidlyV3Data,
28
+ SolidlyV3SimpleSwapParams,
29
+ UniswapV3Param,
30
+ } from './types';
31
+ import {
32
+ getLocalDeadlineAsFriendlyPlaceholder,
33
+ SimpleExchange,
34
+ } from '../simple-exchange';
35
+ import { SolidlyV3Config, Adapters, PoolsToPreload } from './config';
36
+ import { SolidlyV3EventPool } from './solidly-v3-pool';
37
+ import DirectSwapABI from '../../abi/DirectSwap.json';
38
+ import SolidlyV3StateMulticallABI from '../../abi/solidly-v3/SolidlyV3StateMulticall.abi.json';
39
+ import SolidlyV3PoolABI from '../../abi/solidly-v3/SolidlyV3Pool.abi.json';
40
+ import {
41
+ UNISWAPV3_EFFICIENCY_FACTOR,
42
+ UNISWAPV3_POOL_SEARCH_OVERHEAD,
43
+ UNISWAPV3_TICK_BASE_OVERHEAD,
44
+ UNISWAPV3_TICK_GAS_COST,
45
+ } from './constants';
46
+ import { assert, DeepReadonly } from 'ts-essentials';
47
+ import { uniswapV3Math } from './contract-math/uniswap-v3-math';
48
+ import { Contract } from 'web3-eth-contract';
49
+ import { AbiItem } from 'web3-utils';
50
+ import { TickMath } from './contract-math/TickMath';
51
+ import { OnPoolCreatedCallback, SolidlyV3Factory } from './solidly-v3-factory';
52
+
53
+ type PoolPairsInfo = {
54
+ token0: Address;
55
+ token1: Address;
56
+ fee: string;
57
+ };
58
+
59
+ const PoolsRegistryHashKey = `${CACHE_PREFIX}_poolsRegistry`;
60
+
61
+ const UNISWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS = 60 * 60 * 24 * 1000; // 24 hours
62
+ const UNISWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS = 30 * 60 * 1000; // Once in 30 minutes
63
+
64
+ export class SolidlyV3
65
+ extends SimpleExchange
66
+ implements IDex<SolidlyV3Data, UniswapV3Param>
67
+ {
68
+ readonly isFeeOnTransferSupported: boolean = false;
69
+ readonly eventPools: Record<string, SolidlyV3EventPool | null> = {};
70
+
71
+ readonly hasConstantPriceLargeAmounts = false;
72
+ readonly needWrapNative = true;
73
+
74
+ readonly directSwapIface = new Interface(DirectSwapABI);
75
+
76
+ intervalTask?: NodeJS.Timeout;
77
+
78
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
79
+ getDexKeysWithNetwork(_.pick(SolidlyV3Config, ['SolidlyV3']));
80
+
81
+ logger: Logger;
82
+
83
+ private stateMultiContract: Contract;
84
+
85
+ private notExistingPoolSetKey: string;
86
+
87
+ private readonly factory: SolidlyV3Factory;
88
+
89
+ constructor(
90
+ protected network: Network,
91
+ dexKey: string,
92
+ protected dexHelper: IDexHelper,
93
+ protected adapters = Adapters[network] || {},
94
+ readonly poolIface = new Interface(SolidlyV3PoolABI),
95
+ protected config = SolidlyV3Config[dexKey][network],
96
+ protected poolsToPreload = PoolsToPreload[dexKey]?.[network] || [],
97
+ ) {
98
+ super(dexHelper, dexKey);
99
+ this.logger = dexHelper.getLogger(dexKey + '-' + network);
100
+ this.stateMultiContract = new this.dexHelper.web3Provider.eth.Contract(
101
+ this.config.stateMultiCallAbi !== undefined
102
+ ? this.config.stateMultiCallAbi
103
+ : (SolidlyV3StateMulticallABI as AbiItem[]),
104
+ this.config.stateMulticall,
105
+ );
106
+
107
+ // To receive revert reasons
108
+ this.dexHelper.web3Provider.eth.handleRevert = false;
109
+
110
+ // Normalize once all config addresses and use across all scenarios
111
+ this.config = this._toLowerForAllConfigAddresses();
112
+
113
+ this.factory = new SolidlyV3Factory(
114
+ dexHelper,
115
+ dexKey,
116
+ this.config.factory,
117
+ this.logger,
118
+ this.onPoolCreatedDeleteFromNonExistingSet,
119
+ );
120
+
121
+ this.notExistingPoolSetKey =
122
+ `${CACHE_PREFIX}_${network}_${dexKey}_not_existings_pool_set`.toLowerCase();
123
+ }
124
+
125
+ get supportedTickSpacings() {
126
+ return this.config.supportedTickSpacings;
127
+ }
128
+
129
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
130
+ return this.adapters[side] ? this.adapters[side] : null;
131
+ }
132
+
133
+ getPoolIdentifier(
134
+ srcAddress: Address,
135
+ destAddress: Address,
136
+ tickSpacing: bigint,
137
+ ) {
138
+ const tokenAddresses = this._sortTokens(srcAddress, destAddress).join('_');
139
+ return `${this.dexKey}_${tokenAddresses}_${tickSpacing}`;
140
+ }
141
+
142
+ async initializePricing(blockNumber: number) {
143
+ // Init listening to new pools creation
144
+ await this.factory.initialize(blockNumber);
145
+
146
+ // This is only for testing, because cold pool fetching is goes out of
147
+ // FETCH_POOL_INDENTIFIER_TIMEOUT range
148
+ await Promise.all(
149
+ this.poolsToPreload.map(async pool =>
150
+ Promise.all(
151
+ this.config.supportedTickSpacings.map(async tickSpacing =>
152
+ this.getPool(pool.token0, pool.token1, tickSpacing, blockNumber),
153
+ ),
154
+ ),
155
+ ),
156
+ );
157
+
158
+ if (!this.dexHelper.config.isSlave) {
159
+ const cleanExpiredNotExistingPoolsKeys = async () => {
160
+ const maxTimestamp =
161
+ Date.now() - UNISWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS;
162
+ await this.dexHelper.cache.zremrangebyscore(
163
+ this.notExistingPoolSetKey,
164
+ 0,
165
+ maxTimestamp,
166
+ );
167
+ };
168
+
169
+ this.intervalTask = setInterval(
170
+ cleanExpiredNotExistingPoolsKeys.bind(this),
171
+ UNISWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS,
172
+ );
173
+ }
174
+ }
175
+
176
+ /*
177
+ * When a non existing pool is queried, it's blacklisted for an arbitrary long period in order to prevent issuing too many rpc calls
178
+ * Once the pool is created, it gets immediately flagged
179
+ */
180
+ onPoolCreatedDeleteFromNonExistingSet: OnPoolCreatedCallback = async ({
181
+ token0,
182
+ token1,
183
+ tickSpacing,
184
+ }) => {
185
+ const logPrefix = '[onPoolCreatedDeleteFromNonExistingSet]';
186
+ const [_token0, _token1] = this._sortTokens(token0, token1);
187
+ const poolKey = `${_token0}_${_token1}_${tickSpacing}`;
188
+
189
+ // consider doing it only from master pool for less calls to distant cache
190
+
191
+ // delete entry locally to let local instance discover the pool
192
+ delete this.eventPools[
193
+ this.getPoolIdentifier(_token0, _token1, tickSpacing)
194
+ ];
195
+
196
+ try {
197
+ this.logger.info(
198
+ `${logPrefix} delete pool from not existing set=${this.notExistingPoolSetKey}; key=${poolKey}`,
199
+ );
200
+ // delete pool record from set
201
+ const result = await this.dexHelper.cache.zrem(
202
+ this.notExistingPoolSetKey,
203
+ [poolKey],
204
+ );
205
+ this.logger.info(
206
+ `${logPrefix} delete pool from not existing set=${this.notExistingPoolSetKey}; key=${poolKey}; result: ${result}`,
207
+ );
208
+ } catch (error) {
209
+ this.logger.error(
210
+ `${logPrefix} ERROR: failed to delete pool from set: set=${this.notExistingPoolSetKey}; key=${poolKey}`,
211
+ error,
212
+ );
213
+ }
214
+ };
215
+
216
+ async getPool(
217
+ srcAddress: Address,
218
+ destAddress: Address,
219
+ tickSpacing: bigint,
220
+ blockNumber: number,
221
+ ): Promise<SolidlyV3EventPool | null> {
222
+ let pool = this.eventPools[
223
+ this.getPoolIdentifier(srcAddress, destAddress, tickSpacing)
224
+ ] as SolidlyV3EventPool | null | undefined;
225
+
226
+ if (pool === null) return null;
227
+
228
+ if (pool) {
229
+ if (!pool.initFailed) {
230
+ return pool;
231
+ } else {
232
+ // if init failed then prefer to early return pool with empty state to fallback to rpc call
233
+ if (
234
+ ++pool.initRetryAttemptCount % this.config.initRetryFrequency !==
235
+ 0
236
+ ) {
237
+ return pool;
238
+ }
239
+ // else pursue with re-try initialization
240
+ }
241
+ }
242
+
243
+ const [token0, token1] = this._sortTokens(srcAddress, destAddress);
244
+
245
+ const key = `${token0}_${token1}_${tickSpacing}`.toLowerCase();
246
+
247
+ if (!pool) {
248
+ const notExistingPoolScore = await this.dexHelper.cache.zscore(
249
+ this.notExistingPoolSetKey,
250
+ key,
251
+ );
252
+
253
+ const poolDoesNotExist = notExistingPoolScore !== null;
254
+
255
+ if (poolDoesNotExist) {
256
+ this.eventPools[
257
+ this.getPoolIdentifier(srcAddress, destAddress, tickSpacing)
258
+ ] = null;
259
+ return null;
260
+ }
261
+ }
262
+
263
+ this.logger.trace(`starting to listen to new pool: ${key}`);
264
+ pool =
265
+ pool ||
266
+ new SolidlyV3EventPool(
267
+ this.dexHelper,
268
+ this.dexKey,
269
+ this.stateMultiContract,
270
+ this.config.decodeStateMultiCallResultWithRelativeBitmaps,
271
+ this.erc20Interface,
272
+ this.config.factory,
273
+ tickSpacing,
274
+ token0,
275
+ token1,
276
+ this.logger,
277
+ this.cacheStateKey,
278
+ this.config.initHash,
279
+ );
280
+
281
+ try {
282
+ await pool.initialize(blockNumber, {
283
+ initCallback: (state: DeepReadonly<PoolState>) => {
284
+ //really hacky, we need to push poolAddress so that we subscribeToLogs in StatefulEventSubscriber
285
+ pool!.addressesSubscribed[0] = state.pool;
286
+ pool!.poolAddress = state.pool;
287
+ pool!.initFailed = false;
288
+ pool!.initRetryAttemptCount = 0;
289
+ },
290
+ });
291
+ } catch (e) {
292
+ if (e instanceof Error && e.message.endsWith('Pool does not exist')) {
293
+ // no need to await we want the set to have the pool key but it's not blocking
294
+ this.dexHelper.cache.zadd(
295
+ this.notExistingPoolSetKey,
296
+ [Date.now(), key],
297
+ 'NX',
298
+ );
299
+
300
+ // Pool does not exist for this feeCode, so we can set it to null
301
+ // to prevent more requests for this pool
302
+ pool = null;
303
+ this.logger.trace(
304
+ `${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${tickSpacing} not found`,
305
+ e,
306
+ );
307
+ } else {
308
+ // on unknown error mark as failed and increase retryCount for retry init strategy
309
+ // note: state would be null by default which allows to fallback
310
+ this.logger.warn(
311
+ `${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${tickSpacing} pool fallback to rpc and retry every ${this.config.initRetryFrequency} times, initRetryAttemptCount=${pool.initRetryAttemptCount}`,
312
+ e,
313
+ );
314
+ pool.initFailed = true;
315
+ }
316
+ }
317
+
318
+ if (pool !== null) {
319
+ const allEventPools = Object.values(this.eventPools);
320
+ this.logger.info(
321
+ `starting to listen to new non-null pool: ${key}. Already following ${allEventPools
322
+ // Not that I like this reduce, but since it is done only on initialization, expect this to be ok
323
+ .reduce(
324
+ (acc, curr) => (curr !== null ? ++acc : acc),
325
+ 0,
326
+ )} non-null pools or ${allEventPools.length} total pools`,
327
+ );
328
+ }
329
+
330
+ this.eventPools[
331
+ this.getPoolIdentifier(srcAddress, destAddress, tickSpacing)
332
+ ] = pool;
333
+ return pool;
334
+ }
335
+
336
+ async addMasterPool(poolKey: string, blockNumber: number): Promise<boolean> {
337
+ const _pairs = await this.dexHelper.cache.hget(
338
+ PoolsRegistryHashKey,
339
+ `${this.cacheStateKey}_${poolKey}`,
340
+ );
341
+ if (!_pairs) {
342
+ this.logger.warn(
343
+ `did not find poolConfig in for key ${PoolsRegistryHashKey} ${this.cacheStateKey}_${poolKey}`,
344
+ );
345
+ return false;
346
+ }
347
+
348
+ const poolInfo: PoolPairsInfo = JSON.parse(_pairs);
349
+
350
+ const pool = await this.getPool(
351
+ poolInfo.token0,
352
+ poolInfo.token1,
353
+ BigInt(poolInfo.fee),
354
+ blockNumber,
355
+ );
356
+
357
+ if (!pool) {
358
+ return false;
359
+ }
360
+
361
+ return true;
362
+ }
363
+
364
+ async getPoolIdentifiers(
365
+ srcToken: Token,
366
+ destToken: Token,
367
+ side: SwapSide,
368
+ blockNumber: number,
369
+ ): Promise<string[]> {
370
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
371
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
372
+
373
+ const [_srcAddress, _destAddress] = this._getLoweredAddresses(
374
+ _srcToken,
375
+ _destToken,
376
+ );
377
+
378
+ if (_srcAddress === _destAddress) return [];
379
+
380
+ const pools = (
381
+ await Promise.all(
382
+ this.supportedTickSpacings.map(async tickSpacing =>
383
+ this.getPool(_srcAddress, _destAddress, tickSpacing, blockNumber),
384
+ ),
385
+ )
386
+ ).filter(pool => pool);
387
+
388
+ if (pools.length === 0) return [];
389
+
390
+ return pools.map(pool =>
391
+ this.getPoolIdentifier(_srcAddress, _destAddress, pool!.tickSpacing),
392
+ );
393
+ }
394
+
395
+ async getPricesVolume(
396
+ srcToken: Token,
397
+ destToken: Token,
398
+ amounts: bigint[],
399
+ side: SwapSide,
400
+ blockNumber: number,
401
+ limitPools?: string[],
402
+ ): Promise<null | ExchangePrices<SolidlyV3Data>> {
403
+ try {
404
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
405
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
406
+
407
+ const [_srcAddress, _destAddress] = this._getLoweredAddresses(
408
+ _srcToken,
409
+ _destToken,
410
+ );
411
+
412
+ if (_srcAddress === _destAddress) return null;
413
+
414
+ let selectedPools: SolidlyV3EventPool[] = [];
415
+
416
+ if (!limitPools) {
417
+ selectedPools = (
418
+ await Promise.all(
419
+ this.supportedTickSpacings.map(async tickSpacing => {
420
+ const locallyFoundPool =
421
+ this.eventPools[
422
+ this.getPoolIdentifier(_srcAddress, _destAddress, tickSpacing)
423
+ ];
424
+ if (locallyFoundPool) return locallyFoundPool;
425
+
426
+ const newlyFetchedPool = await this.getPool(
427
+ _srcAddress,
428
+ _destAddress,
429
+ tickSpacing,
430
+ blockNumber,
431
+ );
432
+ return newlyFetchedPool;
433
+ }),
434
+ )
435
+ ).filter(isTruthy);
436
+ } else {
437
+ const pairIdentifierWithoutFee = this.getPoolIdentifier(
438
+ _srcAddress,
439
+ _destAddress,
440
+ 0n,
441
+ // Trim from 0 fee postfix, so it become comparable
442
+ ).slice(0, -1);
443
+
444
+ const poolIdentifiers = limitPools.filter(identifier =>
445
+ identifier.startsWith(pairIdentifierWithoutFee),
446
+ );
447
+
448
+ selectedPools = (
449
+ await Promise.all(
450
+ poolIdentifiers.map(async identifier => {
451
+ let locallyFoundPool = this.eventPools[identifier];
452
+ if (locallyFoundPool) return locallyFoundPool;
453
+
454
+ const [, srcAddress, destAddress, tickSpacing] =
455
+ identifier.split('_');
456
+ const newlyFetchedPool = await this.getPool(
457
+ srcAddress,
458
+ destAddress,
459
+ BigInt(tickSpacing),
460
+ blockNumber,
461
+ );
462
+ return newlyFetchedPool;
463
+ }),
464
+ )
465
+ ).filter(isTruthy);
466
+ }
467
+
468
+ if (selectedPools.length === 0) return null;
469
+
470
+ const poolsToUse = selectedPools.reduce(
471
+ (acc, pool) => {
472
+ let state = pool.getState(blockNumber);
473
+ if (state === null) {
474
+ throw new Error('Unable to retrieve pool state.');
475
+ } else {
476
+ acc.poolWithState.push(pool);
477
+ }
478
+ return acc;
479
+ },
480
+ {
481
+ poolWithState: [] as SolidlyV3EventPool[],
482
+ poolWithoutState: [] as SolidlyV3EventPool[],
483
+ },
484
+ );
485
+
486
+ const states = poolsToUse.poolWithState.map(
487
+ p => p.getState(blockNumber)!,
488
+ );
489
+
490
+ const unitAmount = getBigIntPow(
491
+ side == SwapSide.SELL ? _srcToken.decimals : _destToken.decimals,
492
+ );
493
+
494
+ const _amounts = [...amounts.slice(1)];
495
+
496
+ const [token0] = this._sortTokens(_srcAddress, _destAddress);
497
+
498
+ const zeroForOne = token0 === _srcAddress ? true : false;
499
+
500
+ const result = await Promise.all(
501
+ poolsToUse.poolWithState.map(async (pool, i) => {
502
+ const state = states[i];
503
+
504
+ if (state.liquidity <= 0n) {
505
+ if (state.liquidity < 0) {
506
+ this.logger.error(
507
+ `${this.dexKey}-${this.network}: ${pool.poolAddress} pool has negative liquidity: ${state.liquidity}. Find with key: ${pool.mapKey}`,
508
+ );
509
+ }
510
+ this.logger.trace(`pool have 0 liquidity`);
511
+ return null;
512
+ }
513
+
514
+ const balanceDestToken =
515
+ _destAddress === pool.token0 ? state.balance0 : state.balance1;
516
+
517
+ const unitResult = this._getOutputs(
518
+ state,
519
+ [unitAmount],
520
+ zeroForOne,
521
+ side,
522
+ balanceDestToken,
523
+ );
524
+ const pricesResult = this._getOutputs(
525
+ state,
526
+ _amounts,
527
+ zeroForOne,
528
+ side,
529
+ balanceDestToken,
530
+ );
531
+
532
+ if (!unitResult || !pricesResult) {
533
+ this.logger.debug('Prices or unit is not calculated');
534
+ return null;
535
+ }
536
+
537
+ const prices = [0n, ...pricesResult.outputs];
538
+ const gasCost = [
539
+ 0,
540
+ ...pricesResult.outputs.map((p, index) => {
541
+ if (p == 0n) {
542
+ return 0;
543
+ } else {
544
+ return (
545
+ UNISWAPV3_POOL_SEARCH_OVERHEAD +
546
+ UNISWAPV3_TICK_BASE_OVERHEAD +
547
+ pricesResult.tickCounts[index] * UNISWAPV3_TICK_GAS_COST
548
+ );
549
+ }
550
+ }),
551
+ ];
552
+ return {
553
+ unit: unitResult.outputs[0],
554
+ prices,
555
+ data: {
556
+ zeroForOne,
557
+ poolAddress: pool.poolAddress,
558
+ },
559
+ poolIdentifier: this.getPoolIdentifier(
560
+ pool.token0,
561
+ pool.token1,
562
+ pool.tickSpacing,
563
+ ),
564
+ exchange: this.dexKey,
565
+ gasCost: gasCost,
566
+ poolAddresses: [pool.poolAddress],
567
+ };
568
+ }),
569
+ );
570
+
571
+ const notNullResult = result.filter(
572
+ res => res !== null,
573
+ ) as ExchangePrices<SolidlyV3Data>;
574
+
575
+ return notNullResult;
576
+ } catch (e) {
577
+ this.logger.error(
578
+ `Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
579
+ destToken.symbol || destToken.address
580
+ }, ${side}:`,
581
+ e,
582
+ );
583
+ return null;
584
+ }
585
+ }
586
+
587
+ getAdapterParam(
588
+ srcToken: string,
589
+ destToken: string,
590
+ srcAmount: string,
591
+ destAmount: string,
592
+ data: SolidlyV3Data,
593
+ side: SwapSide,
594
+ ): AdapterExchangeParam {
595
+ const sqrtPriceLimitX96 = data.zeroForOne
596
+ ? (TickMath.MIN_SQRT_RATIO + BigInt(1)).toString()
597
+ : (TickMath.MAX_SQRT_RATIO - BigInt(1)).toString();
598
+
599
+ const payload = this.abiCoder.encodeParameter(
600
+ {
601
+ ParentStruct: {
602
+ recipient: 'address',
603
+ zeroForOne: 'bool',
604
+ sqrtPriceLimitX96: 'uint160',
605
+ },
606
+ },
607
+ {
608
+ recipient: this.augustusAddress,
609
+ zeroForOne: data.zeroForOne,
610
+ sqrtPriceLimitX96,
611
+ },
612
+ );
613
+
614
+ return {
615
+ targetExchange: data.poolAddress,
616
+ payload,
617
+ networkFee: '0',
618
+ };
619
+ }
620
+
621
+ getCalldataGasCost(poolPrices: PoolPrices<SolidlyV3Data>): number | number[] {
622
+ const gasCost =
623
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
624
+ CALLDATA_GAS_COST.LENGTH_SMALL +
625
+ // ParentStruct header
626
+ CALLDATA_GAS_COST.OFFSET_SMALL +
627
+ // ParentStruct -> path header
628
+ CALLDATA_GAS_COST.OFFSET_SMALL +
629
+ // ParentStruct -> deadline
630
+ CALLDATA_GAS_COST.TIMESTAMP +
631
+ // ParentStruct -> path (20+3+20 = 43 = 32+11 bytes)
632
+ CALLDATA_GAS_COST.LENGTH_SMALL +
633
+ CALLDATA_GAS_COST.FULL_WORD +
634
+ CALLDATA_GAS_COST.wordNonZeroBytes(11);
635
+ const arr = new Array(poolPrices.prices.length);
636
+ poolPrices.prices.forEach((p, index) => {
637
+ if (p == 0n) {
638
+ arr[index] = 0;
639
+ } else {
640
+ arr[index] = gasCost;
641
+ }
642
+ });
643
+ return arr;
644
+ }
645
+
646
+ getTokenFromAddress(address: Address): Token {
647
+ // In this Dex decimals are not used
648
+ return { address, decimals: 0 };
649
+ }
650
+
651
+ async getSimpleParam(
652
+ srcToken: string,
653
+ destToken: string,
654
+ srcAmount: string,
655
+ destAmount: string,
656
+ data: SolidlyV3Data,
657
+ side: SwapSide,
658
+ ): Promise<SimpleExchangeParam> {
659
+ const swapFunction = this.poolIface.getFunction(
660
+ 'swap(address,bool,int256,uint160)',
661
+ );
662
+
663
+ const swapFunctionParams: SolidlyV3SimpleSwapParams = {
664
+ recipient: this.augustusAddress,
665
+ zeroForOne: data.zeroForOne,
666
+ amountSpecified:
667
+ side === SwapSide.SELL
668
+ ? srcAmount.toString()
669
+ : (-destAmount).toString(),
670
+ sqrtPriceLimitX96: data.zeroForOne
671
+ ? (TickMath.MIN_SQRT_RATIO + BigInt(1)).toString()
672
+ : (TickMath.MAX_SQRT_RATIO - BigInt(1)).toString(),
673
+ };
674
+ const swapData = this.poolIface.encodeFunctionData(swapFunction, [
675
+ swapFunctionParams.recipient,
676
+ swapFunctionParams.zeroForOne,
677
+ swapFunctionParams.amountSpecified,
678
+ swapFunctionParams.sqrtPriceLimitX96,
679
+ ]);
680
+
681
+ return this.buildSimpleParamWithoutWETHConversion(
682
+ srcToken,
683
+ srcAmount,
684
+ destToken,
685
+ destAmount,
686
+ swapData,
687
+ data.poolAddress,
688
+ );
689
+ }
690
+
691
+ getDexParam(
692
+ srcToken: Address,
693
+ destToken: Address,
694
+ srcAmount: NumberAsString,
695
+ destAmount: NumberAsString,
696
+ recipient: Address,
697
+ data: SolidlyV3Data,
698
+ side: SwapSide,
699
+ ): DexExchangeParam {
700
+ const swapFunction = this.poolIface.getFunction(
701
+ 'swap(address,bool,int256,uint160)',
702
+ );
703
+
704
+ const swapFunctionParams: SolidlyV3SimpleSwapParams = {
705
+ recipient,
706
+ zeroForOne: data.zeroForOne,
707
+ amountSpecified:
708
+ side === SwapSide.SELL
709
+ ? srcAmount.toString()
710
+ : (-destAmount).toString(),
711
+ sqrtPriceLimitX96: data.zeroForOne
712
+ ? (TickMath.MIN_SQRT_RATIO + BigInt(1)).toString()
713
+ : (TickMath.MAX_SQRT_RATIO - BigInt(1)).toString(),
714
+ };
715
+ const swapData = this.poolIface.encodeFunctionData(swapFunction, [
716
+ swapFunctionParams.recipient,
717
+ swapFunctionParams.zeroForOne,
718
+ swapFunctionParams.amountSpecified,
719
+ swapFunctionParams.sqrtPriceLimitX96,
720
+ ]);
721
+
722
+ return {
723
+ needWrapNative: this.needWrapNative,
724
+ dexFuncHasRecipient: true,
725
+ exchangeData: swapData,
726
+ targetExchange: data.poolAddress,
727
+ returnAmountPos: undefined,
728
+ };
729
+ }
730
+
731
+ async getTopPoolsForToken(
732
+ tokenAddress: Address,
733
+ limit: number,
734
+ ): Promise<PoolLiquidity[]> {
735
+ const _tokenAddress = tokenAddress.toLowerCase();
736
+
737
+ const res = await this._querySubgraph(
738
+ `query ($token: Bytes!, $count: Int) {
739
+ pools0: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token0: $token, liquidity_gt: "0"}) {
740
+ id
741
+ token0 {
742
+ id
743
+ decimals
744
+ }
745
+ token1 {
746
+ id
747
+ decimals
748
+ }
749
+ totalValueLockedUSD
750
+ }
751
+ pools1: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token1: $token, liquidity_gt: "0"}) {
752
+ id
753
+ token0 {
754
+ id
755
+ decimals
756
+ }
757
+ token1 {
758
+ id
759
+ decimals
760
+ }
761
+ totalValueLockedUSD
762
+ }
763
+ }`,
764
+ {
765
+ token: _tokenAddress,
766
+ count: limit,
767
+ },
768
+ );
769
+
770
+ if (!(res && res.pools0 && res.pools1)) {
771
+ this.logger.error(
772
+ `Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`,
773
+ );
774
+ return [];
775
+ }
776
+
777
+ const pools0 = _.map(res.pools0, pool => ({
778
+ exchange: this.dexKey,
779
+ address: pool.id.toLowerCase(),
780
+ connectorTokens: [
781
+ {
782
+ address: pool.token1.id.toLowerCase(),
783
+ decimals: parseInt(pool.token1.decimals),
784
+ },
785
+ ],
786
+ liquidityUSD:
787
+ parseFloat(pool.totalValueLockedUSD) * UNISWAPV3_EFFICIENCY_FACTOR,
788
+ }));
789
+
790
+ const pools1 = _.map(res.pools1, pool => ({
791
+ exchange: this.dexKey,
792
+ address: pool.id.toLowerCase(),
793
+ connectorTokens: [
794
+ {
795
+ address: pool.token0.id.toLowerCase(),
796
+ decimals: parseInt(pool.token0.decimals),
797
+ },
798
+ ],
799
+ liquidityUSD:
800
+ parseFloat(pool.totalValueLockedUSD) * UNISWAPV3_EFFICIENCY_FACTOR,
801
+ }));
802
+
803
+ const pools = _.slice(
804
+ _.sortBy(_.concat(pools0, pools1), [pool => -1 * pool.liquidityUSD]),
805
+ 0,
806
+ limit,
807
+ );
808
+ return pools;
809
+ }
810
+
811
+ private async _getPoolsFromIdentifiers(
812
+ poolIdentifiers: string[],
813
+ blockNumber: number,
814
+ ): Promise<SolidlyV3EventPool[]> {
815
+ const pools = await Promise.all(
816
+ poolIdentifiers.map(async identifier => {
817
+ const [, srcAddress, destAddress, fee] = identifier.split('_');
818
+ return this.getPool(srcAddress, destAddress, BigInt(fee), blockNumber);
819
+ }),
820
+ );
821
+ return pools.filter(pool => pool) as SolidlyV3EventPool[];
822
+ }
823
+
824
+ private _getLoweredAddresses(srcToken: Token, destToken: Token) {
825
+ return [srcToken.address.toLowerCase(), destToken.address.toLowerCase()];
826
+ }
827
+
828
+ private _sortTokens(srcAddress: Address, destAddress: Address) {
829
+ return [srcAddress, destAddress].sort((a, b) => (a < b ? -1 : 1));
830
+ }
831
+
832
+ private _toLowerForAllConfigAddresses() {
833
+ // If new config property will be added, the TS will throw compile error
834
+ const newConfig: DexParams = {
835
+ factory: this.config.factory.toLowerCase(),
836
+ supportedTickSpacings: this.config.supportedTickSpacings,
837
+ stateMulticall: this.config.stateMulticall.toLowerCase(),
838
+ chunksCount: this.config.chunksCount,
839
+ initRetryFrequency: this.config.initRetryFrequency,
840
+ deployer: this.config.deployer?.toLowerCase(),
841
+ initHash: this.config.initHash,
842
+ subgraphURL: this.config.subgraphURL,
843
+ stateMultiCallAbi: this.config.stateMultiCallAbi,
844
+ decodeStateMultiCallResultWithRelativeBitmaps:
845
+ this.config.decodeStateMultiCallResultWithRelativeBitmaps,
846
+ };
847
+ return newConfig;
848
+ }
849
+
850
+ private _getOutputs(
851
+ state: DeepReadonly<PoolState>,
852
+ amounts: bigint[],
853
+ zeroForOne: boolean,
854
+ side: SwapSide,
855
+ destTokenBalance: bigint,
856
+ ): OutputResult | null {
857
+ try {
858
+ const outputsResult = uniswapV3Math.queryOutputs(
859
+ state,
860
+ amounts,
861
+ zeroForOne,
862
+ side,
863
+ );
864
+
865
+ if (side === SwapSide.SELL) {
866
+ if (outputsResult.outputs[0] > destTokenBalance) {
867
+ return null;
868
+ }
869
+
870
+ for (let i = 0; i < outputsResult.outputs.length; i++) {
871
+ if (outputsResult.outputs[i] > destTokenBalance) {
872
+ outputsResult.outputs[i] = 0n;
873
+ outputsResult.tickCounts[i] = 0;
874
+ }
875
+ }
876
+ } else {
877
+ if (amounts[0] > destTokenBalance) {
878
+ return null;
879
+ }
880
+
881
+ // This may be improved by first checking outputs and requesting outputs
882
+ // only for amounts that makes more sense, but I don't think this is really
883
+ // important now
884
+ for (let i = 0; i < amounts.length; i++) {
885
+ if (amounts[i] > destTokenBalance) {
886
+ outputsResult.outputs[i] = 0n;
887
+ outputsResult.tickCounts[i] = 0;
888
+ }
889
+ }
890
+ }
891
+
892
+ return outputsResult;
893
+ } catch (e) {
894
+ this.logger.debug(
895
+ `${this.dexKey}: received error in _getOutputs while calculating outputs`,
896
+ e,
897
+ );
898
+ return null;
899
+ }
900
+ }
901
+
902
+ private async _querySubgraph(
903
+ query: string,
904
+ variables: Object,
905
+ timeout = 30000,
906
+ ) {
907
+ try {
908
+ const res = await this.dexHelper.httpRequest.post(
909
+ this.config.subgraphURL,
910
+ { query, variables },
911
+ undefined,
912
+ { timeout: timeout },
913
+ );
914
+ return res.data;
915
+ } catch (e) {
916
+ this.logger.error(`${this.dexKey}: can not query subgraph: `, e);
917
+ return {};
918
+ }
919
+ }
920
+
921
+ private _encodePath(
922
+ path: {
923
+ tokenIn: Address;
924
+ tokenOut: Address;
925
+ fee: NumberAsString;
926
+ }[],
927
+ side: SwapSide,
928
+ ): string {
929
+ if (path.length === 0) {
930
+ this.logger.error(
931
+ `${this.dexKey}: Received invalid path=${path} for side=${side} to encode`,
932
+ );
933
+ return '0x';
934
+ }
935
+
936
+ const { _path, types } = path.reduce(
937
+ (
938
+ { _path, types }: { _path: string[]; types: string[] },
939
+ curr,
940
+ index,
941
+ ): { _path: string[]; types: string[] } => {
942
+ if (index === 0) {
943
+ return {
944
+ types: ['address', 'uint24', 'address'],
945
+ _path: [curr.tokenIn, curr.fee, curr.tokenOut],
946
+ };
947
+ } else {
948
+ return {
949
+ types: [...types, 'uint24', 'address'],
950
+ _path: [..._path, curr.fee, curr.tokenOut],
951
+ };
952
+ }
953
+ },
954
+ { _path: [], types: [] },
955
+ );
956
+
957
+ return side === SwapSide.BUY
958
+ ? pack(types.reverse(), _path.reverse())
959
+ : pack(types, _path);
960
+ }
961
+
962
+ releaseResources() {
963
+ if (this.intervalTask !== undefined) {
964
+ clearInterval(this.intervalTask);
965
+ this.intervalTask = undefined;
966
+ }
967
+ }
968
+ }