Skip to main content

bOS v3.0 — Fantasy-First Architecture

The Complete Technical Specification

Version: 3.0 (Fantasy-First "Betfair Killer" Edition) Last Updated: December 2025 Status: Design Phase Vision: Fantasy Sports Platform with Built-in Liquidity Network


Table of Contents

The Vision

  1. Executive Summary
  2. The Multi-Mode Gaming Platform
  3. The Complete bOS Stack

Game Mode Engines

  1. Classic Fantasy Engine
  2. Player Props Engine
  3. Live Trading Engine
  4. Prediction Pools Engine

Fantasy Sports Layer (PRIMARY)

  1. Fantasy Sports Architecture
  2. Contest & Pool System
  3. Live Scoring Engine
  4. Draft & Auction System
  5. Networked Pools (B2B2C)
  6. Agent Wars (B2B Leagues)

Inter-Bookie Orderbook (SECONDARY)

  1. IBO Architecture Overview
  2. Matching Engine Design
  3. Hedge Waterfall System
  4. Settlement & Escrow

Core Platform (FOUNDATION)

  1. Core Platform Modules
  2. Database Schema
  3. API Specifications
  4. Implementation Roadmap

1. Executive Summary

1.1 What is bOS v3.0?

bOS v3.0 transforms from a "Bookie Operating System" into a complete gaming ecosystem. The evolution:

VersionFocusPrimary Revenue
v3.0Fantasy-first with liquidity networkFantasy rake + IBO fees + SaaS

Note: bOS v3.0 is built from the ground up with a Fantasy-First approach. We are NOT extending legacy infrastructure—this is a greenfield build optimized for the crypto-native, globally-distributed gaming ecosystem.

1.2 The Three Pillars of v3.0

Diagram Explanation: The Three Pillars

This diagram illustrates the complete bOS v3.0 ecosystem organized into three interconnected pillars:

Pillar 1: Fantasy Sports (Blue) — THE PRIMARY FOCUS

Fantasy sports becomes the entry point for user acquisition. This is where 80% of player activity will occur:

  • Daily Fantasy: Quick contests that settle after a single match or day. Players draft teams, earn points based on real player performance, and win prizes from prize pools.
  • Season-Long Leagues: Full-season fantasy leagues where players manage teams over weeks/months. Creates recurring engagement and higher lifetime value.
  • Networked Pools: Multiple agents' players compete in shared pools. This is the B2B2C magic—agents contribute players, platform aggregates liquidity, everyone wins.
  • Agent Wars: Agents themselves compete against each other in high-stakes fantasy leagues. B2B engagement driver that creates stickiness.

Pillar 2: Liquidity Network (Red) — THE MOAT

The Inter-Bookie Orderbook (IBO) creates a dark pool where agents can hedge risk with each other:

  • Inter-Bookie Orderbook: A matching engine where agents post bid/ask quotes on sports events. Instead of going to Betfair, agents trade with each other.
  • Matching Engine: Sub-millisecond order matching built in Rust. Handles limit orders, market orders, and partial fills.
  • Hedge Waterfall: Smart routing that tries internal crossing first, then IBO, then external exchanges. Minimizes fees and maximizes efficiency.
  • On-Chain Escrow: Solana smart contracts that lock funds when two agents match on IBO. Trustless settlement.

Pillar 3: Bookie OS (Green) — THE FOUNDATION

The foundation that enables everything else:

  • Digital Ledger: Prepaid wallets, player management, instant settlement
  • Crypto Rails: USDT deposits and withdrawals (TRON/Solana), hot/cold wallet management
  • Risk Dashboard: Real-time exposure tracking, hedging recommendations
  • Telegram Bot: Agent commands, player Mini App, notifications

Important: bOS v3.0 operates on a prepaid model only. Players must deposit USDT before playing. No credit system—this creates a healthier, more sustainable ecosystem and reduces agent risk.

The Interconnections:

  • Fantasy feeds liquidity into the orderbook (agents hedge fantasy exposure)
  • Orderbook integrates with the risk dashboard (positions are visible)
  • Everything settles through the digital ledger (unified accounting)

1.3 Why Fantasy First?

The strategic shift to "Fantasy First" is based on market reality:

FactorTraditional BettingFantasy Sports
Regulatory StatusGray/Illegal in most jurisdictionsSkill-based gaming (more favorable)
User AcquisitionWord-of-mouth onlyTelegram channels, crypto communities
Payment RailsCrypto-onlyCrypto-only (USDT)
RetentionEvent-dependentSeason-long engagement
Monetization5-10% vig (squeezed)15-20% rake (healthy)

Note: As of December 2025, fantasy sports faces regulatory challenges in India and other markets. bOS v3.0 is designed as a global, crypto-native platform targeting the international market. All transactions are in USDT, eliminating fiat payment dependencies.

The Funnel Strategy

Diagram Explanation: The User Funnel

This funnel shows the strategic user journey that bOS v3.0 enables:

  1. Fantasy Player (Entry Point): Acquisition through Telegram channels, crypto gaming communities, and word-of-mouth. USDT deposits create a self-selecting audience of crypto-native users.

  2. Networked Pool (Engagement): Players discover that competing against other agents' players creates larger prize pools. Cross-pollination happens naturally. Players become familiar with the bOS ecosystem.

  3. Sports Bettor (Upsell): Engaged fantasy players are offered prediction markets and eventually traditional sports betting. Everything happens within the Telegram ecosystem.

  4. Shark/Agent (Power User): The most engaged users become agents themselves or provide liquidity to the IBO. They understand odds, manage risk, and participate in Agent Wars.

