-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathdecorators.py
More file actions
76 lines (60 loc) · 2.15 KB
/
decorators.py
File metadata and controls
76 lines (60 loc) · 2.15 KB
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
import functools
from typing import (
TYPE_CHECKING,
Callable,
List,
Optional,
TypeVar,
)
from typing_extensions import Concatenate, ParamSpec
from .constants import ETH_ADDRESS
from .types import AddressLike
if TYPE_CHECKING:
from .uniswap import Uniswap
T = TypeVar("T")
P = ParamSpec("P")
def check_approval(
method: Callable[Concatenate["Uniswap", P], T]
) -> Callable[Concatenate["Uniswap", P], T]:
"""Decorator to check if user is approved for a token. It approves them if they
need to be approved."""
@functools.wraps(method)
def approved(self: "Uniswap", *args: P.args, **kwargs: P.kwargs) -> T:
# Check to see if the first token is actually ETH
token: Optional[AddressLike] = args[0] if args[0] != ETH_ADDRESS else None # type: ignore
token_two = None
# Check second token, if needed
if method.__name__ == "make_trade" or method.__name__ == "make_trade_output":
token_two = args[1] if args[1] != ETH_ADDRESS else None
# Approve both tokens, if needed
if token:
is_approved = self._is_approved(token)
# logger.warning(f"Approved? {token}: {is_approved}")
if not is_approved:
self.approve(token)
return method(self, *args, **kwargs)
return approved
def supports(
versions: List[int],
) -> Callable[
[Callable[Concatenate["Uniswap", P], T]], Callable[Concatenate["Uniswap", P], T]
]:
def g(
f: Callable[Concatenate["Uniswap", P], T]
) -> Callable[Concatenate["Uniswap", P], T]:
if f.__doc__ is None:
f.__doc__ = ""
f.__doc__ += """\n\n
Supports Uniswap
""" + ", ".join(
"v" + str(ver) for ver in versions
)
@functools.wraps(f)
def check_version(self: "Uniswap", *args: P.args, **kwargs: P.kwargs) -> T:
if self.version not in versions:
raise Exception(
f"Function {f.__name__} does not support version {self.version} of Uniswap passed to constructor"
)
return f(self, *args, **kwargs)
return check_version
return g