5
5
"""
6
6
7
7
from decimal import Decimal
8
+ from sqlalchemy import select
8
9
9
10
from shared .starknet_client import StarknetClient
11
+ from shared .db import session
12
+ from apps .data_handler .models import VesuPosition
10
13
from starknet_py .hash .selector import get_selector_from_name
11
14
12
15
@@ -23,7 +26,8 @@ class VesuLoanEntity:
23
26
def __init__ (self ):
24
27
"""Initialize Starknet client and storage."""
25
28
self .client = StarknetClient ()
26
- self .mock_db = {}
29
+ self .session = session
30
+ # self.mock_db = {}
27
31
self ._cache = {}
28
32
self .last_processed_block = 654244 # First VESU event block
29
33
@@ -42,24 +46,27 @@ async def _get_token_decimals(self, token_address: int) -> Decimal:
42
46
return Decimal (10 ) ** Decimal (decimals )
43
47
return Decimal ("Inf" )
44
48
45
- async def calculate_health_factor (self , user_address : int ) -> dict :
49
+ async def calculate_health_factor (self , user_address : int ) -> dict [ str , Decimal ] :
46
50
"""
47
51
Calculate health factors for all positions of a user.
48
52
49
53
:param user_address: User address in int format
50
-
51
- :return: Dictionary with pool IDs as keys and health factors as values
54
+ :return: Dictionary with pool IDs (in hex) as keys and health factors as values
52
55
"""
56
+ result = await self .session .execute (
57
+ select (VesuPosition ).where (VesuPosition .user == str (user_address ))
58
+ )
59
+ positions = result .scalars ().all ()
53
60
54
- user_positions = {k : v for k , v in self .mock_db .items () if k [0 ] == user_address }
55
-
56
- if not user_positions :
61
+ if not positions :
57
62
return {}
58
63
59
64
results = {}
60
- for (_ , pool_id ), position_data in user_positions .items ():
61
- collateral_asset = position_data ["collateral_asset" ]
62
- debt_asset = position_data ["debt_asset" ]
65
+
66
+ for pos in positions :
67
+ pool_id = int (pos .pool_id )
68
+ collateral_asset = int (pos .collateral_asset )
69
+ debt_asset = int (pos .debt_asset )
63
70
64
71
if collateral_asset == 0 or debt_asset == 0 :
65
72
results [hex (pool_id )] = Decimal ("inf" )
@@ -351,10 +358,15 @@ async def update_positions_data(self) -> None:
351
358
user = event_keys [4 ]
352
359
block_number = event .block_number
353
360
354
- self .mock_db [(user , pool_id )] = {
355
- "pool_id" : pool_id ,
356
- "collateral_asset" : collateral_asset ,
357
- "debt_asset" : debt_asset ,
358
- "block_number" : block_number ,
359
- }
361
+ position = VesuPosition (
362
+ user = str (user ),
363
+ pool_id = str (pool_id ),
364
+ collateral_asset = str (collateral_asset ),
365
+ debt_asset = str (debt_asset ),
366
+ block_number = block_number ,
367
+ )
368
+ self .session .add (position )
369
+
360
370
self .last_processed_block = max (self .last_processed_block , block_number )
371
+
372
+ await self .session .commit ()
0 commit comments