Why This Works:

  • Crypto-native audience is comfortable with USDT
  • Fantasy creates habitual engagement (not just event-driven)
  • Natural upsell path to higher-margin products
  • Power users become the supply side of the marketplace
  • No dependency on fiat payment rails or local banking

2. The Multi-Mode Gaming Platform

2.1 Beyond Fantasy: A Complete Gaming Ecosystem

bOS v3.0 is not just a fantasy platform — it's a multi-mode gaming ecosystem that offers four distinct ways to play:

Game Mode Overview

ModeDescriptionComplexityRevenue Model
Classic FantasyBuild teams, earn pointsMedium15% rake on prize pools
Player PropsPredict individual statsLow-Medium10% margin on slips
Live TradingBuy/sell outcome sharesHigh2% trading fee
Prediction PoolsSimple yes/no predictionsLow15% rake on pools

Why Multi-Mode?

  1. Capture Every User Segment — Different users want different experiences
  2. Maximize Lifetime Value — Multi-mode users have 3x higher retention
  3. Cross-Mode Synergies — Users naturally flow between modes
  4. Reduce Seasonality — Different modes peak at different times

2.2 Market Opportunity

The global fantasy sports market is massive and growing:

Metric20232025 (Projected)2027 (Projected)
Users180M250M350M
Market Size$2.5B$5B$10B
Platform Revenue$400M$1B$2.5B
Key PlayersDream11, MPL, My11Circle+ bOSbOS Top 5

2.2 The bOS Advantage

Unlike Dream11 (pure fantasy) or traditional bookies (pure betting), bOS creates a hybrid ecosystem:

Diagram Explanation: Business Model Comparison

This diagram compares three business models to show why bOS v3.0's hybrid approach is superior:

Dream11 Model (Left - Red Result)

  • Revenue comes only from fantasy rake (15-20% of prize pools)
  • No betting, no B2B services
  • Single stream = vulnerable to competition and regulation
  • High customer acquisition cost, must spend heavily on marketing

Traditional Bookie Model (Center - Red Result)

  • Revenue from betting vig (5-10% of wagers)
  • No diversification
  • High regulatory risk, limited distribution
  • Cannot advertise, word-of-mouth only

bOS v3.0 Model (Right - Green Result)

  • Multiple Revenue Streams:
    • Fantasy rake (15-20%) - skill-based gaming
    • IBO trading fees (0.1-0.5%) - high volume, low margin
    • SaaS subscriptions - recurring, predictable
  • Lower overall risk because not dependent on single stream
  • Crypto-native = no fiat banking dependencies
  • Higher lifetime value per user due to multiple products

Key Insight: bOS doesn't compete head-to-head with Dream11 OR traditional bookies. It creates a new category that serves agents (B2B) who then serve players (B2B2C). This is fundamentally different from Dream11's B2C model.


2.3 The Networked Pool Innovation

The killer feature of bOS Fantasy is cross-agent liquidity:

Diagram Explanation: Networked Pool Economics

This diagram shows how multiple agents' players compete in a single pool, creating value for everyone:

The Setup:

  • Three agents (Mumbai Sports, Delhi Bets, Kolkata Kings) each have their own player base
  • Traditionally, each would run separate contests with only their own players
  • Small player bases mean small prize pools → less attractive → fewer entries

The Networked Pool Solution:

  • All 8 players from 3 agents join the same IPL Fantasy Pool
  • Entry fee: 10 USDT each = 80 USDT total prize pool
  • Larger pool = more attractive prizes = more entries = flywheel effect

The Economics:

  • Platform (bOS): Takes 10% (8 USDT) as platform fee
  • Agents: Each agent gets 3% per entry their player makes
    • Agent 1 (3 entries): 0.9 USDT
    • Agent 2 (2 entries): 0.6 USDT
    • Agent 3 (3 entries): 0.9 USDT
  • Winners: 80% goes to prize pool (64 USDT distributed to top 3)

Why Agents Love This:

  • Larger pools attract more entries from their players
  • They earn commission without running contests themselves
  • No risk—they're not the counterparty
  • Players get better experience → more retention → more commission

Why Players Love This:

  • Bigger prize pools than agent-only contests
  • More competition = more exciting
  • Same trusted agent relationship
  • Transparent, platform-managed payouts

3. The Complete bOS Stack

3.1 System Architecture Overview

Diagram Explanation: Complete System Architecture

This diagram shows the full technical stack of bOS v3.0, highlighting the new components:

Client Layer (Top)

  • Player TMA: Enhanced Telegram Mini App that now includes Fantasy features alongside betting
  • Agent Dashboard: Web-based management console for agents
  • Telegram Bot: Command interface for agents (/limit, /bet, /fantasy, etc.)

API Gateway

  • Kong Gateway: Rate limiting, authentication, routing
  • WebSocket Server: Real-time updates for live scoring, odds, balances

Fantasy Services (NEW - Blue) These are the new v3.0 components for fantasy sports:

  • Fantasy Engine: Core business logic for contests, entries, payouts
  • Scoring Service: Consumes live sports data, calculates points in real-time
  • Draft/Auction: Real-time WebSocket-based team drafting and auction bidding
  • Pool Manager: Handles networked pools, cross-agent liquidity, commission distribution

IBO Services (NEW - Red) These are the new v3.0 components for the liquidity network:

  • Matching Engine: Rust-based order matcher for sub-millisecond performance
  • Order Book: Redis-backed bid/ask storage
  • Hedge Router: Smart routing through internal → IBO → external

Core Services (Built Fresh for v3.0) The foundation built specifically for fantasy-first:

  • Auth: Telegram initData validation, JWT sessions
  • Tenant: Multi-tenant isolation for agents
  • Player: Player profiles, prepaid wallets
  • Wallet: USDT deposits/withdrawals, balance management
  • Betting: Bet placement and settlement (future phase)
  • Risk: Exposure tracking, alerts

Data Layer

  • PostgreSQL: Primary database for all entities
  • Redis: Caching, pub/sub, order book storage, leaderboards
  • Solana: On-chain escrow for IBO settlements, collateral vaults

4. Classic Fantasy Engine

4.1 Overview

The Classic Fantasy Engine is the core game mode — the DraftKings/Dream11 experience.

4.2 Team Building Rules

RuleDescriptionConfigurable
Salary CapTotal budget for player selectionYes
Position LimitsMin/max players per positionYes
Team LimitsMax players from same teamYes
Captain/VCMultiplier selectionsYes

4.3 Scoring Integration

Fantasy points are calculated by the shared Scoring Engine (see Section 10).


5. Player Props Engine

5.1 Overview

Player Props allows users to predict individual player statistics.

5.2 Prop Types

CategoryExamplesResolution Trigger
BattingRuns, boundaries, SRPlayer out / innings end
BowlingWickets, economyMatch end
TeamTotal runs, partnershipsInnings end

5.3 Slip Mechanics

  • Single Picks: Bet on one prop
  • Multi-Leg Slips: Combine 2-10 props for multiplied odds
  • Insurance: Optional protection against one miss

6. Live Trading Engine

6.1 Overview

Live Trading transforms sports into a financial market with real-time price movements.

6.2 Market Types

MarketExampleSettlement
Player MilestonesRohit 50+ runsWhen achieved or player out
Match OutcomesTeam to winMatch end
Period MarketsPowerplay runs O/UPeriod end

6.3 AMM Design

The Automated Market Maker provides continuous liquidity:

  • Constant Product Formula: x * y = k
  • Dynamic Fees: 0.5-2% based on volatility
  • Price Bounds: 1¢ to 99¢ per share

7. Prediction Pools Engine

7.1 Overview

Prediction Pools are the simplest game mode — pick a side and share the pool.

7.2 Pool Mechanics

AspectDescription
EntryPick YES or NO, stake any amount
OddsDetermined by pool ratio
SettlementWinners split losing side's stakes
Rake15% of total pool

7.3 Pool Types

  • Match Winner: Will Team A win?
  • Player Performance: Will Player X score 50+?
  • First Events: First boundary a six?
  • Season Predictions: Will Team Y make playoffs?

8. Fantasy Sports Architecture

8.1 Fantasy Domain Model

Diagram Explanation: Fantasy Domain Model

This entity-relationship diagram shows the data model for fantasy sports:

Core Entities:

EntityPurposeKey Fields
FANTASY_POOLNetwork-wide contest poolEntry fee, prize structure, participating agents
FANTASY_CONTESTAgent-specific contest within a poolMax entries, prize splits, agent's players only
FANTASY_ENTRYA player's team submissionSelected athletes, total points, final rank
FANTASY_PICKIndividual athlete selectionPosition, captain multiplier, earned points
ATHLETEReal-world sports playerName, team, salary, historical stats
FANTASY_SCOREPoints earned per athlete per matchBreakdown by category (runs, wickets, etc.)

Key Relationships:

  • A Pool contains multiple Contests (one per participating agent)
  • A Contest has multiple Entries (player submissions)
  • An Entry contains multiple Picks (selected athletes)
  • Scores track points earned per athlete per match

The Pool-Contest Split: This is the key innovation. A Pool is network-wide, but each agent's players only see their agent's Contest. Behind the scenes, all Contests in a Pool compete together for the same prize pool.


4.2 Scoring Engine Architecture

Diagram Explanation: Scoring Engine Architecture

This diagram shows how live sports data becomes fantasy points in real-time:

Data Ingestion (Top) Multiple sports data providers feed into the system:

  • CricketAPI: Ball-by-ball cricket data
  • Football-Data.org: Soccer match events
  • NBA API: Basketball play-by-play

Each provider has different data formats and update frequencies.

Processing Pipeline

  • Data Ingestor: BullMQ worker that polls APIs and queues events for processing
  • Event Parser: Normalizes different API formats into a standard event structure
  • Points Calculator: Applies scoring rules to raw events

Scoring Engine (Core)

  • Scoring Rules: Sport-specific point values (configurable per contest type)
    Cricket Example:
    - Run scored: +1 point
    - Boundary (4): +1 bonus
    - Six: +2 bonus
    - Wicket: +25 points
    - Catch: +8 points
    - Captain: 2x multiplier
  • Real-Time Scorer: Processes events as they arrive, updates player points
  • Aggregator: Sums individual athlete scores into entry totals

Distribution (Bottom) Three parallel outputs for different use cases:

  • Redis ZSET (Leaderboards): O(log N) rank updates using sorted sets. Players see live rankings.
  • WebSocket Push: Instant updates to all connected clients
  • PostgreSQL Persist: Durable storage for historical scoring data

Performance Targets:

  • Event ingestion to leaderboard update: <500ms
  • Support 100+ concurrent matches
  • Handle 10,000+ ball-by-ball events per IPL match

4.3 Scoring Rules Configuration

