openapi: 3.1.0
info:
  title: bhub Seamless Wallet API
  version: 1.1.0-draft
  summary: Calls bhub makes to the operator's wallet. The operator implements these endpoints.
  description: |
    ## Conventions
    - Transport: HTTPS POST, `Content-Type: application/json; charset=utf-8`, UTF-8 strings.
    - Every business outcome returns HTTP 200 with a `status`. Non-200 means infrastructure
      failure and is treated as a timeout (unknown outcome). One exception: a request whose
      signature, key id or timestamp fails verification is answered HTTP 401 with
      `{"status":"INVALID_SIGNATURE"}` (unsigned); bhub treats it as a definite refusal.
    - Guides and the conformance kit: https://bhubsystems.com/docs
    - Amounts: decimal strings in the currency's minor-unit precision (`"12.50"` ZAR,
      `"1500"` UGX), never floats. More decimals than the currency allows is a bad request.
      The precision table is published at `GET /v1/currencies` on the operator API.
    - Identifiers: strings of at most 64 characters, `[A-Za-z0-9._:-]`.
    - Times: RFC 3339 with `Z` (UTC). Reports render SAST for ZA.

    ## Signing (HMAC-SHA256)
    Headers on every request and every response:
    - `X-Bhub-Key-Id`: which key signed (two keys may be live during rotation).
    - `X-Bhub-Timestamp`: Unix seconds. Requests outside +/-300 s are rejected.
    - `X-Bhub-Signature`: hex HMAC-SHA256 of `timestamp + "\n" + raw_body` with the shared key.
    The operator signs its response body the same way, so bhub verifies answers too.
    HMAC-SHA256 doubles as the message error-detection code (SANS 1718-3 10.4, 10.11).

    ## Test and live (`X-Bhub-Environment`)
    Every request carries `X-Bhub-Environment: live` or `X-Bhub-Environment: test`.
    - `test` marks every call of the test studio (simulator) and of "Test connection" in the
      portal: synthetic players, sandbox rounds, trouble caused on purpose. It is sent only to the
      operator's registered test wallets, signed with the test wallet's own keys, which are never
      the live keys.
    - `live` marks real play, and bhub's reconciliation pulls of `GET /v1/transactions`.
    - A live wallet MUST refuse a request marked `test` (HTTP 200 with `status: BAD_REQUEST`, or
      HTTP 401 `INVALID_SIGNATURE` when the test key is unknown to it). A test wallet SHOULD refuse
      a request marked `live`. A missing header is treated as `live` by older wallets; bhub always
      sends it.
    The header is not part of the signed bytes; the separate test keys are what keep test calls out
    of a live wallet. See docs/operator-api.md, "Prepare a test wallet".

    ## Idempotency contract
    - `tx_id` is the idempotency key, globally unique, kept by the operator for at least 180 days.
    - A repeat with the same `tx_id` and identical body MUST return the original outcome
      with the CURRENT balance and `status: OK` (or the original rejection).
    - The same `tx_id` with a different body MUST return `DUPLICATE_CONFLICT`. "Body" means the
      business fields: `request_id` (new on every attempt) and `session_token` (may be
      refreshed) are excluded from the comparison.
    - `rollback` of a transaction the operator never saw MUST return `OK` and remember the
      target `ref_tx_id` (tombstone), so a late-arriving original is refused with
      `TRANSACTION_ROLLED_BACK`.

    ## Retries (published policy)
    - `bet`/`bet_win` debit: timeout ~3 s, NOT retried; bhub sends `rollback` instead,
      delivered with 2 immediate retries, then the async schedule below.
    - `win`, `rollback`, `end_round`, `promo_credit`: 2 immediate retries, then the same
      async schedule (1 min, 10 min, then hourly) up to 72 h, then manual reconciliation (visible in the failed-transaction
      feed and webhook).

    ## Transactions endpoint (optional, for daily reconciliation)
    `GET /v1/transactions` lets bhub read the operator's own records of every bhub money call, one
    business day at a time, instead of the operator uploading a file. It is signed like every
    call, except that a GET has no body: the signed bytes are the request target (path and query
    exactly as sent, e.g. `/bhub/v1/transactions?from=...&limit=5000&to=...`). The answer is signed
    over its body as usual. bhub asks for the business day plus 10 minutes either side and follows
    `next_cursor` until it is null. Lines are in the published layout (the same fields as the file
    upload). A line counts once; a stake the wallet gave back is `status: rolled_back`.
