Skip to content

Prediction Markets Protocol#1

Open
obafemisarah wants to merge 1 commit intomainfrom
market
Open

Prediction Markets Protocol#1
obafemisarah wants to merge 1 commit intomainfrom
market

Conversation

@obafemisarah
Copy link
Copy Markdown
Owner

Prediction Markets Protocol - Smart Contract Description

Overview

The Prediction Markets Protocol is a decentralized binary prediction market platform built on the Stacks blockchain using Clarity smart contract language. It enables users to create event-based markets, stake STX tokens on YES/NO outcomes, and receive proportional payouts when markets are resolved.

Core Mechanics

Market Lifecycle

  1. Creation Phase: Any user can create a prediction market by defining a question (up to 256 characters), an end-time for betting, and a resolution-time when outcomes can be determined.

  2. Betting Phase: Users place bets by locking STX tokens on either YES or NO outcomes. All funds are held in the contract and contribute to the total prize pool. Bets can only be placed while the market is open and before the end-time block height is reached.

  3. Resolution Phase: After the resolution-time, the designated resolver (typically the market creator) declares the winning outcome. This finalizes the market and enables winners to claim their rewards.

  4. Claiming Phase: Users who bet on the winning outcome can claim their proportional share of the entire prize pool, calculated as: (user_winning_bet / total_winning_bets) × total_pool_size - platform_fee.

Payout Distribution

The protocol uses a parimutuel betting system where:

  • The total pool consists of all YES and NO bets combined
  • Winners split the entire pool proportionally based on their stake
  • Losers forfeit their entire bet
  • A 2% platform fee is deducted from winnings (configurable up to 10%)

Example: If the total pool is 300 STX (100 on YES, 200 on NO) and YES wins, a user who bet 50 STX on YES receives: (50/100) × 300 = 150 STX - 2% fee = 147 STX (a 194% return).

Key Features

Dynamic Odds Calculation

The contract provides real-time probability estimates based on the current distribution of bets:

YES odds = (total_yes_bets / total_pool) × 100
NO odds = (total_no_bets / total_pool) × 100

This creates a live market where odds shift as more users participate.

Security & Access Control

  • Time-based restrictions: Markets enforce end-time and resolution-time constraints using block heights to prevent manipulation
  • Authorization layers: Only authorized principals can close or resolve markets
  • Double-claim prevention: Users cannot claim winnings multiple times
  • State management: Markets transition through Open → Closed → Resolved states with proper validation

Position Tracking

Each user's position is tracked independently per market, recording:

  • Total amount bet on YES outcome
  • Total amount bet on NO outcome
  • Claim status (to prevent double withdrawals)

This allows users to bet multiple times on the same outcome or hedge by betting on both sides.

Technical Implementation

Data Storage

  • Markets Map: Stores complete market metadata including creator, question, timestamps, bet totals, status, and winning outcome
  • User Positions Map: Tracks individual betting positions using composite keys (market-id + user principal)
  • Nonce Counter: Auto-increments to assign unique IDs to each new market

Token Flow

  1. Deposits: When users place bets, STX tokens are transferred from their wallet to the contract using stx-transfer?
  2. Escrow: All funds remain locked in the contract until market resolution
  3. Withdrawals: Winners trigger payouts by calling claim-winnings, which transfers STX from the contract back to their wallet
  4. Fees: A percentage is automatically routed to the contract owner upon each claim

Error Handling

The contract implements 11 distinct error codes covering scenarios like:

  • Unauthorized access attempts
  • Invalid market states or transitions
  • Insufficient balances
  • Time constraint violations
  • Resource not found errors

Advanced Functionality

Market Management

  • Early Closure: Market creators or the contract owner can manually close markets before end-time if necessary
  • Emergency Withdrawal: Contract owner has emergency access to extract funds in critical situations
  • Fee Configuration: Platform fee percentage can be adjusted by the owner (capped at 10%)

Read-Only Queries

Users can query without gas costs:

  • Complete market details and current state
  • Personal position information
  • Projected payout amounts before claiming
  • Current odds and probability distribution

Use Cases

Financial Markets

  • Cryptocurrency price predictions ("Will BTC reach $100k by December?")
  • Stock market movements
  • Economic indicators and events

Sports & Entertainment

  • Game outcomes and tournament winners
  • Award show results
  • Box office performance predictions

Political & Social Events

  • Election results
  • Policy decisions
  • Public opinion polls

Governance & DAOs

  • Protocol upgrade decisions
  • Community sentiment gauges
  • Future planning and roadmap votes

Economic Model

Incentive Structure

  • Market Creators: Gain authority to resolve outcomes (potential for curator fees in future versions)
  • Bettors: Profit from accurate predictions with returns proportional to market inefficiency
  • Platform: Earns 2% fee on all winning payouts
  • Liquidity Providers: Early bettors benefit from better odds before market equilibrium

Market Efficiency

As more participants join, odds converge toward true probabilities through crowd wisdom. The parimutuel system ensures the contract remains solvent since all payouts come from the pool itself, not from external reserves.

Limitations & Considerations

Oracle Problem

The contract relies on trusted resolvers to report outcomes honestly. There's no built-in dispute resolution or decentralized oracle integration, making resolver integrity critical.

Liquidity Risk

Markets with one-sided betting create poor odds for latecomers. A market with 100 STX on YES and 0 on NO offers no return for YES bettors even if they win.

Time Dependency

All timing uses block heights rather than timestamps, providing manipulation resistance but requiring block height calculations for real-world time predictions.

No Secondary Market

Users cannot exit positions before resolution or transfer betting positions to others, limiting liquidity and flexibility.

Future Enhancements

Potential upgrades could include:

  • Multi-outcome markets (beyond binary YES/NO)
  • Automated market maker (AMM) integration for guaranteed liquidity
  • Decentralized oracle integration (Chainlink, Pyth)
  • Dispute resolution mechanisms
  • Secondary market for position trading
  • Dynamic fee structures based on market size
  • Reputation systems for resolvers

Technical Specifications

  • Language: Clarity (Stacks blockchain)
  • Token Standard: STX (native Stacks token)
  • Contract Size: 283 lines of code
  • Gas Efficiency: Optimized for minimal transaction costs
  • Security: No external dependencies, immutable logic post-deployment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant