> For the complete documentation index, see [llms.txt](https://docs.overtime.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.overtime.io/overtime-casino/casino-integration.md).

# Casino Integration

The Overtime Casino contracts are not a backend behind a proprietary UI. They are not a gated SDK. They are public, deployed, and callable by any wallet: yours, your users', or an AI agent's.

This page is for developers, vibe coders and AI agents who want to wrap the contracts in their own product. Whether you're building a Telegram bot, a Farcaster Frame, a custom skinned frontend, an AI agent that plays Blackjack on its own terms, or a niche-language UI for a community Overtime hasn't reached, everything you need is onchain, in verified source.

***

### TL;DR for the impatient

* **Contracts:** verified source on each chain's block explorer; [v2.contracts.overtime.io](https://v2.contracts.overtime.io/) redirects every contract name to its latest deployment. MIT-licensed.
* **Two architectures:** the original five games (Roulette, Dice, Blackjack, Baccarat, Slots) are standalone contracts and are what this page's first quickstarts cover. The newer thirteen (Plinko through Tumble) are thin game contracts on a shared treasury, `CasinoCoreV2`, with their own sections below. See How the Games are Built.
* **Approvals differ:** for the original five, approve the game contract. For the newer thirteen, approve `CasinoCoreV2`, which pulls the stake.
* **Networks:** Base, Optimism, Arbitrum.
* **Collaterals:** USDC, WETH, $OVER.
* **Randomness:** Chainlink VRF v2.5 (`IVRFCoordinatorV2Plus`).
* **Same shape everywhere:** `placeBet` → VRF request → callback → resolved. The original five call VRF themselves; the newer games go through `CasinoCoreV2`, and the four streak games share one contract, `StreakGame`.
* **Pass a `_referrer` address** on every bet you make on behalf of users to capture up to 20% of generated fees automatically.
* **Free bets supported:** `placeBetWithFreeBet` in the original five, an `isFreeBet` flag on `placeBet` in the newer games, both against the existing Overtime `IFreeBetsHolder`.

***

### A note for AI agents and vibe coders: use Eth Skills

If you're an AI agent, or you're prompting one, building on Ethereum, the best starting point isn't this page or even the Overtime repo. It's [**ethskills.com**](https://ethskills.com/).

ETHSKILLS is an open library of skill files that fix the things LLMs get wrong about Ethereum out of the box. Stale gas prices. Hallucinated contract addresses. Outdated patterns. Wrong terminology ("on-chain" vs "onchain"). It's structured as fetch-on-demand markdown files an agent can pull at runtime.

Recommended skills to read before integrating with Overtime Casino:

* [**`ethskills.com/SKILL.md`**](https://ethskills.com/SKILL.md): table of contents and overall framing
* [**`ethskills.com/tools/SKILL.md`**](https://ethskills.com/tools/SKILL.md): current tooling (Foundry, Scaffold-ETH 2, abi.ninja, MCPs)
* [**`ethskills.com/standards/SKILL.md`**](https://ethskills.com/standards/SKILL.md): ERC-20, EIP-7702, ERC-8004 (agent identity)
* [**`ethskills.com/orchestration/SKILL.md`**](https://ethskills.com/orchestration/SKILL.md): three-phase build pattern (localhost → live testnet → production)
* **The Chainlink VRF skill in cryptoskills.dev**, VRF v2.5 specifics, subscription management, callback patterns

Bootstrap your project with `npx create-eth@latest` if you want a working Scaffold-ETH 2 frontend wired to a local hardhat fork in 60 seconds. Then point it at the Casino contracts.

The rest of this guide assumes you have basic web3 tooling set up. If you don't, the Eth Skills route will get you there faster than reading 50 docs pages.

***

#### Where the source lives

Every Casino contract is an upgradeable proxy with verified source on its chain's block explorer. [v2.contracts.overtime.io](https://v2.contracts.overtime.io/) redirects each contract name to its latest deployment, in the form `https://v2.contracts.overtime.io/<network>/<Contract>`, where `<network>` is `mainnet-ovm` (Optimism), `arbitrumOne` or `baseMainnet`.

| Group                      | Contracts                                                                                                                                                                                              |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Original five (standalone) | `Roulette`, `Dice`, `Blackjack`, `Baccarat`, `Slots`, plus the read aggregator `CasinoData`                                                                                                            |
| Shared core                | `CasinoCoreV2` (treasury, VRF, free bets, referrals, limits, circuit breaker), plus the read aggregator `CasinoDataV2`                                                                                 |
| Newer games                | `Plinko`, `HiLo`, `Keno`, `VideoPoker`, `ThreeCardPoker`, `OvertimeUltimateHoldem`, `OvertimeBonusHoldem`, `StreakGame` (Penalty Shootout, Hoop Streak, Standoff, Shooting Range), `Cascade`, `Tumble` |

Each implementation is written in Solidity 0.8.20, follows OpenZeppelin upgradeable patterns (`Initializable`, `ProxyOwned`, `ProxyPausable`, `ProxyReentrancyGuard`), and has `@notice` natspec on virtually every public function.

***

### The shape every Casino contract shares

This section covers the original five. The newer games have their own sections further down, and How the Games are Built explains the differences.

This is the part worth internalizing. Once you understand the lifecycle of one contract, you understand all five.

#### Public entry points

```solidity
// Place a real-money bet
function placeBet(
    address collateral,    // USDC, WETH, or $OVER
    uint amount,           // collateral amount, in token-native decimals
    /* game-specific args (bet type, selection, target, etc.) */
    address _referrer      // your affiliate wallet, or address(0)
) external returns (uint betId, uint requestId);

// Place a bet using the user's free-bet balance
function placeBetWithFreeBet(
    address collateral,
    uint amount,
    /* game-specific args */
) external returns (uint betId, uint requestId);

// Cancel a stuck bet after cancelTimeout
function cancelBet(uint betId) external;
```

Roulette additionally exposes `placeMultiBet` and `placeMultiBetWithFreeBet` for multi-pick spins; Blackjack exposes per-action entrypoints (`hit`, `stand`, `doubleDown`, `split`) on top of the initial `placeBet` (named `deal` in some flows).

#### Internal lifecycle

```
user calls placeBet
  ├─ pulls collateral via safeTransferFrom
  ├─ validates selection / target / pick list
  ├─ computes worst-case payout, reserves it against bankroll
  ├─ calls vrfCoordinator.requestRandomWords(...)
  ├─ stores Bet struct, status = PENDING
  └─ emits BetPlaced(betId, requestId, user, collateral, amount, ...)

[time passes — Chainlink generates randomness]

vrfCoordinator calls rawFulfillRandomWords(requestId, randomWords[])
  ├─ msg.sender check: only vrfCoordinator can call this
  ├─ derives game outcome from randomWords[0]
  ├─ updates bet status = RESOLVED
  ├─ transfers payout (if won), pays referrer (if lost)
  └─ emits BetResolved(betId, requestId, user, result, won, payout)
```

That's the whole loop. Every game contract follows it. The only differences are what happens between "derive outcome" and "compute payout", game-specific math.

#### Events you'll want to index

| Event                                                                                   | When it fires                             |
| --------------------------------------------------------------------------------------- | ----------------------------------------- |
| `BetPlaced(betId, requestId, user, collateral, amount, ...)`                            | User places a bet, before VRF callback    |
| `MultiBetPlaced(betId, requestId, user, collateral, totalAmount, pickCount, isFreeBet)` | Roulette only, multi-pick bets            |
| `BetResolved(betId, requestId, user, result, won, payout)`                              | VRF fulfills and bet resolves             |
| `BetCancelled(betId, requestId, user, refundedAmount, adminCancelled)`                  | User or admin cancels a stuck bet         |
| `ReferrerPaid(referrer, user, amount, betAmount, collateral)`                           | Affiliate fee transferred on a losing bet |

For Blackjack, additional events fire for action transitions (`HandActionRequested`, `CardDealt`, etc.). The full event list lives at the bottom of each contract source file.

***

### Quickstart: place a Roulette bet from a TypeScript frontend

```typescript
import { ethers } from "ethers";
import RouletteABI from "./abi/Roulette.json";
import IERC20ABI from "./abi/IERC20.json";

const ROULETTE_ADDRESS = "0x..."; // deployed Roulette address on your target chain
const USDC_ADDRESS    = "0x..."; // USDC on the same chain
const REFERRER        = "0xYOURAFFILIATEWALLET"; // or ethers.ZeroAddress

const provider = new ethers.BrowserProvider(window.ethereum);
const signer   = await provider.getSigner();

const usdc     = new ethers.Contract(USDC_ADDRESS,    IERC20ABI,    signer);
const roulette = new ethers.Contract(ROULETTE_ADDRESS, RouletteABI, signer);

// 1. One-time approval
const stake = 5_000_000n; // 5 USDC (6 decimals)
await (await usdc.approve(ROULETTE_ADDRESS, stake)).wait();

// 2. Place a STRAIGHT bet on number 17
const BetType = { STRAIGHT: 0, RED_BLACK: 1, ODD_EVEN: 2, LOW_HIGH: 3, DOZEN: 4, COLUMN: 5 };
const tx = await roulette.placeBet(USDC_ADDRESS, stake, BetType.STRAIGHT, 17, REFERRER);
const receipt = await tx.wait();

// Extract betId from the BetPlaced event
const event = receipt.logs
  .map(l => { try { return roulette.interface.parseLog(l); } catch { return null; } })
  .find(e => e && e.name === "BetPlaced");
const betId = event.args.betId;

// 3. Wait for resolution by listening for BetResolved
roulette.on("BetResolved", (resolvedBetId, requestId, user, result, won, payout) => {
  if (resolvedBetId === betId) {
    console.log(`Spin result: ${result}, won: ${won}, payout: ${payout}`);
  }
});
```

This is the complete pattern. Substitute the bet type, args and contract address for each game, and the same flow applies.

***

### Quickstart: place a Dice bet from an AI agent (viem)

```typescript
import { createPublicClient, createWalletClient, http, parseAbi } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";

const account = privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`);
const wallet  = createWalletClient({ account, chain: base, transport: http() });
const client  = createPublicClient({ chain: base, transport: http() });

const DICE      = "0x...";
const USDC      = "0x...";
const REFERRER  = "0xYOURAFFILIATEWALLET";

const diceAbi = parseAbi([
  "function placeBet(address collateral, uint256 amount, uint8 betType, uint8 target, address referrer) external returns (uint256, uint256)",
  "event BetResolved(uint256 indexed betId, uint256 indexed requestId, address indexed user, uint8 result, bool won, uint256 payout)",
]);

// ROLL_UNDER 11 = 50% probability
const BetType = { ROLL_UNDER: 0, ROLL_OVER: 1 };

const hash = await wallet.writeContract({
  address: DICE,
  abi: diceAbi,
  functionName: "placeBet",
  args: [USDC, 5_000_000n, BetType.ROLL_UNDER, 11, REFERRER],
});

const receipt = await client.waitForTransactionReceipt({ hash });
// ... parse logs the same way as above
```

For agents specifically, the design is friendly:

* **Each contract is a single-purpose machine.** Small public surface, well-named functions, deterministic behavior.
* **State is queryable.** Read `bets[betId]` (or game-equivalent) to recover any bet's full state at any time.
* **Events are reliable.** Index `BetResolved` to build a "watch and react" loop without polling state.
* **No hidden auth.** No API keys. No login. No CAPTCHA. The wallet *is* the auth.

***

### Reading game configuration from chain

Before you place bets at scale (or expose a slot's RTP to your users), read the relevant configuration directly:

```typescript
// Dice — what's the current house edge?
const houseEdge = await dice.read.houseEdge();
// Returns 1e18-precision; 1e16 = 1%

// Slots — what's the pay table?
const symbolCount = await slots.read.symbolCount();
const weights: bigint[] = [];
const triples: bigint[] = [];
const pairs:   bigint[] = [];
for (let i = 0; i < Number(symbolCount); i++) {
  weights.push(await slots.read.symbolWeights([i]));
  triples.push(await slots.read.triplePayout([i]));
  pairs.push  (await slots.read.pairPayout([i]));
}

// Baccarat — what's the current Banker payout multiplier?
const bankerMul = await baccarat.read.bankerPayoutMultiplier();
// 1.95e18 = 1.95×

// Roulette — what's the maxProfitUsd cap?
const maxProfitUsd = await roulette.read.maxProfitUsd();
```

There is no "pull this from the API and trust the operator." The chain *is* the API.

***

### Free bets

If your product serves users who already have an Overtime free-bet balance, call `placeBetWithFreeBet` (or `placeMultiBetWithFreeBet` in Roulette) instead of `placeBet`. The signature is identical except no collateral pull happens — the contract debits the user's free-bet balance via the existing `IFreeBetsHolder`.

```solidity
function placeBetWithFreeBet(
    address collateral,
    uint amount,
    BetType betType,
    uint8 selection
) external returns (uint betId, uint requestId);
```

Free-bet wins are settled to `freeBetsHolder` automatically. Your frontend doesn't need to do anything special beyond the call itself.

***

### Bankroll, liquidity, and bet sizing

Every Casino contract maintains a **per-collateral bankroll reservation** (`reservedProfitPerCollateral`). When a bet is placed, the contract reserves the worst-case payout against the bankroll. If the bankroll is insufficient at that moment, the bet reverts with `InsufficientAvailableLiquidity`.

For Roulette specifically, multi-pick bets compute the **worst-case net liability across all 37 wheel outcomes**, not the naive sum of all picks' payouts. Mutually exclusive picks (e.g. Dozen 1 + Dozen 2) don't double-reserve. This is implemented in `_worstCaseProfit`. If you write a custom client, mirror this logic when validating bets locally to avoid wasted reverts.

There's also a per-bet `maxProfitUsd` cap, normalized through the Chainlink price feed. Large bets that would exceed it revert with `MaxProfitExceeded`. Your frontend should query `maxProfitUsd` and `getCollateralPrice(collateral)` and gate the user before submission.

***

### Cancellation flow

If a Chainlink VRF callback never arrives (very rare; possible during Chainlink network incidents):

```solidity
function cancelBet(uint betId) external;
```

After `cancelTimeout` (minimum 30 seconds, configurable per game) has passed since the bet was placed, the user can cancel and recover their full stake. Your frontend should expose this as a "Recover stake" button on stuck bets, and ideally hide it behind a 30+ second elapsed-time check so users don't see it on bets that will resolve normally.

There is also `adminCancelBet`, callable only by addresses with the `MARKET_RESOLVING` role on the Overtime manager. Operators (including 3rd-party integrations using their own deployment) can use this for ops emergencies, but **on the canonical Overtime deployment, the user-driven `cancelBet` is the path.**

***

### Pausability

Every contract is `ProxyPausable`. The owner (or addresses with the `TICKET_PAUSER` role) can pause new bets via `setPausedByRole`. **Already-pending bets continue to resolve.** Cancellation paths remain available.

Your frontend should handle the `Paused` revert gracefully and surface a clear "casino paused" state. The pause state itself is readable via `paused()`.

***

### Subgraph and indexing

Overtime maintains a public subgraph that indexes all Casino events across supported chains. If you don't want to run your own indexer, query that. URL and schema are at **docs.overtime.io**.

If you do want your own indexer:

* **Self-host with The Graph node**, Goldsky, Envio, or Ponder
* **Index every game contract per chain, plus `CasinoCoreV2`**, which emits the shared settlement, free-bet and referral event.
* **Watch for proxy upgrades** — these are upgradeable proxies. Address is stable, but ABI may change. Re-pull ABIs after major version bumps.

***

### Security and operational notes

* **Always validate user input client-side** before submitting bets, wrong selection encodings will revert. The interface clarity (`enum BetType`, `uint8 selection`) is a feature; mirror those types in your frontend.
* **Watch for `requestId == 0` collision**: the contracts use `requestIdToBetId` mapping. A `requestId` of zero is treated as "unknown." This is a Chainlink-side guarantee; just be aware.
* **Reentrancy is handled** by `ProxyReentrancyGuard` on every state-mutating function. You don't need to wrap calls in your own reentrancy protection.
* **The CEI pattern** (Checks → Effects → Interactions) is followed in all resolution paths. Bet status flips to `RESOLVED` *before* payout transfers go out. If a payout transfer fails, the resolution still stands; the user retains a claim against the contract balance.
* **Don't hardcode contract addresses.** Read them from the Overtime documentation site or the deployments JSON in the repo. Addresses can vary per chain. **Never hallucinate**, verify on a block explorer.

***

**Streak games: Penalty Shootout, Hoop Streak, Standoff, Shooting Range**

The four streak games run on one contract, `StreakGame`, a multi-round engine on `CasinoCoreV2`. Each game is a registered mode. A run is one stake and a chain of rounds. Each round names a difficulty (`tierIdx`), plus an aim zone (`choice`) in Penalty Shootout. A win compounds the multiplier; a loss ends the run. The player can cash out after any win.

|               |                                                                                                                                                                                                                                       |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Contracts** | `StreakGame` (upgradeable proxy): Optimism `0xD93d8b470FCdcd06782CF0542FBe5182e9A7eBC5`, Arbitrum `0x37633afee713fB41a6941775d84A8258F236FF60`, Base `0x44eD1e9c8F2f08CB072586C7509BdC333dbFE0a7`                                     |
| **Approve**   | `CasinoCoreV2` on the same chain, not the game: core pulls the stake. Optimism `0x4BACE3b2BC955C11166e35673c71Be1593b42F80`, Arbitrum `0xA9d5789824aBc53d52224BA6D4eF6d41E99d8699`, Base `0xab487C74Bd9fb88Cea5D39F25C6a15C4A7734055` |
| **Modes**     | See the table below. Offer only the modes documented here, and only while `getModes()` reports them `active`: the registry can hold modes that haven't launched                                                                       |
| **Free bets** | `isFreeBet = true` on `placeBet`; no separate function                                                                                                                                                                                |

| Game             | `modeId` | Name in `getModes()` | Win rule                           | `tierIdx` → winning slots                                                                     |
| ---------------- | -------- | -------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------- |
| Penalty Shootout | `1`      | Penalty Shootout     | `slot ≠ choice` (`distinctChoice`) | `0` Amateur 4 of 5, `1` Pro 2 of 3, `2` World Class 1 of 2                                    |
| Hoop Streak      | `2`      | Hoop Streak          | `slot < num`                       | `0` Layup 24 of 30, `1` Mid-Range 20 of 30, `2` Three 15 of 30, `3` Half-Court 6 of 30        |
| Shooting Range   | `3`      | Baseball Swing       | `slot < num`                       | `0` Full Body 24 of 30, `1` Torso 20 of 30, `2` Chest 15 of 30, `3` Headshot 6 of 30          |
| Standoff         | `4`      | Bullseye             | `slot < num`                       | `0` 1 Outlaw 72 of 90, `1` 2 Outlaws 60 of 90, `2` 3 Outlaws 45 of 90, `3` 4 Outlaws 18 of 90 |

In Penalty Shootout, `choice` is the zone you aim at, from `0` to `zones − 1`, and it doesn't change the odds. In the other three modes `choice` is ignored; pass `0`.

**Entry points**

```solidity
// Place the bet AND play the first round
function placeBet(
    address collateral,   // USDC, WETH or $OVER
    uint256 amount,       // token-native decimals
    address referrer,     // your affiliate wallet, or address(0)
    uint8 modeId,         // 1 Penalty Shootout, 2 Hoop Streak, 3 Shooting Range, 4 Standoff
    uint8 tierIdx,        // difficulty, see the mode table
    uint32 choice,        // aim zone in Penalty Shootout, 0 elsewhere
    bool isFreeBet
) external returns (uint256 betId, uint256 requestId);

// Next round, only when the run is in PLAYER_TURN (after a win)
function playRound(uint256 betId, uint8 tierIdx, uint32 choice) external returns (uint256 requestId);

// Bank stake × current multiplier
function cashout(uint256 betId) external;
```

**Lifecycle**

```
user calls placeBet
 ├─ core pulls the stake (or the free-bet balance)
 ├─ contract prices the round from the mode's tier table
 ├─ core reserves stake × factor and requests a VRF word
 └─ emits BetPlaced, RoundStarted                              status = AWAITING_ROUND

[Chainlink VRF]

core calls onVrfFulfilled
 ├─ slot = randomWord % den
 ├─ win (slot ≠ choice in Penalty Shootout, slot < num elsewhere):
 │    multiplier × factor, emits RoundResolved(WIN)            status = PLAYER_TURN
 └─ loss: referrer paid, emits RoundResolved(LOSS), BetResolved(LOST)   status = RESOLVED

user calls playRound (next round, back to AWAITING_ROUND)
   or cashout: pays stake × multiplier, emits CashedOut, BetResolved(CASHED_OUT)
```

Payouts happen only in `cashout`, never inside the VRF callback. Enums: `BetStatus` `0` NONE, `1` PLAYER\_TURN, `2` AWAITING\_ROUND, `3` RESOLVED, `4` CANCELLED. `RoundOutcome` `1` WIN, `3` LOSS (`2` PUSH is not used by any current mode). `Outcome` `1` CASHED\_OUT, `2` LOST.

**Events you'll want to index**

| Event                                                                                | When it fires                                                                           |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
| `BetPlaced(betId, user, collateral, amount, modeId)`                                 | Bet placed, with the first round                                                        |
| `RoundStarted(betId, requestId, user, modeId, tierIdx, den, num, choice, factorE18)` | Every round, before VRF                                                                 |
| `RoundResolved(betId, requestId, user, slot, outcome, newMultiplierE18)`             | Every round resolved; `slot` is the drawn slot (in Penalty Shootout, the keeper's zone) |
| `CashedOut(betId, user, multiplierE18, payout)`                                      | Player banked the run                                                                   |
| `BetResolved(betId, user, outcome, payout)`                                          | Run over, cashed out or lost                                                            |
| `AdminCashout(betId, user, multiplierE18, payout)`                                   | Resolver settled an idle run at full multiplier                                         |
| `BetCancelled(betId, user, refundAmount, adminCancelled)`                            | Stalled run refunded, stake only                                                        |

**Reads**

| Call                                                                     | Returns                                                                             |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| `getModes()` / `getMode(modeId)`                                         | Registered modes, their tiers (`den`, `num`, `pushNum`) and `active` flag           |
| `factorForTierE18(modeId, tierIdx)`                                      | Payout factor at the current edge, 1e18 precision                                   |
| `houseEdgeE18()`, `maxMultiplierE18()`                                   | Current edge and cap; both are snapshotted into each bet at `placeBet`              |
| `playableTiers(betId)`                                                   | Which difficulties this run can still take without passing the cap                  |
| `maxFactorAllowedE18(betId)`                                             | Largest factor that still fits; `0` means cash out only                             |
| `getFullRecord(betId)`, `getFullRecords(betIds)`                         | Bet snapshot (status, mode, multiplier, stake, payout, rounds)                      |
| `getUserRecords(user, offset, limit)`, `getRecentRecords(offset, limit)` | Paginated history, newest first, `limit` ≤ 200, all modes mixed: filter on `modeId` |
| `getBetRounds(betId)`                                                    | Per round: tier, factor, slot, outcome, multiplier after                            |
| `core.effectiveMaxProfitUsd(game)`                                       | Max profit per run in USD (1e18); max stake = this ÷ (cap − 1), currently 20.20 USD |

Streak game records are not in `CasinoDataV2`; read them from `StreakGame`.

**Quickstart: an agent that plays twice and banks it (viem)**

```typescript
import { createPublicClient, createWalletClient, http, parseAbi, parseEventLogs, erc20Abi } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { optimism } from "viem/chains";

const account = privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`);
const wallet = createWalletClient({ account, chain: optimism, transport: http() });
const client = createPublicClient({ chain: optimism, transport: http() });

const STREAK = "0xD93d8b470FCdcd06782CF0542FBe5182e9A7eBC5";
const CORE = "0x4BACE3b2BC955C11166e35673c71Be1593b42F80"; // CasinoCoreV2 on Optimism: approve this one
const USDC = "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85";
const REFERRER = "0xYOURAFFILIATEWALLET";

const abi = parseAbi([
  "function placeBet(address collateral, uint256 amount, address referrer, uint8 modeId, uint8 tierIdx, uint32 choice, bool isFreeBet) returns (uint256 betId, uint256 requestId)",
  "function playRound(uint256 betId, uint8 tierIdx, uint32 choice) returns (uint256 requestId)",
  "function cashout(uint256 betId)",
  "function playableTiers(uint256 betId) view returns (bool[])",
  "function getFullRecord(uint256 betId) view returns ((uint256 betId, address user, address collateral, uint256 amount, uint256 payout, uint256 placedAt, uint256 lastRequestAt, uint256 resolvedAt, uint8 status, uint8 outcome, uint256 currentMultiplierE18, uint256 maxMultiplierE18, uint256 houseEdgeE18, uint16 roundCount, uint16 winCount, uint16 pushCount, bool isFreeBet, uint8 modeId, uint256 reserved, uint256 lastActionAt))",
  "event BetPlaced(uint256 indexed betId, address indexed user, address collateral, uint256 amount, uint8 modeId)",
]);

const MODE = 1;       // 1 Penalty Shootout, 2 Hoop Streak, 3 Shooting Range, 4 Standoff
const TIER = 1;       // Penalty Shootout: Pro. In modes 2 to 4, tier 1 is the 66.7% difficulty
const AIM = (zone: number) => (MODE === 1 ? zone : 0); // only Penalty Shootout uses choice
const STATUS = { PLAYER_TURN: 1, AWAITING_ROUND: 2, RESOLVED: 3 };
const stake = 5_000_000n; // 5 USDC

const send = async (req: any) =>
  client.waitForTransactionReceipt({ hash: await wallet.writeContract(req) });

// 1. Approve core, which pulls the stake
await send({ address: USDC, abi: erc20Abi, functionName: "approve", args: [CORE, stake] });

// 2. Bet and play the first round
const receipt = await send({ address: STREAK, abi, functionName: "placeBet",
  args: [USDC, stake, REFERRER, MODE, TIER, AIM(0), false] });
const [{ args: { betId } }] = parseEventLogs({ abi, logs: receipt.logs, eventName: "BetPlaced" });

// 3. Wait for the draw: PLAYER_TURN = win, RESOLVED = loss
async function waitForDraw() {
  for (;;) {
    const run = await client.readContract({ address: STREAK, abi, functionName: "getFullRecord", args: [betId] });
    if (run.status !== STATUS.AWAITING_ROUND) return run;
    await new Promise((r) => setTimeout(r, 1500));
  }
}
let run = await waitForDraw();

// 4. One more round at the same difficulty if it still fits under the cap, then bank it
if (run.status === STATUS.PLAYER_TURN) {
  const playable = await client.readContract({ address: STREAK, abi, functionName: "playableTiers", args: [betId] });
  if (playable[TIER]) {
    await send({ address: STREAK, abi, functionName: "playRound", args: [betId, TIER, AIM(2)] });
    run = await waitForDraw();
  }
  if (run.status === STATUS.PLAYER_TURN) {
    await send({ address: STREAK, abi, functionName: "cashout", args: [betId] });
  }
}
```

**Reverts to handle**

| Error                           | Meaning                                                    | What your client should do                           |
| ------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------- |
| `InvalidAmount` / `AboveMaxBet` | Stake below 3 USD, or above a per-game max                 | Validate the stake in USD before submitting          |
| `MaxProfitExceeded`             | `stake × (cap − 1)` is above max profit                    | Cap the stake at `effectiveMaxProfitUsd ÷ (cap − 1)` |
| `ModeInactive` / `UnknownMode`  | Mode not live                                              | Use only documented, active modes                    |
| `InvalidTier` / `InvalidChoice` | Tier index out of range, or (Penalty Shootout) aim ≥ zones | Mirror the mode table client-side                    |
| `FactorExceedsRemainingCap`     | That difficulty would pass the cap                         | Drive buttons from `playableTiers`                   |
| `MaxMultiplierReached`          | No difficulty fits any more                                | Offer Cash Out only                                  |
| `PoolCannotCoverRound`          | Treasury can't cover this round right now                  | Show it; the run stays cashable at its multiplier    |
| `InvalidBetStatus`              | Acting while a round is pending, or after the run ended    | Wait for the draw before the next action             |
| `BetNotOwner`                   | Only the bettor can play or cash out                       | Sign with the bettor's wallet                        |
| `GameNotActive` (core)          | Core or game paused, or circuit breaker tripped            | New bets and rounds blocked; cash out still works    |

**Cancellation and idle runs**

There is no user-callable cancel. If a VRF request stalls, the resolver's `adminCancelBet` refunds the original stake and forfeits any accumulated multiplier. If a player walks away after a win, the resolver can call `adminCashout` once the run has been idle for `cancelTimeout` (currently 600 seconds); it pays exactly `stake × current multiplier`. If the game itself is paused, `cashout` is blocked until unpause, but `adminCashout` is not.

***

**Slots on the shared core: Cascade and Tumble**

Cascade and Tumble are single-transaction games on `CasinoCoreV2`. One `placeBet`, one VRF word, and the whole round is played and paid inside the VRF callback. There are no mid-round actions.

|                           | Cascade                                                                                                                                                         | Tumble                                                                                                                                                          |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Contract (proxy)**      | Optimism `0x18a79326cffB773C18831adB1fA3aB95795A8104`, Arbitrum `0xc557E2F8Cf4456173b6AeB8af97B8b805fc85bDd`, Base `0xDdd5aE480ef2522e5EBaa964291D7b7e4EfA4b82` | Optimism `0x92f24800734a95ea60fC08b1FAF64574Da66525F`, Arbitrum `0x9190e2003BF2BDBfa6504Fb21D23eAE63E8C9090`, Base `0xF0A2db9f971518cA40C1fA7656e0B958819C3BAa` |
| **Approve**               | `CasinoCoreV2`                                                                                                                                                  | `CasinoCoreV2`                                                                                                                                                  |
| **What you choose**       | `mode`: `0` Normal, `1` Ante, `2` Buy                                                                                                                           | `spins`: `5` or `10` (live list in `getConfig().buyOptions`)                                                                                                    |
| **Amount pulled**         | `baseBet × cost`: 1×, 1.25× or 102×                                                                                                                             | `price`, in full                                                                                                                                                |
| **Wins are multiples of** | `baseBet`                                                                                                                                                       | `baseBet = price / buyCost(spins)`                                                                                                                              |
| **Bet size**              | Base bet 3 to 30 USD (Buy: up to 4.90 USD)                                                                                                                      | Price 3 to 50 USD                                                                                                                                               |
| **Max payout**            | `min(1000 × baseBet, stake + maxProfitUsd)`                                                                                                                     | `price + maxProfitUsd`                                                                                                                                          |
| **Free bets**             | `isFreeBet = true`, Normal mode only                                                                                                                            | `isFreeBet = true`, either round                                                                                                                                |

`maxProfitUsd` is currently 3,000 USD for both games.

**Entry points**

```solidity
// Cascade: baseBet is the unit every win multiplies; the contract pulls baseBet × mode cost
function placeBet(address collateral, uint256 baseBet, uint8 mode, address referrer, bool isFreeBet)
    external returns (uint256 betId, uint256 requestId);

// Tumble: price is pulled in full; baseBet = price / buyCost(spins)
function placeBet(address collateral, uint256 price, uint8 spins, address referrer, bool isFreeBet)
    external returns (uint256 betId, uint256 requestId);
```

**Lifecycle**

```
user calls placeBet
 ├─ core pulls the stake (or the free-bet balance)
 ├─ core reserves the full max payout and requests ONE VRF word
 └─ emits BetPlaced                                             status = PENDING

[Chainlink VRF]

core calls onVrfFulfilled
 ├─ the word seeds a keccak256 stream; every grid of every spin is drawn from it
 ├─ the round plays out: base spin and free spins (Cascade) or all bought spins (Tumble)
 ├─ payout = min(round total, max payout), transferred to the user
 ├─ referrer paid on (stake − payout) if the round paid back less than it cost
 └─ emits BetResolved(word, payout, ...)                       status = RESOLVED
```

`BetStatus`: `0` NONE, `1` PENDING, `2` RESOLVED, `3` CANCELLED.

**Events you'll want to index**

| Event                                                                                                                                  | When it fires                                                    |
| -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `BetPlaced(betId, requestId, user, collateral, baseBet, stakePaid, mode, capPayout, isFreeBet)`                                        | Cascade bet placed                                               |
| `BetPlaced(betId, requestId, user, collateral, price, baseBet, spins, capPayout, isFreeBet)`                                           | Tumble round bought                                              |
| `BetResolved(betId, requestId, user, word, payout, baseWin, bonusWin, freeSpinsPlayed, capHit)`                                        | Cascade round settled                                            |
| `BetResolved(betId, requestId, user, word, payout, win, spinsPlayed, multiplier, capHit)`                                              | Tumble round settled; `multiplier` is the final round multiplier |
| `BetCancelled(betId, user, refundAmount, adminCancelled)`                                                                              | Stalled round refunded                                           |
| `PaytableUpdated`, `WeightsUpdated`, `BombsUpdated`, `RoundConfigUpdated`, `ModeConfigUpdated` (Cascade), `BuyOptionsUpdated` (Tumble) | Any change to the math model                                     |

**Reads**

| Call                                                                                               | Returns                                                                                                                                 |
| -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `getMaxPayout(collateral, baseBet, mode)` / `getMaxPayout(collateral, price, spins)`               | Cascade: stake pulled and max payout. Tumble: derived base bet and max payout                                                           |
| `getConfig()`                                                                                      | The full math model: paytable, scatter pays, symbol weights, bomb values and weights, cascade caps, free-spin rules, mode or buy prices |
| `simulateRound(word, mode, baseBet, capPayout)` / `simulateRound(word, spins, baseBet, capPayout)` | Replays a round from its word: the result plus a trace of every grid and the win paid on it                                             |
| `getFullRecord(betId)`                                                                             | Bet snapshot, including `word` once resolved                                                                                            |
| `getUserBetIds(user, offset, limit)`, `getRecentBetIds(offset, limit)`                             | Paginated bet ids                                                                                                                       |
| `getStats(collateral, mode)` / `getStats(collateral, spins)`                                       | Lifetime staked, paid out and counts per mode or round size                                                                             |

`simulateRound` replays under the current math model. The model is read when the VRF word arrives, not snapshotted at placement, so a round resolved before a model change replays differently from how it paid. `BetResolved` always records what was paid.

**Quickstart: buy a Tumble round and verify it (viem)**

```typescript
import { createPublicClient, createWalletClient, http, parseAbi, parseEventLogs, erc20Abi } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { optimism } from "viem/chains";

const account = privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`);
const wallet = createWalletClient({ account, chain: optimism, transport: http() });
const client = createPublicClient({ chain: optimism, transport: http() });

const TUMBLE = "0x92f24800734a95ea60fC08b1FAF64574Da66525F";
const CORE = "0x4BACE3b2BC955C11166e35673c71Be1593b42F80"; // CasinoCoreV2 on Optimism: approve this one
const USDC = "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85";
const REFERRER = "0xYOURAFFILIATEWALLET";

const abi = parseAbi([
  "function placeBet(address collateral, uint256 price, uint8 spins, address referrer, bool isFreeBet) returns (uint256 betId, uint256 requestId)",
  "function getMaxPayout(address collateral, uint256 price, uint8 spins) view returns (uint256 baseBet, uint256 capPayout)",
  "function getFullRecord(uint256 betId) view returns ((uint256 betId, address user, address collateral, uint256 price, uint256 baseBet, uint256 payout, uint256 capPayout, uint256 placedAt, uint256 lastRequestAt, uint256 resolvedAt, uint256 word, uint256 win, uint8 status, uint8 spins, bool isFreeBet, bool capHit, uint8 spinsPlayed, uint8 retriggers, uint32 multiplier))",
  "function simulateRound(uint256 word, uint8 spins, uint256 baseBet, uint256 capPayout) view returns ((uint256 win, uint256 payout, uint8 spinsPlayed, uint8 retriggers, uint32 multiplier, bool capHit) result, uint256[] trace)",
  "event BetPlaced(uint256 indexed betId, uint256 indexed requestId, address indexed user, address collateral, uint256 price, uint256 baseBet, uint8 spins, uint256 capPayout, bool isFreeBet)",
]);

const SPINS = 10;                 // Steady
const price = 10_000_000n;        // 10 USDC
const PENDING = 1;

const send = async (req: any) =>
  client.waitForTransactionReceipt({ hash: await wallet.writeContract(req) });

// 1. Quote: the base bet every win multiplies, and the most this round can pay
const [baseBet, capPayout] = await client.readContract({ address: TUMBLE, abi, functionName: "getMaxPayout", args: [USDC, price, SPINS] });

// 2. Approve core and buy the round
await send({ address: USDC, abi: erc20Abi, functionName: "approve", args: [CORE, price] });
const receipt = await send({ address: TUMBLE, abi, functionName: "placeBet", args: [USDC, price, SPINS, REFERRER, false] });
const [{ args: { betId } }] = parseEventLogs({ abi, logs: receipt.logs, eventName: "BetPlaced" });

// 3. Wait for the single VRF word to settle the whole round
let rec = await client.readContract({ address: TUMBLE, abi, functionName: "getFullRecord", args: [betId] });
while (rec.status === PENDING) {
  await new Promise((r) => setTimeout(r, 1500));
  rec = await client.readContract({ address: TUMBLE, abi, functionName: "getFullRecord", args: [betId] });
}

// 4. Verify: replay the round from its word and compare with what was paid
const [result] = await client.readContract({ address: TUMBLE, abi, functionName: "simulateRound",
  args: [rec.word, rec.spins, rec.baseBet, rec.capPayout] });
console.log(`paid ${rec.payout}, replay ${result.payout}, match: ${rec.payout === result.payout}`);
```

Cascade follows the same pattern with `placeBet(collateral, baseBet, mode, referrer, isFreeBet)`, `getMaxPayout(collateral, baseBet, mode)` and `simulateRound(word, mode, baseBet, capPayout)`. Approve `baseBet × mode cost`, and read `mode` from the record when you replay.

**Reverts to handle**

| Error                                   | Meaning                                                                                                                       | What your client should do                    |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| `InvalidAmount`                         | Zero, below the 3 USD minimum, or (Tumble) a price so small the base bet rounds to 0                                          | Validate the amount in USD before submitting  |
| `AboveMaxBet`                           | Above the per-game max (Cascade 30 USD base bet, Tumble 50 USD price), or a Cascade Buy above a 4.90 USD base bet             | Cap the input client-side                     |
| `InvalidMode`                           | Cascade: Ante or Buy disabled, or a free bet in Ante or Buy                                                                   | Free bets: Normal only                        |
| `InvalidSpins`                          | Tumble: that spin count isn't offered                                                                                         | Read `getConfig().buyOptions`                 |
| `InvalidCollateral`                     | Collateral not supported by core                                                                                              | USDC, WETH or $OVER only                      |
| `CallbackGasLimitTooLow`                | Core's VRF callback gas is below the 1.5M a heavy round needs; the game refuses bets rather than risk a round it can't settle | Show the game as unavailable                  |
| `InsufficientAvailableLiquidity` (core) | The treasury can't reserve the full max payout right now                                                                      | Show it and let the user retry later          |
| `GameNotActive` (core)                  | Core or game paused, or circuit breaker tripped                                                                               | New bets blocked; pending rounds still settle |

**Cancellation:** there is no user-callable cancel. If a VRF request stalls, the resolver's `adminCancelBet` refunds the full stake (or the Tumble price).

There is no user-callable cancel. If a VRF request stalls, the resolver's `adminCancelBet` refunds the original stake and forfeits any accumulated multiplier. If a player walks away after a goal, the resolver can call `adminCashout` once the run has been idle for `cancelTimeout`; it pays exactly `stake × current multiplier`. If the game itself is paused, `cashout` is blocked until unpause, but `adminCashout` is not.

***

### Don't like the canonical frontend? Build your own.

This is the point. The contracts are public infrastructure. The frontend at overtimemarkets.xyz is *one* possible interface, not *the* interface.

A few examples of what you can ship in an afternoon:

* **A Telegram bot** that lets users place dice rolls in chat, with their own wallet, your address as referrer
* **A Discord game** that runs Blackjack hands inside a server's casino channel
* **A Farcaster Frame** with a "spin slots" button
* **An AI agent** that plays Blackjack autonomously, sized to a budget, optimizing for variance
* **A specialized roulette UI** for a community that wants different table aesthetics, language localization, custom multi-pick presets
* **An embedded widget** on your existing crypto site that lets your users bet from your platform

Pass your `_referrer` address into every bet, and you capture **up to 20% of generated fees** from every interaction. See Become an Overtime Casino Affiliate for the affiliate side.

***

### Resources

* **Contract addresses:** [v2.contracts.overtime.io](https://v2.contracts.overtime.io/), which redirects every contract to its latest deployment, with verified source on the block explorer
* **Overtime docs:** [docs.overtime.io](https://docs.overtime.io)
* **Chainlink VRF v2.5 docs:** [docs.chain.link/vrf/v2-5/overview](https://docs.chain.link/vrf/v2-5/overview)
* **Eth Skills (for AI agents and vibe coders):** [ethskills.com](https://ethskills.com/)
* **Scaffold-ETH 2:** `npx create-eth@latest`

The casino is a public utility, we want to see what gets built on top!
