All projects

PraesagiumChain

Bet on the future. See the confidence band. Get paid when you're right.

Prediction Markets CRE & AI Privacy Risk & Compliance Tenderly Thirdweb

What it is

What it is
PraesagiumChain is a decentralized prediction market platform where users create and trade on binary (Yes/No) markets about real-world events — crypto price levels, weather, sports, news sentiment, etc. Users stake ETH on outcomes and get paid automatically when markets resolve in their favor. It is built for the Chainlink Prediction Markets Hackathon and uses Chainlink CRE (Chainlink Runtime Environment) for trustless resolution.
At its core is the PHPE (Praesagium Hybrid Predictive Engine), a Rust ML pipeline that combines time-series forecasts, AI sentiment (Groq, Hugging Face), and live price data (Binance, Chainlink, etc.) into a single probability estimate plus an uncertainty band (e.g. “65% ±12%”). That transparency is a main differentiator: users see both the probability and how confident the model is.
The stack includes Solidity smart contracts (OpenZeppelin + Chainlink), a Rust/Axum backend with PostgreSQL, a Next.js 14 frontend with wagmi v2, and TypeScript CRE workflows that trigger resolution and feed outcomes on-chain.

How it works

  1. Creating a market
    A user creates a market via the frontend: question, close time, and resolve time. A transaction deploys it on the PredictionMarket contract (Sepolia testnet). The backend indexes the event and stores it in the database.
  2. Betting phase
    Users place Yes/No bets with ETH before the close time. Odds are computed from the current pool; the UI shows total pool, odds, and PHPE uncertainty when available.
  3. Resolution via Chainlink CRE
    When the resolve time is reached, a CRE workflow runs on a schedule. It:
  • Calls the backend /api/ai/sentiment (or other endpoints: price-above, weather, sports)
  • Gets a probability or outcome (0 or 1)
  • Sends it to the OracleConsumer contract
  • The OracleConsumer forwards to CREWorkflow, which calls PredictionMarket.resolveMarket()
  1. Payouts
    After resolution, winners call claimPayout() to withdraw their share. All resolution logic is driven by CRE and on-chain data, not a central operator.
    Data sources: PHPE time series (≈35%), AI sentiment (≈40%), live prices (≈25%) are fused into a hybrid probability. Resolution can use sentiment, Chainlink feeds, Binance, Open-Meteo, API-Football, etc., all orchestrated through CRE. There is also support for private (commit-reveal) markets via Confidential Compute.

What problem it solves
Lack of trust and transparency in prediction markets: Many platforms rely on centralized resolvers or opaque data. PraesagiumChain uses Chainlink CRE so resolution is automated, verifiable, and not controlled by a single party.
Hidden uncertainty: Traditional markets show only point probabilities. PHPE exposes uncertainty (e.g. “65% ±12%”), so users can judge whether the odds are reliable before betting.
Limited data sources: Resolution is often tied to one API or oracle. PraesagiumChain integrates multiple sources (AI, price feeds, weather, sports) in one CRE layer, making markets more robust and flexible.
Trust in creator quality: An on-chain reputation system scores market creators by accuracy, letting users favor better-curated markets.
Privacy for traders: Private markets use commit-reveal and Confidential Compute so positions stay hidden until reveal, reducing front-running and information leakage.

How it Works

How It Was Built (Development Process)
PraesagiumChain was developed layer by layer, with each part built on top of the previous one.
The first step was the smart contract layer. The core Solidity contracts were designed and implemented: PredictionMarket.sol for binary markets, AMM-style pools, bets, resolution, and payouts; OracleConsumer.sol to receive Chainlink CRE callbacks; and CREWorkflow.sol to bridge oracle results to resolveMarket(). OpenZeppelin was used for ownership, reentrancy guards, and access control, and Chainlink for oracle integration. Hardhat was chosen for compilation, testing, and deployment on local and testnet environments. A separate PrivatePredictionMarket.sol was added later for commit-reveal markets with Confidential Compute, and ReputationSystem.sol for on-chain creator reputation.
The backend was built next in Rust using Axum and Tokio. PostgreSQL was selected for persistence, with SQLx for typed queries and migrations. An event indexer based on ethers-rs subscribes to the PredictionMarket contract and writes events into the database so the API can serve market data without querying the chain every time. Rate limiting (tower_governor) and a TTL cache for predictions were added to protect against abuse and reduce load. The AI service was designed to support multiple providers (Groq, Hugging Face, or a mock) so the system could work without API keys during development.

