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

Setting Up a Token-Bonded Prediction Market from Scratch

This guide provides a technical walkthrough for developers to build a prediction market where market creation requires staking a native token, covering bonding curves, slashing, and contract implementation.
Chainscore © 2026
introduction
TUTORIAL

Setting Up a Token-Bonded Prediction Market from Scratch

A technical guide to building a decentralized prediction market where participation requires staking a native token, aligning incentives and governance.

A token-bonded prediction market is a decentralized application where users must stake the platform's native token to create markets, place bets, or resolve outcomes. This model, popularized by platforms like Augur and Polymarket, creates a direct alignment between the accuracy of information and the token's economic value. The bonding requirement mitigates spam, funds a decentralized oracle for resolution, and grants governance rights to active participants. This tutorial will guide you through the core components: a prediction market smart contract, a bonding token (ERC-20), and an oracle resolution mechanism.

Start by designing your MarketFactory.sol contract. This factory will deploy individual PredictionMarket contracts for each event. Each market needs parameters: description (the question), outcomes (e.g., ["Yes", "No"]), resolutionTime (a UNIX timestamp), and a bondAmount (in your native token). The factory should use the Clone pattern (via libraries like OpenZeppelin's Clones) for gas-efficient deployment. Upon creation, the market creator must lock the bondAmount, which is slashed if they act maliciously (e.g., trying to resolve incorrectly).

The core PredictionMarket contract handles trading. Implement a continuous double auction or use an automated market maker (AMM) model like a constant product formula (x * y = k). For each outcome, create a separate ERC-1155 or ERC-20 token representing a share. Users buy Yes shares by bonding tokens into the market's liquidity pool. The price of a share should reflect the market's probability estimate. Use a bonding curve where the cost to buy the last share approaches 1.0 (or 100% of the bond pool) for the winning outcome.

Resolution is the most critical component. You need a decentralized oracle to report the real-world outcome. A common pattern is a dispute resolution system: after resolutionTime, an initial reporter (e.g., the creator) can submit an outcome. This starts a challenge period (e.g., 7 days) where any token-bonded participant can dispute by staking a larger bond. Unresolved disputes escalate to a decentralized court (like Kleros or a custom DAO). Code this as a state machine: Open -> Reporting -> Challenged -> Resolved. Only in the final Resolved state can users redeem winning shares for their portion of the bonded tokens.

Integrate your bonding token (e.g., BOND) using a standard ERC-20 contract with a permit function for gasless approvals. The token should be required for key actions: createMarket(bondAmount), disputeOutcome(bondAmount), and voteInGovernance. Consider implementing a staking mechanism where users lock tokens to earn fees from market activity. The contract should collect small fee percentages on trades and resolution, distributing them to stakers. This creates a sustainable economy where accurate prediction and honest reporting are financially rewarded.

For a complete frontend, use a framework like Next.js with wagmi and viem. Connect to the MarketFactory to fetch deployed markets. For each market, display the description, current probability (derived from share prices), bondAmount, and time until resolution. Use The Graph to index on-chain market creation and trade events for efficient querying. Always audit your contracts thoroughly, as prediction markets handle significant value. Consider using conditional tokens (like those in Gnosis Conditional Tokens Framework) as a more gas-efficient alternative to custom ERC-1155 implementations for representing shares.

prerequisites
FOUNDATION

Prerequisites and Setup

Before deploying a token-bonded prediction market, you need a secure development environment and a clear understanding of the core components.

A token-bonded prediction market is a decentralized application where participants stake a platform's native token to create and resolve prediction questions. This setup requires a robust technical foundation. You will need a working knowledge of Solidity for smart contracts, JavaScript/TypeScript for front-end interaction, and familiarity with Ethereum development tools like Hardhat or Foundry. Ensure your system has Node.js (v18 or later) and npm or yarn installed. A code editor like VS Code with Solidity extensions is recommended for efficient development.

The core architecture relies on several key smart contracts: a factory contract to deploy new markets, a market contract to manage individual predictions and bonding curves, and an ERC-20 token contract for the bonding currency. You must decide on the tokenomics upfront—will you deploy a new token or use an existing one like DAI or USDC for bonding? For testing, configure a local blockchain using Hardhat Network or Ganache, and have a MetaMask wallet ready with test ETH from a faucet. Always use a .env file to manage private keys and API endpoints securely.

Install the essential development packages. Initialize a new project with npm init -y and install Hardhat: npm install --save-dev hardhat. Then, install OpenZeppelin contracts for secure token and access control implementations: npm install @openzeppelin/contracts. For front-end integration, you'll likely need ethers.js v6 or viem and wagmi. Run npx hardhat to generate a sample project structure, which creates directories for contracts, scripts, and tests. This setup provides the scaffold for writing, compiling, and testing your prediction market logic.

Understanding the bonding mechanism is critical. In a token-bonded market, creating a prediction requires locking tokens into a bonding curve contract (often a Constant Product Market Maker model). This creates liquidity and aligns creator incentives with market accuracy. The cost to buy shares ("Yes" or "No") changes based on the pool's reserves. You should review existing implementations like Polymarket's architecture or the UMA Optimistic Oracle for dispute resolution patterns. Start by forking a simple bonding curve contract from a repository like Bancor or Uniswap v2 to understand the core swap and addLiquidity functions.

Finally, plan your deployment strategy. Write and test your contracts extensively on a local fork of Ethereum Mainnet or Polygon using Alchemy or Infura node providers. Use hardhat verify to publish your contract source code on block explorers like Etherscan. For a production launch, consider using a proxy upgrade pattern (e.g., TransparentUpgradeableProxy) from OpenZeppelin to allow for future fixes. Ensure you have a clear front-end plan to interact with your contracts, using a framework like Next.js and a library like RainbowKit for wallet connection.

key-concepts-text
TOKEN-BONDED PREDICTION MARKETS

Core Concepts: Bonding, Slashing, and Resolution

This guide explains the foundational mechanisms of token-bonded prediction markets, focusing on how bonding, slashing, and resolution enforce market integrity and align participant incentives.

A token-bonded prediction market requires participants to bond (or stake) cryptocurrency as collateral to interact with the market. This bonding serves multiple purposes: it acts as a financial commitment to honest participation, provides the liquidity for payouts, and creates a direct financial stake in the market's outcome. For example, when creating a new market on a platform like Polymarket, the creator must bond funds to cover potential payouts and signal the market's legitimacy. Similarly, traders must bond funds to place trades, which are then locked until resolution. This mechanism filters out spam and ensures participants have 'skin in the game,' aligning their financial interests with truthful market behavior.

Slashing is the penalty mechanism that enforces the rules of the market. If a participant acts maliciously or against the protocol's governance rules, a portion or all of their bonded tokens can be slashed (confiscated). Common slashing conditions include: creating a market with an ambiguous or unresolvable question, attempting to manipulate the resolution process, or failing to report a correct outcome as a designated oracle or resolver. The slashed funds are typically burned or redistributed to other honest participants, creating a direct cost for bad actors. This disincentive is crucial for maintaining the system's trustlessness and ensuring that reported outcomes reflect real-world events.

Resolution is the process of determining the outcome of a market event and distributing the bonded collateral accordingly. Markets are typically resolved by a trusted oracle (like Chainlink), a decentralized oracle network (DON), a designated committee, or via futarchy-based governance. Once the real-world event occurs, the resolver submits the outcome to the smart contract. The contract then automatically settles all positions: winners receive their original bond plus a proportional share of the losers' bonds (minus fees), while losers have their bonded tokens redistributed. A well-designed resolution system is paramount, as it is the single point of truth that determines profit and loss, making oracle security and decentralization critical concerns.

Implementing these concepts from scratch involves writing several core smart contract functions. A basic createMarket function would require the creator to bond tokens via ERC20.transferFrom and define the resolution criteria. A placeTrade function would escrow a user's bond and mint a conditional token representing their position. The critical resolveMarket function, which could be callable only by a pre-defined oracle address, would determine the winning outcome and trigger a payout function using a batch transfer to efficiently distribute the pooled bond to the winning side, often employing a constant product or proportional calculation for fairness.

When designing your system, key parameters must be carefully calibrated: the bond size for market creation (to prevent spam), the slashing percentage for violations (to deter malice without being overly punitive), and the time delay between market resolution and fund withdrawal (to allow for dispute challenges). Platforms like Augur and Polymarket have iterated on these parameters through live deployment. Always subject resolution logic to rigorous testing and consider implementing a dispute period where bonded participants can challenge an outcome before final settlement, adding a layer of decentralized verification.

Understanding bonding, slashing, and resolution is essential for building robust prediction markets. These mechanisms collectively replace a central authority with cryptographic and economic guarantees. By requiring financial commitment (bonding), punishing dishonesty (slashing), and automating settlement based on verifiable truth (resolution), token-bonded markets can create credible, decentralized forums for forecasting real-world events, from elections to financial indices, with integrity enforced by code rather than corporations.

contract-architecture
TOKEN-BONDED PREDICTION MARKETS

Smart Contract Architecture Overview

This guide outlines the core components and development steps for building a prediction market where participation is secured by staking a native token.

01

Core Contract Architecture

A token-bonded prediction market is built on three primary smart contracts:

  • Market Factory: Deploys and manages individual market instances.
  • Market Contract: Contains the core logic for creating questions, placing bets, resolving outcomes, and distributing rewards.
  • Bonding Token (ERC-20): A staking token required to participate; its economic design (e.g., bonding curves, slashing) secures the system.

Key design choices include using a pull-payment pattern for security and an oracle abstraction layer for resolution.

02

Implementing the Bonding Mechanism

The bonding token is the system's security backbone. Developers must decide on its economic model:

  • Staking for Access: Users lock tokens to create markets or place predictions.
  • Slashing Conditions: Define rules for penalizing bad actors (e.g., reporting false information).
  • Reward Distribution: Allocate fees and rewards to stakers, often using a continuous token model or fixed rewards.

Integrate an ERC-20 with custom minting/burning logic controlled by the market contract. Consider using OpenZeppelin's ERC20Snapshot for fair reward distribution.

05

Security & Testing Checklist

Critical audits and practices before mainnet deployment:

  • Reentrancy Guards: Protect all state-changing functions, especially payouts.
  • Access Control: Use OpenZeppelin's Ownable or AccessControl for admin functions.
  • Integer Overflow/Underflow: Use Solidity 0.8.x or SafeMath libraries.
  • Formal Verification: Tools like Certora or Solidity SMTChecker can prove contract properties.
  • Fork Testing: Use Foundry or Hardhat to simulate mainnet forks and test oracle interactions under real conditions.
06

Deployment & Gas Optimization

Strategies for efficient and cost-effective deployment:

  • Contract Size: Use libraries (via delegatecall) or the EIP-2535 Diamond Standard to bypass the 24KB contract size limit.
  • Gas-Efficient Patterns: Use immutable and constant variables, pack structs, and prefer external calls.
  • Deployment Scripts: Use Hardhat or Foundry scripts with deterministic addresses via CREATE2.
  • Initialization: Separate construction from initialization to allow for proxy upgrades using Transparent or UUPS proxy patterns.
implementation-bonding-curve
CORE MECHANISM

Step 1: Implementing the Bonding Curve

The bonding curve smart contract is the mathematical engine that determines token price and supply. This step builds the core logic for minting and burning tokens based on a predefined price function.

A bonding curve is a smart contract that mints and burns a token according to a predetermined price-supply relationship. For a prediction market, this token represents a share in the market's liquidity pool or a specific outcome. The most common function is a linear bonding curve, where price increases linearly with supply: price = reserveRatio * supply. The reserveRatio is a constant (e.g., 0.001 ETH) defining how much the reserve grows per token minted. This creates a predictable, automated market maker for your token.

You'll start by writing the core mint and burn functions. The mint function accepts a payment (e.g., ETH) and calculates how many new tokens to mint based on the current price integral. A typical implementation uses a piecewise calculation to determine the new token supply S1 after an investment dx: S1 = sqrt( (2*dx / k) + S0^2 ) for a linear curve, where k is the reserve ratio and S0 is the initial supply. The function then mints S1 - S0 tokens to the buyer and adds the dx payment to the contract's reserve.

The inverse burn function allows a user to sell tokens back to the curve. It calculates the refund amount based on the decrease in the reserve. Using the same formula, it determines the new, lower supply S1 after burning tokens and sends the user the corresponding portion of the reserve (reserve(S0) - reserve(S1)). This ensures the contract is always solvent, holding exactly enough reserve ETH to buy back all outstanding tokens at the current curve price.

Critical security considerations include front-running protection. Without it, a user could see a mint transaction in the mempool and front-run it with their own mint to get a better price. Implement a commit-reveal scheme or use a constant product invariant check within the same block. Furthermore, you must decide on the curve's initial parameters: the reserve ratio (k) and initial token supply. A higher k makes the token more expensive and less volatile, suitable for a large liquidity pool.

For development, use a library like OpenZeppelin for safe math and ERC-20 token basics. Test extensively with forked mainnet simulations using Foundry or Hardhat. A basic linear bonding curve contract can be under 100 lines of Solidity, but its security is paramount as it holds all market liquidity. The completed contract forms the foundation for the next step: integrating conditional logic for market resolution and profit distribution.

implementation-market-factory
CONTRACT ARCHITECTURE

Step 2: Building the Market Factory and Core

This step focuses on deploying the foundational smart contracts that will manage the creation and lifecycle of your token-bonded prediction markets.

The core of your prediction market platform consists of two primary contracts: the MarketFactory and the MarketCore. The MarketFactory is a factory contract responsible for deploying new, individual prediction market instances. Each market is its own separate smart contract, created using a predetermined template. This pattern, common in DeFi, allows for isolated risk and independent market logic. The factory stores a registry of all created markets and handles the initial configuration parameters passed to each new instance, such as the oracle address, resolution time, and the bonding token to be used.

The MarketCore contract is the template that every new market is cloned from. It contains the essential logic for a token-bonded prediction market. Its key functions include: - Accepting user bonds in the form of a specific ERC-20 token to create yes/no shares. - Managing a constant product AMM (like Uniswap V2) for each outcome, allowing users to trade shares. - Resolving the market based on a decentralized oracle report (e.g., Chainlink, UMA, Witnet). - Distributing the bonded collateral to holders of the winning outcome's shares. The bonding mechanism ensures participants have skin in the game, aligning incentives and reducing spam.

To deploy these contracts, you'll use a development framework like Hardhat or Foundry. Start by writing and compiling the Solidity code for both contracts. The factory should use the EIP-1167 minimal proxy pattern for efficient, low-cost cloning. After compilation, write a deployment script. This script will first deploy the MarketCore implementation contract, then deploy the MarketFactory, passing the core's address as a constructor argument. Verify the contracts on a block explorer like Etherscan after deployment. You can find reference implementations in repositories like Omen's Conditional Tokens or Polymarket's core contracts.

Critical security considerations for these contracts include access control on the factory's market creation function, input validation to prevent invalid oracle addresses or resolution times, and ensuring the bonding token is a legitimate ERC-20. The core contract must securely handle oracle resolution to prevent manipulation, often by trusting only a specific, pre-defined oracle address. Thorough testing with frameworks like Waffle or Forge is essential, simulating the full market lifecycle from creation through bonding, trading, and resolution.

implementation-slashing
ENFORCING HONESTY

Step 3: Adding Slashing and Challenge Logic

Implement the core incentive mechanisms that secure your prediction market by penalizing bad actors and rewarding honest dispute resolution.

The slashing mechanism is the enforcement layer of your token-bonded market. It financially penalizes participants who act maliciously or provide incorrect information. When a user submits a prediction or reports an outcome, they must stake collateral (your market's native token). If their submission is successfully challenged and proven wrong, a portion or all of this stake is slashed—burned or redistributed. This creates a direct cost for dishonesty, aligning individual incentives with the network's goal of accurate information.

To trigger slashing, you need a challenge period. After any state-changing action—like reporting a final outcome for a market event—the system enters a predefined window (e.g., 24-72 hours) where other participants can dispute the result. A challenge requires the challenger to also post a bond. The logic for initiating a challenge is typically a function call like challengeOutcome(uint256 marketId), which freezes the disputed funds and kicks off the resolution process.

The heart of the system is the dispute resolution logic. Your smart contract must have a clear, automated way to adjudicate challenges. For many prediction markets, this relies on a designated oracle (like Chainlink) or a decentralized oracle network (DON) to provide the canonical truth. The contract would have a function resolveChallenge(uint256 challengeId) that queries the pre-defined oracle. The party whose position aligns with the oracle's answer wins; the loser gets slashed.

Here is a simplified code snippet illustrating the core slashing logic in Solidity. This example assumes an external oracle resolves the challenge and returns a bool representing the correct outcome.

solidity
function resolveChallenge(uint256 challengeId) external {
    Challenge storage c = challenges[challengeId];
    require(c.resolved == false, "Already resolved");
    
    // Fetch the truthful outcome from the oracle (simplified)
    bool correctOutcome = oracle.getResult(c.marketId);
    
    address loser = c.reportedOutcome == correctOutcome ? c.challenger : c.reporter;
    address winner = loser == c.challenger ? c.reporter : c.challenger;
    
    // Slash 100% of the loser's stake
    uint256 slashAmount = c.stake;
    totalBurned += slashAmount; // Or send to treasury
    
    // Reward the winner (optional: from a reward pool or a portion of slash)
    _rewardWinner(winner);
    
    c.resolved = true;
    emit ChallengeResolved(challengeId, winner, loser, slashAmount);
}

When designing these parameters, you must carefully balance security with usability. Key variables to configure are: - Stake size: Too low, and slashing is ineffective; too high, and it discourages participation. - Challenge period duration: Must be long enough for users to see and react, but short enough to finalize markets promptly. - Slashing percentage: Whether to slash 100% of the stake or a variable amount based on severity. These economic parameters define your market's security model and should be tested extensively in simulations.

Finally, integrate these functions into your market's lifecycle. The challenge logic should be callable after outcome reporting, and the resolution should automatically update the market's final state and distribute winnings. Effective slashing and challenge logic transform your application from a simple polling tool into a cryptoeconomic system where truth is financially incentivized. For further reading on cryptoeconomic design, refer to resources like the Blockchain at Berkeley lectures.

implementation-resolution
MARKET SETTLEMENT

Step 4: Finalizing with Oracle Resolution

This step details how to settle a token-bonded prediction market by resolving its outcome using an oracle, distributing the bonded collateral to winners.

Oracle resolution is the final, trust-minimized step that determines the real-world outcome of your market and triggers the payout of the bonded collateral. After the market's event window closes, the smart contract queries a pre-defined oracle—such as Chainlink, UMA, or a custom reality.eth module—to fetch the final answer. This data feed acts as the single source of truth, automatically settling the market without requiring a centralized administrator. The contract logic, established during market creation, specifies the exact oracle address, job ID, or question ID it will call.

Upon receiving the oracle's answer, the contract executes the settlement function. This function calculates the payout ratio for the winning outcome token. For example, if a "Yes" outcome is resolved as true, all YES tokens become redeemable for a proportional share of the entire collateral pool, while NO tokens become worthless. The core calculation is: payoutPerToken = totalCollateral / totalWinningTokens. Users who hold the winning outcome token can then call a redeem or claimWinnings function to withdraw their share of USDC or ETH from the contract.

Implementing this requires careful smart contract design. Your settlement function must include access control (often only callable by the oracle or after a timelock), robust error handling for oracle failures, and a clear state transition to prevent re-settlement. Here is a simplified Solidity snippet for a settlement trigger:

solidity
function resolveMarket(string memory _outcome) external onlyOracle {
    require(marketState == State.CLOSED, "Market not closed");
    winningOutcome = _outcome;
    marketState = State.RESOLVED;
    emit MarketResolved(_outcome);
}

Security during resolution is paramount. You must guard against oracle manipulation and front-running. Using a decentralized oracle network like Chainlink with multiple nodes mitigates single-point failure. For subjective events, consider a dispute resolution period using a protocol like UMA's Optimistic Oracle, where the initial answer can be challenged. Always verify the oracle's answer on-chain and ensure your contract logic correctly maps this answer to the predefined market outcomes to avoid mispayouts.

After resolution, the market enters a final state. The contract should prevent further trading of the outcome tokens, which now solely represent a claim on collateral. Users typically have an unlimited window to redeem their winnings. This final step completes the lifecycle of a token-bonded prediction market, demonstrating how cryptoeconomic incentives (the bonded collateral) and decentralized data (the oracle) combine to create a self-executing agreement on the outcome of any real-world event.

TOKENOMICS DESIGN

Key Economic Parameters and Their Effects

A comparison of core parameter configurations for a token-bonded prediction market, detailing their impact on liquidity, security, and participation.

ParameterConservative (High Security)Balanced (Recommended)Aggressive (High Growth)

Bonding Curve Slope

0.05

0.10

0.25

Liquidity Provider Fee

0.3%

0.5%

1.0%

Dispute Bond Duration

7 days

3 days

24 hours

Minimum Stake for Resolution

1000 tokens

500 tokens

100 tokens

Arbitration Fee (on bond)

2.5%

1.5%

0.5%

Early Exit Penalty

15%

10%

5%

Oracle Finalization Window

48 hours

24 hours

6 hours

Initial Liquidity Requirement

100,000 tokens

50,000 tokens

10,000 tokens

DEVELOPER FAQ

Frequently Asked Questions

Common technical questions and solutions for building a token-bonded prediction market. This guide addresses setup hurdles, contract logic, and integration challenges.

A token-bonded prediction market is a decentralized application where users bet on event outcomes using a custom bonding curve token as the primary medium of exchange. Unlike markets using stablecoins, the token's value is intrinsically linked to market activity and liquidity.

Core Mechanics:

  1. Market Creation: A creator deploys a market for a specific binary outcome (e.g., "Will ETH be above $4000 on Jan 1?") and seeds its initial liquidity.
  2. Bonding Curve: A smart contract defines a mathematical relationship (e.g., a linear or polynomial curve) between the market's token supply and its price. Buying tokens increases the price; selling decreases it.
  3. Trading: Users buy "Yes" or "No" shares by interacting with the bonding curve. The cost to buy the next share is determined by the current spot price on the curve.
  4. Resolution: When the real-world event resolves, the market settles. Holders of the correct outcome token can redeem each share for a fixed payout (e.g., 1 DAI), while the incorrect token becomes worthless.
conclusion
RECAP AND FORWARD PATH

Conclusion and Next Steps

You have successfully built a foundational token-bonded prediction market. This guide covered the core smart contract architecture, bonding curve mechanics, and a basic frontend. Here's what you've accomplished and where to go next.

Your deployed system now includes a PredictionMarket contract where users can create markets on binary outcomes, stake tokens on YES or NO sides, and resolve them. The BondingCurve contract manages the automated market maker logic, determining token prices based on the pool's liquidity and outstanding shares. This creates a continuous liquidity mechanism, unlike traditional order books. The frontend you built connects a wallet, fetches market data, and allows interaction with the contracts, demonstrating the complete user flow from creation to resolution.

To enhance your application, consider these critical next steps. First, improve security and testing: implement comprehensive unit and fork tests using Foundry or Hardhat, add access controls for the resolveMarket function, and consider integrating a decentralized oracle like Chainlink Functions for tamper-proof resolution. Second, upgrade the economic model: experiment with different bonding curve formulas (e.g., logarithmic or polynomial) to adjust liquidity sensitivity, or introduce a protocol fee to sustain development. Third, refine the UX: add features like market search, sorting by liquidity or closing time, and real-time price updates using WebSocket subscriptions from a provider like Alchemy.

For deeper learning, explore advanced concepts in prediction market design. Study futarchy, a governance model where decisions are made based on market predictions, as proposed by Robin Hanson. Analyze how platforms like Polymarket or Augur handle dispute resolution and liquidity provisioning differently. To scale your project, research Layer 2 solutions like Arbitrum or Optimism to reduce transaction costs and improve speed, which is vital for a high-frequency trading environment. The code from this tutorial is a starting point; the frontier of decentralized forecasting is yours to build upon.

How to Build a Token-Bonded Prediction Market from Scratch | ChainScore Guides