-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathliquidation_bot.py
1581 lines (1315 loc) · 69 KB
/
liquidation_bot.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
EVault Liquidation Bot
"""
import threading
import random
import time
import queue
import os
import json
import sys
import math
import subprocess
from concurrent.futures import ThreadPoolExecutor
from typing import Tuple, Dict, Any, Optional
from web3 import Web3
from web3.logs import DISCARD
from app.liquidation.utils import (setup_logger,
create_contract_instance,
make_api_request,
global_exception_handler,
post_liquidation_opportunity_on_slack,
post_liquidation_result_on_slack,
post_low_health_account_report,
post_unhealthy_account_on_slack,
post_error_notification,
get_eth_usd_quote,
get_btc_usd_quote)
from app.liquidation.config_loader import ChainConfig
### ENVIRONMENT & CONFIG SETUP ###
logger = setup_logger()
sys.excepthook = global_exception_handler
### MAIN CODE ###
class Vault:
"""
Represents a vault in the EVK System.
This class provides methods to interact with a specific vault contract.
This does not need to be serialized as it does not store any state
"""
def __init__(self, address, config: ChainConfig):
self.config = config
self.address = address
self.instance = create_contract_instance(address, self.config.EVAULT_ABI_PATH, self.config)
self.underlying_asset_address = self.instance.functions.asset().call()
self.vault_name = self.instance.functions.name().call()
self.vault_symbol = self.instance.functions.symbol().call()
self.unit_of_account = self.instance.functions.unitOfAccount().call()
self.oracle_address = self.instance.functions.oracle().call()
self.pyth_feed_ids = []
self.redstone_feed_ids = []
def get_account_liquidity(self, account_address: str) -> Tuple[int, int]:
"""
Get liquidity metrics for a given account.
Args:
account_address (str): The address of the account to check.
Returns:
Tuple[int, int]: A tuple containing (collateral_value, liability_value).
"""
try:
balance = self.instance.functions.balanceOf(
Web3.to_checksum_address(account_address)).call()
except Exception as ex: # pylint: disable=broad-except
logger.error("Vault: Failed to get balance for account %s: %s",
account_address, ex, exc_info=True)
return (0, 0, 0)
try:
# Check if vault contains a Pyth oracle
self.pyth_feed_ids, self.redstone_feed_ids = PullOracleHandler.get_feed_ids(self, self.config)
if len(self.pyth_feed_ids) > 0 and len(self.redstone_feed_ids) > 0:
logger.info("Vault: Pyth & Redstone oracle found for vault %s, "
"getting account liquidity through simulation", self.address)
collateral_value, liability_value = PullOracleHandler.get_account_values_with_pyth_and_redstone_simulation(self, account_address, self.pyth_feed_ids, self.redstone_feed_ids, self.config)
elif len(self.pyth_feed_ids) > 0:
logger.info("Vault: Pyth Oracle found for vault %s, "
"getting account liquidity through simulation", self.address)
collateral_value, liability_value = PullOracleHandler.get_account_values_with_pyth_batch_simulation(
self, account_address, self.pyth_feed_ids, self.config)
elif len(self.redstone_feed_ids) > 0:
logger.info("Vault: Redstone Oracle found for vault %s, "
"getting account liquidity through simulation", self.address)
collateral_value, liability_value = PullOracleHandler.get_account_values_with_redstone_batch_simulation(
self, account_address, self.redstone_feed_ids, self.config)
else:
logger.info("Vault: Getting account liquidity normally for vault %s", self.address)
(collateral_value, liability_value) = self.instance.functions.accountLiquidity(
Web3.to_checksum_address(account_address),
True
).call()
except Exception as ex: # pylint: disable=broad-except
if ex.args[0] != "0x43855d0f" and ex.args[0] != "0x6d588708":
logger.error("Vault: Failed to get account liquidity"
" for account %s: Contract error - %s",
account_address, ex)
# return (balance, 100, 100)
return (balance, 0, 0)
return (balance, collateral_value, liability_value)
def check_liquidation(self,
borower_address: str,
collateral_address: str,
liquidator_address: str
) -> Tuple[int, int]:
"""
Call checkLiquidation on EVault for an account
Args:
borower_address (str): The address of the borrower.
collateral_address (str): The address of the collateral asset.
liquidator_address (str): The address of the potential liquidator.
Returns:
Tuple[int, int]: A tuple containing (max_repay, seized_collateral).
"""
logger.info("Vault: Checking liquidation for account %s, collateral vault %s,"
" liquidator address %s, borrowed asset %s",
borower_address, collateral_address,
liquidator_address, self.underlying_asset_address)
if len(self.pyth_feed_ids) > 0 and len(self.redstone_feed_ids) > 0:
(max_repay, seized_collateral) = PullOracleHandler.check_liquidation_with_pyth_and_redstone_simulation(
self,
Web3.to_checksum_address(liquidator_address),
Web3.to_checksum_address(borower_address),
Web3.to_checksum_address(collateral_address),
self.pyth_feed_ids,
self.redstone_feed_ids,
self.config
)
elif len(self.pyth_feed_ids) > 0:
(max_repay, seized_collateral) = PullOracleHandler.check_liquidation_with_pyth_batch_simulation(
self,
Web3.to_checksum_address(liquidator_address),
Web3.to_checksum_address(borower_address),
Web3.to_checksum_address(collateral_address),
self.pyth_feed_ids,
self.config
)
elif len(self.redstone_feed_ids) > 0:
(max_repay, seized_collateral) = PullOracleHandler.check_liquidation_with_redstone_batch_simulation(
self,
Web3.to_checksum_address(liquidator_address),
Web3.to_checksum_address(borower_address),
Web3.to_checksum_address(collateral_address),
self.redstone_feed_ids,
self.config
)
else:
(max_repay, seized_collateral) = self.instance.functions.checkLiquidation(
Web3.to_checksum_address(liquidator_address),
Web3.to_checksum_address(borower_address),
Web3.to_checksum_address(collateral_address)
).call()
return (max_repay, seized_collateral)
def convert_to_assets(self, amount: int) -> int:
"""
Convert an amount of vault shares to underlying assets.
Args:
amount (int): The amount of vault tokens to convert.
Returns:
int: The amount of underlying assets.
"""
return self.instance.functions.convertToAssets(amount).call()
def get_ltv_list(self):
"""
Return list of LTVs for this vault
"""
return self.instance.functions.LTVList().call()
class Account:
"""
Represents an account in the EVK System.
This class provides methods to interact with a specific account and
manages individual account data, including health scores,
liquidation simulations, and scheduling of updates. It also provides
methods for serialization and deserialization of account data.
"""
def __init__(self, address, controller: Vault, config: ChainConfig):
self.config = config
self.address = address
self.owner, self.subaccount_number = EVCListener.get_account_owner_and_subaccount_number(self.address, config)
self.controller = controller
self.time_of_next_update = time.time()
self.current_health_score = math.inf
self.balance = 0
self.value_borrowed = 0
def update_liquidity(self) -> float:
"""
Update account's liquidity & next scheduled update and return the current health score.
Returns:
float: The updated health score of the account.
"""
self.get_health_score()
self.get_time_of_next_update()
return self.current_health_score
def get_health_score(self) -> float:
"""
Calculate and return the current health score of the account.
Returns:
float: The current health score of the account.
"""
balance, collateral_value, liability_value = self.controller.get_account_liquidity(
self.address)
self.balance = balance
self.value_borrowed = liability_value
if self.controller.unit_of_account == self.config.WETH:
logger.info("Account: Getting a quote for %s WETH, unit of account %s",
liability_value, self.controller.unit_of_account)
self.value_borrowed = get_eth_usd_quote(liability_value, self.config)
logger.info("Account: value borrowed: %s", self.value_borrowed)
elif self.controller.unit_of_account == self.config.BTC:
logger.info("Account: Getting a quote for %s BTC, unit of account %s",
liability_value, self.controller.unit_of_account)
self.value_borrowed = get_btc_usd_quote(liability_value, self.config)
logger.info("Account: value borrowed: %s", self.value_borrowed)
# Special case for 0 values on balance or liability
if liability_value == 0:
self.current_health_score = math.inf
return self.current_health_score
self.current_health_score = collateral_value / liability_value
logger.info("Account: %s health score: %s, Collateral Value: %s,"
" Liability Value: %s", self.address, self.current_health_score,
collateral_value, liability_value)
return self.current_health_score
def get_time_of_next_update(self) -> float:
"""
Calculate the time of the next update for this account based on size and health score.
Returns:
float: The timestamp of the next scheduled update.
"""
# Special case for infinite health score
if self.current_health_score == math.inf:
self.time_of_next_update = -1
return self.time_of_next_update
# Determine size category
if self.value_borrowed < self.config.TEENY:
size_prefix = "TEENY"
elif self.value_borrowed < self.config.MINI:
size_prefix = "MINI"
elif self.value_borrowed < self.config.SMALL:
size_prefix = "SMALL"
elif self.value_borrowed < self.config.MEDIUM:
size_prefix = "MEDIUM"
else:
size_prefix = "LARGE" # For anything >= MEDIUM
# Get the appropriate time values based on size
liq_time = getattr(self.config, f"{size_prefix}_LIQ")
high_risk_time = getattr(self.config, f"{size_prefix}_HIGH")
safe_time = getattr(self.config, f"{size_prefix}_SAFE")
# Calculate time gap based on health score
if self.current_health_score < self.config.HS_LIQUIDATION:
time_gap = liq_time
elif self.current_health_score < self.config.HS_HIGH_RISK:
# Linear interpolation between liq and high_risk times
ratio = (self.current_health_score - self.config.HS_LIQUIDATION) / (self.config.HS_HIGH_RISK - self.config.HS_LIQUIDATION)
time_gap = liq_time + (high_risk_time - liq_time) * ratio
elif self.current_health_score < self.config.HS_SAFE:
# Linear interpolation between high_risk and safe times
ratio = (self.current_health_score - self.config.HS_HIGH_RISK) / (self.config.HS_SAFE - self.config.HS_HIGH_RISK)
time_gap = high_risk_time + (safe_time - high_risk_time) * ratio
else:
time_gap = safe_time
# Randomly adjust time by ±10% to avoid synchronized checks
time_of_next_update = time.time() + time_gap * random.uniform(0.9, 1.1)
# Keep existing next update if it's already scheduled between now and calculated time
if not(self.time_of_next_update < time_of_next_update and self.time_of_next_update > time.time()):
self.time_of_next_update = time_of_next_update
logger.info("Account: %s next update scheduled for %s", self.address,
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.time_of_next_update)))
return self.time_of_next_update
def simulate_liquidation(self) -> Tuple[bool, Optional[Dict[str, Any]]]:
"""
Simulate liquidation of this account to determine if it's profitable.
Returns:
Tuple[bool, Optional[Dict[str, Any]]]: A tuple containing a boolean indicating
if liquidation is profitable, and a dictionary with liquidation details if profitable.
"""
result = Liquidator.simulate_liquidation(self.controller, self.address, self, self.config)
return result
def to_dict(self) -> Dict[str, Any]:
"""
Convert the account object to a dictionary representation.
Returns:
Dict[str, Any]: A dictionary representation of the account.
"""
return {
"address": self.address,
"controller_address": self.controller.address,
"time_of_next_update": self.time_of_next_update,
"current_health_score": self.current_health_score
}
@staticmethod
def from_dict(data: Dict[str, Any], vaults: Dict[str, Vault], config: ChainConfig) -> "Account":
"""
Create an Account object from a dictionary representation.
Args:
data (Dict[str, Any]): The dictionary representation of the account.
vaults (Dict[str, Vault]): A dictionary of available vaults.
Returns:
Account: An Account object created from the provided data.
"""
controller = vaults.get(data["controller_address"])
if not controller:
controller = Vault(data["controller_address"], config)
vaults[data["controller_address"]] = controller
account = Account(address=data["address"], controller=controller, config=config)
account.time_of_next_update = data["time_of_next_update"]
account.current_health_score = data["current_health_score"]
return account
class AccountMonitor:
"""
Primary class for the liquidation bot system.
This class is responsible for maintaining a list of accounts, scheduling
updates, triggering liquidations, and managing the overall state of the
monitored accounts. It also handles saving and loading the monitor's state.
"""
def __init__(self, chain_id: int, config: ChainConfig, notify = False, execute_liquidation = False):
self.chain_id = chain_id
self.w3 = config.w3,
self.config = config
self.accounts = {}
self.vaults = {}
self.update_queue = queue.PriorityQueue()
self.condition = threading.Condition()
self.executor = ThreadPoolExecutor(max_workers=32)
self.running = True
self.latest_block = 0
self.last_saved_block = 0
self.notify = notify
self.execute_liquidation = execute_liquidation
self.recently_posted_low_value = {}
def start_queue_monitoring(self) -> None:
"""
Start monitoring the account update queue.
This is the main entry point for the account monitor.
"""
save_thread = threading.Thread(target=self.periodic_save)
save_thread.start()
logger.info("AccountMonitor: Save thread started.")
if self.notify:
low_health_report_thread = threading.Thread(target=
self.periodic_report_low_health_accounts)
low_health_report_thread.start()
logger.info("AccountMonitor: Low health report thread started.")
while self.running:
with self.condition:
while self.update_queue.empty():
logger.info("AccountMonitor: Waiting for queue to be non-empty.")
self.condition.wait()
next_update_time, address = self.update_queue.get()
# check for special value that indicates
# account should be skipped & removed from queue
if next_update_time == -1:
logger.info("AccountMonitor: %s has no position,"
" skipping and removing from queue", address)
continue
current_time = time.time()
if next_update_time > current_time:
self.update_queue.put((next_update_time, address))
self.condition.wait(next_update_time - current_time)
continue
self.executor.submit(self.update_account_liquidity, address)
def update_account_on_status_check_event(self, address: str, vault_address: str) -> None:
"""
Update an account based on a status check event.
Args:
address (str): The address of the account to update.
vault_address (str): The address of the vault associated with the account.
"""
# If the vault is not already tracked in the list, create it
if vault_address not in self.vaults:
self.vaults[vault_address] = Vault(vault_address, self.config)
logger.info("AccountMonitor: Vault %s added to vault list.", vault_address)
vault = self.vaults[vault_address]
# If the account is not in the list or the controller has changed, add it to the list
if (address not in self.accounts or
self.accounts[address].controller.address != vault_address):
account = Account(address, vault, self.config)
self.accounts[address] = account
logger.info("AccountMonitor: Adding %s to account list with controller %s.",
address,
vault.address)
else:
logger.info("AccountMonitor: %s already in list with controller %s.",
address,
vault.address)
self.update_account_liquidity(address)
def update_account_liquidity(self, address: str) -> None:
"""
Update the liquidity of a specific account.
Args:
address (str): The address of the account to update.
"""
try:
account = self.accounts.get(address)
if not account:
logger.error("AccountMonitor: %s not found in account list.",
address, exc_info=True)
return
logger.info("AccountMonitor: Updating %s liquidity.", address)
prev_scheduled_time = account.time_of_next_update
health_score = account.update_liquidity()
if health_score < 1:
try:
if self.notify:
if account.address in self.recently_posted_low_value:
if (time.time() - self.recently_posted_low_value[account.address]
< self.config.LOW_HEALTH_REPORT_INTERVAL
and account.value_borrowed < self.config.SMALL_POSITION_THRESHOLD):
logger.info("Skipping posting notification "
"for account %s, recently posted", address)
else:
try:
post_unhealthy_account_on_slack(address, account.controller.address,
health_score,
account.value_borrowed, self.config)
logger.info("Valut borrowed: %s", account.value_borrowed)
if account.value_borrowed < self.config.SMALL_POSITION_THRESHOLD:
self.recently_posted_low_value[account.address] = time.time()
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: "
"Failed to post low health notification "
"for account %s to slack: %s",
address, ex, exc_info=True)
logger.info("AccountMonitor: %s is unhealthy, "
"checking liquidation profitability.",
address)
(result, liquidation_data, params) = account.simulate_liquidation()
if result:
if self.notify:
try:
logger.info("AccountMonitor: Posting liquidation notification "
"to slack for account %s.", address)
post_liquidation_opportunity_on_slack(address,
account.controller.address,
liquidation_data, params, self.config)
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: "
"Failed to post liquidation notification "
" for account %s to slack: %s",
address, ex, exc_info=True)
if self.execute_liquidation:
try:
tx_hash, tx_receipt = Liquidator.execute_liquidation(
liquidation_data["tx"], self.config)
if tx_hash and tx_receipt:
logger.info("AccountMonitor: %s liquidated "
"on collateral %s.",
address,
liquidation_data["collateral_address"])
if self.notify:
try:
logger.info("AccountMonitor: Posting liquidation result"
" to slack for account %s.", address)
post_liquidation_result_on_slack(address,
account.controller.address,
liquidation_data,
tx_hash, self.config)
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: "
"Failed to post liquidation result "
" for account %s to slack: %s",
address, ex, exc_info=True)
# Update account health score after liquidation
# Need to know how healthy the account is after liquidation
# and if we need to liquidate again
account.update_liquidity()
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: "
"Failed to execute liquidation for account %s: %s",
address, ex, exc_info=True)
else:
logger.info("AccountMonitor: "
"Account %s is unhealthy but not profitable to liquidate.",
address)
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: "
"Exception simulating liquidation for account %s: %s",
address, ex, exc_info=True)
next_update_time = account.time_of_next_update
# if next update hasn't changed, means we already have a check scheduled
if next_update_time == prev_scheduled_time:
logger.info("AccountMonitor: %s next update already scheduled for %s",
address, time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(next_update_time)))
return
with self.condition:
self.update_queue.put((next_update_time, address))
self.condition.notify()
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: Exception updating account %s: %s",
address, ex, exc_info=True)
def save_state(self, local_save: bool = True) -> None:
"""
Save the current state of the account monitor.
Args:
local_save (bool, optional): Whether to save the state locally. Defaults to True.
"""
try:
state = {
"accounts": {address: account.to_dict()
for address, account in self.accounts.items()},
"vaults": {address: vault.address for address, vault in self.vaults.items()},
"queue": list(self.update_queue.queue),
"last_saved_block": self.latest_block,
}
if local_save:
with open(self.config.SAVE_STATE_PATH, "w", encoding="utf-8") as f:
json.dump(state, f)
else:
# Save to remote location
pass
self.last_saved_block = self.latest_block
logger.info("AccountMonitor: State saved at time %s up to block %s",
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
self.latest_block)
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: Failed to save state: %s", ex, exc_info=True)
def load_state(self, save_path: str, local_save: bool = True) -> None:
"""
Load the state of the account monitor from a file.
Args:
save_path (str): The path to the saved state file.
local_save (bool, optional): Whether the state is saved locally. Defaults to True.
"""
try:
if local_save and os.path.exists(save_path):
with open(save_path, "r", encoding="utf-8") as f:
state = json.load(f)
self.vaults = {address: Vault(address, self.config) for address in state["vaults"]}
logger.info("Loaded %s vaults: %s", len(self.vaults), list(self.vaults.keys()))
self.accounts = {address: Account.from_dict(data, self.vaults, self.config)
for address, data in state["accounts"].items()}
logger.info("Loaded %s accounts:", len(self.accounts))
for address, account in self.accounts.items():
logger.info(" Account %s: Controller: %s, "
"Health Score: %s, "
"Next Update: %s",
address,
account.controller.address,
account.current_health_score,
time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(account.time_of_next_update)))
self.rebuild_queue()
self.last_saved_block = state["last_saved_block"]
self.latest_block = self.last_saved_block
logger.info("AccountMonitor: State loaded from save"
" file %s from block %s to block %s",
save_path,
self.config.EVC_DEPLOYMENT_BLOCK,
self.latest_block)
elif not local_save:
# Load from remote location
pass
else:
logger.info("AccountMonitor: No saved state found.")
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: Failed to load state: %s", ex, exc_info=True)
def rebuild_queue(self):
"""
Rebuild queue based on current account health
"""
logger.info("Rebuilding queue based on current account health")
self.update_queue = queue.PriorityQueue()
for address, account in self.accounts.items():
try:
health_score = account.update_liquidity()
if account.current_health_score == math.inf:
logger.info("AccountMonitor: %s has no borrow, skipping", address)
continue
next_update_time = account.time_of_next_update
self.update_queue.put((next_update_time, address))
logger.info("AccountMonitor: %s added to queue"
" with health score %s, next update at %s",
address, health_score, time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(next_update_time)))
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: Failed to put account %s into rebuilt queue: %s",
address, ex, exc_info=True)
logger.info("AccountMonitor: Queue rebuilt with %s acccounts", self.update_queue.qsize())
def get_accounts_by_health_score(self):
"""
Get a list of accounts sorted by health score.
Returns:
List[Account]: A list of accounts sorted by health score.
"""
sorted_accounts = sorted(
self.accounts.values(),
key = lambda account: account.current_health_score
)
return [(account.address, account.owner, account.subaccount_number,
account.current_health_score, account.value_borrowed,
account.controller.vault_name, account.controller.vault_symbol)
for account in sorted_accounts]
def periodic_report_low_health_accounts(self):
"""
Periodically report accounts with low health scores.
"""
while self.running:
try:
sorted_accounts = self.get_accounts_by_health_score()
post_low_health_account_report(sorted_accounts, self.config)
time.sleep(self.config.LOW_HEALTH_REPORT_INTERVAL)
except Exception as ex: # pylint: disable=broad-except
logger.error("AccountMonitor: Failed to post low health account report: %s", ex,
exc_info=True)
@staticmethod
def create_from_save_state(chain_id: int, config: ChainConfig, save_path: str, local_save: bool = True) -> "AccountMonitor":
"""
Create an AccountMonitor instance from a saved state.
Args:
save_path (str): The path to the saved state file.
local_save (bool, optional): Whether the state is saved locally. Defaults to True.
Returns:
AccountMonitor: An AccountMonitor instance initialized from the saved state.
"""
monitor = AccountMonitor(chain_id=chain_id, config=config)
monitor.load_state(save_path, local_save)
return monitor
def periodic_save(self) -> None:
"""
Periodically save the state of the account monitor.
Should be run in a standalone thread.
"""
while self.running:
time.sleep(self.config.SAVE_INTERVAL)
self.save_state()
def stop(self) -> None:
"""
Stop the account monitor and save its current state.
"""
self.running = False
with self.condition:
self.condition.notify_all()
self.executor.shutdown(wait=True)
self.save_state()
class PullOracleHandler:
"""
Class to handle checking and updating Pull oracles.
"""
def __init__(self):
pass
@staticmethod
def get_account_values_with_pyth_and_redstone_simulation(vault, account_address, pyth_feed_ids, redstone_feed_ids, config: ChainConfig):
pyth_update_data = PullOracleHandler.get_pyth_update_data(pyth_feed_ids)
pyth_update_fee = PullOracleHandler.get_pyth_update_fee(pyth_update_data, config)
redstone_addresses, redstone_update_data = PullOracleHandler.get_redstone_update_payloads(redstone_feed_ids)
liquidator = config.liquidator
result = liquidator.functions.simulatePythAndRedstoneAccountStatus(
[pyth_update_data], pyth_update_fee, redstone_update_data, redstone_addresses, vault.address, account_address
).call({
"value": pyth_update_fee
})
return result[0], result[1]
@staticmethod
def check_liquidation_with_pyth_and_redstone_simulation(vault, liquidator_address, borrower_address, collateral_address, pyth_feed_ids, redstone_feed_ids, config: ChainConfig):
pyth_update_data = PullOracleHandler.get_pyth_update_data(pyth_feed_ids)
pyth_update_fee = PullOracleHandler.get_pyth_update_fee(pyth_update_data, config)
redstone_addresses, redstone_update_data = PullOracleHandler.get_redstone_update_payloads(redstone_feed_ids)
liquidator = config.liquidator
result = liquidator.functions.simulatePythAndRedstoneLiquidation(
[pyth_update_data], pyth_update_fee, redstone_update_data, redstone_addresses, vault.address, liquidator_address, borrower_address, collateral_address
).call({
"value": pyth_update_fee
})
return result[0], result[1]
@staticmethod
def get_account_values_with_pyth_batch_simulation(vault, account_address, feed_ids, config: ChainConfig):
update_data = PullOracleHandler.get_pyth_update_data(feed_ids)
update_fee = PullOracleHandler.get_pyth_update_fee(update_data, config)
liquidator = config.liquidator
result = liquidator.functions.simulatePythUpdateAndGetAccountStatus(
[update_data], update_fee, vault.address, account_address
).call({
"value": update_fee
})
return result[0], result[1]
@staticmethod
def check_liquidation_with_pyth_batch_simulation(vault, liquidator_address, borrower_address,
collateral_address, feed_ids, config: ChainConfig):
update_data = PullOracleHandler.get_pyth_update_data(feed_ids)
update_fee = PullOracleHandler.get_pyth_update_fee(update_data, config)
liquidator = config.liquidator
result = liquidator.functions.simulatePythUpdateAndCheckLiquidation(
[update_data], update_fee, vault.address,
liquidator_address, borrower_address, collateral_address
).call({
"value": update_fee
})
return result[0], result[1]
@staticmethod
def get_account_values_with_redstone_batch_simulation(vault, account_address, feed_ids, config: ChainConfig):
addresses, update_data = PullOracleHandler.get_redstone_update_payloads(feed_ids)
liquidator = config.liquidator
result = liquidator.functions.simulateRedstoneUpdateAndGetAccountStatus(
update_data, addresses, vault.address, account_address
).call()
return result[0], result[1]
@staticmethod
def check_liquidation_with_redstone_batch_simulation(vault,
liquidator_address,
borrower_address,
collateral_address,
feed_ids, config: ChainConfig):
addresses, update_data = PullOracleHandler.get_redstone_update_payloads(feed_ids)
liquidator = config.liquidator
result = liquidator.functions.simulateRedstoneUpdateAndCheckLiquidation(
update_data, addresses, vault.address,
liquidator_address, borrower_address, collateral_address
).call()
return result[0], result[1]
@staticmethod
def get_feed_ids(vault, config: ChainConfig):
try:
oracle_address = vault.oracle_address
oracle = create_contract_instance(oracle_address, config.ORACLE_ABI_PATH, config)
unit_of_account = vault.unit_of_account
collateral_vault_list = vault.get_ltv_list()
asset_list = [Vault(collateral_vault, config).underlying_asset_address
for collateral_vault in collateral_vault_list]
asset_list.append(vault.underlying_asset_address)
pyth_feed_ids = set()
redstone_feed_ids = set()
# logger.info("PullOracleHandler: Trying to get feed ids for oracle %s with assets %s and unit of account %s", oracle_address, collateral_vault_list, unit_of_account)
for asset in asset_list:
(_, _, _, configured_oracle_address) = oracle.functions.resolveOracle(0, asset, unit_of_account).call()
configured_oracle = create_contract_instance(configured_oracle_address,
config.ORACLE_ABI_PATH, config)
try:
configured_oracle_name = configured_oracle.functions.name().call()
except Exception as ex: # pylint: disable=broad-except
logger.info("PullOracleHandler: Error calling contract for oracle"
" at %s, asset %s: %s", configured_oracle_address, asset, ex)
continue
if configured_oracle_name == "PythOracle":
logger.info("PullOracleHandler: Pyth oracle found for vault %s: "
"Address - %s", vault.address, configured_oracle_address)
pyth_feed_ids.add(configured_oracle.functions.feedId().call().hex())
elif configured_oracle_name == "RedstoneCoreOracle":
logger.info("PullOracleHandler: Redstone oracle found for"
" vault %s: Address - %s",
vault.address, configured_oracle_address)
redstone_feed_ids.add((configured_oracle_address,
configured_oracle.functions.feedId().call().hex()))
elif configured_oracle_name == "CrossAdapter":
pyth_ids, redstone_ids = PullOracleHandler.resolve_cross_oracle(
configured_oracle, config)
pyth_feed_ids.update(pyth_ids)
redstone_feed_ids.update(redstone_ids)
return list(pyth_feed_ids), list(redstone_feed_ids)
except Exception as ex: # pylint: disable=broad-except
logger.error("PullOracleHandler: Error calling contract: %s", ex, exc_info=True)
@staticmethod
def resolve_cross_oracle(cross_oracle, config):
pyth_feed_ids = set()
redstone_feed_ids = set()
oracle_base_address = cross_oracle.functions.oracleBaseCross().call()
oracle_base = create_contract_instance(oracle_base_address, config.ORACLE_ABI_PATH, config)
oracle_base_name = oracle_base.functions.name().call()
if oracle_base_name == "PythOracle":
pyth_feed_ids.add(oracle_base.functions.feedId().call().hex())
elif oracle_base_name == "RedstoneCoreOracle":
redstone_feed_ids.add((oracle_base_address,
oracle_base.functions.feedId().call().hex()))
elif oracle_base_name == "CrossOracle":
pyth_ids, redstone_ids = PullOracleHandler.resolve_cross_oracle(oracle_base, config)
pyth_feed_ids.add(pyth_ids)
redstone_feed_ids.add(redstone_ids)
oracle_quote_address = cross_oracle.functions.oracleCrossQuote().call()
oracle_quote = create_contract_instance(oracle_quote_address, config.ORACLE_ABI_PATH, config)
oracle_quote_name = oracle_quote.functions.name().call()
if oracle_quote_name == "PythOracle":
pyth_feed_ids.add(oracle_quote.functions.feedId().call().hex())
elif oracle_quote_name == "RedstoneCoreOracle":
redstone_feed_ids.add((oracle_quote_address,
oracle_quote.functions.feedId().call().hex()))
elif oracle_quote_name == "CrossOracle":
pyth_ids, redstone_ids = PullOracleHandler.resolve_cross_oracle(oracle_quote, config)
pyth_feed_ids.update(pyth_ids)
redstone_feed_ids.update(redstone_ids)
return pyth_feed_ids, redstone_feed_ids
@staticmethod
def get_pyth_update_data(feed_ids):
logger.info("PullOracleHandler: Getting update data for feeds: %s", feed_ids)
pyth_url = "https://hermes.pyth.network/v2/updates/price/latest?"
for feed_id in feed_ids:
pyth_url += "ids[]=" + feed_id + "&"
pyth_url = pyth_url[:-1]
api_return_data = make_api_request(pyth_url, {}, {})
return "0x" + api_return_data["binary"]["data"][0]
@staticmethod
def get_pyth_update_fee(update_data, config):
logger.info("PullOracleHandler: Getting update fee for data: %s", update_data)
pyth = create_contract_instance(config.PYTH, config.PYTH_ABI_PATH, config)
return pyth.functions.getUpdateFee([update_data]).call()
@staticmethod
def get_redstone_update_payloads(redstone_oracle_data):
addresses = []
feed_ids = []
for data in redstone_oracle_data:
addresses.append(data[0])
feed_ids.append(data[1])
feed_ids_json = json.dumps(feed_ids)
result = subprocess.run(
["node", "redstone_script/getRedstonePayload.js", feed_ids_json],
capture_output=True,
text=True,
check=True
)
if result.returncode != 0:
logger.error("PullOracleHandler: Error getting update payload")
logger.error("stderr: %s", result.stderr)
logger.error("stdout: %s", result.stdout)
return None
result = json.loads(result.stdout)
output_data = []
for i in range(len(result)):
output_data.append(result[i]["data"])
return addresses, output_data
class EVCListener:
"""
Listener class for monitoring EVC events.
Primarily intended to listen for AccountStatusCheck events.
Contains handling for processing historical blocks in a batch system on startup.
"""
def __init__(self, account_monitor: AccountMonitor, config: ChainConfig):
self.config = config
self.w3 = config.w3
self.account_monitor = account_monitor
self.evc_instance = config.evc
self.scanned_blocks = set()
def start_event_monitoring(self) -> None:
"""
Start monitoring for EVC events.
Scans from last scanned block stored by account monitor
up to the current block number (minus 1 to try to account for reorgs).