# Embedding Vgame Scratch

This guide is for operators (casinos, "parent sites") who embed Vgame games
with their license key. Throughout, `https://play.vgame.example` stands for your
Vgame host (locally: `http://localhost:8080`).

Vgame follows the integration pattern used by game providers and aggregators
(Softswiss-style Game Aggregator, Pragmatic-style direct wallet, Evenbet,
iGNITE, SoftAPI):

| Industry rule | How Vgame implements it |
|---|---|
| The operator wallet is the source of truth; the provider holds no player cash | `seamless` licenses. Vgame never stores a seamless balance, it only displays what your wallet reports. |
| Launch = iframe URL with the license key + a signed session token naming the player | `/embed?license=vg_live_…&launch_token=…`; the token comes from `POST /api/v1/wallet/authenticate` (server secret). |
| Balance read server-to-server | Vgame calls **`POST {wallet_url}/balance`** (GetBalance). |
| Bet = Debit before the RNG commits the round; refused if funds are short | **`POST {wallet_url}/debit`**; only your `"status":"ok"` lets the server RNG draw the outcome. |
| Win = Credit after the result (may be 0) | **`POST {wallet_url}/credit`** closes every round, `amount_minor: 0` for a loss. |
| Rollback when the debit outcome is unknown | **`POST {wallet_url}/rollback`** (timeouts, 5xx, lost replies, expired rounds). |
| Idempotency on every money call | Unique `transaction_id` per call, derived from the round id; repeats must return the first result. |
| Iframe + postMessage for UX only | `vgame.ready`, `vgame.balance`, `vgame.result`, `vgame.resize`… Money never depends on a browser message. |

## 1. Credentials

| Credential | Looks like | Where it lives | Stored by Vgame as |
|---|---|---|---|
| License key | `vg_live_…` | Public: in the iframe URL. Works only when framed by one of the license's `allowed_origins`. | SHA-256 hash |
| Server secret | `vg_secret_…` | Your backend only, header `X-Vgame-Secret`. Mints launch tokens and calls the Vgame APIs. | SHA-256 hash |
| Callback secret | `vg_whsec_…` | Your wallet service. Verifies the `X-Vgame-Signature` on every callback Vgame sends you. | plaintext (Vgame signs with it) |

All three are shown once, when the license is created (Admin → Licenses, or
`vgame-scratch create-license`). Rotate them with *Rotate secret* / *Rotate callback secret*
(`POST /api/v1/admin/licenses/:id/rotate-secret`, `/rotate-callback-secret`).

**`allowed_origins` is required.** List every origin (scheme + host [+ port])
that will embed the game, e.g. `https://casino.example`, `https://*.casino.example`.
`/embed` answers with `Content-Security-Policy: frame-ancestors <allowed origins>`,
so browsers refuse to render the game anywhere else, and sessions are bound to
the embedding origin.

## 2. Copy-paste embed (partner snippet)

Two steps: your **backend** mints a launch token for the logged-in player, your
**page** renders the iframe and listens for messages. A runnable copy of this
snippet is at `/demo/partner-snippet.html`.

**Backend** (Node 18+; any language works, it is one HTTPS call):

```js
// GET /casino/vgame  -> render the game page for req.user
const VGAME = 'https://play.vgame.example';
const r = await fetch(VGAME + '/api/v1/wallet/authenticate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-Vgame-Secret': process.env.VGAME_SERVER_SECRET },
  body: JSON.stringify({ player_ref: req.user.vgameRef, currency: 'TRY' }), // opaque id, no PII
});
const { launch_token } = await r.json(); // valid LAUNCH_TTL (30 min); mint one per page load
res.render('vgame', { licenseKey: process.env.VGAME_LICENSE_KEY, launchToken: launch_token });
```

**Page:**

```html
<div id="vgame-slot"></div>
<script>
  const VGAME_ORIGIN = 'https://play.vgame.example';
  const LICENSE_KEY = 'vg_live_YOUR_KEY';            // public license key
  const LAUNCH_TOKEN = '{{launchToken}}';             // from your backend, per page load

  const url = new URL('/embed', VGAME_ORIGIN);
  url.searchParams.set('license', LICENSE_KEY);
  url.searchParams.set('launch_token', LAUNCH_TOKEN);
  url.searchParams.set('game', 'cbr-mega-scratch');   // optional
  url.searchParams.set('device', 'auto');             // auto | mobile | desktop

  const frame = document.createElement('iframe');
  frame.src = url;
  frame.title = 'Vgame scratch cards';
  frame.style.cssText = 'width:100%;max-width:1280px;height:860px;border:0';
  frame.setAttribute('sandbox', 'allow-scripts allow-same-origin');
  document.getElementById('vgame-slot').append(frame);

  function toVgame(msg) { frame.contentWindow.postMessage(msg, VGAME_ORIGIN); } // never "*"

  window.addEventListener('message', (event) => {
    if (event.origin !== VGAME_ORIGIN || event.source !== frame.contentWindow) return; // ALWAYS check both
    const msg = event.data;
    if (!msg || msg.source !== 'vgame') return;

    switch (msg.type) {
      case 'vgame.ready':
        // msg.settlement: 'wallet_callback' (recommended) | 'server_confirm' | 'client_confirm' | 'transfer'
        // msg.wallet: { balance_minor, currency, source } from GetBalance, or null
        // msg.shell: 'mobile' | 'desktop'
        // Optional: push your header balance for display (also works without callbacks):
        // toVgame({ type: 'vgame.balance', balance_minor: 125000, currency: 'TRY' });
        break;

      case 'vgame.debit_request':
        // Only for postMessage-handshake licenses (section 7). With wallet callbacks
        // this never fires: your wallet gets POST {wallet_url}/debit from Vgame's server.
        break;

      case 'vgame.balance':
        // Vgame's server just got this balance from your wallet (Debit/Credit reply).
        // Refresh your header. Display only: your wallet already booked the money.
        updateHeaderBalance(msg.balance_minor, msg.currency);
        break;

      case 'vgame.result':
        // Informational. Never credit from this message; the Credit callback did it.
        break;

      case 'vgame.prize':
        showPrizeDialog(msg.label); // physical prize; the claim is queued in Vgame admin
        break;

      case 'vgame.resize':
        // Mobile shell reports its content height; the desktop shell fills the frame.
        if (msg.shell === 'mobile') frame.style.height = Math.min(Math.max(msg.height, 560), 1600) + 'px';
        break;

      case 'vgame.error':
        console.warn('Vgame', msg.code, msg.message);
        break;
    }
  });
</script>
```

### Query parameters

| Param | Required | Meaning |
|---|---|---|
| `license` | yes | Your public license key `vg_live_…` |
| `launch_token` | yes for `wallet_callback` and `transfer` | Signed player session from `POST /api/v1/wallet/authenticate`. Bound to the license and `player_ref`; expires after `LAUNCH_TTL`. |
| `player_ref` | handshake modes only | Opaque player id (max 128 chars) when you do not use a launch token. Must match the token if both are sent. No PII. |
| `game` | no | Card slug (e.g. `coin-rush`, `golden-bell`). Default: first active card. Unknown ids fall back to the default. See `GET /api/v1/games`. |
| `picker` | no | `0` hides the in-game card rail and locks the embed to `game`. Default: players can switch between active cards between tickets. |
| `device` (alias `layout`) | no | `auto` (default), `mobile` / `portrait`, `desktop` / `landscape`. See section 4. |

## 3. Settlement modes

Each license has a **settlement**, derived from its settings and returned as
`license.settlement` (admin API, `/embed/validate`) and in `vgame.ready`:

| settlement | License settings | Who moves the money | Browser role |
|---|---|---|---|
| **`wallet_callback`** (recommended) | `wallet_mode=seamless` + `wallet_url` | Vgame's server calls your wallet: Debit, Credit, Rollback, GetBalance (section 5) | none; it cannot approve a spend |
| `server_confirm` | seamless, `debit_mode=server`, no `wallet_url` | Your backend debits, then confirms to Vgame with the server secret (section 7) | relays `vgame.debit_request` to your backend |
| `client_confirm` | seamless, `debit_mode=client` | Your page confirms with `vgame.debit_ok` (**development only**, trusts the frontend) | approves |
| `transfer` | `wallet_mode=transfer` | Vgame holds a per-player wallet that you fund and drain (section 8) | none |

Set the wallet URL in Admin → Licenses (*Wallet URL*), with
`PATCH /api/v1/admin/licenses/:id {"wallet_url":"https://wallet.casino.example/vgame"}`,
or `create-license -wallet-url …`. It must be `https://` (plain `http://` only for
`localhost`), without query or fragment. `""` turns callbacks off.

## 4. Player shells: mobile and desktop

The game ships two separate frontends that share one game core
(`assets/js/embed.js`):

| Shell | Entry | Layout |
|---|---|---|
| **mobile** | `public/embed.html` + `embed-mobile.css` | Portrait gameplace: compact header with the balance chip, full-width ticket, bottom dock with the thumb-reach Buy / Reveal button and a swipeable card rail. Prizes and symbols in a collapsible panel. |
| **desktop** | `public/embed-desktop.html` + `embed-desktop.css` + `embed-desktop.js` | Landscape stage: card list on the left, large ticket in the middle (sized to the frame height), prizes and every card symbol on the right. Mouse scratching and keyboard shortcuts: <kbd>Space</kbd>/<kbd>Enter</kbd> buy · play again · reveal, <kbd>R</kbd> reveal, <kbd>↑</kbd><kbd>↓</kbd> or <kbd>1</kbd>–<kbd>9</kbd> switch card, <kbd>P</kbd> prizes, <kbd>?</kbd> help. |

**Selection rule** for `/embed`:

1. Forced entries: `/embed/mobile`, `/embed/desktop`, `/embed-desktop.html`.
2. `device=` (or `layout=`): `mobile`/`portrait` → mobile, `desktop`/`landscape` → desktop. Never overridden.
3. `auto` (default): the server makes a first guess from the browser's mobile hint
   (`Sec-CH-UA-Mobile: ?1` or a mobile User-Agent → mobile, otherwise desktop).
   The player then measures its frame before starting a session: **desktop when
   the frame is at least 900 px wide and 520 px tall, otherwise mobile**. If
   the guess was wrong it reloads once as the other shell. If the frame is later
   resized across the breakpoint (40 px hysteresis) while no ticket is in
   progress, it switches again.

All entries apply the same license check and `frame-ancestors` CSP.

**Sizing.** Size the iframe, not the game.

- Mobile: `width:100%` (≤ 520 px useful), height ≈ 860 px, or follow `vgame.resize` (`shell: "mobile"`).
- Desktop: ≥ 900 × 560; recommended 1200–1280 × 760–900. The desktop shell
  fits its ticket to the frame height, so give it a fixed height and ignore
  `vgame.resize` for it (the snippet does).

**Balance chip.** Shows the operator balance when it is known: GetBalance at
launch and after `vgame.refresh_balance`, the balances your wallet returns on
Debit/Credit, or your own `vgame.balance` message. Vgame never invents a
balance; with none known it shows "Paid via <your domain>". If the known
balance is below the ticket price, Buy is disabled and reads **Not enough
balance**. That is a display gate only: your Debit reply decides every
purchase.

## 5. Seamless Wallet callbacks (Vgame → your wallet)

With `wallet_url` set, Vgame's server calls four endpoints under it. All are
`POST`, JSON in and out, amounts in **integer minor units** (`1000` = 10.00 TRY).

### Request headers

| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `X-Vgame-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256(callback_secret, "<t>.<raw body>")>` |
| `X-Vgame-License` | the license id (`lic_…`), useful when one wallet serves several licenses |
| `X-Vgame-Action` | `balance` \| `debit` \| `credit` \| `rollback` |
| `Idempotency-Key` | the body's `transaction_id` (`request_id` for balance) |

**Verify every request** before touching money: recompute the HMAC over the
raw body, compare in constant time, and reject timestamps more than 5 minutes
off. Node:

```js
const crypto = require('crypto');
function verifyVgame(req, rawBody, secret) {             // secret = vg_whsec_…
  const parts = Object.fromEntries(req.get('X-Vgame-Signature').split(',').map((p) => p.split('=')));
  if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false;
  const want = crypto.createHmac('sha256', secret).update(parts.t + '.' + rawBody).digest('hex');
  return parts.v1 && crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(want));
}
```

### Reply format (all endpoints)

```json
{ "status": "ok", "operator_tx_id": "wtx-88121", "balance_minor": 124000, "currency": "TRY" }
{ "status": "failed", "reason": "insufficient_funds", "balance_minor": 500, "currency": "TRY" }
```

| Field | Meaning |
|---|---|
| `status` | `ok` (booked) or `failed` (definitively refused, nothing booked). |
| `reason` | for `failed`: `insufficient_funds`, `player_blocked`, `limit_exceeded`, … (≤ 64 chars) |
| `operator_tx_id` | your wallet transaction id; stored as `parent_tx_ref` for reconciliation |
| `balance_minor` | the player's balance **after** this call. Required for `balance`, recommended for the others (it drives the in-game chip). |
| `currency` | optional; if present it must equal the license currency |

How Vgame reads your HTTP status:

| Your answer | Vgame treats it as |
|---|---|
| 2xx + `status: ok` | success |
| 2xx + `status: failed` / any 4xx except 408/429 (402 = `insufficient_funds`) | definitive refusal |
| timeout (8 s), network error, 408, 429, 5xx, non-JSON 2xx, unknown status | **unknown outcome**: debits are rolled back, credits and rollbacks are retried |

### `POST {wallet_url}/balance` (GetBalance)

```json
{ "license_id": "lic_…", "player_ref": "PLAYER_123", "currency": "TRY", "request_id": "bal_…" }
```
→ `{ "status": "ok", "balance_minor": 125000, "currency": "TRY" }`

Called when the game opens and on `vgame.refresh_balance`. Display only.

### `POST {wallet_url}/debit` (bet)

```json
{
  "transaction_id": "debit_ply_4f2a…", "round_id": "ply_4f2a…", "license_id": "lic_…",
  "player_ref": "PLAYER_123", "amount_minor": 1000, "currency": "TRY",
  "game_id": "cbr-mega-scratch", "game_name": "CBR Mega Scratch", "created_at": "2026-09-27T12:00:00Z"
}
```
→ `ok` books the bet; `failed` refuses it (the player sees *Not enough balance* for
`insufficient_funds`, otherwise *Payment declined*). The amount is the server-side
card price. **The outcome does not exist yet**: the server RNG draws it only after
your `ok`.

### `POST {wallet_url}/credit` (win, closes the round)

```json
{
  "transaction_id": "credit_ply_4f2a…", "round_id": "ply_4f2a…", "reference_transaction_id": "debit_ply_4f2a…",
  "license_id": "lic_…", "player_ref": "PLAYER_123", "amount_minor": 50000, "currency": "TRY",
  "game_id": "cbr-mega-scratch", "prize_code": "cash_500", "prize_kind": "cash", "prize_label": "500.00 Cash",
  "round_closed": true, "created_at": "2026-09-27T12:00:01Z"
}
```
Sent for **every** settled round. `amount_minor` is `0` for a loss and for a
physical prize (`prize_kind: "physical"`, e.g. the CBR 1000 RR; the claim is
handled in Vgame admin). Credits must not be refused; Vgame retries an
unacknowledged credit every minute (about 2 hours) and the player sees
*Your win is being credited* until you answer `ok`.

### `POST {wallet_url}/rollback`

```json
{
  "transaction_id": "rollback_ply_4f2a…", "round_id": "ply_4f2a…", "reference_transaction_id": "debit_ply_4f2a…",
  "license_id": "lic_…", "player_ref": "PLAYER_123", "amount_minor": 1000, "currency": "TRY",
  "reason": "debit_outcome_unknown", "created_at": "2026-09-27T12:00:09Z"
}
```
Reverse the referenced debit if you booked it. If you never saw that debit,
answer `ok` anyway (nothing to reverse). Sent when your Debit reply was lost
or invalid, and when a round expired while its Debit was in flight. Retried
until acknowledged.

### Idempotency

- `transaction_id` is unique per money movement and **derived from the round**
  (`debit_<round>`, `credit_<round>`, `rollback_<round>`), so every retry of a step
  reuses its id. Store it with a unique constraint; on a repeat, return the
  original reply and move no money.
- A retried Debit after a lost reply therefore cannot double-charge, and a
  Rollback always targets exactly one debit.
- On Vgame's side each round is also idempotent on the embed's `Idempotency-Key`
  (`debit_<play_id>`): a repeated purchase request returns the stored result
  (`Idempotent-Replayed: true`) without calling you again.

### Round lifecycle

```
 Player (iframe)            Vgame server                                   Your wallet
  Buy ─ POST /plays ───────> round opened (pending, server price)
      ─ POST /plays/:id/wallet-debit ──> POST {wallet_url}/debit ───────────> book bet (idempotent)
                                        <── ok + balance ──────────────────
                                        ledger play_cost → RNG draws NOW → play_win / claim
                                        POST {wallet_url}/credit (0 or win) ─> book win, close round
                                        <── ok + balance ──────────────────
      <── result + balance ──────────── (the reveal is animation only)
      vgame.result / vgame.balance → your page (display)

  Debit refused     → 402 insufficient_funds | debit_declined, round = debit_failed, nothing to undo
  Debit unknown     → round = debit_failed, POST /rollback (retried), player sees "Wallet unavailable"
  Credit unanswered → result shown, credit retried every minute until ok
```

### Reference wallet (Express)

```js
app.post('/vgame/:action', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!verifyVgame(req, req.body.toString(), process.env.VGAME_CALLBACK_SECRET)) return res.status(401).json({ status: 'failed', reason: 'bad_signature' });
  const b = JSON.parse(req.body);
  const prev = await db.vgameTx.find(b.transaction_id);            // idempotency
  if (prev) return res.json(prev.reply);

  let reply;
  await db.transaction(async (tx) => {
    const acct = await tx.accounts.lockByPlayer(b.player_ref);
    switch (req.params.action) {
      case 'balance':  return (reply = { status: 'ok', balance_minor: acct.balance, currency: acct.currency });
      case 'debit':
        if (acct.balance < b.amount_minor) reply = { status: 'failed', reason: 'insufficient_funds', balance_minor: acct.balance };
        else reply = { status: 'ok', operator_tx_id: await tx.accounts.debit(acct, b.amount_minor), balance_minor: acct.balance - b.amount_minor };
        break;
      case 'credit':
        reply = { status: 'ok', operator_tx_id: await tx.accounts.credit(acct, b.amount_minor), balance_minor: acct.balance + b.amount_minor };
        break;
      case 'rollback': {
        const debit = await tx.vgameTx.find(b.reference_transaction_id);
        if (debit && debit.reply.status === 'ok' && !debit.rolledBack) await tx.accounts.credit(acct, b.amount_minor);
        reply = { status: 'ok', balance_minor: (await tx.accounts.lockByPlayer(b.player_ref)).balance };
        break;
      }
    }
    if (b.transaction_id) await tx.vgameTx.insert({ id: b.transaction_id, reply });
  });
  res.json({ currency: 'TRY', ...reply });
});
```

**Try it locally.** Dev servers (while `ADMIN_TOKEN` is the `dev-admin-token`
placeholder, or with `SANDBOX_OPERATOR=1`) mount a sandbox casino wallet at
`/sandbox/operator/wallet` that implements this contract (HMAC-verified,
idempotent, in-memory). Admin → Licenses → **Fill sandbox wallet values**, then
open `/demo/partner-snippet.html?license=vg_live_…`. Its drawer shows every
callback the casino received and can top up, drain, decline the next bet or
"lose" the next Debit reply to watch a Rollback.

## 6. postMessage reference

All messages are plain objects with a `type`; messages from Vgame also carry
`source: "vgame"`. Money never depends on them.

**Vgame → parent**

| type | payload |
|---|---|
| `vgame.ready` | `license_id, currency, debit_mode, wallet_mode, settlement, shell, wallet{balance_minor,currency,source} or null, session_expires_at, game{id,name,cost_minor}, games[…]` |
| `vgame.game_changed` | `game{id,name,cost_minor}` |
| `vgame.debit_request` | handshake modes only: `play_id, amount_minor, currency, game_id, game_name, idempotency_key, expires_at, debit_mode` |
| `vgame.balance` | `balance_minor, currency, source` (`operator` = your wallet's reply to a callback, `vgame` = transfer wallet). Sent whenever Vgame's server learns a new balance. |
| `vgame.result` | `play_id, game_id, amount_minor, currency, wallet_mode, settlement, win, prize{code,label,kind,amount_minor}, credit_request (handshake cash wins only, else null), credit_status, wallet{balance_minor,currency,source} or null` |
| `vgame.prize` | `play_id, claim_id, sku, label, value_minor, currency` (physical prize) |
| `vgame.resize` | `height` (CSS px), `shell` |
| `vgame.error` | `code, message, play_id?` (e.g. `insufficient_funds`, `debit_declined`, `wallet_unavailable`, `debit_timeout`, `game_locked`, `game_not_found`) |

**Parent → Vgame**

| type | payload |
|---|---|
| `vgame.balance` | `balance_minor, currency`: your balance for the chip (not in transfer mode). Buy is disabled while it is below the ticket price. Ignored if `currency` differs from the license currency. |
| `vgame.refresh_balance` | none: re-read the balance (GetBalance for `wallet_callback`, the Vgame wallet for `transfer`), e.g. after a deposit on your site |
| `vgame.select_game` | `game_id`: switch card from your own menu (refused with `game_locked` mid-ticket) |
| `vgame.debit_ok` | handshake modes: `play_id, idempotency_key, parent_tx_ref` |
| `vgame.debit_fail` | handshake modes: `play_id, idempotency_key?, reason` (e.g. `insufficient_funds`) |

Rules on both sides: check `event.origin` **and** `event.source`, and always
pass an explicit target origin, never `"*"`. The iframe only accepts messages
from the origin its session is bound to and only posts to it.

## 7. Handshake modes (`server_confirm`, `client_confirm`)

Without a `wallet_url`, a seamless license settles through a postMessage
handshake. Prefer wallet callbacks; use this when your wallet cannot accept
inbound calls.

```
 Parent page                    Vgame iframe                   Vgame server           Parent backend
     | <-- vgame.ready --------------|  POST /embed/validate  ->  | session (15m)            |
     |                               |  POST /plays           ->  | play=pending_debit       |
     | <-- vgame.debit_request ------|                            |                          |
     | -- ask your backend to debit ----------------------------------------------------> |
     |                               |                            | <- POST /plays/:id/debit-confirm (server secret)
     | -- vgame.debit_ok ----------> |  GET /plays/:id        ->  | RNG decided at confirm   |
     | <-- vgame.result -------------|  (cash win: credit_request)                          |
     | -- credit the win from the server-side result ----------------------------------->  |
     |                               |                            | <- POST /plays/:id/credit-confirm (ack)
```

Backend (server mode). Never trust amounts from the browser; read the play
with the server secret:

```js
async function vgame(path, init = {}) {
  const res = await fetch(VGAME + path, { ...init, headers: { 'Content-Type': 'application/json', 'X-Vgame-Secret': SECRET, ...(init.headers || {}) } });
  const body = await res.json();
  if (!res.ok) throw Object.assign(new Error(body.error?.message), { status: res.status, body });
  return body;
}

app.post('/wallet/vgame/debit', async (req, res) => {
  const { play_id, idempotency_key } = req.body;
  const play = await vgame(`/api/v1/plays/${encodeURIComponent(play_id)}`); // server-side price + currency
  if (play.status !== 'pending_debit') return res.status(409).json({ reason: 'not_pending' });
  const tx = await wallet.debit(req.user.id, play.amount_minor, play.currency, { idempotencyKey: `vgame:${play_id}` });
  if (!tx.ok) {
    await vgame(`/api/v1/plays/${play_id}/debit-confirm`, { method: 'POST', headers: { 'Idempotency-Key': idempotency_key },
      body: JSON.stringify({ status: 'failed', reason: 'insufficient_funds' }) });
    return res.status(402).json({ reason: 'insufficient_funds' });
  }
  const result = await vgame(`/api/v1/plays/${play_id}/debit-confirm`, { method: 'POST', headers: { 'Idempotency-Key': idempotency_key },
    body: JSON.stringify({ status: 'ok', parent_tx_ref: tx.id }) });
  if (result.credit_request) {
    const c = await wallet.credit(req.user.id, result.credit_request.amount_minor, result.currency, { idempotencyKey: result.credit_request.reference });
    await vgame(`/api/v1/plays/${play_id}/credit-confirm`, { method: 'POST', body: JSON.stringify({ parent_tx_ref: c.id }) });
  }
  res.json({ parent_tx_ref: tx.id });
});
```

`debit-confirm` rules: `Idempotency-Key` (or body `idempotency_key`) required, 8–128
chars of `[A-Za-z0-9_-:.]`, suggested `debit_<play_id>`; a repeat returns the stored
response (`Idempotent-Replayed: true`); a different key on a finalised play →
`409 already_finalized`; one key on two plays → `409 idempotency_key_reused`;
after `PLAY_PENDING_TTL` (10 min) → `410 play_expired` (refund if you debited).
`debit-confirm` on a `wallet_callback` license → `409 wallet_callback_mode`.

In `client_confirm` the iframe itself calls `debit-confirm` after your page sends
`vgame.debit_ok`. That trusts your frontend; development and demos only
(`/demo/parent.html`).

## 8. Transfer wallet

In `transfer` mode Vgame keeps a wallet per `(license, player_ref)`. Your
backend moves money in and out with the wallet API; plays are paid from, and
cash wins paid into, that wallet by Vgame. There is no handshake.

All endpoints are `POST`, JSON, `X-Vgame-Secret`, server-to-server only:

| Path under `/api/v1/wallet` | Aliases | Body | Returns |
|---|---|---|---|
| `/authenticate` | | `player_ref`, `currency?` | transfer: opens the wallet if new, `player_ref, currency, balance_minor, created, launch_token, launch_expires_at`. seamless: `player_ref, currency, settlement, launch_token, launch_expires_at` (+ `balance_minor` from GetBalance with wallet callbacks) |
| `/getBalance` | `/balance` | `player_ref` | `player_ref, currency, balance_minor, updated_at` |
| `/withdraw` | `/debit` | `player_ref, amount_minor, currency, idempotency_key, round_ref?` | the wallet transaction |
| `/deposit` | `/credit` | `player_ref, amount_minor, currency, idempotency_key, round_ref?` | the wallet transaction |
| `/transactions` | | `player_ref, limit?` (max 200) | newest-first deposits, withdrawals, bets and wins |

Paths are case-insensitive (`/GetBalance`, `/Withdraw` work); `player_id` is a
synonym for `player_ref`; the idempotency key may also be the `Idempotency-Key`
header or `transaction_id` (8–128 chars; keys starting with `vgame:` are reserved).
Repeats return the original transaction (`Idempotent-Replayed: true`); a key reused
for a different amount/player/kind → `409 idempotency_key_reused`; a withdraw above
the balance → `402 insufficient_funds` (key not consumed). Every movement is a
hash-chained ledger event written with the balance update.

The embed pays with `POST /api/v1/plays/:id/wallet-debit` (session auth,
`Idempotency-Key`): bet, RNG and cash win in one transaction. With too little
balance it returns `402 insufficient_funds` and leaves the play pending. Try it at
`/demo/transfer.html`.

## 9. Errors

Errors are JSON: `{"error": {"code": "...", "message": "..."}}`.

| HTTP | code | when |
|---|---|---|
| 400 | `invalid_idempotency_key`, `invalid_amount`, `invalid_currency`, `invalid_wallet_url`, `game_required`, `parent_origin_required`, … | bad input |
| 401 | `invalid_license`, `session_invalid`, `invalid_secret`, `launch_required`, `launch_invalid` | bad credentials, expired session or launch token |
| 402 | `insufficient_funds`, `debit_declined` | your wallet (callbacks) or the transfer wallet refused the bet |
| 403 | `origin_not_allowed`, `license_revoked`, `server_confirmation_required`, `player_mismatch`, `player_required` | policy |
| 404 | `not_found`, `player_not_found` | unknown play (or another session's), unknown transfer-wallet player |
| 409 | `already_finalized`, `idempotency_key_reused`, `idempotency_key_mismatch`, `no_credit_due`, `wallet_mode_mismatch`, `wallet_mode_transfer`, `wallet_mode_seamless`, `wallet_callback_mode`, `currency_mismatch` | state conflicts |
| 410 | `play_expired` | round expired |
| 429 | `rate_limited` | per-license play rate limit (`Retry-After`) |
| 502 | `wallet_unavailable` | your wallet did not give a usable Debit/GetBalance answer; any debit is rolled back |

## 10. Trust model

- The license key is public. `frame-ancestors`, origin checks at session
  creation and revocation protect it.
- Whenever Vgame moves a player's money (`wallet_callback`, `transfer`), the
  player is named by a launch token only your server secret can mint; a bare
  `player_ref` from the browser is refused (`launch_required`).
- Sessions are HS256 JWTs (15 min) bound to license and parent origin; license
  status and allowed origins are re-checked on every request.
- Prices come from the game config, outcomes from a crypto RNG drawn only after
  the bet is booked, and every movement is written to the append-only,
  hash-chained ledger (`play_cost`, `play_win`, `win_credited`).
- Wallet callbacks are HMAC-signed with a per-license secret, carry
  deterministic `transaction_id`s, and are retried or rolled back until your
  wallet and the ledger agree.
