Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement Conditional Prediction Markets

A developer guide for creating prediction markets whose existence or settlement depends on the outcome of a parent market. Covers smart contract architecture, conditional logic, and collateral management.
Chainscore © 2026
introduction
DEVELOPER TUTORIAL

How to Implement Conditional Prediction Markets

A technical guide to building prediction markets where outcomes depend on the results of other events, using smart contracts and oracles.

A conditional prediction market allows users to bet on an event only if a separate, specified condition is first met. For example, a market could ask, "Will Team A win the championship IF they defeat Team B in the semifinals?" This creates a derivative market whose very existence is contingent. Implementing this requires a two-phase architecture: first resolving the condition market, then creating and resolving the contingent market. Smart contracts must manage escrow, conditional logic, and the lifecycle of both markets.

The core implementation involves three key smart contract components. First, a factory contract deploys the initial condition market using a standard prediction market template like Gnosis Conditional Tokens or a custom MarketFactory.sol. Second, a resolver contract checks the outcome via a decentralized oracle such as Chainlink or UMA. Upon condition resolution, it triggers the third component: the deployment of the contingent market. Funds for the second market are held in escrow within the first market's contract, only released if the condition is met.

Here is a simplified Solidity snippet showing the conditional logic in a resolver contract. It uses an oracle to check the condition and, if true, calls the factory to instantiate the next market.

solidity
function resolveCondition(uint256 conditionMarketId) external {
    require(msg.sender == oracle, "Unauthorized");
    bool conditionMet = checkOracleResult(conditionMarketId);
    
    if (conditionMet) {
        address contingentMarket = marketFactory.createContingentMarket(
            conditionMarketId,
            escrowedFunds[conditionMarketId]
        );
        emit ContingentMarketCreated(conditionMarket);
    } else {
        refundParticipants(conditionMarketId);
    }
}

This pattern ensures the second market is created atomically upon verification.

Key design considerations include gas efficiency for nested deployments, oracle security to prevent manipulation of the initial condition, and user experience for tracking conditional market states. Platforms like Polymarket handle this by creating a new, distinct market for the contingent question, linked by a shared conditionId. Developers must also implement a clear cancellation and refund mechanism for if the condition fails, returning collateral minus fees to the initial liquidity providers.

Use cases extend beyond sports to conditional governance (e.g., "Will proposal B pass IF proposal A passes?"), layered financial derivatives, and sequential R&D milestones. The major challenge is ensuring liquidity fragmentation between the conditional and contingent markets does not make trading impractical. Using a shared liquidity pool design or automated market maker (AMM) curves that account for conditional probability can mitigate this. Testing with frameworks like Foundry or Hardhat is crucial to simulate oracle responses and market state transitions.

To start building, fork the Gnosis Conditional Tokens Framework on GitHub, which provides primitives for splitting and merging outcome shares. Integrate with Chainlink Data Feeds or UMA's Optimistic Oracle for condition resolution. Remember that the legal status of such markets varies by jurisdiction. This implementation creates powerful, composable tools for forecasting in a trust-minimized way, moving beyond simple binary predictions to model complex, real-world dependencies.

prerequisites
FOUNDATIONAL KNOWLEDGE

Prerequisites

Before building a conditional prediction market, you need a solid grasp of core Web3 concepts and tools. This section outlines the essential knowledge and setup required.

To implement a conditional prediction market, you must first understand the underlying blockchain primitives. You should be proficient with smart contract development using Solidity (for EVM chains) or Rust (for Solana), as the market logic will be encoded on-chain. Familiarity with oracles like Chainlink or Pyth is critical, as they provide the external data (e.g., election results, sports scores) that resolve the market's condition. You'll also need to understand how decentralized finance (DeFi) mechanisms, such as automated market makers (AMMs) or bonding curves, facilitate trading and liquidity for the prediction shares.

Your development environment must be properly configured. This includes setting up a local blockchain for testing, such as Hardhat or Foundry for Ethereum, or Anchor for Solana. You will need Node.js and a package manager like npm or yarn installed. Essential tools include a code editor (VS Code is common), the MetaMask browser extension for interacting with your dApp, and testnet faucets to acquire dummy tokens. Having a basic front-end framework like React or Vue.js knowledge is also recommended for building the user interface to interact with your contracts.

