Show pending-inclusive balance and per-player round outcome reliably
Balance display: place_bet/request_withdrawal spend whole UTXOs and mark them spent at broadcast time, well before confirmation, so the confirmed-only balance could drop by far more than the amount actually moving. Add compute_pending_balance() (app/wallet/balance.py) to fold the unconfirmed change from in-flight bet/withdrawal PendingTransactions back in; GET /users/me now returns pending_balance_sats + has_pending, and the frontend shows it colored green (settled) or amber (still pending) instead of the confirmed-only figure. Round outcome display: the win/lose reveal and the "pagamento al vincitore in corso" status were fighting over the same UI slot, and the reveal broke across a page refresh. Now: - The round-status box (generic phase progress) and the personal win/lose box are independent and can both be visible at once. - The win/lose box only renders for users who actually played in that round (new user_played field on GET /rounds/current, via a new optional-auth dependency so the endpoint stays usable logged-out). - The reveal delay is anchored to the round's server-provided closes_at instead of a client-side "first seen" timestamp, so repeated reloads can't reset it, and the revealed result is persisted in localStorage so it survives a refresh even after the round has fully closed. - GET /users/me/last-round-result is a durable DB-backed backstop for players who miss the live window entirely (backgrounded tab, offline). Also hardens the frontend polling loop: call() now times out instead of hanging forever, and a session-epoch counter stops an in-flight request from a previous login from resurrecting a duplicate poll loop after logout. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f822911128
commit
6a857f0e07
8 files changed
+459
-80
No files matched your search
+149
-75
@@ -325,7 +325,7 @@ const ROUND_STATUS_LABELS = {
|
||||
open: 'aperto',
|
||||
closing: 'in chiusura',
|
||||
drawing: 'estrazione in corso',
|
||||
paying_out: 'pagamento in corso',
|
||||
paying_out: 'pagamento al vincitore in corso',
|
||||
};
|
||||
|
||||
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
|
||||
@@ -342,9 +342,9 @@ function drawingLabelFor(data) {
|
||||
}
|
||||
// paying_out
|
||||
if (data.draw_block_height != null) {
|
||||
return 'Vincitore estratto dal blocco #' + data.draw_block_height + ' — pagamento in corso…';
|
||||
return 'Vincitore estratto dal blocco #' + data.draw_block_height + ' — pagamento al vincitore in corso…';
|
||||
}
|
||||
return 'Vincitore estratto — pagamento in corso…';
|
||||
return 'Vincitore estratto — pagamento al vincitore in corso…';
|
||||
}
|
||||
|
||||
// One label per real round status, not just the coarse open/drawing/waiting
|
||||
@@ -355,7 +355,7 @@ const CHAIN_STATUS_LABELS = {
|
||||
open: 'Round aperto',
|
||||
closing: 'Round chiuso — attesa conferma puntate',
|
||||
drawing: 'Estrazione in corso',
|
||||
paying_out: 'Pagamento in corso',
|
||||
paying_out: 'Pagamento al vincitore in corso',
|
||||
};
|
||||
|
||||
function updateChainStatusBar(data) {
|
||||
@@ -438,12 +438,46 @@ document.addEventListener('visibilitychange', () => {
|
||||
}
|
||||
});
|
||||
|
||||
const LAST_SEEN_RESULT_KEY = 'plm_last_seen_result_round_id';
|
||||
// The win/lose box's content lives in localStorage, not just in-memory state —
|
||||
// a page reload (or a completely fresh tab) must be able to redraw it exactly
|
||||
// as it was, without waiting for a new poll or re-running the reveal
|
||||
// animation. This is the single source of truth for "what result box (if any)
|
||||
// is currently shown"; refreshRound() and checkLastRoundResult() below both
|
||||
// read/write it instead of keeping their own separate notion of "revealed".
|
||||
const PERSISTED_RESULT_KEY = 'plm_persisted_result';
|
||||
|
||||
function markResultSeen(roundId) {
|
||||
localStorage.setItem(LAST_SEEN_RESULT_KEY, String(roundId));
|
||||
function getPersistedResult() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(PERSISTED_RESULT_KEY));
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistResult(roundId, won, amountSats) {
|
||||
localStorage.setItem(PERSISTED_RESULT_KEY, JSON.stringify({ round_id: roundId, won, amount_sats: amountSats }));
|
||||
}
|
||||
|
||||
function clearPersistedResult() {
|
||||
localStorage.removeItem(PERSISTED_RESULT_KEY);
|
||||
}
|
||||
|
||||
function renderPersistedResult(result) {
|
||||
setRoundInfoVisible(false);
|
||||
setResultBoxVisible(
|
||||
true,
|
||||
result.won ? '🎉 Hai vinto! +' + (result.amount_sats / SATS_PER_PLM) + ' PLM' : 'Non hai vinto questa volta.',
|
||||
result.won ? 'win' : 'lose'
|
||||
);
|
||||
}
|
||||
|
||||
// The most recent round_id refreshRound() actually saw from the server (null
|
||||
// meaning "confirmed no active round"; undefined meaning "haven't polled yet").
|
||||
// Lets checkLastRoundResult() below avoid clobbering a round that's already
|
||||
// known to be open/in-progress by the time its own (slower, DB-backed) request
|
||||
// resolves.
|
||||
let currentRoundIdSeen;
|
||||
|
||||
// Backstop for the live reveal in refreshRound(): that one only works if a poll
|
||||
// happens to land while the round is still "paying_out" (winner_user_id is
|
||||
// dropped from /rounds/current the instant the round flips to "closed" — see
|
||||
@@ -461,23 +495,19 @@ async function checkLastRoundResult() {
|
||||
return; // silent — this is a backstop, refreshRound()'s own error handling already covers the primary path
|
||||
}
|
||||
if (data.round_id == null) return;
|
||||
if (String(data.round_id) === localStorage.getItem(LAST_SEEN_RESULT_KEY)) return; // already surfaced (live or backstop)
|
||||
markResultSeen(data.round_id);
|
||||
const persisted = getPersistedResult();
|
||||
if (persisted && persisted.round_id === data.round_id) return; // already showing/known
|
||||
if (currentRoundIdSeen != null && currentRoundIdSeen !== data.round_id) return; // a newer round is already in progress on screen
|
||||
|
||||
persistResult(data.round_id, data.won, data.amount_sats);
|
||||
renderPersistedResult({ won: data.won, amount_sats: data.amount_sats });
|
||||
if (data.won) {
|
||||
const won = data.amount_sats / SATS_PER_PLM;
|
||||
toast('Hai vinto il round #' + data.round_id + '! +' + won + ' PLM', 'success');
|
||||
refreshMe();
|
||||
} else {
|
||||
toast('Round #' + data.round_id + ' concluso: non hai vinto questa volta.', 'info');
|
||||
}
|
||||
}
|
||||
|
||||
// Per round_id: when we first saw it enter a drawing status (client clock), and
|
||||
// whether the win/lose result has already been shown for it. Local-only state,
|
||||
// not persisted — a page reload just re-derives it from the next poll.
|
||||
const drawStartedAt = {};
|
||||
const revealedRounds = new Set();
|
||||
let activeResultRoundId = null; // round_id whose win/lose result is on screen, if any
|
||||
let lastJackpotValue = null;
|
||||
|
||||
let timerHitZero = false;
|
||||
@@ -502,29 +532,35 @@ function updateRoundTimer() {
|
||||
}
|
||||
}
|
||||
|
||||
function showDrawingState(label) {
|
||||
document.getElementById('round-normal-row').classList.add('hidden');
|
||||
document.getElementById('round-stats-row').classList.add('hidden');
|
||||
document.getElementById('draw-state').classList.add('active');
|
||||
document.getElementById('draw-result').classList.add('hidden');
|
||||
if (label) document.getElementById('draw-label').textContent = label;
|
||||
// The round's normal info (title/timer/players/jackpot) vs. the drawing-phase
|
||||
// spinner box vs. the personalized win/lose box are three independently
|
||||
// toggled pieces, not three mutually-exclusive "screens" — during closing/
|
||||
// drawing/paying_out, EVERY viewer sees the drawing box (generic phase
|
||||
// progress), and a player who bet in that round ALSO sees the win/lose box at
|
||||
// the same time once revealed, instead of the two fighting over one slot.
|
||||
function setRoundInfoVisible(show) {
|
||||
document.getElementById('round-normal-row').classList.toggle('hidden', !show);
|
||||
document.getElementById('round-stats-row').classList.toggle('hidden', !show);
|
||||
}
|
||||
|
||||
function showResultState(html, cls) {
|
||||
document.getElementById('round-normal-row').classList.add('hidden');
|
||||
document.getElementById('round-stats-row').classList.add('hidden');
|
||||
document.getElementById('draw-state').classList.remove('active');
|
||||
function setDrawingBoxVisible(show, label) {
|
||||
document.getElementById('draw-state').classList.toggle('active', show);
|
||||
if (show && label) document.getElementById('draw-label').textContent = label;
|
||||
}
|
||||
|
||||
function setResultBoxVisible(show, html, cls) {
|
||||
const el = document.getElementById('draw-result');
|
||||
el.className = 'draw-result ' + cls;
|
||||
el.innerHTML = html;
|
||||
el.classList.remove('hidden');
|
||||
if (show) {
|
||||
el.className = 'draw-result ' + cls;
|
||||
el.innerHTML = html;
|
||||
}
|
||||
el.classList.toggle('hidden', !show);
|
||||
}
|
||||
|
||||
function showNormalState() {
|
||||
document.getElementById('round-normal-row').classList.remove('hidden');
|
||||
document.getElementById('round-stats-row').classList.remove('hidden');
|
||||
document.getElementById('draw-state').classList.remove('active');
|
||||
document.getElementById('draw-result').classList.add('hidden');
|
||||
setRoundInfoVisible(true);
|
||||
setDrawingBoxVisible(false);
|
||||
setResultBoxVisible(false);
|
||||
}
|
||||
|
||||
async function refreshRound() {
|
||||
@@ -554,47 +590,64 @@ async function refreshRound() {
|
||||
roundCloseAt = data.closes_at ? new Date(data.closes_at) : null;
|
||||
updateRoundTimer();
|
||||
|
||||
currentRoundIdSeen = data.round_id || null;
|
||||
|
||||
const isDrawing = data.round_id && DRAWING_STATUSES.includes(data.status);
|
||||
document.getElementById('round-card').classList.toggle('drawing-glow', !!isDrawing);
|
||||
const persisted = getPersistedResult();
|
||||
|
||||
if (isDrawing) {
|
||||
if (!(data.round_id in drawStartedAt)) drawStartedAt[data.round_id] = Date.now();
|
||||
const elapsedMs = Date.now() - drawStartedAt[data.round_id];
|
||||
const minMs = data.draw_animation_seconds * 1000;
|
||||
setRoundInfoVisible(false);
|
||||
// The drawing-phase box (spinner + phase label) is generic status info —
|
||||
// every viewer sees it for the whole closing/drawing/paying_out phase,
|
||||
// regardless of whether they played in this round.
|
||||
setDrawingBoxVisible(true, drawingLabelFor(data));
|
||||
|
||||
if (data.winner_user_id != null && elapsedMs >= minMs && !revealedRounds.has(data.round_id)) {
|
||||
revealedRounds.add(data.round_id);
|
||||
activeResultRoundId = data.round_id;
|
||||
markResultSeen(data.round_id);
|
||||
if (myUserId != null && data.winner_user_id === myUserId) {
|
||||
const won = (data.winner_amount_sats / SATS_PER_PLM);
|
||||
showResultState('🎉 Hai vinto! +' + won + ' PLM', 'win');
|
||||
toast('Hai vinto il round #' + data.round_id + '! +' + won + ' PLM', 'success');
|
||||
refreshMe(); // the win toast is useless if the balance card still shows the pre-payout amount
|
||||
} else {
|
||||
showResultState('Non hai vinto questa volta.', 'lose');
|
||||
// The cosmetic reveal delay is anchored to the server's closes_at, not to
|
||||
// any client-side "when did I first see this" timestamp — a page reload
|
||||
// (or repeated reloads) can never reset it, since it's derived purely
|
||||
// from server-provided values that don't change for this round.
|
||||
const elapsedMs = serverNow() - new Date(data.closes_at);
|
||||
const minMs = data.draw_animation_seconds * 1000;
|
||||
const alreadyKnown = persisted && persisted.round_id === data.round_id;
|
||||
// myUserId may not be loaded yet on the very first tick after a reload
|
||||
// (refreshMe() and refreshRound() run concurrently) — fall back to the
|
||||
// persisted result rather than risk showing nothing or the wrong side.
|
||||
const canReveal =
|
||||
data.user_played && data.winner_user_id != null && (alreadyKnown || elapsedMs >= minMs) && myUserId != null;
|
||||
|
||||
if (canReveal) {
|
||||
const won = data.winner_user_id === myUserId;
|
||||
if (!alreadyKnown) {
|
||||
persistResult(data.round_id, won, data.winner_amount_sats);
|
||||
if (won) {
|
||||
const wonAmount = (data.winner_amount_sats / SATS_PER_PLM);
|
||||
toast('Hai vinto il round #' + data.round_id + '! +' + wonAmount + ' PLM', 'success');
|
||||
refreshMe(); // the win toast is useless if the balance card still shows the pre-payout amount
|
||||
}
|
||||
}
|
||||
} else if (!revealedRounds.has(data.round_id)) {
|
||||
showDrawingState(drawingLabelFor(data));
|
||||
renderPersistedResult({ won, amount_sats: data.winner_amount_sats });
|
||||
} else if (alreadyKnown) {
|
||||
renderPersistedResult(persisted);
|
||||
} else {
|
||||
setResultBoxVisible(false);
|
||||
}
|
||||
} 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];
|
||||
} else {
|
||||
setDrawingBoxVisible(false);
|
||||
if (data.round_id && (!persisted || data.round_id !== persisted.round_id)) {
|
||||
// a genuinely new round is open — clear any previous result and go back to normal
|
||||
clearPersistedResult();
|
||||
showNormalState();
|
||||
} else if (!data.round_id && !persisted) {
|
||||
// nothing has ever been revealed and there's no active round — plain empty state
|
||||
showNormalState();
|
||||
} else if (persisted) {
|
||||
// no active round right now (cooldown, or a page reload after the round
|
||||
// fully closed) — keep the persisted result on screen regardless, until
|
||||
// a genuinely new round replaces it above.
|
||||
renderPersistedResult(persisted);
|
||||
}
|
||||
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
|
||||
showNormalState();
|
||||
}
|
||||
// else: no active round right now, but we just revealed a result for the last
|
||||
// one — keep it on screen through the cooldown gap instead of flashing back to
|
||||
// "Nessun round attivo".
|
||||
|
||||
scheduleNextRoundPoll(isDrawing);
|
||||
} catch (e) {
|
||||
@@ -609,7 +662,7 @@ function scheduleNextRoundPoll(fast) {
|
||||
roundPollTimeout = setTimeout(refreshRound, fast ? 3000 : 15000);
|
||||
}
|
||||
|
||||
function showDashboard() {
|
||||
async function showDashboard() {
|
||||
sessionEpoch++; // invalidate any dashboard poll chain left over from a previous login
|
||||
stopChainOnlyPolling();
|
||||
document.getElementById('landing-hero').classList.add('hidden');
|
||||
@@ -619,7 +672,16 @@ function showDashboard() {
|
||||
document.getElementById('dash-username').textContent = username;
|
||||
document.getElementById('dash-address').textContent = address;
|
||||
document.getElementById('dash-qr').src = '/qr/' + encodeURIComponent(address);
|
||||
refreshMe();
|
||||
// Render instantly from localStorage, before the network round-trip below —
|
||||
// otherwise a reload right after a win/lose flashes an empty round card for
|
||||
// a moment. refreshRound()'s own response reconciles this shortly after
|
||||
// (e.g. hides it again if a new round has since opened).
|
||||
const persisted = getPersistedResult();
|
||||
if (persisted) renderPersistedResult(persisted);
|
||||
// Awaited so myUserId is populated before refreshRound() decides whether
|
||||
// data.winner_user_id === myUserId — otherwise that comparison could race
|
||||
// against an unset myUserId right after a reload.
|
||||
await refreshMe();
|
||||
refreshRound();
|
||||
checkLastRoundResult();
|
||||
clearInterval(lastResultInterval);
|
||||
@@ -676,9 +738,7 @@ function resetToLoggedOutUI() {
|
||||
sessionEpoch++; // invalidate any refreshRound() still in flight from the dashboard we're leaving
|
||||
token = username = address = null;
|
||||
myUserId = null;
|
||||
activeResultRoundId = null;
|
||||
revealedRounds.clear();
|
||||
for (const key of Object.keys(drawStartedAt)) delete drawStartedAt[key];
|
||||
currentRoundIdSeen = undefined;
|
||||
clearInterval(roundTimerInterval);
|
||||
clearTimeout(roundPollTimeout);
|
||||
clearInterval(lastResultInterval);
|
||||
@@ -734,7 +794,19 @@ async function copyAddress() {
|
||||
}
|
||||
|
||||
let myUserId = null;
|
||||
let myBalanceSats = 0;
|
||||
let myBalanceSats = 0; // confirmed, spendable balance — what withdrawals/bets can actually draw from
|
||||
|
||||
// Shows the pending-inclusive balance (confirmed + own change still unconfirmed
|
||||
// in a broadcast bet/withdrawal — see compute_pending_balance in
|
||||
// app/wallet/balance.py) so the number doesn't drop by more than the amount
|
||||
// actually spent while a tx is in flight. Green once settled, amber while
|
||||
// has_pending is true so it's clear the figure isn't final yet.
|
||||
function setBalanceDisplay(elementId, pendingBalanceSats, hasPending) {
|
||||
const el = document.getElementById(elementId);
|
||||
el.textContent = pendingBalanceSats / SATS_PER_PLM;
|
||||
el.classList.toggle('balance-pending', hasPending);
|
||||
el.classList.toggle('balance-confirmed', !hasPending);
|
||||
}
|
||||
|
||||
async function refreshMe() {
|
||||
const btn = document.getElementById('refresh-btn');
|
||||
@@ -743,11 +815,13 @@ async function refreshMe() {
|
||||
const data = await call('GET', '/users/me');
|
||||
myUserId = data.id;
|
||||
myBalanceSats = data.balance_sats;
|
||||
document.getElementById('dash-balance').textContent = data.balance_sats / SATS_PER_PLM;
|
||||
document.getElementById('navbar-balance').textContent = (data.balance_sats / SATS_PER_PLM) + ' PLM';
|
||||
setBalanceDisplay('dash-balance', data.pending_balance_sats, data.has_pending);
|
||||
document.getElementById('navbar-balance').textContent = (data.pending_balance_sats / SATS_PER_PLM) + ' PLM';
|
||||
document.getElementById('navbar-balance').classList.toggle('balance-pending', data.has_pending);
|
||||
document.getElementById('navbar-balance').classList.toggle('balance-confirmed', !data.has_pending);
|
||||
document.getElementById('profile-username').textContent = data.username;
|
||||
document.getElementById('profile-address').textContent = data.address;
|
||||
document.getElementById('profile-balance').textContent = data.balance_sats / SATS_PER_PLM;
|
||||
setBalanceDisplay('profile-balance', data.pending_balance_sats, data.has_pending);
|
||||
document.getElementById('profile-created-at').textContent = new Date(data.created_at).toLocaleDateString('it-IT');
|
||||
document.getElementById('wd-full-amount-value').textContent = data.balance_sats / SATS_PER_PLM;
|
||||
if (document.getElementById('wd-full-amount').checked) {
|
||||
|
||||
Reference in new issue
Block a user