Files
plm-lottery/app/wallet/balance.py
T
davideandClaude Sonnet 5 f1261584ff Add wallet key derivation and PSBT building
BIP84 derivation of per-user P2WPKH addresses and the pool address from
the encrypted master xprv (app/wallet/hd.py, keystore.py), the PLM
mainnet chain params (plm_network.py), and PSBT construction for bets/
payouts/withdrawals with change-output and fee-estimation logic
(psbt_builder.py).

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

17 lines
724 B
Python

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import User, UtxoEvent
async def recompute_balance(session: AsyncSession, user_id: int) -> int:
"""Source of truth: sum of this user's confirmed, unspent UTXOs. Updates and
returns the read-cache column (User.cached_balance_sats). Must be called
within the same transaction as whatever inserted/updated utxo_events rows."""
balance = await session.scalar(
select(func.sum(UtxoEvent.amount_sats)).where(UtxoEvent.user_id == user_id, UtxoEvent.spent_txid.is_(None))
)
user = await session.get(User, user_id)
user.cached_balance_sats = balance or 0
return user.cached_balance_sats