@paraswap/dex-lib 2.42.3 → 2.42.4-baseswap

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 (99) hide show
  1. package/build/dex/balancer-v1/balancer-v1.js +21 -10
  2. package/build/dex/balancer-v1/balancer-v1.js.map +1 -1
  3. package/build/dex/balancer-v1/config.d.ts +2 -1
  4. package/build/dex/balancer-v1/config.js +3 -2
  5. package/build/dex/balancer-v1/config.js.map +1 -1
  6. package/build/dex/baseswap-v3/baseswap-v3-factory.d.ts +26 -0
  7. package/build/dex/baseswap-v3/baseswap-v3-factory.js +44 -0
  8. package/build/dex/baseswap-v3/baseswap-v3-factory.js.map +1 -0
  9. package/build/dex/baseswap-v3/baseswap-v3-pool.d.ts +46 -0
  10. package/build/dex/baseswap-v3/baseswap-v3-pool.js +312 -0
  11. package/build/dex/baseswap-v3/baseswap-v3-pool.js.map +1 -0
  12. package/build/dex/baseswap-v3/baseswap-v3.d.ts +71 -0
  13. package/build/dex/baseswap-v3/baseswap-v3.js +752 -0
  14. package/build/dex/baseswap-v3/baseswap-v3.js.map +1 -0
  15. package/build/dex/baseswap-v3/config.d.ts +9 -0
  16. package/build/dex/baseswap-v3/config.js +48 -0
  17. package/build/dex/baseswap-v3/config.js.map +1 -0
  18. package/build/dex/baseswap-v3/constants.d.ts +28 -0
  19. package/build/dex/baseswap-v3/constants.js +35 -0
  20. package/build/dex/baseswap-v3/constants.js.map +1 -0
  21. package/build/dex/baseswap-v3/contract-math/BitMath.d.ts +4 -0
  22. package/build/dex/baseswap-v3/contract-math/BitMath.js +93 -0
  23. package/build/dex/baseswap-v3/contract-math/BitMath.js.map +1 -0
  24. package/build/dex/baseswap-v3/contract-math/FixedPoint128.d.ts +3 -0
  25. package/build/dex/baseswap-v3/contract-math/FixedPoint128.js +8 -0
  26. package/build/dex/baseswap-v3/contract-math/FixedPoint128.js.map +1 -0
  27. package/build/dex/baseswap-v3/contract-math/FixedPoint96.d.ts +4 -0
  28. package/build/dex/baseswap-v3/contract-math/FixedPoint96.js +9 -0
  29. package/build/dex/baseswap-v3/contract-math/FixedPoint96.js.map +1 -0
  30. package/build/dex/baseswap-v3/contract-math/FullMath.d.ts +4 -0
  31. package/build/dex/baseswap-v3/contract-math/FullMath.js +19 -0
  32. package/build/dex/baseswap-v3/contract-math/FullMath.js.map +1 -0
  33. package/build/dex/baseswap-v3/contract-math/LiquidityMath.d.ts +3 -0
  34. package/build/dex/baseswap-v3/contract-math/LiquidityMath.js +22 -0
  35. package/build/dex/baseswap-v3/contract-math/LiquidityMath.js.map +1 -0
  36. package/build/dex/baseswap-v3/contract-math/Oracle.d.ts +10 -0
  37. package/build/dex/baseswap-v3/contract-math/Oracle.js +133 -0
  38. package/build/dex/baseswap-v3/contract-math/Oracle.js.map +1 -0
  39. package/build/dex/baseswap-v3/contract-math/SqrtPriceMath.d.ts +10 -0
  40. package/build/dex/baseswap-v3/contract-math/SqrtPriceMath.js +91 -0
  41. package/build/dex/baseswap-v3/contract-math/SqrtPriceMath.js.map +1 -0
  42. package/build/dex/baseswap-v3/contract-math/SwapMath.d.ts +8 -0
  43. package/build/dex/baseswap-v3/contract-math/SwapMath.js +70 -0
  44. package/build/dex/baseswap-v3/contract-math/SwapMath.js.map +1 -0
  45. package/build/dex/baseswap-v3/contract-math/Tick.d.ts +7 -0
  46. package/build/dex/baseswap-v3/contract-math/Tick.js +45 -0
  47. package/build/dex/baseswap-v3/contract-math/Tick.js.map +1 -0
  48. package/build/dex/baseswap-v3/contract-math/TickBitMap.d.ts +7 -0
  49. package/build/dex/baseswap-v3/contract-math/TickBitMap.js +84 -0
  50. package/build/dex/baseswap-v3/contract-math/TickBitMap.js.map +1 -0
  51. package/build/dex/baseswap-v3/contract-math/TickMath.d.ts +8 -0
  52. package/build/dex/baseswap-v3/contract-math/TickMath.js +162 -0
  53. package/build/dex/baseswap-v3/contract-math/TickMath.js.map +1 -0
  54. package/build/dex/baseswap-v3/contract-math/UnsafeMath.d.ts +3 -0
  55. package/build/dex/baseswap-v3/contract-math/UnsafeMath.js +10 -0
  56. package/build/dex/baseswap-v3/contract-math/UnsafeMath.js.map +1 -0
  57. package/build/dex/baseswap-v3/contract-math/uniswap-v3-math.d.ts +37 -0
  58. package/build/dex/baseswap-v3/contract-math/uniswap-v3-math.js +393 -0
  59. package/build/dex/baseswap-v3/contract-math/uniswap-v3-math.js.map +1 -0
  60. package/build/dex/baseswap-v3/contract-math/utils.d.ts +7 -0
  61. package/build/dex/baseswap-v3/contract-math/utils.js +42 -0
  62. package/build/dex/baseswap-v3/contract-math/utils.js.map +1 -0
  63. package/build/dex/baseswap-v3/types.d.ts +164 -0
  64. package/build/dex/baseswap-v3/types.js +9 -0
  65. package/build/dex/baseswap-v3/types.js.map +1 -0
  66. package/build/dex/baseswap-v3/utils.d.ts +6 -0
  67. package/build/dex/baseswap-v3/utils.js +65 -0
  68. package/build/dex/baseswap-v3/utils.js.map +1 -0
  69. package/build/dex/index.js +2 -0
  70. package/build/dex/index.js.map +1 -1
  71. package/package.json +1 -1
  72. package/src/dex/balancer-v1/balancer-v1.ts +32 -13
  73. package/src/dex/balancer-v1/config.ts +2 -1
  74. package/src/dex/baseswap-v3/baseswap-v3-e2e.test.ts +129 -0
  75. package/src/dex/baseswap-v3/baseswap-v3-events.test.ts +141 -0
  76. package/src/dex/baseswap-v3/baseswap-v3-factory.ts +73 -0
  77. package/src/dex/baseswap-v3/baseswap-v3-integration.test.ts +472 -0
  78. package/src/dex/baseswap-v3/baseswap-v3-pool.ts +519 -0
  79. package/src/dex/baseswap-v3/baseswap-v3.ts +1243 -0
  80. package/src/dex/baseswap-v3/config.ts +53 -0
  81. package/src/dex/baseswap-v3/constants.ts +41 -0
  82. package/src/dex/baseswap-v3/contract-math/BitMath.ts +90 -0
  83. package/src/dex/baseswap-v3/contract-math/FixedPoint128.ts +3 -0
  84. package/src/dex/baseswap-v3/contract-math/FixedPoint96.ts +4 -0
  85. package/src/dex/baseswap-v3/contract-math/FullMath.ts +30 -0
  86. package/src/dex/baseswap-v3/contract-math/LiquidityMath.ts +17 -0
  87. package/src/dex/baseswap-v3/contract-math/Oracle.ts +226 -0
  88. package/src/dex/baseswap-v3/contract-math/SqrtPriceMath.ts +226 -0
  89. package/src/dex/baseswap-v3/contract-math/SwapMath.ts +139 -0
  90. package/src/dex/baseswap-v3/contract-math/Tick.ts +82 -0
  91. package/src/dex/baseswap-v3/contract-math/TickBitMap.ts +123 -0
  92. package/src/dex/baseswap-v3/contract-math/TickMath.ts +211 -0
  93. package/src/dex/baseswap-v3/contract-math/UnsafeMath.ts +5 -0
  94. package/src/dex/baseswap-v3/contract-math/uniswap-v3-math.ts +666 -0
  95. package/src/dex/baseswap-v3/contract-math/utils.ts +55 -0
  96. package/src/dex/baseswap-v3/types.ts +191 -0
  97. package/src/dex/baseswap-v3/utils.ts +83 -0
  98. package/src/dex/index.ts +2 -0
  99. package/tests/constants-e2e.ts +1 -1
