One Ledger interface (deposit, bet, confirm, reject, exclude, payout) with a simulated implementation chosen by LEDGER_BACKEND, refused on mainnet. Every operation is a single write-locked transaction with its audit row; the same request key is the same operation, a key reused for something else is an error. The server validates round, deadline, the round's own quota, limits and funds. The balance is derived from the ledger. Tests include six processes racing on one SQLite file; the idempotency tests were checked to fail when the replay is removed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
32 lines
1.2 KiB
Python
32 lines
1.2 KiB
Python
"""A player's balance, derived from the ledger (DAT-78) — never stored beside it."""
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from django.db.models import Q, Sum
|
|
|
|
from .models import Movement
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Balance:
|
|
spendable_sats: int # confirmed funds, minus whatever a pending operation has already reserved
|
|
incoming_sats: int # funds in confirmation: pending credits, not spendable yet (WEB-21)
|
|
|
|
@property
|
|
def total_sats(self) -> int:
|
|
return self.spendable_sats + self.incoming_sats
|
|
|
|
|
|
def balance_of(user) -> Balance:
|
|
"""Spendable = confirmed lines + pending debits (a bet or withdrawal in flight reserves its
|
|
amount at once). Incoming = pending credits. Failed lines count for nothing."""
|
|
totals = Movement.objects.filter(user=user).aggregate(
|
|
confirmed=Sum("amount_sats", filter=Q(status=Movement.Status.CONFIRMED)),
|
|
pending_debits=Sum("amount_sats", filter=Q(status=Movement.Status.PENDING, amount_sats__lt=0)),
|
|
pending_credits=Sum("amount_sats", filter=Q(status=Movement.Status.PENDING, amount_sats__gt=0)),
|
|
)
|
|
return Balance(
|
|
spendable_sats=(totals["confirmed"] or 0) + (totals["pending_debits"] or 0),
|
|
incoming_sats=totals["pending_credits"] or 0,
|
|
)
|