@paraswap/dex-lib 2.36.1 → 2.36.2-dexalot.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 (163) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/codeStyles/Project.xml +19 -0
  3. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  4. package/.idea/misc.xml +6 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/paraswap-dex-lib.iml +9 -0
  7. package/.idea/vcs.xml +6 -0
  8. package/build/abi/algebra/AlgebraPool.abi.json +727 -0
  9. package/build/abi/curve-v1/StableSwapFRXETH.json +889 -0
  10. package/build/abi/curve-v1/StableSwapWBETH.json +1223 -0
  11. package/build/abi/dexalot/DexalotMainnetRFQ.json +887 -0
  12. package/build/abi/sushiswap-v3/QuoterV2.json +267 -0
  13. package/build/abi/sushiswap-v3/RouterProcessor3.json +289 -0
  14. package/build/abi/wBETH.json +1527 -0
  15. package/build/config.js +2 -0
  16. package/build/config.js.map +1 -1
  17. package/build/dex/algebra/algebra-pool.d.ts +46 -0
  18. package/build/dex/algebra/algebra-pool.js +336 -0
  19. package/build/dex/algebra/algebra-pool.js.map +1 -0
  20. package/build/dex/curve-v1/pools/frxETHpool.d.ts +7 -0
  21. package/build/dex/curve-v1/pools/frxETHpool.js +27 -0
  22. package/build/dex/curve-v1/pools/frxETHpool.js.map +1 -0
  23. package/build/dex/curve-v1/pools/wbETHpool.d.ts +29 -0
  24. package/build/dex/curve-v1/pools/wbETHpool.js +408 -0
  25. package/build/dex/curve-v1/pools/wbETHpool.js.map +1 -0
  26. package/build/dex/{test-dex → dexalot}/config.d.ts +1 -1
  27. package/build/dex/dexalot/config.js +18 -0
  28. package/build/dex/dexalot/config.js.map +1 -0
  29. package/build/dex/dexalot/constants.d.ts +15 -0
  30. package/build/dex/dexalot/constants.js +22 -0
  31. package/build/dex/dexalot/constants.js.map +1 -0
  32. package/build/dex/dexalot/dexalot.d.ts +69 -0
  33. package/build/dex/dexalot/dexalot.js +614 -0
  34. package/build/dex/dexalot/dexalot.js.map +1 -0
  35. package/build/dex/dexalot/rate-fetcher.d.ts +28 -0
  36. package/build/dex/dexalot/rate-fetcher.js +100 -0
  37. package/build/dex/dexalot/rate-fetcher.js.map +1 -0
  38. package/build/dex/dexalot/types.d.ts +114 -0
  39. package/build/dex/dexalot/types.js +12 -0
  40. package/build/dex/dexalot/types.js.map +1 -0
  41. package/build/dex/dexalot/validators.d.ts +5 -0
  42. package/build/dex/dexalot/validators.js +45 -0
  43. package/build/dex/dexalot/validators.js.map +1 -0
  44. package/build/dex/index.js +2 -0
  45. package/build/dex/index.js.map +1 -1
  46. package/build/dex/pancakeswap-v3/types.d.ts +14 -0
  47. package/build/dex/{test-dex → pancakeswap-v3}/types.js.map +1 -1
  48. package/build/dex/ramses-v2/config.d.ts +4 -0
  49. package/build/dex/ramses-v2/config.js +28 -0
  50. package/build/dex/ramses-v2/config.js.map +1 -0
  51. package/build/dex/ramses-v2/constants.d.ts +28 -0
  52. package/build/dex/ramses-v2/constants.js +35 -0
  53. package/build/dex/ramses-v2/constants.js.map +1 -0
  54. package/build/dex/ramses-v2/contract-math/BitMath.d.ts +4 -0
  55. package/build/dex/ramses-v2/contract-math/BitMath.js +93 -0
  56. package/build/dex/ramses-v2/contract-math/BitMath.js.map +1 -0
  57. package/build/dex/ramses-v2/contract-math/FixedPoint128.d.ts +3 -0
  58. package/build/dex/ramses-v2/contract-math/FixedPoint128.js +8 -0
  59. package/build/dex/ramses-v2/contract-math/FixedPoint128.js.map +1 -0
  60. package/build/dex/ramses-v2/contract-math/FixedPoint96.d.ts +4 -0
  61. package/build/dex/ramses-v2/contract-math/FixedPoint96.js +9 -0
  62. package/build/dex/ramses-v2/contract-math/FixedPoint96.js.map +1 -0
  63. package/build/dex/ramses-v2/contract-math/FullMath.d.ts +4 -0
  64. package/build/dex/ramses-v2/contract-math/FullMath.js +19 -0
  65. package/build/dex/ramses-v2/contract-math/FullMath.js.map +1 -0
  66. package/build/dex/ramses-v2/contract-math/LiquidityMath.d.ts +3 -0
  67. package/build/dex/ramses-v2/contract-math/LiquidityMath.js +22 -0
  68. package/build/dex/ramses-v2/contract-math/LiquidityMath.js.map +1 -0
  69. package/build/dex/ramses-v2/contract-math/Oracle.d.ts +10 -0
  70. package/build/dex/ramses-v2/contract-math/Oracle.js +133 -0
  71. package/build/dex/ramses-v2/contract-math/Oracle.js.map +1 -0
  72. package/build/dex/ramses-v2/contract-math/SqrtPriceMath.d.ts +10 -0
  73. package/build/dex/ramses-v2/contract-math/SqrtPriceMath.js +91 -0
  74. package/build/dex/ramses-v2/contract-math/SqrtPriceMath.js.map +1 -0
  75. package/build/dex/ramses-v2/contract-math/SwapMath.d.ts +8 -0
  76. package/build/dex/ramses-v2/contract-math/SwapMath.js +70 -0
  77. package/build/dex/ramses-v2/contract-math/SwapMath.js.map +1 -0
  78. package/build/dex/ramses-v2/contract-math/Tick.d.ts +7 -0
  79. package/build/dex/ramses-v2/contract-math/Tick.js +45 -0
  80. package/build/dex/ramses-v2/contract-math/Tick.js.map +1 -0
  81. package/build/dex/ramses-v2/contract-math/TickBitMap.d.ts +8 -0
  82. package/build/dex/ramses-v2/contract-math/TickBitMap.js +87 -0
  83. package/build/dex/ramses-v2/contract-math/TickBitMap.js.map +1 -0
  84. package/build/dex/ramses-v2/contract-math/TickMath.d.ts +8 -0
  85. package/build/dex/ramses-v2/contract-math/TickMath.js +162 -0
  86. package/build/dex/ramses-v2/contract-math/TickMath.js.map +1 -0
  87. package/build/dex/ramses-v2/contract-math/UnsafeMath.d.ts +3 -0
  88. package/build/dex/ramses-v2/contract-math/UnsafeMath.js +10 -0
  89. package/build/dex/ramses-v2/contract-math/UnsafeMath.js.map +1 -0
  90. package/build/dex/ramses-v2/contract-math/uniswap-v3-math.d.ts +18 -0
  91. package/build/dex/ramses-v2/contract-math/uniswap-v3-math.js +392 -0
  92. package/build/dex/ramses-v2/contract-math/uniswap-v3-math.js.map +1 -0
  93. package/build/dex/ramses-v2/contract-math/utils.d.ts +3 -0
  94. package/build/dex/ramses-v2/contract-math/utils.js +16 -0
  95. package/build/dex/ramses-v2/contract-math/utils.js.map +1 -0
  96. package/build/dex/ramses-v2/ramses-v2-pool.d.ts +42 -0
  97. package/build/dex/ramses-v2/ramses-v2-pool.js +307 -0
  98. package/build/dex/ramses-v2/ramses-v2-pool.js.map +1 -0
  99. package/build/dex/ramses-v2/ramses-v2.d.ts +61 -0
  100. package/build/dex/ramses-v2/ramses-v2.js +690 -0
  101. package/build/dex/ramses-v2/ramses-v2.js.map +1 -0
  102. package/build/dex/ramses-v2/types.d.ts +154 -0
  103. package/build/dex/ramses-v2/types.js +9 -0
  104. package/build/dex/ramses-v2/types.js.map +1 -0
  105. package/build/dex/ramses-v2/utils.d.ts +6 -0
  106. package/build/dex/ramses-v2/utils.js +71 -0
  107. package/build/dex/ramses-v2/utils.js.map +1 -0
  108. package/build/dex/sushiswap-v3/config.d.ts +4 -0
  109. package/build/dex/sushiswap-v3/config.js +132 -0
  110. package/build/dex/sushiswap-v3/config.js.map +1 -0
  111. package/build/dex/sushiswap-v3/constants.d.ts +4 -0
  112. package/build/dex/sushiswap-v3/constants.js +32 -0
  113. package/build/dex/sushiswap-v3/constants.js.map +1 -0
  114. package/build/dex/sushiswap-v3/sushiswap-v3-original.d.ts +56 -0
  115. package/build/dex/sushiswap-v3/sushiswap-v3-original.js +598 -0
  116. package/build/dex/sushiswap-v3/sushiswap-v3-original.js.map +1 -0
  117. package/build/dex/sushiswap-v3/sushiswap-v3-pool.d.ts +1 -0
  118. package/build/dex/sushiswap-v3/sushiswap-v3-pool.js +6 -0
  119. package/build/dex/sushiswap-v3/sushiswap-v3-pool.js.map +1 -0
  120. package/build/dex/sushiswap-v3/sushiswap-v3.d.ts +21 -0
  121. package/build/dex/sushiswap-v3/sushiswap-v3.js +58 -0
  122. package/build/dex/sushiswap-v3/sushiswap-v3.js.map +1 -0
  123. package/build/dex/sushiswap-v3/token.d.ts +6 -0
  124. package/build/dex/sushiswap-v3/token.js +23 -0
  125. package/build/dex/sushiswap-v3/token.js.map +1 -0
  126. package/build/dex/sushiswap-v3/types.d.ts +15 -0
  127. package/build/dex/sushiswap-v3/types.js +18 -0
  128. package/build/dex/sushiswap-v3/types.js.map +1 -0
  129. package/build/types.d.ts +1 -0
  130. package/package.json +1 -1
  131. package/src/abi/dexalot/DexalotMainnetRFQ.json +887 -0
  132. package/src/config.ts +3 -0
  133. package/src/dex/dexalot/config.ts +18 -0
  134. package/src/dex/dexalot/constants.ts +29 -0
  135. package/src/dex/dexalot/dexalot-e2e.test.ts +192 -0
  136. package/src/dex/dexalot/dexalot-integration.test.ts +188 -0
  137. package/src/dex/dexalot/dexalot.ts +935 -0
  138. package/src/dex/dexalot/rate-fetcher.ts +197 -0
  139. package/src/dex/dexalot/types.ts +131 -0
  140. package/src/dex/dexalot/validators.ts +46 -0
  141. package/src/dex/index.ts +2 -0
  142. package/src/types.ts +1 -0
  143. package/build/abi/quickPerps/fast-price-events.json +0 -70
  144. package/build/abi/quickPerps/fast-price-feed.json +0 -748
  145. package/build/abi/quickPerps/reader.json +0 -313
  146. package/build/abi/quickPerps/vault-price-feed.json +0 -477
  147. package/build/abi/quickPerps/vault.json +0 -1953
  148. package/build/dex/test-dex/config.js +0 -15
  149. package/build/dex/test-dex/config.js.map +0 -1
  150. package/build/dex/test-dex/test-dex-pool.d.ts +0 -39
  151. package/build/dex/test-dex/test-dex-pool.js +0 -63
  152. package/build/dex/test-dex/test-dex-pool.js.map +0 -1
  153. package/build/dex/test-dex/test-dex.d.ts +0 -37
  154. package/build/dex/test-dex/test-dex.js +0 -126
  155. package/build/dex/test-dex/test-dex.js.map +0 -1
  156. package/build/dex/test-dex/types.d.ts +0 -6
  157. package/build/dex/woo-fi-v2/woo-fi-math.d.ts +0 -16
  158. package/build/dex/woo-fi-v2/woo-fi-math.js +0 -137
  159. package/build/dex/woo-fi-v2/woo-fi-math.js.map +0 -1
  160. package/build/workers.d.ts +0 -0
  161. package/build/workers.js +0 -2
  162. package/build/workers.js.map +0 -1
  163. /package/build/dex/{test-dex → pancakeswap-v3}/types.js +0 -0
