@paraswap/dex-lib 3.4.2-balancer-v2-single-swap.0 → 3.4.2

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 (110) hide show
  1. package/README.md +377 -377
  2. package/build/config.js +9 -5
  3. package/build/config.js.map +1 -1
  4. package/build/dex/algebra/algebra.js +25 -25
  5. package/build/dex/balancer-v1/balancer-v1.js +34 -34
  6. package/build/dex/balancer-v2/balancer-v2.d.ts +1 -1
  7. package/build/dex/balancer-v2/balancer-v2.js +65 -78
  8. package/build/dex/balancer-v2/balancer-v2.js.map +1 -1
  9. package/build/dex/camelot/camelot.js +27 -27
  10. package/build/dex/kyberdmm/kyberdmm.js +27 -27
  11. package/build/dex/pancakeswap-v3/pancakeswap-v3.js +25 -25
  12. package/build/dex/solidly/solidly.js +27 -27
  13. package/build/dex/solidly-v3/solidly-v3.js +25 -25
  14. package/build/dex/swaap-v2/config.js +15 -0
  15. package/build/dex/swaap-v2/config.js.map +1 -1
  16. package/build/dex/uniswap-v2/uniswap-v2.js +26 -26
  17. package/build/dex/uniswap-v3/uniswap-v3.js +25 -25
  18. package/funding.json +5 -5
  19. package/package.json +1 -1
  20. package/src/config.ts +500 -496
  21. package/src/constants.ts +67 -67
  22. package/src/dex/aave-v2/aave-v2.ts +409 -409
  23. package/src/dex/aave-v3/aave-v3.ts +320 -320
  24. package/src/dex/algebra/algebra.ts +1180 -1180
  25. package/src/dex/angle-staked-stable/angle-staked-stable.ts +347 -347
  26. package/src/dex/augustus-rfq.ts +180 -180
  27. package/src/dex/bProtocol/bProtocol.ts +108 -108
  28. package/src/dex/balancer-v1/balancer-v1.ts +572 -572
  29. package/src/dex/balancer-v2/balancer-v2-e2e.test.ts +1699 -1699
  30. package/src/dex/balancer-v2/balancer-v2.ts +1669 -1701
  31. package/src/dex/bancor/bancor.ts +128 -128
  32. package/src/dex/camelot/camelot.ts +873 -873
  33. package/src/dex/compound/compound.ts +107 -107
  34. package/src/dex/curve-v1/config.ts +1179 -1179
  35. package/src/dex/curve-v1/curve-v1-e2e.test.ts +507 -507
  36. package/src/dex/curve-v1/curve-v1.ts +1315 -1315
  37. package/src/dex/curve-v1-factory/config.ts +1018 -1018
  38. package/src/dex/curve-v1-factory/curve-v1-factory.ts +1288 -1288
  39. package/src/dex/curve-v2/curve-v2.ts +440 -440
  40. package/src/dex/dexalot/dexalot.ts +1100 -1100
  41. package/src/dex/dodo-v1/dodo-v1.ts +132 -132
  42. package/src/dex/dodo-v2.ts +266 -266
  43. package/src/dex/etherfi.ts +239 -239
  44. package/src/dex/generic-rfq/generic-rfq.ts +431 -431
  45. package/src/dex/gmx/gmx.ts +321 -321
  46. package/src/dex/hashflow/hashflow.ts +1135 -1135
  47. package/src/dex/idex.ts +254 -254
  48. package/src/dex/index.ts +357 -357
  49. package/src/dex/jarvis-v6/jarvis-v6.ts +509 -509
  50. package/src/dex/jarvis.ts +262 -262
  51. package/src/dex/kyberdmm/kyberdmm.ts +649 -649
  52. package/src/dex/lido/lido.ts +110 -110
  53. package/src/dex/maker-psm/maker-psm.ts +592 -592
  54. package/src/dex/maverick-v1/maverick-v1.ts +537 -537
  55. package/src/dex/nerve/config.ts +635 -635
  56. package/src/dex/nerve/nerve-e2e.test.ts +731 -731
  57. package/src/dex/nerve/nerve-events.test.ts +911 -911
  58. package/src/dex/nerve/nerve.ts +467 -467
  59. package/src/dex/onebit/onebit.ts +113 -113
  60. package/src/dex/pancakeswap-v3/pancakeswap-v3.ts +1150 -1150
  61. package/src/dex/paraswap-limit-orders/config.ts +60 -60
  62. package/src/dex/paraswap-limit-orders/paraswap-limit-orders-e2e.test.ts +137 -137
  63. package/src/dex/paraswap-limit-orders/paraswap-limit-orders-integration.test.ts +328 -328
  64. package/src/dex/paraswap-limit-orders/paraswap-limit-orders.ts +631 -631
  65. package/src/dex/polygon-migrator/polygon-migrator.ts +194 -194
  66. package/src/dex/quick-perps/quick-perps.ts +337 -337
  67. package/src/dex/quickswap/config.ts +16 -16
  68. package/src/dex/quickswap/quickswap-e2e.test.ts +384 -384
  69. package/src/dex/smoothy/smoothy.ts +110 -110
  70. package/src/dex/solidly/config.ts +225 -225
  71. package/src/dex/solidly/solidly-e2e.test.ts +1421 -1421
  72. package/src/dex/solidly/solidly-integration.test.ts +1753 -1753
  73. package/src/dex/solidly/solidly.ts +687 -687
  74. package/src/dex/solidly-v3/solidly-v3.ts +968 -968
  75. package/src/dex/spark/spark.ts +284 -284
  76. package/src/dex/stable-pool/stable-pool.ts +129 -129
  77. package/src/dex/swaap-v2/config.ts +15 -0
  78. package/src/dex/swaap-v2/swaap-v2-e2e.test.ts +233 -17
  79. package/src/dex/swaap-v2/swaap-v2-integration.test.ts +1 -1
  80. package/src/dex/swaap-v2/swaap-v2.ts +1056 -1056
  81. package/src/dex/swell/swell.ts +312 -312
  82. package/src/dex/synthetix/synthetix.ts +420 -420
  83. package/src/dex/trader-joe-v2.1/trader-joe-v2.1.ts +180 -180
  84. package/src/dex/uniswap-v2/config.ts +637 -637
  85. package/src/dex/uniswap-v2/constants.ts +58 -58
  86. package/src/dex/uniswap-v2/uniswap-v2-e2e-avalanche.test.ts +1257 -1257
  87. package/src/dex/uniswap-v2/uniswap-v2-e2e-base.test.ts +42 -42
  88. package/src/dex/uniswap-v2/uniswap-v2-e2e-bsc.test.ts +1295 -1295
  89. package/src/dex/uniswap-v2/uniswap-v2-e2e-mainnet.test.ts +1834 -1834
  90. package/src/dex/uniswap-v2/uniswap-v2-e2e-polygon.test.ts +871 -871
  91. package/src/dex/uniswap-v2/uniswap-v2.ts +1117 -1117
  92. package/src/dex/uniswap-v3/uniswap-v3.ts +1501 -1501
  93. package/src/dex/uniswap-v3.ts +242 -242
  94. package/src/dex/weth/config.ts +73 -73
  95. package/src/dex/weth/weth.ts +230 -230
  96. package/src/dex/wombat/wombat.ts +467 -467
  97. package/src/dex/woo-fi-v2/woo-fi-v2.ts +529 -529
  98. package/src/dex/wsteth/wsteth.ts +304 -304
  99. package/src/dex/zerox/index.ts +328 -328
  100. package/src/executor/Executor01BytecodeBuilder.ts +474 -474
  101. package/src/executor/Executor02BytecodeBuilder.ts +1392 -1392
  102. package/src/executor/ExecutorBytecodeBuilder.ts +390 -390
  103. package/src/executor/ExecutorDetector.ts +131 -131
  104. package/src/executor/constants.ts +66 -66
  105. package/src/executor/executor01-bytecode-builder-e2e.test.ts +1478 -1478
  106. package/src/executor/utils.ts +62 -62
  107. package/src/router/simpleswap.ts +366 -366
  108. package/src/types.ts +342 -342
  109. package/tests/constants-e2e.ts +1632 -1622
  110. package/tests/generate-new-limit-order.ts +107 -107