The PHPE (Praesagium Hybrid Predictive Engine) was implemented as a separate Rust crate. It handles normalization, causal DAG inference, temporal encoding, and a Bayesian head with MC dropout to produce probability and uncertainty. Isotonic calibration was added to output calibrated uncertainty bands (e.g. 65% ±12%). PHPE is invoked by the backend’s /api/predict and /api/predict/hybrid endpoints.

Chainlink CRE integration was added after the backend and contracts were stable. Two TypeScript workflows were built: praesagium-resolver for standard markets and praesagium-resolver-confidential for private markets. They use CronCapability for scheduled execution, HTTPClient to call the backend, and consensusIdenticalAggregation to agree on the outcome before sending it to the oracle. The CRE SDK (@chainlink/cre-sdk) was used for workflow lifecycle, simulation, and on-chain broadcast.

The frontend was built with Next.js 14 (App Router) and TypeScript. Wagmi v2 and viem were chosen for wallet and contract interaction, React Query for API data, and Tailwind plus shadcn/ui for the UI. Lightweight-charts (TradingView) replaced an earlier charting library for better performance and UX. The market detail page was modeled after CoinGecko, with a full-width chart and sticky sidebar for the bet form and countdown. External data sources were added gradually: Binance, Chainlink, CryptoCompare, Kraken, CoinGecko, Finnhub, ExchangeRate API for prices; Groq and Hugging Face for sentiment and LLM; Open-Meteo for weather; API-Football for sports. All are accessed from the backend, which exposes unified endpoints. The CRE workflows call these backend endpoints, so the CRE layer stays simple and verifiable. Deployment and operations were set up last. A single .env at the repo root configures backend and frontend. Docker Compose was added for PostgreSQL, Redis, and ClickHouse. CI in GitHub Actions runs Hardhat contract tests, Rust backend tests, npm audit, and cargo audit on each push to main. Deployment scripts deploy contracts to Sepolia and Polygon Amoy, and verification scripts run against Etherscan and Polygonscan. The structure was kept modular so each layer can evolve independently.

