70 lines
2.5 KiB
Python
70 lines
2.5 KiB
Python
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 sqlalchemy import select, and_
|
|
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
|
|
# Try restore last connection from DB
|
|
ton_connection = (await db_session.execute(select(WalletConnection).where(
|
|
and_(
|
|
WalletConnection.user_id == user.id,
|
|
WalletConnection.invalidated == False,
|
|
WalletConnection.network == 'ton'
|
|
)
|
|
).order_by(WalletConnection.created.desc()))).scalars().first()
|
|
if ton_connection:
|
|
ton_connect = TonConnect.by_key(ton_connection.keys["connection_key"])
|
|
await ton_connect.restore_connection()
|
|
else:
|
|
ton_connect = TonConnect()
|
|
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
|
|
|
|
result = await db_session.execute(select(WalletConnection).where(
|
|
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False)
|
|
))
|
|
wallet_connections = result.scalars().all()
|
|
for wallet_connection in wallet_connections:
|
|
wallet_connection.invalidated = True
|
|
await db_session.commit()
|
|
return response.json({"success": True})
|