facebook

Decentralized Prediction Market Development on Ethereum

Posted By : Yogesh

Oct 30, 2024

Decentralized Prediction Market Development on Ethereum

 

Prediction markets offer a fascinating blend of finance, information aggregation, and blockchain technology, enabling users to bet on future events transparently and autonomously. In this blog, we'll walk through creating a decentralized prediction market on Ethereum, exploring its structure, coding it in Solidity, and deploying it on the blockchain. By the end, you'll have a foundational understanding of decentralized prediction markets and the knowledge to build one yourself. If you are looking for more about DeFi, visit our DeFi development services

 

Prerequisites

 

  1. Basic knowledge of Solidity and Ethereum Smart Contracts.
  2. Installed tools: Node.js, npm, Truffle, and Ganache or Hardhat.
  3. Ethereum wallet: MetaMask for testing on a public testnet like Rinkeby or Goerli.

 

You may also like | How to Create a Yield Farming Contract

 

What is a Decentralized Prediction Market?

 

A decentralized prediction market allows users to place bets on the outcome of a specific event. Outcomes are decided based on real-world data, and payouts are distributed depending on the result. Events could range from elections to sports outcomes or even crypto price forecasts. The decentralized nature of Ethereum-based prediction markets offers users transparency, fairness, and immutability.

 

Designing the Prediction Market Smart Contract

 

Our smart contract will allow users to:

 

  1. Create markets for predicting events.
  2. Place bets on available outcomes.
  3. Settle markets based on outcomes.
  4. Distribute winnings based on the outcome.

 

Key Functions

 

  1. Creating a Market: Allow a user to create a prediction market.
  2. Placing Bets: Allow users to place bets on specified outcomes.
  3. Finalizing Market: After the outcome is known, finalize the market and distribute winnings.

 

Also, Explore | How to Create a Liquid Staking Pool

 

A Step-by-Step Code Explanation

 

Here's a basic Solidity smart contract to get started:

 

solidity

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract PredictionMarket {
    enum MarketOutcome { None, Yes, No }
    
    struct Market {
        string description;
        uint256 deadline;
        MarketOutcome outcome;
        bool finalized;
        uint256 totalYesBets;
        uint256 totalNoBets;
        mapping(address => uint256) yesBets;
        mapping(address => uint256) noBets;
    }
    
    mapping(uint256 => Market) public markets;
    uint256 public marketCount;
    address public admin;

    event MarketCreated(uint256 marketId, string description, uint256 deadline);
    event BetPlaced(uint256 marketId, address indexed user, MarketOutcome outcome, uint256 amount);
    event MarketFinalized(uint256 marketId, MarketOutcome outcome);

    modifier onlyAdmin() {
        require(msg.sender == admin, 'Only admin can execute');
        _;
    }

    constructor() {
        admin = msg.sender;
    }

    // Create a new market
    function createMarket(string memory _description, uint256 _deadline) public onlyAdmin {
        require(_deadline > block.timestamp, 'Deadline must be in the future');

        Market storage market = markets[marketCount++];
        market.description = _description;
        market.deadline = _deadline;

        emit MarketCreated(marketCount - 1, _description, _deadline);
    }

    // Place a bet
    function placeBet(uint256 _marketId, MarketOutcome _outcome) public payable {
        Market storage market = markets[_marketId];
        require(block.timestamp < market.deadline, 'Betting period is over');
        require(_outcome == MarketOutcome.Yes || _outcome == MarketOutcome.No, 'Invalid outcome');
        require(msg.value > 0, 'Bet amount must be greater than zero');

        if (_outcome == MarketOutcome.Yes) {
            market.yesBets[msg.sender] += msg.value;
            market.totalYesBets += msg.value;
        } else {
            market.noBets[msg.sender] += msg.value;
            market.totalNoBets += msg.value;
        }

        emit BetPlaced(_marketId, msg.sender, _outcome, msg.value);
    }

    // Finalize the market with the actual outcome
    function finalizeMarket(uint256 _marketId, MarketOutcome _outcome) public onlyAdmin {
        Market storage market = markets[_marketId];
        require(block.timestamp >= market.deadline, 'Market cannot be finalized before deadline');
        require(!market.finalized, 'Market already finalized');

        market.outcome = _outcome;
        market.finalized = true;

        emit MarketFinalized(_marketId, _outcome);
    }

    // Claim winnings
    function claimWinnings(uint256 _marketId) public {
        Market storage market = markets[_marketId];
        require(market.finalized, 'Market not finalized yet');

        uint256 payout;

        if (market.outcome == MarketOutcome.Yes) {
            uint256 userBet = market.yesBets[msg.sender];
            payout = userBet + (userBet * market.totalNoBets / market.totalYesBets);
            market.yesBets[msg.sender] = 0;
        } else if (market.outcome == MarketOutcome.No) {
            uint256 userBet = market.noBets[msg.sender];
            payout = userBet + (userBet * market.totalYesBets / market.totalNoBets);
            market.noBets[msg.sender] = 0;
        }

        require(payout > 0, 'No winnings to claim');
        payable(msg.sender).transfer(payout);
    }
}

 

Also, Check | How to Swap Tokens on Uniswap V3

 

Explanation of the Code

 

  1. Structs and Enums: We define a Market struct to store the details of each prediction market, and an enum MarketOutcome to represent the possible outcomes (Yes, No, or None).
  2. Market Creation: The createMarket function lets the admin create a market, specifying a description and a deadline.
  3. Betting on Outcomes: placeBet allows users to bet on an outcome (Yes or No) with an amount in Ether.
  4. Finalizing the Market: finalizeMarket enables the admin to lock in the actual outcome once the event is over.
  5. Claiming Winnings: Users can call claimWinnings to receive their payout if they bet on the correct outcome.

 

Conclusion

 

In conclusion, developing a decentralized prediction market on Ethereum provides a powerful way to leverage blockchain's transparency, security, and trustlessness. By following the outlined steps, developers can create platforms that foster open participation and reliable forecasting. This innovation empowers users to make informed predictions while maintaining trust in the system, ultimately contributing to a more decentralized and efficient financial ecosystem. Embrace this opportunity to build solutions that harness the full potential of blockchain technology. Connect with our skilled blockchain developers for more information. 

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

December 2, 2024 at 11:12 am

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button

Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text