servers:
  - url: https://{operator-wallet-host}/bhub
    variables:
      operator-wallet-host: { default: wallet.example.com }
security:
  - bhubHmac: []
paths:
  /v1/authenticate:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: authenticate
      summary: Exchange a launch token for the player's identity and balance.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/AuthenticateRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/AuthenticateResponse' } } } }
  /v1/balance:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: balance
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/BalanceRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/bet:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: bet
      summary: Debit a stake.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/BetRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/win:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: win
      summary: Credit a win. A round may have several wins. Zero-amount wins are sent when they close a round.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/WinRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/bet_win:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: betWin
      summary: Debit and credit in one call (instant and crash games). Atomic on the operator side.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/BetWinRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/rollback:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: rollback
      summary: Reverse a bet or a win identified by ref_tx_id.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/RollbackRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/end_round:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: endRound
      summary: Close a round. Idempotent per round_id; may repeat.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/EndRoundRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/promo_credit:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    post:
      operationId: promoCredit
      summary: Offline-safe credit outside normal play (free-spins total, jackpot, tournament, prize drop, cashback). No session needed.
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/PromoCreditRequest' } } } }
      responses:
        '200': { description: Outcome, content: { application/json: { schema: { $ref: '#/components/schemas/WalletResponse' } } } }
  /v1/transactions:
    parameters: [{ $ref: '#/components/parameters/Environment' }]
    get:
      operationId: listTransactions
      summary: The operator's records of bhub money calls in a time window (optional; for reconciliation).
      description: |
        Signed over the request target (path and query) instead of a body. Pages are in the
        operator's order; `cursor` is opaque to bhub. Amounts are integers in minor units here
        (this is a records export, not a money call).
      parameters:
        - { name: from, in: query, required: true, schema: { type: string, format: date-time }, description: Inclusive. }
        - { name: to, in: query, required: true, schema: { type: string, format: date-time }, description: Exclusive. }
        - { name: cursor, in: query, required: false, schema: { type: string, maxLength: 200 } }
        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 10000, default: 1000 } }
      responses:
        '200': { description: One page, content: { application/json: { schema: { $ref: '#/components/schemas/TransactionsPage' } } } }
        '400': { description: Bad window, limit or cursor }
        '401': { description: 'Signature failed: {"status":"INVALID_SIGNATURE"}' }
