# BetPlug — Complete developer documentation (`llms-full.txt`) > Complete single-file integration reference for AI coding agents and senior engineers: Table of Contents, Quick Integration Cheatsheet, complete game parameter/action/RNG matrix, and every canonical BetPlug `.md` documentation twin (`/docs.md` and `/docs/.md`). Domains (`*.betrail.example`) are example hostnames; packages are consumed directly from this repository checkout. ## Table of contents 1. [Quick integration cheatsheet](#quick-integration-cheatsheet) 2. [Complete game parameter, action & RNG reference](#complete-game-parameter-action--rng-reference) 3. [BetPlug developer documentation](/docs.md) — Integration path decision matrix, non-negotiable money and signing invariants, and concise headless SDK quickstart. 4. [Getting started: credentials, brand configuration & local stack](/docs/getting-started.md) — 5-minute local stack quickstart, Valkey's 330 s epoch, Console onboarding, production deployment knobs, Console insights, and going live. 5. [Authentication, signing, and idempotency](/docs/authentication-and-signing.md) — API keys, session tokens, 6-line betrail-v1 / betrail-v1-answer HMAC-SHA256 & Ed25519 wire examples, Idempotency-Key retries, and RFC 9457 errors. 6. [Seamless wallet protocol](/docs/seamless-wallet.md) — Drop-in SDK WalletHandler, debit-timeout rollback/tombstone flow, callback schemas (/balance, /debit, /credit, /rollback), signed 4xx refusals, and 29-check tester. 7. [Embed mode, launch tokens, and message bridge](/docs/embed-and-launch.md) — Single-use 60 s launch tokens, Web Component & play iframe, live demo/replay, betrail:v1 bridge, white-label theming, CSP/SRI, and reality checks. 8. [Webhooks (`round.settled`, `credits.low`, `credits.exhausted`)](/docs/webhooks.md) — Outbox retry schedule (1 s to 15 m over 24 h), credit-alert emails, raw-byte verification across all 4 SDKs, and JSON payloads for round.settled, credits.low, and credits.exhausted. 9. [Game catalog, live games protocol & reference casinos](/docs/live-games-and-catalog.md) — Unified live game catalog across Instant, Session, Slots, Live Shows, and Live Tables, WebSocket state machine and frame examples, tenant isolation, and reference casinos. 10. [Provable fairness & verification](/docs/dice-and-fairness.md) — Commit-reveal seed lifecycle, pre-draw vs post-draw void rounds, all legacy RNG recipes (dice-sha512, hmac-nonce bcmath-12, plinko-hmac), FairRandom, and live hash chains. 11. [Official SDKs (TypeScript, Go, Python & PHP)](/docs/sdk.md) — Zero-dependency TypeScript, Go, Python, and PHP SDKs: install & first-call quickstarts, exact integer-atom money helpers, Ed25519 wallet answers, and runnable samples. 12. [Remote MCP server (`@betrail/mcp`)](/docs/mcp.md) — Remote Streamable HTTP MCP server (@betrail/mcp), OAuth 2.1 + PKCE delegation, 12 tools (incl. 6-probe wallet tester), all betrail:// resources, and 4 guided prompts. 13. [Build with Claude Code](/docs/claude-code.md) — Official Claude Code plugin (./claude-plugin v0.1.0), pinned manifest identity, MCP origin wiring, and /betrail-integrate sandbox workflow. 14. [REST & AsyncAPI reference](/docs/api-reference.md) — REST API, seamless wallet callbacks, AsyncAPI live/webhook protocol, shared HTTP error/retry matrix, JSON examples, and component schemas compiled from OpenAPI 3.1 & AsyncAPI 3.1. ## Quick integration cheatsheet ### Base URLs & authentication headers per surface | Surface | Base URL (example) / local dev port | Authentication & signing headers | |---|---|---| | Operator REST (`/v1/rounds`, `/v1/launch`, `/v1/players/*`) | `https://api.betrail.example` (`127.0.0.1:8080`) | `Authorization: Bearer btr_test_`, `Betrail-Timestamp`, `Betrail-Nonce`, `Betrail-Signature: v1=`, `Idempotency-Key` on state-changing `POST` | | Browser Session (`/v1/session/*`, `/v1/sessions/current/reality-check`, `/v1/live/*`) | `https://api.betrail.example` (`127.0.0.1:8080`) | `Authorization: Bearer bts_` + browser `Origin` in brand allowlist (`Idempotency-Key` on `POST`, never `Betrail-Signature`) | | Live WebSockets (`/v1/live/{game}`) | `wss://live.betrail.example` (`127.0.0.1:8090`) | `Sec-WebSocket-Protocol: betrail.v1, ticket.<30s_ticket>` (minted via `POST /v1/live/{game}/tickets` with empty body) | | Seamless Wallet Callbacks (`POST {wallet_base}/{balance,debit,credit,rollback}`) | Operator HTTPS origin | Request: `betrail-v1` HMAC; Response: `Betrail-Timestamp` + `Betrail-Signature` (`betrail-v1-answer`, `ed25519=` or `v1=`); never sign `401` | | Operator Webhooks (`round.settled`, `credits.low`, `credits.exhausted`) | Operator HTTPS origin | `Betrail-Webhook-Id`, `Betrail-Timestamp`, `Betrail-Nonce`, `Betrail-Signature: v1=...` (`betrail-v1` over raw bytes before JSON parse) | | Isolated Play Host | `https://play.betrail.example/{game}?token=...` (`127.0.0.1:8084` optional) | Single-use 60 s launch token exchanged once at `POST /v1/sessions` and stripped from URL | | Local web portals | `3000=site`, `3001=admin`, `3002=console`, `3003=docs`, `3004=verifier` | Console BFF (`:8082`) uses `BETRAIL_CONSOLE_SERVICE_SECRET` + `Cookie: betrail_console=` | ### Exact 6-line canonical signing payloads (`\n`-joined) ```text # Request / Webhook (betrail-v1) betrail-v1 # Seamless Wallet Answer (betrail-v1-answer) betrail-v1-answer <3_digit_http_status> ``` ### Non-negotiable money, wallet & operational invariants - **Exact decimal strings (`Amount`):** `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$` parsed to integer atoms (`bigint`/`int64`/`int`/base-10 string) at currency scale (default `8`). Zero floats. - **Settlement accounting:** `payout` already includes `refund` (`GGR = stake - payout`). Never pay `payout + refund`. - **Wallet idempotency & tombstones:** Key strictly on `transaction_id` (never `round_id`). Re-sign replays over the retry's `Betrail-Nonce`. Tombstone unseen rollbacks and refuse late debits with signed `400 {"code":"invalid_request","transaction_id":"..."}`. Never refuse `/credit` or `/rollback` on balance, limits, or player status. - **Production ops defaults:** `BETRAIL_KYB_REQUIRED=false` (opt-in `true`; unrecognized values fail closed by enforcing operator verification approval rather than halting startup), `BETRAIL_LIVE_KEYS_ENABLED=true` required outside `BETRAIL_ENV=development` to issue live API keys, `BETRAIL_WORKER_ROLLUP_POOL_SIZE=5` (`2..16`), shared SMTP relay (`BETRAIL_SMTP_*`, mandatory STARTTLS off loopback or when credentials are set), Valkey `330 s` post-start epoch. ### Complete `ProblemCode` & retryability table | `code` | HTTP | Retryable? | |---|---|---| | `invalid_input` | `422` | No (fix parameter value or format) | | `invalid_action` | `422` | No (move not allowed in current game state) | | `stake_out_of_range` | `422` | No (adjust stake within brand min/max limits) | | `max_stake` | `422` | No (cap stake to Problem.max_stake or lower) | | `unknown_profile` | `422` | No (check supported game profile) | | `not_offered` | `409` | No (disabled brand/env, currency/FX, or game/preset policy such as MINES (12, 11)) | | `odds_changed` | `409` | Re-quote multiplier and retry with a new Idempotency-Key | | `closed` | `409` | No (round is already settled or pre-draw void) | | `limit` | `409` | No (brand or operator limit reached) | | `pending` | `409` | Retry with fresh nonce once in-flight step resolves | | `seed_not_revealed` | `409` | Rotate seeds first, then re-call /verify | | `unknown_game` | `404` | No (check canonical GameSlug) | | `unknown_version` | `404` | No (check supported game version) | | `no_acceptable_draw` | `500` | Yes — safe to retry with a new Idempotency-Key | | `internal` | `500` | Yes — same Idempotency-Key & body, fresh timestamp & nonce | | `invalid_request` | `400` | No (fix syntax, headers, or schema) | | `unauthorized` | `401` | Re-sign with fresh timestamp & nonce (after Valkey epoch settles) | | `session_expired` | `401` | No (mint a new launch token via POST /v1/launch) | | `forbidden` | `403` | No (check API key scope, IP, origin, player status, or jurisdiction) | | `origin_not_allowed` | `403` | No (register exact origin in Brand Allowed Origins) | | `player_blocked` | `403` | No (player is blocked or self-excluded) | | `jurisdiction_not_allowed` | `403` | No (jurisdiction blocked by brand or operator policy) | | `not_found` | `404` | No (resource does not exist in this operator/environment) | | `idempotency_key_in_use` | `409` | Yes — same Idempotency-Key & body, fresh Betrail-Timestamp & Betrail-Nonce | | `idempotency_key_reused` | `422` | No (generate a new Idempotency-Key for distinct payloads) | | `insufficient_funds` | `409` | No (player wallet declined debit for balance) | | `limit_exceeded` | `409` | No (player wallet declined debit for responsible-gaming limit) | | `wallet_unavailable` | `503` | Only when Retry-After header is present (bulkhead refused before state change); otherwise round voided | | `credits_exhausted` | `402` | After topping up prepaid USD credits | | `plan_inactive` | `402` | After activating or renewing operator plan | | `max_exposure` | `409` | No (round or show exposure cap reached) | | `rate_limited` | `429` | Yes — wait Retry-After seconds, same Idempotency-Key, fresh nonce | | `round_open` | `409` | Finish or force-close open rounds, then rotate seeds | | `reality_check_due` | `409` | Call POST /v1/sessions/current/reality-check, then retry | | `body_too_large` | `413` | No (body exceeds 64 KB limit) | | `unsupported_encoding` | `415` | No (send uncompressed identity JSON body) | ## Complete game parameter, action & RNG reference | `GameSlug` | Engine | Kind | RNG stream | Opening params (`RoundCreate.params` / live bet) | Session `do` / Live WS moves | Entry route | |---|---|---|---|---|---|---| | `dice` | `DICE` v1 | `I` | `dice-sha512` | [`DiceParams`](#diceparams) (`direction`, `chance`, `payout`) | — | `POST /v1/rounds` | | `limbo` | `LIMBO` v1 | `I` | `hmac-nonce` | [`LimboParams`](#limboparams) (`target`) | — | `POST /v1/rounds` | | `plinko` | `PLINKO` v1 | `I` | `plinko-hmac` | [`PlinkoParams`](#plinkoparams) (`pins`, `risk`) | — | `POST /v1/rounds` | | `roulette` | `ROULETTE` v1 | `I` | `hmac-nonce` | [`RouletteParams`](#rouletteparams) (`chips`) | — | `POST /v1/rounds` | | `diamonds` | `DIAMONDS` v1 | `I` | `hmac-nonce` | [`DiamondsParams`](#diamondsparams) (`{}`) | — | `POST /v1/rounds` | | `packs` | `PACKS` v1 | `I` | `FairRandom` | [`PacksParams`](#packsparams) (`{}`) | — | `POST /v1/rounds` | | `range-dice` | `RANGEDICE` v1 | `I` | `FairRandom` | [`RangediceParams`](#rangediceparams) (`mode`, `target`, `multiplier`, `ranges`) | — | `POST /v1/rounds` | | `wheel` | `WHEEL` v1 | `I` | `FairRandom` | [`WheelParams`](#wheelparams) (`risk`, `segments`) | — | `POST /v1/rounds` | | `drill` | `DRILL` v1 | `I` | `FairRandom` | [`DrillParams`](#drillparams) (`target`, `pick`) | — | `POST /v1/rounds` | | `slide` | `SLIDE` v1 | `I` | `FairRandom` | [`SlideParams`](#slideparams) (`target`) | — | `POST /v1/rounds` | | `cases` | `CASES` v1 | `I` | `FairRandom` | [`CasesParams`](#casesparams) (`difficulty`) | — | `POST /v1/rounds` | | `bars` | `BARS` v1 | `I` | `FairRandom` | [`BarsParams`](#barsparams) (`difficulty`, `picks`) | — | `POST /v1/rounds` | | `keno` | `KENO` v1 | `I` | `FairRandom` | [`KenoParams`](#kenoparams) (`risk`, `picks`) | — | `POST /v1/rounds` | | `darts` | `DARTS` v1 | `I` | `FairRandom` | [`DartsParams`](#dartsparams) (`difficulty`) | — | `POST /v1/rounds` | | `tarot` | `TAROT` v1 | `I` | `FairRandom` | [`TarotParams`](#tarotparams) (`difficulty`) | — | `POST /v1/rounds` | | `baccarat` | `BACCARAT` v1 | `I` | `FairRandom` | [`BaccaratParams`](#baccaratparams) (`bets`) | — | `POST /v1/rounds` | | `kaboom` | `KABOOM` v1 | `I` | `FairRandom` | [`KaboomParams`](#kaboomparams) (`charge`, `spot`) | — | `POST /v1/rounds` | | `tilt` | `TILT` v1 | `I` | `FairRandom` | [`TiltParams`](#tiltparams) (`notch`) | — | `POST /v1/rounds` | | `chicken` | `CHICKEN` v1 | `S` | `FairRandom` | [`ChickenParams`](#chickenparams) (`difficulty`, `round`) | [`ChickenAction`](#chickenaction): `step`, `cashout` | `POST /v1/rounds -> /actions` | | `pump` | `PUMP` v1 | `S` | `FairRandom` | [`PumpParams`](#pumpparams) (`difficulty`, `round`) | [`PumpAction`](#pumpaction): `pump`, `cashout` | `POST /v1/rounds -> /actions` | | `mines` | `MINES` v1 | `S` | `FairRandom` | [`MinesParams`](#minesparams) (`mines`, `tiles`) | [`MinesAction`](#minesaction): `sweep`, `cashout` | `POST /v1/rounds -> /actions` | | `towers` | `TOWERS` v1 | `S` | `FairRandom` | [`TowersParams`](#towersparams) (`difficulty`) | [`TowersAction`](#towersaction): `sweep`, `cashout` | `POST /v1/rounds -> /actions` | | `blackjack` | `BLACKJACK` v1 | `S` | `FairRandom` | [`BlackjackParams`](#blackjackparams) (`{}`) | [`BlackjackAction`](#blackjackaction): `hit`, `stand`, `double`, `split`, `insurance`, `no_insurance` | `POST /v1/rounds -> /actions` | | `hilo` | `HILO` v1 | `S` | `FairRandom` | [`HiloParams`](#hiloparams) (`{}`) | [`HiloAction`](#hiloaction): `guess`, `skip`, `cashout` | `POST /v1/rounds -> /actions` | | `snakes` | `SNAKES` v1 | `S` | `FairRandom` | [`SnakesParams`](#snakesparams) (`difficulty`) | [`SnakesAction`](#snakesaction): `roll`, `cashout` | `POST /v1/rounds -> /actions` | | `flip` | `FLIP` v1 | `S` | `FairRandom` | [`FlipParams`](#flipparams) (`call`, `flips`, `pattern`) | [`FlipAction`](#flipaction): `flip`, `cashout` | `POST /v1/rounds -> /actions` | | `rps` | `RPS` v1 | `S` | `FairRandom` | [`RpsParams`](#rpsparams) (`pick`, `hands`, `pattern`, `tie_picks`) | [`RpsAction`](#rpsaction): `throw`, `cashout` | `POST /v1/rounds -> /actions` | | `moles` | `MOLES` v1 | `S` | `FairRandom` | [`MolesParams`](#molesparams) (`moles`, `hole`, `hits`) | [`MolesAction`](#molesaction): `hit`, `cashout` | `POST /v1/rounds -> /actions` | | `video-poker` | `VIDEOPOKER` v1 | `S` | `FairRandom` | [`VideopokerParams`](#videopokerparams) (`{}`) | [`VideopokerAction`](#videopokeraction): `draw` | `POST /v1/rounds -> /actions` | | `sky-rush` | `SKYRUSH` v1 | `S` | `FairRandom` | [`SkyrushParams`](#skyrushparams) (`ring`, `plan`, `land_at`) | [`SkyrushAction`](#skyrushaction): `fly`, `cashout` | `POST /v1/rounds -> /actions` | | `dead-shot` | `DEADSHOT` v1 | `S` | `FairRandom` | [`DeadshotParams`](#deadshotparams) (`herd`, `bullets`) | [`DeadshotAction`](#deadshotaction): `fire`, `stop` | `POST /v1/rounds -> /actions` | | `meme-kombat` | `KOMBAT` v1 | `S` | `FairRandom` | [`KombatParams`](#kombatparams) (`rung`, `fighter`, `duration`, `bets`, `mode`) | [`KombatAction`](#kombataction): `next`, `live_bet` | `POST /v1/rounds -> /actions` | | `stack-packs` | `STACKPACKS` v1 | `S` | `FairRandom` | [`StackpacksParams`](#stackpacksparams) (`risk`) | [`StackpacksAction`](#stackpacksaction): `draw`, `cashout` | `POST /v1/rounds -> /actions` | | `grimoire-of-gains` | `GRIMOIRE` v1 | `SL` | `FairRandom` | [`SlotParams`](#slotparams) (`{}`) | — | `POST /v1/rounds` | | `pharaoh-pump` | `PHARAOH` v1 | `SL` | `FairRandom` | [`SlotParams`](#slotparams) (`{}`) | — | `POST /v1/rounds` | | `shogun-shiba` | `SHOGUN` v1 | `SL` | `FairRandom` | [`SlotParams`](#slotparams) (`{}`) | — | `POST /v1/rounds` | | `trapdoor` | `TRAPDOOR` v1 | `LV` | `reverse SHA-256 chain` | [`TrapdoorBetParams`](#trapdoorbetparams) (`door1`, `plan`) | [`TrapdoorCommand`](#trapdoorcommand): `snapshot`, `pick`, `bank`, `plan` | `POST /v1/live/trapdoor/bets + WS` | | `kombat-multiplayer` | `KOMBATMP` v1 | `LV` | `reverse SHA-256 chain` | [`KombatmpBetParams`](#kombatmpbetparams) (`kind`, `side`, `pay`, `at`) | [`KombatmpCommand`](#kombatmpcommand): `snapshot` | `POST /v1/live/kombat-multiplayer/bets + WS` | | `crash` | `CRASH` v1 | `LV` | `reverse SHA-256 chain` | [`CrashBetParams`](#crashbetparams) (`auto_cashout`) | [`CrashCommand`](#crashcommand): `snapshot`, `cashout` | `POST /v1/live/crash/bets + WS` | | `meme-trade` | `MEME_TRADE` v2 | `LV` | `reverse SHA-256 chain` | [`MemeTradeBuyInCreate`](#memetradebuyincreate) (`round`, `amount`) | [`LiveCommand`](#livecommand): `snapshot`, `open`, `close`, `sidebet`, `auto_sell` | `POST /v1/live/meme-trade/buy-ins + WS` | | `stack-o-pass` | `STACKOPASS` v1 | `LV` | `FairRandom (per-player)` | [`StackOPassParams`](#stackopassparams) (`risk`) | [`StackOPassCommand`](#stackopasscommand): `snapshot`, `watch`, `open`, `pass`, `cashout`, `leave` | `POST /v1/session/rounds (live_seat) + WS` | --- Source: /docs.md --- # BetPlug developer documentation BetPlug is a multi-tenant Remote Gaming Server (RGS) serving a [continuously expanding catalog of provably-fair house games](/docs/live-games-and-catalog) across instant games, stateful sessions, Originals Slots, shared live shows, and per-operator live tables. Every engine runs deterministic fixed-point integer arithmetic backed by cryptographic commitments and four zero-dependency [official SDKs](/docs/sdk). Every page ships alongside its exact `.md` twin (`/docs/.md`) and root [`/llms.txt`](/llms.txt) / [`/llms-full.txt`](/llms-full.txt) indexes — click **Copy for AI** on any guide to copy its canonical Markdown byte for byte. ## Choose your integration path Pick the UI surface and money flow that match your casino architecture: | Integration path | UI surface | Money ledger | Auth & entry flow | Best for | |---|---|---|---|---| | **Embedded + seamless wallet** | `` Web Component or isolated `play.betrail.example` iframe | Your casino (`POST /balance`, `/debit`, `/credit`, `/rollback`) | Server `POST /v1/launch` -> browser `POST /v1/sessions` (`bts_`) -> `/v1/session/*` | Fastest launch with zero frontend game work and full white-label theming ([Embed & launch](/docs/embed-and-launch)) | | **Live multiplayer** (`trapdoor`, `kombat-multiplayer`, `stack-o-pass`, `crash`, `meme-trade`) | `` or play iframe + `wss://live.betrail.example` | Seamless wallet (**mandatory**) | `POST /v1/launch` (`mode: "real"`) -> `POST /v1/sessions` -> `POST /v1/live/{game}/tickets` -> WebSocket `Sec-WebSocket-Protocol: betrail.v1, ticket.` | Shared live shows and per-operator 6-seat tables ([Game catalog & live](/docs/live-games-and-catalog)) | | **Headless REST** | Your custom game UI | Your own operator ledger | Server signs `POST /v1/rounds` (`201`) and `POST /v1/rounds/{id}/actions` (`200`) with `betrail-v1` + `Idempotency-Key` | Bespoke frontend UX where your backend settles balances directly from BetPlug's response | | **Demo & sandbox** | `` or `btr_test_` API | Built-in Sandbox Wallet (`1000.00000000` default) or `FUN` balance | Zero external wallet callbacks required until you wire your own sandbox wallet for the 29-check tester | Evaluating games locally or building your integration ([Getting started](/docs/getting-started)) | > **Tip:** New to BetPlug? Follow the [5-minute Getting started guide](/docs/getting-started) to start the local stack, mint your one-time `btr_test_` and `signing_secret` in Console Onboarding, and send your first round. ## Non-negotiable contract rules 1. **Exact decimal strings for money and multipliers.** Every monetary field (`stake`, `payout`, `refund`, `balance`, `amount`) and multiplier (`chance`, `payout`) is a JSON string matching `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$`, never a JSON float. Parse into integer atoms (`bigint`, `int64`/`*big.Int`, Python `int`, or PHP digit strings) at the currency's scale (default `8`). 2. **`payout` already includes `refund`.** A settled round's `payout` is the gross amount paid to the player (`0` on a loss) and **includes** `refund`. Gross gaming revenue is `GGR = stake - payout`. Never pay `payout + refund`. 3. **Pseudonymous `player_ref` only.** `player_ref` (`^[A-Za-z0-9_.:-]{1,64}$`) is an opaque identifier. Never send emails, names, IP addresses, or other PII. 4. **Sandbox-only keys in development and AI workflows.** Keep `btr_test_` credentials in `.env.local`, CI, MCP, and coding-agent sessions. Production keys belong exclusively in server-side secret managers. 5. **Full catalog availability (`404 unknown_game` vs `409 not_offered`).** Every game in the BetPlug catalog is mounted and served across `sandbox` and `live` ([Game catalog & live](/docs/live-games-and-catalog)). Unrecognized slugs return `404 unknown_game`; policy or brand exclusions — such as a disabled brand game, a currency with no live hourly FX rate, live `mode: "demo"` launches, or the `MINES` `(12, 11)` preset — return `409 not_offered` before any draw or nonce is consumed. `MEME_TRADE` v2 (`meme-trade`) runs in both `sandbox` and `live` with mid-round position adds refused, mid-round platform force-close retired, writer outages voiding and refunding open buy-ins, and zero cross-operator crowd figures. 6. **Self-serve going live.** Once operator live play and a jurisdiction allowlist are active on your account (plus operator verification approval when `BETRAIL_KYB_REQUIRED=true`), moving a brand from `sandbox` to `live` is self-serve after configuring your live seamless wallet (passing the 29-check tester), allowed HTTPS origins, webhooks, live API key, active plan, and prepaid USD credits in BetPlug Console ([Going live](/docs/getting-started#5-going-live)). ## First headless round (SDK & HTTP quickstart) Once you have a sandbox key from [Getting started](/docs/getting-started), open a headless `dice` round, inspect the result, and verify fairness after rotating seeds: ```ts no-eval tab import { BetrailClient, parseAmountAtoms, formatAmountAtoms } from "./sdk/ts/src/index.ts"; const client = new BetrailClient({ baseUrl: process.env.BETRAIL_API_BASE_URL ?? "https://api.betrail.example", apiKey: process.env.BETRAIL_API_KEY!, // btr_test_ signingSecret: process.env.BETRAIL_SIGNING_SECRET!, }); // 1. Open and settle a headless DICE round (Idempotency-Key & betrail-v1 handled automatically) const round = await client.createRound({ game: "dice", brand: process.env.BETRAIL_BRAND_ID!, player_ref: "p_demo_01", currency: "BTC", stake: "0.00010000", params: { direction: "under", chance: "47.98", payout: "1.97999" }, }); if (round.status === "settled") { const ggrAtoms = parseAmountAtoms(round.stake, 8) - parseAmountAtoms(round.payout, 8); const ggr = ggrAtoms < 0n ? `-${formatAmountAtoms(-ggrAtoms, 8)}` : formatAmountAtoms(ggrAtoms, 8); console.log({ id: round.id, roll: round.view.roll, win: round.view.win, ggr }); // 2. Rotate the player's seed pair and verify the settled round on the server await client.rotateSeeds("p_demo_01", "dice"); const proof = await client.verifyRound(round.id); console.log(proof.result); // "ok" } ``` ```sh tab=cURL # Example signed headless POST /v1/rounds (compute Betrail-Signature via betrail-v1) curl -sS -X POST "https://api.betrail.example/v1/rounds" \ -H "Authorization: Bearer $BETRAIL_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: idem_quickstart_round_01" \ -H "Betrail-Timestamp: 1793232000" \ -H "Betrail-Nonce: n_quickstart_attempt_001" \ -H "Betrail-Signature: v1=<64-hex-hmac-sha256>" \ -d '{"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","stake":"0.00010000","params":{"direction":"under","chance":"47.98","payout":"1.97999"}}' ``` ## Verifying `betrail-v1` signing & first-round `nonce: 0` replay Run this compact offline TypeScript check directly in Node to verify canonical `betrail-v1` signing and `dice-sha512` replay from a first-round commitment (`nonce: 0`): ```ts import assert from "node:assert/strict"; import crypto from "node:crypto"; import path from "node:path"; import { pathToFileURL } from "node:url"; const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd(); const sdk = await import(pathToFileURL(path.join(repoRoot, "sdk", "ts", "src", "index.ts")).href); // 1. Sign a POST /v1/rounds request with betrail-v1 and verify the header const secret = "sandbox-signing-secret-for-local-quickstart"; const body = JSON.stringify({ game: "dice", brand: "br_sandbox", player_ref: "p_demo_01", currency: "BTC", stake: "0.00010000", params: { direction: "under", chance: "47.98", payout: "1.97999" }, }); const signed = sdk.signRequest({ method: "POST", target: "/v1/rounds", body, secrets: [secret] }); assert.match(signed.signature, /^v1=[0-9a-f]{64}$/); // 2. Verify a first-round (nonce: 0) DICE commitment and roll extraction const serverSeed = crypto.createHash("sha256").update("betrail/l2/dice/boundary", "utf8").digest("hex"); const serverSeedHash = crypto.createHash("sha256").update(serverSeed, "utf8").digest("hex"); const roundSeed = { server_seed_hash: serverSeedHash, client_seed: "betrail-quickstart", nonce: 0 }; assert.equal(crypto.createHash("sha256").update(serverSeed, "utf8").digest("hex"), roundSeed.server_seed_hash); const digest = crypto .createHash("sha512") .update(`${serverSeed}:${roundSeed.client_seed}:${roundSeed.nonce}`, "utf8") .digest("hex"); const lucky = Number.parseInt(digest.slice(0, 5), 16); assert.equal(lucky, 854109); assert.equal(lucky % 10_000, 4109); // 3. Exact integer-atom accounting on the complete REST Round payload: GGR = stake - payout (payout already includes refund) const settledRound = { id: "rnd_quickstart_01", game: "dice", version: 1, brand: "br_sandbox", player_ref: "p_demo_01", currency: "BTC", status: "settled", step: 1, stake: "0.00010000", payout: "0.00019799", refund: "0.00000000", max_profit: "100.00000000", cap_rule: "truncate", cap_source: "brand", view: { roll: 4109, win: true, direction: "under", chance: "47.98", payout: "1.97999" }, seed: roundSeed, created_at: "2026-10-29T01:45:00Z", settled_at: "2026-10-29T01:45:00Z", }; const stakeAtoms = sdk.parseAmountAtoms(settledRound.stake, 8); const payoutAtoms = sdk.parseAmountAtoms(settledRound.payout, 8); const ggrAtoms = stakeAtoms - payoutAtoms; const ggr = ggrAtoms < 0n ? `-${sdk.formatAmountAtoms(-ggrAtoms, 8)}` : sdk.formatAmountAtoms(ggrAtoms, 8); assert.equal(ggrAtoms, -9_799n); // negative GGR on a player win assert.equal(ggr, "-0.00009799"); assert.equal(payoutAtoms - stakeAtoms, 9_799n); // player net profit ``` ## Guide index - [Getting started: local stack, Console & going live](/docs/getting-started) (`/docs/getting-started.md`) - [Authentication, signing, idempotency & errors](/docs/authentication-and-signing) (`/docs/authentication-and-signing.md`) - [Seamless wallet protocol](/docs/seamless-wallet) (`/docs/seamless-wallet.md`) - [Embed mode, launch tokens, and message bridge](/docs/embed-and-launch) (`/docs/embed-and-launch.md`) - [Game catalog, live games protocol & reference casinos](/docs/live-games-and-catalog) (`/docs/live-games-and-catalog.md`) - [Webhooks (`round.settled`, `credits.low`, `credits.exhausted`)](/docs/webhooks) (`/docs/webhooks.md`) - [Official SDKs (TypeScript, Go, Python & PHP)](/docs/sdk) (`/docs/sdk.md`) - [Remote MCP server (`@betrail/mcp`)](/docs/mcp) (`/docs/mcp.md`) - [Build with Claude Code](/docs/claude-code) (`/docs/claude-code.md`) - [Provable fairness & verification](/docs/dice-and-fairness) (`/docs/dice-and-fairness.md`) - [REST & AsyncAPI reference](/docs/api-reference) (`/docs/api-reference.md`) > **Pre-release preview.** Hostnames (`api.betrail.example`, `play.betrail.example`, `live.betrail.example`, `mcp.betrail.example`, `betrail.example`) are example hostnames, and official SDKs (`./sdk/ts`, `./sdk/go`, `./sdk/python`, `./sdk/php`), client bundles (`./clients`), MCP (`./mcp`), and the Claude Code plugin (`./claude-plugin`) are consumed directly from your verified repository checkout rather than public package registries. --- Source: /docs/getting-started.md --- # Getting started: credentials, brand configuration & local stack This guide takes you from a fresh BetPlug checkout to a running local stack, a provisioned sandbox brand (`br_…`) with one-time `btr_test_` credentials, configured seamless-wallet / origin / webhook endpoints, and production deployment readiness. ## 5-minute happy path 1. **Start infrastructure & migrate** — `sh scripts/dev.sh up` and `betrailctl migrate up`. 2. **Generate local `.env` secrets & launch services** — `betrail-api` (`:8080` / `:8082` / `:8083`), `betrail-worker`, and `betrail-console` (`:3002`). 3. **Clear Valkey's 330-second post-start epoch** — send one Console signup so `betrail:epoch` is stamped on a brand-new Valkey container, then wait `330 s` once. 4. **Onboard in Console** — verify email via Mailpit (`http://127.0.0.1:8025`), enroll Passkey or TOTP at `/security?onboarding=1`, bootstrap your operator & brand, and copy your one-time `btr_test_` + `signing_secret`. 5. **Play or wire your casino** — call `POST /v1/rounds` immediately, or configure your seamless wallet (`/wallet`), allowed origins (`/wallet`), and webhooks (`/webhooks`). ## Part A: Local development stack ### 1. Start infrastructure & apply migrations Start PostgreSQL (`127.0.0.1:5432`), Valkey (`127.0.0.1:6379`), and Mailpit (`127.0.0.1:1025` SMTP / `http://127.0.0.1:8025` web inbox), then apply SQL migrations: ```sh sh scripts/dev.sh up BETRAIL_MIGRATE_DATABASE_URL="postgres://betrail:betrail@127.0.0.1:5432/betrail?sslmode=disable" \ betrailctl migrate up ``` Copy `.env.example` to a git-ignored `.env` (`chmod 0600 .env`) and generate 32-byte random secrets (`node -e 'console.log(require("node:crypto").randomBytes(32).toString("base64url"))'`): | Variable | Local development value | Purpose | |---|---|---| | `BETRAIL_ENV` | `development` | Enables local development mode. Unset or any value outside `development` / `test` enforces strict production startup guards. | | `BETRAIL_DATABASE_URL` | `postgres://betrail:betrail@127.0.0.1:5432/betrail?sslmode=disable` | Database pool for the API and worker (production separates `betrail_app` and `betrail_worker` roles; local mode logs a warning on the dev role). | | `BETRAIL_VALKEY_URL` | `redis://127.0.0.1:6379/0` | Nonce replay store, Valkey epoch (`betrail:epoch`), and rate limits. | | `BETRAIL_SMTP_ADDR` | `127.0.0.1:1025` | Sends Console sign-up, recovery, and worker credit-alert emails to Mailpit (`http://127.0.0.1:8025`). | | `BETRAIL_SEED_KEK_ID` / `BETRAIL_SEED_KEK` | `dev-1` / `<32 random bytes, base64url, no padding>` | Local key-encryption key wrapping server seeds, wallet secrets, and webhook secrets (no default). | | `BETRAIL_CONSOLE_SERVICE_SECRET` | `<32+ byte secret>` | Shared `betrail-v1` service HMAC secret between the Operator Console and the API's private `127.0.0.1:8082` listener. | | `BETRAIL_CONSOLE_RP_ID` / `BETRAIL_CONSOLE_ORIGINS` / `BETRAIL_CONSOLE_URL` | `localhost` / `http://localhost:3002,http://127.0.0.1:3002` / `http://localhost:3002` | WebAuthn Relying Party ID and Console origin used in verification links. | | `BETRAIL_SANDBOX_WALLET_ORIGIN` | `http://127.0.0.1:8083` | Points the API and worker at the built-in Sandbox Wallet listener (`BETRAIL_SANDBOX_WALLET_LISTEN=127.0.0.1:8083`) over plain HTTP. | | `BETRAIL_EGRESS_LOCAL_ALLOW` | `127.0.0.1:3000,[::1]:3000` | Exact comma-separated `address:port` pairs (IP literals only, never hostnames) allowing the SSRF egress guard and Console `/wallet` + `/webhooks` validation to reach your local casino callbacks. | > **Warning:** Both a plain-HTTP `BETRAIL_SANDBOX_WALLET_ORIGIN` and any non-empty `BETRAIL_EGRESS_LOCAL_ALLOW` refuse startup immediately in the API, worker, and Console whenever `BETRAIL_ENV` is anything other than `development` or `test`. Aligned local development ports across all BetPlug web portals: | Portal | Local URL | Purpose | |---|---|---| | Marketing & game showcase (`web/site`) | `http://127.0.0.1:3000` | Public marketing site and live interactive game showcase | | Staff Admin (`web/admin`) | `http://127.0.0.1:3001` | Internal platform administration (private listener `:8081`) | | Operator Console (`web/console`) | `http://localhost:3002` | Operator onboarding, brands, keys, wallet, webhooks, insights, billing | | Developer Docs (`web/docs`) | `http://127.0.0.1:3003` | This documentation portal, `.md` twins, `/llms*.txt`, OpenAPI/AsyncAPI | | Fairness Verifier (`web/verifier`) | `http://127.0.0.1:3004` | Standalone offline browser round verifier | Start the three core local processes in separate terminals with `.env` exported in **every** shell (`set -a && . ./.env && set +a`): ```sh # Terminal 1: public API (:8080), private Console backend API (:8082), and Sandbox Wallet (:8083) set -a && . ./.env && set +a && betrail-api # Terminal 2: transactional outbox webhooks, wallet retries/sweeps, credit-alert emails, and analytics rollups set -a && . ./.env && set +a && betrail-worker # Terminal 3: operator Console UI on http://localhost:3002 set -a && . ./.env && set +a && BETRAIL_CONSOLE_PUBLIC_ORIGIN="http://localhost:3002" betrail-console # Optional Terminal 4 (for live multiplayer shows & STACKOPASS tables): # set -a && . ./.env && set +a && betrail-live ``` Confirm the API is listening: ```sh curl -sS http://127.0.0.1:8080/healthz ``` ### 2. Valkey's 330-second post-start epoch Valkey runs strictly in memory with persistence disabled so lost state is always a clean empty restart. Because signed `betrail-v1` requests accept `Betrail-Timestamp` within ±300 s plus 30 s of host-clock skew (`330` seconds total), a brand-new Valkey cannot tell whether a nonce was spent immediately before restart: 1. On the **first** nonce claim against an empty Valkey, the replay guard atomically writes `SET betrail:epoch NX`. 2. Every signed request with `Betrail-Timestamp <= betrail:epoch + 330` is refused with `401 unauthorized`: - On `:8082` Console backend API: `"Service credential timestamp predates a Valkey restart; sign a fresh request."` - On `:8080` public `/v1/*` routes: `"This request cannot be told from one sent before a restart: sign it again in a few minutes."` 3. **Local workflow:** After starting a fresh Valkey container, submit one request (such as Console sign-up) so `betrail:epoch` is stamped, wait **330 seconds** (`5m30s`), and retry. For the rest of that container's lifetime (`sh scripts/dev.sh up` keeps the container alive), signed calls succeed immediately. ### 3. Obtain a brand ID and sandbox key pair Open `http://localhost:3002/signup` and complete the four-step onboarding flow: 1. **Sign up (`POST /console/auth/signup`).** Returns uniform `202` (`ConsoleNoticeAck`, never disclosing whether an address already exists). Open Mailpit (`http://127.0.0.1:8025`) and follow `/verify-email?token=…` (`POST /console/auth/verify-email`). 2. **Enroll MFA (`http://localhost:3002/security?onboarding=1`).** After email verification, `factor_required` sessions redirect to `/security?onboarding=1`. Register a Passkey (`POST /console/auth/passkey/register/begin` -> `POST /console/auth/passkey/register/finish`, `201`; `http://localhost:3002` matches `BETRAIL_CONSOLE_RP_ID=localhost`, with passkey-only MFA enforced by default in production) or enroll a 6-digit TOTP authenticator (`POST /console/auth/totp/enroll/begin` -> `POST /console/auth/totp/enroll/finish`, `200`). 3. **Bootstrap operator & brand (`POST /console/onboarding/bootstrap`).** Supply an `Idempotency-Key` and `{ "operator_name", "brand_name", "currency"? }` (default `"BTC"`; unknown fields fail with `400 invalid_request`). Save the returned brand ID (`br_…`) as `BETRAIL_BRAND_ID`. 4. **Mint your one-time sandbox API key (`POST /console/brands/{brand}/sandbox-keys`).** Returns `api_key` (`btr_test_`) and `signing_secret` (`>= 32` bytes) once with `Cache-Control: no-store`. Save them in a git-ignored `0600` `.env.local`: ```sh BETRAIL_API_BASE_URL=http://127.0.0.1:8080 BETRAIL_BRAND_ID=br_01jbx... BETRAIL_API_KEY=btr_test_ BETRAIL_SIGNING_SECRET= ``` ### 4. Configure brand wallet, allowed origins, webhooks & launch tester Headless rounds (`POST /v1/rounds`) settle against your own ledger and never call an external wallet. For embedded/seamless sessions (`POST /v1/launch` -> `/v1/session/rounds`), new sandbox brands start wired to the built-in **Sandbox Wallet** (`BETRAIL_SANDBOX_WALLET_ORIGIN`): `POST /console/onboarding/bootstrap` pre-seeds `p_sandbox_demo` with `1000.00000000` in the brand's default currency, and the Sandbox Wallet treats any unseen `player_ref` as `"active"` with `"1000.00000000"` starting balance. When wiring your own casino server (for example on `http://127.0.0.1:3000` with `BETRAIL_EGRESS_LOCAL_ALLOW=127.0.0.1:3000`), configure your brand in the Console UI (`http://localhost:3002`): - **`http://localhost:3002/wallet`:** Switch the sandbox wallet to your operator URL, copy the one-time `wallet_secret`, register an optional RFC 8032 Ed25519 answer public key (`answer_public_key` via `PUT /console/brands/{brand}/wallet/{environment}/answer-key`), run the 29-check wallet conformance tester, and save `allowed_origins`. - **`http://localhost:3002/webhooks`:** Mint or rotate the one-time `signing_secret`, enable your receiver URL and event subscriptions (`round.settled`, `credits.low`, `credits.exhausted`), send a test ping, and inspect delivery logs and health (`GET /console/webhooks/deliveries/{id}` and `GET /console/brands/{brand}/webhooks/{environment}/health`). - **Other Console screens:** Credits & Top-Ups (`/topups` & `/money`), passkey/TOTP & MCP OAuth grants (`/security`), analytics (`/insights`), go-live status (`/go-live`), and team/keys (`/keys`, `/team`). Complete reference casinos live in `./examples/next-casino`, `./examples/go-casino`, and `./examples/laravel-casino` ([Official SDKs](/docs/sdk)). Under the hood, `/wallet` and `/webhooks` call these Console backend API routes (`api/console.yaml`): - **Seamless wallet & `wallet_secret` (`POST /console/brands/{brand}/wallet/{environment}`):** Requires `Idempotency-Key`. Send `{ "target": "operator", "wallet_url": "http://127.0.0.1:3000/api/wallet/v1", "overlap_seconds": 0 }` (`0..86400` during secret rotation, or `{ "target": "sandbox_wallet" }` on `sandbox`). Returns `201` (`BrandWalletIssued`) with one-time `wallet_secret` (`BETRAIL_WALLET_SECRET`; [Seamless wallet protocol](/docs/seamless-wallet)). - **Allowed browser origins (`PUT /console/brands/{brand}/origins/{environment}`):** Send `{ "allowed_origins": ["http://127.0.0.1:3000"] }` (`200`, up to `64` unique bare `scheme://host[:port]` origins with lowercase ASCII host; explicit default ports `:80` on `http` and `:443` on `https` are rejected with `422 invalid_input`; `https://` required on `live`; never `*` or `"null"`). Governs `POST /v1/launch` `return_url`, `/v1/session/*` `Origin` checks (`403 origin_not_allowed`), iframe `frame-ancestors`, and `betrail:v1` `postMessage` origin locking ([Embed & launch](/docs/embed-and-launch)). - **Webhook `signing_secret` & endpoint (`POST /console/brands/{brand}/webhooks/{environment}/secret` then `PUT /console/brands/{brand}/webhooks/{environment}`):** Mint one-time `signing_secret` (`201` `WebhookSecretIssued`, `Idempotency-Key` + `{ "overlap_seconds": 0 }` returning `{ "signing_secret", "secret_overlap_until", "rotated_at" }`), then enable delivery (`200`) with `{ "url": "http://127.0.0.1:3000/api/webhooks/betrail", "enabled": true, "events": ["round.settled", "credits.low", "credits.exhausted"] }` ([Webhooks](/docs/webhooks)). - **Launch tester (`POST /console/brands/{brand}/launch-test/{environment}`):** Requires `Idempotency-Key`. Dry-runs `POST /v1/launch` against the brand environment's exact rules (`200` `LaunchTestResult`). On `sandbox`, accepted non-live-show launches on a brand with `allowed_origins` also return a one-time 60-second sandbox `demo` (`FUN`) `play_host_url` (`Cache-Control: no-store`, `409 secret_already_shown` on replay). On `live` (`owner`/`admin` + `launch_tester.live` passkey step-up), it runs dry-run validation only, writes zero session/ledger rows, calls no wallet, returns `play_host_url: null`, and notifies every Owner. > **Security:** Programmatic test harnesses that call `127.0.0.1:8082` directly must sign every request with `betrail-v1` under `BETRAIL_CONSOLE_SERVICE_SECRET` **and** attach `Cookie: betrail_console=` from `/console/auth/*`. The Operator Console keeps raw session tokens out of browser JavaScript inside an `HttpOnly` cookie. ## Part B: Production deployment, Console operations & going live ### 5. Going live > **Tip:** Once operator live play and a jurisdiction allowlist are active on your account (plus operator verification approval whenever `BETRAIL_KYB_REQUIRED=true`), moving a brand from `sandbox` to `live` is self-serve once your production configuration passes validation: seamless wallet, allowed HTTPS origins, webhooks, live API key, active plan, and prepaid USD credits. 1. **Wallet (`/wallet`):** Point `live` at your production `https://` seamless wallet URL (with `wallet_secret` and recommended Ed25519 answer public keys) and pass the automated 29-check wallet conformance tester ([Seamless wallet protocol](/docs/seamless-wallet)). 2. **Allowed origins (`/wallet`):** Save your production `https://` casino origins (`PUT /console/brands/{brand}/origins/live`). 3. **Webhooks (`/webhooks`):** Mint a `live` webhook `signing_secret` and enable your HTTPS receiver for `round.settled`, `credits.low`, and `credits.exhausted` ([Webhooks](/docs/webhooks)). 4. **Credits (`/topups`):** Fund prepaid USD credits for live play (live rounds pause with `402 credits_exhausted` only if credits reach `0`; open rounds settle normally and sandbox remains active). ### 6. Production deployment settings (`betrail-api`, `betrail-worker`) Self-hosted production deployments control live-key issuance, compliance gating, SMTP credit alerts, and analytics rollup capacity with explicit fail-closed environment variables: | Environment variable | Default | Behavior & fail-closed guarantees | |---|---|---| | `BETRAIL_KYB_REQUIRED` | `false` | Controls whether operator verification approval is required before enabling live play, issuing live API keys, or activating live brands. Defaults to `false` (keeping dual-control live approvals and 29-check wallet conformance gates intact); set `true` to enforce prior approval. Any unrecognized non-empty value fails closed by enforcing operator verification approval (`Required() == true`) rather than halting startup. | | `BETRAIL_LIVE_KEYS_ENABLED` | `false` (off outside `development`) | Explicit production opt-in for live API key issuance outside `BETRAIL_ENV=development`. Set `BETRAIL_LIVE_KEYS_ENABLED=true` when your production deployment is ready to issue live keys; unset or `false` fails closed. | | `BETRAIL_SMTP_ADDR`, `BETRAIL_SMTP_FROM`, `BETRAIL_SMTP_HELO`, `BETRAIL_SMTP_USERNAME`, `BETRAIL_SMTP_PASSWORD_FILE` | `127.0.0.1:1025` (dev) | Shared SMTP relay used by `betrail-api` (Console onboarding & notifications) and `betrail-worker` (`credits.low` / `credits.exhausted` operator emails). **Mandatory STARTTLS (TLS 1.2+)** with certificate hostname verification whenever dialing off loopback **or** whenever SMTP credentials are set (loopback included). `BETRAIL_SMTP_PASSWORD_FILE` must be owner-only (`0600`/`0400`, <= 4096 bytes, read once at startup). | | `BETRAIL_WORKER_ROLLUP_POOL_SIZE` | `5` (`2..16`) | Dedicated PostgreSQL connection pool for `betrail-worker` Console analytics rollups (`application_name = 'betrail-worker-rollup'`), isolated from the worker's main pool so backfills never starve outbox money jobs or `/readyz`. Adds `+5` PostgreSQL connections per worker replica by default; invalid non-blank values refuse startup in every environment. | ### 7. Console insights, delivery health & staff admin operations Operators monitor live health and revenue directly in BetPlug Console (backed by private `api/console.yaml` routes): - **Brand management:** List, create, and rename brands (`GET /console/brands`, `POST /console/brands`, and `PUT /console/brands/{brand}`). - **Console insights (`GET /console/insights/{environment}`):** Aggregated handle, payouts, GGR (exact decimal strings), and basis-point rates (`bp`) fed by the worker rollup pool; returns `503 stats_unavailable` cleanly if a heavy query hits statement timeout. - **Per-brand activity & player counts:** `GET /console/brands/{brand}/activity/{environment}` and `GET /console/brands/{brand}/player-counts/{environment}`. - **Webhook & wallet delivery health:** `GET /console/brands/{brand}/webhooks/{environment}/health` and `GET /console/brands/{brand}/wallet/{environment}/delivery-health` surface recent success rates, latencies, and dead-letter counts. - **Billing alert history & API usage:** `GET /console/billing/alerts/history` tracks unified webhook + SMTP email delivery state for `credits.low` and `credits.exhausted` alerts; `GET /console/request-log/{environment}/usage` summarizes recent API volume. For self-hosted platform operators, the private Staff Admin API (`:8081`, guarded by `BETRAIL_ADMIN_ALLOWLIST` and WebAuthn passkeys) exposes platform summary & operator statistics (`GET /admin/summary`, `GET /admin/statistics`, `GET /admin/operators/{operator}/statistics`), incident banner history (`GET /admin/incident-banner/history`), and system health history (`GET /admin/system/health/history`). ## Validating allowed origins & Console request signing Use this helper to pre-validate `allowed_origins` before calling `PUT /console/brands/{brand}/origins/{environment}` and sign programmatic `:8082` Console calls: ```ts import assert from "node:assert/strict"; import crypto from "node:crypto"; function isValidAllowedOrigin(raw: string, env: "sandbox" | "live"): boolean { if (raw === "*" || raw === "null") return false; let parsed: URL; try { parsed = new URL(raw); } catch { return false; } const schemeOk = env === "live" ? parsed.protocol === "https:" : parsed.protocol === "https:" || parsed.protocol === "http:"; if (!schemeOk || parsed.origin !== raw) return false; if (raw.endsWith(":80") || raw.endsWith(":443")) return false; return true; } assert.equal(isValidAllowedOrigin("http://127.0.0.1:3000", "sandbox"), true); assert.equal(isValidAllowedOrigin("http://127.0.0.1:3000", "live"), false); assert.equal(isValidAllowedOrigin("https://casino.example", "live"), true); assert.equal(isValidAllowedOrigin("https://casino.example:443", "live"), false); assert.equal(isValidAllowedOrigin("*", "sandbox"), false); // Sign a programmatic POST /console/onboarding/bootstrap request with betrail-v1 const body = JSON.stringify({ operator_name: "Acme Gaming", brand_name: "Acme Casino", currency: "BTC" }); const bodyHash = crypto.createHash("sha256").update(body, "utf8").digest("hex"); const canonical = ["betrail-v1", "POST", "/console/onboarding/bootstrap", "1761696000", "nonce-bootstrap-01", bodyHash].join("\n"); const sig = `v1=${crypto.createHmac("sha256", "local-console-service-secret").update(canonical, "utf8").digest("hex")}`; assert.match(sig, /^v1=[0-9a-f]{64}$/); ``` --- Source: /docs/authentication-and-signing.md --- # Authentication, signing, and idempotency Every operator-to-BetPlug REST call, BetPlug-to-wallet callback, and BetPlug-to-operator webhook uses one 6-line HMAC-SHA256 signing scheme (`betrail-v1`). Seamless wallet responses sign the companion answer-side payload (`betrail-v1-answer`) using asymmetric RFC 8032 `ed25519=` keys or `v1=` HMAC-SHA256. ## Credentials by surface | Credential | Wire header / location | Scope & lifetime | |---|---|---| | Sandbox API key (`btr_test_`) + signing secret | `Authorization: Bearer ...` + `Betrail-*` | Operator server -> sandbox REST (`launch:write`, `players:force_close`, `players:write`, `rounds:read`, `rounds:write`, `seeds:read`, `seeds:write`). | | Production API key + signing secret | `Authorization: Bearer ...` + `Betrail-*` | Production server-to-server traffic only. Store exclusively in server-side secret managers; never expose to browsers, CI logs, MCP clients, or AI coding agents. | | Launch token (43 base64url chars) | Body of `POST /v1/sessions` or `?token=` | Single-use, 60 s TTL. Exchanged once by the embedded client and stripped from URL/history immediately. | | Session token (`bts_`) | `Authorization: Bearer ...` | Embedded browser client -> `/v1/session/*`, `/v1/sessions/current/reality-check`, and `/v1/live/*` (`Bearer` only, never `Betrail-Signature`). Max 8 h (900 s idle timeout), memory-only, bound to `Origin`. | | Live join ticket (`v1..`) | `Sec-WebSocket-Protocol: betrail.v1, ticket.` | Single-use, 30 s TTL, minted via `POST /v1/live/{game}/tickets`. Never logged; server echoes `betrail.v1` only. | | Wallet Ed25519 answer keypair | `Betrail-Signature: ed25519=<86-base64url>` | Asymmetric RFC 8032 wallet answer signer (`betrail-v1-answer`). Once an Ed25519 public key is registered on the brand environment, `v1=` HMAC downgrade is strictly refused. | | Top-up webhook (`receiveTopupEvent`) | Provider signature (`x-betrail-public: provider-signature`) | Payment provider -> `POST /v1/topup-events/{provider}` (`security: []`; authenticated by provider HMAC before reading JSON). | ## Request signing (`betrail-v1`) Every signed HTTP request carries three headers alongside `Authorization` (for operator REST calls): - **`Betrail-Timestamp`:** 10-digit Unix timestamp in seconds (`^[0-9]{10}$`). - **`Betrail-Nonce`:** Unique per-attempt token (`^[A-Za-z0-9_-]{16,64}$`). Generate a fresh CSPRNG nonce on **every** HTTP attempt — including retries that reuse the same `Idempotency-Key`. - **`Betrail-Signature`:** `v1=<64-lowercase-hex>` (or comma-separated `v1=,v1=` during a 24-hour secret rotation overlap). ### Signing anatomy (`betrail-v1`) Join these exact six lines with `\n` (`0x0a`, no trailing newline): ```text Line 1: betrail-v1 <-- fixed request domain separator Line 2: POST <-- UPPERCASE HTTP method Line 3: /v1/rounds?player_ref=p-1 <-- exact raw request-target (path + raw query as on wire) Line 4: 1793232000 <-- Betrail-Timestamp header (10 ASCII digits) Line 5: n_01jbx7q2w3e4r5t6y7u8 <-- Betrail-Nonce header (fresh per HTTP attempt) Line 6: e3b0c44298fc1c149afbf4c8996fb924... <-- lowercase hex SHA-256 of exact raw body bytes ``` ### Concrete signed HTTP request (`v1=` HMAC) ```http tab=HTTP POST /v1/rounds HTTP/1.1 Host: api.betrail.example Authorization: Bearer btr_test_ Content-Type: application/json Idempotency-Key: idem_round_0001 Betrail-Timestamp: 1793232000 Betrail-Nonce: n_round_attempt_0001 Betrail-Signature: v1=8f4a2e1c9d0b7a6f5e4d3c2b1a0987654321fedcba9876543210abcdef012345 {"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","stake":"0.00010000","params":{"direction":"under","chance":"47.98","payout":"1.97999"}} ``` ```sh tab=cURL curl -sS -X POST "https://api.betrail.example/v1/rounds" \ -H "Authorization: Bearer $BETRAIL_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: idem_round_0001" \ -H "Betrail-Timestamp: 1793232000" \ -H "Betrail-Nonce: n_round_attempt_0001" \ -H "Betrail-Signature: v1=8f4a2e1c9d0b7a6f5e4d3c2b1a0987654321fedcba9876543210abcdef012345" \ -d '{"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","stake":"0.00010000","params":{"direction":"under","chance":"47.98","payout":"1.97999"}}' ``` > **Security:** Enforce these four verification checks in strict order on every incoming webhook or wallet callback: > 1. Reject any `Content-Encoding` other than `identity` (`415`) and any body over `65,536` bytes (`413`) **before** buffering or hashing. > 2. Hash the **exact raw request-target** (path + raw query string as received on the wire — never normalized or percent-decoded by a proxy) and exact raw UTF-8 body bytes **before** `JSON.parse`. > 3. Reject `Betrail-Timestamp` outside `±300 s` of server time (`401`). > 4. Compare candidate `v1=` hex digests in constant time (`timingSafeEqual`) across active secrets **before** writing `Betrail-Nonce` to your replay store (`SET NX EX 630` in Valkey) so unauthenticated traffic cannot exhaust nonce memory. ## Wallet response signing (`betrail-v1-answer` & Ed25519) Seamless wallet responses (`200` answers and signed `4xx` refusals on verified requests) sign a 6-line `betrail-v1-answer` payload bound to the caller's `Betrail-Nonce` and `transaction_id`: ```text Line 1: betrail-v1-answer <-- fixed answer domain separator (blocks request reflection) Line 2: 200 <-- 3-digit HTTP response status (e.g. 200, 400, 409) Line 3: 1793232001 <-- answer's own Betrail-Timestamp header Line 4: n_01jbx7q2w3e4r5t6y7u8 <-- incoming request's Betrail-Nonce (re-signed on retries!) Line 5: rnd_01:0:1:debit <-- request's transaction_id (empty "" on /balance) Line 6: 4c9d3a1f... <-- lowercase hex SHA-256 of exact raw answer body bytes ``` ### Concrete wallet answer wire examples (`ed25519=` vs `v1=`) ```http tab=Ed25519_200 HTTP/1.1 200 OK Content-Type: application/json Betrail-Timestamp: 1793232001 Betrail-Signature: ed25519=A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8S9t0U1v2W3x4Y5z6A7b8C9d0E1f2G3h4I5j6K7l8M9n0P1q2RA {"transaction_id":"rnd_01:0:1:debit","amount":"0.00010000","currency":"BTC","operator_transaction_id":"op_tx_9001","balance":"0.04990000"} ``` ```http tab=HMAC_409 HTTP/1.1 409 Conflict Content-Type: application/json Betrail-Timestamp: 1793232001 Betrail-Signature: v1=3a7c1e9b5d2f8a4c6e0b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f1a3c {"code":"insufficient_funds","transaction_id":"rnd_01:0:1:debit"} ``` > **Warning:** Once an Ed25519 public key (43 canonical base64url chars, validated on-curve and non-8-torsion) is registered on a brand environment, BetPlug and all four [Official SDKs](/docs/sdk) enforce strict **no-downgrade pinning**: `v1=` HMAC tags alone are rejected. During migration rollout, emit `ed25519=,v1=` (`ed25519=` first). Never sign an unauthenticated `401` response. ## `Idempotency-Key` and retries Every state-changing operator `POST` (`/v1/rounds`, `/v1/rounds/{id}/actions`, `/v1/players/{player_ref}/seeds/{game}/rotate`, `/v1/players/{player_ref}/force-close`, `/v1/launch`) and session `POST` (`/v1/sessions`, `/v1/demo/sessions`, `/v1/session/rounds`, `/v1/session/rounds/{id}/actions`, `/v1/session/seeds/rotate`, `/v1/sessions/current/reality-check`, `/v1/live/{game}/tickets`, `/v1/live/{game}/bets`, `/v1/live/meme-trade/buy-ins`) requires `Idempotency-Key` (`^[!-~]{1,128}$`). - **Network timeout / `500` / `502` / `504` / `409 idempotency_key_in_use`:** Retry with the **exact same `Idempotency-Key`** and identical JSON body, signed with a **fresh `Betrail-Timestamp` and `Betrail-Nonce`**. - **`422 idempotency_key_reused`:** A different body was sent under an existing key. Mint a new `Idempotency-Key` for distinct logical operations. - **`503 wallet_unavailable`:** Retry **only** when the response carries a `Retry-After` header (the wallet bulkhead rejected before changing state). Without `Retry-After`, the opening debit failed or timed out, the round voided, and replaying that `Idempotency-Key` returns the stored `503`. > **Tip:** All four [Official SDKs](/docs/sdk) automatically mint one CSPRNG `Idempotency-Key` per logical call, reuse it on retryable statuses, and rotate `Betrail-Timestamp` + `Betrail-Nonce` on every HTTP attempt. ## Errors (`application/problem+json`) & retry matrix Every BetPlug REST error returns RFC 9457 `application/problem+json` and includes a `Betrail-Request-Id` response header for support and log correlation. | Field | Type | Description | |---|---|---| | `type` | `string` (URI) | Stable problem URI (`https://betrail.example/problems/`) | | `title` | `string` | Short human-readable summary | | `status` | `integer` | HTTP status code | | `detail` | `string` | Specific diagnostic explanation for this request | | `instance` | `string` | Request path that produced the error | | `code` | `ProblemCode` | Machine-readable error code (branch on this, never `detail`) | | `max_stake` | `Amount` (optional) | Returned on `422 max_stake` with the largest allowed stake for the requested target and brand `max_profit` cap | | `elapsed_seconds` / `net_result` | `integer` / `string` (optional) | Returned on `409 reality_check_due` so the client can render the responsible-gaming prompt before calling `POST /v1/sessions/current/reality-check` | Example problem responses: ```json tab=422_max_stake { "type": "https://betrail.example/problems/max_stake", "title": "Stake exceeds maximum allowed for target", "status": 422, "detail": "Requested stake exceeds the maximum stake permitted by the brand max_profit cap.", "instance": "/v1/rounds", "code": "max_stake", "max_stake": "5.00000000" } ``` ```json tab=409_reality_check_due { "type": "https://betrail.example/problems/reality_check_due", "title": "Reality check acknowledgement required", "status": 409, "detail": "Player must acknowledge the elapsed session summary before placing another wager.", "instance": "/v1/session/rounds", "code": "reality_check_due", "elapsed_seconds": 3600, "net_result": "-0.01250000" } ``` ### Quick HTTP error retry matrix | HTTP | Common `code` values | Retry? | Action | |---|---|---|---| | `400` | `invalid_request` | No | Fix malformed JSON, missing headers, or extra fields (`additionalProperties: false`). | | `401` | `unauthorized`, `session_expired` | Conditional | Check clock skew (`±300 s`), Valkey post-start epoch (`330 s`), and fresh `Betrail-Nonce`; re-launch expired `bts_` sessions. | | `402` | `credits_exhausted`, `plan_inactive` | After top-up | Top up prepaid live USD credits in Console `/topups` (sandbox stays unaffected). | | `403` | `forbidden`, `origin_not_allowed`, `player_blocked`, `jurisdiction_not_allowed` | No | Verify API key scopes, allowed origins, player status, or brand/operator jurisdiction policy. | | `404` | `not_found`, `unknown_game`, `unknown_version` | No | Confirm ID belongs to this operator/environment and slug matches [`GameSlug`](/docs/api-reference#gameslug). | | `409` | `idempotency_key_in_use`, `pending` | **Yes** | Retry with the **same** `Idempotency-Key` + body and a **fresh** `Betrail-Nonce`. | | `409` | `odds_changed`, `reality_check_due`, `round_open`, `seed_not_revealed`, `insufficient_funds`, `limit_exceeded`, `not_offered`, `closed`, `max_exposure` | No (resolve state) | Re-quote multiplier (`odds_changed`), acknowledge reality check, finish open round, or rotate seeds first. | | `413` / `415` | `body_too_large`, `unsupported_encoding` | No | Keep body `<= 64 KB` and send uncompressed `identity` JSON. | | `422` | `invalid_input`, `invalid_action`, `stake_out_of_range`, `max_stake`, `idempotency_key_reused` | No | Fix parameters (cap to `max_stake`) or mint a new `Idempotency-Key`. | | `429` | `rate_limited` | **Yes** | Honor `Retry-After` seconds; reuse `Idempotency-Key` with a fresh `Betrail-Nonce`. | | `500` | `internal`, `no_acceptable_draw` | **Yes** | Retry same `Idempotency-Key` + body with a fresh `Betrail-Timestamp` and `Betrail-Nonce`. | | `503` | `wallet_unavailable` | **Only with `Retry-After`** | With `Retry-After`: bulkhead rejected before state change (safe to retry). Without `Retry-After`: round voided (do not retry same key). | For the full table of every `ProblemCode`, see [Shared HTTP errors & retry matrix](/docs/api-reference#shared-http-errors--retry-matrix). ## Verifying official signing vectors (`api/testdata/signing-vectors.json`) This runnable TypeScript sample verifies every official `betrail-v1` request vector (including 24-hour dual-secret rotation) and `betrail-v1-answer` wallet response vector (including reflected-request rejection and retry re-signing): ```ts import assert from "node:assert/strict"; import crypto from "node:crypto"; import fs from "node:fs"; import path from "node:path"; interface SigningVector { name: string; first_line?: string; must_not_verify?: string; hmac_with: string; previous_hmac_with?: string; method?: string; target?: string; status?: string; timestamp: string; nonce: string; transaction_id?: string; body: string; body_sha256: string; canonical: string; signature_header: string; stale_signature_header?: string; } const sha256Hex = (text: string) => crypto.createHash("sha256").update(text, "utf8").digest("hex"); const hmacHex = (secret: string, canonical: string) => crypto.createHmac("sha256", Buffer.from(secret, "utf8")).update(canonical, "utf8").digest("hex"); function verifyHeaderConstantTime(header: string, secrets: string[], canonical: string): boolean { let matched = false; for (const part of header.split(",")) { if (!/^v1=[0-9a-f]{64}$/.test(part)) return false; const given = Buffer.from(part.slice(3), "hex"); for (const secret of secrets) { const expected = Buffer.from(hmacHex(secret, canonical), "hex"); if (given.length === expected.length && crypto.timingSafeEqual(given, expected)) matched = true; } } return matched; } const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd(); const { vectors } = JSON.parse( fs.readFileSync(path.join(repoRoot, "api", "testdata", "signing-vectors.json"), "utf8"), ) as { vectors: SigningVector[] }; assert.equal(vectors.length, 9); for (const v of vectors) { assert.equal(sha256Hex(v.body), v.body_sha256, v.name); if (v.first_line === "betrail-v1-answer") { const canonical = ["betrail-v1-answer", v.status ?? "", v.timestamp, v.nonce, v.transaction_id ?? "", v.body_sha256].join("\n"); assert.equal(canonical, v.canonical, v.name); assert.equal(verifyHeaderConstantTime(v.signature_header, [v.hmac_with], canonical), v.must_not_verify !== "true", v.name); if (v.stale_signature_header) { assert.equal(verifyHeaderConstantTime(v.stale_signature_header, [v.hmac_with], canonical), false, v.name); } } else { const canonical = ["betrail-v1", v.method ?? "", v.target ?? "", v.timestamp, v.nonce, v.body_sha256].join("\n"); assert.equal(canonical, v.canonical, v.name); const secrets = v.previous_hmac_with ? [v.hmac_with, v.previous_hmac_with] : [v.hmac_with]; assert.equal(secrets.map((s) => `v1=${hmacHex(s, canonical)}`).join(","), v.signature_header, v.name); for (const s of secrets) assert.equal(verifyHeaderConstantTime(v.signature_header, [s], canonical), true, v.name); } } ``` --- Source: /docs/seamless-wallet.md --- # Seamless wallet protocol In seamless wallet mode, your casino remains the single ledger of player balances. BetPlug calls four `POST` endpoints under your brand's configured wallet base URL (`https://casino.example/wallet/v1`), routed through BetPlug's SSRF-hardened egress client (`3 s` timeout, `64 KB` response cap). Live multiplayer games ([Game catalog & live](/docs/live-games-and-catalog)) require a seamless wallet in all operator integrations. ## Drop-in SDK `WalletHandler` (recommended) Start with the official `WalletHandler` in any of the four [Official SDKs](/docs/sdk). It implements raw-byte `betrail-v1` verification, 24-hour secret rotation overlap, RFC 8259 duplicate/case-folded JSON key rejection, rollback tombstones, idempotent answer re-signing over each retry's `Betrail-Nonce`, and RFC 8032 `ed25519=` answer signing out of the box: ```ts no-eval tab import { createWalletHandler, parseEd25519SeedBase64Url } from "./sdk/ts/src/index.ts"; // Wire your database-backed WalletBook and Valkey NonceStore (SET NX EX 630) export const walletHandler = createWalletHandler({ requestSecrets: [process.env.BETRAIL_WALLET_SECRET!, process.env.BETRAIL_WALLET_PREV_SECRET].filter(Boolean) as string[], answerEd25519Seeds: [parseEd25519SeedBase64Url(process.env.BETRAIL_WALLET_ED25519_SEED!)], book: myPostgresWalletBook, // implements balance(), debit(), credit(), rollback() nonceStore: myValkeyNonceStore, }); ``` ```go no-eval tab seed, err := betrail.ParseEd25519SeedBase64URL(os.Getenv("BETRAIL_WALLET_ED25519_SEED")) if err != nil { return err } handler, err := betrail.NewWalletHandler(betrail.WalletHandlerOptions{ RequestSecrets: []betrail.Secret{betrail.NewSecret(os.Getenv("BETRAIL_WALLET_SECRET"))}, AnswerEd25519Seeds: []betrail.Secret{seed}, Book: myPostgresWalletBook, NonceStore: myValkeyNonceStore, }) mux.Handle("/wallet/v1/", handler) ``` ```python no-eval tab import os from betrail import Ed25519, Secret, WalletHandler raw_seed = Ed25519.base64url_decode_32(os.environ["BETRAIL_WALLET_ED25519_SEED"]) if raw_seed is None: raise ValueError("BETRAIL_WALLET_ED25519_SEED must be 43-char canonical base64url") handler = WalletHandler( request_secrets=[Secret(os.environ["BETRAIL_WALLET_SECRET"])], book=my_postgres_wallet_book, nonce_store=my_valkey_nonce_store, answer_ed25519_seeds=[Secret(raw_seed)], ) # Inside your HTTP route: res = handler.handle_request("POST", request.full_path, request.headers, raw_body) ``` ```php no-eval tab use Betrail\Sdk\{Ed25519, Secret}; use Betrail\Sdk\Wallet\WalletHandler; $handler = new WalletHandler( requestSecrets: [new Secret(getenv('BETRAIL_WALLET_SECRET'))], book: $myPostgresWalletBook, nonceStore: $myValkeyNonceStore, answerEd25519Seeds: [Ed25519::parseSeedBase64Url(getenv('BETRAIL_WALLET_ED25519_SEED'))], ); $res = $handler->handleRequest('POST', $_SERVER['REQUEST_URI'], getallheaders(), file_get_contents('php://input')); ``` > **Tip:** Generate an Ed25519 keypair with your SDK (`generateEd25519WalletKeyPair`), register the 43-char base64url public key in Console `/wallet`, and pass the 32-byte seed to `WalletHandler`. Once registered, BetPlug pins verification to `ed25519=` and rejects `v1=` HMAC downgrade. ## Debit timeout -> rollback -> tombstone flow When a `/debit` network call times out or returns an unreadable/5xx response, BetPlug **never** retries that debit attempt. Instead it marks the round `void` and enqueues a guaranteed `/rollback` from the transactional outbox: ```text BetPlug API / Worker Your Seamless Wallet | | |--- POST /debit (tx: rnd_9:0:1:debit, nonce: N1) ----->| (delayed / timed out > 3s) | x-- timeout (outcome unknown) | | | |--- POST /rollback (tx: rnd_9:0:1:debit:rollback, ---->| Debit never seen? | rollback_of: rnd_9:0:1:debit, nonce: N2) | -> Store TOMBSTONE(rnd_9:0:1:debit) |<-- 200 WalletAnswer (signed over N2) -----------------| -> Balance unchanged | | | ... if the delayed POST /debit arrives later ... | |--- POST /debit (tx: rnd_9:0:1:debit, nonce: N1) ----->| Tombstone exists! |<-- 400 {"code":"invalid_request","transaction_id":..}-| -> Signed 400 refusal, no debit ``` ## Callback endpoints & JSON contracts All four callbacks receive `POST` with `betrail-v1` headers (`Betrail-Timestamp`, `Betrail-Nonce`, `Betrail-Signature`) and require strict schema responses (`additionalProperties: false`): | Endpoint | `transaction_id` format | Request JSON fields | `200` Response schema | |---|---|---|---| | `POST {base}/balance` | *(none — line 5 of answer signature is `""`)* | `player_ref`, `currency` | `{ "balance", "currency", "status": "active" \| "self_excluded" \| "blocked" }` | | `POST {base}/debit` | Instant/Session/STACKOPASS: `:::debit`
Live show bet (`trapdoor`, `kombat-multiplayer`, `crash`): `:0::debit`
`MEME_TRADE` buy-in: `::b::debit` | `transaction_id`, `round_id`, `player_ref`, `currency`, `amount`, `game`, `brand` | `WalletAnswer`: `{ "transaction_id", "amount", "currency", "operator_transaction_id", "balance" }` | | `POST {base}/credit` | `:credit` | `transaction_id`, `round_id`, `player_ref`, `currency`, `amount` (`>= "0.00000000"`), `kind` (`"payout"` \| `"refund"`), `game`, `brand` | `WalletAnswer` (`200` mandatory even on `"0.00000000"` or blocked player) | | `POST {base}/rollback` | `:rollback` | `transaction_id`, `rollback_of`, `round_id`, `player_ref`, `currency`, `amount` | `WalletAnswer` (returns booked funds once, or records tombstone if unseen) | ### Concrete wire payloads ```json tab=POST_/debit { "transaction_id": "rnd_01jbx7q2:0:1:debit", "round_id": "rnd_01jbx7q2", "player_ref": "p_demo_01", "currency": "BTC", "amount": "0.00100000", "game": "dice", "brand": "br_sandbox" } ``` ```json tab=200_WalletAnswer { "transaction_id": "rnd_01jbx7q2:0:1:debit", "amount": "0.00100000", "currency": "BTC", "operator_transaction_id": "op_ledger_88421", "balance": "0.04900000" } ``` ### Refusal codes & signing requirements | HTTP | Body (`WalletRefusal` / `WalletProtocolRefusal`) | Sign response? | When to return | |---|---|---|---| | `401` | `{"code":"invalid_request"}` | **NEVER** | Missing/invalid `Betrail-Signature`, expired `Betrail-Timestamp`, or replayed `Betrail-Nonce`. | | `400` | `{"code":"invalid_request"}` or `{"code":"invalid_request","transaction_id":"..."}` | **YES** (`betrail-v1-answer`) | Authenticated call with malformed JSON, duplicate/case-folded keys, unknown path, or tombstoned late `/debit`. | | `403` | `{"code":"player_blocked","transaction_id":"..."}` | **YES** | `/debit` only: player is blocked or self-excluded. Never return on `/credit` or `/rollback`. | | `409` | `{"code":"insufficient_funds","transaction_id":"..."}` or `{"code":"limit_exceeded","transaction_id":"..."}` | **YES** | `/debit` only: insufficient balance or player responsible-gaming limit reached. | > **Security:** Never sign an unauthenticated `401` response. Signing responses to requests whose signature failed turns your wallet endpoint into an answer-signing oracle. When implementing a custom handler instead of the SDK `WalletHandler`, reject missing/invalid signatures, stale timestamps, or replayed nonces with an unsigned `401`: ```ts no-eval function unsignedUnauthorized(): { status: number; headers: Record; body: string } { return { status: 401, headers: {}, body: JSON.stringify({ code: "invalid_request" }) }; } ``` ## Six mandatory wallet rules 1. **Key idempotency strictly on `transaction_id` — never `round_id`.** Multi-step games debit once per stake-adding action, and live shows (`MEME_TRADE`) settle multiple players and buy-ins under one shared `round_id`. Keying on `round_id` drops player payouts. 2. **Sign every answer to a verified request (`betrail-v1-answer`), including `4xx` refusals.** Include `Betrail-Timestamp` and `Betrail-Signature` (`ed25519=` or `v1=`) computed over: ```text betrail-v1-answer ``` **Never** sign an unauthenticated `401` response. 3. **Re-sign idempotent replays over the retry's `Betrail-Nonce`.** When BetPlug retries `/credit` or `/rollback` with the same `transaction_id`, return the **exact stored first JSON body and status**, signed afresh with a current `Betrail-Timestamp` and the **retry request's** `Betrail-Nonce`. 4. **Never refuse `/credit` or `/rollback` for balance, limits, or player status.** Every settled round sends one `/credit` (including `"0.00000000"` on a loss so your round record closes). Even if a player self-excludes or is blocked mid-round, `/credit` must succeed (`200`). Only malformed JSON/schema errors answer signed `400 {"code":"invalid_request"}`. 5. **Record rollback tombstones.** If `/rollback` arrives for a `rollback_of` debit your wallet never saw, store a tombstone for that debit ID and return `200` (`WalletAnswer` with the tombstone's own `operator_transaction_id` and current `balance`). If the late `/debit` arrives afterward, refuse it with `400 {"code":"invalid_request","transaction_id":"..."}` (signed; OpenAPI `WalletDebitRefused` accepts `4XX` `WalletRefusal`, and BetPlug's SDK, Sandbox Wallet, and skills standardize on `400` `invalid_request`). 6. **Strict schema echo and `operator_transaction_id != transaction_id`.** BetPlug decodes answers strictly (`additionalProperties: false`). `WalletAnswer` must echo `transaction_id`, `amount`, and `currency`, and provide a non-empty `operator_transaction_id` distinct from BetPlug's `transaction_id`. > **Warning:** Any extra JSON field, duplicate key, missing echo field, or unsigned live `4xx` refusal causes BetPlug to treat a `/debit` as unknown (rolling it back) and to keep retrying `/credit` or `/rollback` until the 24-hour outbox schedule moves it to `dead`. ## Go-live wallet conformance tester Before switching a brand from `sandbox` to `live`, BetPlug Console runs the automated **29-check** wallet conformance suite against your sandbox wallet endpoint across six areas: 1. Valid `POST /balance`, `/debit` (`200`), and `/credit` (`200`, including `"0.00000000"`). 2. Signed `409 {"code":"insufficient_funds","transaction_id":"..."}` debit refusal. 3. Idempotent replay of `/debit` and `/credit` returning the exact first `operator_transaction_id` re-signed for the new `Betrail-Nonce`. 4. `/rollback` after a booked `/debit`, plus `/rollback` before `/debit` (tombstone blocks late debit with signed `400 invalid_request`). 5. `/credit` succeeding while player status is `blocked` or `self_excluded`. 6. Rejection of tampered `Betrail-Signature` and stale `Betrail-Timestamp` with unsigned `401` (`{"code":"invalid_request"}`, no `Betrail-Signature` header). ## Executable seamless wallet verification (SDK + rotation overlap) This runnable TypeScript sample exercises `@betrail/sdk`'s `createWalletHandler` across balance, debit, idempotent replay, tombstone late-debit refusal, unsigned `401` bad-signature rejection, and comma-separated 24-hour secret rotation: ```ts import assert from "node:assert/strict"; import path from "node:path"; import { pathToFileURL } from "node:url"; const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd(); const sdk = await import(pathToFileURL(path.join(repoRoot, "sdk", "ts", "src", "index.ts")).href); const activeSecret = "wallet-secret-rotated-new-32byte!"; const prevSecret = "wallet-secret-rotated-old-32byte!"; const kp = sdk.generateEd25519WalletKeyPair(); const handler = sdk.createWalletHandler({ requestSecrets: [activeSecret, prevSecret], answerEd25519Seeds: [kp.seed], book: new sdk.InMemoryWalletBook({ defaultInitialBalance: "0.05000000" }), nonceStore: new sdk.InMemoryNonceStore(), }); async function callWallet(target: string, bodyObj: object, sigHeaderOverride?: string) { const body = JSON.stringify(bodyObj); const req = sdk.signRequest({ method: "POST", target, body, secrets: [activeSecret, prevSecret] }); const sigHeader = sigHeaderOverride ?? req.signature; assert.ok(sigHeader.split(",").length >= 1); // supports comma-separated rotation overlap const res = await handler({ method: "POST", target, headers: { "betrail-timestamp": req.timestamp, "betrail-nonce": req.nonce, "betrail-signature": sigHeader }, body, }); return { req, res }; } // 1. /balance signed with ed25519= (empty transactionId on line 5) const bal = await callWallet("/wallet/v1/balance", { player_ref: "p_1", currency: "BTC" }); assert.equal(bal.res.status, 200); assert.equal(JSON.parse(bal.res.body).balance, "0.05000000"); assert.equal( sdk.verifyAnswer({ status: 200, headers: bal.res.headers, requestNonce: bal.req.nonce, transactionId: "", body: bal.res.body, ed25519PublicKeys: [kp.publicKey], }).scheme, "ed25519", ); // 2. Rollback before unseen debit stores tombstone; late debit returns signed 400 invalid_request const lateTx = sdk.debitTransactionId("rnd_9", 0, 1); const rb = await callWallet("/wallet/v1/rollback", { transaction_id: sdk.rollbackTransactionId(lateTx), rollback_of: lateTx, round_id: "rnd_9", player_ref: "p_1", currency: "BTC", amount: "0.01000000", }); assert.equal(rb.res.status, 200); const late = await callWallet("/wallet/v1/debit", { transaction_id: lateTx, round_id: "rnd_9", player_ref: "p_1", currency: "BTC", amount: "0.01000000", game: "dice", brand: "br_1", }); assert.equal(late.res.status, 400); assert.equal(JSON.parse(late.res.body).code, "invalid_request"); assert.ok(late.res.headers["Betrail-Signature"]?.startsWith("ed25519=")); // 3. Forged signature returns unsigned 401 const bad = await callWallet("/wallet/v1/balance", { player_ref: "p_1", currency: "BTC" }, `v1=${"0".repeat(64)}`); assert.equal(bad.res.status, 401); assert.equal(bad.res.headers["Betrail-Signature"], undefined); ``` --- Source: /docs/embed-and-launch.md --- # Embed mode, launch tokens, and message bridge Embed BetPlug's vector-only game clients (`<= 150 KB` gzip combined first load, zero raster assets, self-hosted fonts, strict nonce CSP & Trusted Types) using either the `` Web Component on your own origin (Option A) or the isolated `play.betrail.example` iframe host (Option B). ## 1. Backend launch (`POST /v1/launch`) Your backend signs `POST /v1/launch` (`launch:write` scope, `betrail-v1` + `Idempotency-Key`) and passes the single-use `token` (60 s TTL) or `url` to the browser: ```sh tab=cURL curl -sS -X POST "https://api.betrail.example/v1/launch" \ -H "Authorization: Bearer $BETRAIL_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: idem_00000001" \ -H "Betrail-Timestamp: 1793232000" \ -H "Betrail-Nonce: n_launch_attempt_0001" \ -H "Betrail-Signature: v1=<64-hex-hmac-sha256>" \ -d '{"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","mode":"real","locale":"en","return_url":"https://casino.example/lobby"}' ``` ```json tab=201_Response { "token": "example_single_use_launch_token_0001", "url": "https://play.betrail.example/dice?token=example_single_use_launch_token_0001", "expires_at": "2026-10-29T01:46:00Z" } ``` How the browser completes session bootstrap: 1. The client exchanges the 60-second single-use `token` once at `POST /v1/sessions` for an in-memory session (`bts_`, max 8 h, 900 s idle timeout) and strips `?token=` from `location` immediately (`history.replaceState`). 2. Subsequent `/v1/session/*` and `/v1/live/*` requests send `Authorization: Bearer bts_` and are checked against your brand's `allowed_origins` (`403 origin_not_allowed` on mismatch; `Origin: null` is always refused). 3. For unauthenticated previews on BetPlug's own site origins, `POST /v1/demo/sessions` opens a `FUN`-currency demo session for Instant, Stateful, and Slot games; live clients ask for no demo session. > **Security:** Never log `token` or `url` in access logs, analytics, or referrer headers, and never store `bts_` in `localStorage`, `sessionStorage`, or cookies. ## 2. Option A: `` Web Component Load the shared `@betrail/runtime` module and the target `@betrail/game-` bundle from your static origin with SHA-384 Subresource Integrity (`manifest.json`), then mount ``: ```html ``` - **`api-base`:** When omitted, `` calls the host page's own origin. Whenever your casino origin differs from the BetPlug API (for example `http://127.0.0.1:3000` vs `http://127.0.0.1:8080`, or `https://casino.example` vs `https://api.betrail.example`), pass `api-base="https://api.betrail.example"` (or call `await el.bootstrapLaunchToken(launchToken, apiBase)`), allow that API origin in your `connect-src`, and register your casino origin via `PUT /console/brands/{brand}/origins/{environment}` ([Getting started](/docs/getting-started)). - **`live-origin` (live games only):** For `trapdoor`, `kombat-multiplayer`, `stack-o-pass`, `crash`, and `meme-trade`, also set `live-origin="wss://live.betrail.example"` (canonical `wss://`, or loopback `ws://` in local dev) and add it to your page's `connect-src`. - **Host events without an iframe:** Call `el.connectHostBridge({ allowedOrigins: [location.origin], targetWindow: { postMessage(message) { ... } } })` to receive the exact `betrail:v1` event envelopes in-page. ## 3. Option B: Isolated play host iframe Mount `url` returned by `POST /v1/launch` inside a sandboxed ` ``` - **Lobby navigation (`return_url`):** Include `allow-top-navigation-by-user-activation` when passing `return_url` to `POST /v1/launch`; omit it if your host page renders its own lobby chrome. - **Play host deployment (`BETRAIL_PLAY_ORIGIN` / `BETRAIL_PLAY_LISTEN`):** - `POST /v1/launch` builds `url` from `BETRAIL_PLAY_ORIGIN` (default `https://play.betrail.example/?token=…`). - The public API listener (`:8080`) serves no HTML; enable the dedicated play host listener by setting `BETRAIL_PLAY_LISTEN`, `BETRAIL_PLAY_ASSETS_DIR` (output of `betrail-clients build --out `), and `BETRAIL_PLAY_API_ORIGIN` (default `http://127.0.0.1:8080` locally). Every module's SHA-384 digest is verified against `manifest.json` at startup. - On each page load, the play host inspects the launch without consuming it and emits `frame-ancestors` restricted to that brand environment's `allowed_origins`. Unknown, expired, or already-exchanged tokens, mismatched routes, or brands without origins receive a plain-text refusal with `frame-ancestors 'none'`. - Plain `http://` is refused (`400`, no redirect so `?token=` is never echoed) outside loopback local dev (`BETRAIL_ENV=development` or `test`) or proxies in `BETRAIL_TRUSTED_PROXIES` with every `X-Forwarded-Proto` hop equal to `https`. Non-canonical paths (`//dice`, `/x/../dice`) return `404` with no redirect. - Valkey rate limits page loads (`BETRAIL_PLAY_ADDRESS_PER_SECOND=50`, `BETRAIL_PLAY_GLOBAL_PER_SECOND=5000`), returning `429` + `Retry-After` before reading the launch. - Locally, run `BETRAIL_PLAY_LISTEN=127.0.0.1:8084` with `BETRAIL_PLAY_ORIGIN=http://127.0.0.1:8084`, mount `` directly (Option A), or serve `renderPlayHostDocument` from `@betrail/runtime` directly (byte-identical to the server play host, as shown in `./examples/next-casino`). ## 4. Building & hosting client bundles > **Tip:** All `@betrail/game-` client bundles are built directly from your verified repository checkout with zero external dependencies (Node `>= 22.18`). ```sh betrail-clients build --out ./public/betrail-assets ``` The build enforces the `<= 150 KB` gzipped combined first-load budget (`maxGameGzipBytes: 153600`) and emits versioned ES modules plus `manifest.json`: - `/runtime/v0.1.0/betrail-runtime.js` — shared `@betrail/runtime` module registering ``. - `/embed/v0.1.0/betrail-embed.js` — host-page bridge helper (`createBetrailEmbed`, `validateBridgeEvent`, `validateBridgeCommand`, `betrail:v1` constants) for Option B iframes (not loaded by game bundles). - `/games//v0.1.0/betrail-.js` — one zero-raster game plugin bundle per catalog game keyed by canonical OpenAPI `GameSlug` (for example `dice`, `limbo`, `packs`, `plinko`, `roulette`, `diamonds`, `grimoire-of-gains`, `pharaoh-pump`, `shogun-shiba`). Preserve the `/runtime/v0.1.0/…` and `/games//v0.1.0/…` relative tree so game bundles resolve `../../../runtime/v0.1.0/betrail-runtime.js`. - `manifest.json` — `{ version: "0.1.0", maxGameGzipBytes: 153600, runtime, embed, games }` with exact `path`, `bytes`, `gzipBytes`, and `integrity: "sha384-…"`. Read integrity hashes dynamically at render time. ## 5. Live demo (`mode="demo"`) & replay (`mode="replay"`) - **Simulated live demo (`mode="demo"`):** For live clients (`crash`, `kombat-multiplayer`, `meme-trade`, `trapdoor`, `stack-o-pass`), `` needs no token: it runs a simulated show in the browser with a fake `DEMO` balance under the badge `DEMO (simulated show)`. It opens no socket, places no bet, and creates no server record. Its verdict replays the simulated bet locally in the browser, never a server record, so both BetPlug's showcase and an operator's page may embed it. - **No demo token or session on an operator's origin:** Leave `token` off — `POST /v1/launch` with `mode: "demo"` for a live game returns `409 not_offered`. The element asks for no demo session for a live client (it sends no `POST /v1/demo/sessions`, which on an operator's origin would return `403 origin_not_allowed`), so the host bridge receives no error event. See [Game catalog & live](/docs/live-games-and-catalog) for each client's exact badge and verdict. - **Settled round replay (`mode="replay"`):** Pass `mode="replay"`, `token`, and `round-id` to fetch one settled round's record and replay it visually without opening a live socket. A live show bet becomes readable once its show reveals its seed. ## 6. Typed `postMessage` host bridge (`betrail:v1`) Both directions share one strict envelope (`@betrail/runtime`). Messages with missing or extra keys, unknown channels, oversized payloads (`> 8192` UTF-8 bytes, `BRIDGE_MAX_MESSAGE_BYTES`), or event strings over `256` chars are dropped silently: - **Events, client -> your page:** `{ channel: "betrail:v1", kind: "event", event, payload }` - **Commands, your page -> client:** `{ channel: "betrail:v1", kind: "command", command, payload }` | `event` | `payload` | |---|---| | `ready` | `{ game: string, mode: "real" \| "demo" \| "replay", locale: string }` | | `balance` | `{ balance: string, currency: string }` | | `round-start` | `{ stake: string, currency: string }` | | `round-end` | `{ roundId: string, payout: string, profit: string, win: boolean, currency: string }` | | `error` | `{ code: string, message: string }` | | `resize` | `{ width: number, height: number }` | | `command` | `payload` | |---|---| | `setLocale` | `{ locale: string }`: one of `en`, `es`, `pt-BR`, `de`, `fr`, `tr`, `ja`, `ko`, `ar`, `he` | | `setTheme` | `{ theme: "dark" \| "light" \| ThemeOverride }`: an override is at most 4096 bytes of JSON | | `setSound` | `{ enabled: boolean }`: sound is off until you enable it | Every amount (`balance`, `stake`, `payout`) is an exact decimal string; `profit` is signed `payout - stake`. Commands and `resize` coalesce to once per animation frame (last write wins). Breaking protocol revisions will ship on a new channel (`betrail:v2`); pin `betrail:v1`. ### Origin locking with `createBetrailEmbed` Use `/embed/v0.1.0/betrail-embed.js` (loaded with `manifest.embed.integrity`) instead of raw `window.addEventListener("message")` boilerplate: ```ts no-eval import { createBetrailEmbed } from "/betrail-assets/embed/v0.1.0/betrail-embed.js"; const embed = createBetrailEmbed({ frame: document.getElementById("betrail-frame") as HTMLIFrameElement, playOrigin: "https://play.betrail.example", onEvent(ev) { if (ev.event === "balance") updateHeaderBalance(ev.payload.balance, ev.payload.currency); if (ev.event === "resize") resizeFrame(ev.payload.height); }, }); embed.send("setTheme", { theme: "dark" }); embed.send("setLocale", { locale: "pt-BR" }); // On unmount: embed.dispose(); ``` If handling `message` manually: verify **both** `event.origin === "https://play.betrail.example"` **and** `event.source === iframe.contentWindow`, and post commands with `targetOrigin = "https://play.betrail.example"` — never `"*"`. When your brand has multiple configured origins, append `&origin=` to the iframe URL so the client locks onto your page immediately (otherwise it falls back to `document.referrer` or queues up to 32 events until your first command). ## 7. White-label theming & stored brand themes - **Plan gating on the play host:** `ThemeOverride` fields (`colors`, `radii`, `fontFamily`, passed via `?theme=` or `setTheme`) apply on the play host when your subscription includes `white_label` (`GET /console/billing/subscription`, Scale and Enterprise) and is `active` or `grace`. Otherwise the client applies mode (`"dark"` | `"light"`) only and emits `{ event: "error", payload: { code: "theme_not_in_plan", ... } }`. Option A Web Components on your own origin accept every valid override. - **Stored brand themes:** Owners and Admins can save one default theme per brand across both environments via `PUT /console/brands/{brand}/theme` (`{"theme": ThemeOverride}`, validated identically to `setTheme`; `GET` reads, `DELETE` clears, passkey step-up `brand.theme.set` / `brand.theme.clear`, `403 forbidden` if the plan lacks `white_label`). Per-session `?theme=` or `setTheme` overrides the stored theme for that session only. ## 8. CSP & Subresource Integrity checklist | Surface | Required CSP & security headers | |---|---| | **Play host (Option B, automatic)** | `frame-ancestors `, `connect-src []`, `script-src 'nonce-…' 'strict-dynamic'`, `require-trusted-types-for 'script'; trusted-types betrail`, `Referrer-Policy: no-referrer`, `Cache-Control: no-store`, SHA-384 SRI on runtime & game modules. | | **Casino page hosting `` (Option A)** | Load `betrail-runtime.js` and `betrail-.js` with `integrity="sha384-…"` from `manifest.json`; add BetPlug's API origin (and `wss://live.betrail.example` for live games) to your `connect-src`; register your exact casino origin in Brand Allowed Origins. | | **Casino page framing play host (Option B)** | Add `https://play.betrail.example` to your page's `frame-src`; load `betrail-embed.js` with `manifest.embed.integrity`; never use `targetOrigin: "*"`. | ## 9. Reality checks & jurisdictions - **Jurisdiction policy (`403 jurisdiction_not_allowed`):** Pass optional ISO 3166-1 alpha-2 `jurisdiction` on `POST /v1/launch` (or headless `POST /v1/rounds`). BetPlug enforces brand responsible-gaming jurisdiction blocks (`sandbox` & `live`) and operator platform live allowlists (`live` only) before consuming any nonce or calling your wallet. - **Reality checks (`409 reality_check_due`):** When a brand enables periodic reality-check intervals in Console, wagers after the interval return `409 reality_check_due` with `elapsed_seconds` and `net_result` in the RFC 9457 `Problem` body. Embedded clients display the summary and call `POST /v1/sessions/current/reality-check` (`Idempotency-Key` required) once the player acknowledges, after which wagers resume normally. ## Validating bridge messages & SRI digests (runnable sample) ```ts import assert from "node:assert/strict"; import crypto from "node:crypto"; const PLAY_ORIGIN = "https://play.betrail.example"; const AMOUNT_RE = /^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$/; const SIGNED_AMOUNT_RE = /^-?(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$/; type BetrailEvent = | { event: "ready"; payload: { game: string; mode: "real" | "demo" | "replay"; locale: string } } | { event: "balance"; payload: { balance: string; currency: string } } | { event: "round-start"; payload: { stake: string; currency: string } } | { event: "round-end"; payload: { roundId: string; payout: string; profit: string; win: boolean; currency: string } } | { event: "error"; payload: { code: string; message: string } } | { event: "resize"; payload: { width: number; height: number } }; function readBetrailEvent(ev: { origin: string; source: unknown; data: unknown }, frame: unknown): BetrailEvent | null { if (ev.origin !== PLAY_ORIGIN || ev.source !== frame) return null; const msg = ev.data as Record | null; if (!msg || typeof msg !== "object" || msg.channel !== "betrail:v1" || msg.kind !== "event") return null; if (Object.keys(msg).some((k) => !["channel", "kind", "event", "payload"].includes(k))) return null; const p = msg.payload as Record | null; if (!p || typeof p !== "object") return null; const text = (k: string) => typeof p[k] === "string"; const amount = (k: string, re = AMOUNT_RE) => typeof p[k] === "string" && re.test(p[k] as string); const ok = (msg.event === "ready" && text("game") && ["real", "demo", "replay"].includes(p.mode as string) && text("locale")) || (msg.event === "balance" && amount("balance") && text("currency")) || (msg.event === "round-start" && amount("stake") && text("currency")) || (msg.event === "round-end" && text("roundId") && amount("payout") && amount("profit", SIGNED_AMOUNT_RE) && typeof p.win === "boolean" && text("currency")) || (msg.event === "error" && text("code") && text("message")) || (msg.event === "resize" && Number.isFinite(p.width) && Number.isFinite(p.height)); return ok ? ({ event: msg.event, payload: p } as BetrailEvent) : null; } const frame = { id: "betrail-frame" }; const validEnd = { channel: "betrail:v1", kind: "event", event: "round-end", payload: { roundId: "rnd_01JBX7Q2", payout: "0.00000000", profit: "-0.00100000", win: false, currency: "BTC" }, }; assert.ok(readBetrailEvent({ origin: PLAY_ORIGIN, source: frame, data: validEnd }, frame)); assert.equal(readBetrailEvent({ origin: "https://casino.example", source: frame, data: validEnd }, frame), null); assert.equal(readBetrailEvent({ origin: PLAY_ORIGIN, source: {}, data: validEnd }, frame), null); assert.equal( readBetrailEvent({ origin: PLAY_ORIGIN, source: frame, data: { channel: "betrail:v1", kind: "event", event: "balance", payload: { balance: 0.1, currency: "BTC" } } }, frame), null, ); const sampleIntegrity = `sha384-${crypto.createHash("sha384").update("export {};\n", "utf8").digest("base64")}`; assert.match(sampleIntegrity, /^sha384-[A-Za-z0-9+/]{64}$/); ``` --- Source: /docs/webhooks.md --- # Webhooks (`round.settled`, `credits.low`, `credits.exhausted`) BetPlug delivers asynchronous operator events from a transactional PostgreSQL outbox (`api/asyncapi.yaml`) through BetPlug's DNS-pinning SSRF guard (no redirects, 64 KB cap) until your HTTPS endpoint answers with any `2xx` status. ## Quick SDK receivers (recommended) Verify the raw HTTP body **before** `JSON.parse` using any of the four [Official SDKs](/docs/sdk): ```ts no-eval tab import { verifyWebhook, isRoundSettledEvent, isCreditsLowEvent, isCreditsExhaustedEvent, parseUsdMicros } from "./sdk/ts/src/index.ts"; // Express / Next.js Route Handler: read raw bytes via await req.arrayBuffer() const verified = await verifyWebhook({ method: "POST", target: requestRawPathAndQuery, // exact wire path + query, e.g. "/webhooks/betrail?site=1" headers: req.headers, body: new Uint8Array(await req.arrayBuffer()), secrets: [process.env.BETRAIL_WEBHOOK_SECRET!, process.env.BETRAIL_WEBHOOK_PREV_SECRET].filter(Boolean) as string[], nonceStore: myValkeyNonceStore, // SET NX EX 630 }); if (await alreadyProcessed(verified.webhookId)) return new Response("ok", { status: 200 }); // deduplicate on Betrail-Webhook-Id if (isRoundSettledEvent(verified.event)) await recordSettlement(verified.event.data); else if (isCreditsLowEvent(verified.event) || isCreditsExhaustedEvent(verified.event)) { await alertOps(verified.event.type, parseUsdMicros(verified.event.data.balance)); } return new Response("ok", { status: 200 }); ``` ```go no-eval tab event, err := betrail.VerifyHTTPWebhook(r.Context(), r, secrets, nonceStore, time.Time{}) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } if round, ok, _ := event.AsRoundSettled(); ok { recordSettlement(round) } else if low, ok, _ := event.AsCreditsLow(); ok { alertOps("credits.low", low.Balance) } else if ex, ok, _ := event.AsCreditsExhausted(); ok { alertOps("credits.exhausted", ex.Balance) } w.WriteHeader(http.StatusOK) ``` ```python no-eval tab event = verify_webhook("POST", request.full_path, raw_body, request.headers, secrets, nonce_store) if event.is_round_settled(): record_settlement(event.parse_round_settled()) elif event.is_credits_low(): alert_ops("credits.low", event.parse_credits_low().balance) elif event.is_credits_exhausted(): alert_ops("credits.exhausted", event.parse_credits_exhausted().balance) ``` ```php no-eval tab $event = Webhooks::verifyGlobals([$activeSecret, $prevSecret], $nonceStore); if (($round = $event->asRoundSettled()) !== null) { recordSettlement($round); } elseif ($event->isCreditsLow() || $event->isCreditsExhausted()) { alertOps($event->type, $event->data['balance']); } ``` ## Headers & verification order | Header | Pattern | Purpose | |---|---|---| | `Betrail-Webhook-Id` | `string` (equals `body.id`) | Stable event ID across every retry. Deduplicate business side effects strictly on this ID. | | `Betrail-Timestamp` | `^[0-9]{10}$` | Unix seconds when this delivery attempt was signed (`±300 s` window). | | `Betrail-Nonce` | `^[A-Za-z0-9_-]{16,64}$` | Fresh per delivery attempt. Claim in Valkey (`SET NX EX 630`) after MAC verification. | | `Betrail-Signature` | `^v1=[0-9a-f]{64}(,v1=[0-9a-f]{64})?$` | `betrail-v1` HMAC-SHA256 keyed with the brand's webhook secret (`v1=,v1=` during 24 h rotation). | > **Security:** Always verify in this exact order: (1) reject non-`identity` `Content-Encoding` (`415`) and bodies `> 65,536` bytes (`413`), (2) verify `Betrail-Timestamp` (`±300 s`) and constant-time `Betrail-Signature` over the **original raw request-target** and exact raw body bytes **before** `JSON.parse`, (3) claim `Betrail-Nonce` (`SET NX EX 630`), and (4) deduplicate by `Betrail-Webhook-Id` (returning `200` on duplicates). ## Outbox retry schedule, dead-letter replay & credit-alert emails BetPlug's transactional worker (`betrail-worker`) guarantees at-least-once delivery without dropping events: - **Retry backoff schedule:** Full-jitter exponential backoff drawn from CSPRNG starting at **`1 s` base**, doubling per attempt up to a **`15 m` cap**, across a **`24 h` delivery window** (per-operator concurrency cap: `8` live leases, `30 s` lease duration). - **Stuck-money alerting:** Any unacknowledged settlement/money outbox event older than **`1 h`** raises a stuck-money alert automatically. - **Dead-letter queue & Console replay:** After `24 h` without a `2xx` answer, an event transitions to status **`dead`**, raising an operator alert. Inspect full delivery attempts and endpoint health (`GET /console/webhooks/deliveries/{id}` and `GET /console/brands/{brand}/webhooks/{environment}/health`) and **replay `dead` events** directly from BetPlug Console `/webhooks` (which starts a fresh 24-hour retry window). - **Credit-alert emails alongside webhooks:** Whenever `credits.low` or `credits.exhausted` fires on `live`, `betrail-worker` delivers **both** the signed webhook AND an operator alert email over the shared SMTP relay (`BETRAIL_SMTP_*`, mandatory STARTTLS off loopback or when credentials are set). Inspect unified webhook + email delivery status in Console (`/console/billing/alerts/history`). > **Warning:** Return `2xx` within `3 s` — acknowledge receipt immediately after durable persistence (or enqueueing locally) and process heavy downstream analytics asynchronously. ## Event payloads (`api/asyncapi.yaml`) Every event shares the `WebhookEvent` envelope `{ id, type, created_at, environment, data }` (`environment` is `"sandbox"` | `"live"`; both credit events are always `"live"` because prepaid USD credits pay for live play only). Remember that in `round.settled`, `payout` already includes `refund` (`GGR = stake - payout`). ### `round.settled` (`RoundSettledEvent`) ```json { "id": "evt_01JBX7Q2W3E4R5T6", "type": "round.settled", "created_at": "2026-10-28T17:00:00Z", "environment": "sandbox", "data": { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "dice", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 1, "stake": "0.00100000", "payout": "0.00197999", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "roll": 3317, "win": true }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "seed-1", "nonce": 42 }, "created_at": "2026-10-28T17:00:00Z", "settled_at": "2026-10-28T17:00:00Z" } } ``` ### `credits.low` (`CreditsLowEvent`) & `credits.exhausted` (`CreditsExhaustedEvent`) `credits.low` fires once when prepaid USD credits cross below your configured threshold; `credits.exhausted` fires once when a posting takes credits from `> 0` to `<= 0` (new live rounds answer `402 credits_exhausted` until topped up; open rounds still finish and sandbox keeps working; one posting can emit both events in no guaranteed order): ```json tab=credits.low { "id": "evt_low_01JBX7Q2W3", "type": "credits.low", "created_at": "2026-10-28T17:05:00Z", "environment": "live", "data": { "balance": "25.000000", "threshold": "50.000000" } } ``` ```json tab=credits.exhausted { "id": "evt_ex_01JBX7Q2W4", "type": "credits.exhausted", "created_at": "2026-10-28T17:12:00Z", "environment": "live", "data": { "balance": "0.000000", "threshold": "0.000000" } } ``` > **Tip:** Parse `balance` and `threshold` (6-decimal micro-USD strings, potentially negative after a GGR fee or reversed top-up) using `parseUsdMicros` / `ParseUsdMicros` — never `parseFloat`. ## Verifying raw-byte webhooks & rotation overlap (runnable sample) ```ts import assert from "node:assert/strict"; import path from "node:path"; import { pathToFileURL } from "node:url"; const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd(); const sdk = await import(pathToFileURL(path.join(repoRoot, "sdk", "ts", "src", "index.ts")).href); const activeSecret = "whsec-rotated-new-32bytes-secret!"; const prevSecret = "whsec-rotated-old-32bytes-secret!"; const nonces = new sdk.InMemoryNonceStore(); const processed = new Set(); const rawBody = Buffer.from( JSON.stringify({ id: "evt_01JBX7Q2W3E4R5T6", type: "credits.exhausted", created_at: "2026-10-28T17:12:00Z", environment: "live", data: { balance: "0.000000", threshold: "0.000000" }, }), "utf8", ); // 1. First delivery during 24 h rotation overlap (signed with previous secret) succeeds const attempt1 = sdk.signRequest({ method: "POST", target: "/hooks/betrail?site=1", body: rawBody, secrets: [prevSecret] }); const verified1 = await sdk.verifyWebhook({ method: "POST", target: "/hooks/betrail?site=1", headers: { "betrail-webhook-id": "evt_01JBX7Q2W3E4R5T6", "betrail-timestamp": attempt1.timestamp, "betrail-nonce": attempt1.nonce, "betrail-signature": attempt1.signature, }, body: rawBody, secrets: [activeSecret, prevSecret], nonceStore: nonces, }); assert.equal(sdk.isCreditsExhaustedEvent(verified1.event), true); assert.equal(sdk.isCreditsLowEvent(verified1.event), false); assert.equal(sdk.isRoundSettledEvent(verified1.event), false); processed.add(verified1.webhookId); // 2. Replayed identical nonce is rejected; outbox retry with fresh nonce is accepted & deduplicated by Betrail-Webhook-Id await assert.rejects(() => sdk.verifyWebhook({ method: "POST", target: "/hooks/betrail?site=1", headers: { "betrail-webhook-id": "evt_01JBX7Q2W3E4R5T6", "betrail-timestamp": attempt1.timestamp, "betrail-nonce": attempt1.nonce, "betrail-signature": attempt1.signature, }, body: rawBody, secrets: [activeSecret, prevSecret], nonceStore: nonces, }), ); const attempt2 = sdk.signRequest({ method: "POST", target: "/hooks/betrail?site=1", body: rawBody, secrets: [activeSecret] }); const verified2 = await sdk.verifyWebhook({ method: "POST", target: "/hooks/betrail?site=1", headers: { "betrail-webhook-id": "evt_01JBX7Q2W3E4R5T6", "betrail-timestamp": attempt2.timestamp, "betrail-nonce": attempt2.nonce, "betrail-signature": attempt2.signature, }, body: rawBody, secrets: [activeSecret, prevSecret], nonceStore: nonces, }); assert.equal(processed.has(verified2.webhookId), true); ``` --- Source: /docs/live-games-and-catalog.md --- # Game catalog, live games protocol & reference casinos BetPlug ships a **continuously expanding catalog of provably-fair house games** across five runtime shapes ([`/api/openapi.yaml`](/api/openapi.yaml), [`/api/asyncapi.yaml`](/api/asyncapi.yaml)): Instant games, Stateful Session games, Originals Slots, shared Live Shows, and per-operator Live Tables. Every game below is **mounted and served by the BetPlug API across `sandbox` and `live`**, executing deterministic fixed-point integer arithmetic with zero floats on money or outcomes. ## 1. Full game catalog & runtime matrix ### Instant games (single-request settle) Every Instant game settles in one round-trip (`POST /v1/rounds` headless or `POST /v1/session/rounds` embedded) and ships a zero-raster SVG + TypeScript `` client bundle (`<= 150 KB` gzip) as `@betrail/game-`: | `GameSlug` | Engine ID & version | Client bundle | RNG stream, params & availability | | --- | --- | --- | --- | | `dice` | `DICE` v1 | `@betrail/game-dice` | `dice-sha512` (`SHA-512(server_seed:client_seed:nonce)`); [`DiceParams`](/docs/api-reference#diceparams) (`direction`, `chance`, `payout`); mounted in the BetPlug API | | `limbo` | `LIMBO` v1 | `@betrail/game-limbo` | `hmac-nonce` (`HMAC-SHA256(server_seed, client_seed:nonce)`, no `:cursor`, 12-dec `bcdiv` byte sum `S`); [`LimboParams`](/docs/api-reference#limboparams) (`target`); mounted in the BetPlug API | | `plinko` | `PLINKO` v1 | `@betrail/game-plinko` | `plinko-hmac` (`HMAC-SHA256(server_seed, client_seed:nonce:c)`, `c = 0` for 8 pins / `c = 0, 1` for 9..16 pins); 27 pinned Binomial paytables (`8..16` pins x `LOW`/`MEDIUM`/`HIGH`); [`PlinkoParams`](/docs/api-reference#plinkoparams); mounted in the BetPlug API | | `roulette` | `ROULETTE` v1 | `@betrail/game-roulette` | `hmac-nonce` (`HMAC-SHA256(server_seed, client_seed:nonce)`, no `:cursor`, 12-dec `bcdiv` byte sum `S`); single-zero 37-pocket wheel; [`RouletteParams`](/docs/api-reference#rouletteparams) (`chips`); mounted in the BetPlug API | | `diamonds` | `DIAMONDS` v1 | `@betrail/game-diamonds` | `hmac-nonce` (`HMAC-SHA256(server_seed, client_seed:nonce)`, no `:cursor`, 12-dec `bcdiv` byte sum `S`); 5-gem draw across 7 hands; [`DiamondsParams`](/docs/api-reference#diamondsparams) (`{}`); mounted in the BetPlug API | | `packs` | `PACKS` v1 | `@betrail/game-packs` | `FairRandom`; 5-card booster pack over 242-card table (`RTP = 19/20`); [`PacksParams`](/docs/api-reference#packsparams) (`{}`); mounted in the BetPlug API | | `range-dice` | `RANGEDICE` v1 | `@betrail/game-range-dice` | `FairRandom`; configurable `[low, high]` interval; [`RangediceParams`](/docs/api-reference#rangediceparams) (`mode`, `target`/`ranges`, `multiplier`); mounted in the BetPlug API | | `wheel` | `WHEEL` v1 | `@betrail/game-wheel` | `FairRandom`; risk-tiered segment paytables; [`WheelParams`](/docs/api-reference#wheelparams) (`risk`, `segments`); mounted in the BetPlug API | | `drill` | `DRILL` v1 | `@betrail/game-drill` | `FairRandom`; multi-target depth multiplier; [`DrillParams`](/docs/api-reference#drillparams) (`target`, `pick`); mounted in the BetPlug API | | `slide` | `SLIDE` v1 | `@betrail/game-slide` | `FairRandom`; target crash-multiplier reel; [`SlideParams`](/docs/api-reference#slideparams) (`target`); mounted in the BetPlug API | | `cases` | `CASES` v1 | `@betrail/game-cases` | `FairRandom`; weighted mystery-case paytables; [`CasesParams`](/docs/api-reference#casesparams) (`difficulty`); mounted in the BetPlug API | | `bars` | `BARS` v1 | `@betrail/game-bars` | `FairRandom`; multi-bar reveal grid; [`BarsParams`](/docs/api-reference#barsparams) (`difficulty`, `picks`); mounted in the BetPlug API | | `keno` | `KENO` v1 | `@betrail/game-keno` | `FairRandom`; Fisher-Yates 10-of-40 draw (`1..10` picks); [`KenoParams`](/docs/api-reference#kenoparams) (`risk`, `picks`); mounted in the BetPlug API | | `darts` | `DARTS` v1 | `@betrail/game-darts` | `FairRandom`; radial board ring paytables; [`DartsParams`](/docs/api-reference#dartsparams) (`difficulty`); mounted in the BetPlug API | | `tarot` | `TAROT` v1 | `@betrail/game-tarot` | `FairRandom`; 3-arcana multiplier product; [`TarotParams`](/docs/api-reference#tarotparams) (`difficulty`); mounted in the BetPlug API | | `baccarat` | `BACCARAT` v1 | `@betrail/game-baccarat` | `FairRandom`; Punto Banco third-card tableau (`player` / `banker` / `tie` + side bets); [`BaccaratParams`](/docs/api-reference#baccaratparams) (`bets`); mounted in the BetPlug API | | `kaboom` | `KABOOM` v1 | `@betrail/game-kaboom` | `FairRandom`; instant minefield preset sweep (`cap_rule: refuse`); [`KaboomParams`](/docs/api-reference#kaboomparams) (`charge`, `spot`); mounted in the BetPlug API | | `tilt` | `TILT` v1 | `@betrail/game-tilt` | `FairRandom`; balance-beam multiplier (`cap_rule: refuse`); [`TiltParams`](/docs/api-reference#tiltparams) (`notch`); mounted in the BetPlug API | ### Stateful session games (multi-step `open` -> `/actions`) Stateful games debit stake once at `POST /v1/rounds` (or `POST /v1/session/rounds`), advance deterministically via `POST /v1/rounds/{id}/actions` (or `/v1/session/rounds/{id}/actions`) with monotonic `step >= 1`, block seed rotation while a round is `open` (`409 round_open`), and settle on cash-out, terminal loss, or `POST /v1/players/{player_ref}/force-close`. Player `do: "force_close"` is always refused (`422 invalid_action`). | `GameSlug` | Engine ID & version | Availability status | Mechanics & schemas | | --- | --- | --- | --- | | `chicken` | `CHICKEN` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Lane-stepping survival ladder (`step`, `cashout`) — [`ChickenParams`](/docs/api-reference#chickenparams) / [`ChickenAction`](/docs/api-reference#chickenaction) | | `pump` | `PUMP` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Balloon inflation multiplier ladder (`pump`, `cashout`) — [`PumpParams`](/docs/api-reference#pumpparams) / [`PumpAction`](/docs/api-reference#pumpaction) | | `mines` | `MINES` v1 | **Mounted in the BetPlug API** (`FairRandom`) | 5x5 grid (`1..24` mines; `sweep`, `cashout`; note preset `(12, 11)` returns `409 not_offered`) — [`MinesParams`](/docs/api-reference#minesparams) / [`MinesAction`](/docs/api-reference#minesaction) | | `towers` | `TOWERS` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Multi-floor climb across difficulty tiers (`sweep`, `cashout`) — [`TowersParams`](/docs/api-reference#towersparams) / [`TowersAction`](/docs/api-reference#towersaction) | | `blackjack` | `BLACKJACK` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Infinite shoe (`hit`, `stand`, `double`, `split`, `insurance`, `no_insurance`) — [`BlackjackParams`](/docs/api-reference#blackjackparams) / [`BlackjackAction`](/docs/api-reference#blackjackaction) | | `hilo` | `HILO` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Sequential card higher/lower/skip chain (`guess`, `skip`, `cashout`) — [`HiloParams`](/docs/api-reference#hiloparams) / [`HiloAction`](/docs/api-reference#hiloaction) | | `snakes` | `SNAKES` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Dice-driven board path with snake hazards (`roll`, `cashout`) — [`SnakesParams`](/docs/api-reference#snakesparams) / [`SnakesAction`](/docs/api-reference#snakesaction) | | `flip` | `FLIP` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Compounding coin-flip streak (`flip`, `cashout`) — [`FlipParams`](/docs/api-reference#flipparams) / [`FlipAction`](/docs/api-reference#flipaction) | | `rps` | `RPS` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Multi-step rock-paper-scissors streak (`throw`, `cashout`) — [`RpsParams`](/docs/api-reference#rpsparams) / [`RpsAction`](/docs/api-reference#rpsaction) | | `moles` | `MOLES` v1 | **Mounted in the BetPlug API** (`FairRandom`) | Whack-a-mole grid survival ladder (`hit`, `cashout`) — [`MolesParams`](/docs/api-reference#molesparams) / [`MolesAction`](/docs/api-reference#molesaction) | | `video-poker` | `VIDEOPOKER` v1 | **Mounted in the BetPlug API** (`FairRandom`) | 5-card draw + hold (`Jacks or Better`; `draw`) — [`VideopokerParams`](/docs/api-reference#videopokerparams) / [`VideopokerAction`](/docs/api-reference#videopokeraction) | | `sky-rush` | `SKYRUSH` v1 | **Mounted in the BetPlug API** (`FairRandom`, `cap_rule: refuse`) | Step-by-step altitude cash-out (`fly`, `cashout`) — [`SkyrushParams`](/docs/api-reference#skyrushparams) / [`SkyrushAction`](/docs/api-reference#skyrushaction) | | `dead-shot` | `DEADSHOT` v1 | **Mounted in the BetPlug API** (`FairRandom`, `cap_rule: refuse`) | Chamber cylinder survival (`fire`, `stop`) — [`DeadshotParams`](/docs/api-reference#deadshotparams) / [`DeadshotAction`](/docs/api-reference#deadshotaction) | | `meme-kombat` | `KOMBAT` v1 | **Mounted in the BetPlug API** (`FairRandom`, `cap_rule: refuse`) | Single-player fighter duel (`next`, `live_bet`) — [`KombatParams`](/docs/api-reference#kombatparams) / [`KombatAction`](/docs/api-reference#kombataction) | | `stack-packs` | `STACKPACKS` v1 | **Mounted in the BetPlug API** (`FairRandom`, `cap_rule: refuse`) | Progressive pack-stacking session (`draw`, `cashout`) — [`StackpacksParams`](/docs/api-reference#stackpacksparams) / [`StackpacksAction`](/docs/api-reference#stackpacksaction) | ### Originals slots (single-nonce spin + bonus rounds) Each Originals Slot runs on `OriginalsSlotEngine`, consuming a single `(server_seed, client_seed, nonce)` commitment per paid spin (including triggered cascades and free-spin bonus rounds): | `GameSlug` | Engine ID & version | Client package | Bundle asset path | | --- | --- | --- | --- | | `grimoire-of-gains` | `GRIMOIRE` v1 | `@betrail/game-grimoire-of-gains` | `/games/grimoire-of-gains/v0.1.0/betrail-grimoire-of-gains.js` | | `pharaoh-pump` | `PHARAOH` v1 | `@betrail/game-pharaoh-pump` | `/games/pharaoh-pump/v0.1.0/betrail-pharaoh-pump.js` | | `shogun-shiba` | `SHOGUN` v1 | `@betrail/game-shogun-shiba` | `/games/shogun-shiba/v0.1.0/betrail-shogun-shiba.js` | All three are mounted in the BetPlug API (`FairRandom`): `params` is `{}` ([`SlotParams`](/docs/api-reference#slotparams)), and the settled `view` is [`SlotView`](/docs/api-reference#slotview). > **Tip:** New sandbox brands enable the full catalog automatically on onboarding. Existing brands can enable additional games anytime in Console or via `PUT /console/brands/{brand}/games/{environment}` (a disabled brand game returns `409 not_offered`). ### Live multiplayer shows & tables | `GameSlug` | Engine ID & version | Topology | Money entry route (REST) | Socket commands (`receiveLiveCommand`) | Isolation & policy | | --- | --- | --- | --- | --- | --- | | `trapdoor` | `TRAPDOOR` v1 (`ShowEngine`) | Shared environment show | `POST /v1/live/trapdoor/bets` (`createLiveBet`) | `TrapdoorCommand` (`snapshot`, `pick`, `bank`, `plan`) | Zero cross-operator crowd figures | | `kombat-multiplayer` | `KOMBATMP` v1 (`ShowEngine`) | Shared environment show | `POST /v1/live/kombat-multiplayer/bets` (`createLiveBet`) | `KombatmpCommand` (`snapshot`) | Zero cross-operator crowd figures | | `crash` | `CRASH` v1 (`ShowEngine`) | Shared environment show | `POST /v1/live/crash/bets` (`createLiveBet`) | `CrashCommand` (`snapshot`, `cashout`) | Zero cross-operator crowd figures | | `meme-trade` | `MEME_TRADE` v2 (`ShowEngine`) | Shared environment show | `POST /v1/live/meme-trade/buy-ins` (`createMemeTradeBuyIn`) | `LiveCommand` (`snapshot`, `open`, `close`, `sidebet`, `auto_sell`) | Enabled in `sandbox` & `live`; position adds refused; mid-round force-close retired; `OutageVoid` refunds open buy-ins; zero crowd figures | | `stack-o-pass` | `STACKOPASS` v1 (`Engine` live tables) | **Per-operator** 6-seat lobbies | `POST /v1/session/rounds` (`live_seat: { table, seat }`) | `StackOPassCommand` (`snapshot`, `watch`, `open`, `pass`, `cashout`, `leave`) | Per-operator tables; per-player `FairRandom` seeds | --- ## 2. Live games protocol & WebSocket state machine Live WebSocket channels, commands, and settlement frames are specified in [`/api/asyncapi.yaml`](/api/asyncapi.yaml). > **Warning:** Live multiplayer games (`trapdoor`, `kombat-multiplayer`, `stack-o-pass`, `crash`, `meme-trade`) **always require a real player session backed by a seamless wallet** (`mode: "real"`). Demo sessions are refused on live tickets and live bets with `403`. ### Live WebSocket state machine ```text [1] POST /v1/launch (mode:"real") -> [2] POST /v1/sessions (bts_) | v [3] POST /v1/live/{game}/tickets (0-byte body, Idempotency-Key) -> 30 s single-use ticket | v [4] WS wss://live.betrail.example/v1/live/{game} [Sec-WebSocket-Protocol: betrail.v1, ticket.] | +-----------------------------------------+-----------------------------------------+ | | | v v v SNAPSHOT (seq: 1) ---> WAITING (lobby) ---> ACTIVE (ticks / commands) ---> SETTLED (LiveSettledFrame) (or on seq gap: (stakes enter (crash cashout, trapdoor + seed revealed / skipped_link send snapshot cmd) via REST POST) pick/bank, meme-trade trades) + round.settled webhook ``` ### Concrete live WebSocket frames (`snapshot`, `tick`, `settled`, `skipped_link`) Every server frame uses the [`LiveFrame`](/docs/api-reference#liveframe) envelope (`type`, `game`, `seq`, `at`, plus optional `request_id` and `data`). Below are schema-valid [`CrashFrame`](/docs/api-reference#crashframe) examples (`CrashProjectedSnapshot`, `CrashTickFrame`, `CrashSettlement` carrying `CrashResultBeforeReveal`) and a [`MemeTradeFrame`](/docs/api-reference#memetradeframe) [`MemeTradeSkippedLink`](/docs/api-reference#memetradeskippedlink) broadcast from [`/api/asyncapi.yaml`](/api/asyncapi.yaml): ```json tab=snapshot { "type": "snapshot", "game": "crash", "seq": 1, "at": 1793238301300, "data": { "show": { "type": "snapshot", "show": { "type": "lobby", "chain": "crash-main-01", "index": 1042, "commit": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "salt": "00000000000000000001e3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4", "salt_source": "bitcoin:870000", "lobby_closes_at": 1793238300000 }, "phase": "ACTIVE", "step": 14, "tick": 13, "multiplier": "1.08", "elapsed_ms": 1300 }, "self_bets": [ { "bet_id": "bet_01jbx7q2w3e4r5t6y7u8i9o0pa", "currency": "BTC", "stake": "0.00100000", "settled": false } ] } } ``` ```json tab=tick { "type": "tick", "game": "crash", "seq": 15, "at": 1793238311600, "data": { "type": "tick", "tick": 116, "multiplier": "2.00", "elapsed_ms": 11600 } } ``` ```json tab=settled { "type": "settled", "game": "crash", "seq": 42, "at": 1793238311650, "data": { "bet_id": "bet_01jbx7q2w3e4r5t6y7u8i9o0pa", "currency": "BTC", "stake": "0.00100000", "payout": "0.00200000", "refund": "0.00000000", "settled_by": "play", "view": { "chain_id": "crash-main-01", "round_index": 1042, "ended_by": "CASHED_OUT", "reason": "MANUAL", "auto_cashout": null, "cap_multiplier": "1001.00", "settled_step": 117, "at_tick": 116, "elapsed_ms": 11600, "multiplier": "2.00", "seed_revealed_at_settle": false } } } ``` ```json tab=skipped_link { "type": "skipped_link", "game": "meme-trade", "seq": 43, "at": 1793238320000, "data": { "type": "skipped_link", "link": { "chain": "mt-main-01", "index": 1042, "commit": "113459eb7bb31bddee85ade5230d6ad5d8b2fb52879e00a84ff6ae1067a210d3", "salt": "00000000000000000001e3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4", "salt_source": "bitcoin:870000" }, "serverSeed": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8", "tick": 1842 } } ``` ### Step-by-step handshake, betting & settlement details 1. **Mint a `real` launch credential (`POST /v1/launch`)** and exchange it in the browser (`POST /v1/sessions`) for `bts_` (kept strictly in closure memory). 2. **Mint a 30-second single-use join ticket (`POST /v1/live/{game}/tickets`):** Send `Authorization: Bearer bts_…`, a fresh `Idempotency-Key`, and a **0-byte empty body**. Returns `201 { ticket: "v1..", url: "wss://live.betrail.example/v1/live/{game}", expires_at }`. The live server verifies HMAC and `Origin` first (`null` refused `403 origin_not_allowed`) and consumes `jti` last so rejected handshakes do not burn the ticket. 3. **Upgrade via `Sec-WebSocket-Protocol` (`joinTicket` scheme):** Connect with `new WebSocket(url, ["betrail.v1", "ticket." + ticket])`. Access logs scrub `Sec-WebSocket-Protocol` so tickets never leak; the server echoes `betrail.v1` only. 4. **Gap recovery:** Every frame carries monotonic `seq`. On any gap, send `{ "type": "snapshot", "request_id": "req_01" }` (`LiveCommand` requires `["type", "request_id"]` with `additionalProperties: false`). 5. **REST money entry & outbox settlement:** - **Shared shows (`trapdoor`, `kombat-multiplayer`, `crash`):** Stakes enter over REST via `POST /v1/live/{game}/bets` (`{ show, stake, params }`, `Idempotency-Key`), debiting `:0::debit` and crediting `:credit` on settlement. - **`MEME_TRADE` v2 (`meme-trade`):** Buy in over REST via `POST /v1/live/meme-trade/buy-ins` (`{ round, amount }`, `Idempotency-Key`, debiting `::b::debit`). In-round commands (`open`, `close`, `sidebet`, `auto_sell`) travel over WebSocket under the **tick barrier**. Position adds are refused, mid-round force-close retired (`POST /v1/players/{player_ref}/force-close` returns `200 {"rounds":[],"pending":0}` without touching `MEME_TRADE`; `PUT /v1/players/{player_ref}/status` revokes live sessions immediately; post-rug outbox credits run unconditionally; writer outages refund open buy-ins via `OutageVoid`). - **`STACKOPASS` (`stack-o-pass`):** Buy into a per-operator 6-seat table via `POST /v1/session/rounds` (`{ stake, params, live_seat: { table, seat } }`), play `open`/`pass`/`cashout` over WebSocket, and settle per hand via `:credit`. - **Unified `LiveSettlement` (`LiveSettledFrame`):** Emits `{ bet_id, currency, stake, payout, refund, settled_by: "play" | "force_close" | "outage", view }` over the socket alongside the signed `round.settled` webhook. ### Demo and replay in the embedded live clients Live games ship embedded clients: `crash`, `kombat-multiplayer`, `meme-trade`, `trapdoor` and `stack-o-pass` (`@betrail/game-`). `` for one of them needs no token and no session: it runs a simulated show in the browser (a simulated table for `stack-o-pass`) using a local seed chain (local seeds for `stack-o-pass`), the verifier's own maths, and a fake balance of `1000.00000000 DEMO`. It opens no socket, mints no ticket, places no bet, and sends no record anywhere. For these clients the element asks for no demo session: each client declares that its demo needs none, so the element sends no `POST /v1/demo/sessions`, on any origin. Nothing is refused, so the host bridge receives no error event, and the `stack-o-pass` cockpit displays only the simulated table's state. This behaves identically on an operator's origin and on BetPlug's (note that `POST /v1/demo/sessions` accepts only BetPlug's own site origins and returns `403 origin_not_allowed` on an operator's origin; Instant, Stateful, and Slot games still use it in demo mode). The stage and phase bar display a badge, and after each simulated bet settles, the client replays it locally in the browser, never a server record: | Client | Badge | Demo verdict | | --- | --- | --- | | `crash` | `DEMO (simulated show)` | `DEMO: the simulated bet replays from its revealed seed (no server record)` | | `kombat-multiplayer` | `DEMO (simulated show)` | `DEMO: the simulated bet replays from its revealed seed (no server record)` | | `meme-trade` | `DEMO (simulated show)` | `DEMO: the simulated round replays from its revealed seed (no server record)` | | `trapdoor` | `DEMO (simulated show)` | `DEMO: the simulated bean replays from its revealed seed (no server record)` | | `stack-o-pass` | `DEMO (simulated show)` | `DEMO: the simulated hand replays from its revealed seed (no server record)` | On an operator's origin, set `mode="demo"` with no `token`: `POST /v1/launch` with `mode: "demo"` for a live game returns `409 not_offered` ("This live game has no demo play."). `` exchanges the launch token, reads one settled round record (`GET /v1/session/rounds/{id}`), and replays it without opening a socket. A live show bet becomes readable once its show reveals its seed (`404` before then), displaying `VERIFIED MATCH (replay)` with chain anchor unanchored. A `stack-o-pass` hand replays once the player's seed pair rotates. ### Provable fairness & zero cross-operator crowd leakage - **Reverse hash chains (`TRAPDOOR`, `KOMBATMP`, `CRASH`, `MEME_TRADE`):** Each shared show pre-commits the terminal digest of a reverse `SHA-256` hash chain (`link_{k} = SHA256(link_{k+1})`) combined with an external block beacon published before betting opens, disclosing unused links via `skipped_link`. - **Zero cross-operator crowd figures:** Shared shows emit **zero** `round_totals`, **zero** aggregate player counts, and **zero** cross-player bet frames so no operator can subtract its own share to infer competitors' volume. `stack-o-pass` isolates tables strictly per operator. --- ## 3. Reference casinos (`examples/`) Three end-to-end reference casinos in the repository demonstrate headless REST play, `` / iframe embedding, `WalletHandler` with Ed25519 answer signing, and raw-body webhook verification: | Reference casino | Stack & SDK | Highlights | | --- | --- | --- | | `./examples/next-casino` | Next.js + TypeScript (`./sdk/ts`) | Server-side `BetrailClient`, `createWalletHandler` with Ed25519 answers, raw-byte `verifyWebhook`, `` + `betrail:v1` host bridge, strict nonce CSP, zero raster assets. | | `./examples/go-casino` | Go 1.27 `net/http` + `html/template` (`./sdk/go`) | Zero third-party dependencies, `betrail.NewClient`, `betrail.NewWalletHandler` (`GenerateEd25519WalletKeyPair` + `FileBackedNonceStore`), `betrail.VerifyHTTPWebhook` over `r.RequestURI`, SVG-only UI. | | `./examples/laravel-casino` | PHP 8.2+ / Laravel-style (`./sdk/php`) | `Betrail\Sdk\Client`, `WalletHandler` (`Ed25519::generateWalletKeyPair` + `FileBackedWalletBook` + `FileBackedNonceStore`), `Webhooks::verify` over raw `php://input` and `$_SERVER['REQUEST_URI']`, strict CSP iframe launch. | Each reference casino mounts representative games (`dice`, `packs`, `wheel`) and ships an end-to-end local-stack integration test suite. ## 4. Building join-ticket protocols & handling live frames (runnable sample) ```ts import assert from "node:assert/strict"; import crypto from "node:crypto"; function buildLiveProtocols(ticket: string): [string, string] { assert.match(ticket, /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/, "expected signed v1 join ticket"); return ["betrail.v1", `ticket.${ticket}`]; } const protocols = buildLiveProtocols("v1.eyJzaWQiOiJzZXNzXzAxIn0.c2lnbmF0dXJl"); assert.deepEqual(protocols, ["betrail.v1", "ticket.v1.eyJzaWQiOiJzZXNzXzAxIn0.c2lnbmF0dXJl"]); // Gap recovery commands carry "request_id" and CrashFrame settlements carry LiveFrame + CrashResultBeforeReveal const snapshotCmd = { type: "snapshot", request_id: "req_01" } as const; assert.deepEqual(Object.keys(snapshotCmd).sort(), ["request_id", "type"]); const settledFrame = { type: "settled" as const, game: "crash" as const, seq: 42, at: 1793238311650, data: { bet_id: "bet_01jbx7q2w3e4r5t6y7u8i9o0pa", currency: "BTC", stake: "0.00100000", payout: "0.00200000", refund: "0.00000000", settled_by: "play" as const, view: { chain_id: "crash-main-01", round_index: 1042, ended_by: "CASHED_OUT" as const, reason: "MANUAL" as const, auto_cashout: null, cap_multiplier: "1001.00", settled_step: 117, at_tick: 116, elapsed_ms: 11600, multiplier: "2.00", seed_revealed_at_settle: false as const, }, }, }; assert.ok(["play", "force_close", "outage"].includes(settledFrame.data.settled_by)); assert.equal(settledFrame.data.view.elapsed_ms, settledFrame.data.view.at_tick * 100); assert.equal(settledFrame.data.view.seed_revealed_at_settle, false); // Verify MemeTradeSkippedLink commitment: sha256_hex(serverSeed) === link.commit const skippedLink = { type: "skipped_link" as const, game: "meme-trade" as const, seq: 43, at: 1793238320000, data: { type: "skipped_link" as const, link: { chain: "mt-main-01", index: 1042, commit: "113459eb7bb31bddee85ade5230d6ad5d8b2fb52879e00a84ff6ae1067a210d3", salt: "00000000000000000001e3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4", salt_source: "bitcoin:870000", }, serverSeed: "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8", tick: 1842, }, }; const computedCommit = crypto.createHash("sha256").update(skippedLink.data.serverSeed, "utf8").digest("hex"); assert.equal(computedCommit, skippedLink.data.link.commit); ``` --- Source: /docs/dice-and-fairness.md --- # Provable fairness & verification Every BetPlug round commits to its randomness before any wager is placed (`api/openapi.yaml`). Operators, players, and auditors can replay any revealed round server-side via `GET /v1/rounds/{id}/verify` or offline using `@betrail/verifier`, the BetPlug Fairness Verifier web app, or standard SHA/HMAC primitives in any language. ## 1. Commit-reveal seed lifecycle Each `(player_ref, game)` holds a `SeedState` (`GET /v1/players/{player_ref}/seeds/{game}` or `GET /v1/session/seeds`): - **`current` (`SeedPairCommitted`):** `{ server_seed_hash, client_seed, nonces_used }`. `server_seed_hash` is lowercase hex `SHA-256(ascii(server_seed))` over the 64-character lowercase hex server seed (never hex-decoded 32 bytes). - **`next` (`SeedPairCommitted`):** Pre-committed next server seed hash plus the player's chosen next `client_seed` (`PUT /v1/players/{player_ref}/client-seeds/{game}`). - **`previous` (`SeedPairRevealed | null`):** After rotating (`POST /v1/players/{player_ref}/seeds/{game}/rotate` with an empty body), reveals `server_seed` alongside `server_seed_hash`, `client_seed`, and `nonces_used`. > **Security:** Never trim or Unicode-normalize `client_seed` (`3..64` raw UTF-8 bytes, no C0/DEL/C1 controls or unpaired surrogates). NFC `"ñ"` (`c3 b1`) and NFD `"n\u0303"` (`6e cc 83`) hash to completely different outcomes. When displaying untrusted `client_seed` or `player_ref` values to humans, escape bidirectional overrides (`U+202A..U+202E`, `U+2066..U+2069`) and zero-width characters (`U+200B..U+200F`, `U+FEFF`). ### Seed rotation & `GET /v1/rounds/{id}/verify` rules 1. **Rotation blocked while unfinished (`409 round_open`):** Rotating while any round on the current pair is `reserved`, `debiting`, `open`, or has an unresolved placement returns `409 round_open` so an active round's seed never leaks mid-play. 2. **Pre-reveal check (`409 seed_not_revealed`):** Calling `/verify` before rotating returns `409 seed_not_revealed`. 3. **Server replay verdict (`200`):** Once rotated, `/verify` replays every step from the stored `engine.Record` (`v: 1`) and returns HTTP `200` `{ result: "ok", record }` — or `{ result: "verify_mismatch", detail, record }` (a mismatch is always a `200` verdict, never masked as a `5xx`). Verify `record.tables` SHA-256 fingerprints against the published game paytable and confirm `steps[0].outcome.trace.from === 0` with contiguous `trace.from`/`trace.to` across steps. ### Pre-draw vs post-draw `void` rounds Nonces are reserved atomically **before** `engine.Open` and wallet debit, so failed attempts never reuse a nonce and may leave gaps: | Void class | Trigger | Stored `record` | `GET /v1/rounds/{id}/verify` after rotation | |---|---|---|---| | **Post-draw `void`** | `debit_refused` or `debit_unknown` (wallet declined or timed out after draw) | Contains `record.steps[0]` | **`200` `{ result: "ok", record }`** — proves voiding never cherry-picked outcomes | | **Pre-draw `void`** | `persist_error` or `engine_error` during `Open` (before any draw recorded) | Empty `{}` (`0` steps) | **`409 closed`** (`"This round voided before any draw recorded an outcome."`) — audit via `GET /v1/rounds/{id}` + rotated seed state | ## 2. RNG streams across the catalog > **Warning:** BetPlug preserves five exact legacy RNG recipes alongside `FairRandom` and live reverse hash chains. Never substitute one game's RNG or rounding rule for another. | `record.stream.kind` | Games | Digest construction (`server_seed` = 64 ASCII hex chars) | `trace` counter | |---|---|---|---| | `dice-sha512` | `dice` (`DICE`) | Plain `SHA-512(server_seed + ":" + client_seed + ":" + nonce)` (128 lowercase hex chars) | digests (`0..1`) | | `hmac-nonce` | `limbo`, `roulette`, `diamonds` | `HMAC-SHA256(key = ascii(server_seed), msg = client_seed + ":" + nonce)` (32 bytes, **no** `:cursor`) | digests (`0..1`) | | `plinko-hmac` | `plinko` (`PLINKO`) | `HMAC-SHA256(key = ascii(server_seed), msg = client_seed + ":" + nonce + ":" + c)` (`c = 0` for 8 pins; `c = 0, 1` for 9..16 pins) | digests (`1` or `2`) | | `fairrandom` | All other Instant, Stateful, Originals Slots & `stack-o-pass` | `HMAC-SHA256(key = ascii(server_seed), msg = client_seed + ":" + nonce + ":" + cursor)` (8 big-endian `uint32` words/block) | `u32` words | | Reverse `SHA-256` hash chain | Shared live shows (`trapdoor`, `kombat-multiplayer`, `crash`, `meme-trade`) | `link_{k} = SHA-256(ascii(link_{k+1}))` anchored at `s_0` + external public block `salt` | per-show `FairRandom` | ### Legacy recipe 1 — `DICE` (`dice-sha512`) 1. **Multiplier & paytable:** `chance` in `"0.01".."94.05"` (`W = chance * 100` in `1..9405`), `P = floor(950_000_000 / W)` in `10^-5` units (`W = 4798` -> `"1.97999"`). Paytable fingerprint: `7c145a94276eb256705c4c6d326824f70891fbc1120b33eea0433f432f702b4e`. 2. **Roll (`0..9999`):** Compute `H = hex(SHA-512("${server_seed}:${client_seed}:${nonce}"))`. Scan 25 windows `k = 0..24` of 5 hex chars (`H[5k .. 5k+5]`); the first value `< 1_000_000` is `lucky`. If all 25 are `>= 1_000_000`, take the 3-hex tail `parseInt(H.slice(125, 128), 16)` (`0..4095`). Then `roll = lucky % 10_000`. 3. **Settlement:** `"under"` wins iff `roll < W`; `"over"` wins iff `roll >= 10_000 - W`. Winning profit in atoms for stake `b` and max-profit cap `C`: `profit = min(floor(b * P / 100_000) - b, C)`, `payout = b + profit`. ### Legacy recipe 2 — `LIMBO` (`hmac-nonce`, 12-decimal `bcdiv` trap) - Compute `D = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}")` (no `:cursor`). - From the first 4 bytes `b0, b1, b2, b3`, compute the exact 12-decimal truncated byte sum: ```text S = floor(b0 * 10^12 / 256) + floor(b1 * 10^12 / 65536) + floor(b2 * 10^12 / 16777216) + floor(b3 * 10^12 / 4294967296) roll = floor(S / 10^6) // 0 .. 999,999 crash_hundredths = floor(97_000_000 / (roll + 1)) ``` - **Critical `bcmath-12` trap:** Never replace `floor(S / 10^6)` with `floor(u * 10^6 / 2^32)` — per-byte 12-decimal truncation differs at **4,224** values of `u`! Wins iff `crash_hundredths >= target_hundredths` (`101..100_000_000`, i.e. `1.01x`..`1000000.00x`). ### Legacy recipe 3 — `ROULETTE` (`hmac-nonce`) - Compute `D = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}")` and `S` from `D[0..3]`. Pocket `spin = floor(37 * S / 10^12)` (`0..36`, proven identical to `floor(37 * u / 2^32)`). - Two-floor settlement over total stake `B` and winning-chip return sum `W`: `q8 = floor(W * 10^8 / B)`, `gross = floor(B * q8 / 10^8)`, capped at `B + max_profit_atoms`. ### Legacy recipe 4 — `DIAMONDS` (`hmac-nonce`) - Compute `D = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}")`. Read the first 20 bytes as 5 groups `g = 0..4` (`u_g = uint32be(D[4g..4g+4])`): `gem_g = floor(7 * u_g / 2^32)` (`0..6`). - Sorted colour counts map to the 7 canonical hands: `[5]` -> `ALL_DIAMONDS` (`40x`), `[4,1]` -> `FOUR_DIAMONDS` (`5x`), `[3,2]` -> `THREE_DIAMONDS_TWO_DIAMONDS` (`4x`), `[3,1,1]` -> `THREE_DIAMONDS` (`3x`), `[2,2,1]` -> `TWO_DIAMONDS_TWO_DIAMONDS` (`2x`), `[2,1,1,1]` -> `TWO_DIAMONDS` (`0.1x`), `[1,1,1,1,1]` -> `NOTHING` (`0x`). ### Legacy recipe 5 — `PLINKO` (`plinko-hmac`) - Compute `D_c = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}:${c}")` for `c = 0 .. Math.floor((pins + 7) / 8) - 1` (`1` digest for `8` pins, `2` digests `D_0 || D_1` for `9..16` pins). - Concatenate bytes `B`. Pin `i` (`0..pins-1`) steps right (`1`) iff `B[4 * i] >= 128`. `bucket = sum(step_i)` (`0..pins`) indexes the `(pins, risk)` paytable. ### `FairRandom` cursor stream - **`FairRandom` (`HMAC-SHA256(server_seed, client_seed:nonce:cursor)`):** Default byte stream across all other Instant games (`PACKS`, `RANGEDICE`, `WHEEL`, `DRILL`, `SLIDE`, `CASES`, `BARS`, `KENO`, `DARTS`, `TAROT`, `BACCARAT`, `KABOOM`, `TILT`), every Stateful Session game (`CHICKEN`, `PUMP`, `MINES`, `TOWERS`, `BLACKJACK`, `HILO`, `SNAKES`, `FLIP`, `RPS`, `MOLES`, `VIDEOPOKER`, `SKYRUSH`, `DEADSHOT`, `KOMBAT`, `STACKPACKS`), every Originals Slot (`GRIMOIRE`, `PHARAOH`, `SHOGUN` — one nonce per paid spin including bonus rounds), and `STACKOPASS` table hands. - Primitives: `Int(n) = (u * n) >> 32` (for games like `mines`, `towers`, `blackjack`, `snakes`); exact rejection `Uniform(n, maxDraws)` (rejecting `u >= n * floor(2^32 / n)` into `trace.rejected` for `baccarat`, `video-poker`, `moles`, `darts`, `hilo`, `stack-packs`, `trapdoor`, and all Originals Slots); `SuffixedBlock(cursor, k)` (`hilo` rehash when all 8 words reject); splice Fisher-Yates `PickUnique(n, k)` / `Shuffle(n)`; and `AlignToCursor()` advancing to the next 8-word boundary. ### Live hash chains vs `stack-o-pass` per-player seeds - **Shared live shows (`trapdoor`, `kombat-multiplayer`, `crash`, `meme-trade`):** Pre-commit a reverse `SHA-256` chain (`SHA-256(ascii(seed)) === commit`, walking back to terminal anchor `s_0`) salted by an external public block beacon (`salt_source`, e.g. `"bitcoin:"`) announced before betting opens. Any unplayed link is broadcast via `skipped_link`. Seed derivation: `trapdoor` uses `Client = "trapdoor:" + salt, Nonce = gate`; `kombat-multiplayer` uses `Client = salt, Nonce = index`; `crash` uses `Client = "crash:" + salt, Nonce = index`; `meme-trade` uses `Client = "meme-trade:" + salt, Nonce = index`. - **Per-operator live tables (`stack-o-pass`):** Uses **each player's own `FairRandom` seed pair** (not a shared show hash chain), verified after the player rotates their seed pair. > **Tip:** All catalog games are mounted and served across `sandbox` and `live` (`404 unknown_game` applies only to unrecognized slugs; `409 not_offered` applies to disabled brand games, missing live hourly FX rates, live demo launches, or the `MINES (12, 11)` preset). ## 3. Standalone multi-recipe verifier (runnable sample) Verify `SHA-256` server-seed commitments, `DICE` (`dice-sha512` including paytable fingerprint & 26th-read tail), `LIMBO` (`hmac-nonce` exact `bcmath-12` byte sum), and `PLINKO` (`plinko-hmac`) in pure `BigInt`: ```ts import assert from "node:assert/strict"; import crypto from "node:crypto"; const TEN12 = 1_000_000_000_000n; const B_POW = [256n, 65_536n, 16_777_216n, 4_294_967_296n] as const; function diceMultiplierScaled(w: bigint): bigint { return 950_000_000n / w; // exact floor in 10^-5 units } function diceRollFromDigest(digestHex: string): { lucky: number; roll: number; windowsRead: number } { for (let k = 0; k < 25; k++) { const v = Number.parseInt(digestHex.slice(5 * k, 5 * k + 5), 16); if (v < 1_000_000) return { lucky: v, roll: v % 10_000, windowsRead: k + 1 }; } const tail = Number.parseInt(digestHex.slice(125, 128), 16); return { lucky: tail, roll: tail % 10_000, windowsRead: 26 }; } function limboCrashHundredths(serverSeed: string, clientSeed: string, nonce: number): bigint { const d = crypto.createHmac("sha256", Buffer.from(serverSeed, "ascii")).update(`${clientSeed}:${nonce}`, "utf8").digest(); let s = 0n; for (let k = 0; k < 4; k++) s += (BigInt(d[k]!) * TEN12) / B_POW[k]!; const roll = s / 1_000_000n; return 97_000_000n / (roll + 1n); } function plinkoBucket(pins: number, serverSeed: string, clientSeed: string, nonce: number): number { const count = Math.floor((pins + 7) / 8); const bytes = Buffer.concat( Array.from({ length: count }, (_, c) => crypto.createHmac("sha256", Buffer.from(serverSeed, "ascii")).update(`${clientSeed}:${nonce}:${c}`, "utf8").digest(), ), ); let bucket = 0; for (let i = 0; i < pins; i++) if (bytes[4 * i]! >= 128) bucket += 1; return bucket; } // 1. DICE paytable fingerprint across all 9,405 targets const fpLines = Array.from({ length: 9405 }, (_, i) => `${i + 1}|${diceMultiplierScaled(BigInt(i + 1))}`); const fingerprint = crypto.createHash("sha256").update(`betrail-dice-paytable/1\n${fpLines.join("\n")}`, "utf8").digest("hex"); assert.equal(fingerprint, "7c145a94276eb256705c4c6d326824f70891fbc1120b33eea0433f432f702b4e"); // 2. DICE commitment + reference vector (roll = 3317, payout = 0.00019799 BTC) + 26th-read tail const seed = crypto.createHash("sha256").update("betrail/l2/dice/boundary", "utf8").digest("hex"); const seedHash = crypto.createHash("sha256").update(seed, "ascii").digest("hex"); assert.equal(crypto.createHash("sha256").update(seed, "ascii").digest("hex"), seedHash); const diceDigest = crypto.createHash("sha512").update(`${seed}:betrail-dice:1`, "utf8").digest("hex"); assert.equal(diceRollFromDigest(diceDigest).roll, 3317); assert.equal((10_000n * diceMultiplierScaled(4798n)) / 100_000n, 19_799n); assert.deepEqual(diceRollFromDigest(`${"f".repeat(125)}abc`), { lucky: 0xabc, roll: 2748, windowsRead: 26 }); // 3. LIMBO bcmath-12 & PLINKO plinko-hmac determinism checks assert.ok(limboCrashHundredths(seed, "betrail-limbo", 0) >= 97n); const b16 = plinkoBucket(16, seed, "betrail-plinko", 0); assert.ok(b16 >= 0 && b16 <= 16); ``` --- Source: /docs/sdk.md --- # Official SDKs (TypeScript, Go, Python & PHP) > **Pre-release checkout packages.** All four official BetPlug SDKs carry private markers (`"private": true` in `./sdk/ts/package.json` and `./sdk/php/composer.json`, `Private :: Do Not Upload` in `./sdk/python/pyproject.toml`, and an untagged monorepo submodule in `./sdk/go/go.mod`) and have **zero external runtime dependencies**. Consume them directly from your verified local repository checkout rather than public package registries. BetPlug ships four zero-dependency official SDKs implementing the OpenAPI 3.1 contract ([`/api/openapi.yaml`](/api/openapi.yaml)), the AsyncAPI 3.1 live and webhook contract ([`/api/asyncapi.yaml`](/api/asyncapi.yaml)), `betrail-v1` and `betrail-v1-answer` signing (including RFC 8032 `ed25519=` wallet answers), idempotent retry transport, seamless wallet handlers (`WalletHandler`), raw-body webhook verifiers (`Webhooks`), and exact integer-atom money helpers. ## Install & import from your verified checkout | Language | Checkout path | Runtime floor | Import / setup | | --- | --- | --- | --- | | **TypeScript / Node** (`@betrail/sdk`) | `./sdk/ts` | Node `>= 24` (built-in type stripping) | `import * as sdk from "./sdk/ts/src/index.ts";` | | **Go** (`betrail.example/sdk/go`) | `./sdk/go` | Go `>= 1.27` (0 `require` lines) | Add `use ./sdk/go` in `go.work`, or a local `replace` directive in `go.mod` | | **Python** (`betrail`) | `./sdk/python` | Python `>= 3.11` (stdlib only) | Set `PYTHONPATH=/path/to/checkout/sdk/python/src` and `import betrail` | | **PHP** (`Betrail\Sdk\*`) | `./sdk/php` | PHP `>= 8.2` (`ext-hash`, `ext-json`, `ext-sodium`) | `require_once '/path/to/checkout/sdk/php/autoload.php';` | ## Quickstart: first call, launch, wallet & webhook Switch tabs to see the idiomatic production workflow (`createRound`, `createLaunch`, `WalletHandler`, and `verifyWebhook`) in each language: ```ts no-eval tab import { BetrailClient, createWalletHandler, isRoundSettledEvent, parseEd25519SeedBase64Url, verifyWebhook, } from "./sdk/ts/src/index.ts"; const client = new BetrailClient({ baseUrl: process.env.BETRAIL_API_BASE_URL!, apiKey: process.env.BETRAIL_API_KEY!, // btr_test_ signingSecret: process.env.BETRAIL_SIGNING_SECRET!, retry: { maxAttempts: 3, baseDelayMs: 100, maxDelayMs: 2_000 }, }); // 1. Headless instant round (exact decimal strings, auto Idempotency-Key & betrail-v1) const round = await client.createRound({ game: "dice", brand: process.env.BETRAIL_BRAND_ID!, player_ref: "p_demo_01", currency: "BTC", stake: "0.00100000", params: { direction: "under", chance: "47.98", payout: "1.97999" }, }); // 2. Mint a 60 s single-use embed launch token const launch = await client.createLaunch({ game: "dice", brand: process.env.BETRAIL_BRAND_ID!, player_ref: "p_demo_01", currency: "BTC", mode: "real", locale: "en", }); // 3. Seamless wallet callback handler (Ed25519 answer signing) export const wallet = createWalletHandler({ requestSecrets: [process.env.BETRAIL_WALLET_SECRET!], answerEd25519Seeds: [parseEd25519SeedBase64Url(process.env.BETRAIL_WALLET_ED25519_SEED!)], book: myWalletBook, nonceStore: myValkeyNonceStore, }); // 4. Raw-byte webhook verification export async function onWebhook(rawTarget: string, headers: Headers, body: Uint8Array) { const verified = await verifyWebhook({ method: "POST", target: rawTarget, headers, body, secrets: [process.env.BETRAIL_WEBHOOK_SECRET!], nonceStore: myValkeyNonceStore }); if (isRoundSettledEvent(verified.event)) await saveRound(verified.event.data); } ``` ```go no-eval tab client, err := betrail.NewClient(betrail.ClientConfig{ BaseURL: os.Getenv("BETRAIL_API_BASE_URL"), APIKey: betrail.NewSecret(os.Getenv("BETRAIL_API_KEY")), SigningSecrets: []betrail.Secret{betrail.NewSecret(os.Getenv("BETRAIL_SIGNING_SECRET"))}, }) // 1. Headless round & 2. Launch token round, err := client.CreateRound(ctx, betrail.RoundCreate{ Game: "dice", Brand: os.Getenv("BETRAIL_BRAND_ID"), PlayerRef: "p_demo_01", Currency: "BTC", Stake: "0.00100000", Params: betrail.DiceParams{Direction: "under", Chance: "47.98", Payout: "1.97999"}, }) launch, err := client.CreateLaunch(ctx, betrail.LaunchCreate{ Game: "dice", Brand: os.Getenv("BETRAIL_BRAND_ID"), PlayerRef: "p_demo_01", Currency: "BTC", Mode: betrail.LaunchModeReal, Locale: "en", }) // 3. Seamless wallet handler & 4. Webhook verifier seed, err := betrail.ParseEd25519SeedBase64URL(os.Getenv("BETRAIL_WALLET_ED25519_SEED")) walletHandler, err := betrail.NewWalletHandler(betrail.WalletHandlerOptions{ RequestSecrets: []betrail.Secret{betrail.NewSecret(os.Getenv("BETRAIL_WALLET_SECRET"))}, AnswerEd25519Seeds: []betrail.Secret{seed}, Book: myWalletBook, NonceStore: myValkeyNonceStore, }) // Inside webhook handler: ev, err := betrail.VerifyHTTPWebhook(r.Context(), r, webhookSecrets, myValkeyNonceStore, time.Time{}) ``` ```python no-eval tab import os from betrail import Client, Ed25519, Secret, WalletHandler, verify_webhook client = Client( base_url=os.environ["BETRAIL_API_BASE_URL"], api_key=Secret(os.environ["BETRAIL_API_KEY"]), signing_secrets=[Secret(os.environ["BETRAIL_SIGNING_SECRET"])], ) # 1. Headless round & 2. Launch token round_res = client.create_round({ "game": "dice", "brand": os.environ["BETRAIL_BRAND_ID"], "player_ref": "p_demo_01", "currency": "BTC", "stake": "0.00100000", "params": {"direction": "under", "chance": "47.98", "payout": "1.97999"}, }) launch = client.create_launch({ "game": "dice", "brand": os.environ["BETRAIL_BRAND_ID"], "player_ref": "p_demo_01", "currency": "BTC", "mode": "real", "locale": "en", }) # 3. Seamless wallet handler & 4. Webhook verifier raw_seed = Ed25519.base64url_decode_32(os.environ["BETRAIL_WALLET_ED25519_SEED"]) if raw_seed is None: raise ValueError("BETRAIL_WALLET_ED25519_SEED must be 43-char canonical base64url") wallet = WalletHandler( request_secrets=[Secret(os.environ["BETRAIL_WALLET_SECRET"])], book=my_wallet_book, nonce_store=my_valkey_nonce_store, answer_ed25519_seeds=[Secret(raw_seed)], ) # Inside webhook route: ev = verify_webhook("POST", raw_target, raw_body, headers, webhook_secrets, my_valkey_nonce_store) ``` ```php no-eval tab use Betrail\Sdk\{Client, Ed25519, Secret, Webhooks}; use Betrail\Sdk\Wallet\WalletHandler; $client = new Client( baseUrl: getenv('BETRAIL_API_BASE_URL'), apiKey: new Secret(getenv('BETRAIL_API_KEY')), signingSecrets: [new Secret(getenv('BETRAIL_SIGNING_SECRET'))], ); // 1. Headless round & 2. Launch token $round = $client->createRound([ 'game' => 'dice', 'brand' => getenv('BETRAIL_BRAND_ID'), 'player_ref' => 'p_demo_01', 'currency' => 'BTC', 'stake' => '0.00100000', 'params' => ['direction' => 'under', 'chance' => '47.98', 'payout' => '1.97999'], ]); $launch = $client->createLaunch([ 'game' => 'dice', 'brand' => getenv('BETRAIL_BRAND_ID'), 'player_ref' => 'p_demo_01', 'currency' => 'BTC', 'mode' => 'real', 'locale' => 'en', ]); // 3. Seamless wallet handler & 4. Webhook verifier $wallet = new WalletHandler( requestSecrets: [new Secret(getenv('BETRAIL_WALLET_SECRET'))], book: $myWalletBook, nonceStore: $myValkeyNonceStore, answerEd25519Seeds: [Ed25519::parseSeedBase64Url(getenv('BETRAIL_WALLET_ED25519_SEED'))], ); // Inside webhook route: $ev = Webhooks::verifyGlobals([$webhookSecret], $myValkeyNonceStore); ``` ## Cross-SDK capability matrix | Capability | TypeScript (`./sdk/ts`) | Go (`./sdk/go`) | Python (`./sdk/python`) | PHP (`./sdk/php`) | | --- | --- | --- | --- | --- | | **Headless operator client** | `BetrailClient` | `NewClient` (`*Client`) | `Client` | `Betrail\Sdk\Client` | | **Session client (`bts_` only)** | `BetrailSessionClient`, `createSession`, `createDemoSession` | `NewSessionClient` (`CreateLiveTicket`, `CreateLiveBet`, `CreateMemeTradeBuyIn`) | `SessionClient` (`create_live_ticket`, `create_live_bet`, `create_meme_trade_buy_in`) | `Betrail\Sdk\SessionClient` (`createLiveTicket`, `createLiveBet`, `createMemeTradeBuyIn`) | | **Exact integer atoms (zero floats)** | `parseAmountAtoms` / `formatAmountAtoms` (`bigint`), `parseUsdMicros` / `formatUsdMicros` | `ParseAmountAtoms` / `FormatAmountAtoms` (`int64`), `ParseAmountAtomsBig`, `ParseUsdMicros` | `Money.parse` / `parse_amount_atoms` (`int`), `format_amount_atoms`, `floor_mul_div`, `parse_usd_micros` | `Money::parseAmountAtoms` (digit `string`, zero `ext-bcmath`), `Money::parseAmountAtomsInt` (`int`), `Money::formatAmountAtoms` | | **`betrail-v1` signing** | `signRequest`, `verifyRequest` | `SignRequest`, `VerifyRequest`, `VerifyHTTPRequest` | `sign_request`, `verify_request` | `Signature::signRequest`, `Signature::verifyRequest` | | **Wallet answers & Ed25519** | `generateEd25519WalletKeyPair`, `signAnswer`, `verifyAnswer` | `GenerateEd25519WalletKeyPair`, `SignAnswer`, `VerifyAnswer` | `Ed25519.generate_keypair`, `sign_answer`, `verify_answer` | `Ed25519::generateWalletKeyPair`, `Signature::signAnswer`, `Signature::verifyAnswer` | | **Replay store (`NonceStore`)** | `NonceStore`, `InMemoryNonceStore` (inject Valkey in prod) | `NonceStore`, `NewFileBackedNonceStore`, `NewInMemoryNonceStore` | `NonceStore`, `FileBackedNonceStore`, `InMemoryNonceStore` | `NonceStoreInterface`, `FileBackedNonceStore`, `InMemoryNonceStore` | | **Wallet handler & live tx IDs** | `createWalletHandler`, `InMemoryWalletBook`, `debitTransactionId`, `showBetDebitTransactionId`, `buyInDebitTransactionId`, `playerRoundId`, `creditTransactionId`, `rollbackTransactionId` | `NewWalletHandler`, `NewInMemoryWalletBook`, `DebitTransactionID`, `ShowBetDebitTransactionID`, `BuyInDebitTransactionID`, `PlayerRoundID`, `CreditTransactionID`, `RollbackTransactionID` | `WalletHandler`, `FileBackedWalletBook`, `InMemoryWalletBook`, `debit_transaction_id`, `show_bet_debit_transaction_id`, `buy_in_debit_transaction_id`, `player_round_id`, `credit_transaction_id`, `rollback_transaction_id` | `WalletHandler`, `FileBackedWalletBook`, `InMemoryWalletBook`, `WalletHandler::debitTransactionId`, `WalletHandler::showBetDebitTransactionId`, `WalletHandler::buyInDebitTransactionId`, `WalletHandler::playerRoundId` | | **Webhook verification & guards** | `verifyWebhook`, `isRoundSettledEvent`, `isCreditsLowEvent`, `isCreditsExhaustedEvent` | `VerifyWebhook`, `VerifyHTTPWebhook` (`AsRoundSettled`, `AsCreditsLow`, `AsCreditsExhausted`) | `verify_webhook`, `WebhookRouter` (`is_round_settled`, `is_credits_low`, `is_credits_exhausted`) | `Webhooks::verify`, `Webhooks::verifyGlobals` (`asRoundSettled`, `isCreditsLow`, `isCreditsExhausted`) | | **Secret redaction** | `Secret`, `redactString`, `redactHeaders` | `Secret`, `RedactString`, `NewRedactingSlogHandler` | `Secret`, `redact_string`, `redact_headers` | `Secret` (`#[\SensitiveParameter]`), `Redact::string` | ## Shared security & precision guarantees 1. **Exact decimal strings & integer atoms:** Every SDK validates wire `Amount` strings against `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$` at currency scale (default `8`) and converts directly to integer atoms. Floats, scientific notation (`1e-4`), signs, and over-scale decimals fail closed. 2. **Asymmetric Ed25519 wallet answer pinning:** Once a 43-char canonical base64url Ed25519 public key is configured on the brand environment, `VerifyAnswer` and BetPlug reject `v1=` HMAC downgrade (`ed25519=` mandatory, with canonical Edwards25519 curve decompression, 8-torsion point rejection, and `S < L` scalar bounds). 3. **Idempotent retry discipline:** Every `POST` preserves its CSPRNG `Idempotency-Key` across retryable failures (`409 idempotency_key_in_use`, `429 rate_limited`, `502`/`504`, `503 wallet_unavailable` only with `Retry-After`, transport resets) while signing a fresh `Betrail-Timestamp` and `Betrail-Nonce` per attempt. 4. **Strict JSON & durable `NonceStore`:** Authenticated wallet requests with malformed JSON, duplicate keys, or Unicode case-folded duplicates return signed `400 {"code":"invalid_request",...}`. Single-host deployments can use `FileBackedNonceStore` (Go, Python, PHP); multi-replica deployments inject Valkey or PostgreSQL (`SET NX EX 630`). --- ## Runnable SDK verification samples The four compact samples below run directly against `./sdk/ts`, `./sdk/go`, `./sdk/python`, and `./sdk/php` to confirm exact atom arithmetic, Ed25519 wallet answer signing with no-downgrade enforcement, idempotent `retry` transport, webhook event narrowing, and credential redaction. ### 1. TypeScript (`./sdk/ts`) ```ts import assert from "node:assert/strict"; import path from "node:path"; import { pathToFileURL } from "node:url"; const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd(); const sdk = await import(pathToFileURL(path.join(repoRoot, "sdk", "ts", "src", "index.ts")).href); // 1. Exact integer-atom math & live tx-ID helpers (zero floats) const stakeAtoms: bigint = sdk.parseAmountAtoms("0.00100000", 8); const payoutAtoms: bigint = sdk.parseAmountAtoms("0.00197999", 8); assert.equal(sdk.formatAmountAtoms(payoutAtoms - stakeAtoms, 8), "0.00097999"); assert.throws(() => sdk.parseAmountAtoms("1e-4", 8), sdk.BetrailValidationError); assert.equal(sdk.showBetDebitTransactionId("bet_show_01", 1), "bet_show_01:0:1:debit"); assert.equal(sdk.buyInDebitTransactionId(sdk.playerRoundId("mt_rnd_9", "p_1"), 0, 1), "mt_rnd_9:p_1:b0:1:debit"); // 2. Ed25519 wallet handler + no-downgrade verification const kp = sdk.generateEd25519WalletKeyPair(); const walletSecret = "sandbox-wallet-hmac-secret-32byt!"; const handler = sdk.createWalletHandler({ requestSecrets: [walletSecret], answerEd25519Seeds: [kp.seed], book: new sdk.InMemoryWalletBook({ defaultInitialBalance: "1.00000000" }), nonceStore: new sdk.InMemoryNonceStore(), }); const txId = sdk.debitTransactionId("rnd_01", 0, 1); const debitBody = JSON.stringify({ transaction_id: txId, round_id: "rnd_01", player_ref: "p_1", currency: "BTC", amount: "0.00100000", game: "dice", brand: "br_sandbox" }); const reqH = sdk.signRequest({ method: "POST", target: "/wallet/v1/debit", body: debitBody, secrets: [walletSecret] }); const res = await handler({ method: "POST", target: "/wallet/v1/debit", headers: { "betrail-timestamp": reqH.timestamp, "betrail-nonce": reqH.nonce, "betrail-signature": reqH.signature }, body: debitBody, }); assert.equal(res.status, 200); assert.equal( sdk.verifyAnswer({ status: 200, headers: res.headers, requestNonce: reqH.nonce, transactionId: txId, body: res.body, ed25519PublicKeys: [kp.publicKey] }).scheme, "ed25519", ); // 3. BetrailClient (`retry` option) reuses Idempotency-Key & rotates Betrail-Nonce across 502 retry const attempts: Array<{ idem: string; nonce: string }> = []; const client = new sdk.BetrailClient({ baseUrl: "https://api.betrail.example", apiKey: ["btr", "test", "sdkdoc0000000000000000000000000000000000000"].join("_"), signingSecret: "sandbox-sdk-signing-secret-32bytes!", retry: { maxAttempts: 2, baseDelayMs: 1, maxDelayMs: 5 }, fetch: async (_in: string | URL | Request, init?: RequestInit) => { const h = new Headers(init?.headers); attempts.push({ idem: h.get("idempotency-key") ?? "", nonce: h.get("betrail-nonce") ?? "" }); if (attempts.length === 1) return new Response("bad gateway", { status: 502 }); return new Response( JSON.stringify({ id: "rnd_sdk_01", game: "dice", version: 1, brand: "br_sandbox", player_ref: "p_1", currency: "BTC", status: "settled", step: 1, stake: "0.00100000", payout: "0.00197999", refund: "0.00000000", max_profit: "1.00000000", cap_rule: "truncate", cap_source: "brand", view: { roll: 3317, win: true }, seed: { server_seed_hash: "a".repeat(64), client_seed: "seed-1", nonce: 0 }, created_at: "2026-10-29T01:45:00Z", settled_at: "2026-10-29T01:45:00Z", }), { status: 201, headers: { "content-type": "application/json" } }, ); }, }); const round = await client.createRound({ game: "dice", brand: "br_sandbox", player_ref: "p_1", currency: "BTC", stake: "0.00100000", params: { direction: "under", chance: "47.98", payout: "1.97999" } }); assert.equal(round.id, "rnd_sdk_01"); assert.equal(attempts[0]!.idem, attempts[1]!.idem); assert.notEqual(attempts[0]!.nonce, attempts[1]!.nonce); // 4. Webhook guards & secret redaction const exEvt = { id: "evt_ex_01", type: "credits.exhausted", created_at: "2026-10-29T02:05:00Z", environment: "live" as const, data: { balance: "0.000000", threshold: "0.000000" } }; assert.equal(sdk.isCreditsExhaustedEvent(exEvt), true); assert.equal(sdk.isCreditsLowEvent(exEvt), false); assert.equal(sdk.isRoundSettledEvent(exEvt), false); assert.equal(sdk.redactString(`Bearer ${["btr", "test", "secret0000000000000000000000000000000000"].join("_")}`).includes("secret0000"), false); ``` ### 2. Go (`./sdk/go`) ```go package main import ( "bytes" "context" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "time" betrail "betrail.example/sdk/go" ) func must[T any](v T, err error) T { if err != nil { panic(err) } return v } func main() { ctx := context.Background() atoms := must(betrail.ParseAmountAtoms("0.00100000", 8)) if must(betrail.FormatAmountAtoms(atoms, 8)) != "0.00100000" || betrail.ShowBetDebitTransactionID("bet_01", 1) != "bet_01:0:1:debit" { panic("unexpected Go money/tx-id result") } tmpDir := must(os.MkdirTemp("", "betrail-sdk-go-doc-*")) defer os.RemoveAll(tmpDir) kp := must(betrail.GenerateEd25519WalletKeyPair()) walletSecret := betrail.NewSecret("sandbox-go-wallet-secret-32bytes!") handler := must(betrail.NewWalletHandler(betrail.WalletHandlerOptions{ RequestSecrets: []betrail.Secret{walletSecret}, AnswerEd25519Seeds: []betrail.Secret{kp.Seed}, Book: must(betrail.NewInMemoryWalletBook(betrail.InMemoryWalletBookOptions{DefaultInitialBalance: "1.00000000"})), NonceStore: must(betrail.NewFileBackedNonceStore(filepath.Join(tmpDir, "wallet-nonces.json"))), })) txID := betrail.DebitTransactionID("rnd_go_01", 0, 1) rawDebit := []byte(`{"transaction_id":"` + txID + `","round_id":"rnd_go_01","player_ref":"p_1","currency":"BTC","amount":"0.00100000","game":"dice","brand":"br_sandbox"}`) req := httptest.NewRequest(http.MethodPost, "https://casino.example/wallet/v1/debit", bytes.NewReader(rawDebit)) req.RequestURI = "/wallet/v1/debit" signed := must(betrail.SignRequest(betrail.SignRequestInput{Method: http.MethodPost, Target: "/wallet/v1/debit", Body: rawDebit, Secrets: []betrail.Secret{walletSecret}, Headers: req.Header})) rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) respBody, _ := io.ReadAll(rec.Result().Body) ans := must(betrail.VerifyAnswer(betrail.VerifyAnswerInput{Headers: rec.Result().Header, Status: rec.Code, RequestNonce: signed.Nonce, TransactionID: txID, Body: respBody, Ed25519PublicKeys: []string{kp.PublicKey}})) if rec.Code != http.StatusOK || ans.Scheme != betrail.AnswerSchemeEd25519 { panic("expected verified ed25519 wallet answer") } // Verify signed round.settled webhook over unmodified *http.Request + secret redaction whSecret := betrail.NewSecret("sandbox-go-webhook-secret-32byte!") whBody := []byte(`{"id":"evt_go_01","type":"round.settled","environment":"sandbox","created_at":"2026-10-29T02:00:00Z","data":{"id":"rnd_go_01","game":"dice","version":1,"brand":"br_sandbox","player_ref":"p_1","currency":"BTC","status":"settled","step":1,"stake":"0.00100000","payout":"0.00197999","refund":"0.00000000","max_profit":"1.00000000","cap_rule":"truncate","cap_source":"brand","view":{"roll":3317,"win":true},"seed":{"server_seed_hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","client_seed":"seed-1","nonce":0},"created_at":"2026-10-29T02:00:00Z","settled_at":"2026-10-29T02:00:00Z"}}`) whReq := httptest.NewRequest(http.MethodPost, "https://casino.example/webhooks/betrail", bytes.NewReader(whBody)) whReq.RequestURI = "/webhooks/betrail" whReq.Header.Set(betrail.HeaderWebhookID, "evt_go_01") _ = must(betrail.SignRequest(betrail.SignRequestInput{Method: http.MethodPost, Target: "/webhooks/betrail", Body: whBody, Secrets: []betrail.Secret{whSecret}, Headers: whReq.Header})) wh := must(betrail.VerifyHTTPWebhook(ctx, whReq, []betrail.Secret{whSecret}, must(betrail.NewFileBackedNonceStore(filepath.Join(tmpDir, "wh-nonces.json"))), time.Time{})) if settled, ok, err := wh.AsRoundSettled(); err != nil || !ok || settled.Payout != "0.00197999" { panic("expected verified round.settled payout") } if strings.Contains(betrail.RedactString("Bearer btr_"+"test_gosdk0000000000000000000000000000000000"), "gosdk0000") { panic("expected token redaction") } } ``` ### 3. Python (`./sdk/python`) ```python import json, os, tempfile from betrail import ( Ed25519, FileBackedNonceStore, InMemoryWalletBook, Money, Secret, WalletHandler, debit_transaction_id, format_amount_atoms, parse_amount_atoms, redact_string, show_bet_debit_transaction_id, sign_request, verify_answer, verify_webhook, ) stake_atoms = parse_amount_atoms("0.00100000", 8) payout = Money.parse("0.00197999", scale=8) assert format_amount_atoms(payout.atoms - stake_atoms, 8) == "0.00097999" assert show_bet_debit_transaction_id("bet_py_1", 1) == "bet_py_1:0:1:debit" with tempfile.TemporaryDirectory() as tmp: kp = Ed25519.generate_keypair() wallet_secret = Secret("sandbox-py-wallet-secret-32bytes!") handler = WalletHandler( request_secrets=[wallet_secret], book=InMemoryWalletBook(default_initial_balance="1.00000000"), nonce_store=FileBackedNonceStore(os.path.join(tmp, "wallet-nonces.json")), answer_ed25519_seeds=[kp.seed], ) tx_id = debit_transaction_id("rnd_py_01", 0, 1) raw_debit = json.dumps({"transaction_id": tx_id, "round_id": "rnd_py_01", "player_ref": "p_1", "currency": "BTC", "amount": "0.00100000", "game": "dice", "brand": "br_sandbox"}) req_headers: dict[str, str] = {} signed = sign_request("POST", "/wallet/v1/debit", raw_debit, [wallet_secret], headers_out=req_headers) res = handler.handle_request("POST", "/wallet/v1/debit", req_headers, raw_debit) assert res["status"] == 200 assert verify_answer(200, signed.nonce, tx_id, res["body"], res["headers"], ed25519_public_keys=[kp.public_key]).scheme == "ed25519" wh_secret = Secret("sandbox-py-webhook-secret-32byte!") wh_body = json.dumps({"id": "evt_py_01", "type": "credits.low", "environment": "live", "created_at": "2026-10-29T02:10:00Z", "data": {"balance": "25.000000", "threshold": "50.000000"}}) wh_headers = {"Betrail-Webhook-Id": "evt_py_01"} sign_request("POST", "/webhooks/betrail", wh_body, [wh_secret], headers_out=wh_headers) ev = verify_webhook("POST", "/webhooks/betrail", wh_body, wh_headers, [wh_secret], FileBackedNonceStore(os.path.join(tmp, "wh-nonces.json"))) assert ev.is_credits_low() and ev.parse_credits_low().balance == "25.000000" assert "pysdk0000" not in redact_string("Bearer btr_" + "test_pysdk0000000000000000000000000000000000") ``` ### 4. PHP (`./sdk/php`) ```php seed], ); $txId = WalletHandler::debitTransactionId('rnd_php_01', 0, 1); $rawDebit = json_encode(['transaction_id' => $txId, 'round_id' => 'rnd_php_01', 'player_ref' => 'p_1', 'currency' => 'BTC', 'amount' => '0.00100000', 'game' => 'dice', 'brand' => 'br_sandbox'], JSON_THROW_ON_ERROR); $reqHeaders = []; $signed = Signature::signRequest('POST', '/wallet/v1/debit', $rawDebit, [$walletSecret], null, null, $reqHeaders); $res = $handler->handleRequest('POST', '/wallet/v1/debit', $reqHeaders, $rawDebit); $ans = Signature::verifyAnswer($res['status'], $signed['nonce'], $txId, $res['body'], $res['headers'], [$kp->publicKey]); if ($res['status'] !== 200 || $ans['scheme'] !== 'ed25519') { throw new RuntimeException('expected verified ed25519 wallet answer'); } $whSecret = new Secret('sandbox-php-webhook-secret-32byt!'); $whBody = <<<'JSON' {"id":"evt_php_01","type":"round.settled","environment":"sandbox","created_at":"2026-10-29T02:15:00Z","data":{"id":"rnd_php_01","game":"dice","version":1,"brand":"br_sandbox","player_ref":"p_1","currency":"BTC","status":"settled","step":1,"stake":"0.00100000","payout":"0.00197999","refund":"0.00000000","max_profit":"1.00000000","cap_rule":"truncate","cap_source":"brand","view":{"roll":3317,"win":true},"seed":{"server_seed_hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","client_seed":"seed-1","nonce":0},"created_at":"2026-10-29T02:15:00Z","settled_at":"2026-10-29T02:15:00Z"}} JSON; $whHeaders = ['Betrail-Webhook-Id' => 'evt_php_01']; Signature::signRequest('POST', '/webhooks/betrail', $whBody, [$whSecret], null, null, $whHeaders); $ev = Webhooks::verify('POST', '/webhooks/betrail', $whBody, $whHeaders, [$whSecret], new FileBackedNonceStore($tmpDir . '/wh-nonces.json')); $settled = $ev->asRoundSettled(); if ($settled === null || $settled['payout'] !== '0.00197999' || str_contains(Redact::string('Bearer btr_' . 'test_phpsdk0000000000000000000000000000000000'), 'phpsdk0000')) { throw new RuntimeException('unexpected PHP webhook/redaction result'); } } finally { foreach (glob($tmpDir . '/*') ?: [] as $f) @unlink($f); @rmdir($tmpDir); } ``` --- Source: /docs/mcp.md --- # Remote MCP server (`@betrail/mcp`) > **Pre-release checkout package & example hostnames.** `@betrail/mcp` lives in `./mcp` (`"private": true`, zero external npm dependencies). Its canonical Streamable HTTP endpoint is `https://mcp.betrail.example/mcp` (override locally with `BETRAIL_MCP_URL=http://127.0.0.1:8085/mcp`). `@betrail/mcp` implements the Model Context Protocol Streamable HTTP transport so coding agents can inspect BetPlug game specifications, OpenAPI/AsyncAPI operations, and your own sandbox tenant — plus run confirmation-gated sandbox simulations and wallet/webhook probes — without ever holding a server-wide key or touching live state. ## Security architecture 1. **OAuth 2.1 + PKCE with audience-bound sandbox scopes (RFC 9728).** Unauthenticated requests answer `401` with `WWW-Authenticate` pointing to `/.well-known/oauth-protected-resource`. Every JWT verifies `alg === "HS256"` (rejecting `crit` headers), single-audience `aud === resourceUrl`, `iss`, `exp`, `nbf`, active consent, and `operator_id`. Only sandbox scopes exist: `mcp:read`, `mcp:sandbox:write`, and `mcp:sandbox:keys`. 2. **Sandbox-only enforcement; zero live scopes or keys ever.** `@betrail/mcp` refuses startup if any server-wide credential env var (`BETRAIL_API_KEY`, `BETRAIL_SIGNING_SECRET`, etc.) is set. Every `live` scope (`403`) or non-sandbox credential is rejected, delegated sandbox credentials resolve strictly for the caller's `operator_id`, and every sandbox write/tester tool requires `consent_confirmed: true`. 3. **Untrusted data framing & invisible-character escaping.** Player-controlled strings (`client_seed`, `player_ref`, `view`) returned by `lookup_round`, `verify_round`, and `list_webhook_deliveries` are isolated in `untrusted_fields` with bidi overrides (`U+202A..U+202E`, `U+2066..U+2069`), zero-width characters (`U+200B..U+200D`, `U+FEFF`), and Unicode tags (`U+E0000..U+E007F`) escaped to `\uXXXX` / `\u{XXXXX}` alongside lossless `utf8_hex` for byte-exact fairness verification. 4. **Rate limits & SSRF-hardened 30/min tester budget.** Every JSON-RPC message is rate-limited per token and per operator (`64 KiB` body cap). `send_test_webhook` and `test_wallet_endpoint` enforce global-unicast SSRF egress rules (sandbox ports `80`, `443`, `8080`, `8443`) under a shared `30/min` operator tester budget. > **Security:** Never configure live credentials or weaken SSRF rules for MCP testers. All delegated OAuth grants can be revoked with one click in Console `/security` (`DELETE /console/mcp/consents/{id}`), immediately invalidating `/mcp` tokens (`401 consent_revoked`). ## Operator sign-in & live Console delegation `McpOAuthServer` (`/.well-known/oauth-authorization-server`, `/oauth/register`, `/oauth/authorize`, `/oauth/authorize/callback`, `/oauth/token`, `/oauth/revoke`) bridges OAuth 2.1 + PKCE (`S256`) directly through the Operator Console (`/mcp/authorize`) and the API's Console backend API (`/console/mcp/*`): 1. **Browser OAuth 2.1 + PKCE consent (`/mcp/authorize`):** Unauthenticated `GET /oauth/authorize` validates the registered client, redirect URI, `S256` challenge, `resource`, and sandbox scopes, then redirects to `${BETRAIL_MCP_CONSOLE_ORIGIN}/mcp/authorize?ticket=`. After 2FA sign-in (`owner`, `admin`, or `developer`), Console displays the unverified-client warning, exact `redirect_origin`, requested scopes, and `<= 24 h` lifetime, minting a consent-bound `btr_test_` key (`POST /console/mcp/consents`, KEK-wrapped at rest). 2. **Live Console delegation (`BETRAIL_MCP_SERVICE_SECRET`):** Set `BETRAIL_MCP_JWT_SECRET` (`>= 32` bytes, shared with Console), `BETRAIL_MCP_CONSOLE_ORIGIN=http://127.0.0.1:3002`, `BETRAIL_MCP_CONSOLE_BFF_URL=http://127.0.0.1:8082`, `BETRAIL_MCP_API_BASE_URL=http://127.0.0.1:8080`, and `BETRAIL_MCP_SERVICE_SECRET` (`>= 32` bytes, distinct from `BETRAIL_CONSOLE_SERVICE_SECRET`). This advertises all **12** MCP tools (`7` read + `5` sandbox write/tester). 3. **Loopback-only local fallback flags:** For air-gapped testing on `BETRAIL_MCP_LISTEN=127.0.0.1:8085`, `BETRAIL_MCP_DEV_CONSOLE_USER=:` supplies a loopback-only dev user when `BETRAIL_MCP_CONSOLE_ORIGIN` is unset, and `BETRAIL_MCP_DELEGATED_SANDBOX_CREDENTIALS_JSON` maps `` to `{ "api_key": "btr_test_", "signing_secret": "…", "brands": { ... } }` when `BETRAIL_MCP_SERVICE_SECRET` is unset (`11` tools advertised; non-sandbox keys abort startup). ## Tools (7 read + 5 sandbox write/tester) `tools/list` advertises all **12** tools with live Console delegation, **11** tools with static delegated credentials JSON (omitting `create_sandbox_key`), and **7** tools under `readOnlyMode: true`: | Tool | Scope | Inputs | Description | |---|---|---|---| | `list_games` | `mcp:read` | `kind?`, `spec_only?` | Lists all catalog games, spec resource URIs, and `served` status (`additionalProperties: false`). | | `get_game_spec` | `mcp:read` | `game`, `section?` | Returns the canonical game specification or matching heading sections (`section_not_found` on miss). | | `search_docs` | `mcp:read` | `query`, `category?`, `limit?` | Searches game/block specs, OpenAPI/AsyncAPI contracts, runbooks, and technical guides. | | `get_api_operation` | `mcp:read` | `operation_id?`, `method?`, `path?` | Retrieves an OpenAPI REST route, seamless wallet callback, live WebSocket frame, or AsyncAPI webhook contract (`round.settled`, `credits.low`, `credits.exhausted`). | | `lookup_round` | `mcp:read` | `round_id` | Reads a single sandbox round (`GET /v1/rounds/{id}`) scoped to the caller's `operator_id`. | | `verify_round` | `mcp:read` | `round_id` | Replays a revealed sandbox round (`GET /v1/rounds/{id}/verify`) scoped to the caller's `operator_id`. | | `list_webhook_deliveries` | `mcp:read` | `brand?`, `delivery_id?`, `status?`, `limit?` | Lists sandbox webhook delivery summaries (`pending`, `delivered`, `dead`) across `round.settled`, `credits.low`, and `credits.exhausted`. | | `simulate_round` | `mcp:sandbox:write` | `brand`, `game`, `player_ref`, `currency`, `stake`, `params`, `consent_confirmed` | Plays a sandbox round via `POST /v1/rounds` with exact decimal string `stake` after explicit confirmation (to choose a `client_seed`, call `rotate_sandbox_seed` first). | | `rotate_sandbox_seed` | `mcp:sandbox:write` | `player_ref`, `game`, `client_seed?`, `consent_confirmed` | Optionally updates next `client_seed` (`PUT /client-seeds/{game}`) and rotates the sandbox seed pair (`POST /seeds/{game}/rotate`). | | `send_test_webhook` | `mcp:sandbox:write` | `brand`, `url`, `consent_confirmed` | Sends a `betrail-v1`-signed `round.settled` sandbox test webhook under SSRF rules and the 30/min budget. | | `test_wallet_endpoint` | `mcp:sandbox:write` | `brand`, `wallet_url`, `player_ref`, `currency`, `consent_confirmed` | Runs a 6-step sandbox seamless-wallet conformance probe (`balance`, 1-atom `debit`, `idempotent_debit`, `rollback`, `credit`, and `bad_signature` refusal) under SSRF rules and the 30/min budget. | | `create_sandbox_key` | `mcp:sandbox:keys` | `brand`, `name`, `consent_confirmed` | Mints a one-time `btr_test_` and `signing_secret` via Console delegation (`POST /console/mcp/operators/{operator}/consents/{id}/sandbox-keys`). | ## `betrail://` resources & templates All resources require `mcp:read` scope: | Resource / template URI | MIME type | Contents | |---|---|---| | `betrail://catalog/games` | `application/json` | Machine-readable catalog of every BetPlug game (`id`, `slug`, `kind`, `spec_resource_uri`, `engine_ported`, `served`). | | `betrail://contracts/openapi` | `application/yaml` | Full OpenAPI 3.1 REST, session, and seamless wallet callback contract (`api/openapi.yaml`). | | `betrail://contracts/asyncapi` | `application/yaml` | Full AsyncAPI 3.1 live WebSocket and webhook (`round.settled`, `credits.low`, `credits.exhausted`) contract (`api/asyncapi.yaml`). | | `betrail://guides/fairness-recipes` | `text/markdown` | Commit-reveal lifecycle, all five legacy RNG recipes (`dice-sha512`, `hmac-nonce`, `plinko-hmac`), `FairRandom`, and live hash chains vs `stack-o-pass` per-player seeds. | | `betrail://guides/integration-guides` | `text/markdown` | End-to-end sandbox integration guide (`betrail-v1`, seamless wallet callbacks, `POST /v1/launch` embed, and signed webhooks). | | `betrail://specs/games/{slug}` | `text/markdown` | Canonical per-game specification, RNG recipe, paytable, and exact RTP for `{slug}`. | | `betrail://docs/adr/{slug}` | `text/markdown` | Published architecture decision notes by `{slug}`. | | `betrail://docs/blocks/{slug}` | `text/markdown` | Shared engine building-block specifications (`fair-random`, weighted tables, etc.) by `{slug}`. | | `betrail://docs/runbooks/{slug}` | `text/markdown` | Deployment, CI, and operations runbooks by `{slug}`. | | `betrail://docs/security/{slug}` | `text/markdown` | Security threat models and control checklists by `{slug}`. | ## Guided MCP prompts `@betrail/mcp` exposes four zero-secret guided prompts (`prompts/list`, `prompts/get`): | Prompt | Optional arguments | What it guides | |---|---|---| | `integrate` | `stack`, `mode`, `game` | End-to-end sandbox integration across headless REST, seamless wallet callbacks, launch sessions, and conformance tests. | | `embed` | `game`, `surface` | Mounting `` (with SRI from `manifest.json`) or the isolated play iframe with `betrail:v1` `postMessage` origin locking. | | `add-webhook-handler` | `stack`, `events` | Raw-body `betrail-v1` webhook signature verification, nonce replay blocking, and `Betrail-Webhook-Id` deduplication (`round.settled`, `credits.low`, `credits.exhausted`). | | `verify-round` | `round_id` | Cryptographic audit and deterministic replay of settled or post-draw `void` rounds using `lookup_round`, `verify_round`, and `get_game_spec`. | ## Escaping untrusted player fields in MCP responses (runnable sample) ```ts import assert from "node:assert/strict"; function escapeUntrustedDisplay(raw: string): { display_escaped: string; utf8_hex: string } { const utf8Hex = Buffer.from(raw, "utf8").toString("hex"); let escaped = ""; for (const ch of raw) { const cp = ch.codePointAt(0)!; const isControl = cp <= 0x1f || (cp >= 0x7f && cp <= 0x9f); const isBidi = (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069) || cp === 0x061c || cp === 0x200e || cp === 0x200f; const isZeroWidth = (cp >= 0x200b && cp <= 0x200d) || cp === 0x2060 || cp === 0xfeff || cp === 0x00ad; const isTag = cp >= 0xe0000 && cp <= 0xe007f; escaped += isControl || isBidi || isZeroWidth || isTag ? (cp <= 0xffff ? `\\u${cp.toString(16).padStart(4, "0")}` : `\\u{${cp.toString(16)}}`) : ch; } return { display_escaped: escaped, utf8_hex: utf8Hex }; } // Construct hostile seed at runtime using escapes so no invisible runes exist in source const hostileClientSeed = "seed" + "\u202E" + "ignore-rules" + "\u200B" + String.fromCodePoint(0xe0061); const framed = escapeUntrustedDisplay(hostileClientSeed); assert.equal(framed.display_escaped, "seed\\u202eignore-rules\\u200b\\u{e0061}"); // Fairness verifier recovers exact original UTF-8 bytes from utf8_hex without display spoofing assert.equal(Buffer.from(framed.utf8_hex, "hex").toString("utf8"), hostileClientSeed); ``` --- Source: /docs/claude-code.md --- # Build with Claude Code > **Security:** BetPlug's official Claude Code plugin (`version: "0.1.0"`) lives in `./claude-plugin` (`"private": true`) and intentionally ships **zero `hooks/`** so it never runs background shell commands without explicit developer approval. Do **not** install lookalike plugins or third-party marketplaces; load the plugin directly from your verified repository checkout. The official BetPlug Claude Code plugin bundles verified integration skills (`betrail-integrate`, `betrail-embed`, `betrail-verify`), slash commands, and the pinned remote Streamable HTTP MCP endpoint so your coding agent can wire a complete sandbox integration in TypeScript (`./sdk/ts`), Go (`./sdk/go`), Python (`./sdk/python`), or PHP (`./sdk/php`) — matching the reference casinos in `./examples/next-casino`, `./examples/go-casino`, and `./examples/laravel-casino` ([Official SDKs](/docs/sdk)). ## Pinned manifest identity Verify these exact values before loading the plugin: | Field | Pinned value | Defined in | |---|---|---| | Marketplace name | `betrail` | `claude-plugin/.claude-plugin/marketplace.json` | | Plugin install identifier | `betrail@betrail` | `claude-plugin/.claude-plugin/marketplace.json` | | Plugin directory / source | `./claude-plugin` (`source: "./"`) | `claude-plugin/.claude-plugin/marketplace.json` | | Pinned version | `0.1.0` | `claude-plugin/.claude-plugin/plugin.json` & `marketplace.json` | | Remote MCP server (`betrail`) | `https://mcp.betrail.example/mcp` (`${BETRAIL_MCP_URL:-https://mcp.betrail.example/mcp}`) | `claude-plugin/.mcp.json` | | Homepage | `https://betrail.example/docs/claude-code` | `claude-plugin/.claude-plugin/plugin.json` | ## Loading the official plugin locally Launch Claude Code directly from your verified repository checkout: ```sh claude --plugin-dir ./claude-plugin ``` Or register the local checkout as a development marketplace inside an interactive Claude Code session: ```text /plugin marketplace add ./claude-plugin /plugin install betrail@betrail ``` ### Connecting to a local BetPlug stack When developing against your local BetPlug stack — PostgreSQL/Valkey/Mailpit, `betrail-api`, `betrail-worker`, Operator Console (`http://127.0.0.1:3002`, with `BETRAIL_MCP_JWT_SECRET`), and the local MCP server (`node ./mcp/src/cli.ts` with `BETRAIL_MCP_JWT_SECRET`, `BETRAIL_MCP_CONSOLE_ORIGIN=http://127.0.0.1:3002`, `BETRAIL_MCP_CONSOLE_BFF_URL=http://127.0.0.1:8082`, `BETRAIL_MCP_SERVICE_SECRET`, and `BETRAIL_MCP_API_BASE_URL=http://127.0.0.1:8080`; see [Getting started](/docs/getting-started) and [Remote MCP server](/docs/mcp)) — export `BETRAIL_MCP_URL=http://127.0.0.1:8085/mcp` before launching `claude`. Claude Code opens `/mcp/authorize` in your browser so you can approve sandbox scopes under your 2FA-enrolled Console session and revoke them anytime from `/security`. When `BETRAIL_MCP_URL` is unset, `.mcp.json` connects exclusively to `https://mcp.betrail.example/mcp` via OAuth 2.1 + PKCE. ## Included slash commands & skills | Command / skill | Purpose | |---|---| | `/betrail-integrate` (`betrail-integrate`) | Wires a full sandbox integration: `.env.example`, `betrail-v1` / `betrail-v1-answer` signing, seamless wallet callbacks, webhook receiver, launch/headless calls, and conformance tests. | | `/betrail-embed` (`betrail-embed`) | Mounts `` (with SHA-384 SRI from `manifest.json`) or the isolated play host iframe with strict `betrail:v1` origin locking and CSP headers. | | `/betrail-verify` (`betrail-verify`) | Audits and replays settled or post-draw `void` rounds across every legacy recipe, `FairRandom`, and live hash chain with redacted dispute exports. | ## End-to-end sandbox workflow with `/betrail-integrate` Run `/betrail-integrate` inside your project (never pass secrets as command arguments): ```text /betrail-integrate ``` The `betrail-integrate` skill walks through seven verified stages: 1. **Detect stack & scaffold `.env.example`** with placeholder variables (`BETRAIL_API_BASE_URL`, `BETRAIL_BRAND_ID`, `BETRAIL_API_KEY=btr_test_`, `BETRAIL_SIGNING_SECRET`, `BETRAIL_WALLET_SECRET`, `BETRAIL_WEBHOOK_SECRET`, and optional 24-hour rotation overlap `BETRAIL_WALLET_PREV_SECRET`, `BETRAIL_WEBHOOK_PREV_SECRET`) — obtaining one-time sandbox credentials from Console Onboarding's one-time key vault and never committing secrets. 2. **Implement `betrail-v1` & `betrail-v1-answer` signing** verified against `api/testdata/signing-vectors.json` (plus optional RFC 8032 `ed25519=` wallet answers). 3. **Mount seamless wallet routes** (`POST /balance`, `/debit`, `/credit`, `/rollback`) keyed on `transaction_id`, returning unsigned `401` on bad auth, signed `4xx` refusals on insufficient funds, rollback tombstones, and unconditional `200` on `/credit` (including `"0.00000000"` and blocked players). 4. **Mount webhook receiver** (`round.settled`, `credits.low`, `credits.exhausted`) verifying `betrail-v1` over raw bytes before `JSON.parse` and deduplicating on `Betrail-Webhook-Id`. 5. **Wire launch/embed (`POST /v1/launch`) or headless rounds (`POST /v1/rounds`)** using exact decimal strings (`Amount`) and integer-atom math. 6. **Verify provable fairness** via seed rotation (`POST /v1/players/{player_ref}/seeds/{game}/rotate`) and `GET /v1/rounds/{id}/verify`. 7. **Run automated conformance tests** covering forged signatures, replay nonces, idempotent retries, rollback tombstones, and deterministic round replay. > **Tip:** Pair `/betrail-integrate` with the remote MCP server's `test_wallet_endpoint` (6-step conformance probe) and `send_test_webhook` tools to verify your local or staging sandbox endpoints before running the Console's 29-check go-live suite. --- Source: /docs/api-reference.md --- # REST & AsyncAPI reference Complete REST API, seamless wallet callback, and WebSocket protocol reference compiled from the [OpenAPI 3.1](/api/openapi.yaml) and [AsyncAPI 3.1](/api/asyncapi.yaml) specifications. - **OpenAPI version:** `3.1.0` (BetPlug API `v0.1.0`) - **AsyncAPI version:** `3.1.0` (BetPlug live games and webhooks `v0.1.0`) - **REST base URL:** `https://api.betrail.example` (example hostname) - **Live WebSocket host:** `wss://live.betrail.example/v1/live/{game}` ## Shared HTTP errors & retry matrix Every REST error returns RFC 9457 `application/problem+json` ([`Problem`](#problem)) with a unique `Betrail-Request-Id` header (`type`, `title`, `status`, `detail`, `instance`, `code` ([`ProblemCode`](#problemcode)), plus `max_stake` on `422 max_stake` and `elapsed_seconds`/`net_result` on `409 reality_check_due`). ```json { "type": "https://betrail.example/problems/max_stake", "title": "Stake exceeds maximum allowed for this target", "status": 422, "detail": "Stake exceeds the brand max_profit cap.", "instance": "/v1/rounds", "code": "max_stake", "max_stake": "5.00000000" } ``` | HTTP | `ProblemCode` values | Retryability | |---|---|---| | `400` | `invalid_request` | No — fix malformed JSON, headers, or schema | | `401` | `unauthorized`, `session_expired` | Re-sign with fresh timestamp & nonce (or re-launch if `session_expired`) | | `402` | `credits_exhausted`, `plan_inactive` | After topping up live USD credits or reactivating plan | | `403` | `forbidden`, `origin_not_allowed`, `player_blocked`, `jurisdiction_not_allowed` | No — fix key scope, allowed origin, player status, or jurisdiction policy | | `404` | `unknown_game`, `unknown_version`, `not_found` | No — verify resource ID and canonical `GameSlug` | | `409` | `not_offered`, `odds_changed`, `closed`, `limit`, `pending`, `seed_not_revealed`, `idempotency_key_in_use`, `insufficient_funds`, `limit_exceeded`, `max_exposure`, `round_open`, `reality_check_due` | `idempotency_key_in_use`/`pending` only: retry same `Idempotency-Key` + fresh nonce; resolve state for others | | `413` | `body_too_large` | No — keep request body <= 64 KB | | `415` | `unsupported_encoding` | No — send uncompressed `identity` JSON | | `422` | `invalid_input`, `invalid_action`, `stake_out_of_range`, `max_stake`, `unknown_profile`, `idempotency_key_reused` | No — fix parameters or mint a new `Idempotency-Key` | | `429` | `rate_limited` | Yes — wait `Retry-After` seconds, reuse `Idempotency-Key`, fresh nonce | | `500` | `no_acceptable_draw`, `internal` | Yes — retry same `Idempotency-Key` + body with fresh timestamp & nonce | | `503` | `wallet_unavailable` | Only when `Retry-After` is present (bulkhead); without it the round voided | ## Public & operator REST operations ### `getHealthz` — `GET /healthz` - **Summary:** Liveness probe - **Tag:** `probes` - **Authentication and signing:** public (`security: []`) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Responses:** - `200` -> [`Liveness`](#liveness) (`application/json`) (headers: `Cache-Control`): The process is alive. **Contract notes** Answers 200 as soon as the process serves HTTP. It never checks a dependency. The public answer is `{"ok":true}` and nothing else; `/readyz` and `/metrics` live on the private ops listener. **Response example (`200`)** ```json { "ok": true } ``` ### `listRounds` — `GET /v1/rounds` - **Summary:** List rounds - **Tag:** `rounds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Parameters:** `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required), `cursor` (query), `limit` (query), `player_ref` (query), `game` (query) - **Shared errors:** `400`, `401`, `403`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`RoundPage`](#roundpage) (`application/json`): A page of rounds. **Contract notes** The operator's rounds (instant/session rounds and revealed live show bets), newest first by id, optionally filtered to one player or game (including live show slugs `trapdoor`, `kombat-multiplayer`, `crash` and `meme-trade`) and cursor-paged deterministically across both. **Response example (`200`)** ```json { "data": [], "next_cursor": null } ``` ### `createRound` — `POST /v1/rounds` - **Summary:** Open a round - **Tag:** `rounds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`RoundCreate`](#roundcreate) - **Parameters:** `Idempotency-Key` (header, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`Round`](#round) (`application/json`): The round, settled (I and SL games) or open (S games). - `402` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`): The operator cannot open live rounds: its credits are exhausted (`credits_exhausted`) or its plan has lapsed (`plan_inactive`). Open rounds still finish, and sandbox keeps working. **Contract notes** Opens a round in headless mode. The operator debits the stake and credits the payout itself from this answer. Instant and slot games settle immediately; session games answer `open` and continue via actions. Every refusal is decided before the draw, so a refusal consumes no randomness. The nonce is reserved from the player's seed pair, and a round that fails after its draw is `void` and keeps its nonce. - **`404 unknown_game`** answers an unrecognized `game` slug before any offering gate is evaluated. - **`409 not_offered`** refuses, before any claim or nonce reservation: a disabled brand or environment; a game or currency not offered on the brand; an active game kill switch; in `live`, a currency with no FX rate in force at the start of the current UTC hour (USD is always in force, and `sandbox` never checks FX rates); or a bet or configuration the engine does not offer. A STACKOPASS hand (`stack-o-pass`) is played at a live table through a player session and the seamless wallet (`createSessionRound`), so this call refuses it. - **`403 jurisdiction_not_allowed`** refuses, before any claim or nonce reservation, a round whose optional operator-asserted `jurisdiction` is blocked by the brand environment's responsible-gaming settings (`sandbox` and `live`) or outside the operator's platform live allowlist (`live` only). This is an enforcement hook over operator-asserted and configured settings, not a legal compliance certification. - **`429 rate_limited`** refuses, in addition to per-key and public rate limits, a `sandbox` (`btr_test_`) open that would pass the operator's daily UTC sandbox round or stake cap, with `Retry-After` set to the seconds remaining until the next UTC day, before any claim, seed or nonce is spent; an idempotent replay of an already-reserved round still replays, and `live` (`btr_live_`) rounds are never capped. **Request example** ```json { "game": "dice", "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "stake": "0.00100000", "params": { "direction": "under", "chance": "47.98", "payout": "1.97999" } } ``` **Response example (`201`)** ```json { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "dice", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 1, "stake": "0.00100000", "payout": "0.00197999", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "roll": 3317, "win": true }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonce": 42 }, "created_at": "2026-10-29T01:45:00Z", "settled_at": "2026-10-29T01:45:00Z" } ``` ### `getRound` — `GET /v1/rounds/{id}` - **Summary:** Read a round - **Tag:** `rounds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Parameters:** `id` (path, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `401`, `403`, `404`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`Round`](#round) (`application/json`): The round. **Contract notes** One round of this operator. Another operator's round answers 404, never 403. A live show bet (`bet_id` as `id`) is readable as soon as it settles, before its show reveals the link seed: a final settled bet carries its public settle view, snapshotted `max_profit` and public seed commitment with zero unrevealed `server_seed`, and a provisional mid-round `meme-trade` sidebet (`settled_in_play`, voidable on outage) reads as `status: open` with zero `payout`/`refund`, empty `view` and `settled_at: null` until finalized. Once its show reveals, this route serves the full revealed show record (`round.settled`'s `data`). In-flight unsettled (`placed`) and voided show bets answer 404 (in-flight bets are observed via `POST /v1/live/{game}/bets` and the live WebSocket snapshot). **Response example (`200`)** ```json { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "dice", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 1, "stake": "0.00100000", "payout": "0.00197999", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "roll": 3317, "win": true }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonce": 42 }, "created_at": "2026-10-29T01:45:00Z", "settled_at": "2026-10-29T01:45:00Z" } ``` ### `actRound` — `POST /v1/rounds/{id}/actions` - **Summary:** Play one step of an open round - **Tag:** `rounds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`RoundAction`](#roundaction) - **Parameters:** `id` (path, required), `Idempotency-Key` (header, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`Round`](#round) (`application/json`): The round after the step. **Contract notes** One step of a session game (the game engine step handler). `step` numbers the step this action makes, the round's `step` plus one: a repeat of an applied step finds the round already there and is refused (`409 closed`), so one click never applies twice even without its `Idempotency-Key`. A `409 closed` on a round that is still open means the step was already taken: read the round for its current `step` before acting again. The answer says whether the step added stake (a double): the operator takes that increase. A force-close is not a step a player takes here: an action whose `do` is `force_close` is `422 invalid_action` in every game, nothing is drawn, and the round stays as it was (`RoundAction`). Close a player's rounds with `POST /v1/players/{player_ref}/force-close`. **Request example** ```json { "action": { "do": "cashout" }, "step": 3 } ``` **Response example (`200`)** ```json { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "mines", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 3, "stake": "0.00100000", "payout": "0.00107000", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "status": "CASHED_OUT", "mines": 3, "sweeped_tiles": [ 0 ], "mine_locations": [ 2, 11, 19 ], "multiplier": "1.07", "win": true, "payout": "0.00107000", "profit": "0.00007000", "max_profit_hit": false, "floats_used": 24, "game_result": { "status": "CASHED_OUT", "sweeped_tiles": [ 0 ], "mine_locations": [ 2, 11, 19 ] } }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "seed-1", "nonce": 42 }, "created_at": "2026-10-28T17:00:00Z", "settled_at": "2026-10-28T17:00:04Z" } ``` ### `verifyRound` — `GET /v1/rounds/{id}/verify` - **Summary:** Verify a round - **Tag:** `rounds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Parameters:** `id` (path, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `401`, `403`, `404`, `409`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`Verification`](#verification) (`application/json`): The verification, with the record it replayed. **Contract notes** Replays the round's record through the engine's `Verify` once its server seed is revealed. A record that does not replay is an answer, `result: verify_mismatch`, never a problem. Before the reveal the answer is `409 seed_not_revealed`. The record's amounts are decimal strings at its own currency's scale. **Response example (`200`)** ```json { "result": "ok", "record": { "v": 1, "game": "DICE", "version": 1, "tables": [ { "name": "paytable", "fingerprint": "7c145a94276eb256705c4c6d326824f70891fbc1120b33eea0433f432f702b4e" } ], "stream": { "kind": "dice-sha512", "server_seed_hash": "a8ae6e6ee929abea3afcfc5258c8ccd6f85273e0d4626d26c7279f3250f77c8e", "server_seed": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "client_seed": "ñandú-42", "nonce": 42 }, "input": { "profile": "source", "currency": { "code": "BTC", "scale": 8 }, "stake": "0.00100000", "limits": { "min_stake": "0.00000001", "max_stake": "0.10000000", "max_profit": "1.00000000" }, "params": { "direction": "under", "chance": "49.50" } }, "steps": [ { "outcome": { "status": "settled", "stake": "0.00100000", "payout": "0.00191919", "refund": "0.00000000", "exposure": "0.00191919", "trace": { "from": 0, "to": 1 }, "view": { "direction": "under", "chance": "49.50", "multiplier": "1.91919", "roll": 2396, "lucky": 762396, "windows": 1, "win": true, "payout": "0.00191919", "profit": "0.00091919", "capped": false, "game_result": { "type": 1, "payout": "1.91919" } } } } ] } } ``` ### `getSeeds` — `GET /v1/players/{player_ref}/seeds/{game}` - **Summary:** Read a player's seeds - **Tag:** `seeds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Parameters:** `player_ref` (path, required), `game` (path, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `401`, `403`, `404`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`SeedState`](#seedstate) (`application/json`): The seed state. **Contract notes** The player's seed pair for one game: the current server seed's commitment, client seed and next nonce, the next pair's commitment, and the previous pair revealed. A server seed is never shown before its rotation. **Response example (`200`)** ```json { "current": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonces_used": 43 }, "next": { "server_seed_hash": "5c4b3a29180716f5e4d3c2b1a09f8e7d6c5b4a3928170615f4e3d2c1b0a99887", "client_seed": "🎲 lucky", "nonces_used": 0 }, "previous": null } ``` ### `rotateSeeds` — `POST /v1/players/{player_ref}/seeds/{game}/rotate` - **Summary:** Rotate a player's seeds - **Tag:** `seeds` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** yes - **Request body schema:** `none` - **Parameters:** `player_ref` (path, required), `game` (path, required), `Idempotency-Key` (header, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `401`, `403`, `404`, `409`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`SeedState`](#seedstate) (`application/json`): The seed state after the rotation, with the previous pair revealed. **Contract notes** Reveals the current server seed, makes the committed next pair current (with the next client seed), and commits a new next pair; the nonce restarts at 0. It is refused with `409 round_open` while **any round on the current pair is unfinished**: `reserved` (its nonce reserved, nothing drawn yet), `debiting` (a seamless round whose outcome is drawn but hidden until its debit is confirmed), open, or, in a live game, an unresolved placement. Revealing the seed would reveal that round's outcome, or let a `reserved` round draw on a public seed, and a player who sees a loss before the debit could make it fail. One transaction locks the seed row that the nonce reservation updates (`SELECT … FOR UPDATE`), checks the pair for unfinished rounds, reveals the seed, promotes the next pair and commits a new one. A concurrent open has therefore either committed its reservation before the rotation, and its `reserved` round refuses the rotation, or it reserves its nonce on the new pair. **Response example (`200`)** ```json { "current": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonces_used": 43 }, "next": { "server_seed_hash": "5c4b3a29180716f5e4d3c2b1a09f8e7d6c5b4a3928170615f4e3d2c1b0a99887", "client_seed": "🎲 lucky", "nonces_used": 0 }, "previous": null } ``` ### `setPlayerStatus` — `PUT /v1/players/{player_ref}/status` - **Summary:** Set a player's status - **Tag:** `players` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`PlayerStatusSet`](#playerstatusset) - **Parameters:** `player_ref` (path, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `400`, `401`, `403`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`PlayerStatus`](#playerstatus) (`application/json`): The player's status after the call. **Contract notes** Sets the player's status. A player who is not `active` cannot open a round, mint a live join ticket, place a live bet or buy in on MEME_TRADE (`403 player_blocked`), while settled rounds still pay out through the outbox. When `status` is `self_excluded` or `blocked` (repeat calls included), BetPlug also revokes the player's active live sessions for `(operator, environment, player_ref)` immediately, closing open live sockets (`1008`) and refusing further socket commands or re-wagering of a MEME_TRADE round balance; if session revocation cannot be persisted, the call fails closed with `500 internal` so the operator retries. To end a self-excluded player's force-closeable open rounds at once, follow this call with force-close. **Request example** ```json { "status": "self_excluded" } ``` **Response example (`200`)** ```json { "player_ref": "p_8f3a2c", "status": "self_excluded", "updated_at": "2026-10-29T01:45:00Z" } ``` ### `forceClosePlayer` — `POST /v1/players/{player_ref}/force-close` - **Summary:** Force-close a player's open rounds - **Tag:** `players` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`ForceCloseRequest`](#forcecloserequest) - **Parameters:** `player_ref` (path, required), `Idempotency-Key` (header, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `400`, `401`, `403`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`ForceCloseResult`](#forcecloseresult) (`application/json`): The rounds this call settled; an empty list when the player had none open. **Contract notes** Settles every open round of the player, or of one game, with platform force-close. It sends each game's force-close action, which a player cannot send on the actions routes (`RoundAction`). Each round settles under its game's rule, which reads only the player's view and draws nothing hidden. The answer lists the rounds this call settled, and `round.settled` goes out for each. - **A live show bet is not a platform force-close round.** `live` sends its game's force-close command to the show's writer (TRAPDOOR's `bank` with `DISCONNECT`, CRASH's `force_close`), one bet at a time, and the show runs on for everyone else. This call reaches them for live shows. Neither KOMBATMP nor MEME_TRADE v2 has a force-close: a KOMBATMP bet has no in-round action and settles with its round within about a minute, and under the MEME_TRADE settlement rules an in-flight MEME_TRADE position, sidebet or round balance rides to its armed `auto_sell`, liquidation or rug on the 250 ms server clock while `setPlayerStatus` revokes live sessions at once, so this call leaves both open and lists them nowhere. - **A STACKOPASS hand is a platform force-close round**: this call settles it as any round, a cash-out at `⌊100 S⌋ / 100` or a full refund before its first pack, and its table shows the seat closed and tells the player's sockets (`settled_by: force_close`). - **A round with money in flight is left alone.** A round still `reserved` or `debiting`, or one with a debit attempt unresolved (`409 pending` for its next step), is not settled here, because its outcome depends on what the sweep decides. The answer's `pending` counts them: call again with a new `Idempotency-Key` once the sweep has resolved them, within about 2 minutes. - **The time is the operator's choice, so it sees only public state**. No hidden draw reaches the operator before its reveal, so no force-close can be timed against the player. - In seamless mode each settled round's credit goes out through the outbox. In headless mode the operator pays the payouts listed. **Request example** ```json { "game": "dice" } ``` **Response example (`200`)** ```json { "rounds": [], "pending": 0 } ``` ### `createLaunch` — `POST /v1/launch` - **Summary:** Launch a game for a player - **Tag:** `launch` - **Authentication and signing:** `apiKey` (`Bearer`) + `requestSignature` (`betrail-v1`) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`LaunchCreate`](#launchcreate) - **Parameters:** `Idempotency-Key` (header, required), `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`Launch`](#launch) (`application/json`) (headers: `Cache-Control`): The launch token and the play URL. - `402` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`): The operator cannot open live rounds: its credits are exhausted (`credits_exhausted`) or its plan has lapsed (`plan_inactive`). Open rounds still finish, and sandbox keeps working. **Contract notes** Starts seamless play. The operator's backend gets a **launch token**: 32 random bytes, single-use, valid for 60 s, consumed in Postgres. It also gets the play URL for the iframe host; the Web Component takes the token as an attribute instead. The client exchanges the token once for a session token (`POST /v1/sessions`), and its own calls are the `session` operations. - **The token in the URL**: the play page answers with `Referrer-Policy: no-referrer`, removes the token from the address bar with `history.replaceState` before anything else loads, and BetPlug's access logs drop the query string. - **The token is never replayed.** Only its hash is stored, in the launch row and in the idempotency claim. A repeat of the `Idempotency-Key` mints a **fresh** token for the same launch and invalidates the previous one. It never returns the stored answer's token. - `return_url` must be on one of the brand's configured origins, or the launch is refused (`400 invalid_request`). - A `real` launch for a player whose status is not `active` is refused (`403 player_blocked`). A `demo` launch is never refused for `credits_exhausted` or `plan_inactive`, since it touches no wallet and is never billed. - **`403 jurisdiction_not_allowed`** refuses a `real` launch (its idempotent repeat) when the optional operator-asserted `jurisdiction` is blocked by the brand environment's responsible-gaming settings (`sandbox` and `live`) or outside the operator's platform live allowlist (`live` only). The session keeps the launch's jurisdiction and re-checks it on every subsequent exchange, round open, live bet and MEME_TRADE buy-in. - **`409 not_offered`** refuses, before any launch row or token is written: a disabled brand or environment; a game or currency not offered on the brand; an active game kill switch; for `mode: real` in `live`, a currency with no FX rate in force at the start of the current UTC hour (USD is always in force, and `sandbox` and `demo` never check FX rates); or, for a live show or live table game (`LiveGameSlug` including `stack-o-pass`), `mode: demo` (live games have no demo play) or a show not running in that environment. - **`404 unknown_game`** answers an unrecognized `game` slug before any offering gate is evaluated. **Request example** ```json { "game": "dice", "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "mode": "real", "locale": "es-AR" } ``` **Response example (`201`)** ```json { "token": "EXAMPLE_launch_token_0000000000000000000000", "url": "https://play.betrail.example/dice?token=EXAMPLE_launch_token_0000000000000000000000", "expires_at": "2026-10-29T01:46:00Z", "reality_check": { "interval_seconds": 1800, "due_at": "2026-10-29T02:15:00Z" } } ``` ### `createSession` — `POST /v1/sessions` - **Summary:** Exchange a launch token for a session token - **Tag:** `launch` - **Authentication and signing:** public (launch-token) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`SessionCreate`](#sessioncreate) - **Parameters:** `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`Session`](#session) (`application/json`) (headers: `Cache-Control`): The session. **Contract notes** The embedded client's first call. The launch token in the body is the credential, so the call carries no credential header (`security: []`, enforced to this path). - **One exchange per launch token.** The token is consumed in Postgres under a unique constraint. A second exchange, an expired token or an unknown one gets `401 unauthorized`, with the same body for all three. - **The session token is never replayed.** Only its hash is stored. A repeat of the `Idempotency-Key` with the same launch token, within that token's 60 s, mints a fresh session token for the same session and invalidates the previous one, as a launch's repeat does, so a client whose answer was lost is not locked out. After the 60 s a repeat is `401`, like any other exchange. - **The key must be random.** For those 60 s it is what stops a stranger who saw the launch token from minting a fresh session, so the client generates it with `crypto.getRandomValues` and never derives it from the token. - **Nothing is written for a bad token.** The key is scoped to the launch token and is claimed only once the token has been found, so an unauthenticated caller cannot grow the claims table. - **Origins are a browser control**, as `sessionToken` says. An `Origin` outside the brand's allowed set is `403 origin_not_allowed`, and that refusal does not consume the token. A call with no `Origin` is allowed: the launch token alone binds it. - **A live real launch asks the live gate again.** Once live play is no longer enabled for the operator, the exchange of a live real launch token, and its repeat, are `403 forbidden` ("Live play is not enabled for this operator.") and do not consume the token, as a repeat of the launch is. Likewise, if the launch's operator-asserted `jurisdiction` is now blocked by the brand environment's settings (`sandbox` or `live`) or outside the operator's live allowlist (`live`), the exchange and its repeat answer `403 jurisdiction_not_allowed` without consuming the token. **Request example** ```json { "launch_token": "EXAMPLE_launch_token_0000000000000000000000" } ``` **Response example (`201`)** ```json { "session_token": "bts_", "expires_at": "2026-10-29T09:45:10Z", "idle_timeout_seconds": 900, "game": "dice", "currency": "BTC", "mode": "real", "reality_check": { "interval_seconds": 1800, "due_at": "2026-10-29T02:15:00Z" } } ``` ### `createDemoSession` — `POST /v1/demo/sessions` - **Summary:** Start a demo session - **Tag:** `launch` - **Authentication and signing:** public (demo) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`DemoSessionCreate`](#demosessioncreate) - **Parameters:** `Idempotency-Key` (header, required) - **Shared errors:** `400`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`Session`](#session) (`application/json`) (headers: `Cache-Control`): The demo session. **Contract notes** Demo mode: the real engines, on an ephemeral seed pair, with fun money (`FUN`) from a fixed balance. It needs no key (`security: []`, enforced to this path). Its rounds never touch a wallet, the rounds table or the ledger, are never billed, and have no record or proof that anything but their own session can read. - **Only BetPlug's own sites** may call it: an absent `Origin`, or one that is not ours, is `403 origin_not_allowed`. Per-IP and global caps bound sessions and rounds (`429 rate_limited`). CORS does not bind a server-to-server caller, so the caps and the missing proofs are what stop an operator from settling real money on demo outcomes. - **The token works on the session calls, and nothing else sees its rounds.** `GET /v1/rounds/{id}` answers `404` for a demo round. In a keyless demo round `brand` and `player_ref` are both `demo`, and `currency` is `FUN`. `POST /v1/session/seeds/rotate` is how the session sees its ephemeral seed revealed, since a session that has ended can be told nothing. - **No row for a keyless caller.** The session, its rounds and its `Idempotency-Key`s live in Valkey for an hour, never in Postgres, so this call cannot grow a table. A repeat of the key from the same address mints a fresh token for the same demo session, which the caps count once. - **All single-player games supported.** All 36 instant, slot, and session games play with fun money (`FUN`) and never check FX rates. Live shows and live table games (`stack-o-pass`) answer `409 not_offered` (live games have no demo play); an unrecognized game slug answers `404 unknown_game`. **Request example** ```json { "game": "dice", "locale": "en" } ``` **Response example (`201`)** ```json { "session_token": "bts_", "expires_at": "2026-10-29T09:45:10Z", "idle_timeout_seconds": 900, "game": "dice", "currency": "BTC", "mode": "real", "reality_check": { "interval_seconds": 1800, "due_at": "2026-10-29T02:15:00Z" } } ``` ### `listSessionRounds` — `GET /v1/session/rounds` - **Summary:** List the session player's rounds - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Parameters:** `cursor` (query), `limit` (query) - **Shared errors:** `400`, `401`, `403`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`RoundPage`](#roundpage) (`application/json`): A page of the session player's rounds. **Contract notes** The session player's rounds in the session's game (including revealed live show bets in a live show session), newest first, for the client's history panel: the same page as `GET /v1/rounds`, with no filter to name. It sees no other player, brand or game. **Response example (`200`)** ```json { "data": [], "next_cursor": null } ``` ### `createSessionRound` — `POST /v1/session/rounds` - **Summary:** Open a round in the session - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`SessionRoundCreate`](#sessionroundcreate) - **Parameters:** `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`Round`](#round) (`application/json`): The round, settled for an instant game. - `402` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`): The operator cannot open live rounds: its credits are exhausted (`credits_exhausted`) or its plan has lapsed (`plan_inactive`). Open rounds still finish, and sandbox keeps working. - `503` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`, `Retry-After`): The operator's wallet did not answer in time (`wallet_unavailable`). One of three cases: the debit's result is unknown, so the round is voided, the debit rolled back and nothing revealed (a repeat of the `Idempotency-Key` gets this answer again); the operator's in-flight wallet calls are at the bulkhead, so nothing was written and `Retry-After` says when to try again; a balance read got no answer, or one that is not bound, so nothing was written. **Contract notes** `POST /v1/rounds` for the embedded client in seamless mode. The session supplies the brand, player, game and currency. In a `real` session BetPlug debits the operator's wallet before revealing the outcome. A refused debit answers with the wallet's code (`409 insufficient_funds`, `409 limit_exceeded`, `403 player_blocked`, `400 invalid_request`), and an unknown failure answers `503 wallet_unavailable` with the round voided. A `demo` session plays from its fun balance and calls no wallet. - **`409 not_offered`** applies the same pre-draw offering gates as `POST /v1/rounds`, before any claim, debit or nonce reservation: a disabled brand or environment; a game or currency not offered on the brand; an active game kill switch; in a `real` `live` session, a currency with no FX rate in force at the start of the current UTC hour (USD is always in force, and `sandbox` and `demo` never check FX rates); or a bet or configuration the engine does not offer. - **`404 unknown_game`** answers an unrecognized game slug before any offering gate is evaluated. - **`403 jurisdiction_not_allowed`** refuses a `real` session round before any claim, wallet debit or nonce reservation when the session's operator-asserted `jurisdiction` is blocked by the brand environment's responsible-gaming settings (`sandbox` and `live`) or outside the operator's live allowlist (`live`), including when an allowlist narrowing or new brand block takes effect mid-session; open rounds continue to settle. - **`409 reality_check_due`** refuses a `real` session round before any claim, wallet debit or nonce reservation once the session reaches or passes its snapshotted `reality_check.due_at` (`now >= due_at`), carrying `elapsed_seconds` and `net_result` from this session's settled rounds. Acknowledge with `POST /v1/sessions/current/reality-check` to advance `due_at` by one interval and resume play. Demo sessions and sessions launched while reality checks are off are unaffected. - **`429 rate_limited`** refuses, in addition to rate limits, a `real` `sandbox` session round that would pass the operator's daily UTC sandbox round or stake cap (7), with `Retry-After` set to the seconds remaining until the next UTC day, before any claim, wallet debit or nonce is spent; `live` and `demo` sessions are unaffected (`demo` uses its own session limits). - **STACKOPASS's buy-in** (`stack-o-pass`): a hand at a live table is a session round on the player's own seed pair, so its buy-in is this call, never a live bet. The body names the seat, `live_seat` (`LiveTableSeat`), and `params` is `StackOPassParams`. The steps run in this order, and a repeat of the key never takes or loses a seat: 1. **The key.** A repeat of a claimed `Idempotency-Key` replays its stored answer (the `201`, a refusal stored in step 4, or the `409 closed` of step 5) and asks `live` nothing; while the first request still runs it is `409 idempotency_key_in_use`. A repeat whose round is open but not seated (the first request stopped after its debit) asks `live` to seat that round again, which answers as step 5 does. 2. **The checks** of any session round (the offering gates, the player's status, credits, limits and `max_exposure`'s early read), and the body's: `live_seat` on another game, or none on STACKOPASS, is `400 invalid_request`; a `demo` session is `403 forbidden` (demo play has no seat at a live table). 3. **The seat hold.** `live` holds the seat for this key, at most 30 s. It looks the table up among the player's operator's tables first (5), so another operator's table is `409 closed`, with the same `detail` as a gone table, before any other check; then `409 closed` (no writer answers), `409 idempotency_key_in_use` (this key already holds the seat: the first request still runs), `409 not_offered` (another player's seat), `409 limit` (a seat at another table, or an open hand), `409 pending` (this player's buy-in for the seat under another key still in flight), `409 odds_changed` (`params.risk` is not the table's). These move nothing, a refused repeat releases no hold, and a repeat decides them again. 4. **The round**, as any session round: the engine's refusals before the claim (`422 invalid_input`, `422 stake_out_of_range`, `422 max_stake` with `max_stake`), decided again on a repeat; then the claim, the nonce and the exposure in one transaction (`409 max_exposure` writes none of them); then the debit, whose refusal (the wallet's codes) or unknown answer (`503 wallet_unavailable`, the round voided) is the key's stored answer; then `Open`. Every refusal releases this request's hold. 5. **The seat.** `live` seats the open round in the seat this key holds (idempotent by round id), and the answer is `201`, its `view` the engine's open view (`hand`, with `blocks` for all three risks as its record keeps them; the socket shows the table's alone). If the hold is gone (it ran out, `live` failed over), the platform force-closes the round at once, a full refund (`kind: refund`), and `409 closed` is the key's stored answer. A round no table holds 60 s after it opened, whatever stopped (this call, its seat call, `api` itself), is force-closed by the live server's sweep within 10 s more, a full refund (`settled_by: force_close`), and a repeat of its key answers `409 closed`. The hand's moves then go over the socket (`asyncapi.yaml`, `StackOPassCommand`). **Request example** ```json { "stake": "0.00100000", "params": { "direction": "under", "chance": "47.98" } } ``` **Response example (`201`)** ```json { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "dice", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 1, "stake": "0.00100000", "payout": "0.00197999", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "roll": 3317, "win": true }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonce": 42 }, "created_at": "2026-10-29T01:45:00Z", "settled_at": "2026-10-29T01:45:00Z" } ``` ### `getSessionRound` — `GET /v1/session/rounds/{id}` - **Summary:** Read a round of the session's player - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Parameters:** `id` (path, required) - **Shared errors:** `400`, `401`, `403`, `404`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`Round`](#round) (`application/json`): The session player's round. **Contract notes** A round of the session's player in the session's game, as `GET /v1/rounds/{id}` shows it, including a settled live show bet read by its `rnd_` id before or after its show reveals its seed (provisional in-play `meme-trade` sidebets read as `open` with an empty `view` until finalized, and no unrevealed server seed ever leaves). An in-flight unsettled (`placed`) or voided show bet, and any round of another player, brand, environment or game, answers 404, the same as for an id that exists nowhere. A MEME_TRADE session also reads by the `bet_id` of its `settled` frame (`MemeTradeSettlement`), once the show round has revealed its seed: the show round's id (`-`) reads the player's own trade record, and a sidebet's frame id (`sb-:-`, URL-encoded in the path) reads that sidebet's own record — each returning the same `Round` its `rnd_` id reads. A player who only bought in (only placed sidebets) has no trade record, so the show round id answers 404 (a buy-in-only player's balance still returns in full as its round-balance credit); a sidebet's frame id answers 404 until its show round has revealed its seed, and answers 404 for any other player, brand, environment, game or operator, identical to an unknown id. **Response example (`200`)** ```json { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "dice", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 1, "stake": "0.00100000", "payout": "0.00197999", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "roll": 3317, "win": true }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonce": 42 }, "created_at": "2026-10-29T01:45:00Z", "settled_at": "2026-10-29T01:45:00Z" } ``` ### `actSessionRound` — `POST /v1/session/rounds/{id}/actions` - **Summary:** Play one step of a round in the session - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`RoundAction`](#roundaction) - **Parameters:** `id` (path, required), `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`Round`](#round) (`application/json`): The session player's round after the step. - `503` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`, `Retry-After`): The operator's wallet did not answer in time (`wallet_unavailable`). One of three cases: the debit's result is unknown, so the round is voided, the debit rolled back and nothing revealed (a repeat of the `Idempotency-Key` gets this answer again); the operator's in-flight wallet calls are at the bulkhead, so nothing was written and `Retry-After` says when to try again; a balance read got no answer, or one that is not bound, so nothing was written. **Contract notes** `POST /v1/rounds/{id}/actions` for the embedded client: the same `{action, step}`, the same `409 closed` for a step already taken, and the same `422 invalid_action` for an action whose `do` is `force_close`, the platform's move, refused before any debit or draw (`RoundAction`). A step that adds stake is debited from the wallet first, as an open is. A STACKOPASS hand (`stack-o-pass`) is played at its table, which orders its moves, so its moves go over the socket (`StackOPassCommand` in `asyncapi.yaml`) and this route refuses it with `409 not_offered` before anything is read or drawn. For a `real` session with an active reality-check interval, actions at or after `reality_check.due_at` answer `409 reality_check_due` (carrying `elapsed_seconds` and `net_result`) before any draw or debit until acknowledged via `POST /v1/sessions/current/reality-check`; operator force-close and inactivity settlement remain unaffected. **Request example** ```json { "action": { "do": "cashout" }, "step": 3 } ``` **Response example (`200`)** ```json { "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "mines", "version": 1, "brand": "br_casino_main", "player_ref": "p_8f3a2c", "currency": "BTC", "status": "settled", "step": 3, "stake": "0.00100000", "payout": "0.00107000", "refund": "0.00000000", "max_profit": "1.00000000", "cap_rule": "truncate", "cap_source": "brand", "view": { "status": "CASHED_OUT", "mines": 3, "sweeped_tiles": [ 0 ], "mine_locations": [ 2, 11, 19 ], "multiplier": "1.07", "win": true, "payout": "0.00107000", "profit": "0.00007000", "max_profit_hit": false, "floats_used": 24, "game_result": { "status": "CASHED_OUT", "sweeped_tiles": [ 0 ], "mine_locations": [ 2, 11, 19 ] } }, "seed": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "seed-1", "nonce": 42 }, "created_at": "2026-10-28T17:00:00Z", "settled_at": "2026-10-28T17:00:04Z" } ``` ### `getSessionBalance` — `GET /v1/session/balance` - **Summary:** Read the session player's balance - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Shared errors:** `401`, `403`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`SessionBalance`](#sessionbalance) (`application/json`) (headers: `Cache-Control`): The session player's balance. - `503` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`, `Retry-After`): The operator's wallet did not answer in time (`wallet_unavailable`). One of three cases: the debit's result is unknown, so the round is voided, the debit rolled back and nothing revealed (a repeat of the `Idempotency-Key` gets this answer again); the operator's in-flight wallet calls are at the bulkhead, so nothing was written and `Retry-After` says when to try again; a balance read got no answer, or one that is not bound, so nothing was written. **Contract notes** The player's balance in the session's currency, so the balance the client shows is the server's. It reads the operator's wallet (`POST {base}/balance`) and stores nothing. A settled round's credit goes out through the outbox, so it may not be in this figure yet. A `demo` session reads its fun balance and calls no wallet. - **The answer is bound.** The wallet's `currency` must equal the session's, `balance` must parse as an `Amount`, and a live brand's answer is signed. Anything else is `503 wallet_unavailable`. - **Its own bulkhead.** At most 8 of these reads per operator are in flight on each `api` instance (a setting), so a burst of page loads cannot take the debits' slots. Past it the answer is `503 wallet_unavailable` with `Retry-After`. **Response example (`200`)** ```json { "balance": "0.01250000", "currency": "BTC" } ``` ### `getSessionSeeds` — `GET /v1/session/seeds` - **Summary:** Read the session player's seeds - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** no - **Request body schema:** `none` - **Shared errors:** `401`, `403`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`SeedState`](#seedstate) (`application/json`): The session player's seed state. **Contract notes** The seed state of the session's player and game, as `GET /v1/players/{player_ref}/seeds/{game}` shows it. **Response example (`200`)** ```json { "current": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonces_used": 43 }, "next": { "server_seed_hash": "5c4b3a29180716f5e4d3c2b1a09f8e7d6c5b4a3928170615f4e3d2c1b0a99887", "client_seed": "🎲 lucky", "nonces_used": 0 }, "previous": null } ``` ### `setSessionClientSeed` — `PUT /v1/session/client-seed` - **Summary:** Set the session player's next client seed - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`ClientSeedSet`](#clientseedset) - **Shared errors:** `400`, `401`, `403`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`SeedState`](#seedstate) (`application/json`): The session player's seed state, with the new next client seed. **Contract notes** Sets the client seed of the session player's **next** seed pair. It takes effect at the next rotation, so a seed pair in use never changes. Setting the same value again is a no-op. Only the player's own session may set a client seed; operator API keys cannot alter it. **Request example** ```json { "client_seed": "🎲 lucky" } ``` **Response example (`200`)** ```json { "current": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonces_used": 43 }, "next": { "server_seed_hash": "5c4b3a29180716f5e4d3c2b1a09f8e7d6c5b4a3928170615f4e3d2c1b0a99887", "client_seed": "🎲 lucky", "nonces_used": 0 }, "previous": null } ``` ### `rotateSessionSeeds` — `POST /v1/session/seeds/rotate` - **Summary:** Rotate the session player's seeds - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** `none` - **Parameters:** `Idempotency-Key` (header, required) - **Shared errors:** `401`, `403`, `409`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`SeedState`](#seedstate) (`application/json`): The session player's seed state after the rotation, with the previous pair revealed. **Contract notes** `POST /v1/players/{player_ref}/seeds/{game}/rotate` for the embedded client: the same reveal, and the same `409 round_open` while a round drawn from the current pair is unfinished. **Response example (`200`)** ```json { "current": { "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d", "client_seed": "ñandú-42", "nonces_used": 43 }, "next": { "server_seed_hash": "5c4b3a29180716f5e4d3c2b1a09f8e7d6c5b4a3928170615f4e3d2c1b0a99887", "client_seed": "🎲 lucky", "nonces_used": 0 }, "previous": null } ``` ### `acknowledgeRealityCheck` — `POST /v1/sessions/current/reality-check` - **Summary:** Acknowledge a due reality check on the current player session - **Tag:** `session` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** `none` - **Parameters:** `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `200` -> [`RealityCheckAck`](#realitycheckack) (`application/json`) (headers: `Cache-Control`): The recorded reality-check acknowledgement and updated next due timestamp. **Contract notes** Records one player acknowledgement for a due reality check on the authenticated real-money seamless session (part 2; operator-configured hook, not a legal compliance certification; policy defaults pending platform policy). Takes a 0-byte empty body (`400 invalid_request` if any body or query parameter is sent). - **Due-only enforcement (anti-stacking):** succeeds only when the session has an active reality-check interval and `now >= reality_check.due_at`. Calling before `due_at`, on a `demo` session, or on a session launched while reality checks were off answers `409 closed` without writing an idempotency claim or mutating the session. - **State transition:** locks the `player_sessions` row, computes `elapsed_seconds` and `net_result` from this session's settled rounds, advances `reality_check.due_at` to `now + interval_seconds`, and appends an immutable row to `session_reality_checks`. - **Idempotent replay and stale keys:** repeating the same `Idempotency-Key` within the same session replays the stored `200` answer without advancing `due_at` a second time — including after a subsequent interval becomes due, where the next round open remains refused with `409 reality_check_due` until a fresh `Idempotency-Key` is sent. Reusing a key from another session of the same player answers `422 idempotency_key_reused`. **Response example (`200`)** ```json { "acknowledged_at": "2026-10-29T02:15:05Z", "elapsed_seconds": 1805, "net_result": "-0.00050000", "reality_check": { "interval_seconds": 1800, "due_at": "2026-10-29T02:45:05Z" } } ``` ### `createLiveTicket` — `POST /v1/live/{game}/tickets` - **Summary:** Get a join ticket for a live game's socket - **Tag:** `live` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** `none` - **Parameters:** `game` (path, required), `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `413`, `415`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`LiveTicket`](#liveticket) (`application/json`) (headers: `Cache-Control`): The join ticket. **Contract notes** The live client's call before each socket it opens. The answer is a join ticket for the socket `/v1/live/{game}` on the live server (`asyncapi.yaml`, channel `liveGame`), which the client sends as a subprotocol, `Sec-WebSocket-Protocol: betrail.v1, ticket.` (scheme `joinTicket`), never in a URL. The call takes the session token alone, as the `session` operations do, and no body (`400 invalid_request`). - **The ticket** is `v1..`, signed with the live ticket key. Its payload, `{sid, operator, brand, environment, player, game, exp, jti}`, comes from the session and never from the request. It names the session by its own random id (`sid`) and holds no session token, no hash of one and no other secret, because it is signed, not encrypted: anyone who sees a ticket can read it. - **30 s, one socket.** `exp` is 30 s after the mint. `live` checks the MAC, then `exp`, the game and the environment, then the handshake's `Origin`, and consumes the `jti` last, so a refused handshake does not burn the ticket. A client gets a fresh ticket for every socket it opens, a reconnect included: a ticket is never refreshed or extended. - **Nothing is claimed or stored.** The `Idempotency-Key` is required and checked for shape, but a ticket is a 30 s credential, not a resource: every call, a repeat of the key included, mints a fresh ticket with a fresh `jti`, and neither the ticket nor a claim is written. A client whose answer was lost asks again, and the ticket it never saw expires unused. - **`{game}` is the session's game.** A session is bound to one game, so another live game is `403 forbidden`, and a slug that is not a live game is `404 not_found`. A `demo` session is `403 forbidden`: demo play has no seat in a live show, and allowing it later is additive. - **Player status and money gates.** A player whose status is `self_excluded` or `blocked` is refused (`403 player_blocked`). A ticket moves no money and opens nothing, so the call checks neither the operator's credits, plan nor offering gates: an `active` player with a bet in a show can rejoin and finish it, while those gates refuse new bets and buy-ins over REST. - **Origins are a browser control**, as `sessionToken` says, and `live` checks the handshake's `Origin` again against the brand's set. - Minting is rate-limited per session (`429 rate_limited` with `Retry-After`). **Response example (`201`)** ```json { "ticket": "v1.EXAMPLE_payload.EXAMPLE_ticket_mac_000000000000000000000000", "expires_at": "2026-10-29T01:45:30Z" } ``` ### `createLiveBet` — `POST /v1/live/{game}/bets` - **Summary:** Place a bet on a live show - **Tag:** `live` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`LiveBetCreate`](#livebetcreate) - **Parameters:** `game` (path, required), `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`LiveBet`](#livebet) (`application/json`): The bet, placed in the show. - `202` -> [`LiveBet`](#livebet) (`application/json`): The bet's debit is confirmed and its placement is not yet known; repeat the key to learn it. - `402` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`): The operator cannot open live rounds: its credits are exhausted (`credits_exhausted`) or its plan has lapsed (`plan_inactive`). Open rounds still finish, and sandbox keeps working. - `503` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`, `Retry-After`): The operator's wallet did not answer in time (`wallet_unavailable`). One of three cases: the debit's result is unknown, so the round is voided, the debit rolled back and nothing revealed (a repeat of the `Idempotency-Key` gets this answer again); the operator's in-flight wallet calls are at the bulkhead, so nothing was written and `Retry-After` says when to try again; a balance read got no answer, or one that is not bound, so nothing was written. **Contract notes** A live player's bet on the show now open for bets (bets go through REST in both integration modes). One call for every live game whose money goes in as a bet, as the join ticket is one call: the path names the game, `params` is the game's own, and the sequence behind it is the same for all of them (check, debit, place, else roll back). TRAPDOOR, KOMBATMP and CRASH take it. MEME_TRADE's buy-in is not a bet, nor is STACKOPASS's: a hand is a session round on the player's own seed pair, bought in with `createSessionRound` (`live_seat`). Money always runs through the operator's seamless wallet. - **The session's game.** `{game}` must be the session's game (`403 forbidden`); a slug outside the enum is `404 not_found`, and a game in it whose live server does not run on this deployment is `409 not_offered` (TRAPDOOR, KOMBATMP, CRASH, and MEME_TRADE all run live servers). A `demo` session is `403 forbidden`: demo play has no seat in a live show. - **The show.** `show` names the show the client bets on, by its chain index (the `show` of TRAPDOOR's `lobby` frame, the `round_id` of KOMBATMP's `round` frame, the `index` of CRASH's `lobby` frame). A show that is not the one open for bets, or one that no longer takes bets, is `409 closed`: TRAPDOOR's once past its lobby's close plus 1,500 ms, inclusive; the open KOMBATMP round once its fight has ended or the round was aborted, and at no time before: `live` runs the bell at `bell_at` plus 251 ms, so a bet that reaches `live` at or before `bell_at` plus 250 ms is pre-fight, and a later one meets the fight (a winner bet at the exchanges revealed as of its arrival; a side bet `409 not_offered`), under the arrival rule; CRASH's once its lobby has closed (`lobby_closes_at`, 5,000 ms after it opened, when `live` runs its first step): a bet that reaches `live` before then is placed before that step, however many others are queued with it (the arrival rule). - **Before the debit**: the session and the `Idempotency-Key`; the offering gates (`409 not_offered`, including brand/environment, kill-switch, and live hourly FX-rate checks); the player's status (`403 player_blocked`); the operator's credits and plan (`402`); the live gate (`403 forbidden`) and the session's operator-asserted jurisdiction against brand blocks and the live allowlist (`403 jurisdiction_not_allowed`); the session's reality-check schedule (`409 reality_check_due` with `elapsed_seconds` and `net_result` when `now >= reality_check.due_at`); the limits; `max_exposure` (`409`); and the show's public state, as a cheap early refusal. The wallet's refusal answers with the wallet's code (`409 insufficient_funds`, `409 limit_exceeded`, `403 player_blocked`); an unknown debit is `503 wallet_unavailable` with nothing placed. - **The show's refusals** are decided by its writer when the bet is placed, after the debit, which a refusal rolls back: `params` not valid for the game (`422 invalid_input`; TRAPDOOR's `door1` and `plan` are read as sent, so `1.0` or `"1"` is refused), the stake outside the limits (`422 stake_out_of_range`), a stake whose `stake + max_profit` does not fit an amount (`422 invalid_input`), a stake whose winnings could pass the maximum profit (`422 max_stake`, with `max_stake` the largest stake it takes: TRAPDOOR's at its first bank, KOMBATMP's at the bet's `pay`, its exact profit `stake · (pay − 1)`, CRASH's at its `auto_cashout`, else at 1.01x), the show no longer taking bets (`409 closed`), and the game's own: TRAPDOOR's and CRASH's second bet by the same player in the show (`409 limit`, a force-closed one included); CRASH's `auto_cashout` outside `1.01` to `1000000.00` with at most 2 decimals (`422 invalid_input`); KOMBATMP's `at` other than the exchanges revealed as of the bet's arrival at `live`, or a `pay` other than the offer there (`409 odds_changed`; the new offer is in the round's `prices` and the bettor's socket `error`), a market not offered at the bet's arrival (`409 not_offered`: a side bet after the bell, a side bet the paytable drops, a side whose quote is outside `1.01.. 1000.00`), and a player's 13th bet in the round, or its 9th at `at` ≥ 1 (`409 limit`). - **KOMBATMP's round pool** (the game specification's `ROUND_FULL`, scoped to the brand): before the debit, the sum of the `reserved_profit` of the brand's bets in the round, in the bet's currency, plus this bet's (`⌊stake · pay / 100⌋ − stake`, from `params.pay`) may not pass 10 × the brand's `max_profit` for that currency (equality is taken); otherwise `409 max_exposure` with `detail` `This round is full for . Try a smaller stake or the next round.` A bet's reservation is released when it settles, is refunded or its placement is voided. The same `reserved_profit` is what the bet holds against the brand's `max_exposure`, which applies as well; when both would refuse, the pool's `detail` is the answer. Both read the caller's brand alone, so no answer tells of another brand's or operator's bets. A client must not parse `detail`: the two differ only in that the next round may take the same bet after a full round, while the brand's exposure cap holds until the brand's other bets settle. - **Placed or pending.** `201` with `status: placed` once the show's journal holds the bet: it then takes part in the show and settles with it. When the placement's outcome is unknown (a timeout, a failover mid-call), `202` with `status: pending`: BetPlug resolves it (a void tombstone), and a repeat of the `Idempotency-Key` answers `202` again until it is resolved, then `201` with `status: placed` if the show took the bet, or `409 closed` if it did not, its debit rolled back. - **After the answer** the bet is the player's on the socket: TRAPDOOR's picks, banks and pre-plan are socket commands, and its settlement is a `settled` frame (`asyncapi.yaml`, `TrapdoorFrame`), then one credit through the outbox. A KOMBATMP bet has no in-round action: it settles when its fight ends, with `paid` and `settled` frames (`KombatmpFrame`), then one credit. A CRASH bet cashes out on its own at its `auto_cashout` or cap, or by the socket's `cashout`, and settles with a `settled` frame (`CrashFrame`); there is no REST cash-out. `bet_id` is the bet's round id: `GET /v1/rounds/{id}`, `round.settled`, the frame's `LiveSettlement.bet_id`, and the wallet's `round_id` and transaction ids (`:0::debit`, `:credit`) all carry it. **Request example** ```json { "show": 1001, "stake": "0.00100000", "params": { "door1": 2, "plan": { "bank_at": 3, "doors": { "2": 1, "3": 4 } } } } ``` **Response example (`201`)** ```json { "bet_id": "bet_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "game": "trapdoor", "show": 1001, "show_round_id": "chain_2026_11-1001", "status": "placed", "currency": "BTC", "stake": "0.00100000", "view": { "show": 1001, "index": 1001, "format": "CLASSIC", "bean": 1, "bet_amt": "0.00100000", "cap_gate": 8, "max_multiplier": "85.50", "reserved_profit": "0.08450000", "door1": 2, "plan": { "bank_at": null, "doors": {} } } } ``` ### `createMemeTradeBuyIn` — `POST /v1/live/meme-trade/buy-ins` - **Summary:** Buy into the open MEME_TRADE round balance - **Tag:** `live` - **Authentication and signing:** `sessionToken` (`Bearer bts_` + `Origin` check) - **Requires `Idempotency-Key`:** yes - **Request body schema:** [`MemeTradeBuyInCreate`](#memetradebuyincreate) - **Parameters:** `Idempotency-Key` (header, required) - **Shared errors:** `400`, `401`, `403`, `404`, `409`, `413`, `415`, `422`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `201` -> [`MemeTradeBuyIn`](#memetradebuyin) (`application/json`) (headers: `Cache-Control`): The buy-in, booked in the player's round balance. - `202` -> [`MemeTradeBuyIn`](#memetradebuyin) (`application/json`) (headers: `Cache-Control`): The buy-in's debit is confirmed and its booking is being reconciled; repeat the key to learn it. - `402` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`): The operator cannot open live rounds: its credits are exhausted (`credits_exhausted`) or its plan has lapsed (`plan_inactive`). Open rounds still finish, and sandbox keeps working. - `503` -> [`Problem`](#problem) (`application/problem+json`) (headers: `Betrail-Request-Id`, `Retry-After`): The operator's wallet did not answer in time (`wallet_unavailable`). One of three cases: the debit's result is unknown, so the round is voided, the debit rolled back and nothing revealed (a repeat of the `Idempotency-Key` gets this answer again); the operator's in-flight wallet calls are at the bulkhead, so nothing was written and `Retry-After` says when to try again; a balance read got no answer, or one that is not bound, so nothing was written. **Contract notes** Funds the session player's round balance in the open MEME_TRADE v2 show round. MEME_TRADE's trades (`open`, `close`, `sidebet`, `auto_sell`) move value inside `round_balances` over the socket; money enters only through this REST call via the operator's seamless wallet, and exits once after the round's rug (outage void) as `:credit` through the outbox. - **The session's game.** The session must be a `real` session bound to `meme-trade` (`403 forbidden`). - **Before the debit**: the session and `Idempotency-Key`; the offering gates (`409 not_offered`, MEME_TRADE settlement rules); the player's status (`403 player_blocked`); the operator's credits and plan (`402`); the live gate (`403 forbidden`) and the session's operator-asserted jurisdiction against brand blocks and the live allowlist (`403 jurisdiction_not_allowed`); the session's reality-check schedule (`409 reality_check_due` with `elapsed_seconds` and `net_result` when `now >= reality_check.due_at`); the brand's stake limits (`422 stake_out_of_range`); currency lock on subsequent buy-ins in the same round (`422 invalid_action`); and that `round` names the open MEME_TRADE show round (`409 closed`). `max_exposure` does not run on a buy-in. - **Placed or pending.** `201` with `status: placed` and the updated round `balance` once `round_balance_entries` holds the `+B` entry. When the handoff's outcome is unknown, `api` retries under the same debit id within its budget, else answers `202` with `status: pending` while `DebitSweep` reconciles against `round_balance_entries` and `show_rounds`; if the round closed or fenced the buy-in without booking it, the attempt is voided and its debit rolled back (`409 closed`). **Request example** ```json { "round": "chain_2026_11:1001", "amount": "0.00100000" } ``` **Response example (`201`)** ```json { "show": 1001, "round": "chain_2026_11:1001", "show_round_id": "chain_2026_11-1001", "status": "placed", "currency": "BTC", "amount": "0.00100000", "balance": "0.00100000" } ``` ### `receiveTopupEvent` — `POST /v1/topup-events/{provider}` - **Summary:** Top-up provider: report a checkout's event - **Tag:** `topup` - **Authentication and signing:** provider-signature (`security: []`, verified before body decode) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`TopupMockEvent`](#topupmockevent) - **Parameters:** `provider` (path, required) - **Shared errors:** `400`, `401`, `404`, `413`, `415`, `429`, `500` — see [Shared HTTP errors & retry matrix](#shared-http-errors--retry-matrix). - **Responses:** - `204` -> no body: The event is recorded, or was already. **Contract notes** The webhook a top-up provider calls. There is one path per provider. It carries no BetPlug credential (`security: []`, enforced to this path): **the provider's own signature** is the credential. - **The order.** The per-address and global limits, the 64 KB body cap and the refusal of a compressed body, then the provider, then the signature, and only then the body. An unsigned caller writes nothing, and is never told more than `401`, or `404` for a provider this deployment lacks. - **The signature.** It is compared in constant time, with a timestamp within 300 s of BetPlug's clock, and both secrets are accepted during a 24 h rotation. For `mock` it is the scheme (`Betrail-Timestamp`, `Betrail-Nonce`, `Betrail-Signature`), keyed with the mock's key, over the target `/v1/topup-events/mock`. A real provider brings its own scheme and its own body schema here. - **The body** is decoded strictly (strict JSON decoding). A repeated key, an unknown field or trailing data is `400`. - **`204` means recorded, never credited.** `api` only records the event. `worker` asks the provider for the checkout's state, and applies that. The event says when to ask, and the provider's answer is what pays. - **A redelivered event id is a `204`** and changes nothing. If it carries different content, it is still a `204`, the first row stands and an alert fires: the row is only a wake-up, and the provider's answer decides, so a retry could not help. - **A signed event naming a top-up BetPlug does not know is `404`,** with an alert and nothing written. A genuine event always finds its row, because the row is written before the checkout exists. - **No `Idempotency-Key`.** A provider sends none. The event id, unique per provider, does that job. - **An unknown provider, or one this deployment has not configured, is `404`.** `mock` exists only where the start-up guard allows it. **Request example** ```json { "id": "mock_5b2e9c7a-1f4d-4e8b-a3c6-9d0e7f1a2b3c:succeeded", "topup_id": "3f1c8f7e-6d2b-4a8e-9c11-0b7a2d4e5f60", "operator_id": "8a7b6c5d-4e3f-4a1b-9c8d-7e6f5a4b3c2d", "checkout_id": "mock_5b2e9c7a-1f4d-4e8b-a3c6-9d0e7f1a2b3c", "status": "succeeded", "amount_micro": 10000000, "currency": "USD" } ``` ## Seamless wallet callbacks BetPlug calls these four endpoints on your brand's wallet base URL (`POST {wallet_base}/balance`, `/debit`, `/credit`, `/rollback`). Every verified call on a live brand must return `Betrail-Timestamp` and `Betrail-Signature` (`betrail-v1-answer`, `ed25519=` or `v1=`), including `4xx` [`WalletRefusal`](#walletrefusal) / [`WalletProtocolRefusal`](#walletprotocolrefusal) responses. ### `walletBalance` — `POST {wallet_base}/balance` - **Summary:** Wallet: read a player's balance - **Tag:** `wallet` - **Authentication and signing:** `walletSignature` (`betrail-v1` request + `betrail-v1-answer` response) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`WalletBalanceRequest`](#walletbalancerequest) - **Parameters:** `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Responses:** - `200` -> [`WalletBalance`](#walletbalance) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The player's balance. - `4XX` -> [`WalletProtocolRefusal`](#walletprotocolrefusal) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The wallet refuses a balance read, a credit or a rollback as malformed: `invalid_request` only. A credit or rollback is never refused for balance, limits or the player's status. BetPlug keeps a refused or unacknowledged credit or rollback retrying, and alerts when it goes `dead`; the money is never dropped. **Contract notes** `POST {base}/balance`, called by BetPlug on the operator's wallet at the brand's configured base URL, through BetPlug's egress guard. Every wallet call is signed with the brand's wallet secret, carries a JSON body, and has a 3 s timeout and a 64 KB answer cap. **Request example** ```json { "player_ref": "p_8f3a2c", "currency": "BTC" } ``` **Response example (`200`)** ```json { "balance": "0.05000000", "currency": "BTC", "status": "active" } ``` ### `walletDebit` — `POST {wallet_base}/debit` - **Summary:** Wallet: take a stake - **Tag:** `wallet` - **Authentication and signing:** `walletSignature` (`betrail-v1` request + `betrail-v1-answer` response) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`WalletDebitRequest`](#walletdebitrequest) - **Parameters:** `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Responses:** - `200` -> [`WalletAnswer`](#walletanswer) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The debit is booked. - `4XX` -> [`WalletRefusal`](#walletrefusal) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The wallet refuses the debit, and booked nothing. **Only a 4xx whose body is this `WalletRefusal`**, with a `code` from its enum and the echoed `transaction_id`, and, for a `btr_live_` brand, a valid answer signature (`walletSignature`, line 2 being this 4xx), is a refusal. BetPlug then voids the round without a rollback and passes the code to the client. Every other answer is **unknown**, and BetPlug rolls the debit back: a 4xx without this body, an unsigned or badly signed live refusal, a 5xx, a timeout, an unreadable or oversized body. **Contract notes** `POST {base}/debit`. BetPlug calls it once per debit attempt, and never retries an unknown one. - **A success** is a 200 whose `WalletAnswer` echoes `transaction_id`, `amount` and `currency`, carries its own `operator_transaction_id`, and, for a `btr_live_` brand, carries a valid answer signature (`walletSignature`). Any other success counts as unknown. - **A refusal** is a 4xx whose body is a `WalletRefusal`, with a `code` from its enum and the echoed `transaction_id`. For a `btr_live_` brand, it also carries a valid answer signature, whose line 2 is the refusal's own status. Only then does BetPlug void the round without a rollback, since nothing was booked. An unsigned live refusal is unknown and rolled back, which is harmless: the rollback leaves a tombstone. - **Anything else is unknown**, and BetPlug rolls the debit back. That includes a 4xx without that body (a gateway's 408, 413 or 429 page), a 5xx, a timeout, and an unreadable or oversized answer. - **An answer holds exactly its schema's fields.** BetPlug decodes every wallet answer strictly: a field the schema does not list, a repeated field, or a name that differs in case makes the answer unknown. So a debit is rolled back, and a credit or a rollback retries until it goes `dead`. The wallet tester reports it, so it shows before go-live. - **`transaction_id` is the only key to rely on.** On a MEME_TRADE show, several players, and one player's several buy-ins, share a `round_id`. - The same `transaction_id` must get the first answer again, signed afresh for the call it answers (`walletSignature`). - A debit whose id was already rolled back (a tombstone) is refused with `invalid_request`. **Request example** ```json { "transaction_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:0:1:debit", "round_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "player_ref": "p_8f3a2c", "currency": "BTC", "amount": "0.00100000", "game": "dice", "brand": "br_casino_main" } ``` **Response example (`200`)** ```json { "transaction_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:0:1:debit", "amount": "0.00100000", "currency": "BTC", "operator_transaction_id": "op-tx-99812", "balance": "0.04900000" } ``` ### `walletCredit` — `POST {wallet_base}/credit` - **Summary:** Wallet: pay a round - **Tag:** `wallet` - **Authentication and signing:** `walletSignature` (`betrail-v1` request + `betrail-v1-answer` response) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`WalletCreditRequest`](#walletcreditrequest) - **Parameters:** `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Responses:** - `200` -> [`WalletAnswer`](#walletanswer) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The credit is booked. - `4XX` -> [`WalletProtocolRefusal`](#walletprotocolrefusal) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The wallet refuses a balance read, a credit or a rollback as malformed: `invalid_request` only. A credit or rollback is never refused for balance, limits or the player's status. BetPlug keeps a refused or unacknowledged credit or rollback retrying, and alerts when it goes `dead`; the money is never dropped. **Contract notes** `POST {base}/credit`. Every settled round sends exactly one credit, 0 included, so the operator's round closes. A credit is **never refused for balance, limits or the player's status**, whatever rollbacks of the round are still pending: a player blocked or self-excluded mid-round is still paid. Only a protocol error refuses one (`invalid_request`). - **`transaction_id` is the only key to rely on.** On a MEME_TRADE show each player has a credit of their own, under the same `round_id`, so a wallet that keys credits on `round_id` leaves the second player unpaid. - **Acknowledged** means a 200 whose `WalletAnswer` echoes `transaction_id`, `amount` and `currency`, with its own `operator_transaction_id` and, for a `btr_live_` brand, a valid answer signature. A retry's answer is the first one, signed afresh for the retry (`walletSignature`). - **Anything else** (a refusal, a success without the echo, a 5xx, a timeout) is not an acknowledgement. BetPlug keeps the credit retrying from its outbox with backoff. After the retry schedule (24 h) it goes `dead` and raises an alert for a human. The money is never dropped. **Request example** ```json { "transaction_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:credit", "round_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "player_ref": "p_8f3a2c", "currency": "BTC", "amount": "0.00197999", "kind": "payout", "game": "dice", "brand": "br_casino_main" } ``` **Response example (`200`)** ```json { "transaction_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:0:1:debit", "amount": "0.00100000", "currency": "BTC", "operator_transaction_id": "op-tx-99812", "balance": "0.04900000" } ``` ### `walletRollback` — `POST {wallet_base}/rollback` - **Summary:** Wallet: undo a debit - **Tag:** `wallet` - **Authentication and signing:** `walletSignature` (`betrail-v1` request + `betrail-v1-answer` response) - **Requires `Idempotency-Key`:** no - **Request body schema:** [`WalletRollbackRequest`](#walletrollbackrequest) - **Parameters:** `Betrail-Timestamp` (header, required), `Betrail-Nonce` (header, required) - **Responses:** - `200` -> [`WalletAnswer`](#walletanswer) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The rollback is booked, or remembered as a tombstone. - `4XX` -> [`WalletProtocolRefusal`](#walletprotocolrefusal) (`application/json`) (headers: `Betrail-Timestamp`, `Betrail-Signature`): The wallet refuses a balance read, a credit or a rollback as malformed: `invalid_request` only. A credit or rollback is never refused for balance, limits or the player's status. BetPlug keeps a refused or unacknowledged credit or rollback retrying, and alerts when it goes `dead`; the money is never dropped. **Contract notes** `POST {base}/rollback`. It undoes one debit attempt (`rollback_of`). If the wallet never saw that debit, it succeeds as a no-op and remembers the id, so a late debit with it is refused. Such a tombstone's answer carries the tombstone's own `operator_transaction_id` and the player's current `balance`. After a booked debit, it returns the money once. Only a protocol error refuses a rollback (`invalid_request`). Acknowledgement and retries are as for a credit: a 200 with the echo acknowledges it, and anything else keeps it retrying until the outbox gives up and alerts. **Request example** ```json { "transaction_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:0:1:debit:rollback", "rollback_of": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:0:1:debit", "round_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA", "player_ref": "p_8f3a2c", "currency": "BTC", "amount": "0.00100000" } ``` **Response example (`200`)** ```json { "transaction_id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA:0:1:debit", "amount": "0.00100000", "currency": "BTC", "operator_transaction_id": "op-tx-99812", "balance": "0.04900000" } ``` ## AsyncAPI channels, operations, and messages ### `sendLiveFrame` (`send` on `/v1/live/{game}`) - **Summary:** The show's frames to the player's socket (snapshot, round, step, result, paid, error). **Contract notes** Every frame carries a per-socket sequence number; a client that sees a gap asks for a snapshot. A frame never carries another player's identity or a seed before the round closes. ### `receiveLiveCommand` (`receive` on `/v1/live/{game}`) - **Summary:** A player's command (a fresh snapshot, or an in-round command), answered by an ack frame with the same request id. **Contract notes** Commands are rate-limited per connection. Money goes in over REST, so an in-round command (a pick, a bank, a cash-out, a STACKOPASS open or pass) moves no money in; its credits go out through the outbox. The exception is MEME_TRADE's trades, which move value inside the round balance: they commit before the next tick or are voided and refunded (the tick barrier). ### `sendWebhook` (`send` on `{operator_webhook_url}`) - **Summary:** One event, POSTed to the operator's endpoint (round.settled, credits.low, credits.exhausted). **Contract notes** Delivered at least once from the transactional outbox, retried with backoff, and logged in the console where it can be replayed. Any 2xx answer acknowledges it. The endpoint passes the SSRF guard of on every delivery. ### AsyncAPI message payloads - **`LiveFrame`** (`Live frame`, schema [`LiveFrame`](#liveframe)): A frame from the show to a player. - **`LiveSettled`** (`Live bet settled`, schema [`LiveSettledFrame`](#livesettledframe)): The frame that tells a player their bet settled, by play, a force-close or an outage. - **`StackOPassFrame`** (`STACKOPASS live frame`, schema [`StackOPassFrame`](#stackopassframe)): A frame from a STACKOPASS table to a player, its hand's settlement included. - **`StackOPassCommand`** (`STACKOPASS live command`, schema [`StackOPassCommand`](#stackopasscommand)): A STACKOPASS player's socket command (snapshot, watch, open, pass, cashout, leave). - **`MemeTradeFrame`** (`MEME_TRADE live frame`, schema [`MemeTradeFrame`](#memetradeframe)): A frame from the MEME_TRADE v2 show to a player, including skipped_link. - **`LiveCommand`** (`Live command`, schema [`LiveCommand`](#livecommand)): A command from a player to the show. - **`KombatmpFrame`** (`KOMBATMP live frame`, schema [`KombatmpFrame`](#kombatmpframe)): A frame from a KOMBATMP round to a player, its settlement included. - **`KombatmpCommand`** (`KOMBATMP live command`, schema [`KombatmpCommand`](#kombatmpcommand)): A KOMBATMP player's socket command (snapshot only; bets go in over REST). - **`TrapdoorFrame`** (`TRAPDOOR live frame`, schema [`TrapdoorFrame`](#trapdoorframe)): A frame from a TRAPDOOR show to a player, its settlement included. - **`TrapdoorCommand`** (`TRAPDOOR live command`, schema [`TrapdoorCommand`](#trapdoorcommand)): A TRAPDOOR player's socket command (snapshot, pick, bank, plan). - **`CrashFrame`** (`CRASH live frame`, schema [`CrashFrame`](#crashframe)): A frame from a CRASH show to a player, its settlement included. - **`CrashCommand`** (`CRASH live command`, schema [`CrashCommand`](#crashcommand)): A CRASH player's socket command (snapshot, cashout). - **`WebhookEvent`** (`Webhook event`, schema [`WebhookEvent`](#webhookevent)): One event delivered to an operator. - **`RoundSettled`** (`round.settled`, schema [`RoundSettledEvent`](#roundsettledevent)): A round settled, in either integration mode (live games included; a MEME_TRADE player-round). - **`CreditsLow`** (`credits.low`, schema [`CreditsLowEvent`](#creditslowevent)): The operator's credits fell below its threshold. - **`CreditsExhausted`** (`credits.exhausted`, schema [`CreditsExhaustedEvent`](#creditsexhaustedevent)): The operator's credits reached 0 or less, so new live rounds are refused. ## OpenAPI component schemas All object schemas enforce strict JSON decoding (`additionalProperties: false`). Compact field reference below; extended prose notes are in `/docs/api-reference.md` and `/api/openapi.yaml`. ### `Amount` Type: `string` — pattern `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$`; len 0..48 — An amount in the currency's units, as a decimal string, with no sign, no exponent and no leading zero other than `0.`. ### `Multiplier` Type: `string` — pattern `^(0|[1-9][0-9]{0,15})(\.[0-9]{1,18})?$`; len 0..36 — An exact multiplier as a decimal string, at the scale the game computes in (`"1.90"`, DICE's `"1.97999"`). ### `CurrencyCode` Type: `string` — pattern `^[A-Z0-9]{2,12}$` — A currency enabled on the brand (`BTC`, `USDT`, `EUR`, `1INCH`). ### `JurisdictionCode` Type: `string` — pattern `^[A-Z]{2}$` — An optional operator-asserted uppercase ISO 3166-1 alpha-2 country code (`MT`, `CA`). ### `PlayerRef` Type: `string` — pattern `^[A-Za-z0-9_.:-]{1,64}$` — The operator's pseudonymous player id, scoped to the operator. ### `GameSlug` Type: `string` — pattern `^[a-z][a-z0-9]*(-[a-z0-9]+)*$`; len 2..32 — The game's slug (`dice`, `packs`, `wheel`, `grimoire-of-gains`, `limbo`, `chicken`). ### `LiveGameSlug` Type: `string` — enum: `trapdoor`, `kombat-multiplayer`, `stack-o-pass`, `crash`, `meme-trade` — A live game's slug: TRAPDOOR, KOMBATMP, STACKOPASS, CRASH and MEME_TRADE. ### `BrandId` Type: `string` — pattern `^[A-Za-z0-9_-]{1,64}$` — The brand's id, from the console. ### `RoundId` Type: `string` — pattern `^[A-Za-z0-9_-]{1,64}$` — A round's id. ### `SessionRoundId` Type: `string` — pattern `^([A-Za-z0-9_-]{1,64}|sb-[A-Za-z0-9_-]{1,43}:[1-9][0-9]{0,19}-[1-9][0-9]*)$`; len 1..64 — A round's `rnd_` id, or, in a MEME_TRADE session, a show round's id (`-`) for the player's trade record or a... ### `ClientSeed` Type: `string` — pattern `^[^\u0000-\u001F\u007F-\u009F]+$`; len 1..64 — A client seed: **3 to 64 bytes of valid UTF-8**, with no control character (C0, DEL, C1) and no unpaired surrogate. ### `DiceParams` Type: `object` — DICE's params. - `direction` (`string`, req): enum: `under`, `over`; Under wins on a roll below W; over wins on a roll above 9999 − W. - `chance` (`string`, req): pattern `^(0|[1-9][0-9]?)\.[0-9]{2}$`; The win chance in percent with exactly 2 decimals, 0.01 to 94.05. - `payout` (`Multiplier`) ### `PacksParams` Type: `object` — PACKS's params (the game specification): **none**. ### `PacksCard` Type: `object` — One card of a PACKS deal, with its number in the table, its tier and its multiplier. - `id` (`integer`, req): range 1..242; The card's number, 1 (the rarest) to 242. - `tier` (`string`, req): enum: `COMMON`, `UNCOMMON`, `RARE`, `SUPER_RARE`, `EPIC`, `LEGENDARY`; The card's rarity tier. - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]{0,3})\.[0-9]{2}$`; The card's multiplier, with exactly 2 decimals (`0.01` to `1000.00`). ### `PacksView` Type: `object` — The `view` of a settled PACKS round (`Round.view`; the game specification). - `version` (`integer`, req): const `1`; The card table's version. - `cards` (`array`, req): items 5..5; The five cards, in the order they were dealt. - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]{0,3})\.[0-9]{2}$`; The pack's multiplier, the sum of the five cards', with exactly 2 decimals. - `win` (`boolean`, req): The multiplier is above `1.00`. - `push` (`boolean`, req): The multiplier is exactly `1.00`. - `payout` (`Amount`, req): What the round paid, as the round's `payout`. - `profit` (`SignedAmount`, req): `payout − stake`. - `capped` (`boolean`, req): The profit was cut to `max_profit` at settlement. - `game_result` (`object`, req): The source's `bets.game_result` (`PacksEngine::gameResult`). ### `WheelParams` Type: `object` — WHEEL's params (the game specification). - `risk` (`string`, req): enum: `LOW`, `MEDIUM`, `HIGH`; The risk, which picks the wheel with `segments`. - `segments` (`integer | string`, req): The number of equal segments, as a plain JSON integer or its digit string. ### `WheelView` Type: `object` — The `view` of a settled WHEEL round (`Round.view`; the game specification). - `risk` (`string`, req): enum: `LOW`, `MEDIUM`, `HIGH` - `segments` (`integer`, req): enum: `10`, `20`, `30`, `40`, `50`; The wheel's size, always a JSON integer here. - `table_version` (`integer`, req): const `1` - `segment_index` (`integer`, req): range 0..49; The segment the pointer stopped on, 0 to `segments − 1`. - `u` (`integer`, req): range 0..4294967295; The draw, the stream's first word as an unsigned 32-bit integer. - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]?)\.[0-9]{2}$`; The segment's multiplier, with exactly 2 decimals (`0.00` to `47.50`). - `win` (`boolean`, req): The multiplier is above `1.00`. - `push` (`boolean`, req): Always false on table version 1. - `payout` (`Amount`, req): What the round paid, as the round's `payout`. - `profit` (`SignedAmount`, req): `payout − stake`. - `capped` (`boolean`, req): The profit was cut to `max_profit` at settlement. - `game_result` (`object`, req): The source's `bets.game_result` (`WheelEngine::gameResult`). ### `DrillParams` Type: `object` — DRILL's params. - `target` (`string`, req): pattern `^(1\.(0[1-9]|[1-9][0-9]?)|([2-9]|[1-9][0-9]{1,5})(\.[0-9]{1,2})?|1000000(\.0{1,2})?)$`; The target multiplier, `1.01` to `1000000.00`, at most 2 decimals. - `pick` (`integer | string`, req): The drill, as a plain JSON integer or its digit string. ### `DrillView` Type: `object` — The `view` of a settled DRILL round (`Round.view`; the game specification). - `target` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; The target, with exactly 2 decimals. - `pick` (`integer`, req): range 0..2 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; `target` on a win, `0.00` on a loss. - `depths` (`array`, req): items 3..3; Each drill's depth, as a multiplier with exactly 2 decimals. - `words` (`array`, req): items 3..3; The stream words each depth was drawn from, as unsigned 32-bit integers. - `win` (`boolean`, req) - `payout` (`Amount`, req): What the round paid, as the round's `payout`. - `profit` (`SignedAmount`, req): `payout − stake`. - `capped` (`boolean`, req): The profit was cut to `max_profit` at settlement. - `game_result` (`object`, req): The source's `bets.game_result` (`DrillEngine::gameResult`). ### `CasesParams` Type: `object` — CASES's params. - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` ### `CasesView` Type: `object` — The `view` of a settled CASES round (`Round.view`; the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `table_version` (`integer`, req): const `1` - `bucket` (`integer`, req): range 0..+inf; The bucket drawn, an index into the difficulty's table. - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `tier` (`string`, req): enum: `grey`, `light-blue`, `blue`, `green`, `red`, `purple`, `gold` - `word` (`integer`, req): range 0..4294967295 - `strip` (`array`, req): items 49..49 - `strip_floats_used` (`integer`, req): range 0..+inf - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) ### `TarotParams` Type: `object` — TAROT's params. - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` ### `TarotCard` Type: `object` — One of TAROT's three cards, its entry in the card's table, the face shown and its multiplier. - `index` (`integer`, req): range 0..+inf - `face` (`integer`, req): range 0..+inf - `mult` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` ### `TarotView` Type: `object` — The `view` of a settled TAROT round (`Round.view`; the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `table_version` (`integer`, req): const `1` - `words` (`array`, req): items 3..3 - `m` (`TarotCard`, req) - `l` (`TarotCard`, req) - `r` (`TarotCard`, req) - `ended_at` (`string | null`, req): enum: `m`, `l`, `r`, `null` - `payout_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) ### `SlideParams` Type: `object` — SLIDE's params. - `target` (`string`, req): pattern `^(1\.(0[1-9]|[1-9][0-9]?)|([2-9]|[1-9][0-9]{1,5})(\.[0-9]{1,2})?|1000000(\.0{1,2})?)$`; The target multiplier, `1.01` to `1000000.00`, at most 2 decimals. ### `SlideView` Type: `object` — The `view` of a settled SLIDE round (`Round.view`; the game specification). - `target` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `stop` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `float` (`string`, req): pattern `^0(\.[0-9]+)?$`; The draw, `word / 2^32`, as an exact decimal string. - `word` (`integer`, req): range 0..4294967295 - `strip` (`array`, req): items 39..39 - `strip_before` (`integer`, req): const `32` - `strip_floats_used` (`integer`, req): range 0..+inf - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`object`, req): The source's `bets.game_result` (`SlideEngine::gameResult`). ### `BarsView` Type: `object` — The `view` of a settled BARS round (`Round.view`; the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `table_version` (`integer`, req): const `1` - `picks` (`array`, req): items 1..5 - `bars` (`array`, req): items 30..30 - `words` (`array`, req): items 30..30 - `sum` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `payout_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `profit_capped` (`boolean`, req): The profit was cut to `max_profit` at settlement. ### `DartsParams` Type: `object` — DARTS's params. - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` ### `DartsView` Type: `object` — The `view` of a settled DARTS round (`Round.view`; the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `table_version` (`integer`, req): const `1` - `zone` (`string`, req): enum: `bull`, `inner`, `wedge`, `outer` - `wedge` (`integer | null`, req): range 0..+inf; The wedge hit, or `null` outside the wedges. - `level` (`integer | null`, req): range 0..+inf; The wedge's level, or `null` outside the wedges. - `tier` (`string`, req): enum: `gold`, `purple`, `red`, `orange`, `amber`, `green`, `blue`, `light-blue`, `grey` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `u0` (`integer`, req): range 0..4294967295 - `u1` (`integer`, req): range 0..4294967295 - `angle_deg` (`string`, req): pattern `^(0|[1-9][0-9]{0,2})\.[0-9]{10}$` - `radius_ratio` (`string`, req): pattern `^[01]\.[0-9]{10}$` - `angle_float` (`integer`, req): range 0..+inf - `rejected` (`array`, req) - `win` (`boolean`, req) - `push` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`object`, req): The source's `bets.game_result` (`DartsEngine::gameResult`). ### `KaboomParams` Type: `object` — KABOOM's params. - `charge` (`string`, req): enum: `POP`, `BANG`, `KABOOM` - `spot` (`integer | string | null`): The cell, a plain JSON integer or its digit string, or `null` for the default 27. ### `KaboomCell` Type: `object` — One revealed cell of a KABOOM round, in reveal order. - `pos` (`integer`, req): range 0..47 - `by` (`integer | null`, req): range 0..47; The cell whose blast revealed this one, or `null` for the charge's own reveals. - `u` (`integer`, req): range 0..4294967295 - `entry` (`integer`, req): range 0..+inf - `kind` (`string`, req) - `cents` (`integer`, req): range 0..+inf - `claims` (`array`) - `total` (`integer`, req): range 0..+inf; The running total, in hundredths of the stake. ### `KaboomRound` Type: `object` — A KABOOM round's record (the round record, the game specification); `game_result` is this object as JSON text. - `version` (`integer`, req): const `1` - `table_version` (`integer`, req): const `1` - `charge` (`string`, req): enum: `POP`, `BANG`, `KABOOM` - `spot` (`integer`, req): range 0..47 - `cells` (`array`, req) - `revealed` (`integer`, req): range 0..+inf - `tnt` (`integer`, req): range 0..+inf - `lode` (`boolean`, req) - `lode_at` (`integer | null`, req): range 0..47 - `spent_lodes` (`integer`, req): range 0..+inf - `gem_cents` (`integer`, req): range 0..+inf - `total_cents` (`integer`, req): range 0..+inf - `max_win_cents` (`integer`, req): range 0..+inf - `capped` (`boolean`, req) - `cents` (`integer`, req): range 0..+inf - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `floats_used` (`integer`, req): range 0..+inf ### `KaboomView` Type: `object` — The `view` of a settled KABOOM round (`Round.view`; the game specification). - `charge` (`string`, req): enum: `POP`, `BANG`, `KABOOM` - `spot` (`integer`, req): range 0..47 - `table_version` (`integer`, req): const `1` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `max_win` (`boolean`, req) - `max_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `round` (`KaboomRound`, req) - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `profit_capped` (`boolean`, req) - `game_result` (`string`, req): The source's `bets.game_result`, `round` as JSON text. ### `TiltParams` Type: `object` — TILT's params. - `notch` (`string`, req): enum: `SOFT`, `FIRM`, `FULL`, `MAX` ### `TiltBall` Type: `object` — One ball of a TILT round. - `ball` (`integer`, req): range 0..+inf - `lane` (`integer`, req): range 0..+inf - `hits` (`array`, req) - `points` (`array`, req) - `score` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `lock` (`boolean`) - `ramp` (`integer`, req): range 0..+inf - `ramp_factor` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `hole` (`integer`, req): range 0..+inf - `hole_factor` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `payout` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `draws` (`array`, req): items 2..2 ### `TiltRound` Type: `object` — A TILT round's record (the round record, the game specification); `game_result` is this object as JSON text. - `v` (`integer`, req): const `1` - `notch` (`string`, req): enum: `SOFT`, `FIRM`, `FULL`, `MAX` - `table_version` (`integer`, req): const `2` - `balls` (`array`, req): items 1..inf - `multiball` (`boolean`, req) - `total` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `capped` (`boolean`, req) - `cap` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `u` (`array`, req) - `payout_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` ### `TiltView` Type: `object` — The `view` of a settled TILT round (`Round.view`; the game specification). - `notch` (`string`, req): enum: `SOFT`, `FIRM`, `FULL`, `MAX` - `table_version` (`integer`, req): const `2` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `capped` (`boolean`, req): The multiplier was cut to `max_multiplier`. - `max_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `round` (`TiltRound`, req) - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `profit_capped` (`boolean`, req) - `game_result` (`string`, req): The source's `bets.game_result`, `round` as JSON text. ### `SlotParams` Type: `object` — The params of the slots GRIMOIRE (`grimoire-of-gains`), PHARAOH (`pharaoh-pump`) and SHOGUN (`shogun-shiba`) (the game... ### `SlotView` Type: `object` — The `view` of a settled GRIMOIRE, PHARAOH or SHOGUN round (`Round.view`; `the specification` and each game's). - `version` (`integer`, req): const `1` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `win` (`boolean`, req) - `max_win` (`boolean`, req): The spin reached the theme's maximum win. - `profit_capped` (`boolean`, req): The profit was cut to `max_profit` at settlement. - `capped` (`boolean`, req): The multiplier was cut to the theme's maximum win. - `free_spins_played` (`integer`, req): range 0..+inf - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `round` (`object`, req): The spin's record (`fp-originals-slot/1`, full form): the base spin and its free spins (`SlotSpin`,... - `game_result` (`string`, req): The source's `bets.game_result`, `round` as JSON text, or its compact form (PHARAOH's minimal form)... ### `SlotSpin` Type: `object` — One spin of a slot round's record (`SlotView.round.spins`, the full form). - `mode` (`string`, req): enum: `base`, `free` - `floats` (`SlotFloats`, req) - `rejected` (`SlotPositions`, req) - `stops` (`array`, req): items 1..inf - `grid` (`string`, req): pattern `^[A-Za-z0-9]+(\|[A-Za-z0-9]+)*$` - `steps` (`array`, req) - `meter` (`array`): items 2..2; PHARAOH's cascade meter before and after the spin. - `expanding` (`object`): GRIMOIRE's expanding spell on a free spin. - `random_wilds` (`object`): PHARAOH's and SHOGUN's random wilds draw; `pattern` is the drawn pattern, or `null` when not... - `scatters` (`integer`, req): range 0..+inf - `multiplier` (`integer`, req): range 0..+inf - `win_cents` (`integer`, req): range 0..+inf - `scatter_cents` (`integer`, req): range 0..+inf - `cents` (`integer`, req): range 0..+inf - `awarded` (`integer`): range 1..+inf; The free spins this spin won. - `hold` (`object`): SHOGUN's hold-and-spin: the coins it started with (`[cell, cents]`), what each respin landed,... ### `SlotStep` Type: `object` — One evaluation step of a slot spin (`SlotSpin.steps`); PHARAOH's cascade steps add `removed` and `grid_after`. - `wins` (`array>`, req) - `meter` (`integer`, req): range 0..+inf - `cents` (`integer`, req): range 0..+inf - `removed` (`array`) - `grid_after` (`string`): pattern `^[A-Za-z0-9]+(\|[A-Za-z0-9]+)*$` ### `SlotFreeSpins` Type: `object` — The free spins a slot round won (`SlotView.round.free_spins`): how many were awarded, played and retriggered, their multiplier,... - `awarded` (`integer`, req): range 0..+inf - `played` (`integer`, req): range 0..+inf - `retriggers` (`integer`, req): range 0..+inf - `multiplier` (`integer`, req): range 0..+inf - `spell` (`string | null`, req): len 1..inf - `spell_floats` (`SlotFloats`) - `spell_rejected` (`SlotPositions`) ### `SlotFloats` Type: `array` — items 2..2 — A slot draw's first stream position and how many floats it read. ### `SlotPositions` Type: `array` — The stream positions a slot draw refused and drew again. ### `SlotCoin` Type: `array` — items 2..2 — A hold-and-spin coin, `[cell, cents]`. ### `FlipParams` Type: `object` — FLIP's opening params. - `call` (`string`, req): enum: `HEADS`, `TAILS` - `flips` (`integer`): range 0..20 - `pattern` (`string`): enum: `FIXED`, `ALTERNATE` ### `FlipAction` Type: `object | object` — One move on an open manual FLIP round: `flip` the next coin on `call` (`HEADS` or `TAILS`), or `cashout` at the current... - `oneOf[0]`: - `do` (`string`, req): const `"flip"` - `call` (`string`, req): enum: `HEADS`, `TAILS` - `oneOf[1]`: - `do` (`string`, req): const `"cashout"` ### `FlipView` Type: `object` — The `view` of a settled FLIP round (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED` - `mode` (`string`, req): enum: `manual`, `auto` - `flips` (`integer`, req): range 0..20; Number of correct flips won before settlement. - `max_flips` (`integer`, req): const `20` - `calls` (`array`, req): items 1..20 - `results` (`array`, req): items 1..20 - `floats_used` (`integer`, req): range 1..20 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*\.[0-9]{2})$`; Ladder multiplier on `CASHED_OUT` (`1.90` to `996147.20`), or `"0"` on `BUSTED`. - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `cashed_at` (`integer | null`, req): range 1..20; Winning flip count on `CASHED_OUT`, or `null` on `BUSTED`. - `auto_cashout` (`string | null`, req): enum: `TOP`, `MAX_PROFIT`, `null` - `max_profit_hit` (`boolean`, req) - `pattern` (`string`): enum: `FIXED`, `ALTERNATE`; Auto-mode call pattern (present only when `mode` is `auto`). - `target` (`integer`): range 1..20; Auto-mode target flip count (present only when `mode` is `auto`). - `ended_by` (`string`): const `"FORCE_CLOSED"`; Present on a platform Rule 1 force-close. - `rule` (`integer`): const `1`; Force-close rule applied (`1` on Rule 1 cash-out). - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$`; Exact Bellman continuation value as a reduced rational `num/den` on force-close. - `v_star_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$`; Exact gap `V* − F` as a reduced rational `num/den` on force-close. - `game_result` (`object | object`, req): The source's `bets.game_result` (`v: 1`), manual or auto shape. ### `SnakesParams` Type: `object` — SNAKES's opening params. - `difficulty` (`string`, req): pattern `^ *([Ee][Aa][Ss][Yy]|[Mm][Ee][Dd][Ii][Uu][Mm]|[Hh][Aa][Rr][Dd]|[Ee][Xx][Pp][Ee][Rr][Tt]|[Mm][Aa][Ss][Tt][Ee][Rr]) *$` ### `SnakesAction` Type: `object | object` — One move on an open SNAKES round: `roll` the two dice, or `cashout` at the current multiplier (refused before the first roll). - `oneOf[0]`: - `do` (`string`, req): const `"roll"` - `oneOf[1]`: - `do` (`string`, req): const `"cashout"` ### `SnakesRoll` Type: `object` — One dice roll in a SNAKES round (`SnakesView.rolls`; the game specification). - `round` (`integer`, req): range 1..5 - `dice1` (`integer`, req): range 1..6 - `dice2` (`integer`, req): range 1..6 - `sum` (`integer`, req): range 2..12 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; Square multiplier for `sum` on this roll (`0.00` on a snake). ### `SnakesGameResult` Type: `object` — The source's `bets.game_result` for a played SNAKES round. - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT`, `MASTER` - `rolls` (`array`, req): items 1..5 - `multiplier` (`string`, req): pattern `^(0|(0|[1-9][0-9]*)\.[0-9]{2,10})$` ### `SnakesView` Type: `object` — The `view` of a settled SNAKES round (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `REFUNDED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT`, `MASTER` - `nonce` (`integer`, req): range 0..+inf - `round` (`integer`): range 1..5; Latest roll index when settled directly by a roll (`BUSTED` or roll 5 auto-cashout). - `dice1` (`integer`): range 1..6 - `dice2` (`integer`): range 1..6 - `sum` (`integer`): range 2..12 - `multiplier` (`string`): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; Latest roll's square multiplier when settled directly by a roll. - `current_round` (`integer`, req): range 0..5 - `current_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2,10}$`; Running multiplier (`0.00` on `BUSTED`, `1.00` on `REFUNDED`, else exact product trimmed to 2..10... - `rolls` (`array`, req): items 0..5 - `final_multiplier` (`string`): pattern `^(0|(0|[1-9][0-9]*)\.[0-9]{2,10})$`; `0` on `BUSTED`, or the exact running multiplier on `CASHED_OUT` (omitted on `REFUNDED`). - `win` (`boolean`) - `profit` (`SignedAmount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`): Full stake refunded on a Rule 2 force-close (`REFUNDED`). - `auto_cashout` (`boolean`): True on 5th-roll automatic cash-out, false on manual cash-out or bust, omitted on force-close. - `max_profit_hit` (`boolean`) - `floats_used` (`integer`, req): enum: `0`, `2`, `10`, `18`, `26`, `34` - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): enum: `1`, `2` - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `v_star_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `game_result` (`SnakesGameResult | null`, req): The source's `bets.game_result`, or `null` on `REFUNDED`. ### `DeadshotParams` Type: `object` — DEADSHOT's opening params. - `herd` (`string`, req): pattern `^[\t\n\r\x00\x0b ]*([Ll][Oo][Ww]|[Mm][Ee][Dd][Ii][Uu][Mm]|[Hh][Ii][Gg][Hh])[\t\n\r\x00\x0b ]*$` - `bullets` (`integer | string`, req): The magazine's size, a plain JSON integer or its digit string. ### `DeadshotAction` Type: `object | object` — One move on an open DEADSHOT round: `fire` `count` bullets (1 to 10, a plain JSON integer or its digit string; absent or `null`,... - `oneOf[0]`: - `do` (`string`, req): const `"fire"` - `count` (`integer | string | null`) - `aim` (`string | null`): pattern `^[wrbtm]{1,10}$` - `oneOf[1]`: - `do` (`string`, req): const `"stop"` ### `DeadshotShot` Type: `object` — One resolved bullet in a DEADSHOT magazine (`DeadshotView.shots` and `new_shots`; the game specification). - `i` (`integer`, req): range 0..99 - `type` (`string`, req): enum: `walker`, `runner`, `brute`, `tank`, `mega` - `tag` (`string`, req): pattern `^[1-9][0-9]*\.[0-9]{2}$`; Target zombie's tag multiplier with 2 decimals. - `aimed` (`boolean`, req) - `kill` (`boolean`, req) - `return` (`Amount`, req): Bullet return (`0` on a miss, `⌊bullet × tag⌋` on a kill). ### `DeadshotView` Type: `object` — The `view` of a settled DEADSHOT round (`Round.view`; the game specification). - `status` (`string`, req): enum: `FINISHED`, `STOPPED`, `REFUNDED` - `herd` (`string`, req): enum: `LOW`, `MEDIUM`, `HIGH` - `bet_amt` (`Amount`, req) - `bullet` (`Amount`, req) - `bullets` (`integer`, req): range 1..100 - `fired` (`integer`, req): range 0..100 - `remaining` (`integer`, req): range 0..100 - `kills` (`integer`, req): range 0..100 - `total_return` (`Amount`, req) - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; `⌊100 × total_return / bet_amt⌋ / 100`, with 2 decimals. - `shots` (`array`, req): items 0..100 - `new_shots` (`array`, req): items 0..10 - `fired_stake` (`Amount`, req) - `refund` (`Amount`, req) - `credit` (`Amount`, req): `total_return + refund`, matching the round's `payout`. - `payout` (`string | null`, req): pattern `^(1|(0|[1-9][0-9]*)\.[0-9]{2,20})$`; Fired-stake payout ratio (`ceil(total_return / fired_stake)` at 2..20 decimals), `"1"` on Rule 2... - `profit` (`SignedAmount`, req) - `result` (`string`, req): enum: `win`, `push`, `loss` - `win` (`boolean | null`, req) - `floats_used` (`integer`, req): range 0..200 - `acceptable_payout` (`boolean | null`, req) - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): enum: `1`, `2` - `f_value` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `delta` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `game_result` (`string | null`, req): pattern `^\{"v":[23],"herd":"(LOW|MEDIUM|HIGH)",.*\}$`; The source's compact `bets.game_result` JSON text (`v: 2` drawn, `v: 3` aimed), or `null` when... ### `VideopokerParams` Type: `object` — VIDEOPOKER's opening params: **none**. ### `VideopokerAction` Type: `object` — The one move on an open VIDEOPOKER round: `draw`, with `holds` exactly five JSON booleans, one per dealt card in order, `true` to... - `do` (`string`, req): const `"draw"` - `holds` (`array`, req): items 5..5; Which dealt cards to keep, in the order they were dealt. ### `StackpacksParams` Type: `object` — STACKPACKS's opening params. - `risk` (`integer`, req): enum: `9`, `5`, `3` ### `StackpacksAction` Type: `object | object` — One move on an open STACKPACKS round. - `oneOf[0]` (Open the next pack.): - `do` (`string`, req): const `"draw"` - `drawn` (`integer | null`): range 0..+inf; The number of packs the client last saw, or absent or `null` to leave it unchecked. - `oneOf[1]` (Cash out at the stack.): - `do` (`string`, req): const `"cashout"` - `drawn` (`integer | null`): range 0..+inf; The number of packs the client last saw, checked as on `draw`. ### `KombatParams` Type: `object` — KOMBAT's opening params, each read as written. - `rung` (`integer`, req): range 1..6 - `fighter` (`string`, req): enum: `doge`, `wojak`, `cat` - `duration` (`integer`, req): enum: `15`, `20`, `25`, `30`, `35`, `40`, `45` - `bets` (`object`, req): The slip, by bet. - `mode` (`string`, req): enum: `live`, `instant` ### `KombatAction` Type: `object | object` — One move on an open live KOMBAT fight. - `oneOf[0]` (Reveal the next exchange.): - `do` (`string`, req): const `"next"` - `n` (`integer | null`): range 0..999999999; The number of exchanges the client last saw, or absent or `null` to leave it unchecked. - `oneOf[1]` (Bet on a side winning the fight from here, at the quoted pay.): - `do` (`string`, req): const `"live_bet"` - `side` (`string`, req): enum: `you`, `opp` - `stake` (`string`, req) - `pay` (`string`, req): pattern `^(0|[1-9][0-9]{0,6})(\.[0-9]{1,2})?$`; The multiplier the view quotes for `side` now, with at most 2 decimals. ### `SignedAmount` Type: `string` — pattern `^-?(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$`; len 0..49 — An `Amount` that may be negative, with a leading `-` (a round's `profit` on a loss or a partial return). ### `LimboTarget` Type: `string` — pattern `^[1-9][0-9]*(\.[0-9]{1,2})?$` — LIMBO's target multiplier: a decimal string from `1.01` to `1000000.00` with **at most 2 decimals** and no surrounding whitespace. ### `LimboParams` Type: `object` — LIMBO's params (the game specification). - `target` (`LimboTarget`, req) ### `PlinkoParams` Type: `object` — PLINKO's params (the game specification). - `pins` (`integer`, req): range 8..16; The number of pins, as a plain JSON integer (16, never the string "16", 16.0 or 1.6e1). - `risk` (`string`, req): enum: `LOW`, `MEDIUM`, `HIGH`; The risk, which picks the paytable. ### `RouletteParams` Type: `object` — ROULETTE's params (the game specification): a table of 1 to 64 chips. - `chips` (`array`, req): items 1..64; The table's chips, in any order. ### `RouletteChip` Type: `object | object` — One chip, on a number or on a series. - `oneOf[0]` (A chip on one pocket, which returns 36 times its stake.): - `type` (`string`, req): const `"number"`; A number chip. - `number` (`integer`, req): range 0..36; The pocket, as a plain JSON integer (17, never the string "17", 17.0 or 1.7e1). - `stake` (`Amount`, req) - `oneOf[1]` (A chip on a series, which returns 2 or 3 times its stake.): - `type` (`string`, req): const `"series"`; A series chip. - `series` (`string`, req): enum: `all-red`, `all-black`, `even`, `odd`, `first-12`, `second-12`, `third-12`, `first-row`, `second-row`, `third-row`, `1-18`, `19-36`; The series, exactly as listed. - `stake` (`Amount`, req) ### `KenoParams` Type: `object` — KENO's params (the game specification). - `risk` (`string`, req): enum: `CLASSIC`, `LOW`, `MEDIUM`, `HIGH`; The risk, which picks the paytable. - `picks` (`array`, req): items 1..10; The numbers to play. ### `MinesParams` Type: `object` — MINES's opening params (the game specification). - `mines` (`integer`, req): range 1..24; The number of mines, which picks the paytable, as a plain JSON integer. - `tiles` (`array`): items 1..24; Instant play's tiles. ### `MinesAction` Type: `object | object` — A move on an open MINES round. - `oneOf[0]` (Sweep one tile.): - `do` (`string`, req): const `"sweep"`; Sweep. - `tile` (`integer`, req): range 0..24; The tile, as a plain JSON integer. - `oneOf[1]` (Cash out at the current multiplier.): - `do` (`string`, req): const `"cashout"`; Cash out. ### `TowersParams` Type: `object` — TOWERS's opening params (the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `WICKED`, `BRUTAL`; The difficulty, which sets the columns per row, how many are good and the paytable. ### `TowersAction` Type: `object | object` — A move on an open TOWERS round (the game specification). - `oneOf[0]` (Sweep one column on the current row.): - `do` (`string`, req): const `"sweep"`; Sweep a column. - `column` (`integer`, req): range 0..3; The column on the current row, as a plain JSON integer (below the difficulty's column count). - `oneOf[1]` (Cash out at the current row's multiplier.): - `do` (`string`, req): const `"cashout"`; Cash out the climb. ### `LimboView` Type: `object` — The `view` of a settled LIMBO round (`Round.view`). - `target` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; The validated target multiplier, formatted to 2 decimal places. - `crash_point` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; The rolled crash multiplier, formatted to 2 decimal places. - `roll` (`integer`, req): range 0..999999; The integer roll drawn from the provably fair digest (`0.. 999999`). - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`object`, req) ### `PlinkoView` Type: `object` — The `view` of a settled PLINKO round (`Round.view`). - `pins` (`integer`, req): range 8..16 - `risk` (`string`, req): enum: `LOW`, `MEDIUM`, `HIGH` - `bucket` (`integer`, req): range 0..16 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `win` (`boolean`, req) - `push` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`object`, req) ### `RouletteView` Type: `object` — The `view` of a settled ROULETTE round (`Round.view`). - `chips` (`array`, req): items 1..64 - `spin` (`integer`, req): range 0..36 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{8}$` - `win` (`boolean`, req) - `push` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`array`, req): items 0..0 ### `KenoView` Type: `object` — The `view` of a settled KENO round (`Round.view`). - `risk` (`string`, req): enum: `CLASSIC`, `LOW`, `MEDIUM`, `HIGH` - `picks` (`array`, req): items 1..10 - `drawn` (`array`, req): items 10..10 - `hits` (`integer`, req): range 0..10 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `table_version` (`integer`, req): const `1` - `words` (`array`, req): items 10..10 - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) ### `MinesForceClose` Type: `object` — Force-close metadata attached when a MINES round is settled by the platform. - `rule` (`integer`, req): enum: `1`, `2`, `4` - `k` (`integer`, req): range 1..24 - `j` (`integer`, req): range 0..24 - `close_credit` (`string | null`, req): pattern `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$` - `ev_floor` (`string | null`, req): pattern `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$` - `v` (`string | null`, req): pattern `^(0|[1-9][0-9]*)(/[1-9][0-9]*)?$` ### `MinesView` Type: `object` — The `view` of a settled MINES round (`Round.view`). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `REFUNDED`, `FORCE_CLOSED` - `mines` (`integer`, req): range 1..24 - `sweeped_tiles` (`array`, req): items 0..24 - `mine_locations` (`array`, req): items 1..24 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$` - `win` (`boolean | null`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `refund` (`Amount`) - `max_profit_hit` (`boolean | null`, req) - `floats_used` (`integer`, req): const `24` - `ended_by` (`string`): const `"FORCE_CLOSED"` - `force_close` (`MinesForceClose`) - `game_result` (`object | null`, req) ### `TowersResultRow` Type: `object` — One row in a settled TOWERS round's `results` array. - `attempted` (`boolean`, req) - `reward_locations` (`array`, req): items 0..3 - `swept_location` (`integer | null`, req): range 0..3 ### `TowersMatrixRow` Type: `object` — One display row in a settled TOWERS round's `game_table_matrix`. - `current_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$` - `return_amount` (`Amount`, req) - `good_locations` (`array`, req): items 1..3 - `bad_locations` (`array`, req): items 1..3 ### `TowersForceClose` Type: `object` — Force-close metadata attached when a TOWERS round is settled by the platform. - `rule` (`integer`, req): enum: `1`, `2` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `WICKED`, `BRUTAL` - `rows` (`integer`, req): range 0..8 ### `TowersView` Type: `object` — The `view` of a settled TOWERS round (`Round.view`). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `REFUNDED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `WICKED`, `BRUTAL` - `current_row` (`integer | null`, req): range 0..8 - `sw_locs` (`array`, req): items 9..9 - `bad_locs` (`array>`, req): items 9..9 - `results` (`array`): items 9..9 - `game_table_matrix` (`array`): items 9..9 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$` - `win` (`boolean | null`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `refund` (`Amount`) - `max_profit_hit` (`boolean | null`, req) - `floats_used` (`integer`, req): const `9` - `ended_by` (`string`): const `"FORCE_CLOSED"` - `force_close` (`TowersForceClose`) - `game_result` (`object | null`, req) ### `DiamondsParams` Type: `object` — DIAMONDS's opening params: **none**. ### `DiamondsView` Type: `object` — The `view` of a settled DIAMONDS round (`Round.view`). - `gems` (`array`, req): items 5..5 - `hand` (`string`, req): enum: `ALL_DIAMONDS`, `FOUR_DIAMONDS`, `THREE_DIAMONDS_TWO_DIAMONDS`, `THREE_DIAMONDS`, `TWO_DIAMONDS_TWO_DIAMONDS`, `TWO_DIAMONDS`, `NOTHING` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`object`, req) ### `RangediceBound` Type: `string` — pattern `^(100(\.0{1,2})?|[1-9]?[0-9](\.[0-9]{1,2})?)$` — A RANGEDICE target or range endpoint from `0` to `100` with at most 2 decimals and no leading zeros. ### `RangediceParams` Type: `object | object | object` — RANGEDICE's opening params (`range-dice`): `over` and `under` require `target` and `multiplier` (and forbid `ranges`, including... - `oneOf[0]` (Single-threshold over or under selection.): - `mode` (`string`, req): enum: `over`, `under` - `target` (`RangediceBound`, req) - `multiplier` (`string`, req): pattern `^[0-9]{1,5}\.[0-9]{2}$` - `oneOf[1]` (Single-range between or outside selection.): - `mode` (`string`, req): enum: `between`, `outside` - `ranges` (`array>`, req): items 1..1 - `multiplier` (`string`, req): pattern `^[0-9]{1,5}\.[0-9]{2}$` - `oneOf[2]` (Dual-range either selection.): - `mode` (`string`, req): const `"either"` - `ranges` (`array>`, req): items 2..2 - `multiplier` (`string`, req): pattern `^[0-9]{1,5}\.[0-9]{2}$` ### `RangediceView` Type: `object` — The `view` of a settled RANGEDICE round (`Round.view`). - `mode` (`string`, req): enum: `over`, `under`, `between`, `outside`, `either` - `target` (`string | null`, req): pattern `^(100(\.0{1,2})?|[1-9]?[0-9](\.[0-9]{1,2})?)$` - `ranges` (`array | null`, req): items 1..2 - `count` (`integer`, req): range 1..9406 - `chance` (`string`, req): pattern `^(0|[1-9][0-9]?)\.[0-9]{4}$` - `multiplier` (`string`, req): pattern `^[1-9][0-9]{0,4}\.[0-9]{2}$` - `payout_multiplier` (`string`, req): pattern `^(0|[1-9][0-9]{0,4})\.[0-9]{2}$` - `roll` (`string`, req): pattern `^(100\.00|[1-9]?[0-9]\.[0-9]{2})$` - `roll_number` (`integer`, req): range 0..10000 - `word` (`integer`, req): range 0..4294967295 - `float` (`string`, req): pattern `^(0|0\.[0-9]{1,32})$` - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `game_result` (`object`, req) ### `BaccaratParams` Type: `object` — BACCARAT's opening params: `bets` maps any combination of `player`, `banker` and `tie` to canonical decimal strings (at most 12... - `bets` (`object`, req) ### `BaccaratCard` Type: `object` — One dealt card in a settled BACCARAT coup. - `index` (`integer`, req): range 0..51 - `rank` (`integer`, req): range 1..13 - `label` (`string`, req): enum: `A`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `J`, `Q`, `K` - `suit` (`integer`, req): range 0..3 - `value` (`integer`, req): range 0..9 ### `BaccaratView` Type: `object` — The `view` of a settled BACCARAT round (`Round.view`). - `result` (`string`, req): enum: `win`, `loss`, `push` - `win` (`boolean`, req) - `push` (`boolean`, req) - `roll_number` (`integer`, req): range 0..99; `10 * totals.player + totals.banker`. - `payout_ratio` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2,20}$` - `outcome` (`string`, req): enum: `player`, `banker`, `tie` - `natural` (`boolean`, req) - `player_cards` (`array`, req): items 2..3 - `banker_cards` (`array`, req): items 2..3 - `totals` (`object`, req) - `bets` (`object`, req) - `payouts` (`object`, req) - `returns` (`object`, req) - `results` (`object`, req) - `total_bet` (`Amount`, req) - `total_return` (`Amount`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `capped` (`boolean`, req) - `table_version` (`integer`, req): const `1` - `rejected` (`array`, req) - `game_result` (`string`, req): pattern `^\{.*\}$` ### `BlackjackParams` Type: `object` — BLACKJACK's opening params: **none**. ### `BlackjackAction` Type: `object | object | object | object | object | object` — One move on an open BLACKJACK round: `hit`, `stand`, `double`, `split`, `insurance`, or `no_insurance`. - `oneOf[0]` (Draw another card on the active hand.): - `do` (`string`, req): const `"hit"` - `oneOf[1]` (Stand on the active hand (moves to hand 2 after a split, or settles).): - `do` (`string`, req): const `"stand"` - `oneOf[2]` (Double the stake on an initial two-card hand and draw one card.): - `do` (`string`, req): const `"double"` - `oneOf[3]` (Split an initial pair of equal value into two hands by adding one stake.): - `do` (`string`, req): const `"split"` - `oneOf[4]` (Take insurance against a dealer Ace by adding half the opening stake.): - `do` (`string`, req): const `"insurance"` - `oneOf[5]` (Decline insurance against a dealer Ace.): - `do` (`string`, req): const `"no_insurance"` ### `BlackjackView` Type: `object | object` — The `view` of a settled BLACKJACK round (`Round.view`). - `oneOf[0]` (Normal settled BLACKJACK round (`win` or `loss`).): - `status` (`string`, req): enum: `win`, `loss` - `player_hand` (`array`, req): items 2..inf - `player2_hand` (`array`): items 2..inf - `dealer_hand` (`array`, req): items 1..inf - `player_score` (`integer`, req): range 2..31 - `player2_score` (`integer`): range 2..31 - `dealer_score` (`integer`, req): range 2..31 - `win` (`integer`, req): enum: `0`, `1` - `payout` (`string`, req): pattern `^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$` - `bet_amt` (`Amount`, req) - `actions` (`array`, req): items 0..0 - `hand1_status` (`string`, req): enum: `win`, `draw`, `loss` - `hand2_status` (`string`, req): enum: `not_started`, `win`, `draw`, `loss` - `staked` (`Amount`, req) - `credit` (`Amount`, req) - `profit` (`SignedAmount`, req) - `max_profit_hit` (`boolean`, req) - `floats_used` (`integer`, req): const `52` - `game_result` (`string`, req): pattern `^\{.*\}$` - `oneOf[1]` (Force-closed BLACKJACK round (`FORCE_CLOSED`, Rule 4).): - `status` (`string`, req): const `"FORCE_CLOSED"` - `ended_by` (`string`, req): const `"FORCE_CLOSED"` - `rule` (`integer`, req): const `4` - `hand` (`array`, req): items 1..inf - `hand2` (`array`, req) - `up` (`integer`, req): range 1..11 - `known` (`boolean`, req) - `insured` (`boolean`, req) - `current_hand` (`integer`, req): range 0..2 - `double_open` (`boolean`, req) - `pair` (`boolean`, req) - `v` (`string`, req): pattern `^(0|[1-9][0-9]*)(/[1-9][0-9]*)?$` - `ev_floor` (`Amount`, req) - `player_hand` (`array`, req): items 1..inf - `player2_hand` (`array`, req) - `dealer_hand` (`array`, req): items 1..1 - `win` (`null`, req) - `payout` (`string`, req): pattern `^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$` - `staked` (`Amount`, req) - `credit` (`Amount`, req) - `profit` (`SignedAmount`, req) - `max_profit_hit` (`null`, req) - `floats_used` (`integer`, req): const `52` - `game_result` (`null`, req) ### `HiloParams` Type: `object` — HILO's opening params: **none**. ### `HiloAction` Type: `object | object | object` — One move on an open HILO round: `guess` (`HI`, `LO`, or `SAME` when offered on the current card), `skip` (up to 52 skips per... - `oneOf[0]` (Predict the next card relative to the current card.): - `do` (`string`, req): const `"guess"` - `guess` (`string`, req): enum: `HI`, `LO`, `SAME` - `oneOf[1]` (Skip the current card without changing the accumulated multiplier.): - `do` (`string`, req): const `"skip"` - `oneOf[2]` (Cash out the accumulated multiplier after at least one winning guess.): - `do` (`string`, req): const `"cashout"` ### `HiloView` Type: `object` — The `view` of a settled HILO round (`Round.view`). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `REFUNDED` - `nonce` (`integer`, req): range 0..+inf - `card` (`integer`, req): range 0..51 - `cards` (`array`, req): items 1..inf - `actions` (`string`, req): pattern `^[HLSK]*$` - `guesses` (`integer`, req): range 0..100 - `skips` (`integer`, req): range 0..52 - `skips_left` (`integer`, req): range 0..52 - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$` - `can_cashout` (`boolean`, req): const `false` - `options` (`array`, req): items 0..0 - `auto_cashout` (`string | null`, req): enum: `MAX_MULTIPLIER`, `MAX_GUESSES`, `MAX_PROFIT`, `null` - `profit` (`SignedAmount`, req) - `credit` (`Amount`, req) - `refund` (`Amount`) - `win` (`boolean`) - `max_profit_hit` (`boolean`) - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): enum: `1`, `2` - `x_n` (`string`): pattern `^(0|[1-9][0-9]*)(/[1-9][0-9]*)?$` - `x_n_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)(/[1-9][0-9]*)?$` - `game_result` (`object | null`, req) ### `BarsParams` Type: `object` — BARS's params (the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT`; The difficulty, which picks the table. - `picks` (`array`, req): items 1..5; The bars to bet on. ### `ChickenParams` Type: `object` — CHICKEN's opening params (the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT`; The difficulty, which sets the deadly lanes, the rows and the paytable. - `round` (`integer`): range 0..19; 0 (absent) for a manual round; N for auto mode, a cash-out row of the difficulty (`EASY` 2 to 19,... ### `ChickenAction` Type: `object | object` — A move on an open manual CHICKEN round (the game specification). - `oneOf[0]` (Cross the next lane.): - `do` (`string`, req): const `"step"`; Cross a lane. - `oneOf[1]` (Cash out at the multiplier of the row reached.): - `do` (`string`, req): const `"cashout"`; Stop crossing and cash out. ### `ChickenGameResult` Type: `object` — The source's `bets.game_result` for a played CHICKEN round. - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `crossed` (`integer`, req): range 0..19 - `death_lanes` (`array`, req): items 1..10 ### `ChickenView` Type: `object` — The `view` of a settled CHICKEN round (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `REFUNDED`, `FORCED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `current_row` (`integer`, req): range 0..19 - `rows` (`integer`, req): enum: `10`, `15`, `17`, `19` - `target_row` (`integer`): range 1..19; Auto-mode target row (present only in auto mode). - `multiplier` (`string`): pattern `^(0|(0|[1-9][0-9]*)\.[0-9]{2})$`; `0` on `BUSTED`, paytable multiplier on `CASHED_OUT`, floored value (`1.00`) on `FORCED`, omitted... - `win` (`boolean`, req) - `push` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `refund` (`Amount`): Full stake refunded on Rule 2 force-close (`REFUNDED`). - `max_profit_hit` (`boolean`, req) - `death_lane` (`integer | null`, req): range 1..20; The deadly lane stepped onto on `BUSTED`, or `null` otherwise. - `death_lanes` (`array`, req): items 1..10 - `floats_used` (`integer`, req): const `20` - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): enum: `1`, `2`, `3` - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `v_star_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `game_result` (`ChickenGameResult | null`, req): The source's `bets.game_result`, or `null` on `REFUNDED` and `FORCED`. ### `PumpParams` Type: `object` — PUMP's opening params (the game specification). - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT`; The difficulty, which sets the popping positions, the top and the paytable. - `round` (`integer`): range 0..24; 0 (absent) for a manual round; N for auto mode, a cash-out point of the difficulty (`EASY` 2 to 24,... ### `PumpAction` Type: `object | object` — A move on an open manual PUMP round (the game specification). - `oneOf[0]` (Make the next pump.): - `do` (`string`, req): const `"pump"`; Pump once. - `oneOf[1]` (Cash out at the multiplier of the pumps made.): - `do` (`string`, req): const `"cashout"`; Stop pumping and cash out. ### `PumpGameResult` Type: `object` — The source's `bets.game_result` for a played PUMP round (`v: 1`; the game specification). - `v` (`integer`, req): const `1` - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `pops` (`integer`, req): enum: `1`, `3`, `5`, `10` - `pumps` (`integer`, req): range 0..24 - `pop_at` (`integer`, req): range 1..25 - `pop_positions` (`array`, req): items 1..10 - `multiplier` (`string | null`, req): pattern `^[1-9][0-9]*\.[0-9]{2}$` - `target` (`integer | null`, req): range 1..24 - `auto` (`string | null`, req): enum: `TOP`, `MAX_PROFIT`, `null` ### `PumpView` Type: `object` — The `view` of a settled PUMP round (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `REFUNDED`, `FORCED` - `difficulty` (`string`, req): enum: `EASY`, `MEDIUM`, `HARD`, `EXPERT` - `current_row` (`integer`, req): range 0..24 - `max_pumps` (`integer`, req): enum: `15`, `20`, `22`, `24` - `target` (`integer | null`, req): range 1..24; Auto-mode target pumps, or `null` in manual mode. - `multiplier` (`string | null`, req): pattern `^[1-9][0-9]*\.[0-9]{2}$`; Paytable multiplier on `CASHED_OUT`, or `null` otherwise. - `auto_cashout` (`string | null`, req): enum: `TOP`, `MAX_PROFIT`, `null` - `win` (`boolean`, req) - `payout_multiplier` (`string`): pattern `^(0|(0|[1-9][0-9]*)\.[0-9]{2})$`; Settlement multiplier paid (`"0"` on `BUSTED`, `multiplier` on `CASHED_OUT`, `"0.98"` on `FORCED`,... - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `refund` (`Amount`): Full stake refunded on Rule 2 force-close (`REFUNDED`). - `max_profit_hit` (`boolean`, req) - `pop_at` (`integer`, req): range 1..25 - `pop_positions` (`array`, req): items 1..10 - `floats_used` (`integer`, req): const `24` - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): enum: `1`, `2`, `3` - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `v_star_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `game_result` (`PumpGameResult | null`, req): The source's `bets.game_result`, or `null` on `REFUNDED` and `FORCED`. ### `MolesParams` Type: `object` — MOLES's opening params (the game specification –). - `moles` (`integer`, req): range 1..6; How many of the 7 holes hold a mole each round (1 to 6), which picks the ladder, as a plain JSON... - `hole` (`integer`, req): range 0..6; The opening hole on the 2-3-2 board (0 to 6), picked on round 1 in manual mode and on every round... - `hits` (`integer`): range 0..9; 0 (absent) for a manual round; 1 to 8 (1 mole) or 1 to 9 (2 to 6 moles) for auto mode, as a plain... ### `MolesAction` Type: `object | object` — A move on an open manual MOLES round (the game specification –). - `oneOf[0]` (Pick a hole on the next round of the board.): - `do` (`string`, req): const `"hit"`; Whack a hole. - `hole` (`integer`, req): range 0..6; The hole to pick on the 7-hole board (0 to 6), as a plain JSON integer. - `oneOf[1]` (Cash out at m(moles, hits).): - `do` (`string`, req): const `"cashout"`; Stop whacking and cash out. ### `MolesRevealedRound` Type: `object` — One played round of a MOLES board (`MolesView.rounds`; the game specification). - `moles` (`array`, req): items 1..6 - `pick` (`integer`, req): range 0..6 - `hit` (`boolean`, req) - `floats` (`integer`, req): range 1..192 ### `MolesView` Type: `object` — The `view` of a settled MOLES round (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED` - `mode` (`string`, req): enum: `manual`, `auto` - `moles` (`integer`, req): range 1..6 - `hits` (`integer`, req): range 0..9 - `max_rounds` (`integer`, req): enum: `8`, `9` - `rounds` (`array`, req): items 1..9 - `floats_used` (`integer`, req): range 1..1728 - `rejected` (`array`, req) - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*\.[0-9]{2})$` - `can_cashout` (`boolean`, req): const `false` - `win` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `cashed_at` (`integer | null`, req): range 1..9 - `auto_cashout` (`string | null`, req): enum: `TOP`, `MAX_PROFIT`, `null` - `max_profit_hit` (`boolean`, req) - `target` (`integer`): range 1..9; Auto-mode target hit count (present only in auto mode). - `hole` (`integer`): range 0..6; Auto-mode repeated hole pick (present only in auto mode). - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): const `1` - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `v_star_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `game_result` (`object | object`, req): The source's `bets.game_result` (`v: 1`), manual or auto shape. ### `RpsParams` Type: `object | object` — RPS's opening params (the game specification). - `oneOf[0]` (Open a manual RPS round at its first throw (`RpsAction` continues it).): - `pick` (`string`, req): enum: `ROCK`, `PAPER`, `SCISSORS`; The opening throw's hand, upper case, exactly as listed. - `hands` (`integer`): const `0`; 0 (omit the key) for a manual RPS round, as a plain JSON integer. - `oneOf[1]` (Play an auto RPS run of 1 to 20 won hands in the opening request.): - `pick` (`string`, req): enum: `ROCK`, `PAPER`, `SCISSORS`; Hand 1's opening pick, from which `pattern` steps. - `hands` (`integer`, req): range 1..20; Target won hands (1 to 20), as a plain JSON integer. - `pattern` (`string`, req): enum: `FIXED`, `CYCLE`, `REVERSE`; How each hand's first throw steps from `pick` (`FIXED` keeps it, `CYCLE` steps R->P->S->R,... - `tie_picks` (`string`): pattern `^[RPS]{1,640}$`; len 1..640; Browser-chosen re-picks consumed in order across ties and rerolls (1 to 640 letters `R`, `P` or... ### `RpsAction` Type: `object | object` — A move on an open manual RPS round (the game specification). - `oneOf[0]` (Throw ROCK, PAPER or SCISSORS against the house.): - `do` (`string`, req): const `"throw"`; Make the next throw. - `pick` (`string`, req): enum: `ROCK`, `PAPER`, `SCISSORS`; The hand to throw, upper case, exactly as listed. - `oneOf[1]` (Cash out at the multiplier of the won hands.): - `do` (`string`, req): const `"cashout"`; Stand on the won hands and cash out. ### `RpsThrow` Type: `object` — One throw in an RPS round (`RpsView.throws` and `last_hand`; the game specification). - `pick` (`string`, req): enum: `R`, `P`, `S` - `house` (`string | null`, req): enum: `R`, `P`, `S`, `null`; House hand (`R`, `P` or `S`), or `null` on a `u = 0` reroll. - `result` (`string`, req): enum: `win`, `loss`, `tie`, `reroll` - `float_index` (`integer`, req): range 0..659 - `capped` (`boolean`): const `true`; Present and `true` only on the 33rd coin-decided throw of a hand after 32 undecided throws. ### `RpsView` Type: `object` — The `view` of a settled RPS round (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED`, `FORCED` - `mode` (`string`, req): enum: `manual`, `auto` - `wins` (`integer`, req): range 0..20 - `max_wins` (`integer`, req): const `20` - `picks` (`array`, req): items 0..20 - `throws` (`array`, req): items 1..660 - `last_hand` (`array`, req): items 0..33 - `floats_used` (`integer`, req): range 1..660 - `multiplier` (`string | null`, req): pattern `^(0|[1-9][0-9]*\.[0-9]{2})$`; Ladder multiplier on `CASHED_OUT`, `"0"` on `BUSTED`, or `null` on Rule 4 `FORCED`. - `tie_pending` (`boolean`, req) - `can_cashout` (`boolean`, req): const `false` - `win` (`boolean`, req) - `push` (`boolean`, req) - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `cashed_at` (`integer | null`, req): range 1..20 - `auto_cashout` (`string | null`, req): enum: `TOP`, `MAX_PROFIT`, `null` - `max_profit_hit` (`boolean`, req) - `pattern` (`string`): enum: `FIXED`, `CYCLE`, `REVERSE` - `target` (`integer`): range 1..20 - `tie_picks` (`string`): pattern `^[RPS]{1,640}$` - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): enum: `1`, `4` - `v_star_credit` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$`; Exact Rule 4 continuation credit as a reduced rational `num/den` in currency units. - `game_result` (`object | object | null`, req): The source's `bets.game_result` (`v: 2`), manual or auto shape, or `null` on Rule 4 `FORCED`. ### `SkyrushParams` Type: `object | object` — SKYRUSH's opening params (the game specification –). - `oneOf[0]` (Open a manual SKYRUSH flight at gate 0 (`SkyrushAction` flies later gates).): - `ring` (`string`, req): enum: `GREEN`, `GOLD`, `RED`; Gate 0's ring (`GREEN` 1.26x, `GOLD` 1.90x or `RED` 3.80x), upper case, exactly as listed. - `oneOf[1]` (Fly a preset SKYRUSH plan of 1 to 25 canyon gates in the opening request.): - `plan` (`array`, req): items 1..25; The rings to fly in gate order (1 to 25 gates). - `land_at` (`string`): pattern `^(1\.(0[1-9]|[1-9][0-9]?)|([2-9]|[1-9][0-9]{1,5})(\.[0-9]{1,2})?|1000000(\.0{1,2})?)$`; Auto-landing target multiplier from `1.01` to `1000000.00` with at most 2 decimals and no leading... ### `SkyrushAction` Type: `object | object` — A move on an open manual SKYRUSH flight (the game specification). - `oneOf[0]` (Fly the next canyon gate through an offered ring.): - `do` (`string`, req): const `"fly"`; Fly one gate. - `ring` (`string`, req): enum: `GREEN`, `GOLD`, `RED`; The ring to fly at the next gate, upper case, exactly as listed. - `oneOf[1]` (Land at the current path multiplier.): - `do` (`string`, req): const `"cashout"`; Land the flight and cash out. ### `SkyrushGate` Type: `object` — One canyon gate flown in a SKYRUSH round (`SkyrushView.gates`; the game specification). - `ring` (`string`, req): enum: `G`, `Y`, `R` - `u` (`integer`, req): range 0..4294967295 - `survived` (`boolean`, req) - `multiplier` (`string | null`, req): pattern `^[1-9][0-9]*\.[0-9]{2}$`; Path multiplier after surviving this gate, or `null` on a crash. ### `SkyrushView` Type: `object` — The `view` of a settled SKYRUSH flight (`Round.view`; the game specification). - `status` (`string`, req): enum: `CASHED_OUT`, `BUSTED` - `win` (`boolean`, req) - `mode` (`string`, req): enum: `manual`, `auto` - `payout` (`Amount`, req) - `profit` (`SignedAmount`, req) - `profit_capped` (`boolean`, req): const `false` - `multiplier` (`string`, req): pattern `^(0|[1-9][0-9]*\.[0-9]{2})$` - `cleared` (`integer`, req): range 0..25 - `max_gates` (`integer`, req): const `25` - `rings` (`string`, req): pattern `^[GYR]{0,25}$`; Survived ring letters in order (`""` when crashed at gate 0). - `gates` (`array`, req): items 1..25 - `last_gate` (`SkyrushGate | null`, req): Most recently flown gate, or `null` on manual cash-out and force-close. - `greens` (`integer`, req): range 0..25 - `golds` (`integer`, req): range 0..25 - `reds` (`integer`, req): range 0..25 - `floats_used` (`integer`, req): range 1..25 - `cashed_at` (`integer | null`, req): range 1..25 - `auto_cashout` (`string | null`, req): enum: `MAX_GATES`, `MAX_MULTIPLIER`, `MAX_PROFIT`, `TARGET`, `PLAN_END`, `null` - `max_profit` (`Amount`, req) - `plan` (`string`): pattern `^[GYR]{1,25}$`; Auto-mode flight plan in ring letters (present only in auto mode). - `land_at` (`string | null`): pattern `^[1-9][0-9]*\.[0-9]{2}$`; Auto-mode landing target formatted to 2 decimals, or `null` when absent (present only in auto mode). - `ended_by` (`string`): const `"FORCE_CLOSED"` - `rule` (`integer`): const `1` - `v_star` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `v_star_minus_f` (`string`): pattern `^(0|[1-9][0-9]*)/[1-9][0-9]*$` - `game_result` (`object | object`, req): The source's `bets.game_result` (`v: 1`), manual or auto shape. ### `RoundCreate` Type: `object` — A round to open. - `game` (`GameSlug`, req) - `brand` (`BrandId`, req) - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) - `stake` (`Amount`, req) - `jurisdiction` (`JurisdictionCode`) - `params` (`object`, req): The game's opening parameters: DICE takes `DiceParams`, LIMBO `LimboParams`, PLINKO `PlinkoParams`,... ### `RoundAction` Type: `object` — One step of a session round. - `action` (`object`, req): The game's action, an object whose `do` names the move (its spec and schema list them). - `step` (`integer`, req): range 1..+inf; The step this action makes, the round's `step` before it plus one. ### `SeedRef` Type: `object` — The seed pair a round drew from. - `server_seed_hash` (`string`, req): pattern `^[0-9a-f]{64}$`; SHA-256 of the server seed, shown before any round used it. - `client_seed` (`ClientSeed`, req) - `nonce` (`integer`, req): range 0..9007199254740991; The round's nonce in this seed pair. ### `CapRule` Type: `string` — enum: `truncate`, `refuse` — How the engine version applies `max_profit` (platform policy): `truncate`: a settled payout's profit (`payout − stake`) is cut at... ### `CapSource` Type: `string` — enum: `brand`, `demo` — Where the round's snapshotted `max_profit` came from when the round opened: `brand`: the brand's configured `max_profit` for... ### `Round` Type: `object` — A round, as the operator or the session's player sees it. **Every read shows an outcome only once the attempt that pays for it is... - `id` (`RoundId`, req) - `game` (`GameSlug`, req) - `version` (`integer`, req): range 1..+inf; The engine version that plays the round. - `brand` (`BrandId`, req) - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) - `status` (`string`, req): enum: `open`, `settled`, `void`; `open` includes a round whose opening debit is unresolved. - `step` (`integer`, req): range 1..+inf; How many steps the round has taken (1 after the open). - `stake` (`Amount`, req) - `payout` (`Amount`, req): The gross amount the player is paid at settlement: 0 while the round is open, and 0 on a loss. - `refund` (`Amount`, req): The part of `payout` that is stake returned unplayed, neither wagered nor won: DEADSHOT's unfired... - `stake_added` (`Amount`): What the last step added to `stake` (a double), which the operator takes from the player. - `max_profit` (`Amount`, req): The round's profit ceiling (`maximum_profit`, the most `payout − stake` may reach), snapshotted... - `cap_rule` (`CapRule`, req): How this engine version applies `max_profit`. - `cap_source` (`CapSource`, req): Where `max_profit` came from when the round opened. - `view` (`object`, req): What the player may see now, empty while the outcome is hidden (above); when settled, the round's... - `seed` (`SeedRef`, req) - `created_at` (`string`, req): format `date-time`; When the round opened. - `settled_at` (`string | null`): format `date-time`; When it settled; null while open. ### `RoundPage` Type: `object` — One page of the operator's rounds, with the cursor to the next. - `data` (`array`, req): The rounds, newest first. - `next_cursor` (`string | null`, req): Pass it as `cursor` for the next page; null on the last page. ### `VerifiedTablePin` Type: `object` — A table fingerprint pinned by the engine version that played the round (`engine.Table`). - `name` (`string`, req): len 1..64; The table's name within the engine version (for example a slot theme id or weighted-table id). - `fingerprint` (`string`, req): pattern `^[0-9a-f]{64}$`; Pinned lowercase hex SHA-256 fingerprint of the canonical table (including any compiled `max_win_x`... ### `VerifiedChainLink` Type: `object` — Pre-committed hash-chain link and public block salt for a live show record (`fair.ChainLink`, 10). - `chain` (`string`, req): len 1..64; Identifier of the published hash chain. - `index` (`integer`, req): range 0..9007199254740991; Link index `i` in the chain. - `seed` (`string`): pattern `^[0-9a-f]{64}$`; Revealed 64-hex link seed `s_i`, whose SHA-256 over ASCII bytes equals `commit`. - `commit` (`string`, req): pattern `^[0-9a-f]{64}$`; Commitment `s_{i-1} = sha256(s_i)` published before the link ran. - `salt` (`string`, req): pattern `^[0-9a-f]{64}$`; 64-hex public block hash announced after `commit` and before the chain's first round. - `salt_source` (`string`, req): len 1..64; Where `salt` came from (for example `bitcoin:840000`). ### `VerifiedStreamRef` Type: `object` — Stream binding and revealed server seed of a format-1 engine record (`engine.StreamRef`, 7). - `kind` (`string`, req): enum: `fairrandom`, `dice-sha512`, `hmac-nonce`, `plinko-hmac`; Deterministic RNG stream recipe. - `server_seed_hash` (`string`, req): pattern `^[0-9a-f]{64}$`; Pre-committed SHA-256 over the 64 ASCII characters of `server_seed`. - `server_seed` (`string`): pattern `^[0-9a-f]{64}$`; Revealed 64 lowercase hex server seed (populated on `GET /v1/rounds/{id}/verify`). - `client_seed` (`string`, req): len 1..inf; Non-empty UTF-8 client seed mixed into every draw. - `nonce` (`integer`, req): range 0..9007199254740991; Round nonce `0 … 2^53 − 1` (`fair.MaxNonce`). - `chain` (`VerifiedChainLink`) ### `VerifiedCurrency` Type: `object` — Currency code and decimal atom scale carried in `record.input.currency` (`money.Currency`, 7). - `code` (`CurrencyCode`, req) - `scale` (`integer`, req): range 0..18; Number of fractional decimal digits per unit (`0 … 18`). ### `VerifiedLimits` Type: `object` — Per-round stake and profit limits snapshotted into `record.input.limits` when the round opened and immutable thereafter... - `min_stake` (`Amount`, req): Minimum per-bet stake snapshotted at open. - `max_stake` (`Amount`, req): Maximum per-bet stake snapshotted at open. - `max_profit` (`Amount`, req): Maximum round profit (`payout − stake`) snapshotted at open (`brand_currencies.max_profit`). ### `VerifiedRecordInput` Type: `object` — Opening input bound into a format-1 engine record (`engine.Input`). - `profile` (`string`, req): pattern `^[a-z][a-z0-9]*(_[a-z0-9]+)*$`; len 2..32; RTP profile id (`source` on every v1 engine). - `currency` (`VerifiedCurrency`, req) - `stake` (`Amount`, req): Opening stake debited in `Open`, formatted at `currency.scale`. - `limits` (`VerifiedLimits`, req) - `params` (`object`, req): Game-specific opening parameters (`RoundCreate.params`). ### `VerifiedStreamTrace` Type: `object` — Stream positions consumed by one committed step (`fair.Trace`, 7). - `from` (`integer`, req): range 0..9007199254740991; Stream position before the step (`0` on `steps[0]`). - `to` (`integer`, req): range 0..9007199254740991; Stream position after the step. - `rejected` (`array`): `fairrandom` word indices rejected by exact `Uniform` sampling during the step, if any. ### `VerifiedStepOutcome` Type: `object` — Committed outcome of one step in a format-1 engine record (`engine.Outcome`, 7–8), with amounts rendered at... - `status` (`string`, req): enum: `open`, `settled`; `open` on non-final steps; `settled` on the final step only. - `stake` (`Amount`, req): Cumulative stake committed through this step. - `payout` (`Amount`, req): Gross settlement payout (`0` while `open`; includes `refund` when `settled`). - `refund` (`Amount`, req): Unplayed stake included in `payout`. - `capped` (`boolean`): Present and `true` when a `truncate` game cut this settled payout to... - `exposure` (`Amount`, req): Largest gross payout still reachable without new stake (`payout` once `settled`, at most... - `trace` (`VerifiedStreamTrace`, req) - `view` (`object`, req): Public step view (`game_result` on the settled step). ### `VerifiedRecordStep` Type: `object` — One committed call in a format-1 engine record (`steps[0]` is `Open`, omitting `action`; each later step is an `Act` or platform... - `action` (`object`): Action JSON passed to `Act` (or `Descriptor.ForceClose` on a platform force-close step); omitted on... - `outcome` (`VerifiedStepOutcome`, req) ### `VerifiedRecord` Type: `object` — Format-1 engine record (`engine.Record`) as rendered on the wire by `GET /v1/rounds/{id}/verify` (the server `formatRecord`) and... - `v` (`integer`, req): const `1`; Record layout version (`engine.RecordFormat = 1`). - `game` (`string`, req): pattern `^[A-Z][A-Z0-9_]{0,31}$`; Engine `GameID` (for example `DICE`, `PACKS`, `MEME_TRADE`). - `version` (`integer`, req): range 1..+inf; Engine version that played the round. - `tables` (`array | null`, req): Pinned table fingerprints of the engine version (`null` when the engine has no table). - `stream` (`VerifiedStreamRef`, req) - `input` (`VerifiedRecordInput`, req) - `steps` (`array`, req): items 1..inf; Committed steps (`steps[0]` = `Open`; only the final step has `outcome.status: settled`). ### `Verification` Type: `object` — A replay of a revealed round. - `result` (`string`, req): enum: `ok`, `verify_mismatch`; `ok` when every step replays (including `input.limits.max_profit` cap verification);... - `detail` (`string`): With `verify_mismatch`, the first difference. - `record` (`object`, req): The round's format-1 `VerifiedRecord` with every amount rendered as a decimal string at... ### `SeedPairCommitted` Type: `object` — A seed pair in use or committed for next. - `server_seed_hash` (`string`, req): pattern `^[0-9a-f]{64}$`; SHA-256 of the server seed. - `client_seed` (`ClientSeed`, req) - `nonces_used` (`integer`, req): range 0..+inf; How many nonces the pair has reserved; on the current pair, the next round's nonce. ### `SeedPairRevealed` Type: `object` — A seed pair rotated out, with its server seed revealed so every round on it can be verified. - `server_seed_hash` (`string`, req): pattern `^[0-9a-f]{64}$`; SHA-256 of the server seed, as committed before the pair's first round. - `server_seed` (`string`, req): pattern `^[0-9a-f]{64}$`; The revealed server seed; its SHA-256 is `server_seed_hash`. - `client_seed` (`ClientSeed`, req) - `nonces_used` (`integer`, req): range 0..+inf; How many nonces the pair reserved; a nonce is never reused, and one can be skipped. ### `SeedState` Type: `object` — A player's seeds for one game. - `current` (`SeedPairCommitted`, req) - `next` (`SeedPairCommitted`, req) - `previous` (`SeedPairRevealed | null`, req): The pair rotated out last, with its server seed revealed; null before the first rotation. ### `ClientSeedSet` Type: `object` — The client seed for the next seed pair. - `client_seed` (`ClientSeed`, req) ### `LaunchCreate` Type: `object` — What to launch, for whom. - `game` (`GameSlug`, req) - `brand` (`BrandId`, req) - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) - `mode` (`string`, req): enum: `real`, `demo`; `demo` plays with fun money and never touches the wallet. - `locale` (`string`, req): pattern `^[a-z]{2}(-[A-Z]{2})?$`; The player's language, as a BCP 47 tag. - `return_url` (`string`): format `uri`; len 0..2048; Where "back to the casino" goes; it must be on one of the brand's configured origins. - `jurisdiction` (`JurisdictionCode`) ### `RealityCheck` Type: `object` — Operator-configured reality-check schedule snapshotted when a real-money seamless session launched (part 2; enforcement hook over... - `interval_seconds` (`integer`, req): range 300..86400; The snapshotted reality-check interval in seconds (300 to 86400). - `due_at` (`string`, req): format `date-time`; When the next reality-check acknowledgement becomes due (`now >= due_at` refuses new play with... ### `RealityCheckAck` Type: `object` — A recorded player acknowledgement of a due reality check (`POST /v1/sessions/current/reality-check`, part 2; policy defaults... - `acknowledged_at` (`string`, req): format `date-time`; When the player acknowledged the reality check. - `elapsed_seconds` (`integer`, req): range 0..+inf; Whole seconds elapsed since the player session was created. - `net_result` (`SignedAmount`, req): Exact settled net result (`payout - stake`) across this session's rounds in the session currency. - `reality_check` (`RealityCheck`, req) ### `Launch` Type: `object` — A launch. - `token` (`string`, req): pattern `^[A-Za-z0-9_-]{43}$`; The launch token, 32 random bytes in base64url. - `url` (`string`, req): format `uri`; The play URL for the iframe host. - `expires_at` (`string`, req): format `date-time`; When the token stops working, 60 s after it was issued. - `reality_check` (`RealityCheck | null`, req): The brand environment's snapshotted reality-check schedule for this real-money session, or `null`... ### `TopupMockEvent` Type: `object` — The mock provider's webhook body. - `id` (`string`, req): pattern `^[A-Za-z0-9_.:-]{1,128}$`; The provider's event id, unique per provider. - `topup_id` (`string`, req): format `uuid`; BetPlug's id for the top-up, sent to the provider as the client reference. - `operator_id` (`string`, req): format `uuid`; The operator the top-up belongs to. - `checkout_id` (`string`, req): pattern `^[A-Za-z0-9_.:-]{1,128}$`; The provider's id for the checkout. - `status` (`string`, req): enum: `succeeded`, `failed`, `expired`, `reversed`; What happened to the checkout. - `amount_micro` (`integer`, req): range 0..9007199254740991; The amount captured, in micro-USD. - `currency` (`string`, req): pattern `^[A-Z]{3}$`; The currency captured. ### `SessionCreate` Type: `object` — The launch token to exchange. - `launch_token` (`string`, req): pattern `^[A-Za-z0-9_-]{43}$`; The launch token from `POST /v1/launch`. ### `DemoSessionCreate` Type: `object` — The demo to start. - `game` (`GameSlug`, req) - `locale` (`string`, req): pattern `^[a-z]{2}(-[A-Z]{2})?$`; The visitor's language, as a BCP 47 tag. ### `Session` Type: `object` — A session of an embedded client. - `session_token` (`string`, req): pattern `^bts_[A-Za-z0-9_-]{43}$`; The session token (`sessionToken`), 32 random bytes in base64url after `bts_`. - `expires_at` (`string`, req): format `date-time`; The latest the session can last, 8 hours after the exchange. - `idle_timeout_seconds` (`integer`, req): An idle gap this long ends the session sooner (`401 session_expired`). - `game` (`GameSlug`, req) - `currency` (`CurrencyCode`, req) - `mode` (`string`, req): enum: `real`, `demo`; `demo` plays in `FUN`, fun money, and never touches a wallet. - `reality_check` (`RealityCheck | null`, req): The snapshotted reality-check schedule for this real-money session, or `null` when reality checks... ### `SessionRoundCreate` Type: `object` — A round to open in the session; the session gives the brand, player, game and currency. - `stake` (`Amount`, req) - `params` (`object`, req): The game's params, as in `RoundCreate` (DICE takes `DiceParams`, PACKS `PacksParams`, WHEEL... - `live_seat` (`LiveTableSeat`): STACKOPASS only, and required there: the seat at a live table the hand is bought in for... ### `StackOPassParams` Type: `object` — A STACKOPASS hand's params: the table's fixed risk `N`, the devil's `1 in N` on every pack (round 2). - `risk` (`integer`, req): enum: `9`, `5`, `3`; The table's risk. ### `LiveTableSeat` Type: `object` — A seat at a live table (STACKOPASS): the table's id, as its frames name it (`StackOPassTableId` in `asyncapi.yaml`), and the... - `table` (`string`, req): pattern `^[A-Za-z0-9_-]{22}$`; The table's id, 22 base64url characters `live` draws at random (never a counter). - `seat` (`integer`, req): range 0..5; The seat, `0.. 5` clockwise. ### `PlayerStatusSet` Type: `object` — The status to set. - `status` (`string`, req): enum: `active`, `self_excluded`, `blocked`; `self_excluded` is the player's own choice and `blocked` the operator's; both stop new rounds. ### `PlayerStatus` Type: `object` — A player's status. - `player_ref` (`PlayerRef`, req) - `status` (`string`, req): enum: `active`, `self_excluded`, `blocked`; The player's status. - `updated_at` (`string`, req): format `date-time`; When the status last changed. ### `ForceCloseRequest` Type: `object` — Which of the player's open rounds to settle. - `game` (`GameSlug`) ### `ForceCloseResult` Type: `object` — The rounds a force-close settled, and how many it left. - `rounds` (`array`, req): items 0..1000; Each round this call settled, in the order it settled them; at most 1,000 per call. - `pending` (`integer`, req): range 0..+inf; Open rounds this call left, with money in flight or past the 1,000. Call again with a new... ### `SessionBalance` Type: `object` — A player's balance, as the wallet just answered it (a demo session's fun balance). - `balance` (`Amount`, req) - `currency` (`CurrencyCode`, req) ### `LiveTicket` Type: `object` — A join ticket for one socket of a live game. - `ticket` (`string`, req): pattern `^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$`; len 0..1024; `v1..`, base64url without padding, so the whole ticket... - `expires_at` (`string`, req): format `date-time`; The payload's `exp`, 30 s after the mint. ### `LiveBetGameSlug` Type: `string` — enum: `trapdoor`, `kombat-multiplayer`, `crash` — A live game whose money goes in as a REST bet (`createLiveBet`): TRAPDOOR's, KOMBATMP's and CRASH's. ### `LiveShowIndex` Type: `integer` — range 1..9007199254740991 — A show's public id: the index of its link in the published hash chain, the `show` and `index` of its frames and of its bets'... ### `LiveBetCreate` Type: `object` — A bet on the show open for bets; the session gives the brand, player, game and currency. - `show` (`LiveShowIndex`, req) - `stake` (`Amount`, req) - `params` (`TrapdoorBetParams | KombatmpBetParams | CrashBetParams`, req): The game's params, by the path's game: TRAPDOOR's `TrapdoorBetParams`, KOMBATMP's... ### `KombatmpBetParams` Type: `object` — A KOMBATMP bet's params (the game specification to): the market, the side, the pay the client was shown and the exchange count it... - `kind` (`string`, req): enum: `win`, `flawless`, `quick_ko`, `comeback`; The market. - `side` (`string`, req): enum: `red`, `blue`; The side; `red` for every side bet. - `pay` (`string`, req): pattern `^(0|[1-9][0-9]{0,6})(\.[0-9]{1,2})?$`; The multiplier offered for this market at `at`, as the round's `prices` show it (`"1.40"`, or... - `at` (`integer`, req): range 0..31; The exchanges revealed when the offer was shown, a JSON integer literal; it must be the count... ### `KombatmpBetView` Type: `object` — A placed KOMBATMP bet (the game specification, the source's bet view): the `view` of a placed `LiveBet`, the `bet` of the... - `arena_bet_id` (`integer`, req): range 1..+inf; The bet's number among its player's bets in the round, `1, 2, …`, with gaps where a placement's... - `round_id` (`LiveShowIndex`, req) - `index` (`LiveShowIndex`, req) - `coin` (`CurrencyCode`, req) - `kind` (`string`, req): enum: `win`, `flawless`, `quick_ko`, `comeback`; The market. - `side` (`string`, req): enum: `red`, `blue`; The side (`red` for every side bet). - `at` (`integer`, req): range 0..30; The exchanges revealed when the bet was priced (`0` before exchange 1). - `pay` (`string`, req): pattern `^(1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,3})\.[0-9]{2})$`; The multiplier locked, with exactly 2 decimals, `1.01` to `9999.99`. - `stake` (`Amount`, req) - `reserved_profit` (`Amount`, req) ### `CrashBetParams` Type: `object` — A CRASH bet's params: an optional `auto_cashout`, the multiplier at which the bet cashes out on its own, as a decimal string with... - `auto_cashout` (`string | null`): pattern `^(1\.(0[1-9]|[1-9][0-9]?)|([2-9]|[1-9][0-9]{1,5})(\.[0-9]{1,2})?|1000000(\.00?)?)$`; The automatic cash-out target, `1.01` to `1000000.00`, at most 2 decimals, or `null` for none. ### `CrashBetView` Type: `object` — A placed CRASH bet: the `view` of a placed `LiveBet`, the `bet` of the bettor's `bet` frame (`CrashPlacedBet` in `asyncapi.yaml`)... - `chain_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The show's chain, the `chain` of its `lobby` frame. - `round_index` (`integer`, req): range 1..10000000; The show's chain index, `LiveBet.show` (the game specification bounds it at 10,000,000). - `bet_amt` (`Amount`, req) - `auto_cashout` (`string | null`, req): pattern `^(1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,5})\.[0-9]{2}|1000000\.00)$`; The bet's `auto_cashout` with exactly 2 decimals, or `null` when it named none. - `cap_multiplier` (`string`, req): pattern `^(1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,5})\.[0-9]{2}|1000000\.00)$`; The bet's cap `C_cap`, `min(1000000.00, 1 + ⌊100 · max_profit / stake⌋ / 100)`, with exactly 2... - `exposure` (`Amount`, req) ### `TrapdoorBetParams` Type: `object` — A TRAPDOOR bean's params: the door for gate 1 and an optional pre-plan. - `door1` (`integer`, req): range 1..3; The bean's door for gate 1 (`n_1 = 3` in both formats). - `plan` (`TrapdoorPlanInput`) ### `TrapdoorPlanInput` Type: `object | array | null` — items 0..0 — A TRAPDOOR pre-plan as a client sends it: doors for later gates and "bank after surviving gate N". - `bank_at` (`integer | null`): range 1..11; Bank after surviving this gate, or `null` for no planned bank. - `doors` (`object | array | null`): items 0..0; The door to play at each later gate, keyed by the gate as a decimal string; `[]` or `null` is no... ### `TrapdoorPlan` Type: `object` — A TRAPDOOR pre-plan as the show keeps it and answers it (the game specification, `planJson`): both keys always present, `doors`... - `bank_at` (`integer | null`, req): range 1..11; Bank after surviving this gate, or `null`. - `doors` (`object`, req): The planned door per gate `2.. G`, keyed by the gate as a decimal string. ### `TrapdoorEntryView` Type: `object` — A placed TRAPDOOR bean (the game specification, the source's entry): the `view` of a placed `LiveBet`, the `entry` of the... - `show` (`LiveShowIndex`, req) - `index` (`LiveShowIndex`, req) - `format` (`string`, req): enum: `CLASSIC`, `MEGA`; The show's format, by its index (MEGA when the index is a multiple of 10, the game specification). - `bean` (`integer`, req): range 1..1; The bean's label: its ordinal among its own player's beans in the show, so `1`, since a player... - `bet_amt` (`Amount`, req) - `cap_gate` (`integer`, req): range 1..12; The bean's cap gate, the last gate whose exact profit fits the maximum profit. - `max_multiplier` (`Multiplier`, req): `bank(cap_gate)`, the most this bean can bank, with 2 decimals. - `reserved_profit` (`Amount`, req): The profit at `max_multiplier`, the bean's exposure less its stake. - `door1` (`integer`, req): range 1..3; The door for gate 1 the bet named. - `plan` (`TrapdoorPlan`, req) ### `LiveBet` Type: `object` — A live bet as `createLiveBet` answers it. - `bet_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,48}$`; The bet's id, which is also its round id (`GET /v1/rounds/{id}`) and its wallet `round_id`. - `game` (`LiveBetGameSlug`, req) - `show` (`LiveShowIndex`, req) - `show_round_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}-[1-9][0-9]{0,15}$`; len 3..64; The show's round id, `-`: the published chain's id and the show's index, wallet-safe... - `status` (`string`, req): enum: `placed`, `pending`; `placed` (`201`): the show's journal holds the bet. - `currency` (`CurrencyCode`, req) - `stake` (`Amount`, req) - `view` (`TrapdoorEntryView | KombatmpBetView | CrashBetView | null`, req): The game's placed view, or `null` while `pending`. ### `MemeTradeBuyInCreate` Type: `object` — A buy-in to the open MEME_TRADE v2 round balance; the session gives the brand, player and currency. - `round` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}[:-][1-9][0-9]{0,15}$`; len 3..64; The open MEME_TRADE round id (`:` from the socket's `round.id` or `-`). - `amount` (`Amount`, req) ### `MemeTradeBuyIn` Type: `object` — A MEME_TRADE buy-in as `createMemeTradeBuyIn` answers it. - `show` (`LiveShowIndex`, req) - `round` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}:[1-9][0-9]{0,15}$`; len 3..64; The MEME_TRADE wire round id (`:`). - `show_round_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}-[1-9][0-9]{0,15}$`; len 3..64; The wallet-safe show round id (`-`), sent as `round_id` on wallet debits, rollbacks... - `status` (`string`, req): enum: `placed`, `pending`; `placed` (`201`): booked in `round_balance_entries`. - `currency` (`CurrencyCode`, req) - `amount` (`Amount`, req) - `balance` (`Amount | null`, req): The player's updated round balance when `placed`, or `null` while `pending`. ### `TransactionId` Type: `string` — pattern `^[A-Za-z0-9_.:-]{1,200}$` — BetPlug's id for one wallet call, deterministic and naming one attempt: a debit is `:::debit`, where... ### `WalletBalanceRequest` Type: `object` — Whose balance, in which currency. - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) ### `WalletBalance` Type: `object` — The player's balance at the wallet. - `balance` (`Amount`, req) - `currency` (`CurrencyCode`, req) - `status` (`string`, req): enum: `active`, `self_excluded`, `blocked`; The player's status at the operator. ### `WalletDebitRequest` Type: `object` — One debit attempt. - `transaction_id` (`TransactionId`, req) - `round_id` (`RoundId`, req): The round. - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) - `amount` (`Amount`, req) - `game` (`GameSlug`, req) - `brand` (`BrandId`, req) ### `WalletCreditRequest` Type: `object` — A round's one credit. - `transaction_id` (`TransactionId`, req) - `round_id` (`RoundId`, req): The round. - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) - `amount` (`Amount`, req): The round's `payout`, refund included, never `payout + refund`; for MEME_TRADE, the round balance's... - `kind` (`string`, req): enum: `payout`, `refund`; `refund` when the whole stake comes back unplayed (`refund` = `payout` = `stake`), as for a... - `game` (`GameSlug`, req) - `brand` (`BrandId`, req) ### `WalletRollbackRequest` Type: `object` — The undoing of one debit attempt. - `transaction_id` (`TransactionId`, req) - `rollback_of` (`TransactionId`, req) - `round_id` (`RoundId`, req): The `round_id` the debit carried: on a MEME_TRADE buy-in's rollback, the show round. - `player_ref` (`PlayerRef`, req) - `currency` (`CurrencyCode`, req) - `amount` (`Amount`, req) ### `WalletAnswer` Type: `object` — A booked debit, credit or rollback. - `transaction_id` (`TransactionId`, req) - `amount` (`Amount`, req) - `currency` (`CurrencyCode`, req) - `operator_transaction_id` (`string`, req): len 1..200; The wallet's own id for the booking; never empty and never our `transaction_id`. - `balance` (`Amount`, req) ### `WalletRefusal` Type: `object` — Why the wallet refused a debit. - `code` (`string`, req): enum: `insufficient_funds`, `player_blocked`, `limit_exceeded`, `invalid_request`; `limit_exceeded` is the operator's responsible-gaming limits; `invalid_request` also refuses a... - `transaction_id` (`TransactionId`, req) ### `WalletProtocolRefusal` Type: `object` — A balance read, credit or rollback the wallet cannot parse. - `code` (`string`, req): enum: `invalid_request`; The only code a balance read, credit or rollback may answer. - `transaction_id` (`TransactionId`) ### `Liveness` Type: `object` — The public liveness answer. - `ok` (`boolean`, req): Always true when the process answers. ### `ProblemCode` Type: `object` — A stable error code. ### `Problem` Type: `object` — An error, as RFC 9457 problem details, with a stable `code`. - `type` (`string`, req): format `uri`; `https://betrail.example/problems/`, a page that explains the code. - `title` (`string`, req): A short summary of the code, the same for every occurrence. - `status` (`integer`, req): range 400..599; The HTTP status, repeated. - `detail` (`string`): This occurrence, in words safe to show the caller. - `instance` (`string`): An identifier of this occurrence, to quote to support. - `code` (`ProblemCode`, req) - `max_stake` (`string`): pattern `^[0-9]+(\.[0-9]+)?$`; With `max_stake` only, the largest stake this bet takes, in the currency's units. - `elapsed_seconds` (`integer`): range 0..+inf; With `reality_check_due` only, whole seconds elapsed since the player session was created. - `net_result` (`SignedAmount`): With `reality_check_due` only, the exact settled net result (`payout - stake`) for this player... ### `PageInfo` Type: `object` — Every list answer carries it next to its `data` array. - `next_cursor` (`string | null`, req): Pass it as `cursor` to fetch the next page; null on the last page. ## AsyncAPI component schemas All object schemas enforce strict JSON decoding (`additionalProperties: false`). Compact field reference below; extended prose notes are in `/docs/api-reference.md` and `/api/asyncapi.yaml`. ### `WebhookHeaders` Type: `object` — The headers of every webhook delivery; the signature is the webhookSignature scheme's. - `Betrail-Webhook-Id` (`string`, req): The event id; the same on every retry, so a receiver drops duplicates by it. - `Betrail-Timestamp` (`string`, req): pattern `^[0-9]{10}$`; Unix time in seconds when this delivery was signed. - `Betrail-Nonce` (`string`, req): pattern `^[A-Za-z0-9_-]{16,64}$`; New on every delivery attempt (the outbox row's id with its attempt); a receiver refuses one it has... - `Betrail-Signature` (`string`, req): pattern `^v1=[0-9a-f]{64}(,v1=[0-9a-f]{64})?$`; See the webhookSignature scheme. ### `Amount` Type: `string` — pattern `^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$` — An amount in the currency's units, as a decimal string at the currency's scale (as in the REST API). ### `UsdAmount` Type: `string` — pattern `^-?(0|[1-9][0-9]{0,15})\.[0-9]{6}$` — A USD amount of BetPlug's credits, with exactly 6 decimals; it is negative when credits are below 0. ### `RoundSettledEvent` Type: `WebhookEvent & object` — A round.settled event. - `allOf[1]`: - `type` (`"round.settled"`, req): const `"round.settled"` - `data` (`object`, req): The REST API's `Round` (api/openapi.yaml), with `status` settled. - `allOf`: `WebhookEvent` ### `CreditsLowEvent` Type: `WebhookEvent & object` — A credits.low event, sent once each time the balance crosses below the threshold. - `allOf[1]`: - `type` (`"credits.low"`, req): const `"credits.low"` - `environment` (`"live"`, req): const `"live"`; Always `live`. - `data` (`object`, req): The operator's credits in USD, with exactly 6 decimals (micro-USD). - `allOf`: `WebhookEvent` ### `CreditsExhaustedEvent` Type: `WebhookEvent & object` — A credits.exhausted event, sent once each time a posting takes the operator's credits from above 0 to 0 or below. - `allOf[1]`: - `type` (`"credits.exhausted"`, req): const `"credits.exhausted"` - `environment` (`"live"`, req): const `"live"`; Always `live`. - `data` (`object`, req): The operator's credits in USD, with exactly 6 decimals (micro-USD), in the same shape as... - `allOf`: `WebhookEvent` ### `LiveFrame` Type: `object` — The envelope of every frame BetPlug sends on a live socket. - `type` (`string`, req): The frame type (welcome, snapshot, round, step, result, paid, ack, error); each game's spec lists... - `game` (`string`, req): The game's slug. - `seq` (`integer`, req): range 0..+inf; Increases by one per frame on this socket, so a client sees a gap and asks for a snapshot. - `at` (`integer`, req): Unix milliseconds: the time of the one thing that caused the frame, never a time `live` reached... - `request_id` (`string`): On an ack or an error, the request id of the command it answers. - `data` (`object`): The frame's body, per game and type. ### `LiveCommand` Type: `object` — The envelope of every command a player sends on a live socket. - `type` (`string`, req): The command type. - `request_id` (`string`, req): len 1..64; Chosen by the client; a repeated id gets the first answer again (each game says for how long). - `data` (`object`): The command's body, per game and type. ### `LiveSettledFrame` Type: `LiveFrame & object` — The frame that tells a player their bet settled: the `LiveFrame` envelope, whose `type` the game's spec names, with a... - `allOf[1]`: - `data` (`LiveSettlement`, req) - `allOf`: `LiveFrame` ### `LiveSettlement` Type: `object` — How a live bet's settlement reads: the `data` of the frame that tells its player. - `bet_id` (`string`, req): len 1..64; The bet's id (for MEME_TRADE, the player-round's or the sidebet's). - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The bet's currency. - `stake` (`Amount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`, req) - `settled_by` (`string`, req): enum: `play`, `force_close`, `outage`; Which of the three paths settled the bet. - `view` (`object`, req): The game's settled view (its spec's `game_result`). ### `WebhookEvent` Type: `object` — The envelope of every webhook event. - `id` (`string`, req): The event id (also in `Betrail-Webhook-Id`). - `type` (`string`, req): The event type (round.settled, credits.low, credits.exhausted). - `created_at` (`string`, req): format `date-time`; When the event happened. - `environment` (`string`, req): enum: `sandbox`, `live`; The environment it happened in. - `data` (`object`, req): The event's body, per type. ### `LiveSelfBet` Type: `object` — One of the authenticated viewer's own bets on a shared show. - `bet_id` (`string`, req): len 1..64; The bet's id. - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The bet's currency. - `stake` (`Amount`, req) - `payout` (`Amount`) - `settled` (`boolean`, req): Whether the bet has settled. ### `LiveCurrencyAggregate` Type: `object` — Coarse anonymous stake total in one currency over the viewer's operator's bets. - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The currency code. - `bets_count` (`integer`, req): range 1..+inf; How many bets make up `total_stake`. - `total_stake` (`Amount`, req) ### `MemeTradePrice` Type: `string` — pattern `^(0|[1-9][0-9]*)\.[0-9]{12}$` — A price on MEME_TRADE v2's path in units of the 1.00x start price, formatted as an exact decimal string with 12 fractional digits... ### `MemeTradeRoundId` Type: `string` — pattern `^[A-Za-z0-9_-]{1,43}:[0-9]{1,20}$`; len 3..64 — MEME_TRADE v2's wire round identifier (`:`; distinct from the wallet-safe show round id `-`). ### `MemeTradePlayer` Type: `object` — Projected player identity on MEME_TRADE's wire. - `id` (`string`, req): The value `"self"` for the authenticated viewer, or `""` for an unseated spectator in `me.player`. - `name` (`string`, req): The value `"self"` for the authenticated viewer, or `""` for an unseated spectator in `me.player`. - `level` (`integer`, req): range 0..+inf; Display level (`0` in BetPlug's projection). - `avatarUrl` (`string`): Optional avatar URL when set. ### `MemeTradeCoinConfig` Type: `object` — One coin's precision and per-bet limits on MEME_TRADE's wire, in coin units. - `code` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The currency code. - `name` (`string`, req): len 1..inf; Display name of the coin. - `decimals` (`integer`, req): range 0..8; Fractional digits `d` of an atom in coin units. - `minBet` (`Amount`, req) - `maxBet` (`Amount`, req) - `maxProfit` (`Amount`, req) - `usdPrice` (`string`, req): pattern `^(0|[1-9][0-9]*)(\.[0-9]+)?$`; Display-only USD reference price as a decimal string. ### `MemeTradeLink` Type: `object` — A round's pre-committed hash-chain link as published. - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The published hash chain's id (`:` is the wire round id). - `index` (`integer`, req): range 1..9007199254740991; 1-based link index `i` in the chain. - `commit` (`string`, req): pattern `^[0-9a-f]{64}$`; Lowercase hex SHA-256 commitment `s_{i-1} = sha256_hex(s_i)`. - `salt` (`string`, req): pattern `^[0-9a-f]{64}$`; Lowercase hex public salt fixed before link 1 opened. - `salt_source` (`string`, req): len 1..inf; Pre-announced external salt source (such as `bitcoin:`). ### `MemeTradeRoundInfo` Type: `object` — Public state of a MEME_TRADE v2 round. - `id` (`MemeTradeRoundId`, req) - `link` (`MemeTradeLink`, req) - `presaleEndsAt` (`integer`, req): Unix time in milliseconds when the 10 s presale ends. - `startedAt` (`integer | null`, req): Unix time in milliseconds when active ticks began, or `null` during presale. - `tick` (`integer`, req): range 0..+inf; The last tick played: `0` in the presale and after `start` until the first tick, then the `tick` of... - `price` (`MemeTradePrice`, req) - `peak` (`MemeTradePrice`, req) - `rugTick` (`integer | null`, req): range 1..+inf; Tick at which the round rugged, or `null` before the rug. - `serverSeed` (`string | null`, req): pattern `^[0-9a-f]{64}$`; Revealed 64-hex server seed `s_i` once rugged, or `null` before the rug. ### `MemeTradeCandle` Type: `object` — One OHLC summary candle of a finished round's integer price path. - `index` (`integer`, req): range 0..+inf; 0-based candle index. - `startTick` (`integer`, req): range 0..+inf; First tick covered by the candle. - `endTick` (`integer`, req): range 0..+inf; Last tick covered by the candle. - `open` (`MemeTradePrice`, req) - `high` (`MemeTradePrice`, req) - `low` (`MemeTradePrice`, req) - `close` (`MemeTradePrice`, req) - `closed` (`boolean`, req): Whether the candle is complete. - `god` (`boolean`, req): Whether the candle contains a god jump (`next >= 5 * prev`). - `rug` (`boolean`, req): Whether the candle ends on the rug tick. ### `MemeTradeRoundSummary` Type: `object` — Summary of an ended MEME_TRADE v2 round in `rug.summary` and `snapshot.history`: its whole price path, which the `rug` frame... - `id` (`MemeTradeRoundId`, req) - `link` (`MemeTradeLink`, req) - `peak` (`MemeTradePrice`, req) - `rugTick` (`integer`, req): range 1..+inf; Tick at which the round's path rugs; a round an outage aborted ended before it... - `rugPrice` (`MemeTradePrice`, req) - `miniCandles` (`array`, req): Downsampled OHLC candles of the round's path. - `serverSeed` (`string`, req): pattern `^[0-9a-f]{64}$`; Revealed 64-hex server seed `s_i` (`sha256_hex(s_i) == link.commit`). - `endedAt` (`integer`, req): Unix time in milliseconds when the round ended: its rug in play, or the outage abort. ### `MemeTradePosition` Type: `object` — A player's position in fixed-point coin units: `initialMargin` has `d + 4` fractional digits, `margin` (signed after funding) and... - `side` (`string`, req): enum: `long`, `short`; Position direction. - `leverage` (`integer`, req): range 1..5; Integer leverage `1..5`. - `units` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Display-only exposure in coin units per `1.00x`, floored to `d + 8` decimals. - `entry` (`MemeTradePrice`, req) - `margin` (`string`, req): pattern `^-?(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Exact signed margin `G` in coin units with `d + 8` decimals (`G` may go negative while in profit). - `initialMargin` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{4,12}$`; Exact initial margin `M` of the held units in coin units with `d + 4` decimals. - `invested` (`Amount`, req) - `realized` (`Amount`, req) - `fundingPaid` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Exact cumulative funding paid `F` in coin units with `d + 8` decimals. - `buys` (`integer`, req): range 0..+inf; Number of opens/adds in this player-round. - `sells` (`integer`, req): range 0..+inf; Number of closes in this player-round. - `openedTick` (`integer`, req): range 0..+inf; Tick at which the current position opened (`0` in presale). - `lastTradeTick` (`integer`, req): range 0..+inf; Tick of the most recent fill (`0` in presale). ### `MemeTradePositionWithCoin` Type: `object` — A player's position paired with its coin code (`me.position` and `position.position`). - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The position's currency code. - `side` (`string`, req): enum: `long`, `short`; Position direction. - `leverage` (`integer`, req): range 1..5; Integer leverage `1..5`. - `units` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Display-only exposure in coin units per `1.00x`, floored to `d + 8` decimals. - `entry` (`MemeTradePrice`, req) - `margin` (`string`, req): pattern `^-?(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Exact signed margin `G` in coin units with `d + 8` decimals (`G` may go negative while in profit). - `initialMargin` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{4,12}$`; Exact initial margin `M` of the held units in coin units with `d + 4` decimals. - `invested` (`Amount`, req) - `realized` (`Amount`, req) - `fundingPaid` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Exact cumulative funding paid `F` in coin units with `d + 8` decimals. - `buys` (`integer`, req): range 0..+inf; Number of opens/adds in this player-round. - `sells` (`integer`, req): range 0..+inf; Number of closes in this player-round. - `openedTick` (`integer`, req): range 0..+inf; Tick at which the current position opened (`0` in presale). - `lastTradeTick` (`integer`, req): range 0..+inf; Tick of the most recent fill (`0` in presale). ### `MemeTradePlayerSnapshot` Type: `object` — The viewer's own seated entry in `snapshot.players` or `players.players` (`player.id == "self"`). - `player` (`MemeTradePlayer`, req) - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The seat's currency code. - `position` (`MemeTradePosition`, req) - `rugged` (`boolean`, req): Whether the held long was lost on the rug. - `liquidated` (`boolean`, req): Whether the held leveraged position was liquidated. ### `MemeTradeTrade` Type: `object` — One fill (`open`, `close`, or `liquidation`), sent only to the trader who owns it (`player.id == "self"`). - `id` (`string`, req): len 1..inf; Deterministic per-player fill id within the round (`t--`, counting this player's own... - `roundId` (`MemeTradeRoundId`, req) - `player` (`MemeTradePlayer`, req) - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The trade's currency code. - `side` (`string`, req): enum: `buy`, `sell`; Market order side (`buy` or `sell`). - `kind` (`string`, req): enum: `open`, `close`, `liquidation`; Fill kind. - `direction` (`string`, req): enum: `long`, `short`; Position direction (`long` or `short`). - `leverage` (`integer`, req): range 1..5; Position leverage `1..5`. - `tick` (`integer`, req): range 0..+inf; Fill tick (`0` in presale). - `price` (`MemeTradePrice`, req) - `amount` (`Amount`, req) - `units` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Display-only units filled at `d + 8` decimals. - `presale` (`boolean`, req): Whether the fill happened during presale (`1.00x`). - `auto` (`boolean`, req): Whether the fill is a close the server made on a trigger of its own: `true` on a take-profit,... - `at` (`integer`, req): Server fill timestamp in Unix milliseconds. - `fraction` (`string`): pattern `^(0\.[0-9]{4}|1\.0000)$`; Requested close fraction `k / 10,000` with 4 decimals (`"1.0000"` on a full or dust close; omitted... - `pnl` (`string`): pattern `^-?(0|[1-9][0-9]*)\.[0-9]{4,12}$`; Display-only realized PnL of a close or liquidation in coin units with `d + 4` decimals (omitted on... - `autoReason` (`string`): enum: `takeProfit`, `stopLoss`, `forceClose`; Automatic close trigger when set (`takeProfit`, `stopLoss`, or `forceClose`). ### `MemeTradeSidebet` Type: `object` — One 40-tick `4.67x` rug sidebet. - `id` (`string`, req): len 1..inf; Deterministic per-player sidebet id within the round (`sb--`, counting this player's... - `roundId` (`MemeTradeRoundId`, req) - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The sidebet's currency code. - `amount` (`Amount`, req) - `placedTick` (`integer`, req): range 0..+inf; Tick at which the sidebet was placed (`0` in presale). - `endTick` (`integer`, req): range 1..+inf; Last tick on which a rug wins the sidebet (`placedTick + 40`). - `payout` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; Sidebet payout multiplier with 2 decimals (`"4.67"`). - `status` (`string`, req): enum: `open`, `won`, `lost`; Current sidebet status. - `settledTick` (`integer | null`, req): range 1..+inf; Tick at which the sidebet won or expired, or `null` while `open`. ### `MemeTradeAutoSell` Type: `object` — Armed take-profit multiple (`1.10..10.00`) and stop-loss share (`0.05..0.90`), each `null` when off. - `multiple` (`string | null`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; Take-profit multiple with 2 decimals (`"1.10"` to `"10.00"`), or `null` when off. - `stopLoss` (`string | null`, req): pattern `^0\.[0-9]{2}$`; Stop-loss share with 2 decimals (`"0.05"` to `"0.90"`), or `null` when off. ### `MemeTradeMe` Type: `object` — The connecting viewer's own state inside `MemeTradeSnapshot`. - `player` (`MemeTradePlayer`, req) - `balances` (`object`, req): Round balances keyed by currency code, formatted as `Amount` strings. - `position` (`MemeTradePositionWithCoin | null`, req): The viewer's position in the current round, or `null` if never seated in it. - `sidebet` (`MemeTradeSidebet | null`, req): The viewer's latest sidebet in the current round, or `null` if none. - `autoSell` (`MemeTradeAutoSell | null`, req): The viewer's armed take-profit / stop-loss setting, or `null` when both are off. ### `MemeTradeSnapshot` Type: `object` — MEME_TRADE v2's show snapshot (`version: 3`), projected per viewer inside `MemeTradeProjectedSnapshot.show`: `prices` holds... - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `version` (`integer`, req): const `3`; MEME_TRADE v2's wire version (`3`). - `serverTime` (`integer`, req): Server time in Unix milliseconds. - `phase` (`string`, req): enum: `presale`, `active`, `rugged`; Current round phase. - `round` (`MemeTradeRoundInfo`, req) - `prices` (`array`, req): Revealed prices `P_0..P_tick` (`["1.000000000000"]` in presale). - `players` (`array`, req): items 0..1; Projected seated list containing `[self]` when seated or `[]` otherwise. - `history` (`array`, req): Recent finished rounds, newest first. - `coins` (`array`, req): Active coins and their limits in this round. - `me` (`MemeTradeMe`, req) ### `MemeTradeProjectedSnapshot` Type: `object` — `data` of a `snapshot` frame on `/v1/live/meme-trade` while a round is open: the viewer-projected `MemeTradeSnapshot` under... - `show` (`MemeTradeSnapshot`, req) - `self_bets` (`array`): Viewer's own tracked show bets when present. - `operator_totals` (`array`): Anonymous stake totals over the viewer's operator's bets when present. ### `MemeTradeIdleSnapshot` Type: `object` — `data` of a `snapshot` answer on `/v1/live/meme-trade` during the hold between rounds when no round is open. - `phase` (`"idle"`, req): const `"idle"`; Always `idle`. ### `MemeTradePresale` Type: `object` — `data` of a `presale` broadcast opening a new MEME_TRADE v2 round (`round.serverSeed` and `round.rugTick` are `null`). - `type` (`"presale"`, req): const `"presale"`; Always `presale`. - `serverTime` (`integer`, req): Server time in Unix milliseconds. - `round` (`MemeTradeRoundInfo`, req) ### `MemeTradeStart` Type: `object` — `data` of a `start` broadcast closing the 10 s presale and beginning active ticks. - `type` (`"start"`, req): const `"start"`; Always `start`. - `serverTime` (`integer`, req): Server time in Unix milliseconds. - `roundId` (`MemeTradeRoundId`, req) - `startedAt` (`integer`, req): Unix time in milliseconds when active play began. ### `MemeTradeTick` Type: `object` — `data` of a `tick` broadcast publishing `P_tick` (`tick >= 1`). - `type` (`"tick"`, req): const `"tick"`; Always `tick`. - `serverTime` (`integer`, req): Server time in Unix milliseconds. - `roundId` (`MemeTradeRoundId`, req) - `tick` (`integer`, req): range 1..+inf; 1-based tick index. - `price` (`MemeTradePrice`, req) ### `MemeTradeRug` Type: `object` — `data` of a `rug` broadcast ending the round and revealing its `serverSeed` `s_i`. - `type` (`"rug"`, req): const `"rug"`; Always `rug`. - `serverTime` (`integer`, req): Server time in Unix milliseconds. - `roundId` (`MemeTradeRoundId`, req) - `tick` (`integer`, req): range 0..+inf; The tick at which the round ended: the rug tick in play (always >= 1), or, when an outage aborted... - `price` (`MemeTradePrice`, req): The price at `tick`: the rug price in play, or the last published price when an outage aborted the... - `peak` (`MemeTradePrice`, req): The highest price on the round's whole path. - `serverSeed` (`string`, req): pattern `^[0-9a-f]{64}$`; Revealed 64-hex server seed `s_i` (`sha256_hex(s_i) == summary.link.commit`). - `summary` (`MemeTradeRoundSummary`, req): The round's summary. ### `MemeTradeTradeMsg` Type: `object` — `data` of a player-directed `trade` frame reporting one fill (`trade.player.id == "self"`). - `type` (`"trade"`, req): const `"trade"`; Always `trade`. - `trade` (`MemeTradeTrade`, req) ### `MemeTradePlayers` Type: `object` — `data` of a player-projected `players` frame (`[self]` when holding a seat, `[]` otherwise; never another player). - `type` (`"players"`, req): const `"players"`; Always `players`. - `roundId` (`MemeTradeRoundId`, req) - `players` (`array`, req): items 0..1; Projected seated entry for this viewer (`[self]` or `[]`). ### `MemeTradeSidebetMsg` Type: `object` — `data` of a player-directed `sidebet` frame (`playerId == "self"`). - `type` (`"sidebet"`, req): const `"sidebet"`; Always `sidebet`. - `roundId` (`MemeTradeRoundId`, req) - `playerId` (`string`, req): const `"self"`; Always `"self"` after per-player projection. - `sidebet` (`MemeTradeSidebet`, req) ### `MemeTradeBalance` Type: `object` — `data` of a player-directed `balance` frame updating the player's round balance in `coin`. - `type` (`"balance"`, req): const `"balance"`; Always `balance`. - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The round balance's currency code. - `balance` (`Amount`, req) ### `MemeTradeAckError` Type: `object` — Refusal carried by `MemeTradeAck.error` (`insufficient_balance`, `below_min`, `above_max`, `max_profit`, `wrong_phase`,... - `code` (`string`, req): len 1..64; Machine-readable refusal code. - `message` (`string`, req): len 1..inf; Human-readable explanation of the refusal. - `reason` (`string`): enum: `tick_barrier_fenced`, `not_applied`, `tombstoned`, `request_voided`, `duplicate_request`; Why a `pending` refusal was not applied, and so whether to send it again under a new id: every... ### `MemeTradeAck` Type: `object` — `data` of an `ack` frame answering an in-round MEME_TRADE socket command (`LiveFrame.request_id == requestId`). - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `requestId` (`string`, req): len 1..64; Echoed `request_id` of the command it answers. - `ok` (`boolean`, req): `true` when committed, `false` when refused (`error` gives the code). - `error` (`MemeTradeAckError`) ### `MemeTradePositionMsg` Type: `object` — `data` of a player-directed `position` frame (`null` when not seated). - `type` (`"position"`, req): const `"position"`; Always `position`. - `roundId` (`MemeTradeRoundId`, req) - `position` (`MemeTradePositionWithCoin | null`, req): Updated position with its coin, or `null` when not seated. ### `MemeTradeAutoSellMsg` Type: `object` — `data` of a player-directed `autoSell` frame confirming the armed take-profit / stop-loss (`null` when cleared). - `type` (`"autoSell"`, req): const `"autoSell"`; Always `autoSell`. - `autoSell` (`MemeTradeAutoSell | null`, req): Armed take-profit / stop-loss setting, or `null` when both are cleared. ### `MemeTradeSkippedLink` Type: `object` — `data` of a `skipped_link` broadcast published when chain index `link.index`'s integer price path would exceed int64... - `type` (`"skipped_link"`, req): const `"skipped_link"`; Always `skipped_link`. - `link` (`MemeTradeLink`, req) - `serverSeed` (`string`, req): pattern `^[0-9a-f]{64}$`; Revealed 64-hex server seed `s_i` whose path overflowed int64 (`sha256_hex(s_i) == link.commit`). - `tick` (`integer`, req): range 1..+inf; 1-based tick at which `P_tick` exceeded `2^63 - 1`. ### `LiveHubAck` Type: `object` — `data` of the hub's command-envelope `ack` frame (`{"committed": true}` once a two-phase plan commits, or `{"committed": false}`... - `committed` (`boolean`, req): Whether the two-phase command plan committed. ### `MemeTradeAborted` Type: `object` — `data` of an `aborted` broadcast emitted after `rug` when the automatic outage rule ends an open MEME_TRADE v2 round (platform... - `type` (`"aborted"`, req): const `"aborted"`; Always `aborted`. - `round_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}-[0-9]{1,20}$`; Public wallet-safe show round id (`-`). - `step` (`integer`, req): range 0..+inf; Last committed show step before the outage rule ended the round. - `reason` (`string`, req): enum: `heartbeat_expired`, `step_timeout`; Automatic outage condition that triggered the abort. - `commit` (`string`, req): pattern `^[0-9a-f]{64}$`; Committed 64-hex hash `s_{i-1} = sha256_hex(seed)`. - `seed` (`string`, req): pattern `^[0-9a-f]{64}$`; Revealed 64-hex server seed `s_i`. ### `MemeTradeSidebetDetail` Type: `object` — Sidebet detail carried inside `MemeTradeRecordView.sidebet` on a settled sidebet record. - `amount` (`Amount`, req) - `placed_tick` (`integer`, req): range 0..+inf; Tick at which the sidebet was placed (`0` in presale). - `end_tick` (`integer`, req): range 1..+inf; Last tick on which a rug wins the sidebet (`placed_tick + 40`). - `payout` (`string`, req): pattern `^(0|[1-9][0-9]*)\.[0-9]{2}$`; Sidebet payout multiplier with 2 decimals (`"4.67"`). - `status` (`string`, req): enum: `open`, `won`, `lost`; Settled sidebet status. - `settled_tick` (`integer`): range 1..+inf; Tick at which the sidebet won or expired (omitted when unset). ### `MemeTradeRecordView` Type: `object` — `view` of a MEME_TRADE v2 player-round or sidebet `Record`. - `v` (`integer`, req): const `3`; MEME_TRADE v2's record view version (`3`). - `kind` (`string`, req): enum: `position`, `sidebet`; Whether the record settles a player-round position book or one sidebet. - `round_id` (`MemeTradeRoundId`, req) - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; Currency code of the record. - `invested` (`Amount`, req) - `returned` (`Amount`, req) - `profit` (`string`): pattern `^-?(0|[1-9][0-9]*)(\.[0-9]{1,8})?$`; Signed net profit (`returned − invested`) at the coin's decimals when present. - `tick` (`integer`, req): range 0..+inf; Tick at which this record step settled. - `price` (`MemeTradePrice`) - `side` (`string`): enum: `long`, `short`; Last position direction when a position was opened. - `leverage` (`integer`): range 1..5; Last position leverage `1..5` when a position was opened. - `entry` (`MemeTradePrice`) - `margin` (`string`): pattern `^-?(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Signed margin `G` at `d + 8` decimals when present. - `initial_margin` (`string`): pattern `^(0|[1-9][0-9]*)\.[0-9]{4,12}$`; Initial margin `M` at `d + 4` decimals when present. - `funding_paid` (`string`): pattern `^(0|[1-9][0-9]*)\.[0-9]{8,16}$`; Cumulative funding paid `F` at `d + 8` decimals when present. - `buys` (`integer`): range 0..+inf; Number of opens in the player-round when present. - `sells` (`integer`): range 0..+inf; Number of closes in the player-round when present. - `opened_tick` (`integer`): range 0..+inf; Tick at which the position opened when present. - `last_trade_tick` (`integer`): range 0..+inf; Tick of the most recent fill when present. - `held` (`boolean`): Whether a position remained open when present. - `rugged` (`boolean`): Whether a held long was lost on the rug when present. - `liquidated` (`boolean`): Whether a held leveraged position was liquidated when present. - `capped` (`boolean`): Whether payout was truncated at `max_profit` when present. - `ended_by` (`string`): Terminal trigger of the record when present. - `sidebet` (`MemeTradeSidebetDetail`) - `peak` (`MemeTradePrice`) - `rug_tick` (`integer`): range 1..+inf; Revealed rug tick once rugged. - `rug_price` (`MemeTradePrice`) - `scheme` (`string`, req): len 1..inf; Fairness scheme identifier. - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; Published hash chain id. - `index` (`integer`, req): range 1..9007199254740991; 1-based link index in the chain. - `server_seed_hash` (`string`, req): pattern `^[0-9a-f]{64}$`; Committed 64-hex hash `s_{i-1}`. - `server_seed` (`string`): pattern `^[0-9a-f]{64}$`; Revealed 64-hex server seed `s_i` once rugged. - `external_hash` (`string`, req): pattern `^[0-9a-f]{64}$`; Public salt hex fixed before link 1 opened. - `salt_source` (`string`, req): len 1..inf; Pre-announced external salt source. ### `MemeTradeSettlement` Type: `object` — `data` of a player-directed `settled` frame on `/v1/live/meme-trade`: a `LiveSettlement` whose `view` is `MemeTradeRecordView`... - `bet_id` (`string`, req): len 1..64; Settled bet or player-round id. - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; Settlement currency code. - `stake` (`Amount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`, req) - `settled_by` (`string`, req): enum: `play`, `force_close`, `outage`; Settlement path (`play` in MEME_TRADE v2). - `view` (`MemeTradeRecordView`, req) ### `MemeTradeFrameData` Type: `MemeTradeProjectedSnapshot | MemeTradeIdleSnapshot | MemeTradePresale | MemeTradeStart | MemeTradeTick | MemeTradeRug | MemeTradeTradeMsg | MemeTradePlayers | MemeTradeSidebetMsg | MemeTradeBalance | MemeTradeAck | LiveHubAck | LiveHubError | MemeTradePositionMsg | MemeTradeAutoSellMsg | MemeTradeSkippedLink | MemeTradeAborted | MemeTradeSettlement` — Union of MEME_TRADE v2's per-game `LiveFrame.data` payloads. - `oneOf`: `MemeTradeProjectedSnapshot` | `MemeTradeIdleSnapshot` | `MemeTradePresale` | `MemeTradeStart` | `MemeTradeTick` | `MemeTradeRug` | `MemeTradeTradeMsg` | `MemeTradePlayers` | `MemeTradeSidebetMsg` | `MemeTradeBalance` | `MemeTradeAck` | `LiveHubAck` | `LiveHubError` | `MemeTradePositionMsg` | `MemeTradeAutoSellMsg` | `MemeTradeSkippedLink` | `MemeTradeAborted` | `MemeTradeSettlement` ### `MemeTradeFrame` Type: `LiveFrame & object` — A server-to-client frame on `/v1/live/meme-trade` (`game: "meme-trade"`), carrying one of MEME_TRADE v2's frame bodies in `data`. - `allOf[1]`: - `game` (`"meme-trade"`, req): const `"meme-trade"`; Always `meme-trade`. - `data` (`MemeTradeFrameData`, req) - `allOf`: `LiveFrame` ### `LiveIdleSnapshot` Type: `object` — `data` of a `snapshot` answer on any live game's socket while no show is open (TRAPDOOR's between shows). - `phase` (`"idle"`, req): const `"idle"`; Always `idle`. ### `LiveHubError` Type: `object` — `data` of an `error` frame that `live` itself sends, before any show sees the command: a malformed envelope, a `request_id` in... - `code` (`string`, req): pattern `^[a-z][a-z0-9_]*$`; An engine code (`invalid_input`, `invalid_action`, `pending`, `limit`, `closed`,...). - `detail` (`string`, req): len 1..inf; The refusal in words safe to show the player. ### `KombatmpSocketRequestId` Type: `string` — len 1..64 — A KOMBATMP socket command's `request_id`, chosen by the client: 1 to 64 bytes of UTF-8 (`live` counts bytes) that do not start... ### `KombatmpBetRequestId` Type: `string` — pattern `^Bet:[A-Za-z0-9_-]{1,48}:[1-9][0-9]{0,4}$`; len 0..64 — A REST bet's request id in the round, `Bet::` (the same form as `TrapdoorBetRequestId`): `` is... ### `KombatmpRoundIndex` Type: `integer` — range 1..9007199254740991 — A KOMBATMP round's public id: the index of its link in the published hash chain, which the source's database id was. ### `KombatmpHex` Type: `string` — pattern `^[0-9a-f]{64}$` — 64 lowercase hex characters (a seed, a commitment or a salt). ### `KombatmpPay` Type: `string` — pattern `^(1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,3})\.[0-9]{2})$` — A multiplier a KOMBATMP bet is offered or locked at, with exactly 2 decimals, from `1.01` to `9999.99` (the game specification: a... ### `KombatmpHP` Type: `array` — items 2..2 — `[red, blue]`, each fighter's hit points, from its card's `red_hp` or `blue_hp` (at most 30) down to `0` for a fighter knocked... ### `KombatmpCard` Type: `object` — A round's card (the game specification, `cardView`), drawn from words 0 to 2 of the round's stream when it opens and public at... - `fighter` (`string`, req): enum: `doge`, `wojak`, `cat`; Red's fighter skin (cosmetic). - `fighter_name` (`string`, req): enum: `Karate Doge`, `Boxer Wojak`, `Ninja Cat`; Red's fighter's name. - `rung` (`integer`, req): range 1..3; Blue's rung on the ladder; with the duration it picks the round's paytable (one of 21). - `opponent` (`string`, req): enum: `paper-hands-pete`, `rug-puller`, `gas-fee-golem`; Blue's fighter, by its rung (1, 2, 3 in this order). - `opponent_name` (`string`, req): enum: `Paper Hands Pete`, `Rug Puller`, `Gas Fee Golem`; Blue's fighter's name. - `duration` (`integer`, req): enum: `15`, `20`, `25`, `30`, `35`, `40`, `45`; The regulation duration `D` in seconds. - `max_exchanges` (`integer`, req): range 10..30; `N(D)`, the regulation exchanges; a tie at the bell adds one sudden-death exchange. - `beat_ms` (`integer`, req): range 1500..1563; The milliseconds between two steps of the fight. - `red_hp` (`integer`, req): range 10..30; Red's starting hit points. - `blue_hp` (`integer`, req): range 6..30; Blue's starting hit points. - `quick_ko` (`integer`, req): range 8..24; A Red KO at this exchange or before wins `quick_ko`. - `low_hp` (`integer`, req): range 2..6; A Red win with this many hit points or fewer left wins `comeback`. ### `KombatmpPrices` Type: `object` — The offers at the fight's public state after `n` exchanges (the game specification, `priceView`): the winner quote for each side,... - `n` (`integer`, req): range 0..30; The exchanges revealed, the `at` a bet at these offers names. - `red` (`KombatmpPay | null`, req): Red's winner quote, or `null` when not offered. - `blue` (`KombatmpPay | null`, req): Blue's winner quote, or `null` when not offered. - `sides` (`object`, req): The offered Red side bets and their pays, before the bell only; a dropped side bet is absent. ### `KombatmpExchangeView` Type: `object` — One revealed exchange (the game specification, `exchangeView`): its number `n`, who landed it, the move and its damage (`jab` 1,... - `n` (`integer`, req): range 1..31; The exchange's number, `1.. N(D) + 1`. - `by` (`string`, req): enum: `red`, `blue`; Who landed the blow. - `move` (`string`, req): enum: `jab`, `kick`, `special`; The blow. - `dmg` (`integer`, req): range 1..3; Its damage, by the move. - `hp` (`KombatmpHP`, req) - `sudden_death` (`boolean`, req): Whether the blow was struck in sudden death (it then ends the fight). ### `KombatmpEndView` Type: `object` — How a fight ended (the game specification, `endView`): the winner, `ended_by` (`KO` the moment a fighter's hit points reach 0,... - `winner` (`string`, req): enum: `red`, `blue`; The winner. - `ended_by` (`string`, req): enum: `KO`, `DECISION`, `SUDDEN_DEATH`; How the fight ended. - `n` (`integer`, req): range 2..31; The exchanges the fight took (a KO needs at least 2; sudden death ends at `N(D) + 1`). - `hp` (`KombatmpHP`, req) - `flags` (`object`, req): Which Red side bets the fight won. ### `KombatmpRound` Type: `object` — `data` of the `round` broadcast that opens a round for bets: its id, the link's public part (the seed `s_i` stays in the writer... - `type` (`"round"`, req): const `"round"`; Always `round`. - `round_id` (`KombatmpRoundIndex`, req) - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The published hash chain's id. - `index` (`KombatmpRoundIndex`, req) - `commit` (`KombatmpHex`, req): The link's commitment `s_{i-1} = sha256_hex(s_i)`, published before the chain's first round. - `salt` (`KombatmpHex`, req): The chain's public salt, a block hash fixed after the commitment. - `salt_source` (`string`, req): len 1..inf; Where the salt comes from (`bitcoin:`). - `card` (`KombatmpCard`, req) - `prices` (`KombatmpPrices`, req) - `bell_at` (`integer`, req): Unix time in milliseconds when the bell is due, 10,000 ms after the round opened. - `now` (`integer`, req): The round's clock when it opened, Unix milliseconds. ### `KombatmpBell` Type: `object` — `data` of the `bell` broadcast: the fight starts, nothing is revealed yet (`n` stays `0`), the side bets are closed... - `type` (`"bell"`, req): const `"bell"`; Always `bell`. - `round_id` (`KombatmpRoundIndex`, req) - `now` (`integer`, req): The bell's time, `bell_at`, Unix milliseconds; `live` sends the frame after the pre-fight grace, at... - `next_at` (`integer`, req): When exchange 1 is due, `now` plus the card's `beat_ms`. ### `KombatmpExchange` Type: `object` — `data` of the `x` broadcast that reveals one exchange, drawn at that step and never before (every bet priced at the exchange... - `type` (`"x"`, req): const `"x"`; Always `x`. - `round_id` (`KombatmpRoundIndex`, req) - `now` (`integer`, req): When the exchange was revealed, Unix milliseconds. - `exchange` (`KombatmpExchangeView`, req) - `phase` (`string`, req): enum: `FIGHT`, `SUDDEN_DEATH`; The fight's phase after this exchange. - `prices` (`KombatmpPrices | null`, req): The offers after this exchange (`prices.n` is its `n`), or `null` when it ended the fight. - `next_at` (`integer | null`, req): When the next exchange is due, or `null` when this one ended the fight. ### `KombatmpEnd` Type: `object` — `data` of the `end` broadcast after the blow that ends the fight: how it ended, and when the next round may open. - `type` (`"end"`, req): const `"end"`; Always `end`. - `round_id` (`KombatmpRoundIndex`, req) - `now` (`integer`, req): When the fight ended, Unix milliseconds. - `end` (`KombatmpEndView`, req) - `next_round_at` (`integer`, req): `now` plus 5,000 ms, the result screen. ### `KombatmpClosed` Type: `object` — `data` of the `closed` broadcast that ends a round after its fight: the seed `s_i`, so every exchange and every bet's record... - `type` (`"closed"`, req): const `"closed"`; Always `closed`. - `round_id` (`KombatmpRoundIndex`, req) - `index` (`KombatmpRoundIndex`, req) - `seed` (`KombatmpHex`, req) - `commit` (`KombatmpHex`, req) - `salt` (`KombatmpHex`, req) ### `KombatmpAborted` Type: `object` — `data` of the `aborted` broadcast when the outage rule ends a round: the round ends at its last journaled step with... - `type` (`"aborted"`, req): const `"aborted"`; Always `aborted`. - `round_id` (`KombatmpRoundIndex`, req) - `index` (`KombatmpRoundIndex`, req) - `reason` (`"ABORT"`, req): const `"ABORT"`; Always `ABORT`. - `last_revealed` (`integer`, req): range 0..30; The exchanges revealed when the round ended (`0` in the lobby and between the bell and exchange 1);... - `seed` (`KombatmpHex`, req) - `commit` (`KombatmpHex`, req) - `salt` (`KombatmpHex`, req) ### `KombatmpArenaBetId` Type: `integer` — range 1..+inf — A bet's number among its own player's bets in the round: `1, 2, …`, reserved when the round takes the bet for placement (before... ### `KombatmpPlacedBet` Type: `object` — A placed KOMBATMP bet (the game specification, the source's `betView`): the same object as `createLiveBet`'s `view` in... - `arena_bet_id` (`KombatmpArenaBetId`, req) - `round_id` (`KombatmpRoundIndex`, req) - `index` (`KombatmpRoundIndex`, req) - `coin` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The bet's currency. - `kind` (`string`, req): enum: `win`, `flawless`, `quick_ko`, `comeback`; The market. - `side` (`string`, req): enum: `red`, `blue`; The side (`red` for every side bet). - `at` (`integer`, req): range 0..30; The exchanges revealed when the bet was priced. - `pay` (`KombatmpPay`, req) - `stake` (`Amount`, req) - `reserved_profit` (`Amount`, req) ### `KombatmpBetAccepted` Type: `object` — `data` of the `bet` frame sent to the bettor's own sockets once the round's journal holds the bet. - `type` (`"bet"`, req): const `"bet"`; Always `bet`. - `request_id` (`KombatmpBetRequestId`, req) - `bet` (`KombatmpPlacedBet`, req) ### `KombatmpRefusalData` Type: `object` — The source's `data` of a refused KOMBATMP bet, without its balance: `status` names the refusal (`INVALID`, `MAX_STAKE` with the... - `status` (`string`, req): enum: `INVALID`, `MAX_STAKE`, `CLOSED`, `NOT_OFFERED`, `ODDS_CHANGED`, `LIMIT`; The source's word for the refusal. - `max_stake` (`Amount`) - `n` (`integer`): range 0..30; The exchanges revealed as of the refused bet's arrival at `live`, the `at` a bet must name. - `pay` (`KombatmpPay | null`): The bet's pay at `n`, or `null` when it is not offered there. ### `KombatmpBetError` Type: `object` — `data` of the round's `error` frame to the bettor's sockets when a bet was not placed. - `type` (`"error"`, req): const `"error"`; Always `error`. - `request_id` (`KombatmpBetRequestId`, req) - `kind` (`"bet"`, req): const `"bet"`; Always `bet`. - `code` (`string`, req): enum: `invalid_input`, `invalid_action`, `stake_out_of_range`, `max_stake`, `unknown_profile`, `not_offered`, `odds_changed`, `closed`, `limit`, `pending`, `seed_not_revealed`, `unknown_game`, `unknown_version`, `no_acceptable_draw`, `internal`; Why the bet was not placed. - `message` (`string`, req): len 1..inf; The refusal in words safe to show the player (the source's, the game specification, or the fixed... - `data` (`KombatmpRefusalData | null`, req): The source's status object, or `null` where the source had none (the stake's range, a missing pay,... - `max_stake` (`Amount`): With `max_stake` only, the largest stake that bet takes at its pay. ### `KombatmpPaid` Type: `object` — `data` of the `paid` frame to a bettor's own sockets when one of their bets settles, beside its `settled` frame (in no promised... - `type` (`"paid"`, req): const `"paid"`; Always `paid`. - `round_id` (`KombatmpRoundIndex`, req) - `request_id` (`KombatmpBetRequestId`, req) - `arena_bet_id` (`KombatmpArenaBetId`, req) - `won` (`boolean`, req): Whether the bet won. - `multiplier` (`string | null`, req): pattern `^(0\.00|1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,3})\.[0-9]{2})$`; The bet's `pay` on a win, `0.00` on a loss, `null` for a refund. - `payout` (`Amount`, req) - `refunded` (`boolean`, req): Whether the outage rule refunded the bet. ### `KombatmpPublicRound` Type: `object` — The round as the snapshot shows it (`KombatmpSnapshot.round`): its link's public part, the card, the exchanges revealed so far,... - `round_id` (`KombatmpRoundIndex`, req) - `index` (`KombatmpRoundIndex`, req) - `status` (`string`, req): enum: `BETTING`, `FIGHTING`, `CLOSED`, `ABORTED`; Where the round is. - `card` (`KombatmpCard`, req) - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The published hash chain's id. - `commit` (`KombatmpHex`, req) - `salt` (`KombatmpHex`, req) - `salt_source` (`string`, req): len 1..inf; Where the salt comes from (`bitcoin:`). - `seed` (`KombatmpHex | null`, req): The revealed seed `s_i` once the round is over, else `null`. - `bell_at` (`integer`, req): When the bell is (was) due, Unix milliseconds. - `revealed` (`integer`, req): range 0..31; The exchanges revealed so far. - `exchanges` (`array`, req): items 0..31; Every revealed exchange, in order. - `prices` (`KombatmpPrices | null`, req): The current offers while the round is open, else `null`. - `end` (`KombatmpEndView | null`, req): How the fight ended, once it has. ### `KombatmpSnapshot` Type: `object` — A KOMBATMP round as one viewer sees it now, `KombatmpProjectedSnapshot.show`: `phase` is `betting` before the bell, `fighting`... - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `now` (`integer`, req): The time of the snapshot, Unix milliseconds. - `phase` (`string`, req): enum: `betting`, `fighting`, `result`; Where the round is. - `round` (`KombatmpPublicRound`, req) - `my_bets` (`array`): items 1..12; The viewer's own placed bets in the round, when there are any. ### `KombatmpProjectedSnapshot` Type: `object` — `data` of a `snapshot` frame on `/v1/live/kombat-multiplayer` while a round is open or just over: the viewer's `KombatmpSnapshot`... - `show` (`KombatmpSnapshot`, req) - `self_bets` (`array`): items 0..12; The viewer's own bets in the round, when there are any. ### `KombatmpResult` Type: `object` — A played bet's settled view, the record's `game_result`, with exactly these keys in this order: the round (`round` and `round_id`... - `v` (`1`, req): const `1`; The record's version, `1`. - `arena` (`1`, req): const `1`; The arena's version, `1`. - `round` (`KombatmpRoundIndex`, req) - `round_id` (`KombatmpRoundIndex`, req) - `m` (`KombatmpMatchup`, req) - `bet` (`string`, req): enum: `win`, `flawless`, `quick_ko`, `comeback`; The market. - `side` (`string`, req): enum: `red`, `blue`; The side. - `at` (`integer`, req): range 0..30; The exchanges revealed when the bet was priced, always fewer than `x`. - `pay` (`KombatmpPay`, req) - `winner` (`string`, req): enum: `red`, `blue`; The fight's winner. - `by` (`string`, req): enum: `KO`, `DECISION`, `SUDDEN_DEATH`; How the fight ended. - `x` (`integer`, req): range 2..31; The exchanges the fight took. - `hp` (`KombatmpHP`, req) - `paid` (`string`, req): pattern `^(0\.00|1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,3})\.[0-9]{2})$`; `pay` on a win, `"0.00"` on a loss. ### `KombatmpRefund` Type: `object` — The settled view of a bet the outage rule refunded (BetPlug's, since the source wrote no record): the round and bet fields of... - `v` (`1`, req): const `1`; The record's version, `1`. - `arena` (`1`, req): const `1`; The arena's version, `1`. - `round` (`KombatmpRoundIndex`, req) - `round_id` (`KombatmpRoundIndex`, req) - `m` (`KombatmpMatchup`, req) - `bet` (`string`, req): enum: `win`, `flawless`, `quick_ko`, `comeback`; The market. - `side` (`string`, req): enum: `red`, `blue`; The side. - `at` (`integer`, req): range 0..30; The exchanges revealed when the bet was priced, at most `x`. - `pay` (`KombatmpPay`, req) - `settled_by` (`"outage"`, req): const `"outage"`; Always `outage`. - `reason` (`"ABORT"`, req): const `"ABORT"`; Always `ABORT`. - `x` (`integer`, req): range 0..30; The exchanges revealed when the round ended. - `paid` (`"1.00"`, req): const `"1.00"`; Always `"1.00"`, the stake back. ### `KombatmpMatchup` Type: `array` — items 3..3 — `[fighter, rung, duration]`, the round's matchup (its card's `fighter`, `rung` and `duration`). ### `KombatmpSettlement` Type: `object` — `data` of the `settled` frame for a KOMBATMP bet: a `LiveSettlement` whose `view` is the bet's settled view. - `bet_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,48}$`; The bet's id, `createLiveBet`'s `bet_id`. - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The bet's currency. - `stake` (`Amount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`, req) - `settled_by` (`string`, req): enum: `play`, `outage`; Which path settled the bet, read from the record's last action. - `view` (`KombatmpResult | KombatmpRefund`, req): The bet's settled view. ### `KombatmpFrameData` Type: `KombatmpRound | KombatmpBell | KombatmpExchange | KombatmpEnd | KombatmpClosed | KombatmpAborted | KombatmpBetAccepted | KombatmpBetError | KombatmpPaid | KombatmpProjectedSnapshot | LiveIdleSnapshot | KombatmpSettlement | LiveHubError` — Union of KOMBATMP's `LiveFrame.data` bodies (the game specification). - `oneOf`: `KombatmpRound` | `KombatmpBell` | `KombatmpExchange` | `KombatmpEnd` | `KombatmpClosed` | `KombatmpAborted` | `KombatmpBetAccepted` | `KombatmpBetError` | `KombatmpPaid` | `KombatmpProjectedSnapshot` | `LiveIdleSnapshot` | `KombatmpSettlement` | `LiveHubError` ### `KombatmpFrame` Type: `LiveFrame & object` — A server-to-client frame on `/v1/live/kombat-multiplayer` (`game: "kombat-multiplayer"`). - `allOf[1]`: - `game` (`"kombat-multiplayer"`, req): const `"kombat-multiplayer"`; Always `kombat-multiplayer`. - `data` (`KombatmpFrameData`, req) - `allOf`: `LiveFrame` ### `KombatmpCommand` Type: `KombatmpSnapshotCommand` — A KOMBATMP player's socket command, in the `LiveCommand` envelope: `snapshot`, and nothing else. - `oneOf`: `KombatmpSnapshotCommand` ### `KombatmpSnapshotCommand` Type: `object` — Ask for a fresh snapshot (`KombatmpProjectedSnapshot`, or `LiveIdleSnapshot` while no round is open). - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `request_id` (`KombatmpSocketRequestId`, req) - `data` (`object`): None; `{}` is allowed. ### `StackOPassSocketRequestId` Type: `string` — len 1..64 — A STACKOPASS socket command's `request_id`, chosen by the client: 1 to 64 bytes of UTF-8 (`live` counts bytes) that do not start... ### `StackOPassTableId` Type: `string` — pattern `^[A-Za-z0-9_-]{22}$` — A table's id: 22 base64url characters drawn at random by `live` (132 bits from `crypto/rand`), never from a counter, so no id... ### `StackOPassSeatIndex` Type: `integer` — range 0..5 — A seat at a table, `0.. 5` clockwise. ### `StackOPassRisk` Type: `integer` — enum: `9`, `5`, `3` — A table's fixed risk `N`, the devil's `1 in N` on every pack (round 2, the game specification): each table has one for its whole... ### `StackOPassStack` Type: `string` — pattern `^((0|[1-9][0-9]{0,3})\.[0-9]{2}|10000\.00)$` — A multiplier with exactly 2 decimals, `0.00.. 10000.00` (the game specification: no pack is offered whose best case passes... ### `StackOPassBlock` Type: `string` — enum: `MAX_PACKS`, `MAX_MULTIPLIER`, `MAX_PROFIT` — Why a hand may open no more packs (`openBlock`, the game specification), the first that binds in this order: `MAX_PACKS` (40... ### `StackOPassCard` Type: `object` — One slot of an opened pack: the devil's slot (`devil: true`, with `id`, `tier` and `value` all `null`), or a card (... - `slot` (`integer`, req): range 0..4; The slot, `0.. 4`, left to right. - `devil` (`boolean`, req): Whether the devil is in this slot. - `id` (`integer | null`, req): range 1..242; The card's picture, `1.. 242`, rarest first; `null` in the devil's slot. - `tier` (`string | null`, req): enum: `COMMON`, `UNCOMMON`, `RARE`, `SUPER_RARE`, `EPIC`, `LEGENDARY`, `null`; The card's tier; `null` in the devil's slot. - `value` (`string | null`, req): pattern `^[0-7]\.[0-9]{2}$`; The card's value at the table's risk, with 2 decimals (`"0.19"`.. ### `StackOPassPack` Type: `object` — An opened pack, the engine's `pack`: its number in the hand, the table's risk, its five slots, and for a safe pack its total and... - `n` (`integer`, req): range 1..40; The pack's number in its hand, `1.. 40`. - `risk` (`StackOPassRisk`, req) - `devil` (`boolean`, req): Whether the devil was in the pack, which busts the hand. - `cards` (`array`, req): items 5..5; The five slots, in slot order. - `total` (`string`, req): pattern `^(0|[1-9]|[1-3][0-9])\.[0-9]{2}$`; The five cards' sum (`"0.95"`.. - `multiplier` (`StackOPassStack`, req) ### `StackOPassRisks` Type: `array` — items 0..40 — The risk of every pack the hand opened, the table's `N` repeated (round 2 has no heat). ### `StackOPassHandView` Type: `object` — An open hand as its own player sees it on the socket: the engine's open `hand` view with its `blocks` (one entry per risk, as the... - `status` (`"OPEN"`, req): const `"OPEN"`; Always `OPEN`. - `packs` (`integer`, req): range 0..40; Packs opened. - `safe` (`integer`, req): range 0..40; Safe packs opened; equal to `packs` while the hand is open. - `stack` (`StackOPassStack`, req) - `block` (`StackOPassBlock | null`, req): The table's risk's `openBlock`, or `null` while a pack is offered. - `multiplier` (`null`, req): Always `null` while the hand is open. - `payout` (`null`, req): Always `null` while the hand is open. - `risks` (`StackOPassRisks`, req) ### `StackOPassSettledHand` Type: `object` — A settled hand's `hand`: `BUSTED` (the devil pack counted in `packs`, `safe` one less, `stack` and `multiplier` `"0.00"`,... - `status` (`string`, req): enum: `BUSTED`, `CASHED_OUT`, `REFUNDED`; How the hand ended. - `packs` (`integer`, req): range 0..40; Packs opened, the devil's included. - `safe` (`integer`, req): range 0..40; Safe packs opened. - `stack` (`StackOPassStack`, req) - `blocks` (`null`, req): Always `null` once settled. - `multiplier` (`StackOPassStack`, req) - `payout` (`Amount`, req) - `risks` (`StackOPassRisks`, req) ### `StackOPassGameResult` Type: `object` — A settled hand's record, the engine's `game_result`, keys in this order: `risks` the table's risk once per opened pack, `packs`... - `v` (`1`, req): const `1`; The record's version, `1`. - `table` (`1`, req): const `1`; The card table's version, `1`. - `risks` (`string`, req): pattern `^(|9(,9)*|5(,5)*|3(,3)*)$`; len 0..79; The table's risk once per opened pack (`"5,5"`), or `""` for a refund. - `status` (`string`, req): enum: `BUSTED`, `CASHED_OUT`, `REFUNDED`; How the hand ended. - `packs` (`string`, req): pattern `^(|(D|[1-9][0-9]?|1[0-9]{2}|2[0-3][0-9]|24[0-2])(,(D|[1-9][0-9]?|1[0-9]{2}|2[0-3][0-9]|24[0-2])){4}(\|(D|[1-9][0-9]?|1[0-9]{2}|2[0-3][0-9]|24[0-2])(,(D|[1-9][0-9]?|1[0-9]{2}|2[0-3][0-9]|24[0-2])){4})*)$`; len 0..799; The opened packs' slots, or `""` for a refund. - `safe` (`integer`, req): range 0..40; Safe packs opened. - `multiplier` (`StackOPassStack`, req) - `edge_bps` (`500`, req): const `500`; The house edge in basis points, `500`. - `auto` (`string`): enum: `MAX_PROFIT`, `MAX_MULTIPLIER`, `MAX_PACKS`, `FORFEIT`; The table's forced cash-out's block, or `FORFEIT` for a force-close after at least one pack. ### `StackOPassSettledView` Type: `object` — A settled hand's view, its record's last step's `view`: `pack` and `busted: true` only on a bust; `refunded: true` only on a... - `hand` (`StackOPassSettledHand`, req) - `pack` (`StackOPassPack`) - `busted` (`true`): const `true`; Present, and `true`, only on a bust. - `auto` (`string | null`, req): enum: `MAX_PROFIT`, `MAX_MULTIPLIER`, `MAX_PACKS`, `FORFEIT`, `null`; The forced cash-out's block, `FORFEIT` for a force-close after a pack, else `null`. - `refunded` (`true`): const `true`; Present, and `true`, only on a refund. - `profit` (`string`): pattern `^-?(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$`; `payout − stake` at the currency's scale, negative on a loss; absent on a refund. - `profit_capped` (`false`): const `false`; Always `false`; absent on a refund. - `ended_by` (`string`, req): enum: `DEVIL`, `CASHOUT`, `FORCED:MAX_PACKS`, `FORCED:MAX_MULTIPLIER`, `FORCED:MAX_PROFIT`, `REFUND`, `FORCE_CLOSED`; How the hand ended. - `game_result` (`StackOPassGameResult`, req) ### `StackOPassSettlement` Type: `object` — `data` of the `settled` frame for a STACKOPASS hand, sent to its player's sockets when `live` settles the hand or learns that it... - `bet_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,64}$`; The hand's round id (`GET /v1/session/rounds/{id}`). - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The hand's currency. - `stake` (`Amount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`, req) - `settled_by` (`string`, req): enum: `play`, `force_close`, `outage`; Which path settled the hand, as `live` knows it. - `view` (`StackOPassSettledView`, req) ### `StackOPassSeat` Type: `object` — A seat as every watcher of the table sees it, with no identity and no amount: `empty`; `buying` (held for a buy-in whose money is... - `seat` (`StackOPassSeatIndex`, req) - `state` (`string`, req): enum: `empty`, `buying`, `open`, `busted`, `cashed_out`, `refunded`; The seat's state. - `packs` (`integer | null`, req): range 0..40; Packs opened by the seat's hand; `null` while `empty` or `buying`. - `stack` (`StackOPassStack | null`, req): The hand's stack, or the multiplier it was paid; `null` while `empty` or `buying`. - `away` (`boolean`, req): Whether the seat's player has no socket now. ### `StackOPassTurnState` Type: `object` — The seat on the clock and when its turn ends (Unix milliseconds, 10,000 ms after it began). - `seat` (`StackOPassSeatIndex`, req) - `deadline_at` (`integer`, req): When the turn ends; a turn with no `open`, `pass`, `cashout` or `leave` by then is passed for the... ### `StackOPassTableState` Type: `object` — A table as every watcher sees it: its fixed risk, the devil's chance at it, its six seats, the turn (`null` while no seat is on... - `table` (`StackOPassTableId`, req) - `risk` (`StackOPassRisk`, req) - `devil_chance` (`string`, req): enum: `11.11`, `20.00`, `33.33`; The devil's chance per pack in percent, truncated to 2 decimals (`1 in 9`, `1 in 5`, `1 in 3`). - `seats` (`array`, req): items 6..6; The six seats, in seat order. - `turn` (`StackOPassTurnState | null`, req): The turn, or `null` while no seat is on the clock. - `lap_passes` (`integer`, req): range 0..5; Passes on the pack now on the table. ### `StackOPassTableRow` Type: `object` — One of the viewer's operator's tables in the lobby, with how many of its six seats are not `empty`. - `table` (`StackOPassTableId`, req) - `risk` (`StackOPassRisk`, req) - `occupied` (`integer`, req): range 0..6; Seats not `empty`. ### `StackOPassTablesList` Type: `array` — items 3..inf — The viewer's operator's tables in the environment (never another operator's, nor a count of them), at least one per risk with a... ### `StackOPassTables` Type: `object` — `data` of the `tables` broadcast to the sockets that watch the lobby (no table), whenever the lobby changes, at most twice a... - `type` (`"tables"`, req): const `"tables"`; Always `tables`. - `tables` (`StackOPassTablesList`, req) ### `StackOPassMe` Type: `object` — The viewer's own seat, in their snapshot only, present while they hold one: its table and seat and state; `round_id`, `currency`... - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex`, req) - `state` (`string`, req): enum: `buying`, `open`, `busted`, `cashed_out`, `refunded`; The seat's state. - `round_id` (`string`): pattern `^[A-Za-z0-9_-]{1,64}$`; The hand's round id. - `currency` (`string`): pattern `^[A-Z0-9]{2,12}$`; The hand's currency. - `stake` (`Amount`) - `hand` (`StackOPassHandView`) ### `StackOPassSnapshot` Type: `object` — `data` of a `snapshot` frame: the answer to `snapshot` and to `watch`, and the frame `live` sends unasked right after the... - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `tables` (`StackOPassTablesList`, req) - `table` (`StackOPassTableState | null`, req): The watched table, or `null` for the lobby. - `me` (`StackOPassMe`) ### `StackOPassSeated` Type: `object` — `data` of the `seated` broadcast to the table's watchers whenever a seat's public state changes: held for a buy-in (`buying`),... - `type` (`"seated"`, req): const `"seated"`; Always `seated`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeat`, req) ### `StackOPassTurn` Type: `object` — `data` of the `turn` broadcast whenever the turn moves: to `seat` until `deadline_at` (10,000 ms), or to no seat (`seat` and... - `type` (`"turn"`, req): const `"turn"`; Always `turn`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex | null`, req): The seat on the clock, or `null`. - `deadline_at` (`integer | null`, req): When the seat's turn ends (Unix milliseconds), or `null` with no seat. ### `StackOPassOpened` Type: `object` — `data` of the `opened` broadcast to the table's watchers after a seat opened a pack: the pack, safe or the devil's, drawn from... - `type` (`"opened"`, req): const `"opened"`; Always `opened`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex`, req) - `pack` (`StackOPassPack`, req) ### `StackOPassPassed` Type: `object` — `data` of the `passed` broadcast after the seat on the clock passed: by its player (`player`), or by the table at its turn's... - `type` (`"passed"`, req): const `"passed"`; Always `passed`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex`, req) - `by` (`string`, req): enum: `player`, `timeout`; Who passed. - `lap_passes` (`integer`, req): range 1..6; The passes on this pack, this one included. ### `StackOPassReshuffled` Type: `object` — `data` of the `reshuffled` broadcast when every open hand passed the pack once: the pack is discarded (no word is read), and the... - `type` (`"reshuffled"`, req): const `"reshuffled"`; Always `reshuffled`. - `table` (`StackOPassTableId`, req) ### `StackOPassCashedOut` Type: `object` — `data` of the `cashed_out` broadcast to the table's watchers when a seat's hand closed without a bust: `CASHED_OUT` at... - `type` (`"cashed_out"`, req): const `"cashed_out"`; Always `cashed_out`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex`, req) - `status` (`string`, req): enum: `CASHED_OUT`, `REFUNDED`; How the hand closed. - `multiplier` (`StackOPassStack`, req) - `reason` (`string`, req): enum: `cashout`, `left`, `away`, `timeouts`, `force_close`, `outage`; Why it closed. ### `StackOPassLeft` Type: `object` — `data` of the `left` broadcast when a seat became `empty`: its player left (`left`), was away 60 s (`away`) or timed out three... - `type` (`"left"`, req): const `"left"`; Always `left`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex`, req) - `reason` (`string`, req): enum: `left`, `away`, `timeouts`, `idle`, `buy_in_failed`, `outage`; Why the seat emptied. ### `StackOPassHand` Type: `object` — `data` of the `hand` frame to its player's sockets only: their open hand after the buy-in seated it (no `pack`) and after each... - `type` (`"hand"`, req): const `"hand"`; Always `hand`. - `table` (`StackOPassTableId`, req) - `seat` (`StackOPassSeatIndex`, req) - `round_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,64}$`; The hand's round id (`GET /v1/session/rounds/{id}`). - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The hand's currency. - `stake` (`Amount`, req) - `hand` (`StackOPassHandView`, req) - `pack` (`StackOPassPack`) ### `StackOPassOpenAck` Type: `object` — `data` of the `ack` answering an applied `open`: the pack's number in the hand and whether the devil busted it. - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `request_id` (`StackOPassSocketRequestId`, req) - `kind` (`"open"`, req): const `"open"`; Always `open`. - `pack` (`integer`, req): range 1..40; The pack's number in the hand. - `busted` (`boolean`, req): Whether the devil was in it. ### `StackOPassMoveAck` Type: `object` — `data` of the `ack` answering an applied `pass`, `cashout` or `leave`. - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `request_id` (`StackOPassSocketRequestId`, req) - `kind` (`string`, req): enum: `pass`, `cashout`, `leave`; The command's `type`. ### `StackOPassError` Type: `object` — `data` of the table's `error` frame refusing a `watch`, `open`, `pass`, `cashout` or `leave`, which changed nothing: `not_seated`... - `type` (`"error"`, req): const `"error"`; Always `error`. - `request_id` (`StackOPassSocketRequestId`, req) - `kind` (`string`, req): enum: `watch`, `open`, `pass`, `cashout`, `leave`; The command's `type`. - `code` (`string`, req): enum: `not_seated`, `no_hand`, `not_turn`, `busy`, `seated`, `no_table`, `invalid_action`, `closed`, `pending`, `request_id_reused`, `no_acceptable_draw`, `internal`; Why the table refused it. - `message` (`string`, req): len 1..inf; The refusal in words safe to show the player. ### `StackOPassFrameData` Type: `StackOPassTables | StackOPassSnapshot | StackOPassSeated | StackOPassTurn | StackOPassOpened | StackOPassPassed | StackOPassReshuffled | StackOPassCashedOut | StackOPassLeft | StackOPassHand | StackOPassOpenAck | StackOPassMoveAck | StackOPassError | StackOPassSettlement | LiveHubError` — Union of STACKOPASS's `LiveFrame.data` bodies (the game specification). - `oneOf`: `StackOPassTables` | `StackOPassSnapshot` | `StackOPassSeated` | `StackOPassTurn` | `StackOPassOpened` | `StackOPassPassed` | `StackOPassReshuffled` | `StackOPassCashedOut` | `StackOPassLeft` | `StackOPassHand` | `StackOPassOpenAck` | `StackOPassMoveAck` | `StackOPassError` | `StackOPassSettlement` | `LiveHubError` ### `StackOPassFrame` Type: `LiveFrame & object` — A server-to-client frame on `/v1/live/stack-o-pass` (`game: "stack-o-pass"`). - `allOf[1]`: - `game` (`"stack-o-pass"`, req): const `"stack-o-pass"`; Always `stack-o-pass`. - `data` (`StackOPassFrameData`, req) - `allOf`: `LiveFrame` ### `StackOPassWatchData` Type: `object` — A `watch`'s `data`. - `table` (`StackOPassTableId | null`, req): The table to watch, or `null` to watch the lobby. ### `StackOPassNoData` Type: `object` — None; `{}` is allowed. ### `StackOPassCommand` Type: `StackOPassSnapshotCommand | StackOPassWatchCommand | StackOPassOpenCommand | StackOPassPassCommand | StackOPassCashoutCommand | StackOPassLeaveCommand` — A STACKOPASS player's socket command, in the `LiveCommand` envelope: `snapshot`, `watch`, `open`, `pass`, `cashout` or `leave`,... - `oneOf`: `StackOPassSnapshotCommand` | `StackOPassWatchCommand` | `StackOPassOpenCommand` | `StackOPassPassCommand` | `StackOPassCashoutCommand` | `StackOPassLeaveCommand` ### `StackOPassSnapshotCommand` Type: `object` — Ask for a fresh snapshot (`StackOPassSnapshot`). - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `request_id` (`StackOPassSocketRequestId`, req) - `data` (`StackOPassNoData`) ### `StackOPassWatchCommand` Type: `object` — Watch a table, or the lobby. - `type` (`"watch"`, req): const `"watch"`; Always `watch`. - `request_id` (`StackOPassSocketRequestId`, req) - `data` (`StackOPassWatchData`, req) ### `StackOPassOpenCommand` Type: `object` — Open the next pack, on the seat's turn. - `type` (`"open"`, req): const `"open"`; Always `open`. - `request_id` (`StackOPassSocketRequestId`, req) - `data` (`StackOPassNoData`) ### `StackOPassPassCommand` Type: `object` — Pass the pack, on the seat's turn. - `type` (`"pass"`, req): const `"pass"`; Always `pass`. - `request_id` (`StackOPassSocketRequestId`, req) - `data` (`StackOPassNoData`) ### `StackOPassCashoutCommand` Type: `object` — Cash the hand out, at any time. - `type` (`"cashout"`, req): const `"cashout"`; Always `cashout`. - `request_id` (`StackOPassSocketRequestId`, req) - `data` (`StackOPassNoData`) ### `StackOPassLeaveCommand` Type: `object` — Leave the table, cashing the hand out first. - `type` (`"leave"`, req): const `"leave"`; Always `leave`. - `request_id` (`StackOPassSocketRequestId`, req) - `data` (`StackOPassNoData`) ### `TrapdoorSocketRequestId` Type: `string` — len 1..64 — A TRAPDOOR socket command's `request_id`, chosen by the client: 1 to 64 bytes of UTF-8 (`live` counts bytes) that do not start... ### `TrapdoorBetRequestId` Type: `string` — pattern `^Bet:[A-Za-z0-9_-]{1,48}:[1-9][0-9]{0,4}$`; len 0..64 — A REST bet's request id in the show, `Bet::`: `` is `createLiveBet`'s `bet_id` and `` the number of its... ### `TrapdoorShowIndex` Type: `integer` — range 1..9007199254740991 — A TRAPDOOR show's public id: the index of its link in the published hash chain, which the source's database id was. ### `TrapdoorFormat` Type: `string` — enum: `CLASSIC`, `MEGA` — The show's format, by its index (`MEGA` when the index is a multiple of 10; the game specification). ### `TrapdoorBean` Type: `integer` — range 1..1 — A bean's label: its ordinal among its own player's beans in the show, so `1`, since a player holds one bean per show. ### `TrapdoorDoor` Type: `integer` — range 1..5 — A door, `1.. n_g` for its gate (the game specification; at most 5). ### `TrapdoorGate` Type: `integer` — range 1..12 — A gate, `1.. G` (`G` is 8 in CLASSIC, 12 in MEGA). ### `TrapdoorBank` Type: `string` — pattern `^[1-9][0-9]*\.[0-9]{2}$` — A bank multiplier `bank(g)` with exactly 2 decimals (`"1.42"`; the game specification). ### `TrapdoorHex` Type: `string` — pattern `^[0-9a-f]{64}$` — 64 lowercase hex characters (a seed, a commitment or a salt). ### `TrapdoorLayout` Type: `array` — items 1..3 — One gate's trapdoors, `t_g` distinct doors in ascending order. ### `TrapdoorBeanPlan` Type: `object` — A bean's pre-plan as the show keeps it and answers it: both keys always present, `doors` always an object, its gates ascending. - `bank_at` (`integer | null`, req): range 1..11; Bank after surviving this gate, or `null`. - `doors` (`object`, req): The planned door per gate `2.. G`, keyed by the gate as a decimal string. ### `TrapdoorPlanData` Type: `object | array | null` — items 0..0 — A `plan` command's `data`: a pre-plan as a client sends it, the same as `createLiveBet`'s `params.plan` (`TrapdoorPlanInput` in... - `bank_at` (`integer | null`): range 1..11; Bank after surviving this gate, or `null`. - `doors` (`object | array | null`): items 0..0; The door per later gate, keyed by the gate as a decimal string; `[]` or `null` is no door. ### `TrapdoorLobby` Type: `object` — `data` of the `lobby` broadcast that opens a show for bets, and the `show` of every TRAPDOOR snapshot: the link's public part,... - `type` (`"lobby"`, req): const `"lobby"`; Always `lobby`. - `show` (`TrapdoorShowIndex`, req) - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The published hash chain's id. - `index` (`TrapdoorShowIndex`, req) - `format` (`TrapdoorFormat`, req) - `commit` (`TrapdoorHex`, req): The link's commitment `s_{i-1} = sha256_hex(s_i)`, published before the chain's first show. - `salt` (`TrapdoorHex`, req): The chain's public salt, a block hash fixed after the commitment. - `salt_source` (`string`, req): len 1..inf; Where the salt comes from (`bitcoin:`). - `lobby_closes_at` (`integer`, req): Unix time in milliseconds when the lobby closes, 10,000 ms after it opened. - `banks` (`array`, req): items 8..12; `bank(1).. bank(G)`, the multiplier a bean banks after surviving each gate (8 in CLASSIC, 12 in... ### `TrapdoorBeanEntry` Type: `object` — A placed bean: the same object as `createLiveBet`'s `view` in `openapi.yaml`, and the first view of the bean's record. - `show` (`TrapdoorShowIndex`, req) - `index` (`TrapdoorShowIndex`, req) - `format` (`TrapdoorFormat`, req) - `bean` (`TrapdoorBean`, req) - `bet_amt` (`Amount`, req) - `cap_gate` (`TrapdoorGate`, req) - `max_multiplier` (`TrapdoorBank`, req) - `reserved_profit` (`Amount`, req) - `door1` (`integer`, req): range 1..3; The door for gate 1 the bet named. - `plan` (`TrapdoorBeanPlan`, req) ### `TrapdoorEntry` Type: `object` — `data` of the `entry` frame sent to the bettor's own sockets once the show's journal holds the bet. - `type` (`"entry"`, req): const `"entry"`; Always `entry`. - `request_id` (`TrapdoorBetRequestId`, req) - `entry` (`TrapdoorBeanEntry`, req) ### `TrapdoorReveal` Type: `object` — `data` of the `reveal` broadcast after a gate's window closed: every live bean's decision was fixed, then, and only then, the... - `type` (`"reveal"`, req): const `"reveal"`; Always `reveal`. - `gate` (`TrapdoorGate`, req) - `traps` (`TrapdoorLayout`, req) - `last` (`boolean`, req): Whether this was the Golden Door. ### `TrapdoorBeanGate` Type: `object` — `data` of the `bean` frame, sent after each gate's `reveal` to the sockets of every player whose bean was alive before that gate,... - `type` (`"bean"`, req): const `"bean"`; Always `bean`. - `gate` (`TrapdoorGate`, req) - `bean` (`TrapdoorBean`, req) - `door` (`TrapdoorDoor | null`, req): The door the bean played at this gate, or `null` when it banked at the window's close. - `state` (`string`, req): enum: `alive`, `fell`, `banked`; The bean's state after this gate. - `reason` (`string | null`, req): enum: `MANUAL`, `PLAN`, `NO_PICK`, `DISCONNECT`, `CAP`, `FINALE`, `null`; Why it banked; `null` when it is alive or fell. - `multiplier` (`string | null`, req): The bean's multiplier as its record's view gives it (`bank`, or `"0.00"` for a fall), or `null`... ### `TrapdoorResults` Type: `object` — `data` of the `results` broadcast that ends a show after the Golden Door: the seed `s_i` and every layout, so every bean's record... - `type` (`"results"`, req): const `"results"`; Always `results`. - `show` (`TrapdoorShowIndex`, req) - `seed` (`TrapdoorHex`, req) - `commit` (`TrapdoorHex`, req) - `salt` (`TrapdoorHex`, req) - `layouts` (`array`, req): items 8..12; Every gate's layout, gates `1.. G` in order. ### `TrapdoorAborted` Type: `object` — `data` of the `aborted` broadcast when the outage rule ends a show: the show ends at its last journaled gate `last_gate` (K). - `type` (`"aborted"`, req): const `"aborted"`; Always `aborted`. - `show` (`TrapdoorShowIndex`, req) - `last_gate` (`integer`, req): range 0..11; K, the last gate drawn (`0` before gate 1); never the Golden Door, after which the show is over. - `seed` (`TrapdoorHex`, req) - `commit` (`TrapdoorHex`, req) - `salt` (`TrapdoorHex`, req) - `layouts` (`array`, req): items 0..11; The layouts of gates `1.. K`, in order (empty at K = 0). ### `TrapdoorMe` Type: `object` — The viewer's own bean, in their snapshot only, whole: a socket that reconnects learns from it everything the frames it missed... - `bean` (`TrapdoorBean`, req) - `state` (`string`, req): enum: `alive`, `banked`, `fell`, `refunded`; The bean's state. - `cap_gate` (`TrapdoorGate`, req) - `door1` (`integer`, req): range 1..3; The door for gate 1 the bet named. - `picks` (`array`, req): items 0..12; The doors the bean played, gates `1..` in order. - `pick` (`TrapdoorDoor`): The bean's live pick for the open window's gate, when it has one. - `banking` (`boolean`, req): Whether the bean clicked bank in the open window (never at gate 1). - `plan` (`TrapdoorBeanPlan`, req) - `result` (`TrapdoorResult`): The bean's settled view, its record's `game_result` and its settlement's `view`, once it fell,... ### `TrapdoorSnapshot` Type: `object` — A TRAPDOOR show as one viewer sees it now, `TrapdoorProjectedSnapshot.show`. - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `show` (`TrapdoorLobby`, req) - `phase` (`string`, req): enum: `lobby`, `window`, `results`, `aborted`; Where the show is. - `gate` (`integer`, req): range 0..12; The gate to be drawn next (`1` in the lobby), or `0` once the show is over. - `layouts` (`array`, req): items 0..12; The layouts drawn so far, gates `1..` in order. - `seed` (`TrapdoorHex`): The revealed seed `s_i`, once the show is over (`results` or `aborted`). - `me` (`TrapdoorMe`) ### `TrapdoorProjectedSnapshot` Type: `object` — `data` of a `snapshot` frame on `/v1/live/trapdoor` while a show is open: the viewer's `TrapdoorSnapshot` under `show`, and the... - `show` (`TrapdoorSnapshot`, req) - `self_bets` (`array`): items 0..1; The viewer's own bet in the show, when there is one (a player has at most one bean per show). ### `TrapdoorPickAck` Type: `object` — `data` of the `ack` answering an applied `pick`: the bean's live pick for `gate` is now `door`. - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `request_id` (`TrapdoorSocketRequestId`, req): The command's `request_id`. - `kind` (`"pick"`, req): const `"pick"`; Always `pick`. - `gate` (`TrapdoorGate`, req) - `door` (`TrapdoorDoor`, req) ### `TrapdoorBankAck` Type: `object` — `data` of the `ack` answering an applied `bank`: the bean banks `bank(gate − 1)` at this window's close, unless a later `pick` in... - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `request_id` (`TrapdoorSocketRequestId`, req): The command's `request_id`. - `kind` (`"bank"`, req): const `"bank"`; Always `bank`. - `gate` (`integer`, req): range 2..12; The gate whose window the click is in. ### `TrapdoorPlanAck` Type: `object` — `data` of the `ack` answering an applied `plan`: the pre-plan as the show now keeps it, used from the next window's close. - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `request_id` (`TrapdoorSocketRequestId`, req): The command's `request_id`. - `kind` (`"plan"`, req): const `"plan"`; Always `plan`. - `plan` (`TrapdoorBeanPlan`, req) ### `TrapdoorMoveError` Type: `object` — `data` of the show's `error` frame refusing a `pick`, `bank` or `plan`, which changed nothing (the game specification, the... - `type` (`"error"`, req): const `"error"`; Always `error`. - `request_id` (`TrapdoorSocketRequestId`, req): The command's `request_id`. - `kind` (`string`, req): enum: `pick`, `bank`, `plan`; The command's `type`. - `code` (`string`, req): enum: `no_bean`, `not_alive`, `phase`, `late`, `bad_gate`, `bad_door`, `no_bank_at_gate_1`, `bad_plan`, `invalid_action`, `pending`; Why the show refused it. - `message` (`string`, req): len 1..inf; The refusal in words safe to show the player. ### `TrapdoorBetError` Type: `object` — `data` of the show's `error` frame to the bettor's sockets when a bet was not placed. - `type` (`"error"`, req): const `"error"`; Always `error`. - `request_id` (`TrapdoorBetRequestId`, req) - `kind` (`"bet"`, req): const `"bet"`; Always `bet`. - `code` (`string`, req): enum: `invalid_input`, `invalid_action`, `stake_out_of_range`, `max_stake`, `unknown_profile`, `not_offered`, `odds_changed`, `closed`, `limit`, `pending`, `seed_not_revealed`, `unknown_game`, `unknown_version`, `no_acceptable_draw`, `internal`; Why the bet was not placed. - `message` (`string`, req): len 1..inf; The refusal in words safe to show the player. - `max_stake` (`Amount`): With `max_stake` only, the largest stake that bet takes. ### `TrapdoorResult` Type: `object` — A settled bean's view, the record's `game_result`, with exactly these keys in this order. - `v` (`1`, req): const `1`; The record's version, `1`. - `show` (`TrapdoorShowIndex`, req) - `index` (`TrapdoorShowIndex`, req) - `format` (`TrapdoorFormat`, req) - `cap` (`TrapdoorGate`, req) - `picks` (`array`, req): items 0..12; The door played at each gate `1.. at`. - `traps` (`array`, req): items 0..12; Each played gate's layout. - `end` (`string`, req): enum: `BANKED`, `ELIMINATED`, `REFUNDED`; How the bean ended. - `at` (`integer`, req): range 0..12; The last gate played (`0` for a refund). - `reason` (`string | null`, req): enum: `MANUAL`, `PLAN`, `NO_PICK`, `DISCONNECT`, `ABORT`, `CAP`, `FINALE`, `null`; Why it banked or was refunded; `null` for a fall. - `multiplier` (`string`, req): pattern `^[0-9]+\.[0-9]{2}$`; `bank` with 2 decimals for a bank, `"0.00"` for a fall, `"1.00"` for a refund. ### `TrapdoorSettlement` Type: `object` — `data` of the `settled` frame for a TRAPDOOR bean: a `LiveSettlement` whose `view` is the bean's `TrapdoorResult`. - `bet_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,48}$`; The bet's id, `createLiveBet`'s `bet_id`. - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The bet's currency. - `stake` (`Amount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`, req) - `settled_by` (`string`, req): enum: `play`, `force_close`, `outage`; Which path settled the bean, read from the record's last action. - `view` (`TrapdoorResult`, req) ### `TrapdoorFrameData` Type: `TrapdoorLobby | TrapdoorEntry | TrapdoorReveal | TrapdoorBeanGate | TrapdoorResults | TrapdoorAborted | TrapdoorProjectedSnapshot | LiveIdleSnapshot | TrapdoorPickAck | TrapdoorBankAck | TrapdoorPlanAck | TrapdoorMoveError | TrapdoorBetError | TrapdoorSettlement | LiveHubError` — Union of TRAPDOOR's `LiveFrame.data` bodies (the game specification). - `oneOf`: `TrapdoorLobby` | `TrapdoorEntry` | `TrapdoorReveal` | `TrapdoorBeanGate` | `TrapdoorResults` | `TrapdoorAborted` | `TrapdoorProjectedSnapshot` | `LiveIdleSnapshot` | `TrapdoorPickAck` | `TrapdoorBankAck` | `TrapdoorPlanAck` | `TrapdoorMoveError` | `TrapdoorBetError` | `TrapdoorSettlement` | `LiveHubError` ### `TrapdoorFrame` Type: `LiveFrame & object` — A server-to-client frame on `/v1/live/trapdoor` (`game: "trapdoor"`). - `allOf[1]`: - `game` (`"trapdoor"`, req): const `"trapdoor"`; Always `trapdoor`. - `data` (`TrapdoorFrameData`, req) - `allOf`: `LiveFrame` ### `TrapdoorPickData` Type: `object` — A `pick`'s `data`. - `gate` (`integer`, req): The gate, a JSON integer literal; the show answers `bad_gate` or `late` for a gate whose window is... - `door` (`integer`, req): The door, a JSON integer literal; the show answers `bad_door` outside `1.. n_gate`. ### `TrapdoorBankData` Type: `object` — A `bank`'s `data`. - `gate` (`integer`, req): The gate whose window is open, a JSON integer literal; `1` is `no_bank_at_gate_1`. ### `TrapdoorCommand` Type: `TrapdoorSnapshotCommand | TrapdoorPickCommand | TrapdoorBankCommand | TrapdoorPlanCommand` — A TRAPDOOR player's socket command, in the `LiveCommand` envelope: `snapshot`, `pick`, `bank` or `plan`, and nothing else. - `oneOf`: `TrapdoorSnapshotCommand` | `TrapdoorPickCommand` | `TrapdoorBankCommand` | `TrapdoorPlanCommand` ### `TrapdoorSnapshotCommand` Type: `object` — Ask for a fresh snapshot (`TrapdoorProjectedSnapshot`, or `LiveIdleSnapshot` between shows). - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `request_id` (`TrapdoorSocketRequestId`, req) - `data` (`object`): None; `{}` is allowed. ### `TrapdoorPickCommand` Type: `object` — Pick a door for a gate. - `type` (`"pick"`, req): const `"pick"`; Always `pick`. - `request_id` (`TrapdoorSocketRequestId`, req) - `data` (`TrapdoorPickData`, req) ### `TrapdoorBankCommand` Type: `object` — Bank at the open window's close. - `type` (`"bank"`, req): const `"bank"`; Always `bank`. - `request_id` (`TrapdoorSocketRequestId`, req) - `data` (`TrapdoorBankData`, req) ### `TrapdoorPlanCommand` Type: `object` — Replace the bean's pre-plan. - `type` (`"plan"`, req): const `"plan"`; Always `plan`. - `request_id` (`TrapdoorSocketRequestId`, req) - `data` (`TrapdoorPlanData`) ### `CrashSocketRequestId` Type: `string` — len 1..64 — A CRASH socket command's `request_id`, chosen by the client: 1 to 64 bytes of UTF-8 (`live` counts bytes) that do not start with... ### `CrashBetRequestId` Type: `string` — pattern `^Bet:[A-Za-z0-9_-]{1,48}:[1-9][0-9]{0,4}$`; len 0..64 — A CRASH REST bet's request id in the show, `Bet::`, the form TRAPDOOR's takes (`TrapdoorBetRequestId`): `` is... ### `CrashChainIndex` Type: `integer` — range 1..10000000 — A CRASH show's public id: the index of its link in the published hash chain, `1.. 10,000,000`, which is also the link's nonce. ### `CrashHex` Type: `string` — pattern `^[0-9a-f]{64}$` — 64 lowercase hex characters (a seed, a commitment or a salt). ### `CrashMultiplier` Type: `string` — pattern `^([1-9][0-9]{0,5}\.[0-9]{2}|1000000\.00)$` — A multiplier on CRASH's curve, `1.00` to `1000000.00`, with exactly 2 decimals. ### `CrashTarget` Type: `string` — pattern `^(1\.(0[1-9]|[1-9][0-9])|([2-9]|[1-9][0-9]{1,5})\.[0-9]{2}|1000000\.00)$` — A winning multiplier, `1.01` to `1000000.00`, with exactly 2 decimals: an `auto_cashout` target or a cap as the show keeps it. ### `CrashTick` Type: `integer` — range 0..2303 — A tick of the flight, `t = 0.. 2,303`, one every 100 ms; step `k` runs tick `k − 1`. ### `CrashLobby` Type: `object` — `data` of the `lobby` broadcast that opens a show for bets, and the `show` of every CRASH snapshot: the link's public part and... - `type` (`"lobby"`, req): const `"lobby"`; Always `lobby`. - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The published hash chain's id. - `index` (`CrashChainIndex`, req) - `commit` (`CrashHex`, req): The link's commitment `s_{i-1} = sha256_hex(s_i)`, published before the chain's first show. - `salt` (`CrashHex`, req): The chain's public salt, a block hash fixed after the commitment. - `salt_source` (`string`, req): pattern `^bitcoin:[1-9][0-9]{5,8}$`; Where the salt comes from, `bitcoin:`. - `lobby_closes_at` (`integer`, req): Unix time in milliseconds when the lobby closes, 5,000 ms after the show opened. ### `CrashPlacedBet` Type: `object` — A placed CRASH bet: the same object as `createLiveBet`'s `view` in `openapi.yaml` (`CrashBetView`), and the first view of the... - `chain_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The show's chain, the `chain` of its `lobby`. - `round_index` (`CrashChainIndex`, req) - `bet_amt` (`Amount`, req) - `auto_cashout` (`CrashTarget | null`, req): The bet's automatic cash-out target, or `null` when it named none. - `cap_multiplier` (`CrashTarget`, req) - `exposure` (`Amount`, req) ### `CrashBetAccepted` Type: `object` — `data` of the `bet` frame sent to the bettor's own sockets once the show's journal holds the bet. - `type` (`"bet"`, req): const `"bet"`; Always `bet`. - `request_id` (`CrashBetRequestId`, req) - `bet` (`CrashPlacedBet`, req) ### `CrashTickFrame` Type: `object` — `data` of the `tick` broadcast for each tick the rocket survives: `multiplier` is the curve at that tick, `M(t)` (`1.00` at ticks... - `type` (`"tick"`, req): const `"tick"`; Always `tick`. - `tick` (`integer`, req): range 0..2302; The tick, `0.. 2,302`. - `multiplier` (`CrashMultiplier`, req) - `elapsed_ms` (`integer`, req): range 0..230200; `100 · tick`, the flight's time at this tick. ### `CrashCrashed` Type: `object` — `data` of the `crashed` broadcast that ends a show: the rocket crashed at `crash_point` on step `step` (tick `step − 1`), or... - `type` (`"crashed"`, req): const `"crashed"`; Always `crashed`. - `step` (`integer`, req): range 1..2304; The step that ended the show, `crash_step`. - `tick` (`CrashTick`, req) - `multiplier` (`CrashMultiplier`, req) - `crash_point` (`CrashMultiplier`, req) - `crash_step` (`integer`, req): range 1..2304; The step that reveals the show, the first whose tick's multiplier passes `crash_point`. - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The show's chain. - `index` (`CrashChainIndex`, req) - `server_seed` (`CrashHex`, req): The revealed seed `s_i`. - `commit` (`CrashHex`, req) - `salt` (`CrashHex`, req) ### `CrashAborted` Type: `object` — `data` of the `aborted` broadcast when the outage rule ends a show at its last journaled step `step` (K), with no draw. - `type` (`"aborted"`, req): const `"aborted"`; Always `aborted`. - `step` (`integer`, req): range 0..2303; K, the show's last journaled step (`0` in the lobby). - `tick` (`integer | null`, req): Tick `K − 1`, or `null` at K = 0. - `multiplier` (`CrashMultiplier | null`, req): The multiplier at `tick`, or `null` at K = 0. - `crash_point` (`CrashMultiplier`, req) - `crash_step` (`integer`, req): range 1..2304; The step that would have revealed the show. - `chain` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The show's chain. - `index` (`CrashChainIndex`, req) - `server_seed` (`CrashHex`, req): The revealed seed `s_i`. - `commit` (`CrashHex`, req) - `salt` (`CrashHex`, req) ### `CrashMe` Type: `object` — The viewer's own bet, in their snapshot only: the placed bet, whether it has settled, and once it has, its settled view... - `bet` (`CrashPlacedBet`, req) - `settled` (`boolean`, req): Whether the bet has settled. - `view` (`CrashResult`) ### `CrashSnapshot` Type: `object` — A CRASH show as one viewer sees it now, `CrashProjectedSnapshot.show`. - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `show` (`CrashLobby`, req) - `phase` (`string`, req): enum: `WAITING`, `ACTIVE`, `CRASHED`, `ABORTED`; Where the show is. - `step` (`integer`, req): range 0..2304; The last step run (`0` in the lobby). - `tick` (`CrashTick | null`, req): The tick of `step`, `step − 1`, or `null` at step 0. - `multiplier` (`CrashMultiplier | null`, req): The multiplier at `tick`, or `null` at step 0. - `elapsed_ms` (`integer | null`, req): `100 · tick`, or `null` at step 0. - `reveal` (`CrashCrashed | CrashAborted`): The show's `crashed` or `aborted` frame, once it is over. - `me` (`CrashMe`) ### `CrashProjectedSnapshot` Type: `object` — `data` of a `snapshot` frame on `/v1/live/crash` while a show is open: the viewer's `CrashSnapshot` under `show`, and the... - `show` (`CrashSnapshot`, req) - `self_bets` (`array`): items 0..1; The viewer's own bet in the show, when there is one (a player has at most one per show). ### `CrashCashoutAck` Type: `object` — `data` of the `ack` answering an applied `cashout`: the player's bet cashed out at the tick its arrival names, the last tick... - `type` (`"ack"`, req): const `"ack"`; Always `ack`. - `request_id` (`CrashSocketRequestId`, req): The command's `request_id`. - `kind` (`"cashout"`, req): const `"cashout"`; Always `cashout`. ### `CrashCashoutError` Type: `object` — `data` of the show's `error` frame refusing a `cashout`, which changed nothing (the game specification steps 9 to 12, in that... - `type` (`"error"`, req): const `"error"`; Always `error`. - `request_id` (`CrashSocketRequestId`, req): The command's `request_id`. - `kind` (`"cashout"`, req): const `"cashout"`; Always `cashout`. - `code` (`string`, req): enum: `invalid_action`, `wrong_phase`, `no_bet`, `not_cashable`; Why the show refused it. - `message` (`string`, req): pattern `^socket command refused: (invalid_action|wrong_phase|no_bet|not_cashable)$`; `socket command refused: `, the same code. ### `CrashBetError` Type: `object` — `data` of the show's `error` frame to the bettor's sockets when a bet was not placed. - `type` (`"error"`, req): const `"error"`; Always `error`. - `request_id` (`CrashBetRequestId`, req) - `kind` (`"bet"`, req): const `"bet"`; Always `bet`. - `code` (`string`, req): enum: `invalid_input`, `invalid_action`, `stake_out_of_range`, `max_stake`, `unknown_profile`, `not_offered`, `odds_changed`, `closed`, `limit`, `pending`, `seed_not_revealed`, `unknown_game`, `unknown_version`, `no_acceptable_draw`, `internal`; Why the bet was not placed. - `message` (`string`, req): len 1..inf; The refusal in words safe to show the player (from the game specification for the show's own... - `max_stake` (`Amount`): With `max_stake` only, the largest stake that bet takes at its `auto_cashout` (else at 1.01x). ### `CrashResultBeforeReveal` Type: `object` — A CRASH bet's settled view when it settled before the step that revealed its show: a cash-out (manual, or on its own at a tick... - `chain_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The show's chain. - `round_index` (`CrashChainIndex`, req) - `ended_by` (`string`, req): enum: `CASHED_OUT`, `FORCE_CLOSED`; How the bet ended. - `reason` (`string`, req): enum: `MANUAL`, `AUTO`, `CAP`, `FORCE_CLOSED`, `ABORT`; Why. - `auto_cashout` (`CrashTarget | null`, req): The bet's `auto_cashout`, or `null`. - `cap_multiplier` (`CrashTarget`, req) - `settled_step` (`integer`, req): range 0..2303; The step it settled on (`0` in the lobby). - `at_tick` (`integer | null`, req): The tick it settled at, `settled_step − 1`, or `null` in the lobby. - `elapsed_ms` (`integer | null`, req): `100 · at_tick`, or `null` in the lobby. - `multiplier` (`CrashMultiplier | null`, req): The multiplier paid, or `null` for a refund. - `seed_revealed_at_settle` (`false`, req): const `false`; Always `false` here. ### `CrashResultAtReveal` Type: `object` — A CRASH bet's settled view when it settled on the step that revealed its show: the crash, or the 1,000,000.00x finale. - `chain_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,43}$`; The show's chain. - `round_index` (`CrashChainIndex`, req) - `ended_by` (`string`, req): enum: `CRASHED`, `CASHED_OUT`; How the bet ended. - `reason` (`string`, req): enum: `CRASHED`, `AUTO`, `CAP`, `MAX_MULTIPLIER`; Why. - `auto_cashout` (`CrashTarget | null`, req): The bet's `auto_cashout`, or `null`. - `cap_multiplier` (`CrashTarget`, req) - `settled_step` (`integer`, req): range 1..2304; The step it settled on, `crash_step`. - `at_tick` (`CrashTick`, req) - `elapsed_ms` (`integer`, req): range 0..230300; `100 · at_tick`. - `multiplier` (`CrashTarget | null`, req): The multiplier paid, or `null` for a loss. - `crash_point` (`CrashMultiplier`, req) - `crash_step` (`integer`, req): range 1..2304; The step that revealed the show. - `seed_revealed_at_settle` (`true`, req): const `true`; Always `true` here. ### `CrashResult` Type: `CrashResultBeforeReveal | CrashResultAtReveal` — A settled CRASH bet's view, the record's `game_result`, with exactly its keys in this order:... - `oneOf`: `CrashResultBeforeReveal` | `CrashResultAtReveal` ### `CrashSettlement` Type: `object` — `data` of the `settled` frame for a CRASH bet: a `LiveSettlement` whose `view` is the bet's `CrashResult`. - `bet_id` (`string`, req): pattern `^[A-Za-z0-9_-]{1,48}$`; The bet's id, `createLiveBet`'s `bet_id`. - `currency` (`string`, req): pattern `^[A-Z0-9]{2,12}$`; The bet's currency. - `stake` (`Amount`, req) - `payout` (`Amount`, req) - `refund` (`Amount`, req) - `settled_by` (`string`, req): enum: `play`, `force_close`, `outage`; Which path settled the bet, read from the record's last action. - `view` (`CrashResult`, req) ### `CrashFrameData` Type: `CrashLobby | CrashBetAccepted | CrashTickFrame | CrashCrashed | CrashAborted | CrashProjectedSnapshot | LiveIdleSnapshot | CrashCashoutAck | CrashCashoutError | CrashBetError | CrashSettlement | LiveHubError` — Union of CRASH's `LiveFrame.data` bodies (the game specification). - `oneOf`: `CrashLobby` | `CrashBetAccepted` | `CrashTickFrame` | `CrashCrashed` | `CrashAborted` | `CrashProjectedSnapshot` | `LiveIdleSnapshot` | `CrashCashoutAck` | `CrashCashoutError` | `CrashBetError` | `CrashSettlement` | `LiveHubError` ### `CrashFrame` Type: `LiveFrame & object` — A server-to-client frame on `/v1/live/crash` (`game: "crash"`). - `allOf[1]`: - `game` (`"crash"`, req): const `"crash"`; Always `crash`. - `data` (`CrashFrameData`, req) - `allOf`: `LiveFrame` ### `CrashCommand` Type: `CrashSnapshotCommand | CrashCashoutCommand` — A CRASH player's socket command, in the `LiveCommand` envelope: `snapshot` or `cashout`, and nothing else. - `oneOf`: `CrashSnapshotCommand` | `CrashCashoutCommand` ### `CrashSnapshotCommand` Type: `object` — Ask for a fresh snapshot (`CrashProjectedSnapshot`, or `LiveIdleSnapshot` between shows). - `type` (`"snapshot"`, req): const `"snapshot"`; Always `snapshot`. - `request_id` (`CrashSocketRequestId`, req) - `data` (`object`): None; `{}` is allowed. ### `CrashCashoutCommand` Type: `object` — Cash the player's open bet out at the tick its arrival names (`CrashCommand`). - `type` (`"cashout"`, req): const `"cashout"`; Always `cashout`. - `request_id` (`CrashSocketRequestId`, req) - `data` (`object`): None; `{}` is allowed, and a field is `invalid_action`.