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