A successful prediction market requires careful economic and game-theoretic design. You must decide on the market's condition (the specific future event), the resolution source (the trusted oracle or data feed), and the tokenomics of the shares (often a binary YES/NO token pair). Understanding concepts like the efficient market hypothesis, liquidity incentives, and potential attack vectors like oracle manipulation is necessary to create a robust system. Reviewing existing protocols like Polymarket or Augur can provide valuable design patterns and pitfalls to avoid.

core-architecture
CORE CONTRACT ARCHITECTURE

How to Implement Conditional Prediction Markets

Conditional prediction markets allow users to bet on outcomes that depend on specific, verifiable events. This guide details the core smart contract architecture required to build them.

A conditional prediction market is a binary option where the payout depends on whether a predefined condition is met by a specific deadline. The core architecture requires three essential components: a condition oracle, a market factory, and the market contract itself. The oracle (e.g., Chainlink, UMA, or a custom decentralized data feed) is responsible for resolving the condition's outcome. The factory pattern is used to deploy individual market contracts for each unique condition, ensuring modularity and gas efficiency.

The market contract's state is defined by key variables: conditionId, resolutionTime, oracleAddress, outcome, and balances for yes and no shares. Users interact by purchasing yes or no tokens, which represent their position. A common implementation uses an automated market maker (AMM) model, like a constant product formula (x * y = k), to provide liquidity and determine token prices. Alternatively, an order book model can be used for more complex markets, though it is less gas-efficient on-chain.

Here is a simplified Solidity structure for a market's core state:

solidity
contract ConditionalMarket {
    address public oracle;
    bytes32 public conditionId;
    uint256 public resolutionDeadline;
    bool public isResolved;
    bool public outcome;
    mapping(address => uint256) public yesTokenBalance;
    mapping(address => uint256) public noTokenBalance;
    // ...
}

The conditionId is a unique identifier, often a hash of the condition description and resolution parameters, which the oracle uses to fetch the correct result.

The resolution mechanism is the most critical security component. Upon the resolutionDeadline, an authorized function (e.g., resolveMarket) must be called, which queries the trusted oracle contract. The oracle should return a bool or uint256 result that is then used to set the market's outcome and isResolved flags. All trading must be halted after resolution. A robust implementation includes a dispute period or a fallback to a decentralized oracle network to handle oracle failure or manipulation attempts.

For user interaction, implement buyShares(outcomeType, amount) and sellShares(outcomeType, amount) functions. These functions mint/burn the respective outcome tokens and transfer the collateral (e.g., ETH or a stablecoin). After resolution, a redeemWinnings() function allows holders of the correct outcome token to burn them and claim their share of the total collateral pool. Always ensure the contract uses a pull-over-push pattern for withdrawals to prevent reentrancy attacks.

Key considerations for production include: gas optimization by using clones (ERC-1167) for market deployment, integrating a liquidity mining incentive structure, and implementing timelocks on resolution functions for oracle upgrades. Real-world examples include Polymarket, which uses UMA's Optimistic Oracle for resolution, and Augur v2, which uses a decentralized reporting system. Always audit the oracle integration, as it is the primary trust assumption and attack vector in the system.

key-concepts
CONDITIONAL PREDICTION MARKETS

Key Implementation Concepts

Essential technical components and design patterns for building on-chain conditional prediction markets.

01

Condition Resolution Oracles

The core of any conditional market is a trust-minimized oracle to resolve binary or scalar outcomes. Key approaches include:

  • Decentralized Data Feeds: Using oracles like Chainlink to pull in verified real-world data (e.g., sports scores, election results).
  • Committee-Based Resolution: A multisig or DAO of designated reporters votes to settle ambiguous outcomes.
  • Time-Based Lapse: Markets automatically resolve to a default state (e.g., 'NO') if no oracle report is provided within a timeout period. Implementation requires careful handling of dispute periods and bond requirements to prevent manipulation.
02

Conditional Token Standards

Use token standards to represent contingent claims, separating collateral from outcome tokens. The dominant pattern is the Conditional Tokens Framework (CTF).

  • Collateral Token (e.g., USDC) is locked in a ConditionalTokens smart contract.
  • Position Tokens are minted for each possible outcome (e.g., YES-ETH-3000 and NO-ETH-3000).
  • These are ERC-1155 tokens, allowing multiple outcome sets within a single contract. This structure enables efficient combinatorial markets where multiple conditions can be combined into a single position.