┌─────────────────────────────────────────────────────────────────────────────┐
│ CRICKET FANTASY SCORING │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ BATTING BOWLING │
│ ──────── ──────── │
│ Run scored +1 pt Wicket +25 pts │
│ Boundary (4) +1 pt bonus Maiden over +12 pts │
│ Six +2 pts bonus LBW/Bowled bonus +8 pts │
│ Half-century +8 pts bonus 3-wicket haul +4 pts bonus │
│ Century +16 pts bonus 4-wicket haul +8 pts bonus │
│ Strike rate <70 -2 pts 5-wicket haul +16 pts bonus │
│ Strike rate <60 -4 pts Economy <5 +6 pts │
│ Duck -2 pts Economy 5-6 +4 pts │
│ Economy 6-7 +2 pts │
│ FIELDING Economy >10 -2 pts │
│ ──────── Economy >11 -4 pts │
│ Catch +8 pts │
│ Stumping +12 pts MULTIPLIERS │
│ Run out (direct) +12 pts ──────────── │
│ Run out (assist) +6 pts Captain 2x │
│ Vice-Captain 1.5x │
│ │
│ BONUSES │
│ ──────── │
│ Player of Match +15 pts │
│ Winning team +5 pts (all players) │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

9. Contest & Pool System

5.1 Contest Types

Diagram Explanation: Contest Types

bOS Fantasy supports five contest types to serve different player preferences:

TypePool SizeEntriesWin RateTarget User
MEGA10K+ USDT10,000+Top 30%Mass market, lottery feel
HEAD-TO-HEAD2 USDT250% (winner)Competitive players
SMALL100 USDT100Top 20%Balanced risk/reward
PRIVATECustomInviteCustomFriends, local groups
AGENT WARS1K+ USDTAgentsTop 10%B2B competition

The Agent Wars Innovation: Agent Wars is unique to bOS. Agents compete against each other (not their players) in high-stakes fantasy leagues. This creates:

  • B2B engagement and stickiness
  • Bragging rights and community
  • Platform buzz (leaderboards, prizes)
  • Revenue from agent buy-ins

5.2 Pool Lifecycle

Diagram Explanation: Pool Lifecycle

This state diagram shows the complete lifecycle of a fantasy pool:

StateDescriptionDuration
DRAFTPool created, not yet visibleUntil published
OPENAccepting entriesUntil match starts
LIVEMatch in progressDuring match
SCORINGPoints being calculatedDuring match
COMPLETEDMatch ended, final scoresMinutes
SETTLEDPayouts calculatedMinutes
CANCELLEDRefund all entriesIf insufficient entries

Key Transitions:

  • DRAFT → OPEN: Agent publishes the pool, players can now enter
  • OPEN → LIVE: Match starts (automatic based on schedule)
  • LIVE ↔ SCORING: Continuous scoring updates during match
  • COMPLETED → SETTLED: Calculate ranks, apply prize structure, create payouts
  • SETTLED → [*]: Distribute funds via ledger entries

10. Live Scoring Engine

6.1 Real-Time Scoring Flow

Diagram Explanation: Real-Time Scoring Flow

This sequence shows how a single ball in cricket becomes a points update on screen:

Step-by-Step:

  1. API → Worker: Sports data provider sends ball event (e.g., "Kohli hits boundary")
  2. Worker → Worker: Scoring logic applies rules (Run + Boundary bonus = 5 points)
  3. Worker → Redis: Two operations:
    • ZINCRBY: Atomically increment entry's total in leaderboard sorted set
    • HSET: Update athlete's individual score in entry hash
  4. Redis → WS → TMA: Pub/Sub broadcasts change, WebSocket pushes to client
  5. TMA → TMA: React updates UI with new score

Why This Architecture:

  • Redis ZSET: Leaderboards need O(log N) rank queries. ZSET is perfect.
  • Pub/Sub: Decouples scoring from delivery—scales to 100K+ connected users
  • ~100ms latency: From ball bowled to screen update is near-instant

6.2 Leaderboard Query Pattern

┌─────────────────────────────────────────────────────────────────────────────┐
│ REDIS LEADERBOARD OPERATIONS │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ STRUCTURE │
│ ───────── │
│ Key: leaderboard:{contestId} │
│ Type: Sorted Set (ZSET) │
│ Score: Total fantasy points │
│ Member: Entry ID │
│ │
│ OPERATIONS │
│ ────────── │
│ Add/Update: ZINCRBY leaderboard:abc123 5 entry:xyz789 │
│ Get Rank: ZREVRANK leaderboard:abc123 entry:xyz789 → 42 │
│ Top 10: ZREVRANGE leaderboard:abc123 0 9 WITHSCORES │
│ My Position: ZREVRANGE leaderboard:abc123 40 50 WITHSCORES (around me) │
│ │
│ PERFORMANCE │
│ ─────────── │
│ ZINCRBY: O(log N) - ~0.1ms for 100K entries │
│ ZREVRANK: O(log N) - ~0.1ms for 100K entries │
│ ZREVRANGE: O(log N + M) - ~0.2ms for top 10 │
│ │
│ EXAMPLE LEADERBOARD │
│ ─────────────────── │
│ Rank Entry Points Player │
│ ──── ───── ────── ────── │
│ 1 entry:abc 892 Rahul S. │
│ 2 entry:def 876 Priya M. │
│ 3 entry:ghi 854 Amit K. │
│ ... │
│ 42 entry:xyz 723 You │
│ ... │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

11. Draft & Auction System

7.1 Auction Room Architecture

For salary-cap drafts and live auctions, bOS uses WebSocket rooms:

Diagram Explanation: Auction Room Architecture

This diagram shows how live auctions work for fantasy team drafts:

