-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathearn.py
343 lines (297 loc) · 12.4 KB
/
earn.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
import json
import requests
import time
import base64
import os
import subprocess
import winsound
from utils import deObfuscate as d
with open('config.json', 'r') as f:
config = json.load(f)
# VARIABLE # TYPE (DEFAULT) : <DESCRIPTION>.
MYADDRESS = d(config["MYADDRESS"]) # STR (None) : Base64 encoded Public eth/bsc address.
APIKEY = d(config["APIKEY"]) # STR (None) : Base64 encoded bscScan.com API key.
RISK = config["RISK"] # FL (1.05) : Risk profile of missing user-compound.
SAFEBASELINE = config["SAFEBASELINE"] # UINT (1e17) : Initial assets - deflationary.
FARMBASELINE = config["FARMBASELINE"] # UINT (1e17) : Initial assets - inflationary.
GASTHRESHOLD = config["GASTHRESHOLD"] # UINT (3e15) : Before swapping/harboring in vSafe.
MINTX = config["MINTX"] # UINT (1e5) : Minimum transaction amount.
BUFFER = config["BUFFER"] # UINT (160) : Minimum earn() block distance.
AUTOCOMPLIM = config["AUTOCOMPLIM"] # UINT (1e14) : Not implemented.
AUTOCOMPOUND = config["AUTOCOMPOUND"] # Bool (false) : Not implemented.
VERBOSE = config["VERBOSE"] # Bool (true) : Verbosity of prints.
ALARM = config["ALARM"] # Bool (false) : Artifact. 4 second alarm at script termination. (IFTTT)
DEBUG = config["DEBUG"] # Bool (false) : Extra verbosity.
MAKER = config["MAKER"] # Bool (true) : Force earn based on estBlock().
""" Token addresses """
VSAFETOKEN = "0x925d67e6b2e86380833e7c950cccd3748d38baea"
LPTOKEN = "0x8dd39f0a49160cda5ef1e2a2fa7396eec7da8267"
BSWAPTOKEN = "0x4f0ed527e8a95ecaa132af214dfd41f30b361600"
dir = "bsc/" # Directory for scripts interacting with BlockChain
class Swapper():
def __init__(self, startBlock=5188000, location="farm"):
self.startBlock = startBlock # API Limit
self.contract = "0xf08253ebb55c5da33d637ad201a00760776f1d3b"
self.txEndpoint = f"https://api.bscscan.com/api?module=account&action=txlist&address={self.contract}&startblock={self.startBlock}%20&endblock=99999999&sort=asc&apikey={APIKEY}"
self.lastBlock = None
self.location = location
results = getResults(self.txEndpoint)
self.startBlock = results[-5]["blockNumber"]
self.txEndpoint = f"https://api.bscscan.com/api?module=account&action=txlist&address={self.contract}&startblock={self.startBlock}%20&endblock=99999999&sort=asc&apikey={APIKEY}"
def estNextEarn(self):
results = getResults(self.txEndpoint)
if len(results) > 5:
self.startBlock = results[-4]["blockNumber"]
self.txEndpoint = f"https://api.bscscan.com/api?module=account&action=txlist&address={self.contract}&startblock={self.startBlock}%20&endblock=99999999&sort=asc&apikey={APIKEY}"
dist = 0
prior = results[0]["blockNumber"]
for x in (results[1:]):
if DEBUG: print(f"distance: {dist}")
dist += int(x["blockNumber"]) - int(prior)
prior = x["blockNumber"]
avg = dist/(len(results)-1)
if DEBUG: print(f"avg: {avg}")
self.lastBlock = int(results[-1]["blockNumber"])
if DEBUG: print(f"last block: {self.lastBlock}")
estBlock = int(self.lastBlock+avg*RISK)
return min(estBlock, self.lastBlock+550)
def debugDump(s):
safeBalance = tokenBalance(VSAFETOKEN)
walletBalance = tokenBalance(LPTOKEN)
print(f"Balance: {safeBalance} VSAFETOKEN and {walletBalance} LPTOKEN. At {swapper.location}.")
print(time.strftime("%H:%M:%S", time.localtime()))
print(s)
def getCurrentBlock() -> int:
response = requests.get(f"https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={APIKEY}")
response = json.loads(response.text)
result = int(response["result"], 16)
return result
def getResults(txEndpoint):
for attempt in range(30):
try:
response = requests.get(txEndpoint, headers={'Cache-Control': 'no-cache', "Pragma": "no-cache"})
response = json.loads(response.text)
return response["result"]
except:
time.sleep(2)
continue
def callEarn():
""" Contract recalculate share price. """
method = "d389800f"
txData = f"0x{method}"
assert len(txData)==10
return subprocess.run(f"npx ts-node {dir}callEarn.ts --txData={txData}", shell=True, stdout=subprocess.PIPE, check=True)
def addBNB(amount):
""" Swap BSWAPTOKEN for BNB. """
raise NotImplementedError
def checkTx():
""" Check Transaction Status. """
raise NotImplementedError
def compound():
""" Reinvest by swapping 50% of farm yields for BNB. """
raise NotImplementedError
bswapBalance = tokenBalance(BSWAPTOKEN)
addBNB(bswapBalance/2)
def depositSafe(amount):
assert amount > MINTX
amount = str(hex(amount))[2:]
padding = "0"*(64-len(amount))
method = "e2bbb158"
minimum = "0"*64
txData = f"0x{method}{padding}{amount}{minimum}"
assert len(txData)==138
return subprocess.run(f"npx ts-node {dir}depositSafe.ts --txData={txData}", shell=True, stdout=subprocess.PIPE, check=True)
def depositFarm(amount):
assert amount > MINTX
amount = str(hex(amount))[2:]
padding = "0"*(64-len(amount))
method = "e2bbb158"
pid = "0"*64
txData = f"0x{method}{padding}{pid}{amount}"
assert len(txData)==138
return subprocess.run(f"npx ts-node {dir}depositFarm.ts --txData={txData}", shell=True, stdout=subprocess.PIPE, check=True)
def withdrawSafe(amount):
assert amount > MINTX
amount = str(hex(amount))[2:]
padding = "0"*(64-len(amount))
method = "441a3e70"
minimum = "0"*64
txData = f"0x{method}{padding}{amount}{minimum}"
assert len(txData)==138
return subprocess.run(f"npx ts-node {dir}withdrawSafe.ts --txData={txData}", shell=True, stdout=subprocess.PIPE, check=True)
def withdrawFarm(amount):
assert amount > MINTX
amount = str(hex(amount))[2:]
padding = "0"*(64-len(amount))
method = "441a3e70"
pid = "0"*64
txData = f"0x{method}{padding}{pid}{amount}"
assert len(txData)==138
return subprocess.run(f"npx ts-node {dir}withdrawFarm.ts --txData={txData}", shell=True, stdout=subprocess.PIPE, check=True)
def bnbBalance():
txEndpoint = f"https://api.bscscan.com/api?module=account&action=balance&address={MYADDRESS}&tag=latest&apikey={APIKEY}"
results = getResults(txEndpoint)
return int(results)
def tokenBalance(tokenAddress):
txEndpoint = f"https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress={tokenAddress}&address={MYADDRESS}&tag=latest&apikey={APIKEY}"
results = getResults(txEndpoint)
return int(results)
def verifyDeposit(tokenAddress):
if tokenAddress == LPTOKEN: baseline = FARMBASELINE
for _ in range(60):
balance = tokenBalance(tokenAddress)
if balance < 10000:
if VERBOSE : print(f"Verified deposit for LPTOKEN. Balance: {balance}")
return True
time.sleep(2)
if VERBOSE: print(f"Deposit not registered for LPTOKEN. Balance: {balance}.")
return False
def verifyBalance(tokenAddress):
if tokenAddress == VSAFETOKEN:
baseline = SAFEBASELINE
token = "vSafeToken"
if tokenAddress == LPTOKEN:
baseline = FARMBASELINE
token = "LP-Token"
for _ in range(60):
balance = tokenBalance(tokenAddress)
if balance >= baseline-100:
if VERBOSE : print(f"{token} balance: {balance}")
return balance
time.sleep(1)
if VERBOSE: print(f"Insufficient {token} balance: {balance} vs {baseline}")
return False
run = True
if tokenBalance(LPTOKEN) > FARMBASELINE:
location = "wallet"
elif tokenBalance(VSAFETOKEN) > SAFEBASELINE:
location = "safe"
else:
location = "farm"
print("WARNING: Value within vFarm cannot be inferred. Consider starting in vSafe or Wallet.")
if VERBOSE: print(f"Initial location registered as: {location}")
swapper = Swapper(location=location)
estBlock = swapper.estNextEarn()
swaps = 0
missed = 0
swapped = False
excessBlocks = 0
lastSwap = estBlock
if MAKER == True:
if swapper.location == "safe":
callEarn()
pass
# START IN FARM
while run:
time.sleep(5)
estBlock = swapper.estNextEarn()
currentBlock = getCurrentBlock()
balanceBNB = bnbBalance()
if VERBOSE : print(f"({swapper.location}) Estimated block: {estBlock}. Current block: {currentBlock}. BNB balance: {balanceBNB}. Swaps: {swaps}. missed: {missed}. Excess blocks: {excessBlocks}.")
if swapped == False and estBlock != lastSwap and lastSwap > currentBlock:
print(f"Miss of {lastSwap-currentBlock}.")
missed += lastSwap-currentBlock
elif estBlock != lastSwap and lastSwap < currentBlock:
print(f"Excess of {currentBlock-lastSwap}.")
excessBlocks += currentBlock-lastSwap
swapped = True
else:
swapped = False
lastSwap = estBlock
if (swapper.location != "safe" and currentBlock > estBlock) or (swapper.location == "wallet"):
if swapper.location == "farm":
withdrawFarm(FARMBASELINE)
if verifyBalance(LPTOKEN) == False:
debugDump(f"ERROR: Couldnt Withdraw {FARMBASELINE} LP-Token from vFarm")
# Stop or re-attempt
run = False
break
else:
swapper.location = "wallet"
if VERBOSE : print("wallet")
depositSafe(tokenBalance(LPTOKEN))
if verifyBalance(VSAFETOKEN) == False:
debugDump(f"ERROR: Couldn't verify balance")
# Stop or re-attempt
run = False
break
else:
swapper.location = "safe"
if VERBOSE : print("safe")
swaps += 1
if MAKER == True:
callEarn()
if (swapper.location != "farm" and currentBlock+BUFFER < estBlock):
if swapper.location == "safe":
withdrawSafe(tokenBalance(VSAFETOKEN))
if verifyBalance(LPTOKEN) == False:
debugDump(f"ERROR: Couldn't Withdraw {tokenBalance(VSAFETOKEN)} from vSafe")
# Stop or re-attempt
run = False
break
else:
FARMBASELINE = tokenBalance(LPTOKEN)
swapper.location = "wallet"
if VERBOSE : print("wallet")
depositFarm(tokenBalance(LPTOKEN))
if verifyDeposit(LPTOKEN) == False:
# Stop or re-attempt
debugDump("ERROR: Couldn't verify deposit into vFarm")
run = False
break
else:
swapper.location = "farm"
if VERBOSE : print("farm")
swaps += 1
# TODO: Auto compound functionality
if AUTOCOMPOUND:
if AUTOCOMPLIM < tokenBalance(BSWAPTOKEN):
pass
# TODO: addGas(): Swap vBSwap for BNB
# Gas threshold -> Harbor assets in vSafe
if balanceBNB < GASTHRESHOLD:
print("WARNING: low BNB balance")
if swapper.location == "farm":
withdrawFarm(FARMBASELINE)
if verifyBalance(LPTOKEN) == False:
debugDump(f"Couldnt Withdraw {FARMBASELINE} LP-Token from vFarm")
# Stop or re-attempt
run = False
break
else:
swapper.location = "wallet"
if VERBOSE : print("wallet")
depositSafe(tokenBalance(LPTOKEN))
if verifyBalance(VSAFETOKEN) == False:
debugDump("Couldn't verify deposit of LP-Token")
# Stop or re-attempt
run = False
break
else:
swapper.location = "safe"
if VERBOSE : print("safe")
swaps += 1
run = False
break
if swapper.location != "safe" and False:
print("ERROR -> RETURNING TO SAFE")
withdrawFarm(FARMBASELINE)
if verifyBalance(LPTOKEN) == False:
debugDump("Couldnt Withdraw from vFarm")
# Stop or re-attempt
run = False
else:
swapper.location = "wallet"
if VERBOSE : print("wallet")
depositSafe(tokenBalance(LPTOKEN))
if verifyBalance(VSAFETOKEN) == False:
# Stop or re-attempt
run = False
else:
swapper.location = "safe"
if VERBOSE : print("safe")
swaps += 1
if ALARM:
duration = 4000 # milliseconds
freq = 440 # Hz
winsound.Beep(freq, duration)