components:
  parameters:
    Environment:
      name: X-Bhub-Environment
      in: header
      required: true
      description: live for real play, test for the test studio and Test connection. See "Test and live".
      schema: { type: string, enum: [live, test] }
  securitySchemes:
    bhubHmac: { type: apiKey, in: header, name: X-Bhub-Signature }
  schemas:
    Id: { type: string, maxLength: 64, pattern: '^[A-Za-z0-9._:-]+$' }
    Amount:
      type: string
      pattern: '^(0|[1-9][0-9]{0,17})(\.[0-9]{1,4})?$'
      description: Non-negative decimal string in the currency's precision.
    Currency: { type: string, pattern: '^[A-Z]{3}$', description: ISO 4217 }
    Status:
      type: string
      enum:
        - OK
        - INSUFFICIENT_FUNDS         # player-facing
        - PLAYER_NOT_FOUND
        - PLAYER_BLOCKED             # player-facing
        - TOKEN_INVALID
        - TOKEN_EXPIRED
        - INVALID_SIGNATURE
        - BAD_REQUEST
        - GAME_DISABLED
        - LIMIT_REACHED              # player-facing (responsible gambling)
        - BET_OUT_OF_LIMITS
        - CURRENCY_MISMATCH
        - DUPLICATE_CONFLICT
        - TRANSACTION_NOT_FOUND
        - TRANSACTION_ROLLED_BACK
        - REALITY_CHECK              # player-facing
        - INTERNAL_RETRY             # bhub may retry with the same tx_id
        - INTERNAL_NO_RETRY
    Balance:
      type: object
      required: [cash, bonus]
      properties:
        cash: { $ref: '#/components/schemas/Amount' }
        bonus: { $ref: '#/components/schemas/Amount' }
    Common:
      type: object
      required: [request_id, player_id, currency, game_id, provider]
      properties:
        request_id: { $ref: '#/components/schemas/Id' }
        session_token: { type: string, maxLength: 256 }
        player_id: { $ref: '#/components/schemas/Id' }
        currency: { $ref: '#/components/schemas/Currency' }
        game_id: { $ref: '#/components/schemas/Id' }
        provider: { $ref: '#/components/schemas/Id' }
    RoundRef:
      type: object
      required: [round_id]
      properties:
        round_id: { $ref: '#/components/schemas/Id' }
        round_closed:
          type: [boolean, 'null']
          description: true when this call closes the round, false when more calls follow; absent or null when the studio did not say.
        is_free: { type: boolean, default: false, description: "Free spins round (granted by the studio, or an in-game feature). The stake is passed as the studio sent it, normally 0." }
        bonus_ref:
          allOf: [{ $ref: '#/components/schemas/Id' }]
          description: "The studio's own free spins / bonus reference, opaque to bhub. bhub creates and manages no free spins campaigns; it only passes free spins rounds through. A free spins round without a reference is still processed and is flagged for review."
        round_details: { type: object, additionalProperties: true, description: "The studio's raw round and bonus fields, passed through unchanged (no fixed schema)." }
        jurisdiction:
          type: object
          description: ZA WRS ticket fields (ticket number arrives later via the round feed).
          properties:
            code: { type: string, example: ZA }
            province: { type: string }
            venue: { type: string }
    AuthenticateRequest:
      type: object
      required: [request_id, launch_token, game_id, provider]
      properties:
        request_id: { $ref: '#/components/schemas/Id' }
        launch_token: { type: string, maxLength: 256 }
        game_id: { $ref: '#/components/schemas/Id' }
        provider: { $ref: '#/components/schemas/Id' }
        ip_address: { type: string }
    AuthenticateResponse:
      type: object
      required: [status]
      properties:
        status: { $ref: '#/components/schemas/Status' }
        player_id: { $ref: '#/components/schemas/Id' }
        session_token: { type: string, maxLength: 256 }
        currency: { $ref: '#/components/schemas/Currency' }
        balance: { $ref: '#/components/schemas/Balance' }
        country: { type: string, pattern: '^[A-Z]{2}$' }
        jurisdiction: { type: string }
        bet_limits:
          type: object
          properties:
            min_total_bet: { $ref: '#/components/schemas/Amount' }
            max_total_bet: { $ref: '#/components/schemas/Amount' }
        promo_eligible: { type: boolean }
    BalanceRequest:
      type: object
      required: [request_id, player_id, currency]
      properties:
        request_id: { $ref: '#/components/schemas/Id' }
        session_token: { type: string }
        player_id: { $ref: '#/components/schemas/Id' }
        currency: { $ref: '#/components/schemas/Currency' }
    BetRequest:
      allOf:
        - $ref: '#/components/schemas/Common'
        - $ref: '#/components/schemas/RoundRef'
        - type: object
          required: [tx_id, amount]
          properties:
            tx_id: { $ref: '#/components/schemas/Id' }
            amount: { $ref: '#/components/schemas/Amount' }
            jackpot_contribution_micro: { type: string, pattern: '^[0-9]{1,18}$' }
    WinRequest:
      allOf:
        - $ref: '#/components/schemas/Common'
        - $ref: '#/components/schemas/RoundRef'
        - type: object
          required: [tx_id, amount]
          properties:
            tx_id: { $ref: '#/components/schemas/Id' }
            ref_tx_id: { $ref: '#/components/schemas/Id', description: The bet this win settles, when known. }
            amount: { $ref: '#/components/schemas/Amount' }
    BetWinRequest:
      allOf:
        - $ref: '#/components/schemas/Common'
        - $ref: '#/components/schemas/RoundRef'
        - type: object
          required: [tx_id, bet_amount, win_amount]
          properties:
            tx_id: { $ref: '#/components/schemas/Id' }
            bet_amount: { $ref: '#/components/schemas/Amount' }
            win_amount: { $ref: '#/components/schemas/Amount' }
    RollbackRequest:
      allOf:
        - $ref: '#/components/schemas/Common'
        - type: object
          required: [tx_id, ref_tx_id, round_id]
          properties:
            tx_id: { $ref: '#/components/schemas/Id' }
            ref_tx_id: { $ref: '#/components/schemas/Id' }
            round_id: { $ref: '#/components/schemas/Id' }
            round_closed: { type: [boolean, 'null'] }
    EndRoundRequest:
      allOf:
        - $ref: '#/components/schemas/Common'
        - type: object
          required: [tx_id, round_id, total_bet, total_win]
          properties:
            tx_id: { $ref: '#/components/schemas/Id' }
            round_id: { $ref: '#/components/schemas/Id' }
            total_bet: { $ref: '#/components/schemas/Amount' }
            total_win: { $ref: '#/components/schemas/Amount' }
    PromoCreditRequest:
      type: object
      required: [request_id, tx_id, player_id, currency, amount, kind]
      properties:
        request_id: { $ref: '#/components/schemas/Id' }
        tx_id: { $ref: '#/components/schemas/Id' }
        player_id: { $ref: '#/components/schemas/Id' }
        currency: { $ref: '#/components/schemas/Currency' }
        amount: { $ref: '#/components/schemas/Amount' }
        kind: { type: string, enum: [free_spins_win, jackpot, tournament, prize_drop, mission, cashback, adjustment], description: "free_spins_win is a studio's aggregated free spins total paid at the end of the free spins; report it as a promotional payout." }
        bonus_ref:
          allOf: [{ $ref: '#/components/schemas/Id' }]
          description: "The studio's opaque bonus reference, when it sent one."
        round_id: { $ref: '#/components/schemas/Id' }
        game_id: { $ref: '#/components/schemas/Id' }
        provider: { $ref: '#/components/schemas/Id' }
    WalletResponse:
      type: object
      required: [status]
      properties:
        status: { $ref: '#/components/schemas/Status' }
        request_id: { $ref: '#/components/schemas/Id' }
        operator_tx_id: { type: string, maxLength: 64 }
        currency: { $ref: '#/components/schemas/Currency' }
        balance: { $ref: '#/components/schemas/Balance' }
        used_bonus: { $ref: '#/components/schemas/Amount' }
        messages:
          type: array
          maxItems: 3
          description: Player messages the game client renders (responsible gambling, notices).
          items:
            type: object
            required: [title, text]
            properties:
              title: { type: string, maxLength: 60 }
              text: { type: string, maxLength: 300 }
    RecordLine:
      type: object
      description: One line of the operator's records (the published reconciliation layout).
      required: [kind, amount_minor, currency, occurred_at]
      properties:
        operator_tx_id: { type: string, maxLength: 64, description: "The operator's own id for the line." }
        bhub_tx_id: { type: string, maxLength: 64, description: "The tx_id bhub sent. The matching key." }
        round_id: { type: string, maxLength: 64, description: Fallback key with kind and amount when bhub_tx_id is missing. }
        player_ref: { type: string, maxLength: 64 }
        kind: { type: string, enum: [stake, payout, refund], description: "bet_win is two lines: a stake and a payout." }
        amount_minor: { type: integer, minimum: 0, format: int64 }
        currency: { $ref: '#/components/schemas/Currency' }
        occurred_at: { type: string, format: date-time }
        balance_after: { type: integer, format: int64, description: Cash balance after the line, minor units. }
        status: { type: string, enum: [ok, rolled_back, failed], default: ok }
    TransactionsPage:
      type: object
      required: [transactions, next_cursor]
      properties:
        transactions: { type: array, items: { $ref: '#/components/schemas/RecordLine' } }
        next_cursor: { type: [string, 'null'], description: Null on the last page. }