03

Automated Market Makers (AMMs) for Prediction

Specialized AMMs provide liquidity for binary outcome tokens. Unlike Uniswap's constant product formula, they use logarithmic market scoring rules (LMSR) or constant product AMMs with virtual balances.

  • LMSR AMMs (used by Polymarket) provide high liquidity efficiency for low-trading-volume markets by algorithmically setting prices based on a liquidity parameter.
  • CPMM with Virtual Balances (a design used by some forks) treats YES and NO tokens as a trading pair, using virtual reserves to ensure the sum of their prices equals the collateral value (e.g., 1 USDC).
04

Scalar & Categorical Markets

Markets can resolve to more than just yes/no. Implement scalar markets for numerical outcomes (e.g., 'ETH price on Jan 1') and categorical markets for multiple exclusive outcomes (e.g., 'Which candidate will win?').

  • Scalar: Uses a range of short tokens; the redemption value is proportional to how close the outcome is to the reported value.
  • Categorical: Mints a separate outcome token for each possible result. The winning token redeems for 1 unit of collateral; all others become worthless. Design requires defining clear resolution boundaries and a precise oracle reporting format.
05

Integration with DeFi Primitives

Conditional tokens can be composable building blocks. Key integrations include:

  • Use as Collateral: Outcome tokens representing future claims can be used as collateral in lending protocols like Aave (requires price oracles for the tokens).
  • Flash Loans for Arbitrage: Use flash loans to correct mispricings between conditional token AMMs and the expected probability.
  • Perpetual Rollovers: Design markets that automatically create a new conditional token for a future event upon resolution of the current one, creating a perpetual prediction instrument.
06

Dispute Resolution & Security

