@paraswap/dex-lib 2.42.26 → 2.42.27-solidly-v3

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