from datetime import datetime from aiogram.utils.web_app import safe_parse_webapp_init_data from sanic import response from app.core._blockchain.ton.connect import TonConnect, unpack_wallet_info, WalletConnection from app.core._config import TELEGRAM_API_KEY from app.core.models.user import User from app.core.logger import make_log async def pause_ton_connection(ton_connect: TonConnect): if ton_connect.connected: ton_connect._sdk_client.pause_connection() async def s_api_v1_tonconnect_new(request): if not request.ctx.user: return response.json({"error": "User not found"}, status=400) wallet_app_name = request.args.get("wallet_app_name", "tonkeeper") db_session = request.ctx.db_session user = request.ctx.user memory = request.ctx.memory ton_connect, ton_connection = TonConnect.by_user(db_session, user) await ton_connect.restore_connection() make_log("TonConnect_API", f"SDK connected?: {ton_connect.connected}", level='info') if ton_connect.connected: return response.json({"error": "Already connected"}, status=400) connection_link = await ton_connect.new_connection(wallet_app_name) ton_connect.connected memory.add_task(pause_ton_connection, ton_connect, delay_s=60 * 3) make_log("TonConnect_API", f"New connection link for {wallet_app_name}: {connection_link}", level='debug') return response.json({ "connection_link": connection_link, "wallet_app_name": wallet_app_name }) async def s_api_v1_tonconnect_logout(request): if not request.ctx.user: return response.json({"error": "User not found"}, status=400) db_session = request.ctx.db_session user = request.ctx.user memory = request.ctx.memory wallet_connections = db_session.query(WalletConnection).filter( WalletConnection.user_id == user.id, WalletConnection.invalidated == False ).all() for wallet_connection in wallet_connections: wallet_connection.invalidated = True db_session.commit() return response.json({"success": True})