Cryptographically Verified

Provably Fair Casino API
for AI Agents

Every outcome cryptographically committed before the bet is placed. Your agent can independently verify every single game result — no trust required. No KYC. 10% lifetime referral commission.

8 Game Types
SHA-256 Commitment Scheme
10% Referral Rate
0 KYC No Identity Checks
100% Verifiable
Loading live stats…

What Does "Provably Fair" Actually Mean?

Provably fair is a cryptographic commitment scheme that makes it mathematically impossible for the house to manipulate game outcomes after a bet is placed.

In a traditional online casino, you have no way to verify that the random number generator produced a fair outcome. You trust the operator — a fundamentally fragile arrangement, especially for AI agents that require deterministic, auditable systems. Provably fair games solve this problem entirely through cryptography.

The system works as follows. Before any game round begins, the Purple Flea server generates a server seed — a random string of entropy. The server immediately computes the SHA-256 hash of this seed and publishes the hash to the player. This published hash is the commitment: the server is now locked into its secret seed, because changing the seed would change the hash and the player would detect the fraud.

The player then contributes their own entropy — a client seed of their choosing, plus an incrementing nonce that distinguishes each successive bet. The game outcome is computed as:

formulaOutcome derivation
outcome = HMAC-SHA256(server_seed, client_seed + ":" + nonce) mod game_range

After the game resolves, the server reveals the original server seed. The player — or their agent — can independently compute the same HMAC, confirm that the revealed seed matches the published hash, and verify that the outcome was derived exactly as claimed. No trust in the operator is required at any point.

For AI agents, this is more than a trust feature — it is a correctness guarantee. An agent managing a bankroll across thousands of bets can audit every single outcome in its history, compute empirical win rates, and detect statistical anomalies with certainty. The agent can rotate its client seed at any time to start a new verifiable chain, and it can verify the entire history of any session in seconds using the GET /casino/verify/:session_id endpoint, which returns all server seeds, client seeds, nonces, and computed outcomes for independent cross-checking.


How the Random Number Generator Works

A detailed walkthrough of the three-component seed system that guarantees neither the house nor the player can predict or manipulate outcomes.

  1. Server Seed Generation and Commitment

    Before any bets are accepted in a session, the Purple Flea server generates a cryptographically random 64-character hex string as the server seed. It immediately computes SHA-256(server_seed) and returns the hash to your agent in the session initialisation response. From this moment, the server cannot alter the seed without your agent detecting the discrepancy — the commitment is binding.

  2. Client Seed and Nonce

    Your agent supplies its own client seed when initiating a session — any string of your choosing. This ensures that even if the server seed were somehow predictable, the client seed introduces entropy controlled entirely by the player side. The nonce starts at 0 and increments with every bet, so each wager in a session produces a unique, never-repeated derivation input. To start a fresh verifiable chain, rotate the client seed and the nonce resets to 0.

  3. Outcome Derivation via HMAC-SHA256

    Each game outcome is computed as HMAC-SHA256(server_seed, client_seed + ":" + nonce). The resulting 256-bit hash is then reduced modulo the game range — for example, modulo 2 for coin flip, modulo 100 for dice, modulo 37 for roulette. The reduction is performed on the first four bytes of the HMAC output cast as a big-endian 32-bit unsigned integer, providing a uniform distribution with negligible bias from modular reduction.

  4. Post-Game Reveal and Verification

    After the game session ends (or at any point via the rotate endpoint), the server reveals the original server seed. Your agent computes SHA-256(revealed_seed) and confirms it matches the published commitment hash. It then re-derives every outcome in the session and confirms each matches the recorded result. This full audit takes milliseconds and requires no external dependencies — just a standard cryptographic library available in every language.

pythonHMAC derivation — the exact formula used
import hmac, hashlib, struct

def derive_outcome(server_seed: str, client_seed: str, nonce: int, game_range: int) -> int:
    message = f"{client_seed}:{nonce}".encode()
    key = server_seed.encode()
    mac = hmac.new(key, message, hashlib.sha256).digest()
    # Take first 4 bytes as big-endian uint32
    raw = struct.unpack(">I", mac[:4])[0]
    return raw % game_range

# Example: coin flip (range=2) — 0 = heads, 1 = tails
result = derive_outcome(
    server_seed="a3f9bc2d...",
    client_seed="my_agent_seed",
    nonce=0,
    game_range=2
)
print("heads" if result == 0 else "tails")

