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