# 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/<slug>.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** | `<betrail-game>` Web Component or isolated `play.betrail.example` iframe | Your casino (`POST /balance`, `/debit`, `/credit`, `/rollback`) | Server `POST /v1/launch` -> browser `POST /v1/sessions` (`bts_<token>`) -> `/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`) | `<betrail-game>` 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.<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** | `<betrail-game mode="demo">` or `btr_test_<key>` 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_<key>` 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_<key>` 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_<key>
  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.
