-
Notifications
You must be signed in to change notification settings - Fork 2
/
uniswap.py
133 lines (84 loc) · 2.57 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
"""# Uniswap Module
Uniswap style Constant Function Market Maker functions for liquidity provision and token trading.
"""
# Liquidity Provision
def add_liquidity(reserve_balance, supply_balance, voucher_balance, tokens, value):
"""
Example:
new_reserve = (1 + alpha) * reserve_balance
new_supply = (1 + alpha) * supply_balance
new_vouchers = (1 + alpha) * voucher_balance
"""
if voucher_balance <= 0:
dr = value
ds = tokens
dv = tokens
return (dr, ds, dv)
alpha = value / reserve_balance
dr = alpha * reserve_balance
ds = alpha * supply_balance
dv = alpha * voucher_balance
return (dr, ds, dv)
def remove_liquidity(reserve_balance, supply_balance, voucher_balance, tokens):
"""
Example:
new_reserve = (1 - alpha) * reserve_balance
new_supply = (1 - alpha) * supply_balance
new_vouchers = (1 - alpha) * voucher_balance
"""
alpha = tokens / voucher_balance
dr = -alpha * reserve_balance
ds = -alpha * supply_balance
dv = -alpha * voucher_balance
return (dr, ds, dv)
# Token trading
def get_input_price(dx, x_balance, y_balance, trade_fee=0):
"""
How much y received for selling dx?
Example:
new_x = (1 + alpha)*x_balance
new_y = y_balance - dy
"""
rho = trade_fee
alpha = dx / x_balance
gamma = 1 - rho
dy = (alpha * gamma / (1 + alpha * gamma)) * y_balance
_dx = alpha * x_balance
_dy = -dy
return (_dx, _dy)
def get_output_price(dy, x_balance, y_balance, trade_fee=0):
"""
How much x needs to be sold to buy dy?
Example:
new_x = x_balance + dx
new_y = (1 - beta)*y_balance
"""
rho = trade_fee
beta = dy / y_balance
gamma = 1 - rho
dx = (beta / (1 - beta)) * (1 / gamma) * x_balance
_dx = dx
_dy = -beta * y_balance
return (_dx, _dy)
def collateral_to_token(value, reserve_balance, supply_balance, trade_fee):
"""
Trade collateral for token
Example:
new_reserve = reserve_balance + dx
new_supply = supply_balance - dy
"""
if reserve_balance == 0:
return 0
_dx, dy = get_input_price(value, reserve_balance, supply_balance, trade_fee)
return abs(dy)
def token_to_collateral(tokens, reserve_balance, supply_balance, trade_fee):
"""
Trade token for collateral
Example:
new_reserve = reserve_balance - dx
new_supply = supply_balance + dy
"""
if supply_balance == 0:
return 0
_dx, dy = get_input_price(tokens, supply_balance, reserve_balance, trade_fee)
return abs(dy)