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