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.), routed through BetPlug's SSRF-hardened egress client (3 s timeout, 64 KB response cap). Live multiplayer games (Game catalog & live) 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. 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:
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,
});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)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)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 toWalletHandler. Once registered, BetPlug pins verification toed25519=and rejectsv1=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:
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 debitCallback 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_<br>Live show bet (trapdoor, kombat-multiplayer, crash): <bet_<br>MEME_TRADE buy-in: <show_ | transaction_id, round_id, player_ref, currency, amount, game, brand | WalletAnswer: { "transaction_id", "amount", "currency", "operator_ |
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#
{
"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"
}{
"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_ | NEVER | Missing/invalid Betrail-Signature, expired Betrail-Timestamp, or replayed Betrail-Nonce. |
400 | {"code":"invalid_ or {"code":"invalid_ | YES (betrail-v1-answer) | Authenticated call with malformed JSON, duplicate/case-folded keys, unknown path, or tombstoned late /debit. |
403 | {"code":"player_ | YES | /debit only: player is blocked or self-excluded. Never return on /credit or /rollback. |
409 | {"code":"insufficient_ or {"code":"limit_ | YES | /debit only: insufficient balance or player responsible-gaming limit reached. |
Security: Never sign an unauthenticated
401response. 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:
function unsignedUnauthorized(): { status: number; headers: Record<string, string>; body: string } {
return { status: 401, headers: {}, body: JSON.stringify({ code: "invalid_request" }) };
}Six mandatory wallet rules#
- Key idempotency strictly on
transaction_id— neverround_id. Multi-step games debit once per stake-adding action, and live shows (MEME_TRADE) settle multiple players and buy-ins under one sharedround_id. Keying onround_iddrops player payouts. - Sign every answer to a verified request (
betrail-v1-answer), including4xxrefusals. IncludeBetrail-TimestampandBetrail-Signature(ed25519=orv1=) computed over:Never sign an unauthenticatedbetrail-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>401response. - Re-sign idempotent replays over the retry's
Betrail-Nonce. When BetPlug retries/creditor/rollbackwith the sametransaction_id, return the exact stored first JSON body and status, signed afresh with a currentBetrail-Timestampand the retry request'sBetrail-Nonce. - Never refuse
/creditor/rollbackfor 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,/creditmust succeed (200). Only malformed JSON/schema errors answer signed400 {"code":"invalid_.request"} - Record rollback tombstones. If
/rollbackarrives for arollback_ofdebit your wallet never saw, store a tombstone for that debit ID and return200(WalletAnswerwith the tombstone's ownoperator_transaction_idand currentbalance). If the late/debitarrives afterward, refuse it with400 {"code":"invalid_(signed; OpenAPIrequest", "transaction_ id":"..."} WalletDebitRefusedaccepts4XXWalletRefusal, and BetPlug's SDK, Sandbox Wallet, and skills standardize on400invalid_request). - Strict schema echo and
operator_transaction_id != transaction_id. BetPlug decodes answers strictly (additionalProperties: false).WalletAnswermust echotransaction_id,amount, andcurrency, and provide a non-emptyoperator_transaction_iddistinct from BetPlug'stransaction_id.
Warning: Any extra JSON field, duplicate key, missing echo field, or unsigned live
4xxrefusal causes BetPlug to treat a/debitas unknown (rolling it back) and to keep retrying/creditor/rollbackuntil the 24-hour outbox schedule moves it todead.
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:
- Valid
POST /balance,/debit(200), and/credit(200, including"0.00000000"). - Signed
409 {"code":"insufficient_debit refusal.funds", "transaction_ id":"..."} - Idempotent replay of
/debitand/creditreturning the exact firstoperator_transaction_idre-signed for the newBetrail-Nonce. /rollbackafter a booked/debit, plus/rollbackbefore/debit(tombstone blocks late debit with signed400 invalid_request)./creditsucceeding while player status isblockedorself_excluded.- Rejection of tampered
Betrail-Signatureand staleBetrail-Timestampwith unsigned401({"code":"invalid_, norequest"} Betrail-Signatureheader).
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:
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);