-
Notifications
You must be signed in to change notification settings - Fork 1
/
simulator.py
462 lines (364 loc) · 17.9 KB
/
simulator.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
from random import seed
from random import randint
from random import uniform
from random import shuffle
from datetime import datetime
import threading
import time
import price_calcs
import numpy as np
import solver
N_COINS = 3
PRECISION_MUL = [1, 1000000000000, 1000000000000]
FEE_DENOMINATOR = 10 ** 10
PRECISION = 10 ** 18
MAX_ADMIN_FEE = 10 * 10 ** 9
MAX_FEE = 5 * 10 ** 9
MAX_A = 10 ** 6
MAX_A_CHANGE = 10
A_PRECISION = 100
amp = 2000
ADMIN_ACTIONS_DELAY = 3 * 86400
MIN_RAMP_TIME = 86400
#Read by the attack contract from Compound
PRECISION_MUL = [1, 1000000000000, 1000000000000]
#Read from Etherscan for the USDT pool
fee = 4000000
admin_fee = 5000000000
#Expression of the invariant of the USDT pool in the contract code
def USDTpool(xp, amp, D):
'''
Return f(D), takes xp in TokenPrecision units
'''
#amp is already A*n**(n-1)
Ann = amp*N_COINS
S = 0
for _x in xp:
S += _x
if S == 0:
return 0
P = 1 #product of xi
for _x in xp:
P*= _x
return Ann*S + (1-Ann)*D - (D**(N_COINS+1))/((N_COINS**N_COINS)*P)
def TokensToCTokens(amount, index):
return amount*PRECISION//(rates[index]//PRECISION_MUL[index])
def CTokensToTokens(amount, index):
return amount*(rates[index]//PRECISION_MUL[index])//PRECISION
def CTokensToTokensIncreasedPrecision(amount, index):
return rates[index] * amount// PRECISION
def TokensIncreasedPrecisionToCTokens(amount, index):
return amount*PRECISION//rates[index]
denoms = [10**18, 10**6, 10**6]
tokenNames = ['DAI', 'USDC', 'USDT']
cTokenNames = ['cDAI', 'cUSDC', 'USDT']
def TokensToDollars(amount, index):
return amount/denoms[index]
def CTokensToDollars(amount, index):
return CTokensToTokens(amount,index)/denoms[index]
def DollarsToCTokens(amount, index):
return TokensToCTokens(int(amount*denoms[index]),index)
##########################
####MINING PARAMETERS#####
##########################
blockNumber = 11835041
current_ctokens = [ 2236520561601012 , 3481287597858764 , 200709219245 ]
LoanAmounts = [ 2000000000000000000000000 , 2000000000000 , 2000000000000 ]
funds_avail_ctokens = [ 9492175161208640 , 9262735174877799 , 2000000000000 ]
rates = [ 210699862363827219553716955 , 215918944268682000000000000 , 1000000000000000000000000000000 ]
totalSupply = 1366582863843277849699307 # total supply of pool tokens
##########################
##########################
##########################
current_ctokens = [ 1757662794027293 , 3506962588474923 , 324570592963 ]
totalSupply = 1366582863843277849699307
LoanAmounts = [ 15000000000000000000000000 , 15000000000000 , 6000000000000 ]
funds_avail_ctokens = [ 71986950757698170 , 70250803567106466 , 21094498755517 ]
rates = [ 210903268827652604936428979 , 216115143722780000000000000 , 1000000000000000000000000000000 ]
addLiquidity = [ 71986950757698170 , 70250803567106466 , 21094498755517 ]
contract_poolTokens = 0
our_poolTokens = 0
our_balance = []
contract_balance = []
def resetBalances():
global contract_poolTokens,our_poolTokens,our_balance,contract_balance
contract_poolTokens = totalSupply
our_poolTokens = 0
our_balance = funds_avail_ctokens.copy()
contract_balance = current_ctokens.copy()
def simAddLiquidity(amounts):
global contract_poolTokens,our_poolTokens,contract_balance,our_balance
(amounts,fees,D1,contract_poolTokens,mint_amount,contract_balance) = solver.add_liquidity(amounts.copy(), contract_poolTokens, contract_balance.copy(),fee, rates, admin_fee, amp)
our_balance[0] -= amounts[0]
our_balance[1] -= amounts[1]
our_balance[2] -= amounts[2]
our_poolTokens += mint_amount
def simRemoveLiquidity(poolTokensToRemove):
global our_balance,our_poolTokens,contract_poolTokens,contract_balance
(contract_balance,amounts,contract_poolTokens) = solver.remove_liquidity(poolTokensToRemove, [0,0,0], contract_balance.copy(), contract_poolTokens)
our_balance[0] += amounts[0]
our_balance[1] += amounts[1]
our_balance[2] += amounts[2]
our_poolTokens -= poolTokensToRemove
def simRemoveLiquidityImbalanced(amounts):
global our_balance,our_poolTokens,contract_balance
(poolTokensToRemove,contract_balance) = solver.remove_liquidity_imbalance(amounts, contract_poolTokens, fee, admin_fee, rates, contract_balance.copy())
our_balance[0] += amounts[0]
our_balance[1] += amounts[1]
our_balance[2] += amounts[2]
our_poolTokens -= poolTokensToRemove
def simTrade(i, j, dx):
global our_balance,contract_balance
(our_balance,contract_balance) = solver.exchange(i, j, dx, rates, fee, amp,contract_balance.copy(), our_balance.copy(),admin_fee)
seed(None)
bestProfit = 0
while(False):
resetBalances()
our_initial_balance = funds_avail_ctokens
fundsIn = sum([CTokensToDollars(our_initial_balance[i],i) for i in range(N_COINS)])
fundsToUseFrac = [uniform(0, 1),uniform(0, 1),uniform(0, 1)]
fundsToUse = [int(fundsToUseFrac[i]*our_initial_balance[i]) for i in range(N_COINS)]
add1 = [uniform(0, 1),uniform(0, 1),uniform(0, 1)]
coinsLeft=[our_initial_balance[i]-fundsToUse[i] for i in range(N_COINS)]
ti = randint(0,2)
tj = randint(0,2)
amountToTrade = randint(0,coinsLeft[ti])
try:
attackAdd1 = [int(fundsToUse[i]*add1[i]) for i in range(N_COINS)]
attackAdd2 = [fundsToUse[i]-attackAdd1[i] for i in range(N_COINS)]
simAddLiquidity(attackAdd1)
#if(ti!=tj and amountToTrade>0):
# simTrade(ti,tj,amountToTrade)
simAddLiquidity(attackAdd2)
simRemoveLiquidity(our_poolTokens)
fundsOut = sum([CTokensToDollars(our_balance[i],i) for i in range(N_COINS)])
profit = fundsOut-fundsIn
if(profit>bestProfit):
bestProfit=profit
print('made profit!')
print(profit)
#print(attack_balances_c_tokens)
file = open("profits2.txt", "a")
file.write("PROFIT!\n")
file.write(str(fundsToUse[0])+', '+str(fundsToUse[1])+', '+str(fundsToUse[2])+'\n')
file.write("add:\n")
file.write(str(attackAdd1[0])+', '+str(attackAdd1[1])+', '+str(attackAdd1[2])+'\n')
file.write("trade:\n")
file.write(str(ti)+', '+str(tj)+', '+str(amountToTrade)+'\n')
file.write("add:\n")
file.write(str(attackAdd2[0])+', '+str(attackAdd2[1])+', '+str(attackAdd2[2])+'\n')
file.write("calc:\n")
file.write('Funds In: '+str(fundsIn) + '$\n')
file.write('Funds Out: '+str(fundsOut) + '$\n')
file.write('profit'+str(profit) + '$\n')
file.close()
except KeyboardInterrupt:
exit()
except:
continue
#Test: find invalid D for very unbalanced pool, trade on that pool and then trade back.
iteration = 0
while False:
resetBalances()
our_initial_balance = funds_avail_ctokens
fundsIn = sum([CTokensToDollars(our_initial_balance[i],i) for i in range(N_COINS)])
#Current balance of the USDT pool in CTokens
cdai = current_ctokens[0]
cusdc = current_ctokens[1]
cusdt = current_ctokens[2]
#For easily understandable adjustments
attack_balances_usd = [500000,2000000,600000]
#Convert to CTokens
attack_balances_c_tokens = [DollarsToCTokens(attack_balances_usd[0], 0), DollarsToCTokens(attack_balances_usd[1], 1), DollarsToCTokens(attack_balances_usd[2], 2)]
#Perturb to find an invalid D
attack_balances_c_tokens = [int(uniform(0.8,1)*attack_balances_c_tokens[0]), int(uniform(0.8,1)*attack_balances_c_tokens[1]), int(uniform(0.99,1)*attack_balances_c_tokens[2])]
#Convert to TokensPrecision
attack_balances_tokens_precision = [CTokensToTokensIncreasedPrecision(attack_balances_c_tokens[0], 0), CTokensToTokensIncreasedPrecision(attack_balances_c_tokens[1], 1), CTokensToTokensIncreasedPrecision(attack_balances_c_tokens[2], 2)]
#Get D for this pool composition
D = solver.get_D(attack_balances_tokens_precision, amp)
#Check if the D found breaks the invariant
u = USDTpool(attack_balances_tokens_precision, amp, D)
#If D doesn't verify the invariant relationship
if abs(u) > 0:
#try:
#Find liquidity to add to get the invalid D found
liquidityToAdd = [attack_balances_c_tokens[i] - contract_balance[i] for i in range(N_COINS)]
#Add liquidity into the original pool to get to the exact attack balances found
simAddLiquidity(liquidityToAdd)
#Perform a swap of 40% the original amount of (c)USDC for (c)DAI into that new pool
#Get amount in
amountToTradeCUSDC = int(0.6*cusdc)
#Get the amount out before changing the state of the pool
amountOutCDAI = solver._exchange(1, 0, contract_balance, amountToTradeCUSDC, rates, fee, amp)
#Change state of the pool
simTrade(1, 0, amountToTradeCUSDC)
#Trade the exact amount of (c)DAI obtained back to (c)USDC
amountBackCUSDC = solver._exchange(0, 1, contract_balance, amountOutCDAI, rates, fee, amp)
simTrade(0, 1, amountOutCDAI)
# if iteration % 1000000 == 0:
# file = open("check_cdai_in_out.txt", "a")
# file.write("CDAI in: " + str(amountToTradeCDAI) + "\n")
# file.write("CDAI out " + str(amountBackCDAI) + "\n")
# if amountBackCDAI > amountToTradeCDAI:
# file.write("OUT/IN: " + str(amountBackCDAI/amountToTradeCDAI) + "\n \n")
# elif amountToTradeCDAI > amountBackCDAI:
# file.write("IN/OUT: " + str(amountToTradeCDAI/amountBackCDAI) + "\n \n")
# file.close()
if (amountBackCUSDC > 1.009*amountToTradeCUSDC or amountToTradeCUSDC > 1.009*amountBackCUSDC):
print("Solution found!")
#Redo the same attack 10 times
for i in range(10):
print(i)
#Add liquidity to get back to the attack balances
liquidityToAdd = [attack_balances_c_tokens[i] - contract_balance[i] for i in range(N_COINS)]
simAddLiquidity(liquidityToAdd)
amountToTradeCUSDC = int(0.6*cusdc)
amountOutCDAI = solver._exchange(1, 0, contract_balance, amountToTradeCUSDC, rates, fee, amp)
simTrade(1, 0, amountToTradeCUSDC)
amountBackCUSDC = solver._exchange(0, 1, contract_balance, amountOutCDAI, rates, fee, amp)
simTrade(0, 1, amountOutCDAI)
#Save solution found
file = open("unbalanced_back_and_forth_trade_attack.txt", "a")
file.write("Solution found! Swap CUSDC to CDAI back to CUSDC \n")
if amountBackCUSDC > amountToTradeCUSDC:
file.write("OUT/IN: " + str(amountBackCUSDC/amountToTradeCUSDC) + "\n \n")
elif amountToTradeCUSDC > amountBackCUSDC:
file.write("IN/OUT: " + str(amountToTradeCUSDC/amountBackCUSDC) + "\n \n")
file.write("Required attack balances: \n \n")
file.write("CDAI: " + str(attack_balances_c_tokens[0]) + "\n")
file.write("CUSDC: " + str(attack_balances_c_tokens[1]) + "\n")
file.write("USDT: " + str(attack_balances_c_tokens[2]) + "\n \n")
file.write("Amounts to add: \n \n")
file.write("CDAI: " + str(liquidityToAdd[0]) + "\n")
file.write("CUSDC: " + str(liquidityToAdd[1]) + "\n")
file.write("USDT: " + str(liquidityToAdd[2]) + "\n")
simRemoveLiquidity(our_poolTokens)
fundsOut = sum([CTokensToDollars(our_balance[i],i) for i in range(N_COINS)])
profit = fundsOut-fundsIn
file.write("Profit: " + str(profit) + "$\n")
file.write("\n_____________________________________________________________ \n \n")
file.close()
#LATER: Withdraw liquidity and do absolute profit calculations, but if we find a case where we get 1% more out than we put in it's already good enough
# except KeyboardInterrupt:
# exit()
# except:
# continue
iteration += 1
#Test: find invalid D for very unbalanced pool, trade on that pool and then trade back.
iteration = 0
print('circle')
while True:
resetBalances()
our_initial_balance = funds_avail_ctokens
fundsIn = sum([CTokensToDollars(our_initial_balance[i],i) for i in range(N_COINS)])
#Current balance of the USDT pool in CTokens
#For easily understandable adjustments
attack_balances_usd = [1500000,1500000,1500000]
#Convert to CTokens
attack_balances_c_tokens = [DollarsToCTokens(attack_balances_usd[0], 0), DollarsToCTokens(attack_balances_usd[1], 1), DollarsToCTokens(attack_balances_usd[2], 2)]
attack_balances_c_tokens = [int(uniform(0.0,1)*attack_balances_c_tokens[0]), int(uniform(0.0,1)*attack_balances_c_tokens[1]), int(uniform(0,1)*attack_balances_c_tokens[2])]
liquidityToAdd = [attack_balances_c_tokens[i] for i in range(N_COINS)]
simAddLiquidity(liquidityToAdd)
a = [0,1,2]
shuffle(a)
i=a[0]
j=a[1]
k=a[2]
amountToTrade = int(uniform(0.000001, 1)*our_balance[i])
beforeTrades = our_balance.copy()
simTrade(i, j, amountToTrade)
simTrade(j, k, our_balance[j]-beforeTrades[j])
simTrade(k, i, our_balance[k]-beforeTrades[k])
profit=our_balance[i]-beforeTrades[i]
if (profit > 0 ):
print("Solution found!")
print('profit:' + str(profit))
file = open("circle.txt", "a")
file.write("profit:" + str(profit))
file.write(str(i))
file.write(str(j))
file.write(str(k))
file.write(str(amountToTrade))
file.write("CDAI: " + str(liquidityToAdd[0]) + "\n")
file.write("CUSDC: " + str(liquidityToAdd[1]) + "\n")
file.write("USDT: " + str(liquidityToAdd[2]) + "\n")
file.close()
if False:
#Redo the same attack 10 times
for i in range(10):
#Add liquidity to get back to the attack balances
liquidityToAdd = [attack_balances_c_tokens[i] - contract_balance[i] for i in range(N_COINS)]
simAddLiquidity(liquidityToAdd)
daiBeforeTrade = our_balance[0]
simTrade(1, 0, amountToTradeCUSDC)
amountOutCDAI = our_balance[0]-daiBeforeTrade
simTrade(0, 1, amountOutCDAI)
#Save solution found
file = open("unbalanced_back_and_forth_trade_attack2.txt", "a")
file.write("Solution found! Swap CUSDC to CDAI back to CUSDC \n")
if amountBackCUSDC > amountToTradeCUSDC:
file.write("OUT/IN: " + str(amountBackCUSDC/amountToTradeCUSDC) + "\n \n")
elif amountToTradeCUSDC > amountBackCUSDC:
file.write("IN/OUT: " + str(amountToTradeCUSDC/amountBackCUSDC) + "\n \n")
file.write("Required attack balances: \n \n")
file.write("CDAI: " + str(attack_balances_c_tokens[0]) + "\n")
file.write("CUSDC: " + str(attack_balances_c_tokens[1]) + "\n")
file.write("USDT: " + str(attack_balances_c_tokens[2]) + "\n \n")
file.write("Amounts to add: \n \n")
file.write("CDAI: " + str(liquidityToAdd[0]) + "\n")
file.write("CUSDC: " + str(liquidityToAdd[1]) + "\n")
file.write("USDT: " + str(liquidityToAdd[2]) + "\n")
file.write("Amount to Trade: \n \n")
file.write("CUSDC: " + str(amountToTradeCUSDC) + "\n")
simRemoveLiquidity(our_poolTokens)
fundsOut = sum([CTokensToDollars(our_balance[i],i) for i in range(N_COINS)])
profit = fundsOut-fundsIn
file.write("Profit: " + str(profit) + "$\n")
file.write("\n_____________________________________________________________ \n \n")
file.close()
iteration += 1
seed(None)
bestProfit = 0
resetBalances()
fundsIn = sum([CTokensToDollars(our_balance[i],i) for i in range(N_COINS)])
while(False):
resetBalances()
#try:
##add
attackAdd1 = [int(our_balance[i]*uniform(0, 1)) for i in range(N_COINS)]
simAddLiquidity(attackAdd1)
##add
attackAdd2 = [int(our_balance[i]*uniform(0, 1)) for i in range(N_COINS)]
simAddLiquidity(attackAdd2)
attackAdd3 = [int(our_balance[i]*uniform(0, 1)) for i in range(N_COINS)]
simAddLiquidity(attackAdd3)
attackAdd4 = [int(our_balance[i]*uniform(0, 1)) for i in range(N_COINS)]
simAddLiquidity(attackAdd4)
simRemoveLiquidity(our_poolTokens)
fundsOut = sum([CTokensToDollars(our_balance[i],i) for i in range(N_COINS)])
profit = fundsOut-fundsIn
#print(profit)
if(profit>bestProfit):
bestProfit=profit
print('made profit!')
print(profit)
#print(attack_balances_c_tokens)
file = open("profits_remove_inbalanced.txt", "a")
file.write("PROFIT!\n")
file.write(str(attackAdd1[0])+', '+str(attackAdd1[1])+', '+str(attackAdd1[2])+'\n')
file.write(str(attackAdd2[0])+', '+str(attackAdd2[1])+', '+str(attackAdd2[2])+'\n')
file.write(str(attackAdd3[0])+', '+str(attackAdd3[1])+', '+str(attackAdd3[2])+'\n')
file.write(str(attackAdd4[0])+', '+str(attackAdd4[1])+', '+str(attackAdd4[2])+'\n')
#file.write(str(attackRemove1[0])+', '+str(attackRemove1[1])+', '+str(attackRemove1[2])+'\n')
#file.write(str(attackRemove2[0])+', '+str(attackRemove2[1])+', '+str(attackRemove2[2])+'\n')
#file.write(str(attackAdd2[0])+', '+str(attackAdd2[1])+', '+str(attackAdd2[2])+'\n')
#file.write(str(our_poolTokens[0])+', '+str(our_poolTokens[1])+', '+str(our_poolTokens[2])+'\n')
file.write("calc:\n")
file.write('Funds In: '+str(fundsIn) + '$\n')
file.write('Funds Out: '+str(fundsOut) + '$\n')
file.write('profit'+str(profit) + '$\n')
file.close()
#except KeyboardInterrupt:
# exit()
#except:
# continue