Skip to content

Commit

Permalink
Merge pull request #320 from djeck1432/fix/pylint-issues
Browse files Browse the repository at this point in the history
Fix/pylint issues
  • Loading branch information
djeck1432 authored Dec 2, 2024
2 parents 326e698 + d774edf commit 872aa74
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 220 deletions.
4 changes: 2 additions & 2 deletions spotnet_tracker/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ def claim_airdrop_task() -> None:
"""
try:
logger.info("Running claim_airdrop_task.")
logger.info(f"Task started at: {time.strftime("%a, %d %b %Y %H:%M:%S")}")
logger.info("Task started at: ",time.strftime("%a, %d %b %Y %H:%M:%S"))
airdrop_claimer = AirdropClaimer()
asyncio.run(airdrop_claimer.claim_airdrops())
logger.info(f"Task started at: {time.strftime("%a, %d %b %Y %H:%M:%S")}")
logger.info("Task started at: ", time.strftime("%a, %d %b %Y %H:%M:%S"))
except Exception as e:
logger.error(f"Error in claiming airdrop task: {e}")
4 changes: 3 additions & 1 deletion web_app/api/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ async def get_dashboard(wallet_id: str) -> DashboardResponse:
else collections.defaultdict(lambda: None)
)
# Fetch zkLend position for the wallet ID
health_ratio = await HealthRatioMixin.get_health_ratio(contract_address, first_opened_position.token_symbol)
health_ratio = await HealthRatioMixin.get_health_ratio(
contract_address, first_opened_position["token_symbol"]
)

# Fetch balances (assuming you have a method for this)
wallet_balances = await DashboardMixin.get_wallet_balances(wallet_id)
Expand Down
54 changes: 47 additions & 7 deletions web_app/contract_tools/blockchain_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ class RepayDataException(Exception):
"""
Custom RepayDataException for handling errors while repaying data
"""

pass


Expand Down Expand Up @@ -111,8 +110,13 @@ def _build_ekubo_pool_key(
}

async def _get_pool_price(self, pool_key, is_token1: bool):
"""Calculate Ekubo pool price"""
"""
Calculate Ekubo pool price.
:param pool_key: The pool key dictionary.
:param is_token1: Boolean indicating if the token is token1.
:return: The calculated pool price.
"""
ekubo_contract = await Contract.from_address(
EKUBO_MAINNET_ADDRESS, provider=self.client
)
Expand All @@ -137,13 +141,24 @@ async def _get_pool_price(self, pool_key, is_token1: bool):
)

async def _get_zklend_reserve(self, token_address: str) -> list[int]:
"""
Get ZkLend reserve data for a specific token.
:param token_address: The address of the token.
:return: A list of reserve data.
"""
return await self._func_call(
self._convert_address(ZKLEND_MARKET_ADDRESS),
"get_reserve_data",
[self._convert_address(token_address)],
)

async def get_available_zklend_reserves(self) -> dict[str, list[int]]:
"""
Get available ZkLend reserves for all tokens.
:return: A dictionary with token names as keys and reserve data as values.
"""
tasks = [
self._get_zklend_reserve(token.address) for token in TokenParams.tokens()
]
Expand All @@ -155,10 +170,22 @@ async def get_available_zklend_reserves(self) -> dict[str, list[int]]:
}

async def get_z_addresses(self) -> dict[str, tuple[int, int]]:
"""
Get ZkLend addresses.
:return: A dictionary with token names as keys and tuples of addresses as values.
"""
reserves = await self.get_available_zklend_reserves()
return {token: (reserve[1], reserve[2]) for token, reserve in reserves.items()}

async def get_zklend_debt(self, user: str, token: str) -> list[int]:
"""
Get ZkLend debt for a specific user and token.
:param user: The address of the user.
:param token: The address of the token.
:return: A list of debt data.
"""
return await self._func_call(
self._convert_address(ZKLEND_MARKET_ADDRESS),
"get_user_debt_for_token",
Expand Down Expand Up @@ -208,6 +235,12 @@ async def get_loop_liquidity_data(
"""
Get data for Spotnet liquidity looping call.
:param deposit_token: The address of the deposit token.
:param amount: The amount to deposit.
:param multiplier: The multiplier for the deposit.
:param wallet_id: The wallet ID.
:param borrowing_token: The address of the borrowing token.
:return: A dictionary with liquidity data.
"""
# Get pool key
pool_key = self._build_ekubo_pool_key(deposit_token, borrowing_token)
Expand Down Expand Up @@ -242,7 +275,13 @@ async def get_loop_liquidity_data(
}

async def get_repay_data(self, deposit_token: str, borrowing_token: str) -> dict:
"""Get data for Spotnet position closing."""
"""
Get data for Spotnet position closing.
:param deposit_token: The address of the deposit token.
:param borrowing_token: The address of the borrowing token.
:return: A dictionary with repay data.
"""
pool_key = self._build_ekubo_pool_key(deposit_token, borrowing_token)
decimals_sum = TokenParams.get_token_decimals(
deposit_token
Expand Down Expand Up @@ -280,12 +319,13 @@ async def get_repay_data(self, deposit_token: str, borrowing_token: str) -> dict
async def claim_airdrop(self, contract_address: str, proofs: list[str]) -> None:
"""
Claims an airdrop on the Starknet blockchain.
:param contract_address: airdrop contract address
:param proofs: list of proof strings
:return: True if the claim was successful, False otherwise
:param contract_address: The airdrop contract address.
:param proofs: A list of proof strings.
:return: None
"""
return await self._func_call(
addr=self._convert_address(contract_address),
selector="claim",
calldata=proofs,
)
)
4 changes: 4 additions & 0 deletions web_app/contract_tools/mixins/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
"""
Import all mixins here to make them available
to the rest of the application.
"""
from .dashboard import DashboardMixin
from .health_ratio import HealthRatioMixin
from .deposit import DepositMixin
Expand Down
6 changes: 5 additions & 1 deletion web_app/contract_tools/mixins/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ async def get_wallet_balances(cls, holder_address: str) -> Dict[str, str]:
return wallet_balances

@classmethod
async def get_zklend_position(cls, contract_address: str, position: "Position") -> DashboardResponse:
async def get_zklend_position(
cls,
contract_address: str,
position: "Position"
) -> DashboardResponse:
"""
Get the zkLend position for the given wallet ID.
:param contract_address: contract address
Expand Down
42 changes: 42 additions & 0 deletions web_app/contract_tools/mixins/health_ratio.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
"""
HealthRatioMixin is a mixin class to calculate the health ratio of a deposit contract.
"""
import asyncio
from decimal import Decimal