@@ -1,431 +1,431 @@
1
- import BigNumber from 'bignumber.js';
2
- import {
3
- Token,
4
- ExchangePrices,
5
- ExchangeTxInfo,
6
- PreprocessTransactionOptions,
7
- Config,
8
- PoolLiquidity,
9
- Address,
10
- DexExchangeParam,
11
- } from '../../types';
12
- import { Network, SwapSide } from '../../constants';
13
- import { IDexHelper } from '../../dex-helper';
14
- import { ParaSwapLimitOrders } from '../paraswap-limit-orders/paraswap-limit-orders';
15
- import { BN_0, BN_1, getBigNumberPow } from '../../bignumber-constants';
16
- import { ParaSwapLimitOrdersData } from '../paraswap-limit-orders/types';
17
- import { ONE_ORDER_GASCOST } from '../paraswap-limit-orders/constant';
18
- import { RateFetcher } from './rate-fetcher';
19
- import {
20
- PriceAndAmountBigNumber,
21
- RFQConfig,
22
- RFQDirectPayload,
23
- RFQParams,
24
- SlippageCheckError,
25
- } from './types';
26
- import {
27
- ContractMethodV6,
28
- NumberAsString,
29
- OptimalSwapExchange,
30
- ParaSwapVersion,
31
- } from '@paraswap/core';
32
- import { BI_MAX_UINT256 } from '../../bigint-constants';
33
- import { SpecialDex } from '../../executor/types';
34
- import { hexConcat, hexZeroPad, hexlify } from 'ethers/lib/utils';
35
- import { isETHAddress, uuidToBytes16 } from '../../utils';
36
-
37
- export const OVERORDER_BPS = 100;
38
- export const BPS_MAX_VALUE = 10000n;
39
-
40
- export const overOrder = (amount: string, bps: number) =>
41
- ((BigInt(amount) * (BPS_MAX_VALUE + BigInt(bps))) / BPS_MAX_VALUE).toString();
42
-
43
- export class GenericRFQ extends ParaSwapLimitOrders {
44
- readonly isStatePollingDex = true;
45
- private rateFetcher: RateFetcher;
46
-
47
- public static dexKeysWithNetwork: { key: string; networks: Network[] }[] = [];
48
-
49
- static builderDexKeysWithNetwork(config: Config): void {
50
- Object.keys(config.rfqConfigs).forEach(rfqName =>
51
- this.dexKeysWithNetwork.push({
52
- key: rfqName,
53
- networks: [config.network],
54
- }),
55
- );
56
- }
57
-
58
- constructor(
59
- protected network: Network,
60
- dexKey: string,
61
- protected dexHelper: IDexHelper,
62
- private config: RFQConfig,
63
- ) {
64
- super(network, dexKey, dexHelper);
65
- this.rateFetcher = new RateFetcher(dexHelper, config, dexKey, this.logger);
66
- }
67
-
68
- async initializePricing(blockNumber: number): Promise<void> {
69
- await this.rateFetcher.initialize();
70
- if (!this.dexHelper.config.isSlave) {
71
- this.rateFetcher.start();
72
- }
73
- return;
74
- }
75
-
76
- getIdentifier(srcToken: Address, destToken: Address) {
77
- // Keep only destination token in order to prevent taping into the same market maker liquidity during same swap (double spending)
78
- return `${this.dexKey}_${destToken}`.toLowerCase();
79
- }
80
-
81
- async getPoolIdentifiers(
82
- srcToken: Token,
83
- destToken: Token,
84
- side: SwapSide,
85
- blockNumber: number,
86
- ): Promise<string[]> {
87
- const _destToken = this.dexHelper.config.wrapETH(destToken);
88
- return [this.getIdentifier(srcToken.address, _destToken.address)];
89
- }
90
-
91
- calcOutsFromAmounts(
92
- amounts: BigNumber[],
93
- outMultiplier: BigNumber,
94
- amountsWithRates: PriceAndAmountBigNumber[],
95
- ): bigint[] {
96
- let lastOrderIndex = 0;
97
- let lastTotalSrcAmount = BN_0;
98
- let lastTotalDestAmount = BN_0;
99
- const outputs = new Array<BigNumber>(amounts.length).fill(BN_0);
100
- for (const [i, amount] of amounts.entries()) {
101
- if (amount.isZero()) {
102
- outputs[i] = BN_0;
103
- } else {
104
- let srcAmountLeft = amount.minus(lastTotalSrcAmount);
105
- let destAmountFilled = lastTotalDestAmount;
106
- while (lastOrderIndex < amountsWithRates.length) {
107
- const [price, amount] = amountsWithRates[lastOrderIndex];
108
- if (srcAmountLeft.gt(amount)) {
109
- const destAmount = amount.multipliedBy(price);
110
-
111
- srcAmountLeft = srcAmountLeft.minus(amount);
112
- destAmountFilled = destAmountFilled.plus(destAmount);
113
-
114
- lastTotalSrcAmount = lastTotalSrcAmount.plus(amount);
115
- lastTotalDestAmount = lastTotalDestAmount.plus(destAmount);
116
- lastOrderIndex++;
117
- } else {
118
- destAmountFilled = destAmountFilled.plus(
119
- srcAmountLeft.multipliedBy(price),
120
- );
121
- srcAmountLeft = BN_0;
122
- break;
123
- }
124
- }
125
- if (srcAmountLeft.isZero()) {
126
- outputs[i] = destAmountFilled;
127
- } else {
128
- // If current amount was unfillable, then bigger amounts are unfillable as well
129
- break;
130
- }
131
- }
132
- }
133
-
134
- return outputs.map(o => BigInt(o.multipliedBy(outMultiplier).toFixed(0)));
135
- }
136
-
137
- async getPricesVolume(
138
- srcToken: Token,
139
- destToken: Token,
140
- amounts: bigint[],
141
- side: SwapSide,
142
- blockNumber: number,
143
- limitPools?: string[],
144
- ): Promise<ExchangePrices<ParaSwapLimitOrdersData> | null> {
145
- const _srcToken = this.dexHelper.config.wrapETH(srcToken);
146
- const _destToken = this.dexHelper.config.wrapETH(destToken);
147
-
148
- _srcToken.address = _srcToken.address.toLowerCase();
149
- _destToken.address = _destToken.address.toLowerCase();
150
- if (_srcToken.address === _destToken.address) return null;
151
-
152
- const expectedIdentifier = this.getIdentifier(
153
- _srcToken.address,
154
- _destToken.address,
155
- );
156
-
157
- if (!limitPools?.includes(expectedIdentifier)) {
158
- return null;
159
- }
160
-
161
- const rates = await this.rateFetcher.getOrderPrice(
162
- _srcToken,
163
- _destToken,
164
- side,
165
- );
166
- if (!rates) {
167
- return null;
168
- }
169
-
170
- const inDecimals =
171
- side === SwapSide.SELL ? _srcToken.decimals : _destToken.decimals;
172
- const outDecimals =
173
- side === SwapSide.SELL ? _destToken.decimals : _srcToken.decimals;
174
-
175
- const _amountsInBN = amounts.map(a =>
176
- new BigNumber(a.toString()).dividedBy(getBigNumberPow(inDecimals)),
177
- );
178
-
179
- const unitVolume = BN_1;
180
-
181
- const unitResults = this.calcOutsFromAmounts(
182
- [unitVolume],
183
- getBigNumberPow(outDecimals),
184
- rates,
185
- );
186
-
187
- const unit = unitResults[0];
188
- const outputs = this.calcOutsFromAmounts(
189
- _amountsInBN,
190
- getBigNumberPow(outDecimals),
191
- rates,
192
- );
193
- return [
194
- {
195
- gasCost: Number(ONE_ORDER_GASCOST),
196
- exchange: this.dexKey,
197
- poolIdentifier: expectedIdentifier,
198
- prices: outputs,
199
- unit,
200
- data: {
201
- orderInfos: null,
202
- },
203
- },
204
- ];
205
- }
206
-
207
- static getDirectFunctionNameV6(): string[] {
208
- return [ContractMethodV6.swapOnAugustusRFQTryBatchFill];
209
- }
210
-
211
- getDirectParamV6(
212
- srcToken: Address,
213
- destToken: Address,
214
- fromAmount: NumberAsString,
215
- toAmount: NumberAsString,
216
- quotedAmount: NumberAsString,
217
- data: ParaSwapLimitOrdersData,
218
- side: SwapSide,
219
- permit: string,
220
- uuid: string,
221
- partnerAndFee: string,
222
- beneficiary: string,
223
- blockNumber: number,
224
- contractMethod?: string,
225
- ) {
226
- if (!contractMethod) throw new Error(`contractMethod need to be passed`);
227
- if (!GenericRFQ.getDirectFunctionNameV6().includes(contractMethod!)) {
228
- throw new Error(`Invalid contract method ${contractMethod}`);
229
- }
230
- if (data.orderInfos === null) {
231
- throw new Error(
232
- `Error_${this.dexKey}_getDirectParamV6 payload is not received. It may be because of` +
233
- `not calling preProcessTransaction before`,
234
- );
235
- }
236
-
237
- // 2 if dest is ETH, 1 if src is ETH, 0 if none
238
- const wrap = isETHAddress(destToken) ? 2 : isETHAddress(srcToken) ? 1 : 0;
239
-
240
- // 1 if need approve, 0 if not
241
- const approve = data.isApproved ? 0 : 1;
242
-
243
- // 0 for SELL, 1 for BUY
244
- const direction = side === SwapSide.SELL ? 0 : 1;
245
-
246
- const wrapApproveDirection = (direction << 3) | (approve << 2) | wrap;
247
-
248
- const metadata = hexConcat([
249
- hexZeroPad(uuidToBytes16(uuid), 16),
250
- hexZeroPad(hexlify(blockNumber), 16),
251
- ]);
252
-
253
- const params: RFQParams = [
254
- fromAmount,
255
- toAmount,
256
- wrapApproveDirection.toString(),
257
- metadata,
258
- beneficiary,
259
- ];
260
-
261
- const payload: RFQDirectPayload = [params, data.orderInfos, permit];
262
-
263
- const encoder = (...params: (string | RFQDirectPayload)[]) => {
264
- return this.augustusV6Interface.encodeFunctionData(
265
- ContractMethodV6.swapOnAugustusRFQTryBatchFill,
266
- [...params],
267
- );
268
- };
269
-
270
- return { params: payload, encoder, networkFee: '0' };
271
- }
272
-
273
- getDexParam(
274
- srcToken: Address,
275
- destToken: Address,
276
- srcAmount: NumberAsString,
277
- destAmount: NumberAsString,
278
- recipient: Address,
279
- data: ParaSwapLimitOrdersData,
280
- side: SwapSide,
281
- ): DexExchangeParam {
282
- const { orderInfos } = data;
283
-
284
- if (orderInfos === null) {
285
- throw new Error(
286
- `Error_${this.dexKey}_getDexParam payload is not received. It may be because of` +
287
- `not calling preProcessTransaction before`,
288
- );
289
- }
290
-
291
- const isSell = side === SwapSide.SELL;
292
-
293
- const specialDexExchangeData = this.rfqIface.encodeFunctionData(
294
- isSell ? 'tryBatchFillOrderTakerAmount' : 'tryBatchFillOrderMakerAmount',
295
- [orderInfos, isSell ? srcAmount : destAmount, recipient],
296
- );
297
-
298
- return {
299
- needWrapNative: this.needWrapNative,
300
- dexFuncHasRecipient: true,
301
- exchangeData: specialDexExchangeData,
302
- specialDexFlag: SpecialDex.SWAP_ON_AUGUSTUS_RFQ,
303
- targetExchange: this.augustusRFQAddress,
304
- specialDexSupportsInsertFromAmount: true,
305
- returnAmountPos: undefined,
306
- };
307
- }
308
-
309
- async preProcessTransaction?(
310
- optimalSwapExchange: OptimalSwapExchange<ParaSwapLimitOrdersData>,
311
- srcToken: Token,
312
- destToken: Token,
313
- side: SwapSide,
314
- options: PreprocessTransactionOptions,
315
- ): Promise<[OptimalSwapExchange<ParaSwapLimitOrdersData>, ExchangeTxInfo]> {
316
- const isSell = side === SwapSide.SELL;
317
-
318
- const order = await this.rateFetcher.getFirmRate(
319
- srcToken,
320
- destToken,
321
- isSell
322
- ? overOrder(optimalSwapExchange.srcAmount, OVERORDER_BPS)
323
- : overOrder(optimalSwapExchange.destAmount, 1),
324
- side,
325
- options.executionContractAddress,
326
- options.txOrigin,
327
- options.partner,
328
- options.special,
329
- );
330
-
331
- const expiryAsBigInt = BigInt(order.order.expiry);
332
- const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : BI_MAX_UINT256;
333
-
334
- const makerAssetAmount = BigInt(order.order.makerAmount);
335
- const takerAssetAmount = BigInt(order.order.takerAmount);
336
-
337
- const srcAmount = BigInt(optimalSwapExchange.srcAmount);
338
- const destAmount = BigInt(optimalSwapExchange.destAmount);
339
-
340
- const slippageFactor = options.slippageFactor;
341
-
342
- if (side === SwapSide.SELL) {
343
- const makerAssetAmountFilled =
344
- takerAssetAmount > srcAmount
345
- ? (makerAssetAmount * srcAmount) / takerAssetAmount
346
- : makerAssetAmount;
347
-
348
- if (
349
- makerAssetAmountFilled <
350
- BigInt(
351
- new BigNumber(destAmount.toString()).times(slippageFactor).toFixed(0),
352
- )
353
- ) {
354
- const message = `${this.dexKey}: too much slippage on quote ${side} makerAssetAmountFilled ${makerAssetAmountFilled} / destAmount ${destAmount} < ${slippageFactor}`;
355
- this.logger.warn(message);
356
- throw new SlippageCheckError(message);
357
- }
358
- } else {
359
- if (makerAssetAmount < destAmount) {
360
- // Won't receive enough assets
361
- const message = `${this.dexKey}: too much slippage on quote ${side} makerAssetAmount ${makerAssetAmount} < destAmount ${destAmount}`;
362
- this.logger.warn(message);
363
- throw new SlippageCheckError(message);
364
- } else {
365
- if (
366
- takerAssetAmount >
367
- BigInt(slippageFactor.times(srcAmount.toString()).toFixed(0))
368
- ) {
369
- const message = `${
370
- this.dexKey
371
- }: too much slippage on quote ${side} takerAssetAmount ${takerAssetAmount} / srcAmount ${srcAmount} > ${slippageFactor.toFixed()}`;
372
- this.logger.warn(message);
373
- throw new SlippageCheckError(message);
374
- }
375
- }
376
- }
377
-
378
- let isApproved = false;
379
-
380
- // isApproved is only used in direct method and available only for v6, then no need to check approve for v5
381
- // because it's either done in getSimpleParam or approve call in the adapter smart contract
382
- if (options.version === ParaSwapVersion.V6 && options.isDirectMethod) {
383
- isApproved = await this.dexHelper.augustusApprovals.hasApproval(
384
- options.executionContractAddress,
385
- // ETH always need to be wrapped for RFQ
386
- this.dexHelper.config.wrapETH(srcToken).address,
387
- this.augustusRFQAddress,
388
- );
389
- }
390
-
391
- return [
392
- { ...optimalSwapExchange, data: { orderInfos: [order], isApproved } },
393
- { deadline: minDeadline },
394
- ];
395
- }
396
-
397
- async getTopPoolsForToken(
398
- tokenAddress: string,
399
- limit: number,
400
- ): Promise<PoolLiquidity[]> {
401
- const pairs = this.rateFetcher.getPairsLiquidity(
402
- tokenAddress.toLowerCase(),
403
- );
404
-
405
- return pairs.map(pair => ({
406
- exchange: this.dexKey,
407
- address: this.config.maker,
408
- connectorTokens: pair.connectorTokens,
409
- liquidityUSD: pair.liquidityUSD,
410
- }));
411
- }
412
-
413
- async isBlacklisted(userAddress: string): Promise<boolean> {
414
- return this.rateFetcher.isBlackListed(userAddress);
415
- }
416
-
417
- async setBlacklist(userAddress: string): Promise<boolean> {
418
- await this.dexHelper.cache.hset(
419
- this.rateFetcher.blackListCacheKey,
420
- userAddress.toLowerCase(),
421
- 'true',
422
- );
423
- return true;
424
- }
425
-
426
- releaseResources(): void {
427
- if (this.rateFetcher) {
428
- this.rateFetcher.stop();
429
- }
430
- }
431
- }
1
+ import BigNumber from 'bignumber.js';
2
+ import {
3
+ Token,
4
+ ExchangePrices,
5
+ ExchangeTxInfo,
6
+ PreprocessTransactionOptions,
7
+ Config,
8
+ PoolLiquidity,
9
+ Address,
10
+ DexExchangeParam,
11
+ } from '../../types';
12
+ import { Network, SwapSide } from '../../constants';
13
+ import { IDexHelper } from '../../dex-helper';
14
+ import { ParaSwapLimitOrders } from '../paraswap-limit-orders/paraswap-limit-orders';
15
+ import { BN_0, BN_1, getBigNumberPow } from '../../bignumber-constants';
16
+ import { ParaSwapLimitOrdersData } from '../paraswap-limit-orders/types';
17
+ import { ONE_ORDER_GASCOST } from '../paraswap-limit-orders/constant';
18
+ import { RateFetcher } from './rate-fetcher';
19
+ import {
20
+ PriceAndAmountBigNumber,
21
+ RFQConfig,
22
+ RFQDirectPayload,
23
+ RFQParams,
24
+ SlippageCheckError,
25
+ } from './types';
26
+ import {
27
+ ContractMethodV6,
28
+ NumberAsString,
29
+ OptimalSwapExchange,
30
+ ParaSwapVersion,
31
+ } from '@paraswap/core';
32
+ import { BI_MAX_UINT256 } from '../../bigint-constants';
33
+ import { SpecialDex } from '../../executor/types';
34
+ import { hexConcat, hexZeroPad, hexlify } from 'ethers/lib/utils';
35
+ import { isETHAddress, uuidToBytes16 } from '../../utils';
36
+
37
+ export const OVERORDER_BPS = 100;
38
+ export const BPS_MAX_VALUE = 10000n;
39
+
40
+ export const overOrder = (amount: string, bps: number) =>
41
+ ((BigInt(amount) * (BPS_MAX_VALUE + BigInt(bps))) / BPS_MAX_VALUE).toString();
42
+
43
+ export class GenericRFQ extends ParaSwapLimitOrders {
44
+ readonly isStatePollingDex = true;
45
+ private rateFetcher: RateFetcher;
46
+
47
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] = [];
48
+
49
+ static builderDexKeysWithNetwork(config: Config): void {
50
+ Object.keys(config.rfqConfigs).forEach(rfqName =>
51
+ this.dexKeysWithNetwork.push({
52
+ key: rfqName,
53
+ networks: [config.network],
54
+ }),
55
+ );
56
+ }
57
+
58
+ constructor(
59
+ protected network: Network,
60
+ dexKey: string,
61
+ protected dexHelper: IDexHelper,
62
+ private config: RFQConfig,
63
+ ) {
64
+ super(network, dexKey, dexHelper);
65
+ this.rateFetcher = new RateFetcher(dexHelper, config, dexKey, this.logger);
66
+ }
67
+
68
+ async initializePricing(blockNumber: number): Promise<void> {
69
+ await this.rateFetcher.initialize();
70
+ if (!this.dexHelper.config.isSlave) {
71
+ this.rateFetcher.start();
72
+ }
73
+ return;
74
+ }
75
+
76
+ getIdentifier(srcToken: Address, destToken: Address) {
77
+ // Keep only destination token in order to prevent taping into the same market maker liquidity during same swap (double spending)
78
+ return `${this.dexKey}_${destToken}`.toLowerCase();
79
+ }
80
+
81
+ async getPoolIdentifiers(
82
+ srcToken: Token,
83
+ destToken: Token,
84
+ side: SwapSide,
85
+ blockNumber: number,
86
+ ): Promise<string[]> {
87
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
88
+ return [this.getIdentifier(srcToken.address, _destToken.address)];
89
+ }
90
+
91
+ calcOutsFromAmounts(
92
+ amounts: BigNumber[],
93
+ outMultiplier: BigNumber,
94
+ amountsWithRates: PriceAndAmountBigNumber[],
95
+ ): bigint[] {
96
+ let lastOrderIndex = 0;
97
+ let lastTotalSrcAmount = BN_0;
98
+ let lastTotalDestAmount = BN_0;
99
+ const outputs = new Array<BigNumber>(amounts.length).fill(BN_0);
100
+ for (const [i, amount] of amounts.entries()) {
101
+ if (amount.isZero()) {
102
+ outputs[i] = BN_0;
103
+ } else {
104
+ let srcAmountLeft = amount.minus(lastTotalSrcAmount);
105
+ let destAmountFilled = lastTotalDestAmount;
106
+ while (lastOrderIndex < amountsWithRates.length) {
107
+ const [price, amount] = amountsWithRates[lastOrderIndex];
108
+ if (srcAmountLeft.gt(amount)) {
109
+ const destAmount = amount.multipliedBy(price);
110
+
111
+ srcAmountLeft = srcAmountLeft.minus(amount);
112
+ destAmountFilled = destAmountFilled.plus(destAmount);
113
+
114
+ lastTotalSrcAmount = lastTotalSrcAmount.plus(amount);
115
+ lastTotalDestAmount = lastTotalDestAmount.plus(destAmount);
116
+ lastOrderIndex++;
117
+ } else {
118
+ destAmountFilled = destAmountFilled.plus(
119
+ srcAmountLeft.multipliedBy(price),
120
+ );
121
+ srcAmountLeft = BN_0;
122
+ break;
123
+ }
124
+ }
125
+ if (srcAmountLeft.isZero()) {
126
+ outputs[i] = destAmountFilled;
127
+ } else {
128
+ // If current amount was unfillable, then bigger amounts are unfillable as well
129
+ break;
130
+ }
131
+ }
132
+ }
133
+
134
+ return outputs.map(o => BigInt(o.multipliedBy(outMultiplier).toFixed(0)));
135
+ }
136
+
137
+ async getPricesVolume(
138
+ srcToken: Token,
139
+ destToken: Token,
140
+ amounts: bigint[],
141
+ side: SwapSide,
142
+ blockNumber: number,
143
+ limitPools?: string[],
144
+ ): Promise<ExchangePrices<ParaSwapLimitOrdersData> | null> {
145
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
146
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
147
+
148
+ _srcToken.address = _srcToken.address.toLowerCase();
149
+ _destToken.address = _destToken.address.toLowerCase();
150
+ if (_srcToken.address === _destToken.address) return null;
151
+
152
+ const expectedIdentifier = this.getIdentifier(
153
+ _srcToken.address,
154
+ _destToken.address,
155
+ );
156
+
157
+ if (!limitPools?.includes(expectedIdentifier)) {
158
+ return null;
159
+ }
160
+
161
+ const rates = await this.rateFetcher.getOrderPrice(
162
+ _srcToken,
163
+ _destToken,
164
+ side,
165
+ );
166
+ if (!rates) {
167
+ return null;
168
+ }
169
+
170
+ const inDecimals =
171
+ side === SwapSide.SELL ? _srcToken.decimals : _destToken.decimals;
172
+ const outDecimals =
173
+ side === SwapSide.SELL ? _destToken.decimals : _srcToken.decimals;
174
+
175
+ const _amountsInBN = amounts.map(a =>
176
+ new BigNumber(a.toString()).dividedBy(getBigNumberPow(inDecimals)),
177
+ );
178
+
179
+ const unitVolume = BN_1;
180
+
181
+ const unitResults = this.calcOutsFromAmounts(
182
+ [unitVolume],
183
+ getBigNumberPow(outDecimals),
184
+ rates,
185
+ );
186
+
187
+ const unit = unitResults[0];
188
+ const outputs = this.calcOutsFromAmounts(
189
+ _amountsInBN,
190
+ getBigNumberPow(outDecimals),
191
+ rates,
192
+ );
193
+ return [
194
+ {
195
+ gasCost: Number(ONE_ORDER_GASCOST),
196
+ exchange: this.dexKey,
197
+ poolIdentifier: expectedIdentifier,
198
+ prices: outputs,
199
+ unit,
200
+ data: {
201
+ orderInfos: null,
202
+ },
203
+ },
204
+ ];
205
+ }
206
+
207
+ static getDirectFunctionNameV6(): string[] {
208
+ return [ContractMethodV6.swapOnAugustusRFQTryBatchFill];
209
+ }
210
+
211
+ getDirectParamV6(
212
+ srcToken: Address,
213
+ destToken: Address,
214
+ fromAmount: NumberAsString,
215
+ toAmount: NumberAsString,
216
+ quotedAmount: NumberAsString,
217
+ data: ParaSwapLimitOrdersData,
218
+ side: SwapSide,
219
+ permit: string,
220
+ uuid: string,
221
+ partnerAndFee: string,
222
+ beneficiary: string,
223
+ blockNumber: number,
224
+ contractMethod?: string,
225
+ ) {
226
+ if (!contractMethod) throw new Error(`contractMethod need to be passed`);
227
+ if (!GenericRFQ.getDirectFunctionNameV6().includes(contractMethod!)) {
228
+ throw new Error(`Invalid contract method ${contractMethod}`);
229
+ }
230
+ if (data.orderInfos === null) {
231
+ throw new Error(
232
+ `Error_${this.dexKey}_getDirectParamV6 payload is not received. It may be because of` +
233
+ `not calling preProcessTransaction before`,
234
+ );
235
+ }
236
+
237
+ // 2 if dest is ETH, 1 if src is ETH, 0 if none
238
+ const wrap = isETHAddress(destToken) ? 2 : isETHAddress(srcToken) ? 1 : 0;
239
+
240
+ // 1 if need approve, 0 if not
241
+ const approve = data.isApproved ? 0 : 1;
242
+
243
+ // 0 for SELL, 1 for BUY
244
+ const direction = side === SwapSide.SELL ? 0 : 1;
245
+
246
+ const wrapApproveDirection = (direction << 3) | (approve << 2) | wrap;
247
+
248
+ const metadata = hexConcat([
249
+ hexZeroPad(uuidToBytes16(uuid), 16),
250
+ hexZeroPad(hexlify(blockNumber), 16),
251
+ ]);
252
+
253
+ const params: RFQParams = [
254
+ fromAmount,
255
+ toAmount,
256
+ wrapApproveDirection.toString(),
257
+ metadata,
258
+ beneficiary,
259
+ ];
260
+
261
+ const payload: RFQDirectPayload = [params, data.orderInfos, permit];
262
+
263
+ const encoder = (...params: (string | RFQDirectPayload)[]) => {
264
+ return this.augustusV6Interface.encodeFunctionData(
265
+ ContractMethodV6.swapOnAugustusRFQTryBatchFill,
266
+ [...params],
267
+ );
268
+ };
269
+
270
+ return { params: payload, encoder, networkFee: '0' };
271
+ }
272
+
273
+ getDexParam(
274
+ srcToken: Address,
275
+ destToken: Address,
276
+ srcAmount: NumberAsString,
277
+ destAmount: NumberAsString,
278
+ recipient: Address,
279
+ data: ParaSwapLimitOrdersData,
280
+ side: SwapSide,
281
+ ): DexExchangeParam {
282
+ const { orderInfos } = data;
283
+
284
+ if (orderInfos === null) {
285
+ throw new Error(
286
+ `Error_${this.dexKey}_getDexParam payload is not received. It may be because of` +
287
+ `not calling preProcessTransaction before`,
288
+ );
289
+ }
290
+
291
+ const isSell = side === SwapSide.SELL;
292
+
293
+ const specialDexExchangeData = this.rfqIface.encodeFunctionData(
294
+ isSell ? 'tryBatchFillOrderTakerAmount' : 'tryBatchFillOrderMakerAmount',
295
+ [orderInfos, isSell ? srcAmount : destAmount, recipient],
296
+ );
297
+
298
+ return {
299
+ needWrapNative: this.needWrapNative,
300
+ dexFuncHasRecipient: true,
301
+ exchangeData: specialDexExchangeData,
302
+ specialDexFlag: SpecialDex.SWAP_ON_AUGUSTUS_RFQ,
303
+ targetExchange: this.augustusRFQAddress,
304
+ specialDexSupportsInsertFromAmount: true,
305
+ returnAmountPos: undefined,
306
+ };
307
+ }
308
+
309
+ async preProcessTransaction?(
310
+ optimalSwapExchange: OptimalSwapExchange<ParaSwapLimitOrdersData>,
311
+ srcToken: Token,
312
+ destToken: Token,
313
+ side: SwapSide,
314
+ options: PreprocessTransactionOptions,
315
+ ): Promise<[OptimalSwapExchange<ParaSwapLimitOrdersData>, ExchangeTxInfo]> {
316
+ const isSell = side === SwapSide.SELL;
317
+
318
+ const order = await this.rateFetcher.getFirmRate(
319
+ srcToken,
320
+ destToken,
321
+ isSell
322
+ ? overOrder(optimalSwapExchange.srcAmount, OVERORDER_BPS)
323
+ : overOrder(optimalSwapExchange.destAmount, 1),
324
+ side,
325
+ options.executionContractAddress,
326
+ options.txOrigin,
327
+ options.partner,
328
+ options.special,
329
+ );
330
+
331
+ const expiryAsBigInt = BigInt(order.order.expiry);
332
+ const minDeadline = expiryAsBigInt > 0 ? expiryAsBigInt : BI_MAX_UINT256;
333
+
334
+ const makerAssetAmount = BigInt(order.order.makerAmount);
335
+ const takerAssetAmount = BigInt(order.order.takerAmount);
336
+
337
+ const srcAmount = BigInt(optimalSwapExchange.srcAmount);
338
+ const destAmount = BigInt(optimalSwapExchange.destAmount);
339
+
340
+ const slippageFactor = options.slippageFactor;
341
+
342
+ if (side === SwapSide.SELL) {
343
+ const makerAssetAmountFilled =
344
+ takerAssetAmount > srcAmount
345
+ ? (makerAssetAmount * srcAmount) / takerAssetAmount
346
+ : makerAssetAmount;
347
+
348
+ if (
349
+ makerAssetAmountFilled <
350
+ BigInt(
351
+ new BigNumber(destAmount.toString()).times(slippageFactor).toFixed(0),
352
+ )
353
+ ) {
354
+ const message = `${this.dexKey}: too much slippage on quote ${side} makerAssetAmountFilled ${makerAssetAmountFilled} / destAmount ${destAmount} < ${slippageFactor}`;
355
+ this.logger.warn(message);
356
+ throw new SlippageCheckError(message);
357
+ }
358
+ } else {
359
+ if (makerAssetAmount < destAmount) {
360
+ // Won't receive enough assets
361
+ const message = `${this.dexKey}: too much slippage on quote ${side} makerAssetAmount ${makerAssetAmount} < destAmount ${destAmount}`;
362
+ this.logger.warn(message);
363
+ throw new SlippageCheckError(message);
364
+ } else {
365
+ if (
366
+ takerAssetAmount >
367
+ BigInt(slippageFactor.times(srcAmount.toString()).toFixed(0))
368
+ ) {
369
+ const message = `${
370
+ this.dexKey
371
+ }: too much slippage on quote ${side} takerAssetAmount ${takerAssetAmount} / srcAmount ${srcAmount} > ${slippageFactor.toFixed()}`;
372
+ this.logger.warn(message);
373
+ throw new SlippageCheckError(message);
374
+ }
375
+ }
376
+ }
377
+
378
+ let isApproved = false;
379
+
380
+ // isApproved is only used in direct method and available only for v6, then no need to check approve for v5
381
+ // because it's either done in getSimpleParam or approve call in the adapter smart contract
382
+ if (options.version === ParaSwapVersion.V6 && options.isDirectMethod) {
383
+ isApproved = await this.dexHelper.augustusApprovals.hasApproval(
384
+ options.executionContractAddress,
385
+ // ETH always need to be wrapped for RFQ
386
+ this.dexHelper.config.wrapETH(srcToken).address,
387
+ this.augustusRFQAddress,
388
+ );
389
+ }
390
+
391
+ return [
392
+ { ...optimalSwapExchange, data: { orderInfos: [order], isApproved } },
393
+ { deadline: minDeadline },
394
+ ];
395
+ }
396
+
397
+ async getTopPoolsForToken(
398
+ tokenAddress: string,
399
+ limit: number,
400
+ ): Promise<PoolLiquidity[]> {
401
+ const pairs = this.rateFetcher.getPairsLiquidity(
402
+ tokenAddress.toLowerCase(),
403
+ );
404
+
405
+ return pairs.map(pair => ({
406
+ exchange: this.dexKey,
407
+ address: this.config.maker,
408
+ connectorTokens: pair.connectorTokens,
409
+ liquidityUSD: pair.liquidityUSD,
410
+ }));
411
+ }
412
+
413
+ async isBlacklisted(userAddress: string): Promise<boolean> {
414
+ return this.rateFetcher.isBlackListed(userAddress);
415
+ }
416
+
417
+ async setBlacklist(userAddress: string): Promise<boolean> {
418
+ await this.dexHelper.cache.hset(
419
+ this.rateFetcher.blackListCacheKey,
420
+ userAddress.toLowerCase(),
421
+ 'true',
422
+ );
423
+ return true;
424
+ }
425
+
426
+ releaseResources(): void {
427
+ if (this.rateFetcher) {
428
+ this.rateFetcher.stop();
429
+ }
430
+ }
431
+ }