# 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_<key>
  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
<?php

declare(strict_types=1);

$repoRoot = getenv('BETRAIL_REPO_ROOT') ?: getcwd();
require_once $repoRoot . '/sdk/php/autoload.php';

use Betrail\Sdk\{Ed25519, Money, Redact, Secret, Signature, Webhooks};
use Betrail\Sdk\Nonce\FileBackedNonceStore;
use Betrail\Sdk\Wallet\{InMemoryWalletBook, WalletHandler};

if (Money::subAmounts('0.00197999', '0.00100000', 8) !== '0.00097999' || WalletHandler::showBetDebitTransactionId('bet_php_1', 1) !== 'bet_php_1:0:1:debit') {
    throw new RuntimeException('unexpected PHP money/tx-id result');
}

$tmpDir = sys_get_temp_dir() . '/betrail-sdk-php-doc-' . bin2hex(random_bytes(6));
mkdir($tmpDir, 0700, true);
try {
    $kp = Ed25519::generateWalletKeyPair();
    $walletSecret = new Secret('sandbox-php-wallet-secret-32byte!');
    $handler = new WalletHandler(
        requestSecrets: [$walletSecret],
        book: new InMemoryWalletBook(defaultInitialBalance: '1.00000000'),
        nonceStore: new FileBackedNonceStore($tmpDir . '/wallet-nonces.json'),
        answerEd25519Seeds: [$kp->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);
}
```