Eight Provably Fair Games

Every game runs on the same underlying HMAC-SHA256 commitment scheme. Every outcome is independently verifiable. House edge is published in every API response.

🪙

Coin Flip

Win: 50% / Payout: 1.95x / Edge: 2.5%

The simplest provably fair game. Bet on heads or tails. Win probability is 50% with a 1.95x payout, yielding a house edge of 2.5%. Ideal for agents benchmarking RNG quality or implementing basic martingale / anti-martingale experiments.

🎲

Dice

Roll 1–100 / Configurable range / Edge: 2%

Roll a number between 1 and 100. You configure the win threshold (e.g., roll under 50 for a proportional payout). Lower win probabilities yield higher multipliers. House edge is fixed at 2% regardless of chosen range.

🌀

Roulette

European / 37 Numbers / Edge: 2.7%

European single-zero roulette. Bet on a single number (35x payout), colour, dozen, or any standard wager. House edge is 2.7% — the standard European single-zero edge. All outcomes are fully verifiable via HMAC-SHA256.

🂡

Blackjack

Basic strategy / Edge: 0.5%

Provably fair blackjack with a 0.5% house edge when using basic strategy. Deck shuffles are derived from the HMAC commitment so every card drawn can be verified after the hand completes. The lowest house edge in the casino for skilled agents.

🚀

Crash

Multiplier game / Cash out before crash / Edge: 4%

A multiplier starts at 1x and grows exponentially. Cash out at any point to lock your multiplier, or hold for higher returns until the crash. The crash point is provably derived from the server seed. House edge is 4% on every round regardless of exit point.

🆕

Multiplier

Instant multiplier draw / Edge: 3%

A single provably fair draw picks a multiplier from a published distribution. The distribution is constructed to deliver a 3% house edge in expectation. Outcome is derived from the standard HMAC scheme and verifiable immediately after the round.

Plinko

Peg board / Edge: 2–5%

A ball drops through a peg board and lands in a multiplier slot. The path is fully determined by the HMAC derivation — each peg bounce is a deterministic binary outcome from successive nonce increments. House edge ranges from 2% (low-risk rows) to 5% (high-risk outer pegs), configurable per round.

Custom

Variable parameters / Edge: variable

Build any game mechanic on top of the HMAC-SHA256 RNG primitive. Specify your own game range, payout table, and win conditions via the POST /casino/custom endpoint. House edge is determined by your payout table and returned in every response.

Each game exposes its house edge as a field in every API response — for example, "house_edge": 0.030 for coin flip. This allows agents to compute their expected value per bet before placing it, incorporate the edge into Kelly Criterion calculations, and track whether empirical win rates over large sample sizes match the theoretical distribution. Statistically significant deviations from expected win rates are a strong signal of implementation errors in the agent's strategy, not manipulation by the house — because manipulation is cryptographically impossible.


Casino Endpoints

All casino endpoints share the same base URL and authentication as the rest of the Purple Flea API. Base URL: https://api.purpleflea.com/v1

Method Endpoint Description
POST /casino/flip Place a coin flip bet (heads or tails)
POST /casino/dice Roll dice with configurable win threshold
POST /casino/roulette Place a roulette wager
POST /casino/crash/join Join the next crash round with a bet amount
POST /casino/crash/cashout Cash out of active crash round at current multiplier

POST /casino/flip

curlRequest
curl -X POST https://api.purpleflea.com/v1/casino/flip \
  -H "X-PF-Key: pf_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "bet_usdc": 10.00,
    "choice": "heads",
    "client_seed": "my_agent_entropy_string",
    "nonce": 0
  }'
jsonResponse
{
  "game": "coin_flip",
  "bet_usdc": 10.00,
  "choice": "heads",
  "result": "heads",
  "won": true,
  "payout_usdc": 19.50,
  "profit_usdc": 9.50,
  "house_edge": 0.025,
  "server_seed_hash": "a8f3bc29d1e4...",
  "client_seed": "my_agent_entropy_string",
  "nonce": 0
}

POST /casino/dice

curlRequest
curl -X POST https://api.purpleflea.com/v1/casino/dice \
  -H "X-PF-Key: pf_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "bet_usdc": 25.00,
    "win_condition": "under",
    "target": 50,
    "client_seed": "my_agent_entropy_string",
    "nonce": 1
  }'
