A high-performance, decentralized prediction market platform built with Rust, featuring real-time order matching, blockchain integration, and event-driven architecture.
This project implements a microservices-based prediction market system with the following core components:
βββββββββββββββββββ
β Backend API β β REST API server (Axum)
β (backend) β - Market management
β β - Order placement & execution
β β - Authentication (Privy)
ββββββββββ¬βββββββββ
β
ββββββ΄βββββ¬βββββββββββββββ¬βββββββββββββββ
β β β β
βββββΌββββ ββββΌβββββββ ββββββΌββββββ ββββββΌβββββ
β DB β β Event β β Matching β β PM-CLI β
β β βListener β β Engine β β β
βββββββββ βββββββββββ ββββββββββββ βββββββββββ
β β β
β β β
βββββββββββ΄βββββββββββββββ
β
ββββββΌββββββ
β Solana β
β Blockchainβ
ββββββββββββ
The main REST API server that handles:
- Market Operations: Listing, fetching, and querying prediction markets
- Order Management: Placing, canceling, splitting, and merging orders
- Orderbook: Real-time orderbook snapshots for each market
- Authentication: Privy-based JWT authentication middleware
- Blockchain Integration: Solana client for on-chain transaction execution
- Matching Engine Integration: Communicates with the matching engine for order processing
Key Technologies:
- Axum web framework
- Privy for authentication
- Anchor client for Solana program interaction
- PostgreSQL via SQLx
A shared database library providing:
- Database Models: Market entities and data structures
- Query Functions: Type-safe database operations using SQLx
- Migrations: Schema management with SQLx migrations
- Connection Pooling: Efficient database connection management
Schema Highlights:
- Markets table with on-chain address mapping
- Support for Yes/No binary markets
- Market resolution tracking
- Indexed queries for performance
A real-time blockchain event monitoring service that:
- Subscribes to Solana program logs via WebSocket
- Parses Events: Decodes
MarketInitializedandMarketSettledevents - Syncs State: Automatically creates markets in the database when initialized on-chain
- Updates Resolution: Marks markets as resolved when settled on-chain
Event Types:
MarketInitialized: New market creation eventsMarketSettled: Market resolution events
An in-memory order matching engine that:
- Orderbook Management: Maintains separate orderbooks for Yes/No shares
- Order Matching: Implements price-time priority matching algorithm
- Trade Execution: Generates trade fills for matched orders
- Snapshot API: Provides real-time market snapshots
Features:
- Dual orderbook system (Yes/No shares)
- Bid/Ask order matching
- Partial fill support
- Real-time orderbook snapshots
A command-line interface for market administration:
- Create Markets: Initialize new prediction markets on-chain
- Resolve Markets: Settle markets with outcomes
- List Markets: Query on-chain market data
Use Cases:
- Market creation by administrators
- Market resolution after events occur
- On-chain data inspection
- Rust (latest stable version)
- PostgreSQL 16+ (or use Docker Compose)
- Solana CLI (for keypair management)
- Anchor (for Solana program interaction)
-
Clone the repository
git clone <repository-url> cd Prediction-Market
-
Start PostgreSQL database
docker-compose up -d
This starts a PostgreSQL instance on
localhost:5432with:- User:
admin - Password:
password - Database:
postgres_db
- User:
-
Configure environment variables
Copy the
.env.examplefiles to.envin each workspace member:cp backend/.env.example backend/.env cp event-listener/.env.example event-listener/.env
See the
.env.examplefiles for required configuration. -
Run database migrations
cd db cargo runMigrations run automatically when the database pool is initialized.
-
Start the services
Backend API:
cd backend cargo runServer starts on
http://0.0.0.0:8080(configurable viaSERVER_ADDR)Event Listener:
cd event-listener cargo runRuns continuously, listening for on-chain events.
GET /markets- List all marketsGET /markets/{address}- Get market details by on-chain address
POST /orders/open- Place a new orderPOST /orders/close- Cancel an existing orderGET /orderbook/{market_id}- Get orderbook snapshotPOST /orders/split- Split an order into smaller ordersPOST /orders/merge- Merge multiple orders
Authentication: Include privy-id-token header with Privy JWT token.
-
Admin creates market via
pm-cli:cargo run --bin pm-cli -- create-market \ --market-id 1 \ --metadata "Will Bitcoin reach $100k by 2025?" \ --end-time 1735689600 -
On-chain event emitted β
MarketInitializedevent -
Event listener detects event via WebSocket subscription
-
Database updated β Market record created with on-chain address
-
API serves market β Available via
GET /markets
-
User places order β
POST /orders/openwith order details -
Backend validates β Authentication, market existence, order parameters
-
Matching engine processes β Order matched against existing orders
-
Trades generated β Partial or full fills returned
-
On-chain execution β Matched orders executed via Solana transactions
-
Orderbook updated β Real-time snapshot available
-
Admin resolves market via
pm-cli:cargo run --bin pm-cli -- resolve-market \ --market-id 1 \ --outcome "Yes" -
On-chain event emitted β
MarketSettledevent -
Event listener updates β Market marked as resolved in database
-
API reflects status β Market shows resolved state
Each component is a separate Rust crate with clear boundaries:
- Loose coupling via shared database and message passing
- Independent deployment of services
- Scalability through horizontal scaling
- Blockchain events trigger database updates
- Order matching uses async message passing
- Real-time updates via WebSocket subscriptions
- SQLx compile-time queries prevent SQL injection
- Strong typing throughout the Rust codebase
- Anchor types for Solana program interaction
- Migrations version control schema changes
- Type-safe queries with SQLx
- Connection pooling for performance
This is a Cargo workspace with shared dependencies:
[workspace]
members = [
"db",
"backend",
"event-listener",
"matching-engine",
"pm-cli",
]# Run all tests
cargo test --workspace
# Test specific component
cargo test -p backend
cargo test -p matching-engineMigrations are in db/migrations/ and run automatically on pool initialization.
To create a new migration:
cd db
sqlx migrate add <migration_name>- Authentication: Privy JWT tokens validated on protected routes
- Keypair Management: Admin keypairs stored securely, never committed
- SQL Injection: Prevented via SQLx compile-time query checking
- CORS: Configured for specific origins
- Environment Variables: Sensitive data in
.envfiles (gitignored)
- Axum: Modern async web framework
- SQLx: Type-safe SQL with compile-time verification
- Anchor: Solana program framework
- Tokio: Async runtime
- Privy: Authentication service
- Solana SDK: Blockchain interaction
- SPL Token: Token program integration
- Anchor Client: Program client library
This project is licensed under the MIT License - see the LICENSE file for details.
Built with Rust π¦ for performance, reliability, and type safety.