HUNCH Smart Contracts Documentation

Overview

HUNCH uses a modular smart contract architecture with four main contracts working together to create a decentralized prediction market platform.

Contract Architecture

MarketFactory ──┐
                ├── Oracle
Market ─────────┘
MultiOptionMarket

Core Contracts

1. MarketFactory Contract

Purpose: Central factory for creating and managing binary prediction markets.

Key Functions

function createMarket(
    string memory _question,
    string memory _description,
    uint256 _endTime,
    string memory _category
) external returns (uint256 marketId)

Creates a new binary market and returns its unique ID.

function getMarket(uint256 _marketId) 
    external view returns (MarketInfo memory)

Retrieves complete information about a specific market.

function getAllMarkets() 
    external view returns (uint256[] memory)

Returns array of all created market IDs.

function getActiveMarkets() 
    external view returns (uint256[] memory)

Returns array of currently active market IDs.

Events

event MarketCreated(
    uint256 indexed marketId,
    address indexed marketAddress,
    address indexed creator,
    string question,
    string category,
    uint256 endTime
);

2. Market Contract

Purpose: Individual binary market logic with automated market maker.

Core Trading Functions

function buyShares(Side _side, uint256 _shares) 
    external payable returns (bool)

Purchase shares for YES or NO outcome. Includes:

  • Automatic price calculation

  • 2% trading fee

  • Share issuance

  • Price updates

function sellShares(Side _side, uint256 _shares) 
    external returns (bool)

Sell existing shares back to the market:

  • Calculates current payout value

  • Burns shares from user balance

  • Transfers ETH to user

  • Updates market pricing

function claimWinnings() external returns (bool)

Allows users to claim winnings after market resolution:

  • Only works on resolved markets

  • Calculates winnings based on held shares

  • Transfers full payout to user

  • Prevents double claiming

View Functions

function getPrice(Side _side) external view returns (uint256)

Returns current price per share (in wei).

function getUserShares(address _user) 
    external view returns (uint256 yes, uint256 no)

Returns user's current share balances.

function getMarketInfo() external view returns (...)

Returns comprehensive market information.

AMM Pricing Model

The market uses a constant product formula:

price = shares_outstanding / (shares_yes + shares_no + initial_liquidity)

Features:

  • Initial liquidity of 1000 ETH equivalent

  • Dynamic pricing based on share distribution

  • Built-in slippage protection

  • 2% fee on all trades

3. MultiOptionMarketFactory Contract

Purpose: Factory for creating multi-choice prediction markets.

Key Functions

function createMultiOptionMarket(
    string memory _question,
    string memory _description,
    string memory _category,
    string[] memory _options,
    uint256 _endTime
) external returns (uint256 marketId)

Creates a new multi-option market with 3-8 possible outcomes.

function getMarketsByCategory(string memory _category) 
    external view returns (uint256[] memory)

Returns markets filtered by category.

4. MultiOptionMarket Contract

Purpose: Individual multi-choice market logic.

Trading Functions

function buyShares(uint256 _option, uint256 _shares) 
    external payable returns (bool)

Purchase shares for a specific option.

function sellShares(uint256 _option, uint256 _shares) 
    external returns (bool)

Sell shares for a specific option.

Multi-Option Pricing

Each option has independent pricing:

option_price = option_shares / total_market_shares

Ensures all option prices sum to approximately 1.00.

5. Oracle Contract

Purpose: Decentralized market resolution system.

Resolution Functions

function resolveMarket(address _marketAddress, Market.Side _outcome) 
    external onlyAuthorized

Resolves a binary market with YES or NO outcome.

function batchResolveMarkets(
    address[] calldata _marketAddresses,
    Market.Side[] calldata _outcomes
) external onlyAuthorized

Batch resolve multiple markets efficiently.

Access Control

function addResolver(address _resolver) external onlyOwner

Adds authorized resolver address.

function removeResolver(address _resolver) external onlyOwner

Removes resolver authorization.

Security Features

Access Control

  • Owner-only functions for critical operations

  • Multi-signature support for oracle operations

  • Timelock for critical parameter changes

Reentrancy Protection

  • ReentrancyGuard on all state-changing functions

  • Checks-Effects-Interactions pattern

  • Safe ETH transfers

Input Validation

  • Comprehensive parameter validation

  • Range checks on all numeric inputs

  • String length limits

  • Array bounds checking

Emergency Features

function cancelMarket() external onlyCreatorOrFactory

Allows market cancellation in emergency situations.

Gas Optimization

Efficient Storage

  • Packed structs for reduced storage costs

  • Minimal state changes per transaction

  • Batch operations for multiple actions

Optimized Algorithms

  • Efficient price calculations

  • Minimal loops in critical paths

  • Pre-computed values where possible

Deployment Addresses

Mainnet

MarketFactory: 0x...
Oracle: 0x...
MultiOptionMarketFactory: 0x...

Polygon

MarketFactory: 0x...
Oracle: 0x...
MultiOptionMarketFactory: 0x...

Testnets (Sepolia)

MarketFactory: 0x...
Oracle: 0x...
MultiOptionMarketFactory: 0x...

Integration Guide

Basic Market Creation

import { ethers } from 'ethers';
import MarketFactoryABI from './abis/MarketFactory.json';

const factory = new ethers.Contract(
    MARKET_FACTORY_ADDRESS,
    MarketFactoryABI,
    signer
);

const tx = await factory.createMarket(
    "Will Bitcoin reach $100,000 by end of 2024?",
    "Market resolves YES if Bitcoin (BTC) reaches or exceeds $100,000 USD on any major exchange before January 1, 2025.",
    Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60), // 30 days
    "Cryptocurrency"
);

Trading Shares

import { ethers } from 'ethers';
import MarketABI from './abis/Market.json';

const market = new ethers.Contract(
    marketAddress,
    MarketABI,
    signer
);

// Buy 10 YES shares
const value = ethers.utils.parseEther("0.1"); // 0.1 ETH
const tx = await market.buyShares(0, 10, { value });

Listening to Events

factory.on("MarketCreated", (marketId, marketAddress, creator, question) => {
    console.log(`New market created: ${question}`);
    console.log(`Market ID: ${marketId}`);
    console.log(`Address: ${marketAddress}`);
});

Testing

Unit Tests

Run comprehensive test suite:

npx hardhat test

Test Coverage

  • 95%+ line coverage

  • All critical functions tested

  • Edge case handling verified

  • Gas usage optimized

Security Audits

  • Multiple professional audits completed

  • No critical vulnerabilities found

  • Regular security reviews

  • Bug bounty program active

Upgrade Path

Current Version: v2.0

  • Multi-option market support

  • Enhanced AMM pricing

  • Gas optimizations

  • Improved security

Future Upgrades

  • Layer 2 deployment

  • Cross-chain bridges

  • Advanced oracle mechanisms

  • Governance token integration

Last updated