Files
plm-lottery/app/api/routes/withdrawals.py
T
davideandClaude Sonnet 5 8380b80d12 Add withdrawal flow
Builds and broadcasts a user->external-address PSBT with change back to
the user's own address, fee deducted from the withdrawn amount, and
registers the confirmation handler that marks the withdrawal confirmed.
Shares the per-user lock with bets so a build never races a spend from
the same UTXO set.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 10:26:25 +02:00

50 lines
1.6 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import get_current_user
from app.db.models import User
from app.db.session import get_session
from app.withdrawals.service import WithdrawalError, request_withdrawal
router = APIRouter(prefix="/withdrawals", tags=["withdrawals"])
class WithdrawalRequest(BaseModel):
external_address: str
amount_sats: int
class WithdrawalResponse(BaseModel):
txid: str
amount_requested_sats: int
amount_sent_sats: int
status: str
@router.post("", response_model=WithdrawalResponse, status_code=status.HTTP_201_CREATED)
async def create_withdrawal(
body: WithdrawalRequest,
request: Request,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
) -> WithdrawalResponse:
listener = request.app.state.electrum_listener
if listener.client is None:
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "not connected to the network, try again shortly")
async with request.app.state.user_locks.acquire(user.id):
try:
withdrawal = await request_withdrawal(
session, listener.client, user, body.external_address, body.amount_sats
)
except WithdrawalError as exc:
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
return WithdrawalResponse(
txid=withdrawal.txid,
amount_requested_sats=withdrawal.amount_requested_sats,
amount_sent_sats=withdrawal.amount_sent_sats,
status=withdrawal.status,
)