|
| 1 | +import aiohttp |
| 2 | +import config |
| 3 | +from enums.cryptocurrency import Cryptocurrency |
| 4 | +from enums.withdraw_type import WithdrawType |
| 5 | +from models.withdrawal import WithdrawalDTO |
| 6 | + |
| 7 | + |
| 8 | +class CryptoApiWrapper: |
| 9 | + LTC_API_BASENAME_TX = "https://litecoinspace.org/tx/" |
| 10 | + BTC_API_BASENAME_TX = "https://mempool.space/tx/" |
| 11 | + SOL_API_BASENAME_TX = "https://solscan.io/tx/" |
| 12 | + ETH_API_BASENAME_TX = "https://etherscan.io/tx/" |
| 13 | + BNB_API_BASENAME_TX = "https://bscscan.com/tx/" |
| 14 | + |
| 15 | + @staticmethod |
| 16 | + async def fetch_api_request(url: str, params: dict | None = None, method: str = "GET", data: str | None = None, |
| 17 | + headers: dict | None = None) -> dict: |
| 18 | + async with aiohttp.ClientSession() as session: |
| 19 | + async with session.request(method, url, params=params, data=data, headers=headers) as response: |
| 20 | + if response.status == 200: |
| 21 | + data = await response.json() |
| 22 | + return data |
| 23 | + |
| 24 | + @staticmethod |
| 25 | + async def get_crypto_prices() -> dict: |
| 26 | + url = f"https://api.coingecko.com/api/v3/simple/price" |
| 27 | + params = { |
| 28 | + "ids": "bitcoin,litecoin,solana,ethereum,binancecoin", |
| 29 | + "vs_currencies": "usd,eur,gbp,jpy,cad" |
| 30 | + } |
| 31 | + return await CryptoApiWrapper.fetch_api_request(url, params) |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + async def get_wallet_balance() -> dict: |
| 35 | + url = f"{config.KRYPTO_EXPRESS_API_URL}/wallet" |
| 36 | + headers = { |
| 37 | + "X-Api-Key": config.KRYPTO_EXPRESS_API_KEY |
| 38 | + } |
| 39 | + response = await CryptoApiWrapper.fetch_api_request( |
| 40 | + url, |
| 41 | + headers=headers |
| 42 | + ) |
| 43 | + return {k: v for k, v in response.items() if v > 0} |
| 44 | + |
| 45 | + @staticmethod |
| 46 | + async def withdrawal(cryptocurrency: Cryptocurrency, to_address: str, only_calculate: bool) -> WithdrawalDTO: |
| 47 | + url = f"{config.KRYPTO_EXPRESS_API_URL}/wallet/withdrawal" |
| 48 | + headers = { |
| 49 | + "X-Api-Key": config.KRYPTO_EXPRESS_API_KEY, |
| 50 | + "Content-Type": "application/json" |
| 51 | + } |
| 52 | + body = WithdrawalDTO( |
| 53 | + withdrawType=WithdrawType.ALL, |
| 54 | + cryptoCurrency=cryptocurrency.name, |
| 55 | + toAddress=to_address, |
| 56 | + onlyCalculate=only_calculate |
| 57 | + ) |
| 58 | + response = await CryptoApiWrapper.fetch_api_request( |
| 59 | + url, |
| 60 | + method="POST", |
| 61 | + data=body.model_dump_json(), |
| 62 | + headers=headers |
| 63 | + ) |
| 64 | + return WithdrawalDTO.model_validate(response) |
0 commit comments