Expand All @@ -14,9 +17,18 @@


class HealthRatioMixin:
"""
A mixin class to calculate the health ratio of a deposit contract.
"""

@classmethod
async def _get_pragma_price(cls, token: str) -> Decimal:
"""
Get the price of a token from the Pragma API.
:param token: The token symbol (e.g., "ETH", "USDC").
:return: The price of the token as a Decimal.
"""
decimals = 10**8 if token not in ("USDC", "USDT") else 10**6
data = await PRAGMA.get_spot(f"{token}/USD", AggregationMode.MEDIAN)
return Decimal(data.price / decimals)
Expand All @@ -25,6 +37,15 @@ async def _get_pragma_price(cls, token: str) -> Decimal:
async def _get_z_balances(
cls, reserves: dict[str, tuple[int, int]], deposit_contract_address: str
) -> dict[str, Decimal]:
"""
Get the balances of tokens in a deposit contract.
:param reserves: A dictionary of token reserves with token symbols as keys
and tuples of (decimals, address) as values.
:param deposit_contract_address: The address of the deposit contract.
:return: A dictionary of token balances with token symbols as keys
and balances as Decimal values.
"""
tasks = [
CLIENT.get_balance(z_data[1], deposit_contract_address, z_data[0])
for z_data in reserves.values()
Expand All @@ -39,6 +60,13 @@ async def _get_z_balances(
async def _get_deposited_tokens(
cls, deposit_contract_address: str
) -> dict[str, Decimal]:
"""
Get the deposited tokens and their amounts in a deposit contract.
:param deposit_contract_address: The address of the deposit contract.
:return: A dictionary of deposited tokens with token symbols as keys
and amounts as Decimal values.
"""
reserves = await CLIENT.get_z_addresses()
deposits = await cls._get_z_balances(reserves, deposit_contract_address)
return {
Expand All @@ -49,6 +77,13 @@ async def _get_deposited_tokens(

@classmethod
async def _get_pragma_prices(cls, tokens: set) -> dict[str, Decimal]:
"""
Get the prices of multiple tokens from the Pragma API.
:param tokens: A set of token symbols.
:return: A dictionary of token prices with token symbols as
keys and prices as Decimal values.
"""
tasks = [cls._get_pragma_price(token) for token in tokens]
return {
token: price for token, price in zip(tokens, await asyncio.gather(*tasks))
Expand All @@ -58,6 +93,13 @@ async def _get_pragma_prices(cls, tokens: set) -> dict[str, Decimal]:
async def get_health_ratio(
cls, deposit_contract_address: str, borrowed_token: str
) -> str:
"""
Calculate the health ratio of a deposit contract.
:param deposit_contract_address: The address of the deposit contract.
:param borrowed_token: The symbol of the borrowed token.
:return: The health ratio as a string.
"""
deposits = await cls._get_deposited_tokens(deposit_contract_address)
debt_raw = await CLIENT.get_zklend_debt(
deposit_contract_address, TokenParams.get_token_address(borrowed_token)
Expand Down
18 changes: 0 additions & 18 deletions web_app/tests/test_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,24 +62,6 @@ async def generic_exception_handler(request: Request, exc: Exception):

MOCK_WALLET_BALANCES = {"ETH": "10.5", "USDC": "1000.0"}

MOCK_ZKLEND_POSITION = {
"products": [
{
"token": "ETH",
"supplied_amount": "5.0",
"borrowed_amount": "0",
"is_collateral": True,
},
{
"token": "ETH",
"supplied_amount": "0",
"borrowed_amount": "500.0",
"is_collateral": False,
},
]
}


@pytest.mark.asyncio
async def test_get_dashboard_success():
"""Test successful retrieval of dashboard data."""
Expand Down
Loading

0 comments on commit 872aa74

Please sign in to comment.