-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.py
139 lines (120 loc) · 5.22 KB
/
app.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
from audioop import add
from flask import Flask, render_template,request,redirect,json
from anchorProtocol import TooManyRequests, calculateYield, getCurrentAUstExchangeRate, getClosestHistoricalRate, AnchorProtocolHandler
import requests
import datetime
from werkzeug.exceptions import HTTPException
from cachetools import cached, TTLCache
cache = TTLCache(maxsize=100, ttl=7200)
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response
@app.route("/redirectToWallet", methods = ['POST', 'GET'])
def redirectToWallet():
if request.method == 'POST':
wallet = request.form['walletAddress']
print(wallet)
return redirect(f"/address/{wallet}")
@app.route("/address/<address>")
def anchorErningsForAdress(address, checkAllLogs=False):
# First, we query all historical rates. We need them for the plot and to calculate the yield for aUST transfers
historicalRates = getHistoricalAUstRate()
error = ""
# call anchor ...
try:
anchor = AnchorProtocolHandler(address, checkAllLogs=checkAllLogs)
deposits,warnings = anchor.getAnchorTxs()
currentRate = float(getCurrentAUstExchangeRate())
totalYield = calculateYield(deposits, currentRate, historicalRates)
except AssertionError:
error = "Something went wrong with parsing the data. Please open a ticket: https://github.com/jensb89/anchor-earnings/issues"
deposits = []
totalYield = {'yield': 0, 'ustHoldings': 0, 'aUSTHoldings': 0}
currentRate = 0
warnings = ""
except TooManyRequests:
error = "Too many requests to https://fcd.terra.dev/. Try at a later time or raise a ticket if the error is shown all the time: https://github.com/jensb89/anchor-earnings/issues"
deposits = []
totalYield = {'yield': 0, 'ustHoldings': 0, 'aUSTHoldings': 0}
currentRate = 0
warnings = ""
except BaseException:
error = "Something went wrong. Please open a ticket: https://github.com/jensb89/anchor-earnings/issues"
deposits = []
totalYield = {'yield': 0, 'ustHoldings': 0, 'aUSTHoldings': 0}
currentRate = 0
warnings = ""
#todo: requests.exceptions.ConnectionError
# Add UTC time in s
minTime = datetime.datetime.now()
for deposit in deposits:
deposit["unixTimestamp"] = datetime.datetime.strptime(deposit["time"], "%Y-%m-%dT%H:%M:%SZ")
minTime = min(minTime, deposit["unixTimestamp"])
deposit["rate"] = deposit["Out"] / deposit["In"] if deposit["Out"] != 0 else getClosestHistoricalRate(historicalRates, deposit["time"])
# Graph data
histData = getHistData(deposits, historicalRates)
# get Eur rate
rateEurUsd = getEurUsdRateFromTerraPriceOracle()
return render_template('anchorOverview.html', deposits = deposits, address=address, y=totalYield, h=histData, eurRate = rateEurUsd, error=error, warnings=warnings )
@app.route("/address/<address>/full")
def anchorErningsForAdressFull(address):
return anchorErningsForAdress(address, checkAllLogs=True)
@cached(cache)
def getHistoricalAUstRate():
# we use flipside to get historical aust data. Is there a better way by using terra API directly ??
res = requests.get("https://api.flipsidecrypto.com/api/v2/queries/1de96d09-4d77-4ad7-b0c8-e907e86fdcb7/data/latest")
res = res.json()
arr = []
for elem in res:
time = datetime.datetime.fromisoformat(elem["DAYTIMESTAMP"])
arr.append((time, elem["AUST_VALUE"]))
return arr
def getHistData(deposits, historicalRates):
histYields = []
for elem in historicalRates:
time = elem[0]
austVal = elem[1]
timeStr = datetime.datetime.strftime(time, "%Y-%m-%d")
startDateReached = True
histYield = 0
for deposit in deposits:
if deposit["unixTimestamp"] > time:
continue
histYield += (austVal - deposit["rate"]) * deposit["In"]
startDateReached = False
histYields.append({"time":timeStr, "yield":histYield})
if startDateReached:
return histYields
return histYields
def getEurUsdRateFromTerraPriceOracle():
response = requests.get("https://lcd.terra.dev/oracle/denoms/exchange_rates")
if response.status_code == 200:
ret = response.json()
terraEur = 1
terraUsd = 1
for terraPrice in ret["result"]:
if terraPrice["denom"] == "ueur":
terraEur = float(terraPrice["amount"])
if terraPrice["denom"] == "uusd":
terraUsd = float(terraPrice["amount"])
if terraEur == 0 or terraUsd == 0:
return None
return terraEur / terraUsd
elif response.status_code == 404:
print('Not Found.')
else:
raise Exception("Response failed!")