How It Is Built (Current Architecture)
Smart Contract Layer
The system is anchored in Solidity contracts deployed on Sepolia (and Polygon Amoy for testing). PredictionMarket.sol is the main contract. It stores markets (question, close time, resolve time, pool sizes, outcome), processes bets via AMM-style pricing, locks markets at close time, and resolves them when the oracle provides an outcome. Payouts use a checks-effects-interactions pattern and ReentrancyGuard to avoid reentrancy. OracleConsumer.sol has an oracleCallback function restricted to an authorized Chainlink CRE executor. It receives the outcome (0 or 1), validates the market, and forwards to CREWorkflow. CREWorkflow.sol exposes resolveFromOracle, callable only by OracleConsumer, which calls PredictionMarket.resolveMarket() and updates the market state. PrivatePredictionMarket.sol implements commit-reveal: users submit hashed positions during the betting phase and reveal them after resolution; the CRE workflow resolves in Confidential Compute. ReputationSystem.sol tracks market creator accuracy and exposes an on-chain reputation score. All contracts use OpenZeppelin and Chainlink primitives. Hardhat manages compilation, deployment, and verification.
Backend (Rust / Axum)
The backend is a REST API served on port 4000 by Axum on Tokio. PostgreSQL stores markets, predictions, and metadata; SQLx runs typed queries and migrations on startup. The event indexer (ethers-rs) subscribes to the PredictionMarket contract, listens for MarketCreated, MarketResolved, and BetPlaced, and writes them to the database. The API exposes /api/markets (list, stats, create, status), /api/ai/sentiment (sentiment → probability), /api/predict (PHPE time-series), /api/predict/hybrid (PHPE + sentiment + prices), and resolution endpoints for price-above, weather, and sports. Requests pass through rate limiting and a TTL cache for predictions. CORS, error handling, and structured logging are configured globally. Config comes from environment variables loaded at startup.
PHPE Engine
PHPE is a Rust crate inside the backend. It takes time-series data, normalizes it, infers causal structure, applies temporal encoding (sliding window, regime detection), and feeds it to a Bayesian head with MC dropout. Monte Carlo dropout yields uncertainty estimates; isotonic calibration produces calibrated probabilities and uncertainty bands (e.g. 65% ±12%). The hybrid predictor combines PHPE (~35%), AI sentiment (~40%), and live prices (~25%) into a single calibrated probability. All predictions are cached with a configurable TTL to limit recomputation.
Chainlink CRE Workflows
Resolution is driven by Chainlink CRE. The praesagium-resolver workflow runs on a cron schedule at resolution time. It uses HTTPClient to call the backend /api/ai/sentiment (or other endpoints such as /api/price/above, /api/weather/rained, /api/sports/winner), receives a probability or outcome, applies consensusIdenticalAggregation across nodes, and sends the final outcome to OracleConsumer via the CRE oracle gateway. The contract validates the caller and updates the market. praesagium-resolver-confidential mirrors this flow for private markets, running in a TEE (Confidential Compute). Both workflows use the CRE SDK, are defined in TypeScript, and can be simulated locally or broadcast on-chain.
Frontend (Next.js)
The frontend is a Next.js 14 App Router application. It uses wagmi v2 and viem for wallet connection (injected provider, Sepolia), contract calls (createMarket, placeBet, claimPayout), and network switching. React Query fetches market list, stats, and detail from the backend API. The dashboard lists markets with YES/NO stakes and filters. The market detail page shows a full-width OHLCV chart (lightweight-charts), a sticky sidebar with the bet form and countdown, and creator reputation. The create-market flow is a three-step wizard: question, timeline, and on-chain deployment. The signals page visualizes PHPE and hybrid predictions. Tailwind and shadcn/ui provide the design system; next-themes handles dark/light mode. API calls are proxied to the backend through Next.js rewrites so the frontend shares the same origin.
External Data Sources
The backend aggregates multiple external sources. AI/Sentiment: Groq (llama-3.3-70b) or Hugging Face (e.g. twitter-roberta-base-sentiment). Prices: Binance (24h ticker), Chainlink (ETH/USD), CryptoCompare, Kraken, CoinGecko, Finnhub, ExchangeRate API. Weather: Open-Meteo for precipitation. Sports: API-Football for match results. Each source has a dedicated service in the backend; the sources module exposes a unified interface. The CRE workflows call backend endpoints (e.g. /api/ai/sentiment, /api/price/above) and never talk to third-party APIs directly, which keeps CRE logic simple and auditable.
Infrastructure and Deployment
A single .env at the repo root configures backend and frontend: database, API keys, RPC URLs, contract addresses. Docker Compose runs PostgreSQL (port 5433), Redis (6380), and ClickHouse (8123) for local development. Migrations run on backend startup. CI runs Hardhat tests, Rust tests, npm audit, and cargo audit. Deployment uses Hardhat scripts; contracts are verified on Etherscan and Polygonscan. The backend runs as a standalone binary (cargo run --release or via npm run backend). The frontend is built with npm run build in the frontend directory and served with npm run start or npm run dev for development. CRE workflows are simulated with the CRE CLI or run on the Chainlink network when deployed to production.

Links

Created by

  • Jhuomar Boskoll Quintero
  • Querube Ariza