/
exchange_proxy_swap_quote_consumer.ts
758 lines (725 loc) · 33.1 KB
/
exchange_proxy_swap_quote_consumer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
import { ChainId, ContractAddresses } from '@0x/contract-addresses';
import { IZeroExContract } from '@0x/contract-wrappers';
import {
encodeAffiliateFeeTransformerData,
encodeCurveLiquidityProviderData,
encodeFillQuoteTransformerData,
encodePayTakerTransformerData,
encodePositiveSlippageFeeTransformerData,
encodeWethTransformerData,
ETH_TOKEN_ADDRESS,
FillQuoteTransformerOrderType,
FillQuoteTransformerSide,
findTransformerNonce,
} from '@0x/protocol-utils';
import { BigNumber } from '@0x/utils';
import * as _ from 'lodash';
import { constants, POSITIVE_SLIPPAGE_FEE_TRANSFORMER_GAS } from '../constants';
import {
AffiliateFeeType,
CalldataInfo,
ExchangeProxyContractOpts,
MarketBuySwapQuote,
MarketOperation,
MarketSellSwapQuote,
SwapQuote,
SwapQuoteConsumerBase,
SwapQuoteConsumerOpts,
SwapQuoteExecutionOpts,
SwapQuoteGetOutputOpts,
} from '../types';
import { assert } from '../utils/utils';
import {
CURVE_LIQUIDITY_PROVIDER_BY_CHAIN_ID,
NATIVE_FEE_TOKEN_BY_CHAIN_ID,
} from '../utils/market_operation_utils/constants';
import { CurveFillData, FinalUniswapV3FillData, UniswapV2FillData } from '../utils/market_operation_utils/types';
import {
ERC20BridgeSource,
NativeOtcOrderFillData,
NativeRfqOrderFillData,
OptimizedMarketBridgeOrder,
OptimizedOrder,
} from '../types';
import {
multiplexOtcOrder,
multiplexRfqEncoder,
MultiplexSubcall,
multiplexTransformERC20Encoder,
multiplexUniswapEncoder,
} from './multiplex_encoders';
import {
getFQTTransformerDataFromOptimizedOrders,
isBuyQuote,
isDirectSwapCompatible,
isMultiplexBatchFillCompatible,
isMultiplexMultiHopFillCompatible,
requiresTransformERC20,
} from './quote_consumer_utils';
const MAX_UINT256 = new BigNumber(2).pow(256).minus(1);
const { NULL_ADDRESS, ZERO_AMOUNT } = constants;
// use the same order in IPancakeSwapFeature.sol
const PANCAKE_SWAP_FORKS = [
ERC20BridgeSource.PancakeSwap,
ERC20BridgeSource.PancakeSwapV2,
ERC20BridgeSource.BakerySwap,
ERC20BridgeSource.SushiSwap,
ERC20BridgeSource.ApeSwap,
];
const FAKE_PROVIDER = {
sendAsync(): void {
return;
},
};
export class ExchangeProxySwapQuoteConsumer implements SwapQuoteConsumerBase {
public readonly chainId: ChainId;
public readonly transformerNonces: {
wethTransformer: number;
payTakerTransformer: number;
fillQuoteTransformer: number;
affiliateFeeTransformer: number;
positiveSlippageFeeTransformer: number;
};
private readonly _exchangeProxy: IZeroExContract;
constructor(public readonly contractAddresses: ContractAddresses, options: Partial<SwapQuoteConsumerOpts> = {}) {
const { chainId } = _.merge({}, constants.DEFAULT_SWAP_QUOTER_OPTS, options);
assert.isNumber('chainId', chainId);
this.chainId = chainId;
this.contractAddresses = contractAddresses;
this._exchangeProxy = new IZeroExContract(contractAddresses.exchangeProxy, FAKE_PROVIDER);
this.transformerNonces = {
wethTransformer: findTransformerNonce(
contractAddresses.transformers.wethTransformer,
contractAddresses.exchangeProxyTransformerDeployer,
),
payTakerTransformer: findTransformerNonce(
contractAddresses.transformers.payTakerTransformer,
contractAddresses.exchangeProxyTransformerDeployer,
),
fillQuoteTransformer: findTransformerNonce(
contractAddresses.transformers.fillQuoteTransformer,
contractAddresses.exchangeProxyTransformerDeployer,
),
affiliateFeeTransformer: findTransformerNonce(
contractAddresses.transformers.affiliateFeeTransformer,
contractAddresses.exchangeProxyTransformerDeployer,
),
positiveSlippageFeeTransformer: findTransformerNonce(
contractAddresses.transformers.positiveSlippageFeeTransformer,
contractAddresses.exchangeProxyTransformerDeployer,
),
};
}
public async getCalldataOrThrowAsync(
quote: MarketBuySwapQuote | MarketSellSwapQuote,
opts: Partial<SwapQuoteGetOutputOpts> = {},
): Promise<CalldataInfo> {
const optsWithDefaults: ExchangeProxyContractOpts = {
...constants.DEFAULT_EXCHANGE_PROXY_EXTENSION_CONTRACT_OPTS,
...opts.extensionContractOpts,
};
const { refundReceiver, affiliateFee, isFromETH, isToETH, shouldSellEntireBalance } = optsWithDefaults;
const sellToken = quote.takerToken;
const buyToken = quote.makerToken;
// Take the bounds from the worst case
const sellAmount = BigNumber.max(
quote.bestCaseQuoteInfo.totalTakerAmount,
quote.worstCaseQuoteInfo.totalTakerAmount,
);
let minBuyAmount = quote.worstCaseQuoteInfo.makerAmount;
let ethAmount = quote.worstCaseQuoteInfo.protocolFeeInWeiAmount;
if (isFromETH) {
ethAmount = ethAmount.plus(sellAmount);
}
const slippedOrders = slipNonNativeOrders(quote);
// VIP routes.
if (
this.chainId === ChainId.Mainnet &&
isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.UniswapV2, ERC20BridgeSource.SushiSwap])
) {
const source = slippedOrders[0].source;
const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<UniswapV2FillData>).fillData;
return {
calldataHexString: this._exchangeProxy
.sellToUniswap(
fillData.tokenAddressPath.map((a, i) => {
if (i === 0 && isFromETH) {
return ETH_TOKEN_ADDRESS;
}
if (i === fillData.tokenAddressPath.length - 1 && isToETH) {
return ETH_TOKEN_ADDRESS;
}
return a;
}),
sellAmount,
minBuyAmount,
source === ERC20BridgeSource.SushiSwap,
)
.getABIEncodedTransactionData(),
ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
if (
this.chainId === ChainId.Mainnet &&
isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.UniswapV3])
) {
const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<FinalUniswapV3FillData>).fillData;
let _calldataHexString;
if (isFromETH) {
_calldataHexString = this._exchangeProxy
.sellEthForTokenToUniswapV3(fillData.uniswapPath, minBuyAmount, NULL_ADDRESS)
.getABIEncodedTransactionData();
} else if (isToETH) {
_calldataHexString = this._exchangeProxy
.sellTokenForEthToUniswapV3(fillData.uniswapPath, sellAmount, minBuyAmount, NULL_ADDRESS)
.getABIEncodedTransactionData();
} else {
_calldataHexString = this._exchangeProxy
.sellTokenForTokenToUniswapV3(fillData.uniswapPath, sellAmount, minBuyAmount, NULL_ADDRESS)
.getABIEncodedTransactionData();
}
return {
calldataHexString: _calldataHexString,
ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
if (
this.chainId === ChainId.BSC &&
isDirectSwapCompatible(quote, optsWithDefaults, [
ERC20BridgeSource.PancakeSwap,
ERC20BridgeSource.PancakeSwapV2,
ERC20BridgeSource.BakerySwap,
ERC20BridgeSource.SushiSwap,
ERC20BridgeSource.ApeSwap,
])
) {
const source = slippedOrders[0].source;
const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<UniswapV2FillData>).fillData;
return {
calldataHexString: this._exchangeProxy
.sellToPancakeSwap(
fillData.tokenAddressPath.map((a, i) => {
if (i === 0 && isFromETH) {
return ETH_TOKEN_ADDRESS;
}
if (i === fillData.tokenAddressPath.length - 1 && isToETH) {
return ETH_TOKEN_ADDRESS;
}
return a;
}),
sellAmount,
minBuyAmount,
PANCAKE_SWAP_FORKS.indexOf(source),
)
.getABIEncodedTransactionData(),
ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
if (
this.chainId === ChainId.Mainnet &&
isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.Curve]) &&
// Curve VIP cannot currently support WETH buy/sell as the functionality needs to WITHDRAW or DEPOSIT
// into WETH prior/post the trade.
// ETH buy/sell is supported
![sellToken, buyToken].includes(NATIVE_FEE_TOKEN_BY_CHAIN_ID[ChainId.Mainnet])
) {
const fillData = slippedOrders[0].fillData as CurveFillData;
return {
calldataHexString: this._exchangeProxy
.sellToLiquidityProvider(
isFromETH ? ETH_TOKEN_ADDRESS : sellToken,
isToETH ? ETH_TOKEN_ADDRESS : buyToken,
CURVE_LIQUIDITY_PROVIDER_BY_CHAIN_ID[this.chainId],
NULL_ADDRESS,
sellAmount,
minBuyAmount,
encodeCurveLiquidityProviderData({
curveAddress: fillData.pool.poolAddress,
exchangeFunctionSelector: fillData.pool.exchangeFunctionSelector,
fromCoinIdx: new BigNumber(fillData.fromTokenIdx),
toCoinIdx: new BigNumber(fillData.toTokenIdx),
}),
)
.getABIEncodedTransactionData(),
ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
// RFQT VIP
if (
[ChainId.Mainnet, ChainId.Polygon].includes(this.chainId) &&
!isToETH &&
!isFromETH &&
quote.orders.every((o) => o.type === FillQuoteTransformerOrderType.Rfq) &&
!requiresTransformERC20(optsWithDefaults)
) {
const rfqOrdersData = quote.orders.map((o) => o.fillData as NativeRfqOrderFillData);
const fillAmountPerOrder = (() => {
// Don't think order taker amounts are clipped to actual sell amount
// (the last one might be too large) so figure them out manually.
let remaining = sellAmount;
const fillAmounts = [];
for (const o of quote.orders) {
const fillAmount = BigNumber.min(o.takerAmount, remaining);
fillAmounts.push(fillAmount);
remaining = remaining.minus(fillAmount);
}
return fillAmounts;
})();
const callData =
quote.orders.length === 1
? this._exchangeProxy
.fillRfqOrder(rfqOrdersData[0].order, rfqOrdersData[0].signature, fillAmountPerOrder[0])
.getABIEncodedTransactionData()
: this._exchangeProxy
.batchFillRfqOrders(
rfqOrdersData.map((d) => d.order),
rfqOrdersData.map((d) => d.signature),
fillAmountPerOrder,
true,
)
.getABIEncodedTransactionData();
return {
calldataHexString: callData,
ethAmount: ZERO_AMOUNT,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
// OTC orders
// if we have more than one otc order we want to batch fill them through multiplex
if (
[ChainId.Mainnet, ChainId.PolygonMumbai].includes(this.chainId) && // @todo goerli and polygon?
quote.orders.every((o) => o.type === FillQuoteTransformerOrderType.Otc) &&
!requiresTransformERC20(optsWithDefaults) &&
quote.orders.length === 1
) {
const otcOrdersData = quote.orders.map((o) => o.fillData as NativeOtcOrderFillData);
let callData;
// if the otc orders takerToken is the native asset
if (isFromETH) {
callData = this._exchangeProxy
.fillOtcOrderWithEth(otcOrdersData[0].order, otcOrdersData[0].signature)
.getABIEncodedTransactionData();
}
// if the otc orders makerToken is the native asset
else if (isToETH) {
callData = this._exchangeProxy
.fillOtcOrderForEth(otcOrdersData[0].order, otcOrdersData[0].signature, sellAmount)
.getABIEncodedTransactionData();
} else {
// if the otc order contains 2 erc20 tokens
callData = this._exchangeProxy
.fillOtcOrder(otcOrdersData[0].order, otcOrdersData[0].signature, sellAmount)
.getABIEncodedTransactionData();
}
return {
calldataHexString: callData,
ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
if (this.chainId === ChainId.Mainnet && isMultiplexBatchFillCompatible(quote, optsWithDefaults)) {
return {
calldataHexString: this._encodeMultiplexBatchFillCalldata(
{ ...quote, orders: slippedOrders },
optsWithDefaults,
),
ethAmount,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
if (this.chainId === ChainId.Mainnet && isMultiplexMultiHopFillCompatible(quote, optsWithDefaults)) {
return {
calldataHexString: this._encodeMultiplexMultiHopFillCalldata(
{ ...quote, orders: slippedOrders },
optsWithDefaults,
),
ethAmount,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead: ZERO_AMOUNT,
};
}
// Build up the transforms.
const transforms = [];
// Create a WETH wrapper if coming from ETH.
// Don't add the wethTransformer to CELO. There is no wrap/unwrap logic for CELO.
if (isFromETH && this.chainId !== ChainId.Celo) {
transforms.push({
deploymentNonce: this.transformerNonces.wethTransformer,
data: encodeWethTransformerData({
token: ETH_TOKEN_ADDRESS,
amount: shouldSellEntireBalance ? MAX_UINT256 : sellAmount,
}),
});
}
// If it's two hop we have an intermediate token this is needed to encode the individual FQT
// and we also want to ensure no dust amount is left in the flash wallet
const intermediateToken = quote.isTwoHop ? slippedOrders[0].makerToken : NULL_ADDRESS;
// This transformer will fill the quote.
if (quote.isTwoHop) {
const [firstHopOrder, secondHopOrder] = slippedOrders;
transforms.push({
deploymentNonce: this.transformerNonces.fillQuoteTransformer,
data: encodeFillQuoteTransformerData({
side: FillQuoteTransformerSide.Sell,
sellToken,
buyToken: intermediateToken,
...getFQTTransformerDataFromOptimizedOrders([firstHopOrder]),
refundReceiver: refundReceiver || NULL_ADDRESS,
fillAmount: shouldSellEntireBalance ? MAX_UINT256 : firstHopOrder.takerAmount,
}),
});
transforms.push({
deploymentNonce: this.transformerNonces.fillQuoteTransformer,
data: encodeFillQuoteTransformerData({
side: FillQuoteTransformerSide.Sell,
buyToken,
sellToken: intermediateToken,
...getFQTTransformerDataFromOptimizedOrders([secondHopOrder]),
refundReceiver: refundReceiver || NULL_ADDRESS,
fillAmount: MAX_UINT256,
}),
});
} else {
const fillAmount = isBuyQuote(quote) ? quote.makerTokenFillAmount : quote.takerTokenFillAmount;
transforms.push({
deploymentNonce: this.transformerNonces.fillQuoteTransformer,
data: encodeFillQuoteTransformerData({
side: isBuyQuote(quote) ? FillQuoteTransformerSide.Buy : FillQuoteTransformerSide.Sell,
sellToken,
buyToken,
...getFQTTransformerDataFromOptimizedOrders(slippedOrders),
refundReceiver: refundReceiver || NULL_ADDRESS,
fillAmount: !isBuyQuote(quote) && shouldSellEntireBalance ? MAX_UINT256 : fillAmount,
}),
});
}
// Create a WETH unwrapper if going to ETH.
// Dont add the wethTransformer on CELO. There is no wrap/unwrap logic for CELO.
if (isToETH && this.chainId !== ChainId.Celo) {
transforms.push({
deploymentNonce: this.transformerNonces.wethTransformer,
data: encodeWethTransformerData({
token: NATIVE_FEE_TOKEN_BY_CHAIN_ID[this.chainId],
amount: MAX_UINT256,
}),
});
}
const { feeType, buyTokenFeeAmount, sellTokenFeeAmount, recipient: feeRecipient } = affiliateFee;
let gasOverhead = ZERO_AMOUNT;
if (feeType === AffiliateFeeType.PositiveSlippageFee && feeRecipient !== NULL_ADDRESS) {
// bestCaseAmountWithSurplus is used to cover gas cost of sending positive slipapge fee to fee recipient
// this helps avoid sending dust amounts which are not worth the gas cost to transfer
let bestCaseAmountWithSurplus = quote.bestCaseQuoteInfo.makerAmount
.plus(
POSITIVE_SLIPPAGE_FEE_TRANSFORMER_GAS.multipliedBy(quote.gasPrice).multipliedBy(
quote.makerAmountPerEth,
),
)
.integerValue();
// In the event makerAmountPerEth is unknown, we only allow for positive slippage which is greater than
// the best case amount
bestCaseAmountWithSurplus = BigNumber.max(bestCaseAmountWithSurplus, quote.bestCaseQuoteInfo.makerAmount);
transforms.push({
deploymentNonce: this.transformerNonces.positiveSlippageFeeTransformer,
data: encodePositiveSlippageFeeTransformerData({
token: isToETH ? ETH_TOKEN_ADDRESS : buyToken,
bestCaseAmount: BigNumber.max(bestCaseAmountWithSurplus, quote.bestCaseQuoteInfo.makerAmount),
recipient: feeRecipient,
}),
});
// This may not be visible at eth_estimateGas time, so we explicitly add overhead
gasOverhead = POSITIVE_SLIPPAGE_FEE_TRANSFORMER_GAS;
} else if (feeType === AffiliateFeeType.PercentageFee && feeRecipient !== NULL_ADDRESS) {
// This transformer pays affiliate fees.
if (buyTokenFeeAmount.isGreaterThan(0)) {
transforms.push({
deploymentNonce: this.transformerNonces.affiliateFeeTransformer,
data: encodeAffiliateFeeTransformerData({
fees: [
{
token: isToETH ? ETH_TOKEN_ADDRESS : buyToken,
amount: buyTokenFeeAmount,
recipient: feeRecipient,
},
],
}),
});
// Adjust the minimum buy amount by the fee.
minBuyAmount = BigNumber.max(0, minBuyAmount.minus(buyTokenFeeAmount));
}
if (sellTokenFeeAmount.isGreaterThan(0)) {
throw new Error('Affiliate fees denominated in sell token are not yet supported');
}
} else if (feeType === AffiliateFeeType.GaslessFee && feeRecipient !== NULL_ADDRESS) {
if (buyTokenFeeAmount.isGreaterThan(0)) {
transforms.push({
deploymentNonce: this.transformerNonces.affiliateFeeTransformer,
data: encodeAffiliateFeeTransformerData({
fees: [
{
token: isToETH ? ETH_TOKEN_ADDRESS : buyToken,
amount: buyTokenFeeAmount,
recipient: feeRecipient,
},
],
}),
});
// Adjust the minimum buy amount by the fee.
minBuyAmount = BigNumber.max(0, minBuyAmount.minus(buyTokenFeeAmount));
}
if (sellTokenFeeAmount.isGreaterThan(0)) {
throw new Error('Affiliate fees denominated in sell token are not yet supported');
}
}
// Return any unspent sell tokens.
const payTakerTokens = [sellToken];
// Return any unspent intermediate tokens for two-hop swaps.
if (quote.isTwoHop) {
payTakerTokens.push(intermediateToken);
}
// Return any unspent ETH. If ETH is the buy token, it will
// be returned in TransformERC20Feature rather than PayTakerTransformer.
if (!isToETH) {
payTakerTokens.push(ETH_TOKEN_ADDRESS);
}
// The final transformer will send all funds to the taker.
transforms.push({
deploymentNonce: this.transformerNonces.payTakerTransformer,
data: encodePayTakerTransformerData({
tokens: payTakerTokens,
amounts: [],
}),
});
const TO_ETH_ADDRESS = this.chainId === ChainId.Celo ? this.contractAddresses.etherToken : ETH_TOKEN_ADDRESS;
const calldataHexString = this._exchangeProxy
.transformERC20(
isFromETH ? ETH_TOKEN_ADDRESS : sellToken,
isToETH ? TO_ETH_ADDRESS : buyToken,
shouldSellEntireBalance ? MAX_UINT256 : sellAmount,
minBuyAmount,
transforms,
)
.getABIEncodedTransactionData();
return {
calldataHexString,
ethAmount,
toAddress: this._exchangeProxy.address,
allowanceTarget: this._exchangeProxy.address,
gasOverhead,
};
}
public async executeSwapQuoteOrThrowAsync(
_quote: SwapQuote,
_opts: Partial<SwapQuoteExecutionOpts>,
): Promise<string> {
throw new Error('Execution not supported for Exchange Proxy quotes');
}
private _encodeMultiplexBatchFillCalldata(quote: SwapQuote, opts: ExchangeProxyContractOpts): string {
const subcalls = [];
for_loop: for (const [i, order] of quote.orders.entries()) {
switch_statement: switch (order.source) {
case ERC20BridgeSource.Native:
if (
order.type !== FillQuoteTransformerOrderType.Rfq &&
order.type !== FillQuoteTransformerOrderType.Otc
) {
// Should never happen because we check `isMultiplexBatchFillCompatible`
// before calling this function.
throw new Error('Multiplex batch fill only supported for RFQ native orders and OTC Orders');
}
if (order.type !== FillQuoteTransformerOrderType.Otc) {
subcalls.push({
id: MultiplexSubcall.Rfq,
sellAmount: order.takerAmount,
data: multiplexRfqEncoder.encode({
order: order.fillData.order,
signature: order.fillData.signature,
}),
});
} else {
subcalls.push({
id: MultiplexSubcall.Otc,
sellAmount: order.takerAmount,
data: multiplexOtcOrder.encode({
order: order.fillData.order,
signature: order.fillData.signature,
}),
});
}
break switch_statement;
case ERC20BridgeSource.UniswapV2:
case ERC20BridgeSource.SushiSwap:
subcalls.push({
id: MultiplexSubcall.UniswapV2,
sellAmount: order.takerAmount,
data: multiplexUniswapEncoder.encode({
tokens: (order.fillData as UniswapV2FillData).tokenAddressPath,
isSushi: order.source === ERC20BridgeSource.SushiSwap,
}),
});
break switch_statement;
case ERC20BridgeSource.UniswapV3: {
const fillData = (order as OptimizedMarketBridgeOrder<FinalUniswapV3FillData>).fillData;
subcalls.push({
id: MultiplexSubcall.UniswapV3,
sellAmount: order.takerAmount,
data: fillData.uniswapPath,
});
break switch_statement;
}
default: {
const fqtData = encodeFillQuoteTransformerData({
side: FillQuoteTransformerSide.Sell,
sellToken: quote.takerToken,
buyToken: quote.makerToken,
...getFQTTransformerDataFromOptimizedOrders(quote.orders.slice(i)),
refundReceiver: NULL_ADDRESS,
fillAmount: MAX_UINT256,
});
const transformations = [
{ deploymentNonce: this.transformerNonces.fillQuoteTransformer, data: fqtData },
{
deploymentNonce: this.transformerNonces.payTakerTransformer,
data: encodePayTakerTransformerData({
tokens: [quote.takerToken],
amounts: [],
}),
},
];
subcalls.push({
id: MultiplexSubcall.TransformERC20,
sellAmount: BigNumber.sum(...quote.orders.slice(i).map((o) => o.takerAmount)),
data: multiplexTransformERC20Encoder.encode({
transformations,
}),
});
break for_loop;
}
}
}
if (opts.isFromETH) {
return this._exchangeProxy
.multiplexBatchSellEthForToken(quote.makerToken, subcalls, quote.worstCaseQuoteInfo.makerAmount)
.getABIEncodedTransactionData();
} else if (opts.isToETH) {
return this._exchangeProxy
.multiplexBatchSellTokenForEth(
quote.takerToken,
subcalls,
quote.worstCaseQuoteInfo.totalTakerAmount,
quote.worstCaseQuoteInfo.makerAmount,
)
.getABIEncodedTransactionData();
} else {
return this._exchangeProxy
.multiplexBatchSellTokenForToken(
quote.takerToken,
quote.makerToken,
subcalls,
quote.worstCaseQuoteInfo.totalTakerAmount,
quote.worstCaseQuoteInfo.makerAmount,
)
.getABIEncodedTransactionData();
}
}
private _encodeMultiplexMultiHopFillCalldata(quote: SwapQuote, opts: ExchangeProxyContractOpts): string {
const subcalls = [];
const [firstHopOrder, secondHopOrder] = quote.orders;
const intermediateToken = firstHopOrder.makerToken;
const tokens = [quote.takerToken, intermediateToken, quote.makerToken];
for (const order of [firstHopOrder, secondHopOrder]) {
switch (order.source) {
case ERC20BridgeSource.UniswapV2:
case ERC20BridgeSource.SushiSwap:
subcalls.push({
id: MultiplexSubcall.UniswapV2,
data: multiplexUniswapEncoder.encode({
tokens: (order.fillData as UniswapV2FillData).tokenAddressPath,
isSushi: order.source === ERC20BridgeSource.SushiSwap,
}),
});
break;
case ERC20BridgeSource.UniswapV3:
subcalls.push({
id: MultiplexSubcall.UniswapV3,
data: (order.fillData as FinalUniswapV3FillData).uniswapPath,
});
break;
default:
// Should never happen because we check `isMultiplexMultiHopFillCompatible`
// before calling this function.
throw new Error(`Multiplex multi-hop unsupported source: ${order.source}`);
}
}
if (opts.isFromETH) {
return this._exchangeProxy
.multiplexMultiHopSellEthForToken(tokens, subcalls, quote.worstCaseQuoteInfo.makerAmount)
.getABIEncodedTransactionData();
} else if (opts.isToETH) {
return this._exchangeProxy
.multiplexMultiHopSellTokenForEth(
tokens,
subcalls,
quote.worstCaseQuoteInfo.totalTakerAmount,
quote.worstCaseQuoteInfo.makerAmount,
)
.getABIEncodedTransactionData();
} else {
return this._exchangeProxy
.multiplexMultiHopSellTokenForToken(
tokens,
subcalls,
quote.worstCaseQuoteInfo.totalTakerAmount,
quote.worstCaseQuoteInfo.makerAmount,
)
.getABIEncodedTransactionData();
}
}
}
function slipNonNativeOrders(quote: MarketSellSwapQuote | MarketBuySwapQuote): OptimizedOrder[] {
const slippage = getMaxQuoteSlippageRate(quote);
if (slippage === 0) {
return quote.orders;
}
return quote.orders.map((o) => {
if (o.source === ERC20BridgeSource.Native) {
return o;
}
return {
...o,
...(quote.type === MarketOperation.Sell
? {
makerAmount: o.makerAmount.eq(MAX_UINT256)
? MAX_UINT256
: o.makerAmount.times(1 - slippage).integerValue(BigNumber.ROUND_DOWN),
}
: {
takerAmount: o.takerAmount.eq(MAX_UINT256)
? MAX_UINT256
: o.takerAmount.times(1 + slippage).integerValue(BigNumber.ROUND_UP),
}),
};
});
}
function getMaxQuoteSlippageRate(quote: MarketBuySwapQuote | MarketSellSwapQuote): number {
return quote.worstCaseQuoteInfo.slippage;
}