from __future__ import annotations import aiohttp import logging from config import CRYPTO_PAY_TOKEN async def _get_usdt_rub_rate(session: aiohttp.ClientSession) -> float: rate = 90.0 async with session.get( "https://testnet-pay.crypt.bot/api/getExchangeRates", headers={"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN}, ) as response: data = await response.json() if data.get("ok"): for item in data.get("result", []): if item.get("source") == "USDT" and item.get("target") == "RUB": rate = float(item["rate"]) break return rate async def create_crypto_check(amount_rub: float) -> str | None: try: headers = {"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN} async with aiohttp.ClientSession() as session: usdt_rub = await _get_usdt_rub_rate(session) amount_usdt = round(amount_rub / usdt_rub, 4) async with session.post( "https://testnet-pay.crypt.bot/api/createCheck", headers=headers, json={"asset": "USDT", "amount": str(amount_usdt)}, ) as response: data = await response.json() if data.get("ok"): return data["result"]["bot_check_url"] except Exception as exc: logging.error("crypto check: %s", exc) return None async def create_treasury_invoice(amount_rub: float) -> tuple[str, int, float] | None: try: headers = {"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN} async with aiohttp.ClientSession() as session: usdt_rub = await _get_usdt_rub_rate(session) amount_usdt = round(amount_rub / usdt_rub, 4) async with session.post( "https://testnet-pay.crypt.bot/api/createInvoice", headers=headers, json={ "asset": "USDT", "amount": str(amount_usdt), "description": f"Treasury +{amount_rub} RUB", "payload": f"treasury_{amount_rub}", }, ) as response: data = await response.json() if data.get("ok"): result = data["result"] return result["pay_url"], int(result["invoice_id"]), amount_usdt except Exception as exc: logging.error("create_treasury_invoice: %s", exc) return None async def check_treasury_invoice(invoice_id: int) -> bool: try: headers = {"Crypto-Pay-API-Token": CRYPTO_PAY_TOKEN} async with aiohttp.ClientSession() as session: async with session.get( f"https://testnet-pay.crypt.bot/api/getInvoices?invoice_ids={invoice_id}", headers=headers, ) as response: data = await response.json() if data.get("ok"): items = data.get("result", {}).get("items", []) return bool(items and items[0].get("status") == "paid") except Exception as exc: logging.error("check_treasury_invoice: %s", exc) return False