Skip to content

Commit

Permalink
add new dashboard logic
Browse files Browse the repository at this point in the history
  • Loading branch information
djeck1432 committed Sep 26, 2024
1 parent 4ba97a5 commit 24fc73d
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 0 deletions.
59 changes: 59 additions & 0 deletions web_app/api/serializers/dashboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from decimal import Decimal
from pydantic import BaseModel, Field, validator
from typing import Optional, Dict, List

from web_app.contract_tools.constants import TokenParams


class PositionData(BaseModel):
apy: str
group: Optional[int]
lending: bool
collateral: bool
debt: bool


class Position(BaseModel):
token_address: Optional[str] = Field(None, alias="tokenAddress") # Made optional
total_balances: Dict[str, str] = Field(alias="totalBalances")
data: PositionData

@validator('total_balances', pre=True, each_item=False)
def convert_total_balances(cls, balances, values):
"""
Convert total_balances to their decimal values based on token decimals.
"""
converted_balances = {}
for token_address, balance in balances.items():
try:
# Fetch the token decimals from TokenParams
decimals = TokenParams.get_token_decimals(token_address)
# Convert the balance using the decimals
converted_balances[token_address] = str(Decimal(balance) / Decimal(10 ** decimals))
except ValueError as e:
raise ValueError(f"Error in balance conversion: {str(e)}")
return converted_balances




class GroupData(BaseModel):
health_ratio: str = Field(alias="healthRatio")


class Product(BaseModel):
name: str
manage_url: Optional[str] = Field(None, alias="manageUrl") # This field might not always be present
groups: Dict[str, GroupData]
positions: Optional[List[Position]]
type: str


class Dapp(BaseModel):
dappId: str
products: List[Product]


class ZkLendPositionResponse(BaseModel):
dapps: List[Dapp]
nonce: int
Empty file added web_app/api/tools/__init__.py
Empty file.
54 changes: 54 additions & 0 deletions web_app/api/tools/redis_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import redis.asyncio as aioredis

WALLET_ID_EXPIRATION = 60 * 60 * 24 # 24 hours


class RedisCache:
_instance = None # Singleton instance

def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(RedisCache, cls).__new__(cls, *args, **kwargs)
return cls._instance

def __init__(self, redis_url: str = "redis://localhost:6379"):
if not hasattr(self, 'redis_url'): # Ensure initialization happens only once
self.redis_url = redis_url
self.redis = None

async def connect(self):
"""
Connect to the Redis server.
"""
if self.redis is None: # Only connect if not already connected
self.redis = await aioredis.from_url(self.redis_url, decode_responses=True)

async def close(self):
"""
Close the Redis connection.
"""
if self.redis:
await self.redis.close()
self.redis = None # Reset the connection

async def set(self, key: str, value: str, expiration: int = WALLET_ID_EXPIRATION):
"""
Set a key-value pair in Redis with optional expiration time.
"""
await self.redis.set(key, value, ex=expiration)

async def get(self, key: str):
"""
Get a value from Redis by key.
"""
return await self.redis.get(key)

async def delete(self, key: str):
"""
Delete a key from Redis.
"""
await self.redis.delete(key)


# Global singleton instance
redis_cache = RedisCache()

0 comments on commit 24fc73d

Please sign in to comment.