Sync round countdown across clients and enforce the bet cutoff on deadline, not scheduler tick
The round timer relied on each client's own wall clock, so two browsers with skewed local clocks showed different countdowns for the same round; the server now also returns server_time so the frontend can correct for clock skew. Also drop out-of-order /rounds/current responses (multiple independent triggers could resolve late and revert the UI to a stale drawing/result state) and prune per-round bookkeeping maps on round transitions. Separately, place_bet only checked status == "open", leaving a window (up to the scheduler's 5s tick interval) after a round's timer hit zero where a new bet could still be accepted. place_bet now checks the round's own deadline directly (round_accepts_bets), acting as an immediate "yellow light" for new entries while still letting already-broadcast bets confirm before the round closes. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f27fe6243c
commit
7dcf6d2756
8 files changed
+87
-17
No files matched your search
@@ -1,4 +1,4 @@
|
||||
from datetime import timedelta, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from pydantic import BaseModel
|
||||
@@ -14,6 +14,7 @@ router = APIRouter(prefix="/rounds", tags=["rounds"])
|
||||
|
||||
|
||||
class CurrentRoundResponse(BaseModel):
|
||||
server_time: str
|
||||
round_id: int | None = None
|
||||
status: str | None = None
|
||||
opened_at: str | None = None
|
||||
@@ -37,6 +38,7 @@ async def current_round(request: Request, session: AsyncSession = Depends(get_se
|
||||
if round_ is None:
|
||||
await session.commit()
|
||||
return CurrentRoundResponse(
|
||||
server_time=datetime.now(timezone.utc).isoformat(),
|
||||
bet_amount_sats=config.bet_amount_sats,
|
||||
draw_animation_seconds=config.draw_animation_seconds,
|
||||
chain_tip_height=chain_tip_height,
|
||||
@@ -51,6 +53,7 @@ async def current_round(request: Request, session: AsyncSession = Depends(get_se
|
||||
await session.commit()
|
||||
|
||||
return CurrentRoundResponse(
|
||||
server_time=datetime.now(timezone.utc).isoformat(),
|
||||
round_id=round_.id,
|
||||
status=round_.status,
|
||||
opened_at=opened_at.isoformat(),
|
||||
|
||||
+4
-3
@@ -8,7 +8,7 @@ from app.audit.log import write_audit_log
|
||||
from app.db.models import PendingTransaction, RoundParticipant, User, UtxoEvent
|
||||
from app.electrum.client import ElectrumClient
|
||||
from app.rounds.config import get_round_config
|
||||
from app.rounds.service import open_new_round_if_needed
|
||||
from app.rounds.service import open_new_round_if_needed, round_accepts_bets
|
||||
from app.wallet.balance import recompute_balance
|
||||
from app.wallet.hd import derive_pool_address, derive_user_key
|
||||
from app.wallet.psbt_builder import BuiltTransaction, InsufficientFundsError, Utxo, build_signed_transaction
|
||||
@@ -22,7 +22,9 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
|
||||
round_ = await open_new_round_if_needed(session)
|
||||
if round_ is None:
|
||||
raise BetError("no round open right now, please try again shortly")
|
||||
if round_.status != "open":
|
||||
|
||||
config = await get_round_config(session)
|
||||
if not round_accepts_bets(round_, config.round_duration_seconds):
|
||||
raise BetError("the current round is closing, please try again shortly")
|
||||
|
||||
already_playing = await session.scalar(
|
||||
@@ -33,7 +35,6 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
|
||||
if already_playing is not None:
|
||||
raise BetError("you already have an active bet in the current round")
|
||||
|
||||
config = await get_round_config(session)
|
||||
bet_amount = config.bet_amount_sats
|
||||
|
||||
unspent = (
|
||||
|
||||
@@ -16,6 +16,19 @@ async def get_active_round(session: AsyncSession) -> Round | None:
|
||||
return await session.scalar(select(Round).where(Round.status.in_(_ACTIVE_STATUSES)).order_by(Round.id.desc()))
|
||||
|
||||
|
||||
def round_accepts_bets(round_: Round, round_duration_seconds: int) -> bool:
|
||||
"""The authoritative "yellow light" check: once a round's timer has expired,
|
||||
no new bet may be accepted, even though its DB status is still "open" (the
|
||||
scheduler only flips it to "closing" on its next tick, up to
|
||||
_TICK_INTERVAL_SECONDS later — see rounds/scheduler.py). Bets already placed
|
||||
before the deadline are unaffected: the round still waits for them to confirm
|
||||
before actually closing."""
|
||||
if round_.status != "open":
|
||||
return False
|
||||
opened_at = round_.opened_at.replace(tzinfo=timezone.utc)
|
||||
return datetime.now(timezone.utc) < opened_at + timedelta(seconds=round_duration_seconds)
|
||||
|
||||
|
||||
async def open_new_round_if_needed(session: AsyncSession) -> Round | None:
|
||||
"""Returns the active round if one exists (whatever its status). Otherwise
|
||||
opens a fresh one, unless the last closed round's cooldown (ROUND_COOLDOWN_SECONDS)
|
||||
|
||||
+21
-2
@@ -544,6 +544,14 @@ function switchPanel(name) {
|
||||
}
|
||||
|
||||
let roundCloseAt = null;
|
||||
let serverTimeOffsetMs = 0; // serverNow - clientNow, so every client's countdown agrees regardless of local clock skew
|
||||
function serverNow() { return new Date(Date.now() + serverTimeOffsetMs); }
|
||||
// refreshRound() is triggered from several independent sources (poll timer, timer-hits-zero,
|
||||
// visibilitychange, placeBet, showDashboard) whose requests can resolve out of order over the
|
||||
// network. Track the latest applied response so a slow, stale one can never revert the UI to an
|
||||
// older round's state after a newer response has already moved it forward.
|
||||
let roundRequestSeq = 0;
|
||||
let roundAppliedSeq = 0;
|
||||
let roundTimerInterval = null;
|
||||
let roundPollTimeout = null;
|
||||
|
||||
@@ -649,7 +657,7 @@ let timerHitZero = false;
|
||||
function updateRoundTimer() {
|
||||
const el = document.getElementById('round-timer');
|
||||
if (!roundCloseAt) { el.textContent = '--:--'; timerHitZero = false; return; }
|
||||
const rawSec = Math.floor((roundCloseAt - new Date()) / 1000);
|
||||
const rawSec = Math.floor((roundCloseAt - serverNow()) / 1000);
|
||||
const totalSec = Math.max(0, rawSec);
|
||||
const mm = String(Math.floor(totalSec / 60)).padStart(2, '0');
|
||||
const ss = String(totalSec % 60).padStart(2, '0');
|
||||
@@ -691,8 +699,11 @@ function showNormalState() {
|
||||
}
|
||||
|
||||
async function refreshRound() {
|
||||
const seq = ++roundRequestSeq;
|
||||
try {
|
||||
const data = await call('GET', '/rounds/current');
|
||||
if (seq < roundAppliedSeq) return; // a newer refreshRound() call already applied its result
|
||||
roundAppliedSeq = seq;
|
||||
noteFetchOutcome(true);
|
||||
updateChainStatusBar(data);
|
||||
document.getElementById('round-title').textContent = data.round_id
|
||||
@@ -708,6 +719,7 @@ async function refreshRound() {
|
||||
jackpotEl.classList.add('jackpot-bump');
|
||||
}
|
||||
lastJackpotValue = jackpotValue;
|
||||
if (data.server_time) serverTimeOffsetMs = new Date(data.server_time) - new Date();
|
||||
roundCloseAt = data.closes_at ? new Date(data.closes_at) : null;
|
||||
updateRoundTimer();
|
||||
|
||||
@@ -735,6 +747,13 @@ async function refreshRound() {
|
||||
} else if (data.round_id && data.round_id !== activeResultRoundId) {
|
||||
// a genuinely new round is open — clear any previous result and go back to normal
|
||||
activeResultRoundId = null;
|
||||
// drop bookkeeping for old rounds so these maps don't grow for the life of the session
|
||||
for (const key of Object.keys(drawStartedAt)) {
|
||||
if (Number(key) !== data.round_id) delete drawStartedAt[key];
|
||||
}
|
||||
for (const id of revealedRounds) {
|
||||
if (id !== data.round_id) revealedRounds.delete(id);
|
||||
}
|
||||
showNormalState();
|
||||
} else if (!data.round_id && activeResultRoundId == null) {
|
||||
// nothing has ever been revealed and there's no active round — plain empty state
|
||||
@@ -747,7 +766,7 @@ async function refreshRound() {
|
||||
// The countdown reaching zero doesn't mean the server has actually closed the
|
||||
// round yet (it still waits for in-flight bets to confirm) — poll faster
|
||||
// through that gap too, not just once status flips to closing/drawing/paying_out.
|
||||
const pastDeadline = data.status === 'open' && roundCloseAt !== null && roundCloseAt - new Date() <= 0;
|
||||
const pastDeadline = data.status === 'open' && roundCloseAt !== null && roundCloseAt - serverNow() <= 0;
|
||||
scheduleNextRoundPoll(isDrawing || pastDeadline);
|
||||
} catch (e) {
|
||||
noteFetchOutcome(false);
|
||||
|
||||
Reference in new issue
Block a user