jsonResponse
{
  "game": "dice",
  "bet_usdc": 25.00,
  "roll": 34,
  "target": 50,
  "win_condition": "under",
  "won": true,
  "payout_multiplier": 1.96,
  "payout_usdc": 49.00,
  "profit_usdc": 24.00,
  "house_edge": 0.020,
  "server_seed_hash": "a8f3bc29d1e4...",
  "nonce": 1
}

POST /casino/roulette

jsonResponse — single number bet
{
  "game": "roulette",
  "bet_type": "single_number",
  "bet_value": 17,
  "bet_usdc": 5.00,
  "spin_result": 17,
  "colour": "black",
  "won": true,
  "payout_multiplier": 35,
  "payout_usdc": 175.00,
  "house_edge": 0.027,
  "server_seed_hash": "c4d71a3f8b29..."
}

POST /casino/crash/join and /cashout

jsonJoin round — response
{
  "round_id": "crash_rnd_39fa21",
  "bet_usdc": 50.00,
  "status": "active",
  "current_multiplier": 1.24,
  "server_seed_hash": "7b9e4c2f1da8..."
}
jsonCashout — response
{
  "round_id": "crash_rnd_39fa21",
  "cashed_out_at": 2.71,
  "bet_usdc": 50.00,
  "payout_usdc": 135.50,
  "profit_usdc": 85.50,
  "crash_point": 4.18,
  "server_seed": "f2a8c91e3b47...",
  "server_seed_hash": "7b9e4c2f1da8..."
}

Verify Any Outcome Independently

After any game, your agent can verify the result with a few lines of Python. This is the gold standard of trust: mathematical proof that requires no faith in the operator.

The verification process is identical for all games. After a round ends (or after a server seed rotation), Purple Flea reveals the original server seed. Your agent has already stored the server seed hash from the initial API response. The verification proceeds in three steps: confirm the revealed seed hashes to the commitment, re-derive each outcome using the known inputs, and confirm each matches the recorded result. Any discrepancy would indicate a server bug or malicious behaviour — detectable immediately and irrefutably.

Because the verification code is just standard HMAC and SHA-256 available in every language's standard library, no Purple Flea SDK is required to audit results. An agent running on any platform can independently validate its entire game history using only the raw seed values, nonces, and the formula documented in the API specification.

pythonComplete fairness verification — no external dependencies
import hmac, hashlib, struct, json, urllib.request

def verify_session(session_id: str, api_key: str):
    # 1. Fetch session history from the API
    req = urllib.request.Request(
        f"https://api.purpleflea.com/v1/casino/verify/{session_id}",
        headers={"X-PF-Key": api_key}
    )
    session = json.loads(urllib.request.urlopen(req).read())

    revealed_seed   = session["server_seed"]
    committed_hash  = session["server_seed_hash"]
    client_seed     = session["client_seed"]
    bets            = session["bets"]

    # 2. Confirm revealed seed matches committed hash
    actual_hash = hashlib.sha256(revealed_seed.encode()).hexdigest()
    assert actual_hash == committed_hash, "SEED HASH MISMATCH — server cheated!"
    print(f"Seed commitment verified ✓ ({len(bets)} bets)")

    # 3. Re-derive every outcome and compare
    for bet in bets:
        key   = revealed_seed.encode()
        msg   = f"{client_seed}:{bet['nonce']}".encode()
        mac   = hmac.new(key, msg, hashlib.sha256).digest()
        raw   = struct.unpack(">I", mac[:4])[0]
        derived = raw % bet["game_range"]
        assert derived == bet["outcome"], f"Outcome mismatch at nonce {bet['nonce']}"

    print("All outcomes verified ✓ — session is provably fair")

verify_session("sess_a3f9bc2d", "pf_live_your_api_key_here")

Run this verification script against any completed session and it will independently confirm every single bet outcome. A successful run means the house played fair — not because you trust them, but because cryptography makes any other outcome mathematically impossible to conceal. This is the foundation of agent-native gambling infrastructure: your autonomous system can operate with full epistemic confidence in the data it receives.


Kelly Criterion for AI Gambling Agents

Optimal bet sizing is as important as game selection. Purple Flea exposes the house edge in every response, giving agents the data they need to compute Kelly fractions precisely.

The Kelly Criterion is a mathematically optimal bet-sizing formula derived from information theory. For a binary game (win or lose), the Kelly fraction is: f* = (b*p - q) / b, where b is the net odds received on the wager (payout minus stake), p is the probability of winning, and q = 1 - p is the probability of losing.

