@paraswap/dex-lib 3.11.6 → 3.11.7-cables.0
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/dex/bebop/bebop.js +1 -1
- package/build/dex/bebop/bebop.js.map +1 -1
- package/build/dex/cables/cables.js +28 -36
- package/build/dex/cables/cables.js.map +1 -1
- package/build/dex/index.js +2 -0
- package/build/dex/index.js.map +1 -1
- package/package.json +1 -1
- package/src/abi/cables/CablesMainnetRFQ.json +1083 -0
- package/src/dex/bebop/bebop.ts +1 -1
- package/src/dex/cables/cables-e2e.test.ts +207 -0
- package/src/dex/cables/cables-integration.test.ts +319 -0
- package/src/dex/cables/cables.ts +911 -0
- package/src/dex/cables/config.ts +13 -0
- package/src/dex/cables/constants.ts +35 -0
- package/src/dex/cables/rate-fetcher.ts +212 -0
- package/src/dex/cables/types.ts +128 -0
- package/src/dex/cables/validators.test.ts +151 -0
- package/src/dex/cables/validators.ts +61 -0
- package/src/dex/index.ts +2 -0
- package/tests/constants-e2e.ts +2 -2
|
@@ -0,0 +1,911 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Address,
|
|
3
|
+
NumberAsString,
|
|
4
|
+
OptimalSwapExchange,
|
|
5
|
+
SwapSide,
|
|
6
|
+
} from '@paraswap/core';
|
|
7
|
+
import { assert, AsyncOrSync } from 'ts-essentials';
|
|
8
|
+
import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
|
|
9
|
+
import { ETHER_ADDRESS, Network, NULL_ADDRESS } from '../../constants';
|
|
10
|
+
import { IDexHelper } from '../../dex-helper';
|
|
11
|
+
import {
|
|
12
|
+
AdapterExchangeParam,
|
|
13
|
+
DexExchangeParam,
|
|
14
|
+
ExchangePrices,
|
|
15
|
+
ExchangeTxInfo,
|
|
16
|
+
Logger,
|
|
17
|
+
PoolLiquidity,
|
|
18
|
+
PoolPrices,
|
|
19
|
+
PreprocessTransactionOptions,
|
|
20
|
+
Token,
|
|
21
|
+
TransferFeeParams,
|
|
22
|
+
} from '../../types';
|
|
23
|
+
import { getDexKeysWithNetwork, Utils } from '../../utils';
|
|
24
|
+
import { IDex } from '../idex';
|
|
25
|
+
import { SimpleExchange } from '../simple-exchange';
|
|
26
|
+
import { CablesConfig } from './config';
|
|
27
|
+
import {
|
|
28
|
+
CABLES_API_BLACKLIST_POLLING_INTERVAL_MS,
|
|
29
|
+
CABLES_API_PAIRS_POLLING_INTERVAL_MS,
|
|
30
|
+
CABLES_API_PRICES_POLLING_INTERVAL_MS,
|
|
31
|
+
CABLES_API_TOKENS_POLLING_INTERVAL_MS,
|
|
32
|
+
CABLES_API_URL,
|
|
33
|
+
CABLES_BLACKLIST_CACHE_KEY,
|
|
34
|
+
CABLES_BLACKLIST_CACHES_TTL_S,
|
|
35
|
+
CABLES_ERRORS_CACHE_KEY,
|
|
36
|
+
CABLES_FIRM_QUOTE_TIMEOUT_MS,
|
|
37
|
+
CABLES_GAS_COST,
|
|
38
|
+
CABLES_PAIRS_CACHES_TTL_S,
|
|
39
|
+
CABLES_PRICES_CACHES_TTL_S,
|
|
40
|
+
CABLES_RESTRICT_CHECK_INTERVAL_MS,
|
|
41
|
+
CABLES_RESTRICT_COUNT_THRESHOLD,
|
|
42
|
+
CABLES_RESTRICT_TTL_S,
|
|
43
|
+
CABLES_RESTRICTED_CACHE_KEY,
|
|
44
|
+
CABLES_TOKENS_CACHES_TTL_S,
|
|
45
|
+
} from './constants';
|
|
46
|
+
import { CablesRateFetcher } from './rate-fetcher';
|
|
47
|
+
import {
|
|
48
|
+
CablesData,
|
|
49
|
+
CablesRFQResponse,
|
|
50
|
+
RestrictData,
|
|
51
|
+
SlippageError,
|
|
52
|
+
} from './types';
|
|
53
|
+
import mainnetRFQAbi from '../../abi/cables/CablesMainnetRFQ.json';
|
|
54
|
+
import { Interface } from 'ethers/lib/utils';
|
|
55
|
+
import BigNumber from 'bignumber.js';
|
|
56
|
+
import { ethers } from 'ethers';
|
|
57
|
+
import { BI_MAX_UINT256 } from '../../bigint-constants';
|
|
58
|
+
|
|
59
|
+
export class Cables extends SimpleExchange implements IDex<any> {
|
|
60
|
+
public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
|
|
61
|
+
getDexKeysWithNetwork(CablesConfig);
|
|
62
|
+
|
|
63
|
+
readonly isStatePollingDex = true;
|
|
64
|
+
|
|
65
|
+
private rateFetcher: CablesRateFetcher;
|
|
66
|
+
|
|
67
|
+
logger: Logger;
|
|
68
|
+
private tokensMap: { [address: string]: Token } = {};
|
|
69
|
+
|
|
70
|
+
hasConstantPriceLargeAmounts: boolean = false;
|
|
71
|
+
|
|
72
|
+
constructor(
|
|
73
|
+
readonly network: Network,
|
|
74
|
+
readonly dexKey: string,
|
|
75
|
+
readonly dexHelper: IDexHelper,
|
|
76
|
+
readonly mainnetRFQAddress: string = CablesConfig['Cables'][network]
|
|
77
|
+
.mainnetRFQAddress,
|
|
78
|
+
protected rfqInterface = new Interface(mainnetRFQAbi),
|
|
79
|
+
) {
|
|
80
|
+
super(dexHelper, dexKey);
|
|
81
|
+
this.logger = dexHelper.getLogger(dexKey);
|
|
82
|
+
|
|
83
|
+
this.rateFetcher = new CablesRateFetcher(
|
|
84
|
+
this.dexHelper,
|
|
85
|
+
this.dexKey,
|
|
86
|
+
this.network,
|
|
87
|
+
this.logger,
|
|
88
|
+
{
|
|
89
|
+
rateConfig: {
|
|
90
|
+
pairsReqParams: {
|
|
91
|
+
url: CABLES_API_URL + '/pairs',
|
|
92
|
+
},
|
|
93
|
+
pricesReqParams: {
|
|
94
|
+
url: CABLES_API_URL + '/prices',
|
|
95
|
+
},
|
|
96
|
+
blacklistReqParams: {
|
|
97
|
+
url: CABLES_API_URL + '/blacklist',
|
|
98
|
+
},
|
|
99
|
+
tokensReqParams: {
|
|
100
|
+
url: CABLES_API_URL + '/tokens',
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
pricesIntervalMs: CABLES_API_PRICES_POLLING_INTERVAL_MS,
|
|
104
|
+
pricesCacheTTLSecs: CABLES_PRICES_CACHES_TTL_S,
|
|
105
|
+
pricesCacheKey: 'cablesPricesCacheKey',
|
|
106
|
+
|
|
107
|
+
pairsIntervalMs: CABLES_API_PAIRS_POLLING_INTERVAL_MS,
|
|
108
|
+
pairsCacheTTLSecs: CABLES_PAIRS_CACHES_TTL_S,
|
|
109
|
+
pairsCacheKey: 'cablesPairsCacheKey',
|
|
110
|
+
|
|
111
|
+
tokensIntervalMs: CABLES_API_TOKENS_POLLING_INTERVAL_MS,
|
|
112
|
+
tokensCacheTTLSecs: CABLES_TOKENS_CACHES_TTL_S,
|
|
113
|
+
tokensCacheKey: 'cablesTokensCacheKey',
|
|
114
|
+
|
|
115
|
+
blacklistIntervalMs: CABLES_API_BLACKLIST_POLLING_INTERVAL_MS,
|
|
116
|
+
blacklistCacheTTLSecs: CABLES_BLACKLIST_CACHES_TTL_S,
|
|
117
|
+
blacklistCacheKey: CABLES_BLACKLIST_CACHE_KEY,
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async preProcessTransaction?(
|
|
124
|
+
optimalSwapExchange: OptimalSwapExchange<CablesData>,
|
|
125
|
+
srcToken: Token,
|
|
126
|
+
destToken: Token,
|
|
127
|
+
side: SwapSide,
|
|
128
|
+
options: PreprocessTransactionOptions,
|
|
129
|
+
): Promise<[OptimalSwapExchange<CablesData>, ExchangeTxInfo]> {
|
|
130
|
+
if (await this.isBlacklisted(options.txOrigin)) {
|
|
131
|
+
this.logger.warn(
|
|
132
|
+
`${this.dexKey}-${this.network}: blacklisted TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`,
|
|
133
|
+
);
|
|
134
|
+
throw new Error(
|
|
135
|
+
`${this.dexKey}-${
|
|
136
|
+
this.network
|
|
137
|
+
}: user=${options.txOrigin.toLowerCase()} is blacklisted`,
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (BigInt(optimalSwapExchange.srcAmount) === 0n) {
|
|
142
|
+
throw new Error('getFirmRate failed with srcAmount === 0');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const normalizedSrcToken = this.normalizeToken(srcToken);
|
|
146
|
+
const normalizedDestToken = this.normalizeToken(destToken);
|
|
147
|
+
const swapIdentifier = `${this.dexKey}_${normalizedSrcToken.address}_${normalizedDestToken.address}_${side}`;
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
let makerToken = normalizedDestToken;
|
|
151
|
+
let takerToken = normalizedSrcToken;
|
|
152
|
+
|
|
153
|
+
const isSell = side === SwapSide.SELL;
|
|
154
|
+
const isBuy = side === SwapSide.BUY;
|
|
155
|
+
|
|
156
|
+
const rfqParams = {
|
|
157
|
+
makerAsset: ethers.utils.getAddress(makerToken.address),
|
|
158
|
+
takerAsset: ethers.utils.getAddress(takerToken.address),
|
|
159
|
+
...(isBuy && { makerAmount: optimalSwapExchange.destAmount }),
|
|
160
|
+
...(isSell && { takerAmount: optimalSwapExchange.srcAmount }),
|
|
161
|
+
userAddress: options.executionContractAddress,
|
|
162
|
+
chainId: String(this.network),
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const rfq: CablesRFQResponse = await this.dexHelper.httpRequest.post(
|
|
166
|
+
`${CABLES_API_URL}/quote`,
|
|
167
|
+
rfqParams,
|
|
168
|
+
CABLES_FIRM_QUOTE_TIMEOUT_MS,
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
if (!rfq) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
'Failed to fetch RFQ' +
|
|
174
|
+
swapIdentifier +
|
|
175
|
+
JSON.stringify(rfq + 'params' + rfqParams),
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const { order } = rfq;
|
|
180
|
+
|
|
181
|
+
assert(
|
|
182
|
+
order.makerAsset.toLowerCase() === makerToken.address,
|
|
183
|
+
`QuoteData makerAsset=${order.makerAsset} is different from Paraswap makerAsset=${makerToken.address}`,
|
|
184
|
+
);
|
|
185
|
+
assert(
|
|
186
|
+
order.takerAsset.toLowerCase() === takerToken.address,
|
|
187
|
+
`QuoteData takerAsset=${order.takerAsset} is different from Paraswap takerAsset=${takerToken.address}`,
|
|
188
|
+
);
|
|
189
|
+
if (isSell) {
|
|
190
|
+
assert(
|
|
191
|
+
order.takerAmount === optimalSwapExchange.srcAmount,
|
|
192
|
+
`QuoteData takerAmount=${order.takerAmount} is different from Paraswap srcAmount=${optimalSwapExchange.srcAmount}`,
|
|
193
|
+
);
|
|
194
|
+
} else {
|
|
195
|
+
assert(
|
|
196
|
+
order.makerAmount === optimalSwapExchange.destAmount,
|
|
197
|
+
`QuoteData makerAmount=${order.makerAmount} is different from Paraswap destAmount=${optimalSwapExchange.destAmount}`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const expiryAsBigInt = BigInt(order.expiry);
|
|
202
|
+
const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : BI_MAX_UINT256;
|
|
203
|
+
|
|
204
|
+
if (side === SwapSide.BUY) {
|
|
205
|
+
const requiredAmount = BigInt(optimalSwapExchange.srcAmount);
|
|
206
|
+
const quoteAmount = BigInt(order.takerAmount);
|
|
207
|
+
const requiredAmountWithSlippage = new BigNumber(
|
|
208
|
+
requiredAmount.toString(),
|
|
209
|
+
)
|
|
210
|
+
.multipliedBy(options.slippageFactor)
|
|
211
|
+
.toFixed(0);
|
|
212
|
+
if (quoteAmount > BigInt(requiredAmountWithSlippage)) {
|
|
213
|
+
throw new SlippageError(
|
|
214
|
+
`Slipped, factor: ${quoteAmount.toString()} > ${requiredAmountWithSlippage}`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
} else {
|
|
218
|
+
const requiredAmount = BigInt(optimalSwapExchange.destAmount);
|
|
219
|
+
const quoteAmount = BigInt(order.makerAmount);
|
|
220
|
+
const requiredAmountWithSlippage = new BigNumber(
|
|
221
|
+
requiredAmount.toString(),
|
|
222
|
+
)
|
|
223
|
+
.multipliedBy(options.slippageFactor)
|
|
224
|
+
.toFixed(0);
|
|
225
|
+
if (quoteAmount < BigInt(requiredAmountWithSlippage)) {
|
|
226
|
+
throw new SlippageError(
|
|
227
|
+
`Slipped, factor: ${
|
|
228
|
+
options.slippageFactor
|
|
229
|
+
} ${quoteAmount.toString()} < ${requiredAmountWithSlippage}`,
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return [
|
|
235
|
+
{
|
|
236
|
+
...optimalSwapExchange,
|
|
237
|
+
data: {
|
|
238
|
+
quoteData: order,
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
{ deadline: minDeadline },
|
|
242
|
+
];
|
|
243
|
+
} catch (e: any) {
|
|
244
|
+
const message = `${this.dexKey}-${this.network}: ${e}`;
|
|
245
|
+
this.logger.error(message);
|
|
246
|
+
if (!e?.isSlippageError) {
|
|
247
|
+
this.restrict();
|
|
248
|
+
}
|
|
249
|
+
throw new Error(message);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
getDexParam(
|
|
254
|
+
srcToken: Address,
|
|
255
|
+
destToken: Address,
|
|
256
|
+
srcAmount: NumberAsString,
|
|
257
|
+
destAmount: NumberAsString,
|
|
258
|
+
recipient: Address,
|
|
259
|
+
data: CablesData,
|
|
260
|
+
side: SwapSide,
|
|
261
|
+
): DexExchangeParam {
|
|
262
|
+
const { quoteData } = data;
|
|
263
|
+
|
|
264
|
+
assert(
|
|
265
|
+
quoteData !== undefined,
|
|
266
|
+
`${this.dexKey}-${this.network}: quoteData undefined`,
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
const swapFunction = 'simpleSwap';
|
|
270
|
+
const swapFunctionParams = [
|
|
271
|
+
[
|
|
272
|
+
quoteData.nonceAndMeta,
|
|
273
|
+
quoteData.expiry,
|
|
274
|
+
quoteData.makerAsset,
|
|
275
|
+
quoteData.takerAsset,
|
|
276
|
+
quoteData.maker,
|
|
277
|
+
quoteData.taker,
|
|
278
|
+
quoteData.makerAmount,
|
|
279
|
+
quoteData.takerAmount,
|
|
280
|
+
],
|
|
281
|
+
quoteData.signature,
|
|
282
|
+
];
|
|
283
|
+
|
|
284
|
+
const exchangeData = this.rfqInterface.encodeFunctionData(
|
|
285
|
+
swapFunction,
|
|
286
|
+
swapFunctionParams,
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
return {
|
|
290
|
+
exchangeData,
|
|
291
|
+
swappedAmountNotPresentInExchangeData: true, // to prevent insert from amount
|
|
292
|
+
needWrapNative: this.needWrapNative,
|
|
293
|
+
dexFuncHasRecipient: false,
|
|
294
|
+
targetExchange: this.mainnetRFQAddress,
|
|
295
|
+
returnAmountPos: undefined,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
getAdapterParam(
|
|
300
|
+
srcToken: string,
|
|
301
|
+
destToken: string,
|
|
302
|
+
srcAmount: string,
|
|
303
|
+
destAmount: string,
|
|
304
|
+
data: CablesData,
|
|
305
|
+
side: SwapSide,
|
|
306
|
+
): AdapterExchangeParam {
|
|
307
|
+
const { quoteData } = data;
|
|
308
|
+
|
|
309
|
+
assert(
|
|
310
|
+
quoteData !== undefined,
|
|
311
|
+
`${this.dexKey}-${this.network}: quoteData undefined`,
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
const params = [
|
|
315
|
+
{
|
|
316
|
+
nonceAndMeta: quoteData.nonceAndMeta,
|
|
317
|
+
expiry: quoteData.expiry,
|
|
318
|
+
makerAsset: quoteData.makerAsset,
|
|
319
|
+
takerAsset: quoteData.takerAsset,
|
|
320
|
+
maker: quoteData.maker,
|
|
321
|
+
taker: quoteData.taker,
|
|
322
|
+
makerAmount: quoteData.makerAmount,
|
|
323
|
+
takerAmount: quoteData.takerAmount,
|
|
324
|
+
},
|
|
325
|
+
quoteData.signature,
|
|
326
|
+
];
|
|
327
|
+
|
|
328
|
+
const payload = this.abiCoder.encodeParameter(
|
|
329
|
+
{
|
|
330
|
+
ParentStruct: {
|
|
331
|
+
order: {
|
|
332
|
+
nonceAndMeta: 'uint256',
|
|
333
|
+
expiry: 'uint128',
|
|
334
|
+
makerAsset: 'address',
|
|
335
|
+
takerAsset: 'address',
|
|
336
|
+
maker: 'address',
|
|
337
|
+
taker: 'address',
|
|
338
|
+
makerAmount: 'uint256',
|
|
339
|
+
takerAmount: 'uint256',
|
|
340
|
+
},
|
|
341
|
+
signature: 'bytes',
|
|
342
|
+
},
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
order: params[0],
|
|
346
|
+
signature: params[1],
|
|
347
|
+
},
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
targetExchange: this.mainnetRFQAddress,
|
|
352
|
+
payload,
|
|
353
|
+
networkFee: '0',
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
normalizeToken(token: Token): Token {
|
|
358
|
+
return {
|
|
359
|
+
...token,
|
|
360
|
+
address: this.normalizeTokenAddress(token.address),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
normalizeTokenAddress(address: Address): Address {
|
|
365
|
+
return address.toLowerCase();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
getTokenFromAddress(address: Address): Token {
|
|
369
|
+
return this.tokensMap[this.normalizeAddress(address)];
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
getPoolIdentifier(srcAddress: Address, destAddress: Address, mm?: string) {
|
|
373
|
+
return `${this.dexKey}_${srcAddress}_${destAddress}`.toLowerCase();
|
|
374
|
+
return `${this.dexKey}_${srcAddress}_${destAddress}_${mm}`.toLowerCase();
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async getPoolIdentifiers(
|
|
378
|
+
srcToken: Token,
|
|
379
|
+
destToken: Token,
|
|
380
|
+
side: SwapSide,
|
|
381
|
+
blockNumber: number,
|
|
382
|
+
): Promise<string[]> {
|
|
383
|
+
if (!srcToken || !destToken) {
|
|
384
|
+
return [];
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (srcToken.address.toLowerCase() === destToken.address.toLowerCase()) {
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const pairData = await this.getPairData(srcToken, destToken);
|
|
392
|
+
|
|
393
|
+
if (!pairData) {
|
|
394
|
+
return [];
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const tokensAddr = (await this.getCachedTokensAddr()) || {};
|
|
398
|
+
|
|
399
|
+
return [
|
|
400
|
+
this.getPoolIdentifier(
|
|
401
|
+
tokensAddr[pairData.base.toLowerCase()],
|
|
402
|
+
tokensAddr[pairData.quote.toLowerCase()],
|
|
403
|
+
),
|
|
404
|
+
];
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
calculateOrderPrice(
|
|
408
|
+
amounts: bigint[],
|
|
409
|
+
orderbook: string[][],
|
|
410
|
+
baseToken: Token,
|
|
411
|
+
quoteToken: Token,
|
|
412
|
+
isInputQuote: boolean,
|
|
413
|
+
) {
|
|
414
|
+
let result = [];
|
|
415
|
+
|
|
416
|
+
for (let i = 0; i < amounts.length; i++) {
|
|
417
|
+
let amt = amounts[i];
|
|
418
|
+
if (amt === 0n) {
|
|
419
|
+
result.push(amt);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
let decimals = baseToken.decimals;
|
|
424
|
+
let out_decimals = quoteToken.decimals;
|
|
425
|
+
|
|
426
|
+
let price = this.calculatePriceSwap(
|
|
427
|
+
orderbook,
|
|
428
|
+
Number(amt) / 10 ** decimals,
|
|
429
|
+
isInputQuote,
|
|
430
|
+
);
|
|
431
|
+
result.push(BigInt(Math.round(price * 10 ** out_decimals)));
|
|
432
|
+
}
|
|
433
|
+
return result;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
calculatePriceSwap(
|
|
437
|
+
prices: string[][],
|
|
438
|
+
requiredQty: number,
|
|
439
|
+
qtyMode: Boolean,
|
|
440
|
+
) {
|
|
441
|
+
let sumBaseQty = 0;
|
|
442
|
+
let sumQuoteQty = 0;
|
|
443
|
+
const selectedRows: string[][] = [];
|
|
444
|
+
|
|
445
|
+
const isBase = qtyMode;
|
|
446
|
+
const isQuote = !qtyMode;
|
|
447
|
+
|
|
448
|
+
for (const [price, volume] of prices) {
|
|
449
|
+
if (isBase) {
|
|
450
|
+
if (sumBaseQty >= requiredQty) {
|
|
451
|
+
break;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (isQuote) {
|
|
456
|
+
if (sumQuoteQty >= requiredQty) {
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
let currentBaseQty = Number(volume);
|
|
462
|
+
let currentQuoteQty = Number(volume) * Number(price);
|
|
463
|
+
|
|
464
|
+
const overQty = isBase
|
|
465
|
+
? currentBaseQty + sumBaseQty > requiredQty
|
|
466
|
+
: currentQuoteQty + sumQuoteQty > requiredQty;
|
|
467
|
+
|
|
468
|
+
if (overQty) {
|
|
469
|
+
if (isBase) {
|
|
470
|
+
currentBaseQty = requiredQty - sumBaseQty;
|
|
471
|
+
currentQuoteQty = currentBaseQty * Number(price);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if (isQuote) {
|
|
475
|
+
currentQuoteQty = requiredQty - sumQuoteQty;
|
|
476
|
+
currentBaseQty =
|
|
477
|
+
currentQuoteQty *
|
|
478
|
+
new BigNumber(1).dividedBy(new BigNumber(price)).toNumber();
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
sumBaseQty += currentBaseQty;
|
|
483
|
+
sumQuoteQty += currentQuoteQty;
|
|
484
|
+
selectedRows.push([price, currentBaseQty.toString()]);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const vSumBase = selectedRows.reduce((sum: number, [price, volume]) => {
|
|
488
|
+
return sum + Number(price) * Number(volume);
|
|
489
|
+
}, 0);
|
|
490
|
+
|
|
491
|
+
const price = new BigNumber(vSumBase)
|
|
492
|
+
.dividedBy(new BigNumber(sumBaseQty))
|
|
493
|
+
.toNumber();
|
|
494
|
+
|
|
495
|
+
if (isBase) {
|
|
496
|
+
return requiredQty / price;
|
|
497
|
+
} else {
|
|
498
|
+
return requiredQty * price;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async getPricesVolume(
|
|
503
|
+
srcToken: Token,
|
|
504
|
+
destToken: Token,
|
|
505
|
+
amounts: bigint[],
|
|
506
|
+
side: SwapSide,
|
|
507
|
+
blockNumber: number,
|
|
508
|
+
limitPools?: string[],
|
|
509
|
+
transferFees?: TransferFeeParams,
|
|
510
|
+
isFirstSwap?: boolean,
|
|
511
|
+
): Promise<ExchangePrices<CablesData> | null> {
|
|
512
|
+
const isRestricted = await this.isRestricted();
|
|
513
|
+
if (isRestricted) {
|
|
514
|
+
return null;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
try {
|
|
518
|
+
const normalizedSrcToken = this.normalizeToken(srcToken);
|
|
519
|
+
const normalizedDestToken = this.normalizeToken(destToken);
|
|
520
|
+
// If: same token, return null
|
|
521
|
+
if (
|
|
522
|
+
normalizedSrcToken.address.toLowerCase() ===
|
|
523
|
+
normalizedDestToken.address.toLowerCase()
|
|
524
|
+
) {
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// Ensure that "symbol" is set
|
|
529
|
+
const tokens = await this.getCachedTokens();
|
|
530
|
+
this.tokensMap = Object.keys(tokens).reduce((acc, key) => {
|
|
531
|
+
//@ts-ignore
|
|
532
|
+
acc[tokens[key].address.toLowerCase()] = tokens[key];
|
|
533
|
+
return acc;
|
|
534
|
+
}, {});
|
|
535
|
+
|
|
536
|
+
for (const symbol of Object.keys(tokens)) {
|
|
537
|
+
const normalizedTokenAddress = tokens[symbol].address.toLowerCase();
|
|
538
|
+
|
|
539
|
+
if (normalizedSrcToken.address === normalizedTokenAddress) {
|
|
540
|
+
normalizedSrcToken.symbol = tokens[symbol].symbol;
|
|
541
|
+
}
|
|
542
|
+
if (normalizedDestToken.address === normalizedTokenAddress) {
|
|
543
|
+
normalizedDestToken.symbol = tokens[symbol].symbol;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// ---------- Pools ----------
|
|
548
|
+
let pools = await this.getPoolIdentifiers(
|
|
549
|
+
srcToken,
|
|
550
|
+
destToken,
|
|
551
|
+
side,
|
|
552
|
+
blockNumber,
|
|
553
|
+
);
|
|
554
|
+
if (pools.length === 0) return null;
|
|
555
|
+
|
|
556
|
+
// ---------- Prices ----------
|
|
557
|
+
const priceMap = await this.getCachedPrices();
|
|
558
|
+
|
|
559
|
+
if (!priceMap) return null;
|
|
560
|
+
|
|
561
|
+
let isInputQuote = false;
|
|
562
|
+
let pairKey = `${normalizedSrcToken.symbol}/${normalizedDestToken.symbol}`;
|
|
563
|
+
const pairsKeys = Object.keys(priceMap);
|
|
564
|
+
|
|
565
|
+
if (!pairsKeys.includes(pairKey)) {
|
|
566
|
+
// Revert
|
|
567
|
+
isInputQuote = true;
|
|
568
|
+
pairKey = `${normalizedDestToken.symbol}/${normalizedSrcToken.symbol}`;
|
|
569
|
+
if (!pairsKeys.includes(pairKey)) {
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Orderbook
|
|
576
|
+
*/
|
|
577
|
+
const priceData = priceMap[pairKey];
|
|
578
|
+
|
|
579
|
+
let orderbook: any[] = [];
|
|
580
|
+
if (side === SwapSide.BUY) {
|
|
581
|
+
orderbook = priceData.asks;
|
|
582
|
+
} else {
|
|
583
|
+
orderbook = priceData.bids;
|
|
584
|
+
}
|
|
585
|
+
if (orderbook?.length === 0) {
|
|
586
|
+
throw new Error(`Empty orderbook for ${pairKey}`);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const prices = this.calculateOrderPrice(
|
|
590
|
+
amounts,
|
|
591
|
+
orderbook,
|
|
592
|
+
side === SwapSide.SELL ? srcToken : destToken,
|
|
593
|
+
side === SwapSide.SELL ? destToken : srcToken,
|
|
594
|
+
side === SwapSide.SELL ? isInputQuote : !isInputQuote,
|
|
595
|
+
);
|
|
596
|
+
|
|
597
|
+
const result = [
|
|
598
|
+
{
|
|
599
|
+
prices: prices,
|
|
600
|
+
unit: BigInt(normalizedDestToken.decimals),
|
|
601
|
+
exchange: this.dexKey,
|
|
602
|
+
gasCost: CABLES_GAS_COST,
|
|
603
|
+
poolAddresses: [this.mainnetRFQAddress],
|
|
604
|
+
data: {},
|
|
605
|
+
},
|
|
606
|
+
];
|
|
607
|
+
|
|
608
|
+
return result;
|
|
609
|
+
} catch (e: unknown) {
|
|
610
|
+
this.logger.error(
|
|
611
|
+
`Error in getPricesVolume`,
|
|
612
|
+
{
|
|
613
|
+
srcToken: srcToken.address || srcToken.symbol,
|
|
614
|
+
destToken: destToken.address || destToken.symbol,
|
|
615
|
+
side,
|
|
616
|
+
},
|
|
617
|
+
e,
|
|
618
|
+
);
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
getCalldataGasCost(poolPrices: PoolPrices<CablesData>): number | number[] {
|
|
624
|
+
return (
|
|
625
|
+
CALLDATA_GAS_COST.DEX_OVERHEAD +
|
|
626
|
+
// addresses: makerAsset, takerAsset, maker, taker
|
|
627
|
+
CALLDATA_GAS_COST.ADDRESS * 4 +
|
|
628
|
+
// uint256: expiry
|
|
629
|
+
CALLDATA_GAS_COST.wordNonZeroBytes(16) +
|
|
630
|
+
// uint256: nonceAndMeta, makerAmount, takerAmount
|
|
631
|
+
CALLDATA_GAS_COST.AMOUNT * 3 +
|
|
632
|
+
// bytes: _signature (65 bytes)
|
|
633
|
+
CALLDATA_GAS_COST.FULL_WORD * 2 +
|
|
634
|
+
CALLDATA_GAS_COST.OFFSET_SMALL
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async initializePricing(blockNumber: number): Promise<void> {
|
|
639
|
+
if (!this.dexHelper.config.isSlave) {
|
|
640
|
+
this.rateFetcher.start();
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
getAdapters(side: SwapSide): { name: string; index: number }[] | null {
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
releaseResources?(): AsyncOrSync<void> {
|
|
651
|
+
if (this.rateFetcher) {
|
|
652
|
+
this.rateFetcher.stop();
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
normalizeAddress(address: string): string {
|
|
657
|
+
return address.toLowerCase() === ETHER_ADDRESS
|
|
658
|
+
? NULL_ADDRESS
|
|
659
|
+
: address.toLowerCase();
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async getTopPoolsForToken(
|
|
663
|
+
tokenAddress: Address,
|
|
664
|
+
limit: number,
|
|
665
|
+
): Promise<PoolLiquidity[]> {
|
|
666
|
+
const tokens = (await this.getCachedTokens()) as { [key: string]: Token };
|
|
667
|
+
const token = Object.values(tokens).find(
|
|
668
|
+
token => token.address.toLowerCase() === tokenAddress.toLowerCase(),
|
|
669
|
+
);
|
|
670
|
+
|
|
671
|
+
if (!token) {
|
|
672
|
+
return [];
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
const tokenPriceUsd = await this.dexHelper.getTokenUSDPrice(
|
|
676
|
+
token,
|
|
677
|
+
BigInt(10 ** token.decimals),
|
|
678
|
+
);
|
|
679
|
+
|
|
680
|
+
const erc20BalanceCalldata = this.erc20Interface.encodeFunctionData(
|
|
681
|
+
'balanceOf',
|
|
682
|
+
[this.mainnetRFQAddress],
|
|
683
|
+
);
|
|
684
|
+
const tokenBalanceMultiCall = [
|
|
685
|
+
{
|
|
686
|
+
target: token.address,
|
|
687
|
+
callData: erc20BalanceCalldata,
|
|
688
|
+
},
|
|
689
|
+
];
|
|
690
|
+
const res = (
|
|
691
|
+
await this.dexHelper.multiContract.methods
|
|
692
|
+
.aggregate(tokenBalanceMultiCall)
|
|
693
|
+
.call()
|
|
694
|
+
).returnData[0];
|
|
695
|
+
|
|
696
|
+
let tokenLiquidity = BigInt(res);
|
|
697
|
+
|
|
698
|
+
let tokenLiquidityUsd =
|
|
699
|
+
(tokenLiquidity * BigInt(tokenPriceUsd * 1_000_000)) /
|
|
700
|
+
BigInt(1_000_000 * 10 ** token.decimals);
|
|
701
|
+
|
|
702
|
+
let tokenWithLiquidity = [];
|
|
703
|
+
|
|
704
|
+
tokenWithLiquidity.push({
|
|
705
|
+
exchange: this.dexKey,
|
|
706
|
+
address: this.mainnetRFQAddress,
|
|
707
|
+
connectorTokens: [
|
|
708
|
+
{
|
|
709
|
+
address: token.address,
|
|
710
|
+
decimals: token.decimals,
|
|
711
|
+
},
|
|
712
|
+
],
|
|
713
|
+
liquidityUSD: Number(tokenLiquidityUsd),
|
|
714
|
+
});
|
|
715
|
+
|
|
716
|
+
return tokenWithLiquidity;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* CACHED UTILS
|
|
721
|
+
*/
|
|
722
|
+
async getCachedTokens(): Promise<any> {
|
|
723
|
+
const cachedTokens = await this.dexHelper.cache.get(
|
|
724
|
+
this.dexKey,
|
|
725
|
+
this.network,
|
|
726
|
+
this.rateFetcher.tokensCacheKey,
|
|
727
|
+
);
|
|
728
|
+
|
|
729
|
+
return cachedTokens ? JSON.parse(cachedTokens) : {};
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
async getCachedPairs(): Promise<any> {
|
|
733
|
+
const cachedPairs = await this.dexHelper.cache.get(
|
|
734
|
+
this.dexKey,
|
|
735
|
+
this.network,
|
|
736
|
+
this.rateFetcher.pairsCacheKey,
|
|
737
|
+
);
|
|
738
|
+
|
|
739
|
+
return cachedPairs ? JSON.parse(cachedPairs) : {};
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
async getCachedPrices(): Promise<any> {
|
|
743
|
+
const cachedPrices = await this.dexHelper.cache.get(
|
|
744
|
+
this.dexKey,
|
|
745
|
+
this.network,
|
|
746
|
+
this.rateFetcher.pricesCacheKey,
|
|
747
|
+
);
|
|
748
|
+
|
|
749
|
+
return cachedPrices ? JSON.parse(cachedPrices) : {};
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
async getCachedTokensAddr(): Promise<any> {
|
|
753
|
+
const tokens = await this.getCachedTokens();
|
|
754
|
+
const tokensAddr: Record<string, Address> = {};
|
|
755
|
+
for (const key of Object.keys(tokens)) {
|
|
756
|
+
tokensAddr[tokens[key].symbol.toLowerCase()] = tokens[key].address;
|
|
757
|
+
}
|
|
758
|
+
return tokensAddr;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
getPairString(baseToken: Token, quoteToken: Token): string {
|
|
762
|
+
return `${baseToken.symbol}/${quoteToken.symbol}`.toLowerCase();
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// Function to find a key by address
|
|
766
|
+
private findKeyByAddress = (
|
|
767
|
+
jsonData: Record<string, { address: string }>,
|
|
768
|
+
targetAddress: string,
|
|
769
|
+
): string | undefined => {
|
|
770
|
+
const entries = Object.entries(jsonData);
|
|
771
|
+
const foundEntry = entries.find(
|
|
772
|
+
([_, value]) =>
|
|
773
|
+
value.address.toLowerCase() === targetAddress.toLowerCase(),
|
|
774
|
+
);
|
|
775
|
+
return foundEntry ? foundEntry[0] : undefined;
|
|
776
|
+
};
|
|
777
|
+
|
|
778
|
+
async getPairData(srcToken: Token, destToken: Token): Promise<any> {
|
|
779
|
+
const normalizedSrcToken = this.normalizeToken(srcToken);
|
|
780
|
+
const normalizedDestToken = this.normalizeToken(destToken);
|
|
781
|
+
|
|
782
|
+
if (normalizedSrcToken.address === normalizedDestToken.address) {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const cachedTokens = await this.getCachedTokens();
|
|
787
|
+
|
|
788
|
+
normalizedSrcToken.symbol = this.findKeyByAddress(
|
|
789
|
+
cachedTokens,
|
|
790
|
+
normalizedSrcToken.address,
|
|
791
|
+
);
|
|
792
|
+
normalizedDestToken.symbol = this.findKeyByAddress(
|
|
793
|
+
cachedTokens,
|
|
794
|
+
normalizedDestToken.address,
|
|
795
|
+
);
|
|
796
|
+
|
|
797
|
+
const cachedPairs = await this.getCachedPairs();
|
|
798
|
+
|
|
799
|
+
const potentialPairs = [
|
|
800
|
+
{
|
|
801
|
+
base: normalizedSrcToken.symbol,
|
|
802
|
+
quote: normalizedDestToken.symbol,
|
|
803
|
+
identifier: this.getPairString(normalizedSrcToken, normalizedDestToken),
|
|
804
|
+
isSrcBase: true,
|
|
805
|
+
},
|
|
806
|
+
{
|
|
807
|
+
base: normalizedDestToken.symbol,
|
|
808
|
+
quote: normalizedSrcToken.symbol,
|
|
809
|
+
identifier: this.getPairString(normalizedDestToken, normalizedSrcToken),
|
|
810
|
+
isSrcBase: false,
|
|
811
|
+
},
|
|
812
|
+
];
|
|
813
|
+
|
|
814
|
+
for (const pair of potentialPairs) {
|
|
815
|
+
if (pair.identifier in cachedPairs) {
|
|
816
|
+
const pairData = cachedPairs[pair.identifier];
|
|
817
|
+
pairData.isSrcBase = pair.isSrcBase;
|
|
818
|
+
return pairData;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return null;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
async isBlacklisted(txOrigin: Address): Promise<boolean> {
|
|
825
|
+
const cachedBlacklist = await this.dexHelper.cache.get(
|
|
826
|
+
this.dexKey,
|
|
827
|
+
this.network,
|
|
828
|
+
CABLES_BLACKLIST_CACHE_KEY,
|
|
829
|
+
);
|
|
830
|
+
|
|
831
|
+
if (cachedBlacklist) {
|
|
832
|
+
const blacklist = JSON.parse(cachedBlacklist) as string[];
|
|
833
|
+
return blacklist.includes(txOrigin.toLowerCase());
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
async isRestricted(): Promise<boolean> {
|
|
840
|
+
const result = await this.dexHelper.cache.get(
|
|
841
|
+
this.dexKey,
|
|
842
|
+
this.network,
|
|
843
|
+
CABLES_RESTRICTED_CACHE_KEY,
|
|
844
|
+
);
|
|
845
|
+
|
|
846
|
+
return result === 'true';
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
async restrict() {
|
|
850
|
+
const errorsDataRaw = await this.dexHelper.cache.get(
|
|
851
|
+
this.dexKey,
|
|
852
|
+
this.network,
|
|
853
|
+
CABLES_ERRORS_CACHE_KEY,
|
|
854
|
+
);
|
|
855
|
+
|
|
856
|
+
const errorsData: RestrictData = Utils.Parse(errorsDataRaw);
|
|
857
|
+
const ERRORS_TTL_S = Math.floor(CABLES_RESTRICT_CHECK_INTERVAL_MS / 1000);
|
|
858
|
+
|
|
859
|
+
if (
|
|
860
|
+
!errorsData ||
|
|
861
|
+
errorsData?.addedDatetimeMs + CABLES_RESTRICT_CHECK_INTERVAL_MS <
|
|
862
|
+
Date.now()
|
|
863
|
+
) {
|
|
864
|
+
this.logger.warn(
|
|
865
|
+
`${this.dexKey}-${this.network}: First encounter of error OR error ocurred outside of threshold, setting up counter`,
|
|
866
|
+
);
|
|
867
|
+
const data: RestrictData = {
|
|
868
|
+
count: 1,
|
|
869
|
+
addedDatetimeMs: Date.now(),
|
|
870
|
+
};
|
|
871
|
+
await this.dexHelper.cache.setex(
|
|
872
|
+
this.dexKey,
|
|
873
|
+
this.network,
|
|
874
|
+
CABLES_ERRORS_CACHE_KEY,
|
|
875
|
+
ERRORS_TTL_S,
|
|
876
|
+
Utils.Serialize(data),
|
|
877
|
+
);
|
|
878
|
+
return;
|
|
879
|
+
} else {
|
|
880
|
+
if (errorsData.count + 1 >= CABLES_RESTRICT_COUNT_THRESHOLD) {
|
|
881
|
+
this.logger.warn(
|
|
882
|
+
`${this.dexKey}-${this.network}: Restricting due to error count=${
|
|
883
|
+
errorsData.count + 1
|
|
884
|
+
} within ${CABLES_RESTRICT_CHECK_INTERVAL_MS / 1000 / 60} minutes`,
|
|
885
|
+
);
|
|
886
|
+
await this.dexHelper.cache.setex(
|
|
887
|
+
this.dexKey,
|
|
888
|
+
this.network,
|
|
889
|
+
CABLES_RESTRICTED_CACHE_KEY,
|
|
890
|
+
CABLES_RESTRICT_TTL_S,
|
|
891
|
+
'true',
|
|
892
|
+
);
|
|
893
|
+
} else {
|
|
894
|
+
this.logger.warn(
|
|
895
|
+
`${this.dexKey}-${this.network}: Error count increased`,
|
|
896
|
+
);
|
|
897
|
+
const data: RestrictData = {
|
|
898
|
+
count: errorsData.count + 1,
|
|
899
|
+
addedDatetimeMs: errorsData.addedDatetimeMs,
|
|
900
|
+
};
|
|
901
|
+
await this.dexHelper.cache.setex(
|
|
902
|
+
this.dexKey,
|
|
903
|
+
this.network,
|
|
904
|
+
CABLES_RESTRICTED_CACHE_KEY,
|
|
905
|
+
ERRORS_TTL_S,
|
|
906
|
+
Utils.Serialize(data),
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|