The Auction Room:

  • Each auction is a WebSocket "room" with a unique ID
  • Tracks current state: which athlete is being bid on, time remaining, current bid
  • Manages room membership (who's connected)

Connected Clients:

  • All participants maintain WebSocket connections
  • Each sees real-time updates as bids come in
  • Client-side shows remaining budget, bid history

Bid Processing:

  1. Player places bid: WebSocket message to server
  2. Validation: Check budget, check bid > current, check timing
  3. If valid: Update room state, broadcast to all clients
  4. If invalid: Return error to bidder only

Auction Flow:

  1. Athlete is presented (e.g., "Virat Kohli, Base Price 12 USDT")
  2. Timer starts (30-60 seconds)
  3. Players bid in increments (0.5 USDT minimum)
  4. Highest bid when timer expires wins
  5. Next athlete presented, repeat

7.2 Auction State Machine

Diagram Explanation: Auction State Machine

This nested state machine shows auction lifecycle:

Outer States:

  • WAITING: Room created, waiting for all players to join
  • ACTIVE: Auction in progress (nested state machine)
  • COMPLETED: All athletes drafted, teams locked
  • CANCELLED: Timeout or manual cancellation

Inner States (ACTIVE):

  • PRESENTING: Current athlete shown, about to start bidding
  • BIDDING: Timer running, accepting bids
  • SOLD: Timer expired, athlete assigned to winner

Key Behaviors:

  • Each new bid resets the timer (+10 seconds)
  • Prevents sniping—must outbid with time for response
  • When all athletes drafted, auction completes automatically

12. Networked Pools (B2B2C)

8.1 Cross-Agent Pool Flow

Diagram Explanation: Cross-Agent Pool Flow

This sequence shows the complete lifecycle of a networked pool:

Phase 1: Pool Creation

  1. Platform creates the network pool (e.g., "IPL Final Fantasy")
  2. Platform invites participating agents
  3. Each agent accepts and creates their "view" of the pool (their contest)

Phase 2: Entry Collection 4. Player 1 (Agent 1's customer) browses and sees the pool contest 5. Player 1 enters with 10 USDT 6. Player 2 (Agent 2's customer) does the same 7. Both entries are in the same underlying pool

Phase 3: Settlement 8. Match ends, pool calculates rankings across ALL entries 9. Winners receive payouts (regardless of which agent they belong to) 10. Platform takes 10% fee 11. Each agent receives 3% commission on their players' entries

The Key Innovation: Players only interact with their agent's contest, but compete in a global pool. This solves the liquidity problem—small agents can offer big-pool experiences.


8.2 Commission Distribution

Diagram Explanation: Commission Distribution

This pie chart shows how prize money flows:

RecipientPercentageAmount (100 USDT pool)Notes
Winners80%80 USDTDistributed per prize structure
Platform10%10 USDTbOS revenue
Agents10%10 USDTSplit by entries contributed

Agent Commission Calculation: If Agent A contributed 6 entries and Agent B contributed 4 entries:

  • Agent A: 6/10 × 10 USDT = 6 USDT
  • Agent B: 4/10 × 10 USDT = 4 USDT

Why Agents Love This:

  • Risk-free revenue (not counterparty)
  • Larger pools = more player engagement = more entries
  • Automatic commission calculation and distribution

13. Agent Wars (B2B Leagues)

9.1 Agent Wars Concept

Agent Wars is a B2B fantasy league where agents compete against each other:

Diagram Explanation: Agent Wars Concept

What is Agent Wars? A season-long fantasy league exclusively for agents. Instead of players competing against players, agents compete against agents.

League Structure:

  • Buy-in: High stakes (500+ USDT) for serious competition
  • Duration: Full IPL season (2 months, 70+ matches)
  • Entries: Verified agents only (prevents sybil attacks)
  • Scoring: Cumulative points across all matches

How It Works:

  1. Agent joins league by paying buy-in (locked in escrow)
  2. Before each match, agent selects their fantasy team
  3. Points accumulate over the season
  4. At season end, top agents win from prize pool

Why Agent Wars Matters:

  • Engagement: Agents check in daily (not just when their players are active)
  • Community: Creates relationships between agents
  • Marketing: Leaderboard creates buzz, winners become advocates
  • Revenue: High-stakes buy-ins generate significant platform revenue

14. IBO Architecture Overview

10.1 The Inter-Bookie Orderbook Concept

The IBO is a dark pool for agent-to-agent hedging:

Diagram Explanation: IBO Concept

The Problem: Agent A has 5,000 USDT liability on India winning. If India wins, Agent A loses big. Traditionally, Agent A would hedge on Betfair (expensive, 2-5% fees).

The IBO Solution: Agent B has capacity and wants exposure to India. Instead of going to external exchanges, they match internally through the IBO.

How It Works:

  1. Agent A posts SELL order: "Selling India @ 1.82 for 2,000 USDT"
  2. Agent B posts BUY order: "Buying India @ 1.82 for 2,000 USDT"
  3. Matching Engine detects compatible orders
  4. Funds from both agents locked in Solana escrow
  5. After match, winner gets payout from escrow

Why This Is Powerful:

  • Lower fees: 0.1% vs 2-5% on Betfair
  • Instant matching: No waiting for external liquidity
  • Privacy: Dark pool—orders not visible publicly
  • Trustless: Escrow ensures settlement

10.2 IBO System Architecture

Diagram Explanation: IBO System Architecture

Agent Interface (Top)

  • IBO API Gateway: REST endpoints for order submission, cancellation, position queries
  • WebSocket: Real-time order updates, fill notifications, position changes

IBO Core (Middle)

  • IBO Service: NestJS module that orchestrates all IBO operations
  • Matching Engine: High-performance Rust service for order matching
  • Order Book: Redis Streams for order storage and event sourcing
  • Quote Service: Returns current best bid/ask for quick quotes

Settlement Layer (Bottom-Left)

  • Hedge Waterfall: Routes orders through internal → IBO → external
  • Solana Escrow: Locks funds when orders match
  • Settlement Engine: Distributes funds when event settles

External Fallback (Bottom-Right)

  • If no internal match and no IBO liquidity, falls back to Betfair/Pinnacle
  • This is the "last resort" with higher fees

15. Matching Engine Design

11.1 Order Types

┌─────────────────────────────────────────────────────────────────────────────┐
│ IBO ORDER TYPES │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ LIMIT ORDER │
│ ──────────── │
│ "I want to BUY India Win @ 1.80 for 500 USDT" │
│ • Specifies exact price │
│ • Sits in order book until matched or cancelled │
│ • Maker order (provides liquidity) │
│ │
│ MARKET ORDER │
│ ──────────── │
│ "I want to BUY India Win NOW, best available price" │
│ • Executes immediately at best available price │
│ • May have slippage if order book is thin │
│ • Taker order (consumes liquidity) │
│ │
│ IMMEDIATE-OR-CANCEL (IOC) │
│ ───────────────────────── │
│ "I want to BUY India Win @ 1.80, but only if there's liquidity" │
│ • Executes what's available at specified price │
│ • Cancels remainder (no partial sitting) │
│ • Good for agents who don't want open orders │
│ │
│ FILL-OR-KILL (FOK) │
│ ───────────────── │
│ "I want to BUY 1K USDT of India Win @ 1.80, all or nothing" │
│ • Must execute entire amount or none │
│ • No partial fills │
│ • Used for large hedges that need certainty │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

11.2 Matching Algorithm

Diagram Explanation: Matching Algorithm

This flowchart shows how orders are processed by the matching engine:

Step 1: Validation Before any matching, validate:

  • Is the agent verified and authorized?
  • Do they have sufficient collateral locked?
  • Is the market still open for trading?

Step 2: Check Order Book Look for compatible orders on the opposite side:

  • BUY orders match with SELL orders at same or better price
  • Price-time priority: best price first, then earliest order

Step 3: Execute Match When orders match:

  • Lock funds from both parties in Solana escrow
  • Update agent positions
  • Send WebSocket notifications

Step 4: Handle Remainder If order only partially filled:

  • LIMIT: Add remainder to order book
  • MARKET/IOC/FOK: Cancel remainder (or entire order for FOK)

Performance Target:

  • Order validation to match execution: <1ms
  • Rust implementation for hot path
  • Redis for atomic order book updates

16. Hedge Waterfall System

12.1 Three-Tier Hedging Strategy

Diagram Explanation: Three-Tier Hedging

This diagram shows the hedge waterfall that minimizes hedging costs:

Tier 1: Internal Crossing (0% cost)

  • Look within agent's own book for opposite bets
  • Example: Player A bets 300 USDT on India, Player B bets 300 USDT on Australia
  • These naturally offset—no external hedge needed
  • Agent keeps full vig from both sides

Tier 2: IBO Dark Pool (0.1% cost)

  • Post remaining exposure to the Inter-Bookie Orderbook
  • Other agents with appetite take the other side
  • 0.1% maker-taker fee (vs 2-5% on exchanges)
  • 5-second timeout before falling through

Tier 3: External Exchanges (2-5% cost)

  • Last resort for unmatched exposure
  • Route to Betfair, Pinnacle, or other APIs
  • Higher fees but guaranteed liquidity
  • Only for time-sensitive hedges

Cost Savings Example: Hedge 1,000 USDT with traditional approach: 30 USDT (3% on Betfair) Hedge 1,000 USDT with waterfall: 6.5 USDT (0% + 0.5 + 6) Savings: 23.5 USDT (78%)


12.2 Hedge Waterfall Flow

Diagram Explanation: Hedge Waterfall Flow

This sequence shows a complete hedge operation through all three tiers:

Phase 1: Assessment

  1. Agent views risk dashboard
  2. Sees 1,000 USDT liability on India winning
  3. Decides to hedge

Phase 2: Internal Crossing 4. Hedge Router checks for opposite bets 5. Finds 300 USDT in opposite positions 6. Marks as internally hedged (no cost)

Phase 3: IBO Submission 7. Submits remaining 700 USDT to IBO 8. Order sits in book with 5-second timeout 9. Gets partial fill of 500 USDT from another agent 10. Locks matched amount in Solana escrow

Phase 4: External Fallback 11. After timeout, routes remaining 200 USDT to Betfair 12. External order placed at market price

Phase 5: Confirmation 13. Agent sees complete breakdown 14. Total cost calculated and deducted


17. Settlement & Escrow

13.1 On-Chain Escrow Flow

Diagram Explanation: On-Chain Escrow Flow

This sequence shows trustless settlement for IBO matches:

Phase 1: Order Match

  1. Matching engine pairs Agent A and Agent B
  2. Solana program creates escrow PDA (Program Derived Address)

Phase 2: Funding 3. Both agents approve USDC transfer 4. Funds locked in escrow—neither can withdraw 5. Escrow confirmed funded

Phase 3: Resolution 6. Match ends, sports oracle reports outcome 7. Solana program calculates payouts

Phase 4: Distribution 8. Winner receives funds (minus platform fee) 9. Platform treasury receives 2.5% 10. Escrow PDA closed (reclaim rent)

Why Solana?

  • Speed: ~400ms finality
  • Cost: ~$0.00025 per transaction
  • Programmable: Complex escrow logic in Anchor
  • Verifiable: Anyone can audit escrow state

13.2 Escrow States

Diagram Explanation: Escrow States

StateDescriptionDuration
CREATEDMatch found, PDA createdSeconds
FUNDINGWaiting for both depositsUp to 5 min
FUNDEDBoth depositedSeconds
LOCKEDMatch in progressMatch duration
RESOLVINGMatch ended, calculatingSeconds
SETTLEDPayouts distributedFinal
EXPIREDFunding timeoutRefund
DISPUTEDChallenge raised24-48 hours
JURYJury voting24 hours

18. Core Platform Modules

14.1 Module Architecture (Built Fresh)

bOS v3.0 is built from scratch with a Fantasy-First architecture. All modules are designed for prepaid USDT operations:

Diagram Explanation: Module Architecture

Primary Layer (Fantasy - Blue) Built first, this is the core of bOS v3.0:

  • Fantasy Module: Contest management, entries, settlements
  • Scoring Engine: Real-time points calculation
  • Pool Manager: Networked pools, cross-agent liquidity

Secondary Layer (IBO - Red) Built after Fantasy proves traction:

  • IBO Module: Order management, positions
  • Matching Engine: High-performance Rust matcher

Foundation Layer (Core - Gray) Supporting infrastructure for all operations:

  • Auth: Telegram initData, JWT sessions
  • Tenant: Multi-agent isolation
  • Player: Profiles, prepaid wallets
  • Wallet: USDT deposits/withdrawals (no credit!)
  • Risk: Exposure tracking
  • Notify: Push notifications
  • Crypto: TRON/Solana blockchain operations

14.2 Module Summary

ModulePurposeNotes
AuthTelegram initData validation, JWT sessionsSupports both player and agent auth
TenantMulti-tenant isolationEach agent is a tenant
PlayerPlayer profilesPrepaid model only
WalletUSDT balance managementDeposits, withdrawals, holds
RiskExposure trackingIBO position monitoring
NotifyPush notificationsScoring updates, win alerts
CryptoBlockchain operationsTRON/Solana USDT handling

Important Design Principle: No credit system. All players must deposit USDT before playing. This creates:

  • Lower risk for agents
  • Cleaner accounting
  • Faster settlements
  • No collection headaches

19. Database Schema

15.1 Fantasy Tables

All monetary values are in USDT (stored as DECIMAL with 6 decimal places for precision).

-- Fantasy Pool (network-wide)
CREATE TABLE fantasy_pools (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
sport VARCHAR(50) NOT NULL,
match_id UUID REFERENCES sports_matches(id),
entry_fee DECIMAL(18,2) NOT NULL,
max_entries INTEGER,
platform_fee_pct DECIMAL(5,2) DEFAULT 10.00,
agent_fee_pct DECIMAL(5,2) DEFAULT 3.00,
prize_structure JSONB NOT NULL,
status VARCHAR(20) DEFAULT 'DRAFT',
starts_at TIMESTAMP WITH TIME ZONE NOT NULL,
ends_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Fantasy Contest (agent-specific view of pool)
CREATE TABLE fantasy_contests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
pool_id UUID REFERENCES fantasy_pools(id),
agent_id UUID REFERENCES tenants(id),
name VARCHAR(255) NOT NULL,
max_entries INTEGER,
current_entries INTEGER DEFAULT 0,
status VARCHAR(20) DEFAULT 'OPEN',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Fantasy Entry (player's team)
CREATE TABLE fantasy_entries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
contest_id UUID REFERENCES fantasy_contests(id),
player_id UUID REFERENCES players(id),
agent_id UUID REFERENCES tenants(id),
salary_used DECIMAL(18,2) NOT NULL,
total_points INTEGER DEFAULT 0,
rank INTEGER,
payout DECIMAL(18,2) DEFAULT 0,
submitted_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Fantasy Picks (selected athletes)
CREATE TABLE fantasy_picks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
entry_id UUID REFERENCES fantasy_entries(id),
athlete_id UUID REFERENCES athletes(id),
position VARCHAR(20) NOT NULL,
is_captain BOOLEAN DEFAULT FALSE,
is_vice_captain BOOLEAN DEFAULT FALSE,
salary DECIMAL(18,2) NOT NULL,
points INTEGER DEFAULT 0
);

-- Athletes (real-world players)
CREATE TABLE athletes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
external_id VARCHAR(100) UNIQUE,
name VARCHAR(255) NOT NULL,
team VARCHAR(100),
sport VARCHAR(50) NOT NULL,
position VARCHAR(50),
salary DECIMAL(18,2),
stats JSONB DEFAULT '{}',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

15.2 IBO Tables

-- IBO Markets
CREATE TABLE ibo_markets (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID REFERENCES sports_events(id),
market_type VARCHAR(50) NOT NULL,
selection VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'OPEN',
outcome VARCHAR(50),
settled_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- IBO Orders
CREATE TABLE ibo_orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
market_id UUID REFERENCES ibo_markets(id),
agent_id UUID REFERENCES tenants(id),
side VARCHAR(4) NOT NULL CHECK (side IN ('BUY', 'SELL')),
order_type VARCHAR(20) NOT NULL,
price DECIMAL(10,4) NOT NULL,
amount DECIMAL(18,2) NOT NULL,
filled_amount DECIMAL(18,2) DEFAULT 0,
status VARCHAR(20) DEFAULT 'PENDING',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- IBO Matches (filled orders)
CREATE TABLE ibo_matches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
market_id UUID REFERENCES ibo_markets(id),
buy_order_id UUID REFERENCES ibo_orders(id),
sell_order_id UUID REFERENCES ibo_orders(id),
buyer_agent_id UUID REFERENCES tenants(id),
seller_agent_id UUID REFERENCES tenants(id),
price DECIMAL(10,4) NOT NULL,
amount DECIMAL(18,2) NOT NULL,
escrow_address VARCHAR(100),
escrow_status VARCHAR(20) DEFAULT 'PENDING',
matched_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- IBO Positions (agent exposure)
CREATE TABLE ibo_positions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
agent_id UUID REFERENCES tenants(id),
market_id UUID REFERENCES ibo_markets(id),
net_position DECIMAL(18,2) DEFAULT 0,
avg_price DECIMAL(10,4),
realized_pnl DECIMAL(18,2) DEFAULT 0,
unrealized_pnl DECIMAL(18,2) DEFAULT 0,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(agent_id, market_id)
);

20. API Specifications

16.1 Fantasy API Endpoints

┌─────────────────────────────────────────────────────────────────────────────┐
│ FANTASY API ENDPOINTS │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ POOLS │
│ ───── │
│ GET /api/fantasy/pools List available pools │
│ GET /api/fantasy/pools/:id Get pool details │
│ POST /api/fantasy/pools Create pool (admin) │
│ │
│ CONTESTS │
│ ──────── │
│ GET /api/fantasy/contests List agent's contests │
│ GET /api/fantasy/contests/:id Get contest details │
│ POST /api/fantasy/contests Create contest in pool │
│ │
│ ENTRIES │
│ ─────── │
│ GET /api/fantasy/entries List player's entries │
│ GET /api/fantasy/entries/:id Get entry details │
│ POST /api/fantasy/entries Submit entry (team) │
│ PUT /api/fantasy/entries/:id Edit entry (before lock) │
│ │
│ ATHLETES │
│ ──────── │
│ GET /api/fantasy/athletes List athletes for match │
│ GET /api/fantasy/athletes/:id Get athlete details │
│ │
│ LEADERBOARDS │
│ ──────────── │
│ GET /api/fantasy/contests/:id/leaderboard Get live leaderboard │
│ WS /ws/fantasy/contests/:id Subscribe to live updates │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

16.2 IBO API Endpoints

┌─────────────────────────────────────────────────────────────────────────────┐
│ IBO API ENDPOINTS │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ MARKETS │
│ ─────── │
│ GET /api/ibo/markets List available markets │
│ GET /api/ibo/markets/:id Get market details │
│ GET /api/ibo/markets/:id/orderbook Get order book depth │
│ │
│ ORDERS │
│ ────── │
│ GET /api/ibo/orders List agent's orders │
│ POST /api/ibo/orders Submit new order │
│ DELETE /api/ibo/orders/:id Cancel order │
│ │
│ POSITIONS │
│ ───────── │
│ GET /api/ibo/positions List agent's positions │
│ GET /api/ibo/positions/:marketId Get position for market │
│ │
│ QUOTES │
│ ────── │
│ GET /api/ibo/quote Get instant quote │
│ POST /api/ibo/hedge Execute hedge via waterfall │
│ │
│ WEBSOCKET │
│ ───────── │
│ WS /ws/ibo/markets/:id Subscribe to order book │
│ WS /ws/ibo/orders Subscribe to order updates │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

21. Implementation Roadmap

17.1 Phase Overview

Diagram Explanation: Implementation Roadmap

This Gantt chart shows the phased implementation of bOS v3.0:

Phase 1: Fantasy MVP (8 weeks)

  • Build core fantasy infrastructure
  • Launch with single-agent contests
  • Validate scoring engine with real matches

Phase 2: Networked Pools (7 weeks)

  • Enable cross-agent pools
  • Implement commission distribution
  • Update agent dashboard for pool management

Phase 3: IBO Core (11 weeks)

  • Build Rust matching engine
  • Deploy Solana escrow program
  • Launch IBO beta with select agents

Phase 4: Hedge Waterfall (6 weeks)

  • Integrate internal crossing
  • Connect IBO to hedge flow
  • Add external exchange fallbacks

Phase 5: Agent Wars (5 weeks)

  • Build B2B league system
  • Launch first Agent Wars season

Total Timeline: ~37 weeks (9 months)


17.2 Success Metrics

PhaseMetricTarget
Fantasy MVPDaily Active Users10,000
Fantasy MVPContests per day100
Networked PoolsCross-agent entries30% of total
Networked PoolsAgent participation50 agents
IBO CoreDaily trading volume100K USDT
IBO CoreActive trading agents20
Hedge WaterfallInternal crossing rate40%
Hedge WaterfallCost savings vs Betfair70%
Agent WarsParticipating agents30
Agent WarsSeason prize pool5K USDT

Appendix A: Glossary

TermDefinition
AgentA bookie/operator using bOS to manage their betting business
PlayerAn end-user who places bets or plays fantasy through an agent
TMATelegram Mini App—the player-facing mobile interface
IBOInter-Bookie Orderbook—the agent-to-agent trading platform
Networked PoolA fantasy pool where multiple agents' players compete together
Agent WarsB2B fantasy leagues where agents compete against each other
Hedge WaterfallThree-tier hedging: internal → IBO → external
EscrowSolana smart contract that locks funds until settlement
Scoring EngineReal-time system that converts sports events to fantasy points
Matching EngineHigh-performance order matcher for IBO

Appendix B: Technology Stack

LayerTechnologyPurpose
FrontendReact + TypeScriptTMA and Dashboard
APINestJS + TypeScriptREST and WebSocket APIs
Matching EngineRust + ActixHigh-performance order matching
DatabasePostgreSQLPrimary data store
CacheRedisLeaderboards, order books, sessions
BlockchainSolana + AnchorEscrow and settlement
QueueBullMQBackground job processing
RealtimeSocket.ioWebSocket connections
InfraDocker + KubernetesContainer orchestration

Appendix C: Security Considerations

C.1 Fantasy Security

RiskMitigation
Entry manipulationLock entries before match start
Score tamperingCryptographic audit trail
CollusionLimit entries per player per contest
Bot entriesRate limiting, CAPTCHA for high-value

C.2 IBO Security

RiskMitigation
Order spoofingCollateral requirements
Front-runningEncrypted order submission
Escrow theftMulti-sig, time-locks
Oracle manipulationMultiple oracle sources

End of bOS v3.0 Architecture Document