Chapter 35: Exercises

Conditional Token Framework Fundamentals

Exercise 1: Computing Condition IDs

Given an oracle address 0xABCD...1234, a questionId of 0x01 (32 bytes, zero-padded), and 3 outcome slots, compute the conditionId using Python's Web3.solidity_keccak. Verify by re-implementing with the hashlib approach using the raw ABI encoding.

Exercise 2: Index Set Enumeration

For a prediction market with 4 outcomes (A, B, C, D), enumerate all possible non-empty index sets as both binary strings and decimal values. How many are there? How many valid partitions exist?

Exercise 3: Partition Validation

Write a Python function is_valid_partition(index_sets: List[int], outcome_count: int) -> bool that checks whether a list of index sets forms a valid partition. Test it with: - [1, 2] for 2 outcomes (should be True) - [1, 2, 4] for 3 outcomes (should be True) - [3, 4] for 3 outcomes (should be True: {A or B} vs {C}) - [1, 3] for 3 outcomes (should be False: overlapping) - [1, 4] for 3 outcomes (should be False: incomplete)

Exercise 4: Collection ID XOR

Given two conditions with collection IDs coll_A = keccak256(condA, 2) and coll_B = keccak256(condB, 1), compute the combined collection ID using XOR. Explain why XOR is commutative and associative, and why these properties matter for the CTF.

Exercise 5: Split and Merge Simulation

Write a Python class CTFSimulator that tracks token balances for multiple users across multiple conditions. Implement split(), merge(), and redeem() methods. Verify the collateral invariant after each operation.

Augur Deep Dive

Exercise 6: Dispute Cost Escalation

In Augur's dispute resolution, if the base stake is 100 REP, compute the cumulative cost to sustain a false outcome through 10 rounds of disputes. At what round does the cost exceed 100,000 REP? Plot the cumulative cost as a function of round number.

Exercise 7: Fork Threshold Analysis

If the fork threshold is 2.5% of total REP supply (11 million tokens), what is the maximum market value that Augur can securely support? Assuming REP trades at $10, compute the maximum secure market size. What happens if REP price drops to $2?

Exercise 8: Reporting Fee Dynamics

Implement a simulation of Augur's dynamic reporting fee. Start with a fee of 1%, total open interest of $1M, and REP market cap of $100M. Simulate 100 time steps where open interest grows by a random amount each step, and the fee adjusts to maintain the security invariant.

Exercise 9: Augur Market Lifecycle

Trace the complete lifecycle of an Augur binary market from creation to settlement. For each step, list the smart contract function called, the gas cost (approximate), and the state changes. Calculate the total cost in gas for a market that is created, has 10 trades, is reported correctly, and settles without disputes.

Exercise 10: Invalid Outcome Impact

In Augur v2, the "Invalid" outcome was added. If a market resolves as Invalid, all outcome tokens receive equal payout. For a binary market where Yes trades at 0.70 and No at 0.30, calculate the payout per token if the market resolves as Invalid. What is the P&L for a trader holding 1000 Yes tokens bought at 0.70?

Polymarket Architecture

Exercise 11: Neg Risk Adapter Analysis

For a multi-outcome market (3 candidates: A, B, C), the Neg Risk Adapter creates three binary markets. If the binary market prices are: A=0.50, B=0.35, C=0.20, the sum is 1.05. Explain the arbitrage opportunity. Write Python code to calculate the risk-free profit for a $1000 investment.

Exercise 12: Order Book Simulation

Implement a simplified Polymarket order book for a binary market. Support limit orders (buy/sell), market orders, and order cancellation. Simulate a sequence of 100 random orders and track the mid-price over time. Plot the results.

Exercise 13: Trade Lifecycle Tracing

Given a specific Polymarket trade, trace all on-chain state changes. For a trade where Alice buys 100 Yes tokens at $0.60 from Bob: - What USDC transfer occurs? - What ERC-1155 transfer occurs? - What are the token IDs involved? - What events are emitted?

Exercise 14: UMA Oracle Timing

If a market resolves via UMA's Optimistic Oracle with a 2-hour challenge period, and a proposer submits the outcome at block time T, at what block time is the outcome finalized? What happens if a dispute is filed at T + 1 hour? Describe the full timeline.

Exercise 15: Gas Cost Optimization

Compare the gas cost of executing the same 10-trade sequence on: (a) a fully on-chain AMM, (b) a fully on-chain CLOB, and (c) Polymarket's hybrid model. Use the gas estimates from Section 35.5.3. Which approach costs the least on Ethereum mainnet? On Polygon?

