@paraswap/dex-lib 2.28.10-ramses-v2 → 2.28.10

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