// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {IERC20, IERC20Permit, IFeed, SafeTransfer} from "./Interfaces.sol"; /// @title ClapperMarkets /// @notice Parimutuel YES/NO markets on Chainlink feeds, staked in USDG. Odds are the pool ratio. At settle time anyone /// passes the first Chainlink round at or after settleTime; winners split the pool pro rata minus a 2% fee that goes to /// the fee reserve. One-sided pools and stale feeds are voided and refunded in full. /// @dev Immutable. No owner, no pause, no admin path over staked funds. The feed allowlist is fixed at deploy. contract ClapperMarkets { using SafeTransfer for IERC20; enum Kind { ABOVE, // YES if price >= a (strike) MOVE_UP, // YES if price * 10_000 >= a (open price) * (10_000 + b (bps)) RANGE // YES if a (low) <= price < b (high) } enum State { OPEN, SETTLED, VOID } enum VoidReason { NONE, ONE_SIDED, STALE_FEED, BAD_ANSWER } struct Market { address feed; Kind kind; State state; bool outcomeYes; VoidReason voidReason; uint64 createdAt; uint64 lockTime; uint64 settleTime; address creator; int256 a; int256 b; uint256 yesPool; uint256 noPool; uint256 payoutPool; // pool minus fee, set at settle uint256 paidOut; uint256 claimedWinStake; int256 settlePrice; uint80 settleRound; uint64 settleUpdatedAt; uint80 openRound; // MOVE_UP only } struct Position { uint256 yes; uint256 no; bool claimed; } uint256 public constant FEE_BPS = 200; uint256 public constant BPS = 10_000; uint256 public constant MIN_DURATION = 1 hours; // creation -> settleTime uint256 public constant MAX_DURATION = 35 days; uint256 public constant STALE_WINDOW = 6 hours; // first round after settleTime must land within this window uint256 public constant MIN_STAKE = 100_000; // 0.10 USDG (6 decimals) uint256 public constant MAX_MOVE_BPS = 5_000; uint256 public constant OPEN_PRICE_MAX_AGE = 4 days; // weekend-safe freshness for MOVE_UP opening reads IERC20 public immutable usdg; address public immutable feeReserve; address[] private _feeds; mapping(address => bool) public isFeed; Market[] private _markets; mapping(uint256 => mapping(address => Position)) public positions; uint256 public totalStaked; uint256 public totalFees; uint256 public settledCount; uint256 public voidCount; uint256 private _lock = 1; event MarketCreated( uint256 indexed id, address indexed feed, Kind kind, int256 a, int256 b, uint64 lockTime, uint64 settleTime, address indexed creator, uint80 openRound ); event Staked(uint256 indexed id, address indexed user, bool yes, uint256 amount, uint256 yesPool, uint256 noPool); event Settled( uint256 indexed id, uint80 roundId, int256 price, uint256 updatedAt, bool outcomeYes, uint256 fee, address settler ); event Voided(uint256 indexed id, VoidReason reason, address settler); event Claimed(uint256 indexed id, address indexed user, uint256 amount, bool refund); error NotAllowedFeed(); error BadTimes(); error BadParams(); error StaleOpenPrice(); error NotCurrentRound(); error UnknownMarket(); error MarketClosed(); error Locked(); error StakeTooSmall(); error TooEarly(); error RoundMismatch(); error RoundBeforeSettle(); error NotFirstRound(); error PrevRoundUnreadable(); error FeedNotStale(); error NotFinal(); error NothingToClaim(); error AlreadyClaimed(); error Reentrancy(); error ZeroAddress(); modifier nonReentrant() { if (_lock != 1) revert Reentrancy(); _lock = 2; _; _lock = 1; } constructor(IERC20 usdg_, address feeReserve_, address[] memory feeds_) { if (address(usdg_) == address(0) || feeReserve_ == address(0) || feeds_.length == 0) revert ZeroAddress(); usdg = usdg_; feeReserve = feeReserve_; for (uint256 i; i < feeds_.length; ++i) { address f = feeds_[i]; if (f == address(0)) revert ZeroAddress(); if (isFeed[f]) continue; isFeed[f] = true; _feeds.push(f); } } // ---------------------------------------------------------------- create /// @param a ABOVE: strike. MOVE_UP: the feed round that is current right now (the open price is read from it). /// RANGE: low. Prices use the feed's decimals. /// @param b ABOVE: ignored. MOVE_UP: move in bps (1..5000). RANGE: high. function createMarket(address feed, Kind kind, int256 a, int256 b, uint64 lockTime, uint64 settleTime) external returns (uint256 id) { if (!isFeed[feed]) revert NotAllowedFeed(); if ( lockTime <= block.timestamp || lockTime >= settleTime || settleTime < block.timestamp + MIN_DURATION || settleTime > block.timestamp + MAX_DURATION ) revert BadTimes(); uint80 openRound; if (kind == Kind.ABOVE) { if (a <= 0) revert BadParams(); b = 0; } else if (kind == Kind.MOVE_UP) { if (b <= 0 || b > int256(MAX_MOVE_BPS) || a <= 0 || a > int256(uint256(type(uint80).max))) { revert BadParams(); } openRound = uint80(uint256(a)); a = _openPrice(IFeed(feed), openRound); } else { if (a <= 0 || b <= a) revert BadParams(); } id = _markets.length; Market storage m = _markets.push(); m.feed = feed; m.kind = kind; m.createdAt = uint64(block.timestamp); m.lockTime = lockTime; m.settleTime = settleTime; m.creator = msg.sender; m.a = a; m.b = b; m.openRound = openRound; emit MarketCreated(id, feed, kind, a, b, lockTime, settleTime, msg.sender, openRound); } // ---------------------------------------------------------------- stake function stake(uint256 id, bool yes, uint256 amount) public nonReentrant { Market storage m = _market(id); if (m.state != State.OPEN) revert MarketClosed(); if (block.timestamp >= m.lockTime) revert Locked(); if (amount < MIN_STAKE) revert StakeTooSmall(); Position storage p = positions[id][msg.sender]; if (yes) { m.yesPool += amount; p.yes += amount; } else { m.noPool += amount; p.no += amount; } totalStaked += amount; usdg.safeTransferFrom(msg.sender, address(this), amount); emit Staked(id, msg.sender, yes, amount, m.yesPool, m.noPool); } /// @notice Stake with an EIP-2612 permit (USDG supports it). A failed permit is ignored so a front-run permit /// cannot grief the stake; the transferFrom still needs the allowance. function stakeWithPermit(uint256 id, bool yes, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { try IERC20Permit(address(usdg)).permit(msg.sender, address(this), amount, deadline, v, r, s) {} catch {} stake(id, yes, amount); } // ---------------------------------------------------------------- settle /// @notice Ring the bell. `roundId` must be the FIRST Chainlink round with updatedAt >= settleTime. /// One-sided markets are voided from lockTime on (no round needed); a first round later than settleTime + /// STALE_WINDOW voids the market. function settle(uint256 id, uint80 roundId) external nonReentrant { Market storage m = _market(id); if (m.state != State.OPEN) revert MarketClosed(); if (block.timestamp >= m.lockTime && (m.yesPool == 0 || m.noPool == 0)) { _void(id, m, VoidReason.ONE_SIDED); return; } if (block.timestamp < m.settleTime) revert TooEarly(); IFeed feed = IFeed(m.feed); (uint80 rid, int256 answer,, uint256 updatedAt,) = feed.getRoundData(roundId); if (rid != roundId) revert RoundMismatch(); if (updatedAt < m.settleTime) revert RoundBeforeSettle(); if (_prevUpdatedAt(feed, roundId) >= m.settleTime) revert NotFirstRound(); if (updatedAt > m.settleTime + STALE_WINDOW) { _void(id, m, VoidReason.STALE_FEED); return; } if (answer <= 0) { _void(id, m, VoidReason.BAD_ANSWER); return; } bool outcomeYes = _decide(m, answer); uint256 pool = m.yesPool + m.noPool; uint256 fee = (pool * FEE_BPS) / BPS; m.state = State.SETTLED; m.outcomeYes = outcomeYes; m.payoutPool = pool - fee; m.settlePrice = answer; m.settleRound = roundId; m.settleUpdatedAt = uint64(updatedAt); settledCount++; totalFees += fee; if (fee > 0) usdg.safeTransfer(feeReserve, fee); emit Settled(id, roundId, answer, updatedAt, outcomeYes, fee, msg.sender); } /// @notice Void a market whose feed has produced no round at all since settleTime and the stale window is over. function voidStale(uint256 id) external nonReentrant { Market storage m = _market(id); if (m.state != State.OPEN) revert MarketClosed(); if (block.timestamp <= m.settleTime + STALE_WINDOW) revert TooEarly(); (,,, uint256 updatedAt,) = IFeed(m.feed).latestRoundData(); if (updatedAt >= m.settleTime) revert FeedNotStale(); _void(id, m, VoidReason.STALE_FEED); } // ---------------------------------------------------------------- claim function claim(uint256 id) external nonReentrant returns (uint256 paid) { paid = _claim(id, msg.sender, false); if (paid == 0) revert NothingToClaim(); } /// @notice Claim several markets; ones with nothing to claim are skipped. function claimMany(uint256[] calldata ids) external nonReentrant returns (uint256 total) { for (uint256 i; i < ids.length; ++i) { total += _claim(ids[i], msg.sender, true); } if (total == 0) revert NothingToClaim(); } // ---------------------------------------------------------------- views function marketCount() external view returns (uint256) { return _markets.length; } function getMarket(uint256 id) external view returns (Market memory) { return _market(id); } function feeds() external view returns (address[] memory) { return _feeds; } function feedCount() external view returns (uint256) { return _feeds.length; } /// @notice What `user` could claim now (0 if not final, already claimed or lost). function claimable(uint256 id, address user) public view returns (uint256) { Market storage m = _market(id); Position storage p = positions[id][user]; if (p.claimed) return 0; if (m.state == State.VOID) return p.yes + p.no; if (m.state != State.SETTLED) return 0; (uint256 win, uint256 winPool) = _winning(m, p); if (win == 0) return 0; if (m.claimedWinStake + win == winPool) return m.payoutPool - m.paidOut; return (win * m.payoutPool) / winPool; } /// @notice Threshold check used at settle, exposed so the UI can show "YES if ..." with the same math. function wouldBeYes(uint256 id, int256 price) external view returns (bool) { return _decide(_market(id), price); } // ---------------------------------------------------------------- internal function _market(uint256 id) internal view returns (Market storage) { if (id >= _markets.length) revert UnknownMarket(); return _markets[id]; } function _decide(Market storage m, int256 price) internal view returns (bool) { if (m.kind == Kind.ABOVE) return price >= m.a; if (m.kind == Kind.MOVE_UP) return price * int256(BPS) >= m.a * (int256(BPS) + m.b); return price >= m.a && price < m.b; } /// @dev Opening price for MOVE_UP: `rid` must be in the feed's current phase, already published, fresh, and the /// newest round as of now (the next round is missing or later than block.timestamp). function _openPrice(IFeed feed, uint80 rid) internal view returns (int256) { if (uint16(rid >> 64) != feed.phaseId()) revert NotCurrentRound(); (uint80 r, int256 answer,, uint256 updatedAt,) = feed.getRoundData(rid); if (r != rid) revert RoundMismatch(); if (answer <= 0 || updatedAt == 0 || updatedAt > block.timestamp || block.timestamp - updatedAt > OPEN_PRICE_MAX_AGE) { revert StaleOpenPrice(); } try feed.getRoundData(rid + 1) returns (uint80, int256, uint256, uint256 nextAt, uint80) { if (nextAt != 0 && nextAt <= block.timestamp) revert NotCurrentRound(); } catch {} return answer; } /// @dev updatedAt of the round before `roundId`, crossing a phase boundary through phaseAggregators. function _prevUpdatedAt(IFeed feed, uint80 roundId) internal view returns (uint256) { uint16 phase = uint16(roundId >> 64); uint64 aggRound = uint64(roundId); if (aggRound > 1) { try feed.getRoundData(roundId - 1) returns (uint80, int256, uint256, uint256 at, uint80) { return at; } catch { revert PrevRoundUnreadable(); } } if (phase <= 1) return 0; // very first round of the feed address prevAgg = feed.phaseAggregators(phase - 1); if (prevAgg == address(0)) return 0; try IFeed(prevAgg).latestRoundData() returns (uint80, int256, uint256, uint256 at, uint80) { return at; } catch { revert PrevRoundUnreadable(); } } function _winning(Market storage m, Position storage p) internal view returns (uint256 win, uint256 winPool) { if (m.outcomeYes) return (p.yes, m.yesPool); return (p.no, m.noPool); } function _void(uint256 id, Market storage m, VoidReason reason) internal { m.state = State.VOID; m.voidReason = reason; voidCount++; emit Voided(id, reason, msg.sender); } /// @param skip true for claimMany: open or already-claimed markets return 0 instead of reverting. function _claim(uint256 id, address user, bool skip) internal returns (uint256 paid) { Market storage m = _market(id); Position storage p = positions[id][user]; if (m.state == State.OPEN || p.claimed) { if (skip) return 0; if (m.state == State.OPEN) revert NotFinal(); revert AlreadyClaimed(); } bool refund = m.state == State.VOID; if (refund) { paid = p.yes + p.no; } else { (uint256 win, uint256 winPool) = _winning(m, p); if (win == 0) return 0; m.claimedWinStake += win; // The last winner takes the rounding dust so the contract ends at exactly zero for this market. paid = m.claimedWinStake == winPool ? m.payoutPool - m.paidOut : (win * m.payoutPool) / winPool; m.paidOut += paid; } if (paid == 0) return 0; p.claimed = true; usdg.safeTransfer(user, paid); emit Claimed(id, user, paid, refund); } }