CLIENT PROTOCOL
Shared crash rooms — client protocol (including Zenith)
Each title has one authoritative clock and round for all its real players. The room owns the seats and the chain; PlayerDO owns the stake, wallet calls and receipts. See rgs/src/crash-room.ts, rgs/src/crash-engine.ts, games/crash.ts and test/integration/crash.test.ts. The CSP, SDK, accessibility and honest-presentation rules in docs/game-dev-guide.md still apply.
Multi-game: same client, different room
Use exactly the same paths and messages for every game. Never send a room name or a game selector with a bet, upgrade or cash-out: the authenticated session selects it. Independent titles may have the same round number; a public round is identified by (game code, seq). Real room IDs are the code; demo IDs are demo:<code>. Zenith retains its historical IDs main and demo including their chains and outstanding bets. A demo has a separate clock and chain and never publishes to the real record. If a title disables its demo room, a demo launch is refused, not routed to real money.
Read sv.game for code, name, rtp, edge_bps, max_multiplier, curve_k, betting_ms, pause_ms, max_bets_per_round, min_auto_cashout, partial_cashout. Bet slots are numbered from zero. Trust the room's state.k, deadlines and events rather than hard-coding timings. All pre-existing Zenith messages/paths and its 97.00% nominal RTP, 1,000,000× ceiling, two slots and 1.01× minimum target are unchanged.
Definitions live in games/crash-games/<code>.ts: export game = defineCrashGame({ code, name, ... }) and add it to the import list in games/crash-games/index.ts. The registry exposes shared titles without pretending they are per-player Game engines. Review clients separately before adding their codes to CLIENT_READY. Settings: multiplier integers are hundredths (maxMultiplierE2, minAutoCashoutE2); edge_bps defaults to 100 (1%), k is per ms, bettingMs/pauseMs are ms, betsPerPlayer is 1–3. Optional partialCashout defaults off; demoRoom defaults on. Regenerate the local math manifest with node games/variants/manifest.ts --game <code> after finalizing a definition. Edge and crash cap are immutable for a committed chain: coordinate a live change at a chain boundary, never discard a chain to change a result. (A deployed definition whose edge or cap differs from the live chain's makes the room refuse every bet with GAME_NOT_READY until a chain under the new terms is committed and salted.) The QA server starts fresh on restart.
The round
betting (Zenith: 6 s) → flying (until the crash point) → crashed (Zenith: 3 s pause) → next betting …- Multiplier while flying:
m(t) = e^(k·t),t= milliseconds since take-off,k = 0.00006for Zenith (always use the snapshot’sk). It starts at 1.00× and doubles about every 11.6 s. The client draws this curve itself fromt0and its estimate of the server clock; the server does not stream ticks. - The crash point is fixed before betting opens and is revealed only in the
crashmessage. Until then nothing the server sends contains it. Never display or imply a future value. - A player may use
max_bets_per_roundslots (two in Zenith), each with an optional auto cash-out target. - A round where nobody is connected and nobody bets does not start: the room idles.
Clock
Every server message carries now (server time in ms). Keep offset = now − Date.now() (smooth it over a few messages) and compute elapsed flight time as Date.now() + offset − t0. Send {"t":"ping"} occasionally; the reply {"t":"pong","now":…} refines the offset. The server's clock decides everything; the client's only draws.
Connecting
const ws = sv.openSocket("/crash/ws"); // SDK: authenticated, token in the subprotocolThe first message is always a full snapshot. If the session is no longer valid, the server accepts the socket only to send {"t":"error","code":"SESSION_NOT_FOUND"} and close it with code 4401: stop reconnecting and show "session expired". Reconnect automatically with a short backoff whenever the socket closes (deploys, network changes, phone sleep), and rebuild all UI state from the next snapshot. During local development the server hot-reloads often and drops sockets — your client must ride through that without a visible glitch.
Server → client messages
t | When | Fields |
|---|---|---|
state | on connect, or after {"t":"sync"} | now, phase, k, seq, prev_seed, betting_ends_at, t0, crash, seed, next_at, bets[], you[], history[], chain |
betting | betting opens | now, seq, prev_seed, betting_ends_at |
start | take-off | now, seq, t0 |
bets | batched changes to the public bet list | now, add[], cashed[], remove[] |
crash | the round stopped | now, seq, crash ("2.37"), seed, prev_seed |
you | only to the player concerned | now, event, bet_id, slot, … |
pong | reply to ping | now |
phase:preparing(first start-up, a second or two) ·awaiting_salt·idle·betting·flying·crashed.bets[]/add[]items:{ id, name, amount, currency, auto, cashout }—nameis a masked player id,amounta decimal string in that player's currency,cashoutthe multiplier they left at (or null).cashed[]items:{ id, mult }.remove[]: ids of cancelled bets. Demo (play-money) bets never appear here.you[](instate): your own bets in the current round:{ bet_id, slot, amount, currency, auto, status, cashout },status∈reserved | active | cashed | lost.youevents:placed(seq, amount, currency, auto),cashed(mult),partial(mult, only where enabled),cancelled,cashout_failed(code:TOO_LATEthe round is over or has not taken off,NO_ACTIVE_BETnothing to cash in that slot,RATE_LIMITEDtoo many cash-out requests (burst 6, then 4 per second per player per room),INVALID_PARAMETERbad slot/flag,PARTIAL_NOT_AVAILABLE).bet_count: the real number of bets in the round;bets[]is capped at 200 rows.history[]: last 30 rounds, newest first:{ seq, crash }.chain:{ no, commitment, salt, rtp, edge_bps, max_e2 }for the fairness panel.next_at: when the next betting window opens (duringcrashed).
Client → server messages
| Message | Meaning |
|---|---|
{"t":"cashout","slot":0} | cash out now (fastest path) |
{"t":"ping"} | clock sync |
{"t":"sync"} | send me a fresh state |
Betting and cancelling (HTTP, through the SDK)
Bets move money, so they go through the wallet path, not the socket:
// place — only while phase === "betting"
const r = await sv.play("bet", { bet: "5.00", params: { slot: 0, auto_cashout: "2.00" } }); // auto_cashout optional, from game.min_auto_cashout through game.max_multiplier
// r.status === "open", r.balance is the new balance, r.result = { seq, slot, auto_cashout }
// take it back before take-off
await sv.play("cancel", { params: { slot: 0 } }); // balance returned in the replyErrors (GameError.code): BETTING_CLOSED, BET_EXISTS, TOO_MANY_BETS, BET_TOO_LATE (the wallet answered after take-off; the stake is returned automatically), BET_TOO_LARGE, BET_OUT_OF_RANGE, INVALID_PARAMETER, INSUFFICIENT_FUNDS, WALLET_UNAVAILABLE, CANNOT_CANCEL, NO_OPEN_ROUND (cancel with no bet in that slot), RATE_LIMITED, GAME_NOT_READY.
Take-off happens at betting_ends_at, or up to 1.5 seconds later when a bet's wallet debit is still in flight; rely on the start message, not on the timestamp.
A bet takes a wallet round-trip (typically 50–300 ms). Let players queue a bet for the next round during flight and send it the instant betting arrives; do not send it early.
Cashing out
Send {"t":"cashout","slot":n} on the socket (preferred) or, as a fallback when the socket is down:
const r = await sv.request("POST", "/crash/cashout", { slot: 0 }); // { bet_id, multiplier, seq }The multiplier paid is the curve value when the server received the request (or the bet's auto target / maximum-win cap if that came first). For the HTTP fallback that is the Worker's arrival time when it is at most 2 s old; for the socket it is the room's receive time. The room's crash is atomic: the instant it processes the crash (and sends the seed), every later cash-out is refused, even one the Worker stamped a moment earlier. That keeps a lagging edge clock from paying a request sent after the reveal; in practice it means a click in the last few tens of milliseconds can lose, so never animate a cash-out as confirmed before cashed arrives. The confirmation is the you event cashed with mult. Show the confirmed value, not the one on screen when the button was pressed; they differ by network latency. If the request arrives after the crash it fails (TOO_LATE / cashout_failed) and the bet is lost. Auto cash-out is executed by the server even if the player is disconnected.
After a cash-out or a crash, the balance arrives a moment later (the win is credited through the casino wallet): call sv.refreshBalance() shortly after cashed/crash, and again if it has not changed.
Optional: lock in half
Only offer this action when sv.game.partial_cashout === true. Send {"t":"cashout","slot":0,"partial":true} or POST the same {slot,partial:true} to /crash/cashout. An accepted half returns partial:true on HTTP and emits a private you event {event:"partial", bet_id, slot, mult}. The personal snapshot adds partial_cashout:"1.57" to that bet; it is still active, not a public exit. A repeated half request during flight returns the same receipt; use sync after a missing socket acknowledgement. A seat with partial exits disabled refuses it with PARTIAL_NOT_AVAILABLE. If auto/max-win already triggered, the whole seat is closed instead. A regular cash-out still means “all that remains.” An unused partial option changes nothing for existing clients.
Half of the original stake (even an odd minor unit) is locked at that confirmed multiplier once. The rest pays at manual/auto cash-out or zero on a crash. There is one closing wallet credit, not an interim credit. For stake S in minor units and confirmed hundredths p and q, pay floor(S*(p+q)/200), limited by the frozen maximum win. With no partial, pay floor(S*q/100). Example: 11 cents, halves at 1.33× and 2.33×: 20 cents total, not 19 from rounding the legs separately. If the remainder loses, pay 7 cents. History's multiplier describes the final leg, partial_cashout the first; show the payout as the total. A disconnected player keeps the locked half. The remainder keeps the original stake-based multiplier ceiling. After a split, you[].status and the receipt’s cashed_out describe the remainder: lost does not erase the locked payout.
Money integrity (what the server guarantees, and where it is tested)
| Guarantee | How | Tests |
|---|---|---|
| A cash-out pays only a value the curve reached strictly before the crash, on the server's clock, never above the auto target, the stake's frozen maximum-win multiplier or the crash point | receive/arrival time checked against t0 ≤ t < crash_at; stale (>2 s) or future arrival stamps are replaced by the receive time; a stamp before take-off is refused | test/unit/crash-integrity.test.ts (randomised I1 + edges) |
| The crash point and seed never leave the room before the crash | the point lives only in the room's private tables; snapshots and events carry crash/seed only once the round is over | randomised I2 (every message on every socket), reconnect tests |
| Every bet that took off is settled exactly once; refused, failed, unknown-outcome, cancelled and late (debited after take-off) bets are never paid and are refunded | seat reserve → wallet debit → confirm; take-off releases unconfirmed seats; settlement goes through a durable outbox retried with back-off; PlayerDO closes a seat only from open | randomised I3, test/integration/crash-integrity.test.ts (slow debit after take-off, wallet failures, duplicate/reordered settlements) |
| Auto and manual never both pay; an auto target equal to the crash point pays | one bet row transition active → cashed, one outbox row per bet | randomised I4, auto/manual race, equality edge |
| Games, demo and real money never share a seat, a feed or a settlement | one room per (code, mode); the session picks the room, request bodies cannot; settlements carry game code and seq and are checked by the PlayerDO | randomised I5, isolation tests, crash-multigame.test.ts |
| Bursts are bounded | 3 sockets per player per room, 20-message burst then 5/s per socket (closed at 60 refusals), 1 sync/s, 6 cash-outs burst then 4/s per player; HTTP bets go through the PlayerDO throttle | burst tests (unit and integration) |
| Payouts round down once and respect the maximum win | floor(S·q/100) or floor(S·(p+q)/200) with a partial, then capped by the frozen maximum win | ledger checks in the randomised test, cap tests |
A slow or failing PlayerDO never stalls a room: the room keeps running rounds while the outbox retries (back-off up to 60 s). Residual, documented behaviour: if the room's confirmation reply is lost in transit after a successful debit, the PlayerDO keeps the seat bet_pending and refunds it after 30 s; a result the room later reports for that seat is ignored (the bet is void, never paid twice).
Fairness panel
Do not use per-player seeds. Fetch sv.publicInfo("/crash/" + sv.game.code) for up to 5 real chains and 100 revealed rounds (newest first). Demo clients verify their own socket's revealed seed, not a real round with the same seq. SHA-256 of the UTF-8 hex text of each seed must equal prev_seed (for the first index, the pre-salt commitment). HMAC-SHA256 uses the seed's hex text as key and salt text as message. Let r be its first 13 hex digits as an integer, N=2^52. In hundredths the point is:
min(chain.max_e2, max(100, floor(100*(10000-chain.edge_bps)*N / (10000*(N-r))))).
Exact ceiling effect: for an integer target 101 <= u <= max_e2, equality pays; the hit probability is floor(100*(10000-edge_bps)*N / (10000*u)) / N. The cap moves the entire higher tail onto the ceiling and changes no such probability, including at equality. Higher targets have zero hit probability and are rejected. With stake S and no tighter wallet cap, exact fixed-target RTP is that probability times floor(S*u/100)/S. Nominal RTP (99.00% at 100 bps; Zenith 97.00%) ignores the finite 52-bit grid and sub-minor-unit rounding. A smaller wallet maximum forces an earlier exit at min(u,floor(100*maxWin/S)); do not promise an unattainable payout. Manual exits are timed before the crash; an auto target tied with the crash wins.
Developing
Fast loopback QA (no Worker, credentials, migrations or external services)
node tools/dev-game.ts --game sky-courier --port 4110 --currency USD --crash-points 1.00,2.50
node tools/launch-url.ts sky-courier --dev-port 4110 --player ada
node tools/launch-url.ts sky-courier --dev-port 4110 --player bo
curl -s -X POST http://localhost:4110/dev/crash -H 'Content-Type: application/json' -d '{"queue":["1.01","3.00"]}'Open both URLs (or /play/sky-courier?t=dev-ada and ?t=dev-bo). These are distinct fake wallets in the same visible feed. Add --demo to the URL command for the isolated play-money room; set "mode":"demo" in the QA request to queue demo points. The CLI queue is for the visible room. A queue replaces future points, never the current round; an empty queue goes back to the real generator. Unforced rooms have verifiable seed links and outcomes. Forced results are explicitly non-verifiable (dev_forced:true on their local public history rows). GET /dev/state shows a snapshot. No upcoming points or seeds in the game protocol. --game games/crash-games/<code>.ts, --latency, --balance, --max-win also work. Supply your game's own rgs/public/static/<code>/main.js for visual QA. Restart to reset the in-memory rooms/wallets. There is no forced-point path in the RGS.
Real local wallet integration
Apply the local migrations through 0062_crash_chain_cap.sql before testing the new rooms. The whole system must be running: npm run dev (game server 8797, demo casino 8798). If it is not, run npm run setup:local once and then npm run dev in the background. Do not stop or restart these if they are already up; other work depends on them.
node tools/launch-url.ts zenith --player you-1 # prints a one-time launch URL (real mode, demo casino wallet)
node tools/launch-url.ts zenith --demo # play-money session
node tools/shot.ts --url "$(node tools/launch-url.ts zenith --player you-1)" --out .tmp/zenith/a.png --size 390x844 --wait 9000 --port 9306A launch URL works once; get a new one for every page load. Rounds run on real time, so use --wait and {"wait":…} actions to catch each phase (betting, flying, crashed). To see other players in the bet list, open a second session with another --player and place bets through its page. The demo casino lobby at http://localhost:8798 can launch the game in a frame and inject wallet failures.
Provably fair
How players and auditors verify rounds: seed commitment, client seed, nonce and the HMAC-SHA256 stream for every game, and the Bitcoin-salted hash chain for the shared crash rooms.
- Provably fair overview
- Crash fairness: hash chain and salt ceremony
- Salt ceremony records
- verify-crash.mjs, the standalone crash verifier (checksum and instructions)