# 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: `<round_id>:<step>:<attempt>:debit`<br>Live show bet (`trapdoor`, `kombat-multiplayer`, `crash`): `<bet_id>:0:<attempt>:debit`<br>`MEME_TRADE` buy-in: `<show_round_id>:<player_ref>:b<buyIn>:<attempt>:debit` | `transaction_id`, `round_id`, `player_ref`, `currency`, `amount`, `game`, `brand` | `WalletAnswer`: `{ "transaction_id", "amount", "currency", "operator_transaction_id", "balance" }` |
| `POST {base}/credit` | `<subject>: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` | `<debit_id>: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<string, string>; 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
   <three_digit_http_status>
   <answer_Betrail-Timestamp>
   <request_Betrail-Nonce>
   <request_transaction_id_or_empty_for_balance>
   <lowercase_hex_sha256_of_answer_body>
   ```
   **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);
```
