This repository has been archived by the owner on Jul 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
anchor.py
492 lines (413 loc) · 15.9 KB
/
anchor.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import requests
import inspect
import base64
import json
from terra_sdk.core.wasm.msgs import MsgExecuteContract
from terra_sdk.core.coins import Coins
from terra_sdk.core.strings import AccAddress
from terra_sdk.exceptions import LCDResponseError
from aiogram.utils.markdown import quote_html
from terra_chain import TerraChain
from config import Config
class AnchorException(Exception):
def __init__(self, action, code, message):
self._code = code
self._message = message
self._action = action
super().__init__(message)
def __str__(self):
return "❗️ Anchor error: {}\n{} : {}".format(
self._action,
self._code,
self._message,
)
def to_telegram_str(self):
return "❗️ Anchor error: <code>{}</code>\n<pre>{} : {}</pre>".format(
self._action,
self._code,
quote_html(self._message),
)
class Anchor:
async def get_config(contract_address):
try:
query = {"config": {}}
response = await TerraChain.chain.wasm.contract_query(
contract_address,
query,
)
for val in response:
if (isinstance(response[val], str)):
if ("terra" in response[val]):
Config._address[val] = response[val]
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
async def get_block_height():
block_info = await TerraChain.chain.tendermint.block_info()
block_height = int(block_info["block"]["header"]["height"])
return block_height
async def get_borrow_value(wallet_address):
borrow_value = 0
try:
query = {
"borrower_info": {
"borrower": wallet_address,
"block_height": await Anchor.get_block_height(),
}
}
response = await TerraChain.chain.wasm.contract_query(
Config._address["market_contract"],
query,
)
borrow_value = float(response["loan_amount"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return borrow_value
async def get_borrow_limit(wallet_address):
borrow_limit = 0
try:
query = {
"borrow_limit": {
"borrower": wallet_address,
"block_time": await Anchor.get_block_height(),
}
}
response = await TerraChain.chain.wasm.contract_query(
Config._address["overseer_contract"],
query,
)
borrow_limit = float(response["borrow_limit"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return borrow_limit
async def get_bluna_amount(wallet_address):
bluna_price = 0
try:
query = {"borrower": {"address": wallet_address}}
response = await TerraChain.chain.wasm.contract_query(
Config._address["mmCustody"],
query,
)
bluna_price = float(response["balance"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return bluna_price
async def get_bluna_price():
price = None
try:
query = {"price" : {"base": Config._address["collateral_token"], "quote": "uusd"}}
response = await TerraChain.chain.wasm.contract_query(Config._address["oracle_contract"], query)
price = float(response["rate"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(inspect.currentframe().f_code.co_name, e.errno if e.errno else -1, e.message)
return price
async def get_pending_rewards(wallet_address):
pending_rewards = 0
try:
query = {
"borrower_info": {
"borrower": wallet_address,
"block_height": await Anchor.get_block_height(),
}
}
response = await TerraChain.chain.wasm.contract_query(
Config._address["market_contract"],
query,
)
pending_rewards = float(response["pending_rewards"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return pending_rewards
async def get_current_ltv(wallet_address, borrow_value=None, borrow_limit=None):
current_ltv = None
if borrow_value is None:
borrow_value = await Anchor.get_borrow_value(wallet_address)
if borrow_limit is None:
borrow_limit = await Anchor.get_borrow_limit(wallet_address)
if borrow_value != 0 and borrow_limit != 0:
# (v1*100/v2)
current_ltv = round((borrow_value * 100) / (borrow_limit * Config._maximum_ltv_allowed), 2)
return current_ltv
async def get_amount_to_repay(
wallet_address, target_ltv, borrow_value=None, borrow_limit=None
):
amount_to_repay = None
try:
if borrow_value is None:
borrow_value = await Anchor.get_borrow_value(wallet_address)
if borrow_limit is None:
borrow_limit = await Anchor.get_borrow_limit(wallet_address)
amount_to_repay = int(
borrow_value - ((target_ltv * (borrow_limit * Config._maximum_ltv_allowed)) / 100)
)
except Exception as e:
Config._log.exception(e)
amount_to_repay = None
return amount_to_repay
async def get_amount_to_borrow(
wallet_address, target_ltv, borrow_value=None, borrow_limit=None
):
amount_to_borrow = None
try:
if borrow_value is None:
borrow_value = await Anchor.get_borrow_value(wallet_address)
if borrow_limit is None:
borrow_limit = await Anchor.get_borrow_limit(wallet_address)
amount_to_borrow = int(
((target_ltv * (borrow_limit * Config._maximum_ltv_allowed)) / 100) - borrow_value
)
except Exception as e:
Config._log.exception(e)
amount_to_borrow = None
return amount_to_borrow
async def do_trx(wallet, msgs, usd_gas_price = None):
trxhash = None
terra_wallet = wallet._wallet
try:
tx = await terra_wallet.create_and_sign_tx(msgs=msgs)
estimated_fees = await TerraChain.estimate_fee(wallet.get_wallet_address(), msgs, usd_gas_price)
tx = await terra_wallet.create_and_sign_tx(
msgs=msgs,
fee=estimated_fees,
)
result = await TerraChain.chain.tx.broadcast(tx)
if result.is_tx_error():
raise AnchorException(
inspect.currentframe().f_code.co_name,
result.code,
result.raw_log,
)
trxhash = result.txhash
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return trxhash
async def get_repay_amount_msg(wallet_address, amount_to_repay):
try:
query = {"repay_stable": {}}
return MsgExecuteContract(
AccAddress(wallet_address),
contract=Config._address["market_contract"],
execute_msg=query,
coins=Coins(uusd=amount_to_repay),
)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
async def get_borrow_amount_msg(wallet_address, amount_to_borrow):
try:
query = {
"borrow_stable": {
"borrow_amount": str(amount_to_borrow),
"to": wallet_address,
}
}
return MsgExecuteContract(
AccAddress(wallet_address),
contract=Config._address["market_contract"],
execute_msg=query,
)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
async def get_withdraw_from_earn_msg(wallet_address, amount_to_withdraw):
try:
b64 = base64.b64encode(bytes(json.dumps({"redeem_stable": {}}), "ascii")).decode()
msg = {
"send": {
"contract": str(Config._address["market_contract"]),
"amount": str(amount_to_withdraw),
"msg": b64,
}
}
return MsgExecuteContract(
AccAddress(wallet_address),
contract=Config._address["aterra_contract"],
execute_msg=msg,
)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
async def get_deposit_to_earn_msg(wallet_address, amount_to_deposit):
try:
query = {"deposit_stable": {}}
return MsgExecuteContract(
AccAddress(wallet_address),
contract=Config._address["market_contract"],
execute_msg=query,
coins=Coins(uusd=amount_to_deposit),
)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
async def get_claim_anc_rewards_msg(wallet_address):
try:
query = {"claim_rewards": {"to": wallet_address}}
return MsgExecuteContract(
AccAddress(wallet_address),
contract=Config._address["market_contract"],
execute_msg=query,
)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
async def get_exchange_rate():
exchange_rate = 0
try:
query = {"epoch_state": {}}
response = await TerraChain.chain.wasm.contract_query(
Config._address["market_contract"], query
)
exchange_rate = float(response["exchange_rate"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return exchange_rate
async def get_total_deposit_amount(wallet_address):
total_deposit = 0
try:
exchange_rate = await Anchor.get_exchange_rate()
balance = await Anchor.get_balance_on_earn(wallet_address)
total_deposit = exchange_rate * balance
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return total_deposit
async def get_balance_on_earn(wallet_address):
balance = 0
try:
query = {"balance": {"address": wallet_address}}
response = await TerraChain.chain.wasm.contract_query(
Config._address["aterra_contract"],
query,
)
balance = float(response["balance"])
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return balance
async def get_earn_apy():
earn_apy = None
try:
query = {"epoch_state": {}}
response = await TerraChain.chain.wasm.contract_query(
Config._address["overseer_contract"],
query,
)
deposit_rate = float(response["deposit_rate"])
earn_apy = round(deposit_rate * Config.BLOCKS_PER_YEAR * 100, 2)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return earn_apy
async def get_borrow_apy():
borrow_apy = None
try:
query = {
"query": '{{\n marketBalances: BankBalancesAddress(Address: "{}") {{\n Result {{\n Denom\n Amount\n }}\n }}\n}}\n'.format(
Config._address["market_contract"]
)
}
response = requests.post(Config._address["mantle_endpoint"], query)
market_balance = response.json()["data"]["marketBalances"]["Result"][0][
"Amount"
]
response = requests.get("https://api.anchorprotocol.com/api/v2/distribution-apy").json()
distribution_apy = response["distribution_apy"]
total_liabilities = response["total_liabilities"]
query = {"state": {}}
response = await TerraChain.chain.wasm.contract_query(
Config._address["market_contract"], query
)
total_reserves = response["total_reserves"]
query = {
"borrow_rate": {
"market_balance": market_balance,
"total_liabilities": total_liabilities,
"total_reserves": total_reserves,
},
}
response = await TerraChain.chain.wasm.contract_query(
Config._address["interest_model"],
query,
)
borrow_rate = Config.BLOCKS_PER_YEAR * float(response["rate"])
query = {"state": {}}
response = await TerraChain.chain.wasm.contract_query(
Config._address["market_contract"],
query,
)
borrow_apy = round((float(distribution_apy) - borrow_rate) * 100, 2)
except LCDResponseError as e:
Config._log.exception(e)
raise AnchorException(
inspect.currentframe().f_code.co_name,
e.errno if e.errno else -1,
e.message,
)
return borrow_apy