Token Economics

Exercise 16: Complete Set Arbitrage

Write a Python function that monitors the prices of all outcome tokens in a binary market and detects arbitrage opportunities (sum > 1 or sum < 1). Given a sequence of price snapshots, identify all arbitrage windows and calculate the theoretical profit (ignoring gas costs).

Exercise 17: Annualized Return Calculation

A trader buys a Yes token at $0.60 in a market that resolves in 45 days. If the event occurs (probability estimated at 0.75), calculate: - The expected return per trade - The annualized expected return - The Kelly criterion optimal fraction of bankroll to wager

Exercise 18: Portfolio Optimization

Given 5 prediction markets with current prices and your subjective probabilities, use mean-variance optimization to find the optimal portfolio allocation. Assume your total capital is $10,000 and no position can exceed $3,000.

Exercise 19: Yield Strategy Backtesting

Implement a backtesting framework for the "Complete Set Arbitrage" strategy. Given historical price data for both outcome tokens in a binary market (simulated), calculate the number of arbitrage opportunities, the average profit per opportunity, and the total return over the period.

Exercise 20: Token Lending Economics

If a Yes token trading at $0.90 can be lent at 10% APR on a DeFi protocol, calculate the breakeven probability of the event occurring for the lender. What is the lender's expected return if the true probability is 0.95? What if it is 0.85?

Security and Testing

Exercise 21: Reentrancy Attack Simulation

Write a Python simulation of a reentrancy attack on a vulnerable prediction market contract. Create the attacker contract logic, the vulnerable redeem function, and show how the attacker drains funds. Then show the fixed version using the checks-effects-interactions pattern.

Exercise 22: Oracle Manipulation Scenarios

For a prediction market that uses a price oracle (e.g., "Will ETH be above $5000?"), describe three different oracle manipulation attacks. For each, calculate the minimum profitable attack size given gas costs and oracle manipulation costs.

Exercise 23: Front-Running Detection

Write a Python script that analyzes mempool transactions to detect potential front-running attacks on an AMM-based prediction market. Given a sequence of transactions in a block, identify pairs where: (a) transaction A buys before transaction B, (b) transaction A was submitted after transaction B, (c) transaction A profits from the price impact of transaction B.

Exercise 24: Invariant Testing

Write a property-based testing framework (using hypothesis library) for a prediction market contract. Define the following invariants and generate random transaction sequences to test them: - Collateral invariant (total collateral = total token supply) - No negative balances - Resolution correctness (payout vector sums to 1) - Merge/split inverse (split then merge returns to original state)

Exercise 25: Access Control Audit

Given the SimplePredictionMarket contract from Section 35.8, perform a manual audit: - List all public/external functions and their access controls - Identify at least 3 potential vulnerabilities - Propose fixes for each vulnerability - Write Python tests that verify the fixes

Advanced Patterns

Exercise 26: Combinatorial Market Construction

Design a combinatorial market for two conditions: "Which party wins the election?" (D, R, I) and "Will GDP growth exceed 3%?" (Yes, No). Compute all 6 position IDs. Write Python code to split collateral into all 6 positions and verify the collateral invariant.

Exercise 27: Market Factory Implementation

Implement a Python class MarketFactory that simulates creating parameterized markets. Create a price ladder for BTC at strikes [80000, 90000, 100000, 110000, 120000] with a 3-month expiry. Compute all condition IDs and position IDs.

Exercise 28: Conditional-on-Conditional Position

For two conditions A (binary) and B (binary), compute the position ID for the conditional position "A=Yes AND B=No". Verify that the XOR-based collection ID computation gives the same result regardless of the order of conditions (A then B vs. B then A).

Exercise 29: Automated Market Resolution

Design a system that automatically resolves a prediction market using a Chainlink price feed. Write Python pseudocode for a keeper bot that: 1. Monitors the market's resolution time 2. Fetches the price from Chainlink at the resolution time 3. Calls the resolution function on the market contract 4. Handles failure cases (price feed unavailable, gas spike, etc.)

Exercise 30: Full System Integration

Combine all components from this chapter into a complete prediction market system in Python: 1. Create a market (compute condition ID) 2. Split collateral into outcome tokens 3. Simulate trading on an order book 4. Resolve the market 5. Redeem winning tokens 6. Calculate final P&L for all participants

Track all state changes and verify the collateral invariant at every step. Print a complete audit trail.