@@ -0,0 +1,1243 @@
1
+ import { defaultAbiCoder, Interface } from '@ethersproject/abi';
2
+ import _ from 'lodash';
3
+ import { pack } from '@ethersproject/solidity';
4
+ import {
5
+ AdapterExchangeParam,
6
+ Address,
7
+ ExchangePrices,
8
+ ExchangeTxInfo,
9
+ Logger,
10
+ NumberAsString,
11
+ PoolLiquidity,
12
+ PoolPrices,
13
+ PreprocessTransactionOptions,
14
+ SimpleExchangeParam,
15
+ Token,
16
+ TxInfo,
17
+ } from '../../types';
18
+ import { CACHE_PREFIX, Network, SwapSide } from '../../constants';
19
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
20
+ import {
21
+ getBigIntPow,
22
+ getDexKeysWithNetwork,
23
+ interpolate,
24
+ isTruthy,
25
+ uuidToBytes16,
26
+ } from '../../utils';
27
+ import { IDex } from '../idex';
28
+ import { IDexHelper } from '../../dex-helper/idex-helper';
29
+ import {
30
+ DexParams,
31
+ OutputResult,
32
+ PoolState,
33
+ UniswapV3Data,
34
+ UniswapV3Functions,
35
+ UniswapV3Param,
36
+ UniswapV3SimpleSwapParams,
37
+ } from './types';
38
+ import {
39
+ getLocalDeadlineAsFriendlyPlaceholder,
40
+ SimpleExchange,
41
+ } from '../simple-exchange';
42
+ import { Adapters, PoolsToPreload, BaseswapV3Config } from './config';
43
+ import { BaseswapV3EventPool } from './baseswap-v3-pool';
44
+ import UniswapV3RouterABI from '../../abi/uniswap-v3/UniswapV3Router.abi.json';
45
+ import UniswapV3QuoterV2ABI from '../../abi/uniswap-v3/UniswapV3QuoterV2.abi.json';
46
+ import UniswapV3MultiABI from '../../abi/uniswap-v3/UniswapMulti.abi.json';
47
+ import DirectSwapABI from '../../abi/DirectSwap.json';
48
+ import UniswapV3StateMulticallABI from '../../abi/uniswap-v3/UniswapV3StateMulticall.abi.json';
49
+ import {
50
+ DirectMethods,
51
+ UNISWAPV3_EFFICIENCY_FACTOR,
52
+ UNISWAPV3_POOL_SEARCH_OVERHEAD,
53
+ UNISWAPV3_TICK_BASE_OVERHEAD,
54
+ UNISWAPV3_TICK_GAS_COST,
55
+ } from './constants';
56
+ import { assert, DeepReadonly } from 'ts-essentials';
57
+ import { uniswapV3Math } from './contract-math/uniswap-v3-math';
58
+ import { Contract } from 'web3-eth-contract';
59
+ import { AbiItem } from 'web3-utils';
60
+ import { BalanceRequest, getBalances } from '../../lib/tokens/balancer-fetcher';
61
+ import {
62
+ AssetType,
63
+ DEFAULT_ID_ERC20,
64
+ DEFAULT_ID_ERC20_AS_STRING,
65
+ } from '../../lib/tokens/types';
66
+ import { OptimalSwapExchange } from '@paraswap/core';
67
+ import {
68
+ OnPoolCreatedCallback,
69
+ BaseswapV3Factory,
70
+ } from './baseswap-v3-factory';
71
+
72
+ type PoolPairsInfo = {
73
+ token0: Address;
74
+ token1: Address;
75
+ fee: string;
76
+ };
77
+
78
+ const BASESWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS = 3 * 24 * 60 * 60 * 1000; // 3 days
79
+ const BASESWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS = 24 * 60 * 60 * 1000; // Once in a day
80
+ const BASESWAPV3_QUOTE_GASLIMIT = 200_000;
81
+
82
+ export class BaseswapV3
83
+ extends SimpleExchange
84
+ implements IDex<UniswapV3Data, UniswapV3Param>
85
+ {
86
+ private readonly factory: BaseswapV3Factory;
87
+ readonly isFeeOnTransferSupported: boolean = false;
88
+ readonly eventPools: Record<string, BaseswapV3EventPool | null> = {};
89
+
90
+ readonly hasConstantPriceLargeAmounts = false;
91
+ readonly needWrapNative = true;
92
+
93
+ readonly directSwapIface = new Interface(DirectSwapABI);
94
+
95
+ intervalTask?: NodeJS.Timeout;
96
+
97
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
98
+ getDexKeysWithNetwork(_.pick(BaseswapV3Config, ['BaseswapV3']));
99
+
100
+ logger: Logger;
101
+
102
+ private uniswapMulti: Contract;
103
+ private stateMultiContract: Contract;
104
+
105
+ private notExistingPoolSetKey: string;
106
+
107
+ constructor(
108
+ protected network: Network,
109
+ dexKey: string,
110
+ protected dexHelper: IDexHelper,
111
+ protected adapters = Adapters[network] || {},
112
+ readonly routerIface = new Interface(UniswapV3RouterABI),
113
+ readonly quoterIface = new Interface(UniswapV3QuoterV2ABI),
114
+ protected config = BaseswapV3Config[dexKey][network],
115
+ protected poolsToPreload = PoolsToPreload[dexKey]?.[network] || [],
116
+ ) {
117
+ super(dexHelper, dexKey);
118
+ this.logger = dexHelper.getLogger(dexKey + '-' + network);
119
+ this.uniswapMulti = new this.dexHelper.web3Provider.eth.Contract(
120
+ UniswapV3MultiABI as AbiItem[],
121
+ this.config.uniswapMulticall,
122
+ );
123
+ this.stateMultiContract = new this.dexHelper.web3Provider.eth.Contract(
124
+ this.config.stateMultiCallAbi !== undefined
125
+ ? this.config.stateMultiCallAbi
126
+ : (UniswapV3StateMulticallABI as AbiItem[]),
127
+ this.config.stateMulticall,
128
+ );
129
+
130
+ // To receive revert reasons
131
+ this.dexHelper.web3Provider.eth.handleRevert = false;
132
+
133
+ // Normalize once all config addresses and use across all scenarios
134
+ this.config = this._toLowerForAllConfigAddresses();
135
+
136
+ this.notExistingPoolSetKey =
137
+ `${CACHE_PREFIX}_${network}_${dexKey}_not_existings_pool_set`.toLowerCase();
138
+
139
+ this.factory = new BaseswapV3Factory(
140
+ dexHelper,
141
+ dexKey,
142
+ this.config.factory,
143
+ this.logger,
144
+ this.onPoolCreatedDeleteFromNonExistingSet,
145
+ );
146
+ }
147
+
148
+ get supportedFees() {
149
+ return this.config.supportedFees;
150
+ }
151
+
152
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
153
+ return this.adapters[side] ? this.adapters[side] : null;
154
+ }
155
+
156
+ getPoolIdentifier(srcAddress: Address, destAddress: Address, fee: bigint) {
157
+ const tokenAddresses = this._sortTokens(srcAddress, destAddress).join('_');
158
+ return `${this.dexKey}_${tokenAddresses}_${fee}`;
159
+ }
160
+
161
+ async initializePricing(blockNumber: number) {
162
+ // Init listening to new pools creation
163
+ await this.factory.initialize(blockNumber);
164
+
165
+ // This is only for testing, because cold pool fetching is goes out of
166
+ // FETCH_POOL_INDENTIFIER_TIMEOUT range
167
+ await Promise.all(
168
+ this.poolsToPreload.map(async pool =>
169
+ Promise.all(
170
+ this.config.supportedFees.map(async fee =>
171
+ this.getPool(pool.token0, pool.token1, fee, blockNumber),
172
+ ),
173
+ ),
174
+ ),
175
+ );
176
+
177
+ if (!this.dexHelper.config.isSlave) {
178
+ const cleanExpiredNotExistingPoolsKeys = async () => {
179
+ const maxTimestamp =
180
+ Date.now() - BASESWAPV3_CLEAN_NOT_EXISTING_POOL_TTL_MS;
181
+ await this.dexHelper.cache.zremrangebyscore(
182
+ this.notExistingPoolSetKey,
183
+ 0,
184
+ maxTimestamp,
185
+ );
186
+ };
187
+
188
+ this.intervalTask = setInterval(
189
+ cleanExpiredNotExistingPoolsKeys.bind(this),
190
+ BASESWAPV3_CLEAN_NOT_EXISTING_POOL_INTERVAL_MS,
191
+ );
192
+ }
193
+ }
194
+
195
+ /*
196
+ * When a non existing pool is queried, it's blacklisted for an arbitrary long period in order to prevent issuing too many rpc calls
197
+ * Once the pool is created, it gets immediately flagged
198
+ */
199
+ onPoolCreatedDeleteFromNonExistingSet: OnPoolCreatedCallback = async ({
200
+ token0,
201
+ token1,
202
+ fee,
203
+ }) => {
204
+ const logPrefix = '[UniswapV3.onPoolCreatedDeleteFromNonExistingSet]';
205
+ const [_token0, _token1] = this._sortTokens(token0, token1);
206
+ const poolKey = `${_token0}_${_token1}_${fee}`;
207
+
208
+ // consider doing it only from master pool for less calls to distant cache
209
+
210
+ // delete entry locally to let local instance discover the pool
211
+ delete this.eventPools[this.getPoolIdentifier(_token0, _token1, fee)];
212
+
213
+ try {
214
+ this.logger.info(
215
+ `${logPrefix} delete pool from not existing set: ${poolKey}`,
216
+ );
217
+ // delete pool record from set
218
+ await this.dexHelper.cache.zrem(this.notExistingPoolSetKey, [poolKey]);
219
+ } catch (error) {
220
+ this.logger.error(
221
+ `${logPrefix} failed to delete pool from set: ${poolKey}`,
222
+ error,
223
+ );
224
+ }
225
+ };
226
+
227
+ async getPool(
228
+ srcAddress: Address,
229
+ destAddress: Address,
230
+ fee: bigint,
231
+ blockNumber: number,
232
+ ): Promise<BaseswapV3EventPool | null> {
233
+ let pool = this.eventPools[
234
+ this.getPoolIdentifier(srcAddress, destAddress, fee)
235
+ ] as BaseswapV3EventPool | null | undefined;
236
+
237
+ if (pool === null) return null;
238
+
239
+ if (pool) {
240
+ if (!pool.initFailed) {
241
+ return pool;
242
+ } else {
243
+ // if init failed then prefer to early return pool with empty state to fallback to rpc call
244
+ if (
245
+ ++pool.initRetryAttemptCount % this.config.initRetryFrequency !==
246
+ 0
247
+ ) {
248
+ return pool;
249
+ }
250
+ // else pursue with re-try initialization
251
+ }
252
+ }
253
+
254
+ const [token0, token1] = this._sortTokens(srcAddress, destAddress);
255
+
256
+ const key = `${token0}_${token1}_${fee}`.toLowerCase();
257
+
258
+ if (!pool) {
259
+ const notExistingPoolScore = await this.dexHelper.cache.zscore(
260
+ this.notExistingPoolSetKey,
261
+ key,
262
+ );
263
+
264
+ const poolDoesNotExist = notExistingPoolScore !== null;
265
+
266
+ if (poolDoesNotExist) {
267
+ this.eventPools[this.getPoolIdentifier(srcAddress, destAddress, fee)] =
268
+ null;
269
+ return null;
270
+ }
271
+
272
+ await this.dexHelper.cache.hset(
273
+ this.dexmapKey,
274
+ key,
275
+ JSON.stringify({
276
+ token0,
277
+ token1,
278
+ fee: fee.toString(),
279
+ }),
280
+ );
281
+ }
282
+
283
+ this.logger.trace(`starting to listen to new pool: ${key}`);
284
+
285
+ const poolImplementation =
286
+ this.config.eventPoolImplementation !== undefined
287
+ ? this.config.eventPoolImplementation
288
+ : BaseswapV3EventPool;
289
+
290
+ pool =
291
+ pool ||
292
+ new poolImplementation(
293
+ this.dexHelper,
294
+ this.dexKey,
295
+ this.stateMultiContract,
296
+ this.config.decodeStateMultiCallResultWithRelativeBitmaps,
297
+ this.erc20Interface,
298
+ this.config.factory,
299
+ fee,
300
+ token0,
301
+ token1,
302
+ this.logger,
303
+ this.cacheStateKey,
304
+ this.config.initHash,
305
+ );
306
+
307
+ try {
308
+ await pool.initialize(blockNumber, {
309
+ initCallback: (state: DeepReadonly<PoolState>) => {
310
+ //really hacky, we need to push poolAddress so that we subscribeToLogs in StatefulEventSubscriber
311
+ pool!.addressesSubscribed[0] = state.pool;
312
+ pool!.poolAddress = state.pool;
313
+ pool!.initFailed = false;
314
+ pool!.initRetryAttemptCount = 0;
315
+ },
316
+ });
317
+ } catch (e) {
318
+ if (e instanceof Error && e.message.endsWith('Pool does not exist')) {
319
+ // no need to await we want the set to have the pool key but it's not blocking
320
+ this.dexHelper.cache.zadd(
321
+ this.notExistingPoolSetKey,
322
+ [Date.now(), key],
323
+ 'NX',
324
+ );
325
+
326
+ // Pool does not exist for this feeCode, so we can set it to null
327
+ // to prevent more requests for this pool
328
+ pool = null;
329
+ this.logger.trace(
330
+ `${this.dexHelper}: Pool: srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} not found`,
331
+ e,
332
+ );
333
+ } else {
334
+ // on unknown error mark as failed and increase retryCount for retry init strategy
335
+ // note: state would be null by default which allows to fallback
336
+ this.logger.warn(
337
+ `${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress}, fee=${fee} pool fallback to rpc and retry every ${this.config.initRetryFrequency} times, initRetryAttemptCount=${pool.initRetryAttemptCount}`,
338
+ e,
339
+ );
340
+ pool.initFailed = true;
341
+ }
342
+ }
343
+
344
+ if (pool !== null) {
345
+ const allEventPools = Object.values(this.eventPools);
346
+ this.logger.info(
347
+ `starting to listen to new non-null pool: ${key}. Already following ${allEventPools
348
+ // Not that I like this reduce, but since it is done only on initialization, expect this to be ok
349
+ .reduce(
350
+ (acc, curr) => (curr !== null ? ++acc : acc),
351
+ 0,
352
+ )} non-null pools or ${allEventPools.length} total pools`,
353
+ );
354
+ }
355
+
356
+ this.eventPools[this.getPoolIdentifier(srcAddress, destAddress, fee)] =
357
+ pool;
358
+ return pool;
359
+ }
360
+
361
+ async addMasterPool(poolKey: string, blockNumber: number): Promise<boolean> {
362
+ const _pairs = await this.dexHelper.cache.hget(this.dexmapKey, poolKey);
363
+ if (!_pairs) {
364
+ this.logger.warn(
365
+ `did not find poolConfig in for key ${this.dexmapKey} ${poolKey}`,
366
+ );
367
+ return false;
368
+ }
369
+
370
+ const poolInfo: PoolPairsInfo = JSON.parse(_pairs);
371
+
372
+ const pool = await this.getPool(
373
+ poolInfo.token0,
374
+ poolInfo.token1,
375
+ BigInt(poolInfo.fee),
376
+ blockNumber,
377
+ );
378
+
379
+ if (!pool) {
380
+ return false;
381
+ }
382
+
383
+ return true;
384
+ }
385
+
386
+ async getPoolIdentifiers(
387
+ srcToken: Token,
388
+ destToken: Token,
389
+ side: SwapSide,
390
+ blockNumber: number,
391
+ ): Promise<string[]> {
392
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
393
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
394
+
395
+ const [_srcAddress, _destAddress] = this._getLoweredAddresses(
396
+ _srcToken,
397
+ _destToken,
398
+ );
399
+
400
+ if (_srcAddress === _destAddress) return [];
401
+
402
+ const pools = (
403
+ await Promise.all(
404
+ this.supportedFees.map(async fee =>
405
+ this.getPool(_srcAddress, _destAddress, fee, blockNumber),
406
+ ),
407
+ )
408
+ ).filter(pool => pool);
409
+
410
+ if (pools.length === 0) return [];
411
+
412
+ return pools.map(pool =>
413
+ this.getPoolIdentifier(_srcAddress, _destAddress, pool!.feeCode),
414
+ );
415
+ }
416
+
417
+ async getPricingFromRpc(
418
+ from: Token,
419
+ to: Token,
420
+ amounts: bigint[],
421
+ side: SwapSide,
422
+ pools: BaseswapV3EventPool[],
423
+ states: PoolState[],
424
+ ): Promise<ExchangePrices<UniswapV3Data> | null> {
425
+ if (pools.length === 0) {
426
+ return null;
427
+ }
428
+ this.logger.warn(`fallback to rpc for ${pools.length} pool(s)`);
429
+
430
+ const requests = pools.map<BalanceRequest>(
431
+ pool => ({
432
+ owner: pool.poolAddress,
433
+ asset: side == SwapSide.SELL ? from.address : to.address,
434
+ assetType: AssetType.ERC20,
435
+ ids: [
436
+ {
437
+ id: DEFAULT_ID_ERC20,
438
+ spenders: [],
439
+ },
440
+ ],
441
+ }),
442
+ [],
443
+ );
444
+
445
+ const balances = await getBalances(this.dexHelper.multiWrapper, requests);
446
+
447
+ pools = pools.filter((pool, index) => {
448
+ const balance = balances[index].amounts[DEFAULT_ID_ERC20_AS_STRING];
449
+ if (balance >= amounts[amounts.length - 1]) {
450
+ return true;
451
+ }
452
+ this.logger.warn(
453
+ `[${this.network}][${pool.parentName}] have no balance ${pool.poolAddress} ${from.address} ${to.address}. (Balance: ${balance})`,
454
+ );
455
+ return false;
456
+ });
457
+
458
+ pools.forEach(pool => {
459
+ this.logger.warn(
460
+ `[${this.network}][${pool.parentName}] fallback to rpc for ${pool.name}`,
461
+ );
462
+ });
463
+
464
+ const unitVolume = getBigIntPow(
465
+ (side === SwapSide.SELL ? from : to).decimals,
466
+ );
467
+
468
+ const chunks = amounts.length - 1;
469
+
470
+ const _width = Math.floor(chunks / this.config.chunksCount);
471
+
472
+ const _amounts = [unitVolume].concat(
473
+ Array.from(Array(this.config.chunksCount).keys()).map(
474
+ i => amounts[(i + 1) * _width],
475
+ ),
476
+ );
477
+
478
+ const calldata = pools.map(pool =>
479
+ _amounts.map(_amount => ({
480
+ target: this.config.quoter,
481
+ gasLimit: BASESWAPV3_QUOTE_GASLIMIT,
482
+ callData:
483
+ side === SwapSide.SELL
484
+ ? this.quoterIface.encodeFunctionData('quoteExactInputSingle', [
485
+ [
486
+ from.address,
487
+ to.address,
488
+ _amount.toString(),
489
+ pool.feeCodeAsString,
490
+ 0, //sqrtPriceLimitX96
491
+ ],
492
+ ])
493
+ : this.quoterIface.encodeFunctionData('quoteExactOutputSingle', [
494
+ [
495
+ from.address,
496
+ to.address,
497
+ _amount.toString(),
498
+ pool.feeCodeAsString,
499
+ 0, //sqrtPriceLimitX96
500
+ ],
501
+ ]),
502
+ })),
503
+ );
504
+
505
+ const data = await this.uniswapMulti.methods
506
+ .multicall(calldata.flat())
507
+ .call();
508
+
509
+ const decode = (j: number): bigint => {
510
+ if (!data.returnData[j].success) {
511
+ return 0n;
512
+ }
513
+ const decoded = defaultAbiCoder.decode(
514
+ ['uint256'],
515
+ data.returnData[j].returnData,
516
+ );
517
+ return BigInt(decoded[0].toString());
518
+ };
519
+
520
+ let i = 0;
521
+ const result = pools.map((pool, index) => {
522
+ const _rates = _amounts.map(() => decode(i++));
523
+ const unit: bigint = _rates[0];
524
+
525
+ const prices = interpolate(
526
+ _amounts.slice(1),
527
+ _rates.slice(1),
528
+ amounts,
529
+ side,
530
+ );
531
+
532
+ return {
533
+ prices,
534
+ unit,
535
+ data: {
536
+ path: [
537
+ {
538
+ tokenIn: from.address,
539
+ tokenOut: to.address,
540
+ fee: pool.feeCodeAsString,
541
+ currentFee: states[index].fee.toString(),
542
+ },
543
+ ],
544
+ exchange: pool.poolAddress,
545
+ },
546
+ poolIdentifier: this.getPoolIdentifier(
547
+ pool.token0,
548
+ pool.token1,
549
+ pool.feeCode,
550
+ ),
551
+ exchange: this.dexKey,
552
+ gasCost: prices.map(p => (p === 0n ? 0 : BASESWAPV3_QUOTE_GASLIMIT)),
553
+ poolAddresses: [pool.poolAddress],
554
+ };
555
+ });
556
+
557
+ return result;
558
+ }
559
+
560
+ async getPricesVolume(
561
+ srcToken: Token,
562
+ destToken: Token,
563
+ amounts: bigint[],
564
+ side: SwapSide,
565
+ blockNumber: number,
566
+ limitPools?: string[],
567
+ ): Promise<null | ExchangePrices<UniswapV3Data>> {
568
+ try {
569
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
570
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
571
+
572
+ const [_srcAddress, _destAddress] = this._getLoweredAddresses(
573
+ _srcToken,
574
+ _destToken,
575
+ );
576
+
577
+ if (_srcAddress === _destAddress) return null;
578
+
579
+ let selectedPools: BaseswapV3EventPool[] = [];
580
+
581
+ if (!limitPools) {
582
+ selectedPools = (
583
+ await Promise.all(
584
+ this.supportedFees.map(async fee => {
585
+ const locallyFoundPool =
586
+ this.eventPools[
587
+ this.getPoolIdentifier(_srcAddress, _destAddress, fee)
588
+ ];
589
+ if (locallyFoundPool) return locallyFoundPool;
590
+
591
+ const newlyFetchedPool = await this.getPool(
592
+ _srcAddress,
593
+ _destAddress,
594
+ fee,
595
+ blockNumber,
596
+ );
597
+ return newlyFetchedPool;
598
+ }),
599
+ )
600
+ ).filter(isTruthy);
601
+ } else {
602
+ const pairIdentifierWithoutFee = this.getPoolIdentifier(
603
+ _srcAddress,
604
+ _destAddress,
605
+ 0n,
606
+ // Trim from 0 fee postfix, so it become comparable
607
+ ).slice(0, -1);
608
+
609
+ const poolIdentifiers = limitPools.filter(identifier =>
610
+ identifier.startsWith(pairIdentifierWithoutFee),
611
+ );
612
+
613
+ selectedPools = (
614
+ await Promise.all(
615
+ poolIdentifiers.map(async identifier => {
616
+ let locallyFoundPool = this.eventPools[identifier];
617
+ if (locallyFoundPool) return locallyFoundPool;
618
+
619
+ const [, srcAddress, destAddress, fee] = identifier.split('_');
620
+ const newlyFetchedPool = await this.getPool(
621
+ srcAddress,
622
+ destAddress,
623
+ BigInt(fee),
624
+ blockNumber,
625
+ );
626
+ return newlyFetchedPool;
627
+ }),
628
+ )
629
+ ).filter(isTruthy);
630
+ }
631
+
632
+ if (selectedPools.length === 0) return null;
633
+
634
+ const poolsToUse = selectedPools.reduce(
635
+ (acc, pool) => {
636
+ let state = pool.getState(blockNumber);
637
+ if (state === null) {
638
+ this.logger.trace(
639
+ `${this.dexKey}: State === null. Fallback to rpc ${pool.name}`,
640
+ );
641
+ acc.poolWithoutState.push(pool);
642
+ } else {
643
+ acc.poolWithState.push(pool);
644
+ }
645
+ return acc;
646
+ },
647
+ {
648
+ poolWithState: [] as BaseswapV3EventPool[],
649
+ poolWithoutState: [] as BaseswapV3EventPool[],
650
+ },
651
+ );
652
+
653
+ const states = poolsToUse.poolWithState.map(
654
+ p => p.getState(blockNumber)!,
655
+ );
656
+
657
+ const rpcResultsPromise = this.getPricingFromRpc(
658
+ _srcToken,
659
+ _destToken,
660
+ amounts,
661
+ side,
662
+ this.network === Network.ZKEVM ? [] : poolsToUse.poolWithoutState,
663
+ this.network === Network.ZKEVM ? [] : states,
664
+ );
665
+
666
+ const unitAmount = getBigIntPow(
667
+ side == SwapSide.SELL ? _srcToken.decimals : _destToken.decimals,
668
+ );
669
+
670
+ const _amounts = [...amounts.slice(1)];
671
+
672
+ const [token0] = this._sortTokens(_srcAddress, _destAddress);
673
+
674
+ const zeroForOne = token0 === _srcAddress ? true : false;
675
+
676
+ const result = await Promise.all(
677
+ poolsToUse.poolWithState.map(async (pool, i) => {
678
+ const state = states[i];
679
+
680
+ if (state.liquidity <= 0n) {
681
+ if (state.liquidity < 0) {
682
+ this.logger.error(
683
+ `${this.dexKey}-${this.network}: ${pool.poolAddress} pool has negative liquidity: ${state.liquidity}. Find with key: ${pool.mapKey}`,
684
+ );
685
+ }
686
+ this.logger.trace(`pool have 0 liquidity`);
687
+ return null;
688
+ }
689
+
690
+ const balanceDestToken =
691
+ _destAddress === pool.token0 ? state.balance0 : state.balance1;
692
+
693
+ const unitResult = this._getOutputs(
694
+ state,
695
+ [unitAmount],
696
+ zeroForOne,
697
+ side,
698
+ balanceDestToken,
699
+ );
700
+ const pricesResult = this._getOutputs(
701
+ state,
702
+ _amounts,
703
+ zeroForOne,
704
+ side,
705
+ balanceDestToken,
706
+ );
707
+
708
+ if (!unitResult || !pricesResult) {
709
+ this.logger.debug('Prices or unit is not calculated');
710
+ return null;
711
+ }
712
+
713
+ const prices = [0n, ...pricesResult.outputs];
714
+ const gasCost = [
715
+ 0,
716
+ ...pricesResult.outputs.map((p, index) => {
717
+ if (p == 0n) {
718
+ return 0;
719
+ } else {
720
+ return (
721
+ UNISWAPV3_POOL_SEARCH_OVERHEAD +
722
+ UNISWAPV3_TICK_BASE_OVERHEAD +
723
+ pricesResult.tickCounts[index] * UNISWAPV3_TICK_GAS_COST
724
+ );
725
+ }
726
+ }),
727
+ ];
728
+ return {
729
+ unit: unitResult.outputs[0],
730
+ prices,
731
+ data: {
732
+ path: [
733
+ {
734
+ tokenIn: _srcAddress,
735
+ tokenOut: _destAddress,
736
+ fee: pool.feeCode.toString(),
737
+ currentFee: state.fee.toString(),
738
+ },
739
+ ],
740
+ },
741
+ poolIdentifier: this.getPoolIdentifier(
742
+ pool.token0,
743
+ pool.token1,
744
+ pool.feeCode,
745
+ ),
746
+ exchange: this.dexKey,
747
+ gasCost: gasCost,
748
+ poolAddresses: [pool.poolAddress],
749
+ };
750
+ }),
751
+ );
752
+ const rpcResults = await rpcResultsPromise;
753
+
754
+ const notNullResult = result.filter(
755
+ res => res !== null,
756
+ ) as ExchangePrices<UniswapV3Data>;
757
+
758
+ if (rpcResults) {
759
+ rpcResults.forEach(r => {
760
+ if (r) {
761
+ notNullResult.push(r);
762
+ }
763
+ });
764
+ }
765
+
766
+ return notNullResult;
767
+ } catch (e) {
768
+ this.logger.error(
769
+ `Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
770
+ destToken.symbol || destToken.address
771
+ }, ${side}:`,
772
+ e,
773
+ );
774
+ return null;
775
+ }
776
+ }
777
+
778
+ getAdapterParam(
779
+ srcToken: string,
780
+ destToken: string,
781
+ srcAmount: string,
782
+ destAmount: string,
783
+ data: UniswapV3Data,
784
+ side: SwapSide,
785
+ ): AdapterExchangeParam {
786
+ const { path: rawPath } = data;
787
+ const path = this._encodePath(rawPath, side);
788
+
789
+ const payload = this.abiCoder.encodeParameter(
790
+ {
791
+ ParentStruct: {
792
+ path: 'bytes',
793
+ deadline: 'uint256',
794
+ },
795
+ },
796
+ {
797
+ path,
798
+ deadline: getLocalDeadlineAsFriendlyPlaceholder(), // FIXME: more gas efficient to pass block.timestamp in adapter
799
+ },
800
+ );
801
+
802
+ return {
803
+ targetExchange: this.config.router,
804
+ payload,
805
+ networkFee: '0',
806
+ };
807
+ }
808
+
809
+ getCalldataGasCost(poolPrices: PoolPrices<UniswapV3Data>): number | number[] {
810
+ const gasCost =
811
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
812
+ CALLDATA_GAS_COST.LENGTH_SMALL +
813
+ // ParentStruct header
814
+ CALLDATA_GAS_COST.OFFSET_SMALL +
815
+ // ParentStruct -> path header
816
+ CALLDATA_GAS_COST.OFFSET_SMALL +
817
+ // ParentStruct -> deadline
818
+ CALLDATA_GAS_COST.TIMESTAMP +
819
+ // ParentStruct -> path (20+3+20 = 43 = 32+11 bytes)
820
+ CALLDATA_GAS_COST.LENGTH_SMALL +
821
+ CALLDATA_GAS_COST.FULL_WORD +
822
+ CALLDATA_GAS_COST.wordNonZeroBytes(11);
823
+ const arr = new Array(poolPrices.prices.length);
824
+ poolPrices.prices.forEach((p, index) => {
825
+ if (p == 0n) {
826
+ arr[index] = 0;
827
+ } else {
828
+ arr[index] = gasCost;
829
+ }
830
+ });
831
+ return arr;
832
+ }
833
+
834
+ getTokenFromAddress(address: Address): Token {
835
+ // In this Dex decimals are not used
836
+ return { address, decimals: 0 };
837
+ }
838
+
839
+ async preProcessTransaction(
840
+ optimalSwapExchange: OptimalSwapExchange<UniswapV3Data>,
841
+ srcToken: Token,
842
+ _0: Token,
843
+ _1: SwapSide,
844
+ options: PreprocessTransactionOptions,
845
+ ): Promise<[OptimalSwapExchange<UniswapV3Data>, ExchangeTxInfo]> {
846
+ if (!options.isDirectMethod) {
847
+ return [
848
+ optimalSwapExchange,
849
+ {
850
+ deadline: BigInt(getLocalDeadlineAsFriendlyPlaceholder()),
851
+ },
852
+ ];
853
+ }
854
+
855
+ assert(
856
+ optimalSwapExchange.data !== undefined,
857
+ `preProcessTransaction: data field is missing`,
858
+ );
859
+
860
+ let isApproved: boolean | undefined;
861
+
862
+ try {
863
+ this.erc20Contract.options.address =
864
+ this.dexHelper.config.wrapETH(srcToken).address;
865
+ const allowance = await this.erc20Contract.methods
866
+ .allowance(this.augustusAddress, this.config.router)
867
+ .call(undefined, 'latest');
868
+ isApproved =
869
+ BigInt(allowance.toString()) >= BigInt(optimalSwapExchange.srcAmount);
870
+ } catch (e) {
871
+ this.logger.error(
872
+ `preProcessTransaction failed to retrieve allowance info: `,
873
+ e,
874
+ );
875
+ }
876
+
877
+ return [
878
+ {
879
+ ...optimalSwapExchange,
880
+ data: {
881
+ ...optimalSwapExchange.data,
882
+ isApproved,
883
+ },
884
+ },
885
+ {
886
+ deadline: BigInt(getLocalDeadlineAsFriendlyPlaceholder()),
887
+ },
888
+ ];
889
+ }
890
+
891
+ getDirectParam(
892
+ srcToken: Address,
893
+ destToken: Address,
894
+ srcAmount: NumberAsString,
895
+ destAmount: NumberAsString,
896
+ expectedAmount: NumberAsString,
897
+ data: UniswapV3Data,
898
+ side: SwapSide,
899
+ permit: string,
900
+ uuid: string,
901
+ feePercent: NumberAsString,
902
+ deadline: NumberAsString,
903
+ partner: string,
904
+ beneficiary: string,
905
+ contractMethod?: string,
906
+ ): TxInfo<UniswapV3Param> {
907
+ if (
908
+ contractMethod !== DirectMethods.directSell &&
909
+ contractMethod !== DirectMethods.directBuy
910
+ ) {
911
+ throw new Error(`Invalid contract method ${contractMethod}`);
912
+ }
913
+
914
+ let isApproved: boolean = !!data.isApproved;
915
+ if (data.isApproved === undefined) {
916
+ this.logger.warn(`isApproved is undefined, defaulting to false`);
917
+ }
918
+
919
+ const path = this._encodePath(data.path, side);
920
+
921
+ const swapParams: UniswapV3Param = [
922
+ srcToken,
923
+ destToken,
924
+ this.config.router,
925
+ srcAmount,
926
+ destAmount,
927
+ expectedAmount,
928
+ feePercent,
929
+ deadline,
930
+ partner,
931
+ isApproved,
932
+ beneficiary,
933
+ path,
934
+ permit,
935
+ uuidToBytes16(uuid),
936
+ ];
937
+
938
+ const encoder = (...params: UniswapV3Param) => {
939
+ return this.directSwapIface.encodeFunctionData(
940
+ side === SwapSide.SELL
941
+ ? DirectMethods.directSell
942
+ : DirectMethods.directBuy,
943
+ [params],
944
+ );
945
+ };
946
+
947
+ return {
948
+ params: swapParams,
949
+ encoder,
950
+ networkFee: '0',
951
+ };
952
+ }
953
+
954
+ static getDirectFunctionName(): string[] {
955
+ return [DirectMethods.directSell, DirectMethods.directBuy];
956
+ }
957
+
958
+ async getSimpleParam(
959
+ srcToken: string,
960
+ destToken: string,
961
+ srcAmount: string,
962
+ destAmount: string,
963
+ data: UniswapV3Data,
964
+ side: SwapSide,
965
+ ): Promise<SimpleExchangeParam> {
966
+ const swapFunction =
967
+ side === SwapSide.SELL
968
+ ? UniswapV3Functions.exactInput
969
+ : UniswapV3Functions.exactOutput;
970
+
971
+ const path = this._encodePath(data.path, side);
972
+ const swapFunctionParams: UniswapV3SimpleSwapParams =
973
+ side === SwapSide.SELL
974
+ ? {
975
+ recipient: this.augustusAddress,
976
+ deadline: getLocalDeadlineAsFriendlyPlaceholder(),
977
+ amountIn: srcAmount,
978
+ amountOutMinimum: destAmount,
979
+ path,
980
+ }
981
+ : {
982
+ recipient: this.augustusAddress,
983
+ deadline: getLocalDeadlineAsFriendlyPlaceholder(),
984
+ amountOut: destAmount,
985
+ amountInMaximum: srcAmount,
986
+ path,
987
+ };
988
+ const swapData = this.routerIface.encodeFunctionData(swapFunction, [
989
+ swapFunctionParams,
990
+ ]);
991
+
992
+ return this.buildSimpleParamWithoutWETHConversion(
993
+ srcToken,
994
+ srcAmount,
995
+ destToken,
996
+ destAmount,
997
+ swapData,
998
+ this.config.router,
999
+ );
1000
+ }
1001
+
1002
+ async getTopPoolsForToken(
1003
+ tokenAddress: Address,
1004
+ limit: number,
1005
+ ): Promise<PoolLiquidity[]> {
1006
+ const _tokenAddress = tokenAddress.toLowerCase();
1007
+
1008
+ const res = await this._querySubgraph(
1009
+ `query ($token: Bytes!, $count: Int) {
1010
+ pools0: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token0: $token}) {
1011
+ id
1012
+ token0 {
1013
+ id
1014
+ decimals
1015
+ }
1016
+ token1 {
1017
+ id
1018
+ decimals
1019
+ }
1020
+ totalValueLockedUSD
1021
+ }
1022
+ pools1: pools(first: $count, orderBy: totalValueLockedUSD, orderDirection: desc, where: {token1: $token}) {
1023
+ id
1024
+ token0 {
1025
+ id
1026
+ decimals
1027
+ }
1028
+ token1 {
1029
+ id
1030
+ decimals
1031
+ }
1032
+ totalValueLockedUSD
1033
+ }
1034
+ }`,
1035
+ {
1036
+ token: _tokenAddress,
1037
+ count: limit,
1038
+ },
1039
+ );
1040
+
1041
+ if (!(res && res.pools0 && res.pools1)) {
1042
+ this.logger.error(
1043
+ `Error_${this.dexKey}_Subgraph: couldn't fetch the pools from the subgraph`,
1044
+ );
1045
+ return [];
1046
+ }
1047
+
1048
+ const pools0 = _.map(res.pools0, pool => ({
1049
+ exchange: this.dexKey,
1050
+ address: pool.id.toLowerCase(),
1051
+ connectorTokens: [
1052
+ {
1053
+ address: pool.token1.id.toLowerCase(),
1054
+ decimals: parseInt(pool.token1.decimals),
1055
+ },
1056
+ ],
1057
+ liquidityUSD:
1058
+ parseFloat(pool.totalValueLockedUSD) * UNISWAPV3_EFFICIENCY_FACTOR,
1059
+ }));
1060
+
1061
+ const pools1 = _.map(res.pools1, pool => ({
1062
+ exchange: this.dexKey,
1063
+ address: pool.id.toLowerCase(),
1064
+ connectorTokens: [
1065
+ {
1066
+ address: pool.token0.id.toLowerCase(),
1067
+ decimals: parseInt(pool.token0.decimals),
1068
+ },
1069
+ ],
1070
+ liquidityUSD:
1071
+ parseFloat(pool.totalValueLockedUSD) * UNISWAPV3_EFFICIENCY_FACTOR,
1072
+ }));
1073
+
1074
+ const pools = _.slice(
1075
+ _.sortBy(_.concat(pools0, pools1), [pool => -1 * pool.liquidityUSD]),
1076
+ 0,
1077
+ limit,
1078
+ );
1079
+ return pools;
1080
+ }
1081
+
1082
+ private async _getPoolsFromIdentifiers(
1083
+ poolIdentifiers: string[],
1084
+ blockNumber: number,
1085
+ ): Promise<BaseswapV3EventPool[]> {
1086
+ const pools = await Promise.all(
1087
+ poolIdentifiers.map(async identifier => {
1088
+ const [, srcAddress, destAddress, fee] = identifier.split('_');
1089
+ return this.getPool(srcAddress, destAddress, BigInt(fee), blockNumber);
1090
+ }),
1091
+ );
1092
+ return pools.filter(pool => pool) as BaseswapV3EventPool[];
1093
+ }
1094
+
1095
+ private _getLoweredAddresses(srcToken: Token, destToken: Token) {
1096
+ return [srcToken.address.toLowerCase(), destToken.address.toLowerCase()];
1097
+ }
1098
+
1099
+ private _sortTokens(srcAddress: Address, destAddress: Address) {
1100
+ return [srcAddress, destAddress].sort((a, b) => (a < b ? -1 : 1));
1101
+ }
1102
+
1103
+ private _toLowerForAllConfigAddresses() {
1104
+ // If new config property will be added, the TS will throw compile error
1105
+ const newConfig: DexParams = {
1106
+ router: this.config.router.toLowerCase(),
1107
+ quoter: this.config.quoter.toLowerCase(),
1108
+ factory: this.config.factory.toLowerCase(),
1109
+ supportedFees: this.config.supportedFees,
1110
+ stateMulticall: this.config.stateMulticall.toLowerCase(),
1111
+ chunksCount: this.config.chunksCount,
1112
+ initRetryFrequency: this.config.initRetryFrequency,
1113
+ uniswapMulticall: this.config.uniswapMulticall,
1114
+ deployer: this.config.deployer?.toLowerCase(),
1115
+ initHash: this.config.initHash,
1116
+ subgraphURL: this.config.subgraphURL,
1117
+ stateMultiCallAbi: this.config.stateMultiCallAbi,
1118
+ eventPoolImplementation: this.config.eventPoolImplementation,
1119
+ decodeStateMultiCallResultWithRelativeBitmaps:
1120
+ this.config.decodeStateMultiCallResultWithRelativeBitmaps,
1121
+ };
1122
+ return newConfig;
1123
+ }
1124
+
1125
+ private _getOutputs(
1126
+ state: DeepReadonly<PoolState>,
1127
+ amounts: bigint[],
1128
+ zeroForOne: boolean,
1129
+ side: SwapSide,
1130
+ destTokenBalance: bigint,
1131
+ ): OutputResult | null {
1132
+ try {
1133
+ const outputsResult = uniswapV3Math.queryOutputs(
1134
+ state,
1135
+ amounts,
1136
+ zeroForOne,
1137
+ side,
1138
+ );
1139
+
1140
+ if (side === SwapSide.SELL) {
1141
+ if (outputsResult.outputs[0] > destTokenBalance) {
1142
+ return null;
1143
+ }
1144
+
1145
+ for (let i = 0; i < outputsResult.outputs.length; i++) {
1146
+ if (outputsResult.outputs[i] > destTokenBalance) {
1147
+ outputsResult.outputs[i] = 0n;
1148
+ outputsResult.tickCounts[i] = 0;
1149
+ }
1150
+ }
1151
+ } else {
1152
+ if (amounts[0] > destTokenBalance) {
1153
+ return null;
1154
+ }
1155
+
1156
+ // This may be improved by first checking outputs and requesting outputs
1157
+ // only for amounts that makes more sense, but I don't think this is really
1158
+ // important now
1159
+ for (let i = 0; i < amounts.length; i++) {
1160
+ if (amounts[i] > destTokenBalance) {
1161
+ outputsResult.outputs[i] = 0n;
1162
+ outputsResult.tickCounts[i] = 0;
1163
+ }
1164
+ }
1165
+ }
1166
+
1167
+ return outputsResult;
1168
+ } catch (e) {
1169
+ this.logger.debug(
1170
+ `${this.dexKey}: received error in _getOutputs while calculating outputs`,
1171
+ e,
1172
+ );
1173
+ return null;
1174
+ }
1175
+ }
1176
+
1177
+ private async _querySubgraph(
1178
+ query: string,
1179
+ variables: Object,
1180
+ timeout = 30000,
1181
+ ) {
1182
+ try {
1183
+ const res = await this.dexHelper.httpRequest.post(
1184
+ this.config.subgraphURL,
1185
+ { query, variables },
1186
+ undefined,
1187
+ { timeout: timeout },
1188
+ );
1189
+ return res.data;
1190
+ } catch (e) {
1191
+ this.logger.error(`${this.dexKey}: can not query subgraph: `, e);
1192
+ return {};
1193
+ }
1194
+ }
1195
+
1196
+ private _encodePath(
1197
+ path: {
1198
+ tokenIn: Address;
1199
+ tokenOut: Address;
1200
+ fee: NumberAsString;
1201
+ }[],
1202
+ side: SwapSide,
1203
+ ): string {
1204
+ if (path.length === 0) {
1205
+ this.logger.error(
1206
+ `${this.dexKey}: Received invalid path=${path} for side=${side} to encode`,
1207
+ );
1208
+ return '0x';
1209
+ }
1210
+
1211
+ const { _path, types } = path.reduce(
1212
+ (
1213
+ { _path, types }: { _path: string[]; types: string[] },
1214
+ curr,
1215
+ index,
1216
+ ): { _path: string[]; types: string[] } => {
1217
+ if (index === 0) {
1218
+ return {
1219
+ types: ['address', 'uint24', 'address'],
1220
+ _path: [curr.tokenIn, curr.fee, curr.tokenOut],
1221
+ };
1222
+ } else {
1223
+ return {
1224
+ types: [...types, 'uint24', 'address'],
1225
+ _path: [..._path, curr.fee, curr.tokenOut],
1226
+ };
1227
+ }
1228
+ },
1229
+ { _path: [], types: [] },
1230
+ );
1231
+
1232
+ return side === SwapSide.BUY
1233
+ ? pack(types.reverse(), _path.reverse())
1234
+ : pack(types, _path);
1235
+ }
1236
+
1237
+ releaseResources() {
1238
+ if (this.intervalTask !== undefined) {
1239
+ clearInterval(this.intervalTask);
1240
+ this.intervalTask = undefined;
1241
+ }
1242
+ }
1243
+ }