@paraswap/dex-lib 2.19.0 → 2.19.1-swaap-v2
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/.idea/aws.xml +17 -0
- package/.idea/codeStyles/Project.xml +19 -0
- package/.idea/codeStyles/codeStyleConfig.xml +5 -0
- package/.idea/misc.xml +6 -0
- package/.idea/modules.xml +8 -0
- package/.idea/paraswap-dex-lib.iml +9 -0
- package/.idea/vcs.xml +6 -0
- package/build/abi/swaap-v2/vault.json +918 -0
- package/build/config.js +4 -2
- package/build/config.js.map +1 -1
- package/build/dex/aave-v3/tokens/arbitrum.json +50 -0
- package/build/dex/aave-v3/tokens/avalanche.json +74 -0
- package/build/dex/aave-v3/tokens/fantom.json +62 -0
- package/build/dex/aave-v3/tokens/optimism.json +50 -0
- package/build/dex/aave-v3/tokens/polygon.json +116 -0
- package/build/dex/index.js +2 -0
- package/build/dex/index.js.map +1 -1
- package/build/dex/pancakeswap-v3/types.d.ts +14 -0
- package/build/dex/pancakeswap-v3/types.js +3 -0
- package/build/dex/pancakeswap-v3/types.js.map +1 -0
- package/build/dex/swaap-v2/config.d.ts +4 -0
- package/build/dex/swaap-v2/config.js +19 -0
- package/build/dex/swaap-v2/config.js.map +1 -0
- package/build/dex/swaap-v2/constants.d.ts +11 -0
- package/build/dex/swaap-v2/constants.js +15 -0
- package/build/dex/swaap-v2/constants.js.map +1 -0
- package/build/dex/swaap-v2/rate-fetcher.d.ts +16 -0
- package/build/dex/swaap-v2/rate-fetcher.js +101 -0
- package/build/dex/swaap-v2/rate-fetcher.js.map +1 -0
- package/build/dex/swaap-v2/swaap-v2.d.ts +59 -0
- package/build/dex/swaap-v2/swaap-v2.js +525 -0
- package/build/dex/swaap-v2/swaap-v2.js.map +1 -0
- package/build/dex/swaap-v2/types.d.ts +78 -0
- package/build/dex/swaap-v2/types.js +10 -0
- package/build/dex/swaap-v2/types.js.map +1 -0
- package/build/dex/swaap-v2/utils.d.ts +7 -0
- package/build/dex/swaap-v2/utils.js +34 -0
- package/build/dex/swaap-v2/utils.js.map +1 -0
- package/build/dex/swaap-v2/validators.d.ts +6 -0
- package/build/dex/swaap-v2/validators.js +125 -0
- package/build/dex/swaap-v2/validators.js.map +1 -0
- package/build/types.d.ts +1 -0
- package/package.json +1 -1
- package/src/abi/swaap-v2/vault.json +918 -0
- package/src/config.ts +5 -2
- package/src/dex/index.ts +2 -0
- package/src/dex/swaap-v2/config.ts +19 -0
- package/src/dex/swaap-v2/constants.ts +21 -0
- package/src/dex/swaap-v2/rate-fetcher.ts +165 -0
- package/src/dex/swaap-v2/swaap-v2-e2e.test.ts +199 -0
- package/src/dex/swaap-v2/swaap-v2-integration.test.ts +145 -0
- package/src/dex/swaap-v2/swaap-v2.ts +817 -0
- package/src/dex/swaap-v2/types.ts +90 -0
- package/src/dex/swaap-v2/utils.ts +44 -0
- package/src/dex/swaap-v2/validators.ts +130 -0
- package/src/types.ts +1 -0
- package/tests/constants-e2e.ts +1 -1
- package/tests/utils-e2e.ts +5 -0
- package/build/abi/DirectSwap.json +0 -1008
|
@@ -0,0 +1,817 @@
|
|
|
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 { SwapSide, Network, MAX_INT, MAX_UINT } from '../../constants';
|
|
15
|
+
import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
|
|
16
|
+
import { getDexKeysWithNetwork } from '../../utils';
|
|
17
|
+
import { IDex } from '../idex';
|
|
18
|
+
import { IDexHelper } from '../../dex-helper/idex-helper';
|
|
19
|
+
import {
|
|
20
|
+
SwaapV2Data,
|
|
21
|
+
SwaapV2PriceLevel,
|
|
22
|
+
SwaapV2PriceLevels,
|
|
23
|
+
SwaapV2APIParameters,
|
|
24
|
+
SwaapV2QuoteError,
|
|
25
|
+
SlippageCheckError, TokensMap, SwaapV2TokensResponse,
|
|
26
|
+
} from './types';
|
|
27
|
+
import { getLocalDeadlineAsFriendlyPlaceholder, SimpleExchange } from '../simple-exchange';
|
|
28
|
+
import { Adapters, SwaapV2Config } from './config';
|
|
29
|
+
import { RateFetcher } from './rate-fetcher';
|
|
30
|
+
import routerAbi from '../../abi/swaap-v2/vault.json';
|
|
31
|
+
import BigNumber from 'bignumber.js';
|
|
32
|
+
import { BN_0, BN_1, getBigNumberPow } from '../../bignumber-constants';
|
|
33
|
+
import { Interface } from 'ethers/lib/utils';
|
|
34
|
+
import { assert } from 'ts-essentials';
|
|
35
|
+
import {
|
|
36
|
+
SWAAP_RFQ_API_URL,
|
|
37
|
+
SWAAP_RFQ_PRICES_ENDPOINT,
|
|
38
|
+
SWAAP_RFQ_QUOTE_ENDPOINT,
|
|
39
|
+
SWAAP_RFQ_API_PRICES_POLLING_INTERVAL_MS,
|
|
40
|
+
SWAAP_RFQ_PRICES_CACHES_TTL_S,
|
|
41
|
+
GAS_COST_ESTIMATION,
|
|
42
|
+
BATCH_SWAP_SELECTOR,
|
|
43
|
+
CALLER_SLOT,
|
|
44
|
+
SWAAP_BLACKLIST_TTL_S,
|
|
45
|
+
SWAAP_RFQ_TOKENS_ENDPOINT,
|
|
46
|
+
} from './constants';
|
|
47
|
+
import {
|
|
48
|
+
getPoolIdentifier,
|
|
49
|
+
getPriceLevelsCacheKey,
|
|
50
|
+
normalizeTokenAddress,
|
|
51
|
+
getPairName,
|
|
52
|
+
} from './utils';
|
|
53
|
+
import { Method } from '../../dex-helper/irequest-wrapper';
|
|
54
|
+
import { validateAndCast } from '../../lib/validators';
|
|
55
|
+
import { getTokensResponseValidator } from './validators';
|
|
56
|
+
|
|
57
|
+
const BLACKLISTED = 'blacklisted';
|
|
58
|
+
|
|
59
|
+
export class SwaapV2 extends SimpleExchange implements IDex<SwaapV2Data> {
|
|
60
|
+
readonly isStatePollingDex = true;
|
|
61
|
+
readonly hasConstantPriceLargeAmounts = false;
|
|
62
|
+
readonly needWrapNative = false;
|
|
63
|
+
readonly isFeeOnTransferSupported = false;
|
|
64
|
+
private rateFetcher: RateFetcher;
|
|
65
|
+
private tokensMap: TokensMap = {};
|
|
66
|
+
private swaapV2AuthToken: string;
|
|
67
|
+
|
|
68
|
+
public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
|
|
69
|
+
getDexKeysWithNetwork(SwaapV2Config);
|
|
70
|
+
|
|
71
|
+
logger: Logger;
|
|
72
|
+
|
|
73
|
+
constructor(
|
|
74
|
+
readonly network: Network,
|
|
75
|
+
readonly dexKey: string,
|
|
76
|
+
readonly dexHelper: IDexHelper,
|
|
77
|
+
protected adapters = Adapters[network] || {},
|
|
78
|
+
protected routerInterface = new Interface(routerAbi),
|
|
79
|
+
) {
|
|
80
|
+
super(dexHelper, dexKey);
|
|
81
|
+
this.logger = dexHelper.getLogger(dexKey);
|
|
82
|
+
const token = dexHelper.config.data.swaapV2AuthToken;
|
|
83
|
+
assert(
|
|
84
|
+
token !== undefined,
|
|
85
|
+
'SwaapV2 auth token is not specified with env variable',
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
this.swaapV2AuthToken = token;
|
|
89
|
+
|
|
90
|
+
this.rateFetcher = new RateFetcher(
|
|
91
|
+
this.dexHelper,
|
|
92
|
+
this.dexKey,
|
|
93
|
+
this.logger,
|
|
94
|
+
{
|
|
95
|
+
rateConfig: {
|
|
96
|
+
pricesIntervalMs: SWAAP_RFQ_API_PRICES_POLLING_INTERVAL_MS,
|
|
97
|
+
pricesReqParams: this.getPriceLevelsReqParams(),
|
|
98
|
+
pricesCacheTTLSecs: SWAAP_RFQ_PRICES_CACHES_TTL_S,
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async initializePricing(blockNumber: number): Promise<void> {
|
|
105
|
+
const { data } = await this.dexHelper.httpRequest.request<unknown>(
|
|
106
|
+
this.getTokensReqParams(),
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
const tokensResp = validateAndCast<SwaapV2TokensResponse>(
|
|
110
|
+
data,
|
|
111
|
+
getTokensResponseValidator,
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
this.tokensMap = Object.keys(tokensResp.tokens).reduce((acc, key: string) => {
|
|
115
|
+
acc[key.toLowerCase()] = tokensResp.tokens[key];
|
|
116
|
+
return acc;
|
|
117
|
+
}, {} as TokensMap);
|
|
118
|
+
|
|
119
|
+
if (!this.dexHelper.config.isSlave) {
|
|
120
|
+
await this.rateFetcher.start();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
getAdapters(side: SwapSide): { name: string; index: number }[] | null {
|
|
127
|
+
return this.adapters[side] ? this.adapters[side] : null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async getPoolIdentifiers(
|
|
131
|
+
srcToken: Token,
|
|
132
|
+
destToken: Token,
|
|
133
|
+
side: SwapSide,
|
|
134
|
+
blockNumber: number,
|
|
135
|
+
): Promise<string[]> {
|
|
136
|
+
const normalizedSrcToken = this.normalizeToken(srcToken);
|
|
137
|
+
const normalizedDestToken = this.normalizeToken(destToken);
|
|
138
|
+
|
|
139
|
+
if (normalizedSrcToken.address === normalizedDestToken.address) {
|
|
140
|
+
return [];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const poolIdentifier = getPoolIdentifier(
|
|
144
|
+
this.dexKey,
|
|
145
|
+
normalizedSrcToken.address,
|
|
146
|
+
normalizedDestToken.address,
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
const levels = await this.getCachedLevels();
|
|
150
|
+
if (levels === null) {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return Object.keys(levels)
|
|
155
|
+
.map((pair: string) => {
|
|
156
|
+
return getPoolIdentifier(
|
|
157
|
+
this.dexKey,
|
|
158
|
+
levels[pair].base!,
|
|
159
|
+
levels[pair].quote!,
|
|
160
|
+
);
|
|
161
|
+
})
|
|
162
|
+
.filter((pi: string) => pi === poolIdentifier);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
computePricesFromLevelsBis(
|
|
166
|
+
amounts: BigNumber[],
|
|
167
|
+
asksAndBids: SwaapV2PriceLevels,
|
|
168
|
+
srcToken: Token,
|
|
169
|
+
destToken: Token,
|
|
170
|
+
side: SwapSide,
|
|
171
|
+
): bigint[] {
|
|
172
|
+
let levels: SwaapV2PriceLevel[] = [];
|
|
173
|
+
if (side === SwapSide.BUY) {
|
|
174
|
+
if (destToken.address === asksAndBids.base!) {
|
|
175
|
+
levels = asksAndBids.asks;
|
|
176
|
+
} else {
|
|
177
|
+
levels = this.invertPrices(asksAndBids.bids);
|
|
178
|
+
}
|
|
179
|
+
} else {
|
|
180
|
+
if (srcToken.address === asksAndBids.base!) {
|
|
181
|
+
levels = asksAndBids.bids;
|
|
182
|
+
} else {
|
|
183
|
+
levels = this.invertPrices(asksAndBids.asks);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return this.computeLevelsQuote(amounts, levels, srcToken, destToken, side);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
inversePrice(priceLevel: SwaapV2PriceLevel): SwaapV2PriceLevel {
|
|
190
|
+
return {
|
|
191
|
+
level: priceLevel.level * priceLevel.price,
|
|
192
|
+
price: 1 / priceLevel.price,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
invertPrices(levels: SwaapV2PriceLevel[]): SwaapV2PriceLevel[] {
|
|
197
|
+
return levels.map(pl => this.inversePrice(pl));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
computeLevelsQuote(
|
|
201
|
+
amounts: BigNumber[],
|
|
202
|
+
levels: SwaapV2PriceLevel[],
|
|
203
|
+
srcToken: Token,
|
|
204
|
+
destToken: Token,
|
|
205
|
+
side: SwapSide,
|
|
206
|
+
): bigint[] {
|
|
207
|
+
const size = levels.length;
|
|
208
|
+
if (size === 0) {
|
|
209
|
+
return amounts.map(_ => BigInt(0));
|
|
210
|
+
}
|
|
211
|
+
return amounts.map((amount: BigNumber) => {
|
|
212
|
+
if (amount.isZero() || amount.lt(BigNumber(levels[0].level))) {
|
|
213
|
+
return BigInt(0);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let i = 0;
|
|
217
|
+
let output = BN_0;
|
|
218
|
+
let previousLevel = BN_0;
|
|
219
|
+
let remaininig = BigNumber(amount);
|
|
220
|
+
let enoughLiquidity = false;
|
|
221
|
+
while (i < size) {
|
|
222
|
+
const levelDelta = BigNumber(levels[i].level).minus(previousLevel);
|
|
223
|
+
if (levelDelta.lte(remaininig)) {
|
|
224
|
+
output = output.plus(levelDelta.times(levels[i].price));
|
|
225
|
+
remaininig = remaininig.minus(levelDelta);
|
|
226
|
+
previousLevel = BigNumber(levels[i].level);
|
|
227
|
+
i += 1;
|
|
228
|
+
} else {
|
|
229
|
+
output = output.plus(remaininig.times(levels[i].price));
|
|
230
|
+
enoughLiquidity = true;
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (enoughLiquidity) {
|
|
235
|
+
return BigInt(
|
|
236
|
+
output
|
|
237
|
+
.multipliedBy(
|
|
238
|
+
getBigNumberPow(
|
|
239
|
+
side === SwapSide.BUY ? srcToken.decimals : destToken.decimals,
|
|
240
|
+
),
|
|
241
|
+
)
|
|
242
|
+
.toFixed(0),
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
return BigInt(0); // not enough liquidity
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async getCachedLevels(): Promise<Record<string, SwaapV2PriceLevels> | null> {
|
|
250
|
+
const cachedLevels = await this.dexHelper.cache.get(
|
|
251
|
+
this.dexKey,
|
|
252
|
+
this.network,
|
|
253
|
+
getPriceLevelsCacheKey(this.dexKey),
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
if (cachedLevels) {
|
|
257
|
+
return JSON.parse(cachedLevels) as Record<string, SwaapV2PriceLevels>;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
normalizeToken(token: Token): Token {
|
|
264
|
+
return {
|
|
265
|
+
address: normalizeTokenAddress(token.address),
|
|
266
|
+
decimals: token.decimals,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async getPricesVolume(
|
|
271
|
+
srcToken: Token,
|
|
272
|
+
destToken: Token,
|
|
273
|
+
amounts: bigint[],
|
|
274
|
+
side: SwapSide,
|
|
275
|
+
blockNumber: number,
|
|
276
|
+
limitPools?: string[],
|
|
277
|
+
): Promise<null | ExchangePrices<SwaapV2Data>> {
|
|
278
|
+
try {
|
|
279
|
+
const normalizedSrcToken = this.normalizeToken(srcToken);
|
|
280
|
+
const normalizedDestToken = this.normalizeToken(destToken);
|
|
281
|
+
|
|
282
|
+
const requestedPoolIdentifier: string = getPoolIdentifier(
|
|
283
|
+
this.dexKey,
|
|
284
|
+
normalizedSrcToken.address,
|
|
285
|
+
normalizedDestToken.address,
|
|
286
|
+
);
|
|
287
|
+
|
|
288
|
+
if (normalizedSrcToken.address === normalizedDestToken.address) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const pools =
|
|
293
|
+
limitPools ??
|
|
294
|
+
(await this.getPoolIdentifiers(srcToken, destToken, side, blockNumber));
|
|
295
|
+
|
|
296
|
+
const levels = await this.getCachedLevels();
|
|
297
|
+
if (levels === null) {
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const poolIdentifier = getPoolIdentifier(
|
|
302
|
+
this.dexKey,
|
|
303
|
+
normalizedSrcToken.address,
|
|
304
|
+
normalizedDestToken.address,
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
const levelEntries: SwaapV2PriceLevels[] = Object.keys(levels)
|
|
308
|
+
.map((pair: string) => {
|
|
309
|
+
if (pools.includes(poolIdentifier)) {
|
|
310
|
+
return levels[pair];
|
|
311
|
+
}
|
|
312
|
+
return undefined;
|
|
313
|
+
})
|
|
314
|
+
.filter((o): o is SwaapV2PriceLevels => o !== undefined);
|
|
315
|
+
|
|
316
|
+
const divider = getBigNumberPow(
|
|
317
|
+
(side === SwapSide.SELL ? normalizedSrcToken : normalizedDestToken)
|
|
318
|
+
.decimals,
|
|
319
|
+
);
|
|
320
|
+
|
|
321
|
+
const amountsFloat = amounts.map(a =>
|
|
322
|
+
new BigNumber(a.toString()).dividedBy(divider),
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
const prices = levelEntries.map((askAndBids: SwaapV2PriceLevels) => {
|
|
326
|
+
|
|
327
|
+
const unitPrice = this.computePricesFromLevelsBis(
|
|
328
|
+
[BN_1],
|
|
329
|
+
askAndBids,
|
|
330
|
+
normalizedSrcToken,
|
|
331
|
+
normalizedDestToken,
|
|
332
|
+
side,
|
|
333
|
+
)[0];
|
|
334
|
+
const prices = this.computePricesFromLevelsBis(
|
|
335
|
+
amountsFloat,
|
|
336
|
+
askAndBids,
|
|
337
|
+
normalizedSrcToken,
|
|
338
|
+
normalizedDestToken,
|
|
339
|
+
side,
|
|
340
|
+
);
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
gasCost: GAS_COST_ESTIMATION,
|
|
344
|
+
exchange: this.dexKey,
|
|
345
|
+
data: {},
|
|
346
|
+
prices,
|
|
347
|
+
unit: unitPrice,
|
|
348
|
+
poolIdentifier: requestedPoolIdentifier,
|
|
349
|
+
} as PoolPrices<SwaapV2Data>;
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
return prices;
|
|
353
|
+
} catch (e) {
|
|
354
|
+
this.logger.error(
|
|
355
|
+
`Error_getPrices ${srcToken}, ${destToken}, ${side}:`, e,
|
|
356
|
+
);
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
getBaseToken(poolIdentifier: string): string {
|
|
362
|
+
return poolIdentifier.split('_')[1];
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
getLevels(
|
|
366
|
+
askAndBids: SwaapV2PriceLevels,
|
|
367
|
+
side: SwapSide,
|
|
368
|
+
poolIdentifier: string,
|
|
369
|
+
) {
|
|
370
|
+
const baseToken: string = this.getBaseToken(poolIdentifier);
|
|
371
|
+
if (side === SwapSide.SELL) {
|
|
372
|
+
return askAndBids.asks;
|
|
373
|
+
}
|
|
374
|
+
return askAndBids.asks;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async preProcessTransaction(
|
|
378
|
+
optimalSwapExchange: OptimalSwapExchange<SwaapV2Data>,
|
|
379
|
+
srcToken: Token,
|
|
380
|
+
destToken: Token,
|
|
381
|
+
side: SwapSide,
|
|
382
|
+
options: PreprocessTransactionOptions,
|
|
383
|
+
): Promise<[OptimalSwapExchange<SwaapV2Data>, ExchangeTxInfo]> {
|
|
384
|
+
if (await this.isBlacklisted(options.txOrigin)) {
|
|
385
|
+
this.logger.warn(
|
|
386
|
+
`${this.dexKey}-${this.network}: blacklisted TX Origin address '${options.txOrigin}' trying to build a transaction. Bailing...`,
|
|
387
|
+
);
|
|
388
|
+
throw new Error(
|
|
389
|
+
`${this.dexKey}-${
|
|
390
|
+
this.network
|
|
391
|
+
}: user=${options.txOrigin.toLowerCase()} is blacklisted`,
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const isSell = side === SwapSide.SELL;
|
|
396
|
+
|
|
397
|
+
const normalizedSrcToken = this.normalizeToken(srcToken);
|
|
398
|
+
const normalizedDestToken = this.normalizeToken(destToken);
|
|
399
|
+
|
|
400
|
+
const tolerance = (
|
|
401
|
+
options.slippageFactor > BN_1
|
|
402
|
+
? options.slippageFactor.minus(BN_1)
|
|
403
|
+
: BN_1.minus(options.slippageFactor)
|
|
404
|
+
).toNumber();
|
|
405
|
+
|
|
406
|
+
try {
|
|
407
|
+
const quote = await this.rateFetcher.getQuote(
|
|
408
|
+
this.network,
|
|
409
|
+
normalizedSrcToken,
|
|
410
|
+
normalizedDestToken,
|
|
411
|
+
isSell ? optimalSwapExchange.srcAmount : optimalSwapExchange.destAmount,
|
|
412
|
+
isSell ? 1 : 2,
|
|
413
|
+
options.txOrigin,
|
|
414
|
+
this.augustusAddress,
|
|
415
|
+
tolerance,
|
|
416
|
+
this.getQuoteReqParams(),
|
|
417
|
+
);
|
|
418
|
+
|
|
419
|
+
if (!quote.success) {
|
|
420
|
+
const message = `${this.dexKey}-${
|
|
421
|
+
this.network
|
|
422
|
+
}: Failed to fetch RFQ for ${getPairName(
|
|
423
|
+
normalizedSrcToken.address,
|
|
424
|
+
normalizedDestToken.address,
|
|
425
|
+
)}: ${JSON.stringify(quote)}`;
|
|
426
|
+
this.logger.warn(message);
|
|
427
|
+
throw new SwaapV2QuoteError(message);
|
|
428
|
+
} else if (!quote.calldata) {
|
|
429
|
+
const message = `${this.dexKey}-${
|
|
430
|
+
this.network
|
|
431
|
+
}: Failed to fetch RFQ for ${getPairName(
|
|
432
|
+
normalizedSrcToken.address,
|
|
433
|
+
normalizedDestToken.address,
|
|
434
|
+
)}. Missing quote data`;
|
|
435
|
+
this.logger.warn(message);
|
|
436
|
+
throw new SwaapV2QuoteError(message);
|
|
437
|
+
} else if (!quote.router) {
|
|
438
|
+
const message = `${this.dexKey}-${
|
|
439
|
+
this.network
|
|
440
|
+
}: Failed to fetch RFQ for ${getPairName(
|
|
441
|
+
normalizedSrcToken.address,
|
|
442
|
+
normalizedDestToken.address,
|
|
443
|
+
)}. Missing router address`;
|
|
444
|
+
this.logger.warn(message);
|
|
445
|
+
throw new SwaapV2QuoteError(message);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const srcAmount = BigInt(optimalSwapExchange.srcAmount);
|
|
449
|
+
const destAmount = BigInt(optimalSwapExchange.destAmount);
|
|
450
|
+
const quoteTokenAmount = BigInt(quote.amount);
|
|
451
|
+
const slippageFactor = options.slippageFactor;
|
|
452
|
+
|
|
453
|
+
if(side === SwapSide.SELL) {
|
|
454
|
+
if (
|
|
455
|
+
quoteTokenAmount <
|
|
456
|
+
BigInt(
|
|
457
|
+
new BigNumber(destAmount.toString())
|
|
458
|
+
.times(slippageFactor)
|
|
459
|
+
.toFixed(0),
|
|
460
|
+
)
|
|
461
|
+
) {
|
|
462
|
+
const message = `${this.dexKey}-${this.network}: too much slippage on quote ${side} quoteTokenAmount ${quoteTokenAmount} / destAmount ${destAmount} < ${slippageFactor}`;
|
|
463
|
+
this.logger.warn(message);
|
|
464
|
+
throw new SlippageCheckError(message);
|
|
465
|
+
}
|
|
466
|
+
} else {
|
|
467
|
+
if (
|
|
468
|
+
quoteTokenAmount >
|
|
469
|
+
BigInt(slippageFactor.times(srcAmount.toString()).toFixed(0))
|
|
470
|
+
) {
|
|
471
|
+
const message = `${this.dexKey}-${
|
|
472
|
+
this.network
|
|
473
|
+
}: too much slippage on quote ${side} baseTokenAmount ${srcAmount} / srcAmount ${srcAmount} > ${slippageFactor.toFixed()}`;
|
|
474
|
+
this.logger.warn(message);
|
|
475
|
+
throw new SlippageCheckError(message);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
return [
|
|
480
|
+
{
|
|
481
|
+
...optimalSwapExchange,
|
|
482
|
+
data: {
|
|
483
|
+
router: quote.router,
|
|
484
|
+
callData: quote.calldata,
|
|
485
|
+
},
|
|
486
|
+
},
|
|
487
|
+
{ deadline: BigInt(getLocalDeadlineAsFriendlyPlaceholder()) },
|
|
488
|
+
];
|
|
489
|
+
} catch (e) {
|
|
490
|
+
await this.setBlacklist(options.txOrigin);
|
|
491
|
+
this.logger.warn(
|
|
492
|
+
`${this.dexKey}-${this.network}: Encountered restricted user=${options.txOrigin}. Adding to local blacklist cache`,
|
|
493
|
+
);
|
|
494
|
+
throw e;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async isBlacklisted(txOrigin: Address): Promise<boolean> {
|
|
499
|
+
const result = await this.dexHelper.cache.get(
|
|
500
|
+
this.dexKey,
|
|
501
|
+
this.network,
|
|
502
|
+
this.getBlackListKey(txOrigin),
|
|
503
|
+
);
|
|
504
|
+
return result === BLACKLISTED;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
getBlackListKey(address: Address) {
|
|
508
|
+
return `blacklist_${address}`.toLowerCase();
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async setBlacklist(
|
|
512
|
+
txOrigin: Address,
|
|
513
|
+
ttl: number = SWAAP_BLACKLIST_TTL_S,
|
|
514
|
+
) {
|
|
515
|
+
await this.dexHelper.cache.setex(
|
|
516
|
+
this.dexKey,
|
|
517
|
+
this.network,
|
|
518
|
+
this.getBlackListKey(txOrigin),
|
|
519
|
+
ttl,
|
|
520
|
+
BLACKLISTED,
|
|
521
|
+
);
|
|
522
|
+
return true;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// Returns estimated gas cost of calldata for this DEX in multiSwap
|
|
526
|
+
getCalldataGasCost(poolPrices: PoolPrices<SwaapV2Data>): number | number[] {
|
|
527
|
+
return (
|
|
528
|
+
CALLDATA_GAS_COST.DEX_OVERHEAD +
|
|
529
|
+
CALLDATA_GAS_COST.LENGTH_LARGE +
|
|
530
|
+
// ParentStruct header
|
|
531
|
+
CALLDATA_GAS_COST.OFFSET_SMALL +
|
|
532
|
+
// ParentStruct -> swaps[] header
|
|
533
|
+
CALLDATA_GAS_COST.OFFSET_LARGE +
|
|
534
|
+
// ParentStruct -> assets[] header
|
|
535
|
+
CALLDATA_GAS_COST.OFFSET_LARGE +
|
|
536
|
+
// ParentStruct -> funds
|
|
537
|
+
CALLDATA_GAS_COST.ADDRESS +
|
|
538
|
+
CALLDATA_GAS_COST.BOOL +
|
|
539
|
+
CALLDATA_GAS_COST.ADDRESS +
|
|
540
|
+
CALLDATA_GAS_COST.BOOL +
|
|
541
|
+
// ParentStruct -> limits[] header
|
|
542
|
+
CALLDATA_GAS_COST.OFFSET_LARGE +
|
|
543
|
+
// ParentStruct -> deadline
|
|
544
|
+
CALLDATA_GAS_COST.TIMESTAMP +
|
|
545
|
+
// ParentStruct -> swaps[]
|
|
546
|
+
CALLDATA_GAS_COST.LENGTH_SMALL +
|
|
547
|
+
// ParentStruct -> swaps[0] header
|
|
548
|
+
CALLDATA_GAS_COST.OFFSET_SMALL +
|
|
549
|
+
// ParentStruct -> swaps[0] -> poolId
|
|
550
|
+
CALLDATA_GAS_COST.FULL_WORD +
|
|
551
|
+
// ParentStruct -> swaps[0] -> assetInIndex
|
|
552
|
+
CALLDATA_GAS_COST.INDEX +
|
|
553
|
+
// ParentStruct -> swaps[0] -> assetOutIndex
|
|
554
|
+
CALLDATA_GAS_COST.INDEX +
|
|
555
|
+
// ParentStruct -> swaps[0] -> amount
|
|
556
|
+
CALLDATA_GAS_COST.AMOUNT +
|
|
557
|
+
// ParentStruct -> swaps[0] -> userData header
|
|
558
|
+
CALLDATA_GAS_COST.OFFSET_SMALL +
|
|
559
|
+
// ParentStruct -> swaps[0] -> userData
|
|
560
|
+
CALLDATA_GAS_COST.ZERO +
|
|
561
|
+
// ParentStruct -> assets[]
|
|
562
|
+
CALLDATA_GAS_COST.LENGTH_SMALL +
|
|
563
|
+
// ParentStruct -> assets[0:2]
|
|
564
|
+
CALLDATA_GAS_COST.ADDRESS * 2 +
|
|
565
|
+
// ParentStruct -> limits[]
|
|
566
|
+
CALLDATA_GAS_COST.LENGTH_SMALL +
|
|
567
|
+
// ParentStruct -> limits[0:2]
|
|
568
|
+
CALLDATA_GAS_COST.FULL_WORD * 2 +
|
|
569
|
+
// Bool -> IsBatchSwap
|
|
570
|
+
CALLDATA_GAS_COST.BOOL
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
getAdapterParam(
|
|
575
|
+
srcToken: string,
|
|
576
|
+
destToken: string,
|
|
577
|
+
srcAmount: string,
|
|
578
|
+
destAmount: string,
|
|
579
|
+
data: SwaapV2Data,
|
|
580
|
+
side: SwapSide,
|
|
581
|
+
): AdapterExchangeParam {
|
|
582
|
+
const { router, callData } = data;
|
|
583
|
+
|
|
584
|
+
assert(
|
|
585
|
+
router !== undefined,
|
|
586
|
+
`${this.dexKey}-${this.network}: router undefined`,
|
|
587
|
+
);
|
|
588
|
+
|
|
589
|
+
assert(
|
|
590
|
+
callData !== undefined,
|
|
591
|
+
`${this.dexKey}-${this.network}: callData undefined`,
|
|
592
|
+
);
|
|
593
|
+
|
|
594
|
+
let payload: string;
|
|
595
|
+
const truncatedCalldata = '0x' + callData.slice(10); // droping the function selector
|
|
596
|
+
const isBatchSwap = callData.slice(0, 10) === BATCH_SWAP_SELECTOR;
|
|
597
|
+
|
|
598
|
+
if (isBatchSwap) {
|
|
599
|
+
const batchswapAbi = routerAbi.filter(abi => abi.name === 'batchSwap');
|
|
600
|
+
|
|
601
|
+
const callDataStruct = this.abiCoder.decodeParameters(
|
|
602
|
+
batchswapAbi[0].inputs!,
|
|
603
|
+
truncatedCalldata,
|
|
604
|
+
);
|
|
605
|
+
|
|
606
|
+
const callerSlots = Array(callDataStruct.swaps.length).fill(160);
|
|
607
|
+
|
|
608
|
+
payload = this.abiCoder.encodeParameters(
|
|
609
|
+
[
|
|
610
|
+
'bool',
|
|
611
|
+
'uint256[]',
|
|
612
|
+
{
|
|
613
|
+
ParentStruct: {
|
|
614
|
+
'swaps[]': {
|
|
615
|
+
poolId: 'bytes32',
|
|
616
|
+
assetInIndex: 'uint256',
|
|
617
|
+
assetOutIndex: 'uint256',
|
|
618
|
+
amount: 'uint256',
|
|
619
|
+
userData: 'bytes',
|
|
620
|
+
},
|
|
621
|
+
assets: 'address[]',
|
|
622
|
+
funds: {
|
|
623
|
+
sender: 'address',
|
|
624
|
+
fromInternalBalance: 'bool',
|
|
625
|
+
recipient: 'address',
|
|
626
|
+
toInternalBalance: 'bool',
|
|
627
|
+
},
|
|
628
|
+
limits: 'int256[]',
|
|
629
|
+
},
|
|
630
|
+
},
|
|
631
|
+
],
|
|
632
|
+
[
|
|
633
|
+
isBatchSwap,
|
|
634
|
+
callerSlots,
|
|
635
|
+
{
|
|
636
|
+
swaps: callDataStruct.swaps,
|
|
637
|
+
assets: callDataStruct.assets,
|
|
638
|
+
funds: callDataStruct.funds,
|
|
639
|
+
limits: callDataStruct.limits.map((_: any) => MAX_INT),
|
|
640
|
+
},
|
|
641
|
+
],
|
|
642
|
+
);
|
|
643
|
+
} else {
|
|
644
|
+
const swapAbi = routerAbi.filter(abi => abi.name === 'swap');
|
|
645
|
+
|
|
646
|
+
const callDataStruct = this.abiCoder.decodeParameters(
|
|
647
|
+
swapAbi[0].inputs!,
|
|
648
|
+
truncatedCalldata,
|
|
649
|
+
);
|
|
650
|
+
|
|
651
|
+
const callerSlot = CALLER_SLOT;
|
|
652
|
+
|
|
653
|
+
payload = this.abiCoder.encodeParameters(
|
|
654
|
+
[
|
|
655
|
+
'bool',
|
|
656
|
+
'uint256',
|
|
657
|
+
{
|
|
658
|
+
ParentStruct: {
|
|
659
|
+
swap: {
|
|
660
|
+
poolId: 'bytes32',
|
|
661
|
+
kind: 'uint8',
|
|
662
|
+
assetIn: 'address',
|
|
663
|
+
assetOut: 'address',
|
|
664
|
+
amount: 'uint256',
|
|
665
|
+
userData: 'bytes',
|
|
666
|
+
},
|
|
667
|
+
funds: {
|
|
668
|
+
sender: 'address',
|
|
669
|
+
fromInternalBalance: 'bool',
|
|
670
|
+
recipient: 'address',
|
|
671
|
+
toInternalBalance: 'bool',
|
|
672
|
+
},
|
|
673
|
+
limit: 'uint256',
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
],
|
|
677
|
+
[
|
|
678
|
+
isBatchSwap,
|
|
679
|
+
callerSlot,
|
|
680
|
+
{
|
|
681
|
+
swap: {
|
|
682
|
+
poolId: callDataStruct.singleSwap.poolId,
|
|
683
|
+
kind: callDataStruct.singleSwap.kind,
|
|
684
|
+
assetIn: callDataStruct.singleSwap.assetIn,
|
|
685
|
+
assetOut: callDataStruct.singleSwap.assetOut,
|
|
686
|
+
amount: callDataStruct.singleSwap.amount,
|
|
687
|
+
userData: callDataStruct.singleSwap.userData,
|
|
688
|
+
},
|
|
689
|
+
funds: {
|
|
690
|
+
sender: callDataStruct.funds.sender,
|
|
691
|
+
fromInternalBalance: callDataStruct.funds.fromInternalBalance,
|
|
692
|
+
recipient: callDataStruct.funds.recipient,
|
|
693
|
+
toInternalBalance: callDataStruct.funds.toInternalBalance,
|
|
694
|
+
},
|
|
695
|
+
limit: side === SwapSide.BUY ? MAX_UINT : '0',
|
|
696
|
+
},
|
|
697
|
+
],
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
return {
|
|
702
|
+
targetExchange: router,
|
|
703
|
+
payload: payload,
|
|
704
|
+
networkFee: '0',
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
async getSimpleParam(
|
|
709
|
+
srcToken: string,
|
|
710
|
+
destToken: string,
|
|
711
|
+
srcAmount: string,
|
|
712
|
+
destAmount: string,
|
|
713
|
+
data: SwaapV2Data,
|
|
714
|
+
side: SwapSide,
|
|
715
|
+
): Promise<SimpleExchangeParam> {
|
|
716
|
+
const { router, callData } = data;
|
|
717
|
+
|
|
718
|
+
assert(
|
|
719
|
+
router !== undefined,
|
|
720
|
+
`${this.dexKey}-${this.network}: router undefined`,
|
|
721
|
+
);
|
|
722
|
+
|
|
723
|
+
assert(
|
|
724
|
+
callData !== undefined,
|
|
725
|
+
`${this.dexKey}-${this.network}: callData undefined`,
|
|
726
|
+
);
|
|
727
|
+
|
|
728
|
+
return this.buildSimpleParamWithoutWETHConversion(
|
|
729
|
+
srcToken,
|
|
730
|
+
srcAmount,
|
|
731
|
+
destToken,
|
|
732
|
+
destAmount,
|
|
733
|
+
callData,
|
|
734
|
+
router,
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
computeMaxLiquidity = (
|
|
739
|
+
levels: SwaapV2PriceLevels,
|
|
740
|
+
tokenAddress: string,
|
|
741
|
+
): number => {
|
|
742
|
+
if (tokenAddress === levels.base!) {
|
|
743
|
+
return (
|
|
744
|
+
(levels.asks[levels.asks.length - 1]?.level ?? 0) *
|
|
745
|
+
levels.asks[0]?.price
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
return (
|
|
749
|
+
(levels.asks[levels.bids.length - 1]?.level ?? 0) * levels.asks[0]?.price
|
|
750
|
+
);
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
async getTopPoolsForToken(
|
|
754
|
+
tokenAddress: Address,
|
|
755
|
+
limit: number,
|
|
756
|
+
): Promise<PoolLiquidity[]> {
|
|
757
|
+
const normalizedTokenAddress = normalizeTokenAddress(tokenAddress);
|
|
758
|
+
|
|
759
|
+
const pLevels = await this.getCachedLevels();
|
|
760
|
+
|
|
761
|
+
if (pLevels === null) {
|
|
762
|
+
return [];
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
return Object.keys(pLevels)
|
|
766
|
+
.filter((pair: string) => {
|
|
767
|
+
return (
|
|
768
|
+
normalizedTokenAddress === pLevels[pair].base ||
|
|
769
|
+
normalizedTokenAddress === pLevels[pair].quote
|
|
770
|
+
);
|
|
771
|
+
})
|
|
772
|
+
.map((pair: string) => {
|
|
773
|
+
return {
|
|
774
|
+
exchange: this.dexKey,
|
|
775
|
+
connectorTokens: [this.getTokenFromAddress(normalizedTokenAddress === pLevels[pair].base ? pLevels[pair].quote : pLevels[pair].base)],
|
|
776
|
+
liquidityUSD: this.computeMaxLiquidity(pLevels[pair], tokenAddress),
|
|
777
|
+
} as PoolLiquidity;
|
|
778
|
+
})
|
|
779
|
+
.sort((pl: PoolLiquidity) => {
|
|
780
|
+
return -pl.liquidityUSD;
|
|
781
|
+
})
|
|
782
|
+
.slice(0, limit);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
getTokenFromAddress(address: Address): Token {
|
|
786
|
+
return this.tokensMap[address];
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
releaseResources(): void {
|
|
790
|
+
if (this.rateFetcher) {
|
|
791
|
+
this.rateFetcher.stop();
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
getPriceLevelsReqParams(): SwaapV2APIParameters {
|
|
796
|
+
return this.getAPIReqParams(SWAAP_RFQ_PRICES_ENDPOINT, 'GET');
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
getQuoteReqParams(): SwaapV2APIParameters {
|
|
800
|
+
return this.getAPIReqParams(SWAAP_RFQ_QUOTE_ENDPOINT, 'POST');
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
getTokensReqParams(): SwaapV2APIParameters {
|
|
804
|
+
return this.getAPIReqParams(SWAAP_RFQ_TOKENS_ENDPOINT, 'GET');
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
getAPIReqParams(endpoint: string, method: Method): SwaapV2APIParameters {
|
|
808
|
+
return {
|
|
809
|
+
url: `${SWAAP_RFQ_API_URL}/${endpoint}`,
|
|
810
|
+
params: {
|
|
811
|
+
networkId: this.network,
|
|
812
|
+
},
|
|
813
|
+
headers: { 'x-api-key': this.swaapV2AuthToken },
|
|
814
|
+
method: method,
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
}
|