-
Notifications
You must be signed in to change notification settings - Fork 366
/
uniswap.py
1991 lines (1782 loc) 路 75.4 KB
/
uniswap.py
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import logging
import os
import time
from collections import namedtuple
from typing import (
Any,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
)
from eth_typing.evm import Address, ChecksumAddress
from hexbytes import HexBytes
from web3 import Web3
from web3._utils.abi import map_abi_data
from web3._utils.normalizers import BASE_RETURN_NORMALIZERS
from web3.contract import Contract
from web3.contract.contract import ContractFunction
from web3.exceptions import BadFunctionCallOutput, ContractLogicError
from web3.types import (
Nonce,
TxParams,
TxReceipt,
Wei,
)
from .constants import (
ETH_ADDRESS,
MAX_TICK,
MAX_UINT_128,
MIN_TICK,
WETH9_ADDRESS,
_factory_contract_addresses_v1,
_factory_contract_addresses_v2,
_netid_to_name,
_router_contract_addresses_v2,
_tick_bitmap_range,
_tick_spacing,
)
from .decorators import check_approval, supports
from .exceptions import InsufficientBalance, InvalidToken
from .fee import validate_fee_tier
from .token import ERC20Token
from .types import AddressLike
from .util import (
_addr_to_str,
_get_eth_simple_cache_middleware,
_load_contract,
_load_contract_erc20,
_str_to_addr,
_validate_address,
chunks,
encode_sqrt_ratioX96,
is_same_address,
nearest_tick,
realised_fee_percentage,
)
logger = logging.getLogger(__name__)
class Uniswap:
"""
Wrapper around Uniswap contracts.
"""
address: AddressLike
version: int
w3: Web3
netid: int
netname: str
default_slippage: float
use_estimate_gas: bool
def __init__(
self,
address: Union[AddressLike, str, None],
private_key: Optional[str],
provider: Optional[str] = None,
web3: Optional[Web3] = None,
version: int = 1,
default_slippage: float = 0.01,
use_estimate_gas: bool = True,
# use_eip1559: bool = True,
factory_contract_addr: Optional[str] = None,
router_contract_addr: Optional[str] = None,
enable_caching: bool = False,
) -> None:
"""
:param address: The public address of the ETH wallet to use.
:param private_key: The private key of the ETH wallet to use.
:param provider: Can be optionally set to a Web3 provider URI. If none set, will fall back to the PROVIDER environment variable, or web3 if set.
:param web3: Can be optionally set to a custom Web3 instance.
:param version: Which version of the Uniswap contracts to use.
:param default_slippage: Default slippage for a trade, as a float (0.01 is 1%). WARNING: slippage is untested.
:param factory_contract_addr: Can be optionally set to override the address of the factory contract.
:param router_contract_addr: Can be optionally set to override the address of the router contract (v2 only).
:param enable_caching: Optionally enables middleware caching RPC method calls.
"""
self.address = _str_to_addr(
address or "0x0000000000000000000000000000000000000000"
)
self.private_key = (
private_key
or "0x0000000000000000000000000000000000000000000000000000000000000000"
)
self.version = version
if self.version not in [1, 2, 3]:
raise Exception(
f"Invalid version '{self.version}', only 1, 2 or 3 supported"
) # pragma: no cover
# TODO: Write tests for slippage
self.default_slippage = default_slippage
self.use_estimate_gas = use_estimate_gas
if web3:
self.w3 = web3
else:
# Initialize web3. Extra provider for testing.
if not provider:
provider = os.environ["PROVIDER"]
self.w3 = Web3(Web3.HTTPProvider(provider, request_kwargs={"timeout": 60}))
if enable_caching:
self.w3.middleware_onion.inject(_get_eth_simple_cache_middleware(), layer=0)
self.netid = int(self.w3.net.version)
if self.netid in _netid_to_name:
self.netname = _netid_to_name[self.netid]
else:
raise Exception(f"Unknown netid: {self.netid}") # pragma: no cover
logger.info(f"Using {self.w3} ('{self.netname}', netid: {self.netid})")
self.last_nonce: Nonce = self.w3.eth.get_transaction_count(self.address)
# This code automatically approves you for trading on the exchange.
# max_approval is to allow the contract to exchange on your behalf.
# max_approval_check checks that current approval is above a reasonable number
# The program cannot check for max_approval each time because it decreases
# with each trade.
max_approval_hex = f"0x{64 * 'f'}"
self.max_approval_int = int(max_approval_hex, 16)
max_approval_check_hex = f"0x{15 * '0'}{49 * 'f'}"
self.max_approval_check_int = int(max_approval_check_hex, 16)
if self.version == 1:
if factory_contract_addr is None:
factory_contract_addr = _factory_contract_addresses_v1[self.netname]
self.factory_contract = _load_contract(
self.w3,
abi_name="uniswap-v1/factory",
address=_str_to_addr(factory_contract_addr),
)
elif self.version == 2:
if router_contract_addr is None:
router_contract_addr = _router_contract_addresses_v2[self.netname]
self.router_address: AddressLike = _str_to_addr(router_contract_addr)
if factory_contract_addr is None:
factory_contract_addr = _factory_contract_addresses_v2[self.netname]
self.factory_contract = _load_contract(
self.w3,
abi_name="uniswap-v2/factory",
address=_str_to_addr(factory_contract_addr),
)
# Documented here: https://uniswap.org/docs/v2/smart-contracts/router02/
self.router = _load_contract(
self.w3,
abi_name="uniswap-v2/router02",
address=self.router_address,
)
elif self.version == 3:
# https://github.com/Uniswap/uniswap-v3-periphery/blob/main/deploys.md
factory_contract_address = _str_to_addr(
"0x1F98431c8aD98523631AE4a59f267346ea31F984"
)
self.factory_contract = _load_contract(
self.w3, abi_name="uniswap-v3/factory", address=factory_contract_address
)
quoter_addr = _str_to_addr("0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6")
self.router_address = _str_to_addr(
"0xE592427A0AEce92De3Edee1F18E0157C05861564"
)
self.quoter = _load_contract(
self.w3, abi_name="uniswap-v3/quoter", address=quoter_addr
)
self.router = _load_contract(
self.w3, abi_name="uniswap-v3/router", address=self.router_address
)
self.positionManager_addr = _str_to_addr(
"0xC36442b4a4522E871399CD717aBDD847Ab11FE88"
)
self.nonFungiblePositionManager = _load_contract(
self.w3,
abi_name="uniswap-v3/nonFungiblePositionManager",
address=self.positionManager_addr,
)
if self.netname == "arbitrum":
multicall2_addr = _str_to_addr(
"0x50075F151ABC5B6B448b1272A0a1cFb5CFA25828"
)
else:
multicall2_addr = _str_to_addr(
"0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696"
)
self.multicall2 = _load_contract(
self.w3, abi_name="uniswap-v3/multicall", address=multicall2_addr
)
else:
raise Exception(
f"Invalid version '{self.version}', only 1, 2 or 3 supported"
)
if hasattr(self, "factory_contract"):
logger.info(f"Using factory contract: {self.factory_contract}")
# ------ Market --------------------------------------------------------------------
def get_price_input(
self,
token0: AddressLike, # input token
token1: AddressLike, # output token
qty: int,
fee: Optional[int] = None,
route: Optional[List[AddressLike]] = None,
) -> int:
"""Given `qty` amount of the input `token0`, returns the maximum output amount of output `token1`."""
fee = validate_fee_tier(fee=fee, version=self.version)
if token0 == ETH_ADDRESS:
return self._get_eth_token_input_price(token1, Wei(qty), fee)
elif token1 == ETH_ADDRESS:
return self._get_token_eth_input_price(token0, qty, fee)
else:
return self._get_token_token_input_price(token0, token1, qty, fee, route)
def get_price_output(
self,
token0: AddressLike,
token1: AddressLike,
qty: int,
fee: Optional[int] = None,
route: Optional[List[AddressLike]] = None,
) -> int:
"""Returns the minimum amount of `token0` required to buy `qty` amount of `token1`."""
fee = validate_fee_tier(fee=fee, version=self.version)
if is_same_address(token0, ETH_ADDRESS):
return self._get_eth_token_output_price(token1, qty, fee)
elif is_same_address(token1, ETH_ADDRESS):
return self._get_token_eth_output_price(token0, Wei(qty), fee)
else:
return self._get_token_token_output_price(token0, token1, qty, fee, route)
def _get_eth_token_input_price(
self,
token: AddressLike, # output token
qty: Wei,
fee: int,
) -> Wei:
"""Public price (i.e. amount of output token received) for ETH to token trades with an exact input."""
if self.version == 1:
ex = self._exchange_contract(token)
price: Wei = ex.functions.getEthToTokenInputPrice(qty).call()
elif self.version == 2:
price = self.router.functions.getAmountsOut(
qty, [self.get_weth_address(), token]
).call()[-1]
elif self.version == 3:
price = self._get_token_token_input_price(
self.get_weth_address(), token, qty, fee=fee
) # type: ignore
else:
raise ValueError # pragma: no cover
return price
def _get_token_eth_input_price(
self,
token: AddressLike, # input token
qty: int,
fee: int,
) -> int:
"""Public price (i.e. amount of ETH received) for token to ETH trades with an exact input."""
if self.version == 1:
ex = self._exchange_contract(token)
price: int = ex.functions.getTokenToEthInputPrice(qty).call()
elif self.version == 2:
price = self.router.functions.getAmountsOut(
qty, [token, self.get_weth_address()]
).call()[-1]
elif self.version == 3:
price = self._get_token_token_input_price(
token, self.get_weth_address(), qty, fee=fee
)
else:
raise ValueError # pragma: no cover
return price
def _get_token_token_input_price(
self,
token0: AddressLike, # input token
token1: AddressLike, # output token
qty: int,
fee: int,
route: Optional[List[AddressLike]] = None,
) -> int:
"""
Public price (i.e. amount of output token received) for token to token trades with an exact input.
:param fee: (v3 only) The pool's fee in hundredths of a bip, i.e. 1e-6 (3000 is 0.3%)
"""
if route is None:
if self.version == 2:
# If one of the tokens are WETH, delegate to appropriate call.
# See: https://github.com/shanefontaine/uniswap-python/issues/22
if is_same_address(token0, self.get_weth_address()):
return int(self._get_eth_token_input_price(token1, Wei(qty), fee))
elif is_same_address(token1, self.get_weth_address()):
return int(self._get_token_eth_input_price(token0, qty, fee))
route = [token0, self.get_weth_address(), token1]
logger.warning(f"No route specified, assuming route: {route}")
if self.version == 2:
price: int = self.router.functions.getAmountsOut(qty, route).call()[-1]
elif self.version == 3:
if route:
# NOTE: to support custom routes we need to support the Path data encoding: https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/Path.sol
# result: tuple = self.quoter.functions.quoteExactInput(route, qty).call()
raise Exception("custom route not yet supported for v3")
# FIXME: How to calculate this properly? See https://docs.uniswap.org/reference/libraries/SqrtPriceMath
sqrtPriceLimitX96 = 0
price = self.quoter.functions.quoteExactInputSingle(
token0, token1, fee, qty, sqrtPriceLimitX96
).call()
else:
raise ValueError("function not supported for this version of Uniswap")
return price
def _get_eth_token_output_price(
self,
token: AddressLike, # output token
qty: int,
fee: Optional[int] = None,
) -> Wei:
"""Public price (i.e. amount of ETH needed) for ETH to token trades with an exact output."""
fee = validate_fee_tier(fee=fee, version=self.version)
if self.version == 1:
ex = self._exchange_contract(token)
price: Wei = ex.functions.getEthToTokenOutputPrice(qty).call()
elif self.version == 2:
route = [self.get_weth_address(), token]
price = self.router.functions.getAmountsIn(qty, route).call()[0]
elif self.version == 3:
price = Wei(
self._get_token_token_output_price(
self.get_weth_address(), token, qty, fee=fee
)
)
else:
raise ValueError # pragma: no cover
return price
def _get_token_eth_output_price(
self, token: AddressLike, qty: Wei, fee: Optional[int] = None # input token
) -> int:
"""Public price (i.e. amount of input token needed) for token to ETH trades with an exact output."""
fee = validate_fee_tier(fee=fee, version=self.version)
if self.version == 1:
ex = self._exchange_contract(token)
price: int = ex.functions.getTokenToEthOutputPrice(qty).call()
elif self.version == 2:
route = [token, self.get_weth_address()]
price = self.router.functions.getAmountsIn(qty, route).call()[0]
elif self.version == 3:
price = self._get_token_token_output_price(
token, self.get_weth_address(), qty, fee=fee
)
else:
raise ValueError # pragma: no cover
return price
@supports([2, 3])
def _get_token_token_output_price(
self,
token0: AddressLike, # input token
token1: AddressLike, # output token
qty: int,
fee: Optional[int] = None,
route: Optional[List[AddressLike]] = None,
) -> int:
"""
Public price (i.e. amount of input token needed) for token to token trades with an exact output.
:param fee: (v3 only) The pool's fee in hundredths of a bip, i.e. 1e-6 (3000 is 0.3%)
"""
fee = validate_fee_tier(fee=fee, version=self.version)
if not route:
if self.version == 2:
# If one of the tokens are WETH, delegate to appropriate call.
# See: https://github.com/shanefontaine/uniswap-python/issues/22
if is_same_address(token0, self.get_weth_address()):
return int(self._get_eth_token_output_price(token1, qty, fee))
elif is_same_address(token1, self.get_weth_address()):
return int(self._get_token_eth_output_price(token0, Wei(qty), fee))
route = [token0, self.get_weth_address(), token1]
logger.warning(f"No route specified, assuming route: {route}")
if self.version == 2:
price: int = self.router.functions.getAmountsIn(qty, route).call()[0]
elif self.version == 3:
if route:
# NOTE: to support custom routes we need to support the Path data encoding: https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/Path.sol
# result: tuple = self.quoter.functions.quoteExactOutput(route, qty).call()
raise Exception("custom route not yet supported for v3")
# FIXME: How to calculate this properly?
# - https://docs.uniswap.org/reference/libraries/SqrtPriceMath
# - https://github.com/Uniswap/uniswap-v3-sdk/blob/main/src/swapRouter.ts
sqrtPriceLimitX96 = 0
price = self.quoter.functions.quoteExactOutputSingle(
token0, token1, fee, qty, sqrtPriceLimitX96
).call()
else:
raise ValueError # pragma: no cover
return price
# ------ Make Trade ----------------------------------------------------------------
@check_approval
def make_trade(
self,
input_token: AddressLike,
output_token: AddressLike,
qty: Union[int, Wei],
recipient: Optional[AddressLike] = None,
fee: Optional[int] = None,
slippage: Optional[float] = None,
fee_on_transfer: bool = False,
) -> HexBytes:
"""Make a trade by defining the qty of the input token."""
if not isinstance(qty, int):
raise TypeError("swapped quantity must be an integer")
fee = validate_fee_tier(fee=fee, version=self.version)
if slippage is None:
slippage = self.default_slippage
if input_token == output_token:
raise ValueError
if input_token == ETH_ADDRESS:
return self._eth_to_token_swap_input(
output_token, Wei(qty), recipient, fee, slippage, fee_on_transfer
)
elif output_token == ETH_ADDRESS:
return self._token_to_eth_swap_input(
input_token, qty, recipient, fee, slippage, fee_on_transfer
)
else:
return self._token_to_token_swap_input(
input_token,
output_token,
qty,
recipient,
fee,
slippage,
fee_on_transfer,
)
@check_approval
def make_trade_output(
self,
input_token: AddressLike,
output_token: AddressLike,
qty: Union[int, Wei],
recipient: Optional[AddressLike] = None,
fee: Optional[int] = None,
slippage: Optional[float] = None,
) -> HexBytes:
"""Make a trade by defining the qty of the output token."""
fee = validate_fee_tier(fee=fee, version=self.version)
if slippage is None:
slippage = self.default_slippage
if input_token == output_token:
raise ValueError
if input_token == ETH_ADDRESS:
balance = self.get_eth_balance()
need = self._get_eth_token_output_price(output_token, qty, fee)
if balance < need:
raise InsufficientBalance(balance, need)
return self._eth_to_token_swap_output(
output_token, qty, recipient, fee, slippage
)
elif output_token == ETH_ADDRESS:
return self._token_to_eth_swap_output(
input_token, Wei(qty), recipient, fee, slippage
)
else:
return self._token_to_token_swap_output(
input_token, output_token, qty, recipient, fee, slippage
)
def _eth_to_token_swap_input(
self,
output_token: AddressLike,
qty: Wei,
recipient: Optional[AddressLike],
fee: int,
slippage: float,
fee_on_transfer: bool = False,
) -> HexBytes:
"""Convert ETH to tokens given an input amount."""
if output_token == ETH_ADDRESS:
raise ValueError
eth_balance = self.get_eth_balance()
if qty > eth_balance:
raise InsufficientBalance(eth_balance, qty)
if self.version == 1:
token_funcs = self._exchange_contract(output_token).functions
tx_params = self._get_tx_params(qty)
func_params: List[Any] = [qty, self._deadline()]
if not recipient:
function = token_funcs.ethToTokenSwapInput(*func_params)
else:
func_params.append(recipient)
function = token_funcs.ethToTokenTransferInput(*func_params)
return self._build_and_send_tx(function, tx_params)
elif self.version == 2:
if recipient is None:
recipient = self.address
amount_out_min = int(
(1 - slippage) * self._get_eth_token_input_price(output_token, qty, fee)
)
if fee_on_transfer:
func = (
self.router.functions.swapExactETHForTokensSupportingFeeOnTransferTokens
)
else:
func = self.router.functions.swapExactETHForTokens
return self._build_and_send_tx(
func(
amount_out_min,
[self.get_weth_address(), output_token],
recipient,
self._deadline(),
),
self._get_tx_params(qty),
)
elif self.version == 3:
if recipient is None:
recipient = self.address
if fee_on_transfer:
raise Exception("fee on transfer not supported by Uniswap v3")
min_tokens_bought = int(
(1 - slippage)
* self._get_eth_token_input_price(output_token, qty, fee=fee)
)
sqrtPriceLimitX96 = 0
return self._build_and_send_tx(
self.router.functions.exactInputSingle(
{
"tokenIn": self.get_weth_address(),
"tokenOut": output_token,
"fee": fee,
"recipient": recipient,
"deadline": self._deadline(),
"amountIn": qty,
"amountOutMinimum": min_tokens_bought,
"sqrtPriceLimitX96": sqrtPriceLimitX96,
}
),
self._get_tx_params(value=qty),
)
else:
raise ValueError # pragma: no cover
def _token_to_eth_swap_input(
self,
input_token: AddressLike,
qty: int,
recipient: Optional[AddressLike],
fee: int,
slippage: float,
fee_on_transfer: bool = False,
) -> HexBytes:
"""Convert tokens to ETH given an input amount."""
if input_token == ETH_ADDRESS:
raise ValueError
# Balance check
input_balance = self.get_token_balance(input_token)
if qty > input_balance:
raise InsufficientBalance(input_balance, qty)
if self.version == 1:
token_funcs = self._exchange_contract(input_token).functions
func_params: List[Any] = [qty, 1, self._deadline()]
if not recipient:
function = token_funcs.tokenToEthSwapInput(*func_params)
else:
func_params.append(recipient)
function = token_funcs.tokenToEthTransferInput(*func_params)
return self._build_and_send_tx(function)
elif self.version == 2:
if recipient is None:
recipient = self.address
amount_out_min = int(
(1 - slippage) * self._get_token_eth_input_price(input_token, qty, fee)
)
if fee_on_transfer:
func = (
self.router.functions.swapExactTokensForETHSupportingFeeOnTransferTokens
)
else:
func = self.router.functions.swapExactTokensForETH
return self._build_and_send_tx(
func(
qty,
amount_out_min,
[input_token, self.get_weth_address()],
recipient,
self._deadline(),
),
)
elif self.version == 3:
if recipient is None:
recipient = self.address
if fee_on_transfer:
raise Exception("fee on transfer not supported by Uniswap v3")
output_token = self.get_weth_address()
min_tokens_bought = int(
(1 - slippage)
* self._get_token_eth_input_price(input_token, qty, fee=fee)
)
sqrtPriceLimitX96 = 0
swap_data = self.router.encodeABI(
fn_name="exactInputSingle",
args=[
(
input_token,
output_token,
fee,
ETH_ADDRESS,
self._deadline(),
qty,
min_tokens_bought,
sqrtPriceLimitX96,
)
],
)
unwrap_data = self.router.encodeABI(
fn_name="unwrapWETH9", args=[min_tokens_bought, recipient]
)
# Multicall
return self._build_and_send_tx(
self.router.functions.multicall([swap_data, unwrap_data]),
self._get_tx_params(),
)
else:
raise ValueError # pragma: no cover
def _token_to_token_swap_input(
self,
input_token: AddressLike,
output_token: AddressLike,
qty: int,
recipient: Optional[AddressLike],
fee: int,
slippage: float,
fee_on_transfer: bool = False,
) -> HexBytes:
"""Convert tokens to tokens given an input amount."""
# Balance check
input_balance = self.get_token_balance(input_token)
if qty > input_balance:
raise InsufficientBalance(input_balance, qty)
if recipient is None:
recipient = self.address
if input_token == ETH_ADDRESS:
raise ValueError
elif output_token == ETH_ADDRESS:
raise ValueError
if self.version == 1:
token_funcs = self._exchange_contract(input_token).functions
# TODO: This might not be correct
min_tokens_bought, min_eth_bought = self._calculate_max_output_token(
input_token, qty, output_token
)
func_params = [
qty,
min_tokens_bought,
min_eth_bought,
self._deadline(),
output_token,
]
if not recipient:
function = token_funcs.tokenToTokenSwapInput(*func_params)
else:
func_params.insert(len(func_params) - 1, recipient)
function = token_funcs.tokenToTokenTransferInput(*func_params)
return self._build_and_send_tx(function)
elif self.version == 2:
min_tokens_bought = int(
(1 - slippage)
* self._get_token_token_input_price(
input_token, output_token, qty, fee=fee
)
)
if fee_on_transfer:
func = (
self.router.functions.swapExactTokensForTokensSupportingFeeOnTransferTokens
)
else:
func = self.router.functions.swapExactTokensForTokens
return self._build_and_send_tx(
func(
qty,
min_tokens_bought,
[input_token, self.get_weth_address(), output_token],
recipient,
self._deadline(),
),
)
elif self.version == 3:
if fee_on_transfer:
raise Exception("fee on transfer not supported by Uniswap v3")
min_tokens_bought = int(
(1 - slippage)
* self._get_token_token_input_price(
input_token, output_token, qty, fee=fee
)
)
sqrtPriceLimitX96 = 0
return self._build_and_send_tx(
self.router.functions.exactInputSingle(
{
"tokenIn": input_token,
"tokenOut": output_token,
"fee": fee,
"recipient": recipient,
"deadline": self._deadline(),
"amountIn": qty,
"amountOutMinimum": min_tokens_bought,
"sqrtPriceLimitX96": sqrtPriceLimitX96,
}
),
self._get_tx_params(),
)
else:
raise ValueError # pragma: no cover
def _eth_to_token_swap_output(
self,
output_token: AddressLike,
qty: int,
recipient: Optional[AddressLike],
fee: int,
slippage: float,
) -> HexBytes:
"""Convert ETH to tokens given an output amount."""
if output_token == ETH_ADDRESS:
raise ValueError
# Balance check
eth_balance = self.get_eth_balance()
cost = self._get_eth_token_output_price(output_token, qty, fee)
amount_in_max = Wei(int((1 + slippage) * cost))
# We check balance against amount_in_max rather than cost to be conservative
if amount_in_max > eth_balance:
raise InsufficientBalance(eth_balance, amount_in_max)
if self.version == 1:
token_funcs = self._exchange_contract(output_token).functions
eth_qty = self._get_eth_token_output_price(output_token, qty)
tx_params = self._get_tx_params(eth_qty)
func_params: List[Any] = [qty, self._deadline()]
if not recipient:
function = token_funcs.ethToTokenSwapOutput(*func_params)
else:
func_params.append(recipient)
function = token_funcs.ethToTokenTransferOutput(*func_params)
return self._build_and_send_tx(function, tx_params)
elif self.version == 2:
if recipient is None:
recipient = self.address
eth_qty = int(
(1 + slippage)
* self._get_eth_token_output_price(output_token, qty, fee)
) # type: ignore
return self._build_and_send_tx(
self.router.functions.swapETHForExactTokens(
qty,
[self.get_weth_address(), output_token],
recipient,
self._deadline(),
),
self._get_tx_params(eth_qty),
)
elif self.version == 3:
if recipient is None:
recipient = self.address
sqrtPriceLimitX96 = 0
swap_data = self.router.encodeABI(
fn_name="exactOutputSingle",
args=[
(
self.get_weth_address(),
output_token,
fee,
recipient,
self._deadline(),
qty,
amount_in_max,
sqrtPriceLimitX96,
)
],
)
refund_data = self.router.encodeABI(fn_name="refundETH", args=None)
# Multicall
return self._build_and_send_tx(
self.router.functions.multicall([swap_data, refund_data]),
self._get_tx_params(value=amount_in_max),
)
else:
raise ValueError
def _token_to_eth_swap_output(
self,
input_token: AddressLike,
qty: Wei,
recipient: Optional[AddressLike],
fee: int,
slippage: float,
) -> HexBytes:
"""Convert tokens to ETH given an output amount."""
if input_token == ETH_ADDRESS:
raise ValueError
# Balance check
input_balance = self.get_token_balance(input_token)
cost = self._get_token_eth_output_price(input_token, qty, fee)
amount_in_max = int((1 + slippage) * cost)
# We check balance against amount_in_max rather than cost to be conservative
if amount_in_max > input_balance:
raise InsufficientBalance(input_balance, amount_in_max)
if self.version == 1:
# From https://uniswap.org/docs/v1/frontend-integration/trade-tokens/
# Is all this really necessary? Can't we just use `cost` for max_tokens?
outputAmount = qty
inputReserve = self.get_ex_token_balance(input_token)
outputReserve = self.get_ex_eth_balance(input_token)
numerator = outputAmount * inputReserve * 1000
denominator = (outputReserve - outputAmount) * 997
inputAmount = numerator / denominator + 1
max_tokens = int((1 + slippage) * inputAmount)
ex = self._exchange_contract(input_token)
func_params: List[Any] = [qty, max_tokens, self._deadline()]
if not recipient:
function = ex.functions.tokenToEthSwapOutput(*func_params)
else:
func_params.append(recipient)
function = ex.functions.tokenToEthTransferOutput(*func_params)
return self._build_and_send_tx(function)
elif self.version == 2:
if recipient is None:
recipient = self.address
max_tokens = int((1 + slippage) * cost)
return self._build_and_send_tx(
self.router.functions.swapTokensForExactETH(
qty,
max_tokens,
[input_token, self.get_weth_address()],
recipient,
self._deadline(),
),
)
elif self.version == 3:
if recipient is None:
recipient = self.address
sqrtPriceLimitX96 = 0
swap_data = self.router.encodeABI(
fn_name="exactOutputSingle",
args=[
(
input_token,
self.get_weth_address(),
fee,
ETH_ADDRESS,
self._deadline(),
qty,
amount_in_max,
sqrtPriceLimitX96,
)
],
)
unwrap_data = self.router.encodeABI(
fn_name="unwrapWETH9", args=[qty, recipient]
)
# Multicall
return self._build_and_send_tx(
self.router.functions.multicall([swap_data, unwrap_data]),
self._get_tx_params(),
)
else:
raise ValueError
def _token_to_token_swap_output(
self,
input_token: AddressLike,
output_token: AddressLike,
qty: int,
recipient: Optional[AddressLike],
fee: int,
slippage: float,
) -> HexBytes:
"""Convert tokens to tokens given an output amount.
:param fee: TODO
"""
if input_token == ETH_ADDRESS:
raise ValueError
elif output_token == ETH_ADDRESS:
raise ValueError
# Balance check
input_balance = self.get_token_balance(input_token)
cost = self._get_token_token_output_price(input_token, output_token, qty, fee)
amount_in_max = int((1 + slippage) * cost)
if (
amount_in_max > input_balance
): # We check balance against amount_in_max rather than cost to be conservative
raise InsufficientBalance(input_balance, amount_in_max)
if self.version == 1:
token_funcs = self._exchange_contract(input_token).functions
max_tokens_sold, max_eth_sold = self._calculate_max_input_token(
input_token, qty, output_token
)
tx_params = self._get_tx_params()
func_params = [
qty,
max_tokens_sold,
max_eth_sold,
self._deadline(),
output_token,
]
if not recipient:
function = token_funcs.tokenToTokenSwapOutput(*func_params)
else:
func_params.insert(len(func_params) - 1, recipient)
function = token_funcs.tokenToTokenTransferOutput(*func_params)
return self._build_and_send_tx(function, tx_params)
elif self.version == 2: