# YeeGame Integration Guide

For operators (casino platforms, called “the operator” below) that want to offer YeeGame games. YeeGame is the game provider: game pages, tables and draws live at YeeGame; the money always stays in the operator’s wallet. YeeGame holds no player balances — every bet, payout, buy-in and cash-out calls the operator’s wallet API in real time.

- Production: `https://api.yee.pub`; staging: `https://yeegame-staging.root-d7f.workers.dev`
- Protocol: the common aggregator seamless-wallet protocol. If you have integrated such an aggregator before, register YeeGame as one more aggregator — usually no code is needed.
- Status: final (2026-11-30, G9). Every endpoint, field and status code below is implemented and covered by tests; where this document and the code disagree the code wins — please tell us so we fix the document. Chinese version: [protocol-zh.md](protocol-zh.md) (same content).

## 1. Onboarding

YeeGame gives the operator:

| Item | Notes |
|---|---|
| `API Key` | Identifies the operator; used in both directions |
| `API Secret` | Signing key, used in both directions, server-side only. Shown once at registration and on rotation; the old one stops working immediately after a rotation |
| Currency | One currency per operator. Currently `USDT`, `USD` (amounts of different operators at the same table are added directly, so only 1:1 currencies are supported) |
| Read-only statement password (optional) | To view your clearing statements (section 7); unrelated to the Secret, cannot move money |

The operator gives YeeGame:

| Item | Notes |
|---|---|
| Wallet callback URL | e.g. `https://api.example.com/gp`; YeeGame appends `/wallet/bet` etc. Must be https |
| Egress IPs (optional) | If given, only these addresses (or IPv4 ranges) may call YeeGame |
| Wallet timeout (optional) | How long YeeGame waits for your wallet; default 4 s (0.5–15 s) |
| Supported extensions (optional) | Nickname/avatar, deep links, notifications, group messages (section 8) |

## 2. Signing and general rules

Both directions use `POST`, `Content-Type: application/json`, and the headers:

```
X-API-Key: <API Key>
X-Signature: <lowercase hex( HMAC-SHA256( API Secret, raw request body ) )>
```

- The signature covers the **raw body bytes**. Verify first, then parse the JSON; do not re-serialise before verifying.
- Responses are always HTTP 200 with `{ "traceId": "...", "status": "SC_OK", "data": { ... } }`. Any `status` other than `SC_OK` is a failure; `message` may explain.
- Amounts are decimals with at most two places (`12.5` means 12.50). Times are millisecond timestamps (UTC).
- Every request carries a `traceId` that is **different every time** (retries too). When YeeGame calls you it likewise uses a fresh `traceId` and `timestamp` and re-signs; the `transactionId` stays the same.
- For your calls to `/game/url`, the same `traceId` from the same operator is accepted only once within two days; a repeat gets `SC_INVALID_REQUEST` (`message: traceId already used`) — replaying a captured signed request does not yield a new game URL.
- Maximum body 64 KB; `POST` only (other methods get HTTP 405).

Statuses you may receive from YeeGame:

| Status | Meaning |
|---|---|
| `SC_OK` | Success |
| `SC_AUTHENTICATION_FAILED` | Unknown key, operator disabled, or source IP not allowed (`message: ip not allowed`) |
| `SC_INVALID_SIGNATURE` | Bad signature |
| `SC_INVALID_REQUEST` | Bad parameters, broken JSON, repeated `traceId` (`message` names the field) |
| `SC_INVALID_GAME` | No such game, or it is switched off |
| `SC_UNDER_MAINTENANCE` | The game is in maintenance, your operator status is maintenance, or YeeGame as a whole is in maintenance |
| `SC_WRONG_CURRENCY` | Currency differs from the one registered |
| `SC_INTERNAL_ERROR` | Internal error at YeeGame; safe to retry |

## 3. Operator → YeeGame

### 3.1 `POST /game/vendors`

`data`: `{ "vendors": [{ "code": "YEEGAME", "name": "YeeGame", "currencies": ["USDT"] }] }`.

### 3.2 `POST /game/list`

Request: `{ "traceId", "vendorCode"?, "pageNo"?, "pageSize"? (max 500, default 100), "displayLanguage"? }` (languages: `zh` `en` `my` `bn` `fil` `pt-BR`). A `vendorCode` other than `YEEGAME` returns an empty list.

`data`:

```json
{ "currentPage": 1, "totalItems": 3, "totalPages": 1,
  "games": [{ "gameCode": "hlh", "gameName": "Hash Dragon Tiger", "vendorCode": "YEEGAME", "categoryCode": "TABLE",
              "imageSquare": "", "orientation": "portrait", "status": "ACTIVE", "currencies": ["USDT"] }] }
```

Only games that are on or in maintenance are listed (`status` `ACTIVE` / `MAINTENANCE`). Game codes:

| Kind | Game codes |
|---|---|
| Hash (house-banked; player banking optional) | `hlh` Hash Dragon Tiger, `hbjl` Hash Baccarat, `hsg` Hash Sam Gong |
| Blackjack (house-banked; player banking optional) | `bj` |
| PvP (players against each other, seated) | `sss` Chinese Poker, `ofc` Pineapple OFC, `gd` Guandan, `hzmj` Hongzhong Mahjong, `ddz` Dou Dizhu, `sk` Shuangkou, `mq` Mingkou, `xzmj` Bloody Mahjong, `kdmj` Koudian Mahjong, `nn` Niu Niu, `nn12` 12-player Niu Niu, `zjh` Zha Jin Hua |

### 3.3 `POST /game/url`

| Field | Required | Notes |
|---|---|---|
| `username` | yes | Your player id. 1–64 printable ASCII characters; treated as an opaque string |
| `gameCode` | yes (optional when `room` is given) | A code from the catalogue |
| `language` | no | Page language, default `en` |
| `currency` | no | Must equal the registered currency, otherwise `SC_WRONG_CURRENCY` |
| `lobbyUrl` | no | Where “back” takes the player (http/https) |
| `nickname`, `avatarUrl` | no | Name (max 24 chars; control characters and `<>` removed) and avatar shown to table-mates in PvP games. Without them an anonymous code “Player·a3f9” is shown |
| `room`, `deepLink` | no | Deep links (8.6): a private-room code; the deep-link template for this launch |

`data`: `{ "gameUrl": "https://game.yee.pub/hash/?gameCode=hlh&token=lt_…&language=zh", "token": "yg_…" }`

- `gameUrl`: open it directly or in an iframe (no cookies are used; works in iframes). The entry token in it is single-use and valid for 5 minutes; the game session it becomes lasts 24 hours.
- `token`: the **session token**. YeeGame sends it back on `balance`, `bet` and `bet_debit` calls (and also on payouts/cash-outs). Treat it as “this player’s latest launch”: **accept only the token from your most recent `/game/url` for that player** and answer `SC_INVALID_TOKEN` for anything else (including tokens you never saw). This is what stops old pages and leaked game URLs from debiting money. Payouts, cash-outs, rollbacks and adjustments are not subject to it (4.3).
- Page ↔ parent window contract (optional): `postMessage` `{ type: 'yf:balance', balance, currency }` when the balance changes, `{ type: 'yf:close' }` when the player taps back.

Errors: `SC_INVALID_GAME`, `SC_UNDER_MAINTENANCE`, `SC_WRONG_CURRENCY`, `SC_INVALID_REQUEST` (parameters, `room` not matching `gameCode`, bad `deepLink`, repeated `traceId`).

### 3.4 `POST /game/terminate`

`{ "username" }` → all of this player’s YeeGame sessions and unused entry tokens are invalidated; `data`: `{ "terminated": <sessions> }`. Bets already placed are drawn and settled as usual; if the player sits at a PvP table they are asked to leave (the hand in progress is auto-played to the end) and their chips are cashed out as usual (`bet_credit`).

### 3.5 `POST /transaction/list`

Reconciliation. `{ "fromTime", "toTime", "pageNo"?, "pageSize"? (max 2000) }`, at most one day, by **completion time**, your own records only. One row per bet, buy-in/cash-out or adjustment (grouped by `betId`):

```json
{ "username": "u1", "betId": "…", "roundId": "hlh-88459149", "externalTransactionId": "…", "gameCode": "hlh", "currency": "USDT",
  "betAmount": 5, "winAmount": 10, "jackpotAmount": 0, "effectiveTurnover": 5, "winLoss": 5,
  "status": 1, "isFreespin": 0, "betTime": 1796051772349, "settledTime": 1796051818502 }
```

- `status`: 1 settled, 2 cancelled (rolled back, all amounts 0).
- Rows come from: each bet result (`bet_result`), each cash-out (`bet_credit`; `betAmount` is that buy-in), rollbacks, adjustments (`adjustment`, `betAmount` 0). Operations still being retried or in the manual queue are listed too (with the amounts YeeGame recorded); anything you did not receive yet arrives later with the same transaction id.

## 4. YeeGame → operator wallet

URL = wallet callback URL + path. Except `balance`, every request carries `traceId`, `timestamp`, `username`, `currency`, `transactionId` (and the same value as `externalTransactionId`), `gameCode`, `roundId`, and `token` when a session token exists.

The response `data` must contain at least `{ "username", "currency", "balance" }`, where `balance` is the balance after this operation.

### 4.1 Endpoints

| Path | When | Fields (besides the common ones) | Balance |
|---|---|---|---|
| `/wallet/balance` | Entry, refresh | `username`, `currency`, `token` (no `timestamp`) | unchanged |
| `/wallet/bet` | A bet (each hash / blackjack bet; double, split, insurance are separate bets) | `betId`, `amount`, `token` | − `amount` |
| `/wallet/bet_result` | A bet’s result | `betId`, `betAmount`, `winAmount`, `effectiveTurnover`, `winLoss`, `jackpotAmount` (0), `resultType` (`WIN` / `LOSE`), `isFreespin` (0), `isEndRound`, `betTime`, `settledTime` | + `winAmount` |
| `/wallet/rollback` | Cancel a bet / buy-in (missed the round, round voided, no answer to a debit) | `betId` | + what was debited |
| `/wallet/bet_debit` | Buy-in: PvP seat or top-up; player-bank deposit for hash / blackjack | `amount`, `takeAll` (0), `token`; **`roundId` is this buy-in’s id and also its bet id** | − `amount` |
| `/wallet/bet_credit` | Cash-out: leaving a PvP table; bank deposit returned / banker steps down | `betId` (= that buy-in’s `roundId`), `amount`, `betAmount`, `winAmount`, `effectiveTurnover`, `winLoss`, `jackpotAmount` (0), `isRefund`, `betTime`, `settledTime` | + `amount` |
| `/wallet/adjustment` | A late PvP win paid to a player already cashed out (rare, see 5.3) | `amount` (signed; YeeGame only sends positive), `roundId` = that seating’s id | + `amount` |

- Push: `resultType` is `WIN`, `winAmount` equals the stake, `effectiveTurnover` is 0.
- `effectiveTurnover` counts only the part that was really at risk; refunded stakes do not count (see section 5).
- `isEndRound` is only a hint (the player’s last result in the round); never make settlement depend on it.
- A buy-in’s `bet_debit`, its rollback and its `bet_credit` share one id: `bet_debit.roundId` = `rollback.betId` = `bet_credit.betId`. Book a buy-in as a bet whose bet id is its `roundId` (the rollback-first tombstone rule applies to it too).

### 4.2 Status codes (your answers to YeeGame)

| Status | Meaning | What YeeGame does |
|---|---|---|
| `SC_OK` | Success | — |
| `SC_INSUFFICIENT_FUNDS` | Not enough balance | Bet / buy-in not placed, player is told |
| `SC_USER_DISABLED`, `SC_USER_NOT_EXISTS` | Player disabled / unknown | Not placed, the session is closed |
| `SC_INVALID_TOKEN` | Session token is not the latest | Same |
| `SC_GAME_DISABLED` | You switched this game off | Not placed |
| `SC_DUPLICATE_REQUEST` | This `transactionId` was already processed | Treated as success |
| `SC_TRANSACTION_NOT_EXISTS` | Rollback for an unknown bet | Treated as success (rule 3 in 4.3) |
| `SC_INTERNAL_ERROR`, `SC_OPERATOR_TIMEOUT`, `SC_TRANSACTION_STILL_PROCESSING`, `SC_TOO_MANY_CONCURRENT_REQUESTS`, `SC_UNDER_MAINTENANCE`, or a timeout / non-200 / unreadable response | No outcome | Resent with **the same `transactionId`** |
| Anything else | Explicit refusal | Debits: not placed; payouts: moved to the manual queue with an alert (see rule 2 in 4.3 — please never answer this way) |

### 4.3 The four rules

1. **De-duplicate by `transactionId`.** The same `transactionId` may arrive several times (YeeGame resends when it gets no answer; each attempt has a new `traceId` and `timestamp`, and a resend may arrive while you are still processing the previous attempt). From the second time on, do not move money again; return the first result (or `SC_DUPLICATE_REQUEST`).
2. **Never refuse payouts, cash-outs, rollbacks or adjustments.** `bet_result`, `bet_credit`, `rollback` and `adjustment` are money owed to the player: do not refuse or hold them because the token expired, the player went offline, was disabled, the game was switched off or a risk rule fired — credit first, review afterwards. YeeGame resends them until they succeed: 3 attempts immediately, then the scheduler retries every minute for the first 5 times and every 5 minutes after that; an alert fires after 5 retries, and after 48 hours the operation enters YeeGame’s manual queue to be reconciled with you (YeeGame never transfers money on anyone’s behalf).
3. **A rollback may arrive before its bet, or refer to a bet you never saw.** When YeeGame gets no answer to a debit it sends a `rollback` and abandons the bet. If you cannot find the bet, answer `SC_TRANSACTION_NOT_EXISTS` and **remember that `betId`** (for a buy-in: its `roundId`): a late `bet` / `bet_debit` for it must then be refused (otherwise the player is charged for a bet that does not exist).
4. **Answer debits fast.** Please answer `bet` and `bet_debit` within 3 seconds (the timeout is the one registered, default 4 s). Without an outcome YeeGame retries once after 0.4 s with the same transaction id; still nothing, it rolls back and tells the player the bet was not placed.

Also: wallet calls for the same player are sent one at a time, never two at once; different players are served concurrently.

### 4.4 What transaction ids look like

`transactionId` is generated by YeeGame, at most 64 characters, always the same for the same business step; store it as an opaque string. The prefix is only for humans:

| Prefix | Meaning |
|---|---|
| `b:` | Bet (`bet`) |
| `r:` | A bet’s result (`bet_result`) |
| `x:` | Rollback (`rollback`): `x:<bet id>`, or `x:<that operation’s transaction id>` (e.g. `x:b:…`, `x:i:…`) when abandoning a debit without an outcome |
| `i:` | Buy-in (`bet_debit`): PvP seat / top-up, player-bank deposit |
| `o:` | Cash-out (`bet_credit`) |
| `a:` | Adjustment (`adjustment`): `a:<hand id>.<seat>` |

## 5. How each kind of game moves money

| Game | Entry | During play | End |
|---|---|---|---|
| Hash (three games) | `balance` | One `bet` per bet; bets that missed the close, or a voided round, are rolled back | One `bet_result` per bet |
| Blackjack | `balance` | One `bet` per bet (double, split, insurance, side bets are separate); cancellations rolled back | One `bet_result` per bet |
| PvP | `balance` | Seat: `bet_debit` buy-in; top-up: another `bet_debit`; wins and losses at the table are booked by YeeGame, not per hand | Leaving: one `bet_credit` per buy-in |
| Player bank (hash, blackjack; off by default) | — | Bid deposit `bet_debit` | Step down, not chosen, cancelled: `bet_credit` |

### 5.1 PvP buy-ins and cash-outs (as implemented)

- **Seat**: one `bet_debit`; `roundId` is this seating’s id (`s_` + 20 hex chars); transaction id `i:<id>`.
- **Top-up**: another `bet_debit` with `roundId` `<seating id>.<n>` (`.1`, `.2`, …). In the common protocol one buy-in maps to one cash-out, so every top-up is a new buy-in. **There is no partial cash-out mid-session**; chips leave the table only when the player leaves.
- **Leaving** (stand up, quit, removed by the room owner, your `/game/terminate`, table closed, private room dissolved): the remaining chips are split over the buy-ins in proportion to their amounts (rounded down, leftover cents go to the first ones), and each buy-in gets one `bet_credit`:
  - `betId` = that buy-in’s `roundId`, transaction id `o:<roundId>`;
  - `betAmount` = that buy-in’s amount; `amount` = `winAmount` = its share of the chips; `winLoss` = `amount − betAmount`;
  - `effectiveTurnover`: chips actually lost during this seating, `max(0, total buy-in − total cash-out)`, reported on the first buy-in only (0 on the others); 0 for winners;
  - left without playing a hand: `isRefund` = 1, full refund, turnover 0.
- The cash-out amount is taken only from YeeGame’s books and is recorded before it is sent (must-deliver, rule 2 in 4.3). YeeGame does not wait for your answer, so a slow wallet never blocks a table.
- Rake (public tables), table fees (private rooms) and the Pineapple jackpot fee/prize are settled in table chips, not through the wallet; therefore “buy-in + table result − rake − fees − jackpot fee + jackpot prize = cash-out”. Each hand’s figures are shown to players in the hand history.
- A player can sit at only one table at a time (sitting elsewhere is refused; no money moves).

### 5.2 Player-bank deposits

Hash games and blackjack can let players be the bank (off by default; you will be told before it is switched on): a bid deposit is one `bet_debit` (transaction id `i:<deposit id>`); stepping down, not being chosen, cancelling or a table close is one `bet_credit` (`o:<deposit id>`, `amount` = bank pool minus the platform fee; a full refund has `isRefund` = 1 and turnover 0). Changing the bid = full refund of the old deposit + a new buy-in for the new amount.

### 5.3 Adjustments (`adjustment`)

Sent in one case only: after a rare failure a PvP table is restored from an older snapshot, a player whose chips were already cashed out is still part of the hand in progress, and that hand he wins. The win (minus rake) is paid to him as an `adjustment`, transaction id `a:<hand id>.<seat>`, `roundId` = his seating id, must-deliver. If he loses that hand it counts as 0; YeeGame never claims money from you this way.

## 6. Fairness

- **Hash**: when a round opens, the height of the TRON block that will decide it (the round number) is announced — that block does not exist yet. When bets close, a digest of all bets is published and two Telegram dice are rolled in one operator’s public verification group (8.7; every round). Once the block and 3 more blocks are produced the round is drawn: the deck is shuffled from “block hash + round number”, cut by the product of the two dice, and dealt. Neither the block hash nor the dice exist when bets are placed, so nobody (player, operator, YeeGame) can predict or influence the result. A round whose dice could not be rolled has no cut (0 cards), and says so. Anyone can recompute at `https://<YeeGame domain>/hash/verify.html?q=<round>` (in the browser; the page shows the dice values and a link to the Telegram message); block hashes can be looked up by height in any TRON explorer.
- **Blackjack**: each shoe publishes a commitment (hash of the seed) when it opens and reveals the seed when it is replaced; the two cut dice are rolled from the fairness session seed, or by your bot in your Telegram group when you declared `group.dice` (8.7). Verify pages: `/bj/verify.html?q=<commitment / shoe / round>` and `/fair/verify?id=<id>`.
- **PvP**: each hand publishes a commitment at the start and reveals the seed after settlement; the hand history can re-shuffle and re-deal to check. Bots (if enabled) see only their own cards.

## 7. Cross-operator tables and clearing

PvP games can seat players of different operators at the same table (by default players are matched only with your own players). When A’s player wins money from B’s player, A’s wallet paid out more and B’s took in more; YeeGame issues periodic clearing statements for the difference — operators never settle with each other directly. **YeeGame only issues statements and records settlement; it never transfers money for anyone.**

One statement per period (weekly by default, Monday–Sunday UTC):

```
Players' net = PvP: table result − rake − table fees − jackpot fees + jackpot prizes (booked when each hand ends)     Bet games: payouts − bets
Share        = (rake your players paid + table fees they paid + player-bank fees) × share ratio, rounded down
Payable      = −players' net − share        positive: you pay YeeGame; negative: YeeGame pays you
```

- Rake applies only at public PvP tables: a percentage (default 5%) of each winner’s net win per hand, rounded down to the cent, capped per hand (default 20 base units), nothing when there is no win; Zha Jin Hua is raked on the pot, and a hand where only one player put money in is not raked. Table fees apply only in private rooms, per hand. Both are shown to players on the table page and recorded per hand in the hand history.
- Statement states: draft → confirmed (you confirm on the statement page; drafts are auto-confirmed 3 days after issue) → settled (after both sides transferred offline, YeeGame records the transfer hash/reference and time).
- Statement page: `https://<YeeGame domain>/op/`, sign in with the **read-only password** YeeGame gives you (not the API Secret; it can only view your statements and confirm; 5 wrong attempts lock it for 15 minutes). It shows per-game and per-day details, your credit limit and exposure. Six languages.
- Credit limit: at 80% of the limit YeeGame raises an alert; at the limit your players **temporarily cannot take new seats at cross-operator tables** (players already seated keep playing, cash out and top up normally; tables with only your players and bet games are unaffected). Overdue confirmed statements have the same effect.
- Bots: YeeGame can fill public tables that lack players with bots (marked “bot” in name and seat, funded by YeeGame’s own pool, seeing only their own cards). Off for every operator by default; if bots are allowed in your region you can ask for them. Only operators with bots enabled are ever seated with bots.
- Period, currency, deposit, payment terms, overdue handling and limits are agreed before cross-operator tables are opened. Operators offering only bet games (hash, blackjack) also receive statements (house-banked results), without the cross-operator part.

## 8. Telegram extensions (optional)

If your site is a Telegram mini app / bot you can implement a few extra endpoints so YeeGame games get group betting, draw cards, dice cuts, private-room cards, reports, notifications and deep links. All optional: without them the related entries simply do not appear on the pages; tables and rounds work as usual.

### 8.1 Declaration

Tell YeeGame at onboarding which items you support (stored in your `ext`):

```json
{ "notify": 1,
  "group": { "send": 1, "dice": 1, "bet": 1 },
  "deeplink": "https://t.me/<your bot>?startapp=yg_{code}",
  "scale": 100 }
```

| Item | Meaning | When not declared |
|---|---|---|
| `notify` | You implement `POST <callback URL>/notify` | No notifications or reports |
| `group.send` | You implement `POST <callback URL>/group/send` | No draw cards or room cards; no “send to chat” button |
| `group.dice` | You implement `POST <callback URL>/group/dice` | Blackjack cut dice are rolled from the fairness seed (stated on the verify page); hash dice are never rolled in your group |
| `group.bet` | You forward group bets to YeeGame’s `POST /group/bet` | `/group/bet` answers `SC_INVALID_REQUEST` |
| `deeplink` | Deep-link template (https, with `{code}`); `{code}` becomes `<game>-<room>` (e.g. `sss-123456`, valid in Telegram startapp) | Private rooms show only the room number to type in; no “copy link” |
| `scale` | How amounts shown to players and amounts in group bet texts are written: `100` (default) = currency units with two decimals; `1` = integer cents (when your “coin” is 0.01) | 100 |

`"group": 1` means all three. If one operator has several bots (e.g. several white labels), leave `deeplink` out and pass `deepLink` on each `/game/url` instead (8.6).

Signing and response format are exactly as for the wallet (section 2). YeeGame’s calls to your extension endpoints time out after 4 s (dice: 15 s). Without an outcome (timeout, non-200, `SC_INTERNAL_ERROR`, `SC_UNDER_MAINTENANCE`, …) notifications are resent every minute until they expire; cards go stale quickly and are not resent; explicit refusals (`SC_USER_NOT_EXISTS`, `SC_INVALID_REQUEST`) are not resent. **None of these calls is awaited**: if your endpoints are down or slow, tables and rounds continue.

### 8.2 Buttons

Buttons in cards and notifications are “one array per row”; each button is one of the following, rendered as your own button:

| Form | Meaning |
|---|---|
| `{ "text", "open": { "game", "room"? } }` | Open your own mini app / page into this game (`room` = six-digit private room). Pass `room` back to `/game/url` (8.6) |
| `{ "text", "url" }` | Plain link (verify page, a filled-in deep link) |
| `{ "text", "chip": amount }` | Chip on a group draw card: remember this person’s chosen chip (in `scale` units) |
| `{ "text", "bet": { "game", "area" } }` | Betting area on a group draw card: place one bet with the remembered chip (forward to `/group/bet`, 8.5) |
| `{ "text", "copy": "123456" }` | Copy to clipboard (room number) |

Texts are Telegram HTML (`<b>` `<code>` `<a>`), already written in the right language; `image` is a YeeGame URL (1200×630 JPEG without any brand or text).

### 8.3 `POST <callback URL>/notify`

Sends one notification to a player who is not on the game page.

```json
{ "traceId": "…", "timestamp": 1796051772349,
  "username": "u1", "kind": "table", "code": "room.push.ask", "lang": "en",
  "text": "[Chinese Poker room 123456] Player·a3f9 asks to buy in 8 chips, please return to the table.",
  "buttons": [[{ "text": "🀄 Back to table", "open": { "game": "sss", "room": "123456" }, "url": "https://t.me/…?startapp=yg_sss-123456" }],
              [{ "text": "📋 Copy room number 123456", "copy": "123456" }]],
  "game": "sss", "room": { "game": "sss", "code": "123456" }, "link": "https://t.me/…?startapp=yg_sss-123456", "ttl": 120000 }
```

- `kind`: `table` (table reminders; `code` is `room.push.ask` buy-in request / `room.push.approved` / `room.push.rejected` / `room.push.started`) or `report` (private-room report, `code` = `bot.report`, plus an `image` and `win`: this person came first).
- `lang`: the player’s language at launch (`/game/url` `language`); `text` is written in it. `ttl`: no need to deliver after this many ms. `link` is present only when a deep-link template is registered (or was given at launch).
- Answer `SC_OK` (sent or queued on your side), `SC_USER_NOT_EXISTS` (no such person / cannot receive messages); anything else is handled as in 8.1.

### 8.4 `POST <callback URL>/group/send`

Sends a card to a group (or to one person). `content` has one entry per language (`zh` `en` `my` `bn` `fil` `pt-BR`); pick by the group’s / person’s language, falling back to `en`.

```json
{ "traceId": "…", "timestamp": 1796051772349,
  "kind": "hash", "key": "hash:hlh", "target": { "type": "hash", "game": "hlh" },
  "frame": { "kind": "result", "n": 81234567, "round": "hlh-81234567", "at": 1796051772349, "sig": "" },
  "image": "https://game.yee.pub/img/share/h_hlh.jpg",
  "content": { "en": { "text": "🏁 <b>Hash Dragon Tiger</b> · round <code>81234567</code> · result…", "buttons": [[{ "text": "🔍 Verify this round", "url": "https://game.yee.pub/hash/verify.html?q=hlh-81234567" }, { "text": "🎰 Play hash games", "open": { "game": "hlh" } }]] }, "zh": { … } },
  "tails": { "<chat>": { "en": "👥 5 bets in this group, 3 won · top win A** +950", "zh": "…" } } }
```

| `target.type` | Destination | Used for |
|---|---|---|
| `hash` | Every group of yours where this hash game is enabled (you manage which) | Per-round cards: `frame.kind` = `open` / `bets` (totals changed; at most every 4 s) / `close` / `result` / `idle` (waiting for bets: rounds without bets, voided rounds). **The same `key` is the same card**: later frames of the same round (`frame.n`) should edit the earlier message; a new round starts a new one; `bets` frames with an unchanged `sig` may be skipped. On result frames, `tails` holds each group’s own line (keyed by the `chat` you sent in `/group/bet`), appended to the card text; groups without one get nothing |
| `user` + `username` | That player (who forwards it to friends) | Private-room card: the player tapped “send to chat” on the table page (`kind` = `room`, `edit` = false, `room` = the room); later changes (seats, start, end, dissolved) are sent with the same `key` (`room:<room>`), `edit` = true, `frame.phase` = `waiting` / `playing` / `final` / `gone` — edit the earlier message if you can, otherwise ignore |

Answer `SC_OK`. Hash cards are not resent on failure; the first, final and dissolved room cards are resent for 5 minutes.

### 8.5 YeeGame’s `POST /group/bet` (you call YeeGame)

When someone bets in a group (replying to a YeeGame card with e.g. “B100 PP10”, sending `/b D100`, tapping a betting-area button), forward it to YeeGame. Signed as in section 2. Parsing (game names, area names and their aliases in each language, amount before or after, full-width digits, at most 10 bets per message, amounts must be multiples of the minimum unit) is identical to the built-in group betting of the YF site.

```json
{ "traceId": "…", "username": "u1", "chat": "-1001234567890", "msg": "5521", "lang": "en", "name": "Annie",
  "text": "B100 PP10",
  "card": { "game": "hbjl", "n": 81234567 },
  "games": ["hlh", "hbjl"],
  "bet": { "game": "hlh", "area": "L", "amt": 100 }, "key": "cb123456",
  "token": "…" }
```

| Field | Notes |
|---|---|
| `username` | Player id (as for the wallet). Check first that they may bet (enabled, not banned); reply to them yourself if not, no need to forward |
| `chat`, `msg` | The group (1–64 printable ASCII characters, used verbatim as the key of `tails` on result cards) and the message id. **Bet ids are derived from “group + message + bet index”**: forwarding the same message twice does not bet twice |
| `name` | Their display name in the group, only for the “top win” line on result cards (masked to the first character) |
| `text` + `card` | They replied to a YeeGame card: `card` is that card’s game and round (`frame.n`); a reply to an old round is not placed on the new round |
| `text` + `games` | The text after `/b`; `games` are the games enabled in that group (a game name in the text selects it; may be omitted if only one) |
| `bet` + `key` | A betting-area button: one bet; `amt` is their remembered chip (in `scale` units); `key` identifies this tap (6–24 lowercase letters/digits): **the same `key` bets only once** |
| `token` | Optional: passed back on the wallet `bet` call (so you can recognise group bets without a game session) |

`data`:

- `{ "ignored": true }`: not a bet (just chat); do nothing.
- `{ "game", "placed": [{ "area", "amt" }], "failed": [{ "area", "amt", "code" }], "mine": { "<area>": round total }, "total", "reply" }`: `reply` is an HTML snippet in `lang` (“✅ Placed Banker 100, Player Pair 10 (110 in this round)”, “❌ Banker 105: amount must be a multiple of 10”, …) to post under the original message; for button bets, strip the tags and show it as a toast.

Each bet is exactly a page bet: recorded first, then your wallet `bet` (`transactionId` = `b:<bet id>`), then `bet_result` / `rollback` as usual (4.1). Without `group.bet` declared: `SC_INVALID_REQUEST`.

### 8.6 Deep links

- Links YeeGame produces: the registered `deeplink` template (or the `deepLink` given at this launch, which wins) with `{code}` replaced by `<game>-<room>`. Used by “copy link” in private rooms and by buttons in notifications and cards; without a template there is only the button’s `open` and you build the link.
- When a player opens one, pass the room code back to `/game/url`: `{ "username", "room": "sss-123456" }` (`gameCode` may be omitted and is taken from the code; with only the six digits, `gameCode` is required). The returned `gameUrl` carries `room=123456` and the page enters that private room directly. Room code and `gameCode` mismatch: `SC_INVALID_REQUEST`.
- `deepLink` on `/game/url`: an https URL containing `{code}`, at most 400 characters.

### 8.7 `POST <callback URL>/group/dice`

When blackjack opens a new shoe, YeeGame asks your bot to roll the cut dice in your verification group (the values are decided by Telegram; nobody can change them).

```json
{ "traceId": "…", "timestamp": 1796051772349, "username": "u1", "game": "bj", "gameName": "Blackjack", "gameNames": { "zh": "21 点", "en": "Blackjack", … },
  "ref": "bj-1-s7", "commit": "<commitment hash, 64 hex>", "count": 2, "url": "https://game.yee.pub/fair/verify?id=f…" }
```

First post the `commit` (with the game name and `ref`) in the group, then roll `count` dice, then post the values and the `url`. Answer `data`: `{ "dice": [4, 6], "source": "telegram", "tg": { "link": "link to the message", "pub": true, "title": "group title" } }`. If it cannot be done (no verification group, the bot cannot post, not all dice rolled) answer any other status: YeeGame does not retry (a re-roll would allow choosing values) and rolls from the fairness seed instead, stating which source was used on the verify page and the shoe panel.

**Every hash round, after bets close,** YeeGame calls this endpoint too (`kind` = `hash`). A round is shared by all operators, so only one operator is called: the one YeeGame designated for that game, or, if none is designated, the first operator (by id) that declared `group.dice`. The request has a few more fields, `username` is empty (these dice belong to no single player) and `commit` is the bets digest:

```json
{ "traceId": "…", "timestamp": 1796051772349, "username": "", "kind": "hash", "game": "hlh", "gameName": "Hash Dragon Tiger", "gameNames": { "zh": "哈希龙虎", … },
  "ref": "hlh-81234567", "round": "hlh-81234567", "height": 81234567, "bets": 3,
  "digest": "<bets digest, 64 hex>", "commit": "<same as digest>", "count": 2, "url": "https://game.yee.pub/hash/verify.html?q=hlh-81234567" }
```

In your public verification group, first post “round `height` closed, `bets` bets, digest `digest`, result block height `height`; the product of the two dice below is the number of cards cut this round”, then roll two dice (as replies to that message); no result message is needed. The answer is the same as above (`tg.link` points to the closing message). Any other status means **no cut for that round** (0 cards): no re-roll and no other operator is asked; the game page and verify page say so. YeeGame waits at most 15 seconds for your answer (between closing and the draw, so the draw time is not affected).

## 9. Integration testing and acceptance

1. Integrate against staging with the staging key.
2. `providers/yeegame/scripts/operator-mock.mjs` in the repository is a minimal operator (in-memory wallet + game launcher + acceptance remote control); compare your behaviour with it.
3. Acceptance checklist (every item must pass):

| # | Scenario | Expected |
|---|---|---|
| 1 | Signature off by one character | Refused with a signature error (preferably `SC_INVALID_SIGNATURE`), no money moves |
| 2 | Same `transactionId` `bet` sent twice | Debited once, both answers show the same balance |
| 3 | Same `transactionId` `bet_result` sent twice | Credited once |
| 4 | `rollback` of a debited bet | Refunded once; a repeat does not refund again |
| 5 | `rollback` of an unknown bet, then that `bet` arrives | Rollback answers `SC_TRANSACTION_NOT_EXISTS`; the late `bet` is refused, no debit |
| 6 | `bet` above the balance | `SC_INSUFFICIENT_FUNDS`, no debit |
| 7 | After the player relaunched, a `bet` with the old token | `SC_INVALID_TOKEN`, no debit |
| 8 | After the player relaunched, `bet_result` for a bet placed under the old token | Credited |
| 9 | After the player was disabled, `bet_result` for their earlier bet | Credited (new bets while disabled get `SC_USER_DISABLED`) |
| 10 | `bet_result` without an answer, resent with the same `transactionId` (the first attempt may still be processing) | Credited once |
| 11 | Reconciliation: start balance + every confirmed movement = end balance; `/transaction/list` matched against your own ledger for a day | Counts and amounts agree |

4. **Acceptance kit** `providers/yeegame/scripts/acceptance.mjs`: acting as YeeGame, it runs the 11 items above against your wallet and prints a pass/fail table (failures state the answers and balances). It uses dedicated test players and tiny amounts (default 0.01) and closes every operation according to the protocol.

```sh
ACC_WALLET_URL=https://api.example.com/gp ACC_KEY=… ACC_SECRET=… \
ACC_USER=yg_accept_1 ACC_USER2=yg_accept_2 ACC_HOOK_URL=https://api.example.com/yg-accept \
node providers/yeegame/scripts/acceptance.mjs            # --json prints JSON (with the transaction list); --interactive pauses at manual steps
```

- Both test players must exist on your side (a few units of balance are enough). Key and Secret are read only from environment variables and never printed.
- Items 7, 8 and 9 need “the player relaunches” and “disable / re-enable the player”: provide a remote-control URL `ACC_HOOK_URL` (`POST { action: 'relaunch' | 'disable' | 'enable', username }`, signed like the wallet; `relaunch` answers `{ status: 'SC_OK', data: { token } }` and from then on you accept only that new token) and everything is automatic. Otherwise give `ACC_TOKEN` (current token) and `ACC_OLD_TOKEN` (an earlier one) for items 7–8, and use `--interactive` for item 9 to act in your back office when prompted; without either they are reported as skipped.
- The exit code is 1 when any item fails.

## 10. FAQ

- **Can player ids leak to other operators’ players?** No. Table-mates see an anonymous code generated by YeeGame (or the nickname you pass), with no reversible link to `username`; nothing sent to pages contains player ids, session tokens or operator ids.
- **Can we offer only some games?** Yes — you decide on your side which games to show (none of the catalogue has to be shown). Switching a game on/off at YeeGame applies to all operators; stopping a single operator is done by disabling it or setting it to maintenance.
- **Where are limits set?** Limits and stakes of every game are set by YeeGame centrally; all operators’ players share the same rounds and limits.
- **What if our wallet is down?** The debit in progress is not placed (the player sees “not placed”); money owed to players is resent until delivered and enters the manual queue after 48 hours for both sides to reconcile (4.3). Tables and rounds never stop because of a slow wallet.