For a game with a negative expected value — which all casino games have by construction — the Kelly fraction will be negative, advising zero exposure to the game from a pure EV perspective. However, gambling agents often operate under mandates beyond pure EV maximisation: entertainment budgets, stress-testing probabilistic systems, or exploring the statistical properties of the RNG. In these cases, a fractional Kelly (typically 0.1x to 0.25x of the theoretical Kelly) limits downside while allowing meaningful exploration of the game's distribution.

Purple Flea returns the house edge in every game response so agents can dynamically verify their edge assumptions haven't drifted. If the API reports a 1% house edge on dice but empirical results over 10,000 bets show a 4% loss rate, the agent has a signal that its bet selection criteria — not the RNG — require review.

Kelly Calculation — Dice (roll under 50 at 1.96x payout)

Win probability (p) 0.49 (49%)
Lose probability (q = 1 - p) 0.51 (51%)
Net odds (b = payout - 1) 0.96
Kelly fraction (f* = (b*p - q) / b) -0.021 (negative — do not bet)
Recommended stake if playing anyway (0.1x fractional Kelly of available bankroll) 0.21% of bankroll per bet
House edge returned in API response 0.010 (1.0%)

GET /api/v1/kelly/limits

Returns pre-computed Kelly-optimal bet limits for each game given your current account balance. The API calculates both the full Kelly fraction and a recommended 0.25x fractional Kelly stake, taking the published house edge and payout odds as inputs. Call this endpoint before constructing your betting strategy for the session.

curlRequest
curl https://casino.purpleflea.com/api/v1/kelly/limits \
  -H "X-PF-Key: pf_live_your_api_key_here"
jsonResponse
{
  "balance_usdc": 1000.00,
  "games": {
    "coin_flip": {
      "house_edge": 0.025,
      "win_probability": 0.50,
      "payout_multiplier": 1.95,
      "kelly_fraction": -0.026,
      "recommended_stake_usdc": 0.00,
      "fractional_kelly_0_25x_usdc": 0.00
    },
    "dice": {
      "house_edge": 0.020,
      "note": "varies by target; example at roll_under_50",
      "kelly_fraction": -0.021,
      "recommended_stake_usdc": 0.00
    },
    "blackjack": {
      "house_edge": 0.005,
      "note": "assumes basic strategy; lowest edge game",
      "kelly_fraction": -0.005,
      "recommended_stake_usdc": 0.00
    }
  },
  "note": "Negative Kelly fractions indicate negative expected value — house always has an edge."
}

An agent that enforces fractional Kelly sizing across all bets will, in expectation, survive far longer than a flat-bet agent and lose bankroll at a rate proportional to the house edge rather than variance. For agents tasked with maximising the number of completed bets within a budget — for RNG auditing, entertainment, or referral generation — fractional Kelly is the mathematically correct approach. The Purple Flea SDK includes a built-in KellyBetSizer utility class that accepts house edge and current bankroll and returns the recommended stake in USDC.


10% of Every Wager, Forever

Refer agents and players to the Purple Flea Casino API and earn 10% of all wagers they place — permanently, with no cap and no time limit.

The referral commission is calculated as a percentage of the total wager amount, not the fee. When a referred user bets $100 on a coin flip, you earn $10 — regardless of whether they win or lose, and regardless of the house edge on that particular game. This makes the referral economics straightforward: commission is proportional purely to wagering activity, not to game outcomes or profitability.

AI agents that onboard other gambling agents earn passively. An agent that introduces three other agents each wagering $10,000 per day earns $3,000 per day in referral commissions — $90,000 per month — without placing a single bet itself. The referral system is designed to reward agent developers who build compelling gambling applications, strategy bots, or entertainment layers on top of the Purple Flea casino infrastructure.

To onboard a referred user, include your ref_code in the session initialisation request. Attribution is immediate and permanent. You can track all referred sessions, their cumulative wagering, and your earned commissions through the GET /referral/casino/stats endpoint, which returns daily, weekly, and all-time breakdowns per referred account.

Daily wager volume per agent (example) $10,000
Referral commission rate 10%
Daily earnings (1 agent) $1,000 / day
Monthly earnings (1 agent) $30,000
Monthly earnings (10 agents) $300,000
Commission is permanent — no time limit, no cap Forever

Start Building in Minutes

Get your API key, initialise a session with your client seed, and place your first provably fair bet. No KYC, no waiting, full cryptographic verifiability on every outcome.