A robust system must handle oracle failures and malicious reports. Implement a layered security model:

  • Challenge Periods: A mandatory delay (e.g., 24-72 hours) between oracle resolution and final token redemption, allowing users to dispute.
  • Dispute Bonds: Challengers must post a bond, which is slashed if their challenge fails, preventing spam.
  • Fallback Oracles: A secondary oracle network (e.g., UMA's Optimistic Oracle) can be queried if the primary fails.
  • Pause Mechanisms: Admin functions to freeze markets in case of critical bugs or exploits.
step-by-step-implementation
TUTORIAL

How to Implement Conditional Prediction Markets

This guide walks through the practical steps of building a conditional prediction market, from defining the oracle and resolution logic to deploying the smart contract and creating the market UI.

A conditional prediction market settles based on a specific, verifiable outcome from an external data source, or oracle. The first implementation step is to define the market's condition and resolution source. For example, a condition could be "Will the ETH/USD price be above $4,000 at 12:00 UTC on January 1, 2025?" The resolution source would be a trusted price oracle like Chainlink's Data Feeds. You must select an oracle that provides the specific data (price, sports score, election result) your condition requires and ensure its update frequency and decentralization meet your security needs.

Next, you'll write the core settlement logic in a smart contract. Using Solidity and a framework like Foundry or Hardhat, you create a contract that inherits from a prediction market base template (like those from Polymarket or Gnosis Conditional Tokens). The key function is resolveMarket, which queries the pre-defined oracle. For a Chainlink price feed, this involves calling latestRoundData() and comparing the result to your condition's threshold. Based on the outcome, the contract should distribute the collateral pool to holders of the correct outcome token, burning the losing tokens. Always include a timelock or governance mechanism for manual intervention in case of oracle failure.

After the contract logic is tested, you must create and distribute the outcome tokens. Most systems use the ERC-1155 multi-token standard for efficiency, minting a unique token ID for each possible outcome (e.g., Token ID 1 for "Yes," Token ID 2 for "No"). Users buy these tokens by depositing collateral (like USDC or DAI) into a liquidity pool. Your contract mints an equal value of each outcome token upon deposit. Implement a bonding curve or an Automated Market Maker (AMM) like Uniswap V3 to facilitate trading and provide liquidity before resolution, allowing the token price to reflect the market's probability estimate.

The final step is building the user interface. A basic UI needs to connect a user's wallet (via libraries like wagmi or ethers.js), display active markets, and interact with your contract. Key frontend actions include: allowing users to buyShares by depositing collateral, displaying the current probability based on token prices, and enabling the redeemWinnings function after resolution. For a production app, you should integrate The Graph to index and query market creation, trades, and resolutions efficiently, avoiding slow direct blockchain queries. Always include clear disclaimers about the risks of oracle manipulation and market volatility.

IMPLEMENTATION ARCHITECTURE

Conditional Logic Patterns Comparison

Comparison of on-chain logic patterns for resolving prediction market outcomes based on external conditions.

Logic PatternOracle-Based ResolutionMulti-Sig CommitteeOptimistic Challenge

Finalization Time

~5 min - 24 hrs

1-7 days

7-14 days

Trust Assumption

Single Oracle

N-of-M Committee

Economic Bond

Max Gas Cost

$50-200

$200-1000

$1000-5000

Censorship Resistance

Dispute Resolution

Committee Vote

Challenge Period

Best For

High-Frequency Data

Governance Events

High-Value Contests

Example Protocol

Chainlink

UMA

Kleros

Implementation Complexity

Low

Medium

High

use-cases
CONDITIONAL PREDICTION MARKETS

Use Cases and Applications

Conditional prediction markets enable complex, event-driven betting on platforms like Polymarket and Gnosis Conditional Tokens. This section covers practical implementation patterns.

04

Composing Conditions with "AND" & "OR"

Complex logic is achieved by combining basic conditions. The CTF supports composition through collection IDs.

  • AND Condition (Conjunction): A market that pays out only if multiple sub-conditions are true (e.g., "Team A wins AND total points > 50"). Created by combining the outcome tokens of each sub-condition.
  • OR Condition (Disjunction): A market that pays out if any one of several sub-conditions is true. This is typically implemented by creating separate markets and aggregating liquidity.
  • Application: Useful for insurance products, milestone-based funding, and multi-factor event derivatives.
05

Oracle Design for Secure Resolution

Market integrity depends on a secure, decentralized oracle. Best practices include:

  • Reality.eth (UMA's Optimistic Oracle): Uses a dispute period where anyone can challenge an incorrect resolution, with bonds at stake. Common for subjective events.
  • Chainlink Data Feeds: For verifiable, objective data like sports scores or price feeds. Use Chainlink Functions for custom computation.
  • Fallback Mechanisms: Implement a final arbitrator (e.g., a DAO vote via Snapshot) for edge cases or oracle failure.
  • Resolution Time: Set a clear resolution date and grace period for oracle reporting in the smart contract.
collateral-flow-management
TUTORIAL

How to Implement Conditional Prediction Markets

A technical guide to building prediction markets with conditional outcomes, covering smart contract design for collateral management and payout resolution.

A conditional prediction market allows users to bet on the outcome of an event that depends on a prior condition being met. For example, a market on "Will Team A win the championship IF they defeat Team B in the semi-finals?" requires resolving two sequential events. Implementing this requires a smart contract architecture that locks collateral, tracks multiple binary conditions, and executes payouts based on a logical AND of those conditions. The core challenge is designing a state machine that can handle conditional resolution without relying on a centralized oracle for intermediate states.

The contract must manage collateral in a non-custodial pool. When a user creates a conditional market, they deposit an equal amount of collateral for both the 'Yes' and 'No' outcome tokens (e.g., using ERC-1155). A typical pattern is to escrow funds in a ConditionalMarket contract that inherits from a base PredictionMarket template. The collateral ratio is often 1:1, meaning minting 100 YES tokens and 100 NO tokens requires depositing 100 units of the base asset. This ensures the market is fully collateralized from inception, preventing insolvency.

Payout logic is determined by an outcome resolution function. For a condition C (Team A wins semi-finals) and a question Q (Team A wins championship), the final valid outcomes are: C_TRUE && Q_TRUE or C_TRUE && Q_FALSE. If C_FALSE, the market resolves as invalid, and collateral is returned to liquidity providers. This requires integrating with an oracle like Chainlink or UMA's Optimistic Oracle to resolve each condition sequentially. The contract state should progress through stages: Open, ConditionResolved, QuestionResolved, and PayoutsDistributed.

Here is a simplified Solidity snippet for a payout function after both conditions are resolved:

solidity
function resolveMarket(bool conditionMet, bool outcome) external onlyOracle {
    require(state == MarketState.ConditionResolved, "Condition not resolved");
    if (!conditionMet) {
        finalOutcome = Outcome.INVALID;
    } else {
        finalOutcome = outcome ? Outcome.YES : Outcome.NO;
    }
    state = MarketState.PayoutsDistributed;
    _distributePayouts();
}

The _distributePayouts function would then allow holders of the winning outcome token to redeem each token for 1 unit of collateral, while the losing tokens become worthless.

Key considerations for developers include oracle security (using decentralized oracles for each condition), liquidity provisioning (ensuring enough collateral for trading), and gas optimization for the resolution flow. Platforms like Polymarket and Augur v2 demonstrate real-world implementations, though their contract architectures are more complex. Always audit conditional logic thoroughly, as incorrect state transitions can permanently lock funds. For testing, use frameworks like Foundry to simulate the sequence of oracle reports and market resolutions.

CONDITIONAL PREDICTION MARKETS

Common Pitfalls and Security Considerations

Implementing conditional prediction markets introduces unique complexities around state resolution, oracle integration, and dispute handling. This guide addresses frequent developer challenges and security risks.

Resolution failures often stem from oracle misconfiguration or incorrect condition logic. The most common issues are:

  • Unreachable Finalization: The smart contract's resolveCondition function may require a specific data format or signature from the oracle (e.g., Chainlink, UMA, Witnet) that isn't provided.
  • Timestamp Mismatch: The market's resolution timestamp must align with the oracle's data availability window. If the contract checks for data before the oracle reports, it will revert.
  • Condition Granularity: Binary conditions like "Will ETH be > $3000 on Jan 1?" must be precisely defined. Using a floating-point comparison or an imprecise >= operator can cause unexpected failures.

Debugging Steps:

  1. Simulate the oracle response off-chain using tools like cast or a forked mainnet environment.
  2. Verify the condition ID or question ID matches between your market factory and the oracle contract.
  3. Ensure the resolution transaction includes sufficient gas for the oracle callback.
CONDITIONAL PREDICTION MARKETS

Frequently Asked Questions

Common questions and technical clarifications for developers building and interacting with conditional prediction markets.

A conditional prediction market is a decentralized exchange where users trade shares on the outcome of a future event, but only if a specific condition is first met. It uses a two-stage resolution process.

  1. Condition Check: An oracle (e.g., Chainlink, UMA) reports on the binary condition (e.g., "Did Team A win the semi-final?").
  2. Market Resolution: Only if the condition is TRUE does the market resolve based on the final outcome (e.g., "Will Team A win the championship?"). If the condition is FALSE, the market cancels, and liquidity is returned.

This structure is implemented via smart contracts that lock funds and logic until oracle data is provided, enabling complex, contingent betting scenarios.

conclusion
IMPLEMENTATION GUIDE

Conclusion and Next Steps

You now understand the core components of a conditional prediction market. This section outlines the final steps to deploy your application and explores advanced concepts for further development.

To deploy your conditional prediction market, you must first select a production-ready oracle and a suitable blockchain. For high-value markets, consider using a decentralized oracle network like Chainlink, which provides reliable data feeds and verifiable randomness for resolution. For the underlying smart contracts, you can fork and customize established frameworks like Polymarket's open-source contracts or Gnosis Conditional Tokens. Ensure your contracts undergo a thorough security audit by a reputable firm before mainnet deployment to protect user funds.

The frontend interface is critical for user adoption. Integrate a Web3 wallet library like wagmi or Web3Modal for seamless connection. Use a UI component library such as Chakra UI or Tailwind CSS to build a responsive trading interface that displays real-time market data, order books, and user positions. For scalability, consider implementing a layer-2 solution like Arbitrum or Optimism to reduce transaction fees and latency, which is essential for a smooth trading experience.

Beyond the basic implementation, you can explore advanced features to enhance your platform. Implement automated market makers (AMMs) for continuous liquidity, allowing users to trade against a pool rather than waiting for a counterparty. Integrate liquidity mining programs to incentivize participation. For complex, multi-condition markets, research futarchy governance models or combinatorial betting. Always monitor key metrics like total value locked (TVL), daily active users, and market resolution accuracy to iteratively improve your product.

How to Implement Conditional Prediction Markets | ChainScore Guides