@@ -0,0 +1,935 @@
1
+ import {
2
+ Token,
3
+ Address,
4
+ ExchangePrices,
5
+ PoolPrices,
6
+ AdapterExchangeParam,
7
+ SimpleExchangeParam,
8
+ PoolLiquidity,
9
+ Logger,
10
+ ExchangeTxInfo,
11
+ OptimalSwapExchange,
12
+ PreprocessTransactionOptions,
13
+ } from '../../types';
14
+ import {
15
+ SwapSide,
16
+ Network,
17
+ ETHER_ADDRESS,
18
+ NULL_ADDRESS,
19
+ } from '../../constants';
20
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
21
+ import { getDexKeysWithNetwork, isAxiosError } from '../../utils';
22
+ import { IDex } from '../idex';
23
+ import { IDexHelper } from '../../dex-helper/idex-helper';
24
+ import {
25
+ ClobSide,
26
+ DexalotData,
27
+ PairData,
28
+ PairDataMap,
29
+ PriceDataMap,
30
+ DexalotRfqError,
31
+ DexalotAPIParameters,
32
+ RFQResponse,
33
+ RFQResponseError,
34
+ TokenAddrDataMap,
35
+ TokenDataMap,
36
+ } from './types';
37
+ import { SlippageCheckError, TooStrictSlippageCheckError } from '../generic-rfq/types';
38
+ import { SimpleExchange } from '../simple-exchange';
39
+ import { Adapters, DexalotConfig } from './config';
40
+ import { RateFetcher } from './rate-fetcher';
41
+ import mainnetRFQAbi from '../../abi/dexalot/DexalotMainnetRFQ.json';
42
+ import { Interface } from 'ethers/lib/utils';
43
+ import { assert } from 'ts-essentials';
44
+ import {
45
+ DEXALOT_API_URL,
46
+ DEXALOT_API_PRICES_POLLING_INTERVAL_MS,
47
+ DEXALOT_PRICES_CACHES_TTL_S,
48
+ DEXALOT_GAS_COST,
49
+ DEXALOT_PAIRS_CACHES_TTL_S,
50
+ DEXALOT_API_PAIRS_POLLING_INTERVAL_MS,
51
+ DEXALOT_TOKENS_CACHES_TTL_S,
52
+ DEXALOT_API_BLACKLIST_POLLING_INTERVAL_MS,
53
+ DEXALOT_RATE_LIMITED_TTL_S,
54
+ DEXALOT_MIN_SLIPPAGE_FACTOR_THRESHOLD_FOR_RESTRICTION,
55
+ DEXALOT_RESTRICTED_CACHE_KEY,
56
+ DEXALOT_RESTRICT_TTL_S,
57
+ DEXALOT_RATELIMIT_CACHE_VALUE,
58
+ DEXALOT_BLACKLIST_CACHES_TTL_S,
59
+ } from './constants';
60
+ import { BI_MAX_UINT256 } from '../../bigint-constants';
61
+ import { ethers } from 'ethers';
62
+ import BigNumber from 'bignumber.js';
63
+ import { Method } from '../../dex-helper/irequest-wrapper';
64
+ import { normalizeTokenAddress } from '../swaap-v2/utils';
65
+
66
+ export class Dexalot extends SimpleExchange implements IDex<DexalotData> {
67
+ readonly isStatePollingDex = true;
68
+ readonly hasConstantPriceLargeAmounts = false;
69
+ readonly needWrapNative = false;
70
+ readonly isFeeOnTransferSupported = false;
71
+ private rateFetcher: RateFetcher;
72
+
73
+ private dexalotAuthToken: string;
74
+
75
+ private pricesCacheKey: string;
76
+ private pairsCacheKey: string;
77
+ private tokensAddrCacheKey: string;
78
+ private tokensCacheKey: string;
79
+ private blacklistCacheKey: string;
80
+ private tokensMap: TokenDataMap = {};
81
+
82
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
83
+ getDexKeysWithNetwork(DexalotConfig);
84
+
85
+ logger: Logger;
86
+
87
+ constructor(
88
+ readonly network: Network,
89
+ readonly dexKey: string,
90
+ readonly dexHelper: IDexHelper,
91
+ protected adapters = Adapters[network] || {},
92
+ readonly mainnetRFQAddress: string = DexalotConfig['Dexalot'][network]
93
+ .mainnetRFQAddress,
94
+ protected rfqInterface = new Interface(mainnetRFQAbi),
95
+ ) {
96
+ super(dexHelper, dexKey);
97
+ this.logger = dexHelper.getLogger(dexKey);
98
+
99
+ const authToken = dexHelper.config.data.dexalotAuthToken;
100
+ assert(
101
+ authToken !== undefined,
102
+ 'Dexalot auth token is not specified with env variable',
103
+ );
104
+ this.dexalotAuthToken = authToken;
105
+
106
+ this.pricesCacheKey = 'prices';
107
+ this.pairsCacheKey = 'pairs';
108
+ this.tokensAddrCacheKey = 'tokens_addr';
109
+ this.tokensCacheKey = 'tokens';
110
+ this.blacklistCacheKey = 'blacklist';
111
+
112
+ this.rateFetcher = new RateFetcher(
113
+ this.dexHelper,
114
+ this.dexKey,
115
+ this.network,
116
+ this.logger,
117
+ {
118
+ rateConfig: {
119
+ pairsIntervalMs: DEXALOT_API_PAIRS_POLLING_INTERVAL_MS,
120
+ pricesIntervalMs: DEXALOT_API_PRICES_POLLING_INTERVAL_MS,
121
+ blacklistIntervalMs: DEXALOT_API_BLACKLIST_POLLING_INTERVAL_MS,
122
+ pairsReqParams: this.getAPIReqParams('api/rfq/pairs', 'GET'),
123
+ pricesReqParams: this.getAPIReqParams('api/rfq/prices', 'GET'),
124
+ blacklistReqParams: this.getAPIReqParams('api/rfq/blacklist', 'GET'),
125
+ pairsCacheKey: this.pairsCacheKey,
126
+ pairsCacheTTLSecs: DEXALOT_PAIRS_CACHES_TTL_S,
127
+ pricesCacheKey: this.pricesCacheKey,
128
+ pricesCacheTTLSecs: DEXALOT_PRICES_CACHES_TTL_S,
129
+ tokensAddrCacheKey: this.tokensAddrCacheKey,
130
+ tokensCacheKey: this.tokensCacheKey,
131
+ tokensCacheTTLSecs: DEXALOT_TOKENS_CACHES_TTL_S,
132
+ blacklistCacheKey: this.blacklistCacheKey,
133
+ blacklistCacheTTLSecs: DEXALOT_BLACKLIST_CACHES_TTL_S,
134
+ },
135
+ },
136
+ );
137
+ }
138
+
139
+ async initializePricing(blockNumber: number): Promise<void> {
140
+ if (!this.dexHelper.config.isSlave) {
141
+ this.rateFetcher.start();
142
+ }
143
+
144
+ return;
145
+ }
146
+
147
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
148
+ return this.adapters[side] ? this.adapters[side] : null;
149
+ }
150
+
151
+ getPairString(baseToken: Token, quoteToken: Token): string {
152
+ return `${baseToken.symbol}/${quoteToken.symbol}`.toLowerCase();
153
+ }
154
+
155
+ async getPairData(
156
+ srcToken: Token,
157
+ destToken: Token,
158
+ ): Promise<PairData | null> {
159
+ const normalizedSrcToken = this.normalizeToken(srcToken);
160
+ const normalizedDestToken = this.normalizeToken(destToken);
161
+ if (normalizedSrcToken.address === normalizedDestToken.address) {
162
+ return null;
163
+ }
164
+
165
+ const cachedTokens = (await this.getCachedTokens()) || {};
166
+ if (
167
+ !(normalizedSrcToken.address in cachedTokens) ||
168
+ !(normalizedDestToken.address in cachedTokens)
169
+ ) {
170
+ return null;
171
+ }
172
+ normalizedSrcToken.symbol = cachedTokens[normalizedSrcToken.address].symbol;
173
+ normalizedDestToken.symbol =
174
+ cachedTokens[normalizedDestToken.address].symbol;
175
+
176
+ const cachedPairs = (await this.getCachedPairs()) || {};
177
+
178
+ const potentialPairs = [
179
+ {
180
+ identifier: this.getPairString(normalizedSrcToken, normalizedDestToken),
181
+ isSrcBase: true,
182
+ },
183
+ {
184
+ identifier: this.getPairString(normalizedDestToken, normalizedSrcToken),
185
+ isSrcBase: false,
186
+ },
187
+ ];
188
+
189
+ for (const pair of potentialPairs) {
190
+ if (pair.identifier in cachedPairs) {
191
+ const pairData = cachedPairs[pair.identifier];
192
+ pairData.isSrcBase = pair.isSrcBase;
193
+ return pairData;
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+
199
+ getIdentifier(baseSymbol: string, quoteSymbol: string) {
200
+ // return `${this.dexKey}_${baseSymbol}_${quoteSymbol}`.toLowerCase();
201
+ // To disable Dexalot in multi/mega routes
202
+ return this.dexKey;
203
+ }
204
+
205
+ async getPoolIdentifiers(
206
+ srcToken: Token,
207
+ destToken: Token,
208
+ side: SwapSide,
209
+ blockNumber: number,
210
+ ): Promise<string[]> {
211
+ if (!srcToken || !destToken) {
212
+ return [];
213
+ }
214
+ const pairData = await this.getPairData(srcToken, destToken);
215
+ if (!pairData) {
216
+ return [];
217
+ }
218
+ return [this.getIdentifier(pairData.base, pairData.quote)];
219
+ }
220
+
221
+ async getCachedPairs(): Promise<PairDataMap | null> {
222
+ const cachedPairs = await this.dexHelper.cache.get(
223
+ this.dexKey,
224
+ this.network,
225
+ this.pairsCacheKey,
226
+ );
227
+
228
+ if (cachedPairs) {
229
+ return JSON.parse(cachedPairs) as PairDataMap;
230
+ }
231
+
232
+ return null;
233
+ }
234
+
235
+ async getCachedPrices(): Promise<PriceDataMap | null> {
236
+ const cachedPrices = await this.dexHelper.cache.get(
237
+ this.dexKey,
238
+ this.network,
239
+ this.pricesCacheKey,
240
+ );
241
+
242
+ if (cachedPrices) {
243
+ return JSON.parse(cachedPrices) as PriceDataMap;
244
+ }
245
+
246
+ return null;
247
+ }
248
+
249
+ async getCachedTokensAddr(): Promise<TokenAddrDataMap | null> {
250
+ const cachedTokensAddr = await this.dexHelper.cache.get(
251
+ this.dexKey,
252
+ this.network,
253
+ this.tokensAddrCacheKey,
254
+ );
255
+
256
+ if (cachedTokensAddr) {
257
+ return JSON.parse(cachedTokensAddr) as TokenAddrDataMap;
258
+ }
259
+
260
+ return null;
261
+ }
262
+
263
+ async getCachedTokens(): Promise<TokenDataMap | null> {
264
+ const cachedTokens = await this.dexHelper.cache.get(
265
+ this.dexKey,
266
+ this.network,
267
+ this.tokensCacheKey,
268
+ );
269
+
270
+ if (cachedTokens) {
271
+ return JSON.parse(cachedTokens) as TokenDataMap;
272
+ }
273
+
274
+ return null;
275
+ }
276
+
277
+ normalizeAddress(address: string): string {
278
+ return address.toLowerCase() === ETHER_ADDRESS
279
+ ? NULL_ADDRESS
280
+ : address.toLowerCase();
281
+ }
282
+
283
+ denormalizeAddress(address: string): string {
284
+ return address.toLowerCase() === NULL_ADDRESS
285
+ ? ETHER_ADDRESS
286
+ : address.toLowerCase();
287
+ }
288
+
289
+ // Dexalot protocol for native token expects 0x00000... instead of 0xeeeee...
290
+ normalizeToken(token: Token): Token {
291
+ return {
292
+ address: this.normalizeAddress(token.address),
293
+ decimals: token.decimals,
294
+ };
295
+ }
296
+
297
+ denormalizeToken(token: Token): Token {
298
+ return {
299
+ address: this.denormalizeAddress(token.address),
300
+ decimals: token.decimals,
301
+ };
302
+ }
303
+
304
+ calculateOrderPrice(
305
+ amounts: bigint[],
306
+ orderbook: string[][],
307
+ baseToken: Token,
308
+ quoteToken: Token,
309
+ side: ClobSide,
310
+ ) {
311
+ let result = [];
312
+
313
+ for (let i = 0; i < amounts.length; i++) {
314
+ let amt = amounts[i];
315
+ if (amt === 0n) {
316
+ result.push(amt);
317
+ continue;
318
+ }
319
+
320
+ let totalVolume = 0n;
321
+ let combinedPrice = 0n;
322
+
323
+ for (let j = 0; j < orderbook.length; j++) {
324
+ const order = orderbook[j];
325
+ const priceBN = ethers.utils.parseUnits(order[0], quoteToken.decimals);
326
+ const price = BigInt(priceBN.toString());
327
+ const qtyBN = ethers.utils.parseUnits(order[1], baseToken.decimals);
328
+ const qty = BigInt(qtyBN.toString());
329
+ let vol = qty;
330
+ if (side === ClobSide.BID) {
331
+ vol = (qty * price) / BigInt(10 ** baseToken.decimals);
332
+ }
333
+ if (amt < vol) {
334
+ totalVolume += amt;
335
+ combinedPrice += amt * price;
336
+ amt = 0n;
337
+ } else {
338
+ amt -= vol;
339
+ totalVolume += vol;
340
+ combinedPrice += vol * price;
341
+ }
342
+ if (amt === 0n) {
343
+ break;
344
+ }
345
+ }
346
+ if (amt > 0n) {
347
+ return result;
348
+ }
349
+ const avgPrice = combinedPrice / totalVolume;
350
+ if (side === ClobSide.BID) {
351
+ result.push((amounts[i] * BigInt(10 ** baseToken.decimals)) / avgPrice);
352
+ } else {
353
+ result.push((avgPrice * amounts[i]) / BigInt(10 ** baseToken.decimals));
354
+ }
355
+ }
356
+ return result;
357
+ }
358
+
359
+ async getPricesVolume(
360
+ srcToken: Token,
361
+ destToken: Token,
362
+ amounts: bigint[],
363
+ side: SwapSide,
364
+ blockNumber: number,
365
+ limitPools?: string[],
366
+ ): Promise<null | ExchangePrices<DexalotData>> {
367
+ try {
368
+ if (await this.isRestricted()) {
369
+ return null;
370
+ }
371
+
372
+ const normalizedSrcToken = this.normalizeToken(srcToken);
373
+ const normalizedDestToken = this.normalizeToken(destToken);
374
+
375
+ this.tokensMap = (await this.getCachedTokens()) || {};
376
+ if (normalizedSrcToken.address === normalizedDestToken.address) {
377
+ return null;
378
+ }
379
+
380
+ if (limitPools && limitPools.length !== 1) {
381
+ return null;
382
+ }
383
+
384
+ const pairData = await this.getPairData(
385
+ normalizedSrcToken,
386
+ normalizedDestToken,
387
+ );
388
+ if (!pairData) {
389
+ return null;
390
+ }
391
+
392
+ const priceMap = await this.getCachedPrices();
393
+ if (!priceMap) {
394
+ return null;
395
+ }
396
+
397
+ const pairKey = `${pairData.base}/${pairData.quote}`.toLowerCase();
398
+ if (!(pairKey in priceMap)) {
399
+ return null;
400
+ }
401
+
402
+ const priceData = priceMap[pairKey];
403
+ const baseToken = pairData.isSrcBase
404
+ ? normalizedSrcToken
405
+ : normalizedDestToken;
406
+ const quoteToken = pairData.isSrcBase
407
+ ? normalizedDestToken
408
+ : normalizedSrcToken;
409
+
410
+ // convert from swap to clob side
411
+ let orderbook = priceData.asks;
412
+ let clobSide = ClobSide.BID;
413
+ if (
414
+ (side === SwapSide.SELL && pairData.isSrcBase) ||
415
+ (side === SwapSide.BUY && !pairData.isSrcBase)
416
+ ) {
417
+ orderbook = priceData.bids;
418
+ clobSide = ClobSide.ASK;
419
+ }
420
+ if (orderbook.length === 0) {
421
+ throw new Error(`Empty orderbook for ${pairKey}`);
422
+ }
423
+
424
+ const prices = this.calculateOrderPrice(
425
+ amounts,
426
+ orderbook,
427
+ baseToken,
428
+ quoteToken,
429
+ clobSide,
430
+ );
431
+ const outDecimals =
432
+ clobSide === ClobSide.BID ? baseToken.decimals : quoteToken.decimals;
433
+ const poolIdentifier = this.getIdentifier(pairData.base, pairData.quote);
434
+
435
+ return [
436
+ {
437
+ prices,
438
+ unit: BigInt(outDecimals),
439
+ data: {},
440
+ poolIdentifier: poolIdentifier,
441
+ exchange: this.dexKey,
442
+ gasCost: DEXALOT_GAS_COST,
443
+ poolAddresses: [this.mainnetRFQAddress],
444
+ },
445
+ ];
446
+ } catch (e: unknown) {
447
+ this.logger.error(
448
+ `Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
449
+ destToken.symbol || destToken.address
450
+ }, ${side}:`,
451
+ e,
452
+ );
453
+ return null;
454
+ }
455
+ }
456
+
457
+ generateRFQError(errorStr: string, swapIdentifier: string) {
458
+ const message = `${this.dexKey}-${this.network}: Failed to fetch RFQ for ${swapIdentifier}. ${errorStr}`;
459
+ this.logger.warn(message);
460
+ throw new DexalotRfqError(message);
461
+ }
462
+
463
+ async preProcessTransaction(
464
+ optimalSwapExchange: OptimalSwapExchange<DexalotData>,
465
+ srcToken: Token,
466
+ destToken: Token,
467
+ side: SwapSide,
468
+ options: PreprocessTransactionOptions,
469
+ ): Promise<[OptimalSwapExchange<DexalotData>, ExchangeTxInfo]> {
470
+ if (await this.isBlacklisted(options.txOrigin)) {
471
+ this.logger.warn(
472
+ `${this.dexKey}-${this.network}: blacklisted TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`,
473
+ );
474
+ throw new Error(
475
+ `${this.dexKey}-${
476
+ this.network
477
+ }: user=${options.txOrigin.toLowerCase()} is blacklisted`,
478
+ );
479
+ }
480
+ if (await this.isRateLimited(options.txOrigin)) {
481
+ this.logger.warn(
482
+ `${this.dexKey}-${this.network}: rate limited TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`,
483
+ );
484
+ throw new Error(
485
+ `${this.dexKey}-${
486
+ this.network
487
+ }: user=${options.txOrigin.toLowerCase()} is rate limited`,
488
+ );
489
+ }
490
+ if (BigInt(optimalSwapExchange.srcAmount) === 0n) {
491
+ throw new Error('getFirmRate failed with srcAmount === 0');
492
+ }
493
+
494
+ const normalizedSrcToken = this.normalizeToken(srcToken);
495
+ const normalizedDestToken = this.normalizeToken(destToken);
496
+ const swapIdentifier = `${this.getIdentifier(
497
+ normalizedSrcToken.address,
498
+ normalizedDestToken.address,
499
+ )}_${side}`;
500
+
501
+ try {
502
+ const makerToken = normalizedDestToken;
503
+ const takerToken = normalizedSrcToken;
504
+
505
+ const rfqParams = {
506
+ makerAsset: ethers.utils.getAddress(makerToken.address),
507
+ takerAsset: ethers.utils.getAddress(takerToken.address),
508
+ makerAmount:
509
+ side === SwapSide.BUY ? optimalSwapExchange.destAmount : undefined,
510
+ takerAmount:
511
+ side === SwapSide.SELL ? optimalSwapExchange.srcAmount : undefined,
512
+ userAddress: options.txOrigin,
513
+ chainid: this.network,
514
+ };
515
+
516
+ const rfq: RFQResponse = await this.dexHelper.httpRequest.post(
517
+ `${DEXALOT_API_URL}/api/rfq/firm`,
518
+ rfqParams,
519
+ undefined,
520
+ { 'x-apikey': this.dexalotAuthToken },
521
+ );
522
+ if (!rfq) {
523
+ this.generateRFQError(
524
+ 'Missing quote data',
525
+ `RFQ ${swapIdentifier} ${JSON.stringify(rfq)}`,
526
+ );
527
+ } else if (!rfq.signature) {
528
+ this.generateRFQError('Missing signature', swapIdentifier);
529
+ }
530
+ rfq.order.signature = rfq.signature;
531
+
532
+ const { order } = rfq;
533
+
534
+ assert(
535
+ order.makerAsset.toLowerCase() === makerToken.address,
536
+ `QuoteData makerAsset=${order.makerAsset} is different from Paraswap makerAsset=${makerToken.address}`,
537
+ );
538
+ assert(
539
+ order.takerAsset.toLowerCase() === takerToken.address,
540
+ `QuoteData takerAsset=${order.takerAsset} is different from Paraswap takerAsset=${takerToken.address}`,
541
+ );
542
+ if (side === SwapSide.SELL) {
543
+ assert(
544
+ order.takerAmount === optimalSwapExchange.srcAmount,
545
+ `QuoteData takerAmount=${order.takerAmount} is different from Paraswap srcAmount=${optimalSwapExchange.srcAmount}`,
546
+ );
547
+ } else {
548
+ assert(
549
+ order.makerAmount === optimalSwapExchange.destAmount,
550
+ `QuoteData makerAmount=${order.makerAmount} is different from Paraswap destAmount=${optimalSwapExchange.destAmount}`,
551
+ );
552
+ }
553
+
554
+ const expiryAsBigInt = BigInt(order.expiry);
555
+ const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : BI_MAX_UINT256;
556
+
557
+ const slippageFactor = options.slippageFactor;
558
+ let isFailOnSlippage = false;
559
+ let slippageErrorMessage = '';
560
+
561
+ if (side === SwapSide.SELL) {
562
+ if (
563
+ BigInt(order.makerAmount) <
564
+ BigInt(
565
+ new BigNumber(optimalSwapExchange.destAmount.toString())
566
+ .times(slippageFactor)
567
+ .toFixed(0),
568
+ )
569
+ ) {
570
+ isFailOnSlippage = true;
571
+ const message = `${this.dexKey}-${this.network}: too much slippage on quote ${side} quoteTokenAmount ${order.makerAmount} / destAmount ${optimalSwapExchange.destAmount} < ${slippageFactor}`;
572
+ slippageErrorMessage = message;
573
+ this.logger.warn(message);
574
+ }
575
+ } else {
576
+ if (
577
+ BigInt(order.takerAmount) >
578
+ BigInt(slippageFactor.times(optimalSwapExchange.srcAmount.toString()).toFixed(0))
579
+ ) {
580
+ isFailOnSlippage = true;
581
+ const message = `${this.dexKey}-${
582
+ this.network
583
+ }: too much slippage on quote ${side} baseTokenAmount ${order.takerAmount} / srcAmount ${optimalSwapExchange.srcAmount} > ${slippageFactor.toFixed()}`;
584
+ slippageErrorMessage = message;
585
+ this.logger.warn(message);
586
+ }
587
+ }
588
+
589
+ let isTooStrictSlippage = false;
590
+ if (
591
+ isFailOnSlippage &&
592
+ side === SwapSide.SELL &&
593
+ new BigNumber(1)
594
+ .minus(slippageFactor)
595
+ .lt(DEXALOT_MIN_SLIPPAGE_FACTOR_THRESHOLD_FOR_RESTRICTION)
596
+ ) {
597
+ isTooStrictSlippage = true;
598
+ } else if (
599
+ isFailOnSlippage &&
600
+ side === SwapSide.BUY &&
601
+ slippageFactor
602
+ .minus(1)
603
+ .lt(DEXALOT_MIN_SLIPPAGE_FACTOR_THRESHOLD_FOR_RESTRICTION)
604
+ ) {
605
+ isTooStrictSlippage = true;
606
+ }
607
+
608
+ if (isFailOnSlippage && isTooStrictSlippage) {
609
+ throw new TooStrictSlippageCheckError(slippageErrorMessage);
610
+ } else if (isFailOnSlippage && !isTooStrictSlippage) {
611
+ throw new SlippageCheckError(slippageErrorMessage);
612
+ }
613
+
614
+ return [
615
+ {
616
+ ...optimalSwapExchange,
617
+ data: {
618
+ quoteData: order,
619
+ },
620
+ },
621
+ { deadline: minDeadline },
622
+ ];
623
+ } catch (e) {
624
+ if (isAxiosError(e) && e.response && e.response.data) {
625
+ const errorData: RFQResponseError = e.response.data;
626
+ if (errorData.ReasonCode === 'FQ-009') {
627
+ this.logger.warn(
628
+ `${this.dexKey}-${this.network}: Encountered rate limited user=${options.txOrigin}. Adding to local rate limit cache`,
629
+ );
630
+ await this.setRateLimited(options.txOrigin, errorData.RetryAfter);
631
+ } else {
632
+ await this.setBlacklist(options.txOrigin);
633
+ this.logger.error(
634
+ `${this.dexKey}-${this.network}: Failed to fetch RFQ for ${swapIdentifier}: ${errorData.Reason}`,
635
+ );
636
+ }
637
+ } else {
638
+ if(e instanceof TooStrictSlippageCheckError) {
639
+ this.logger.warn(
640
+ `${this.dexKey}-${this.network}: failed to build transaction on side ${side} with too strict slippage. Skipping restriction`,
641
+ );
642
+ } else {
643
+ this.logger.warn(
644
+ `${this.dexKey}-${this.network}: protocol is restricted`,
645
+ );
646
+ await this.restrict();
647
+ }
648
+ }
649
+
650
+ throw e;
651
+ }
652
+ }
653
+
654
+ getCalldataGasCost(poolPrices: PoolPrices<DexalotData>): number | number[] {
655
+ return (
656
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
657
+ // addresses: makerAsset, takerAsset, maker, taker
658
+ CALLDATA_GAS_COST.ADDRESS * 4 +
659
+ // uint256: expiry
660
+ CALLDATA_GAS_COST.wordNonZeroBytes(16) +
661
+ // uint256: nonceAndMeta, makerAmount, takerAmount
662
+ CALLDATA_GAS_COST.AMOUNT * 3 +
663
+ // bytes: _signature (65 bytes)
664
+ CALLDATA_GAS_COST.FULL_WORD * 2 +
665
+ CALLDATA_GAS_COST.OFFSET_SMALL
666
+ );
667
+ }
668
+
669
+ getTokenFromAddress(address: Address): Token {
670
+ return this.tokensMap[this.normalizeAddress(address)];
671
+ }
672
+
673
+ getAdapterParam(
674
+ srcToken: string,
675
+ destToken: string,
676
+ srcAmount: string,
677
+ destAmount: string,
678
+ data: DexalotData,
679
+ side: SwapSide,
680
+ ): AdapterExchangeParam {
681
+ const { quoteData } = data;
682
+
683
+ assert(
684
+ quoteData !== undefined,
685
+ `${this.dexKey}-${this.network}: quoteData undefined`,
686
+ );
687
+
688
+ const params = [
689
+ {
690
+ nonceAndMeta: quoteData.nonceAndMeta,
691
+ expiry: quoteData.expiry,
692
+ makerAsset: quoteData.makerAsset,
693
+ takerAsset: quoteData.takerAsset,
694
+ maker: quoteData.maker,
695
+ taker: quoteData.taker,
696
+ makerAmount: quoteData.makerAmount,
697
+ takerAmount: quoteData.takerAmount,
698
+ },
699
+ quoteData.signature,
700
+ ];
701
+
702
+ const payload = this.abiCoder.encodeParameter(
703
+ {
704
+ ParentStruct: {
705
+ order: {
706
+ nonceAndMeta: 'uint256',
707
+ expiry: 'uint128',
708
+ makerAsset: 'address',
709
+ takerAsset: 'address',
710
+ maker: 'address',
711
+ taker: 'address',
712
+ makerAmount: 'uint256',
713
+ takerAmount: 'uint256',
714
+ },
715
+ signature: 'bytes',
716
+ },
717
+ },
718
+ {
719
+ order: params[0],
720
+ signature: params[1],
721
+ },
722
+ );
723
+
724
+ return {
725
+ targetExchange: this.mainnetRFQAddress,
726
+ payload,
727
+ networkFee: '0',
728
+ };
729
+ }
730
+
731
+ async restrict(ttl: number = DEXALOT_RESTRICT_TTL_S): Promise<boolean> {
732
+ await this.dexHelper.cache.setex(
733
+ this.dexKey,
734
+ this.network,
735
+ DEXALOT_RESTRICTED_CACHE_KEY,
736
+ ttl,
737
+ 'true',
738
+ );
739
+ return true;
740
+ }
741
+
742
+ async isRestricted(): Promise<boolean> {
743
+ const result = await this.dexHelper.cache.get(
744
+ this.dexKey,
745
+ this.network,
746
+ DEXALOT_RESTRICTED_CACHE_KEY,
747
+ );
748
+
749
+ return result === 'true';
750
+ }
751
+
752
+ async setBlacklist(txOrigin: Address, ttl: number = DEXALOT_BLACKLIST_CACHES_TTL_S,): Promise<boolean> {
753
+ const cachedBlacklist = await this.dexHelper.cache.get(
754
+ this.dexKey,
755
+ this.network,
756
+ this.blacklistCacheKey,
757
+ );
758
+
759
+ let blacklist: string[] = [];
760
+ if (cachedBlacklist) {
761
+ blacklist = JSON.parse(cachedBlacklist);
762
+ }
763
+
764
+ blacklist.push(txOrigin.toLowerCase());
765
+
766
+ this.dexHelper.cache.setex(
767
+ this.dexKey,
768
+ this.network,
769
+ this.blacklistCacheKey,
770
+ ttl,
771
+ JSON.stringify(blacklist),
772
+ );
773
+
774
+ return true;
775
+ }
776
+
777
+ async isBlacklisted(txOrigin: Address): Promise<boolean> {
778
+ const cachedBlacklist = await this.dexHelper.cache.get(
779
+ this.dexKey,
780
+ this.network,
781
+ this.blacklistCacheKey,
782
+ );
783
+
784
+ if (cachedBlacklist) {
785
+ const blacklist = JSON.parse(cachedBlacklist) as string[];
786
+ return blacklist.includes(txOrigin.toLowerCase());
787
+ }
788
+
789
+ return false;
790
+ }
791
+
792
+ getRateLimitedKey(address: Address) {
793
+ return `rate_limited_${address}`.toLowerCase();
794
+ }
795
+
796
+ async isRateLimited(txOrigin: Address): Promise<boolean> {
797
+ const result = await this.dexHelper.cache.get(
798
+ this.dexKey,
799
+ this.network,
800
+ this.getRateLimitedKey(txOrigin),
801
+ );
802
+ return result === DEXALOT_RATELIMIT_CACHE_VALUE;
803
+ }
804
+
805
+ async setRateLimited(txOrigin: Address, ttl = DEXALOT_RATE_LIMITED_TTL_S) {
806
+ await this.dexHelper.cache.setex(
807
+ this.dexKey,
808
+ this.network,
809
+ this.getRateLimitedKey(txOrigin),
810
+ ttl,
811
+ DEXALOT_RATELIMIT_CACHE_VALUE,
812
+ );
813
+ return true;
814
+ }
815
+
816
+ async getSimpleParam(
817
+ srcToken: string,
818
+ destToken: string,
819
+ srcAmount: string,
820
+ destAmount: string,
821
+ data: DexalotData,
822
+ side: SwapSide,
823
+ ): Promise<SimpleExchangeParam> {
824
+ const { quoteData } = data;
825
+
826
+ assert(
827
+ quoteData !== undefined,
828
+ `${this.dexKey}-${this.network}: quoteData undefined`,
829
+ );
830
+
831
+ const swapFunction = 'simpleSwap';
832
+ const swapFunctionParams = [
833
+ [
834
+ quoteData.nonceAndMeta,
835
+ quoteData.expiry,
836
+ quoteData.makerAsset,
837
+ quoteData.takerAsset,
838
+ quoteData.maker,
839
+ quoteData.taker,
840
+ quoteData.makerAmount,
841
+ quoteData.takerAmount,
842
+ ],
843
+ quoteData.signature,
844
+ ];
845
+
846
+ const swapData = this.rfqInterface.encodeFunctionData(
847
+ swapFunction,
848
+ swapFunctionParams,
849
+ );
850
+
851
+ return this.buildSimpleParamWithoutWETHConversion(
852
+ srcToken,
853
+ srcAmount,
854
+ destToken,
855
+ destAmount,
856
+ swapData,
857
+ this.mainnetRFQAddress,
858
+ );
859
+ }
860
+
861
+ async getTopPoolsForToken(
862
+ tokenAddress: Address,
863
+ limit: number,
864
+ ): Promise<PoolLiquidity[]> {
865
+ if (await this.isRestricted()) {
866
+ return [];
867
+ }
868
+
869
+ const normalizedTokenAddress = normalizeTokenAddress(tokenAddress);
870
+ const pairs = (await this.getCachedPairs()) || {};
871
+ this.tokensMap = (await this.getCachedTokens()) || {};
872
+ const tokensAddr = (await this.getCachedTokensAddr()) || {};
873
+ const token = this.getTokenFromAddress(normalizedTokenAddress);
874
+ if (!token) {
875
+ return [];
876
+ }
877
+
878
+ const tokenSymbol = token.symbol?.toLowerCase() || '';
879
+
880
+ let pairsByLiquidity = [];
881
+ for (const pairName of Object.keys(pairs)) {
882
+ if (!pairName.includes(tokenSymbol)) {
883
+ continue;
884
+ }
885
+
886
+ const tokensInPair = pairName.split('/');
887
+ if (tokensInPair.length !== 2) {
888
+ continue;
889
+ }
890
+
891
+ const [ baseToken, quoteToken ] = tokensInPair;
892
+ const addr = tokensAddr[baseToken.toLowerCase()];
893
+ let outputToken = this.getTokenFromAddress(addr);
894
+ if (baseToken === tokenSymbol) {
895
+ const addr = tokensAddr[quoteToken.toLowerCase()];
896
+ outputToken = this.getTokenFromAddress(addr);
897
+ }
898
+
899
+ const denormalizedToken = this.denormalizeToken(outputToken);
900
+
901
+ pairsByLiquidity.push({
902
+ exchange: this.dexKey,
903
+ address: this.mainnetRFQAddress,
904
+ connectorTokens: [{
905
+ address: denormalizedToken.address,
906
+ decimals: denormalizedToken.decimals,
907
+ }],
908
+ liquidityUSD: pairs[pairName].liquidityUSD,
909
+ });
910
+ }
911
+
912
+ pairsByLiquidity.sort(
913
+ (a: PoolLiquidity, b: PoolLiquidity) => b.liquidityUSD - a.liquidityUSD,
914
+ );
915
+
916
+ return pairsByLiquidity.slice(0, limit);
917
+ }
918
+
919
+ getAPIReqParams(endpoint: string, method: Method): DexalotAPIParameters {
920
+ return {
921
+ url: `${DEXALOT_API_URL}/${endpoint}`,
922
+ headers: { 'x-apikey': this.dexalotAuthToken },
923
+ params: {
924
+ chainid: this.network,
925
+ },
926
+ method: method,
927
+ };
928
+ }
929
+
930
+ releaseResources(): void {
931
+ if (this.rateFetcher) {
932
+ this.rateFetcher.stop();
933
+ }
934
+ }
935
+ }