DeFi Oracles: V3 TWAPs, Pyth & Optimism

Why Spot Prices are dangerous. The physics of Geometric Mean TWAPs (Uniswap V3), Confidence Intervals (Pyth), and Optimistic Oracles (UMA).

Intermediate 45 min read Expert Version →

🎯 What You'll Learn

  • Deconstruct Uniswap V3's Geometric Mean TWAP
  • Analyze Pyth's Confidence Intervals in Liquidation Logic
  • Trace an Optimistic Oracle Dispute (UMA)
  • Calculate the cost of manipulating a 30-minute TWAP
  • Audit a Price Feed for 'Heartbeat' risks

Introduction

Chainlink is the King of “Push” Oracles. But for Derivatives and Prediction Markets, we need more. We need High Frequency (Pyth) and Subjective Truth (UMA). And for protocols that want zero external dependencies, we have the TWAP (Time-Weighted Average Price).

This lesson explores the exotic edge of Oracle Physics.


The Physics: Uniswap V3 TWAP (Geometric Mean)

V2 stored the Cumulative Price. V3 stores the Cumulative Log Price.

Why Logarithms? Because the Geometric Mean of the price ratio is equal to the ratio of the Geometric Means. log(PaPb)=log(Pa)log(Pb)\log(\frac{P_a}{P_b}) = \log(P_a) - \log(P_b) This allows us to calculate the TWAP of any pair (Tick) purely by subtracting two cumulative values, regardless of which token is “Attribute 0” or “Attribute 1”.

Physics:

  • Manipulation Cost: To move a 30-minute TWAP by 5%, you must hold the spot price at +1000% for 90 seconds (costing massive arbitrage losses), or +5% for 30 minutes.

Deep Dive: Pyth (Confidence Intervals)

Chainlink gives you a number: $2000. Pyth gives you a distribution: $2000 \pm $10.

Physics: Markets are never perfect. During volatility, the bid-ask spread widens on Binance. If Pyth reports $2000 \pm $50, the protocol should be conservative.

  • Longing? Use $2050.
  • Shorting? Use $1950.
  • Liquidating? Use the value that favors the user to prevent unfair liquidations during chaos.

Architecture: Optimistic Oracles (UMA)

How do you ask: “Did Trump win the election?” Code cannot verify this. Humans must.

The Game:

  1. Request: “Who won?”
  2. Proposer: bonds money and says “Trump”.
  3. Dispute Window: 2 hours.
  4. Disputer: Can bond money to say “False”.
  5. DVM: If disputed, UMA token holders vote. The winner takes the loser’s bond.

Physics: This assumes Honest Majority. If the cost to corrupt UMA token holders > Profit from lying, the system works.


Code: Using a V3 TWAP

import "@uniswap/v3-core/contracts/libraries/OracleLibrary.sol";

function getTwap(address pool, uint32 secondsAgo) public view returns (uint256) {
    // 1. Get Cumulative Ticks from the Pool
    (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(
        new uint32[](2) {secondsAgo, 0} 
    );
    
    // 2. Calculate Average Tick
    int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
    int24 arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));
    
    // 3. Convert Tick to Price (Base^Tick)
    return OracleLibrary.getQuoteAtTick(
        arithmeticMeanTick,
        1e18, // Base Amount
        tokenA,
        tokenB
    );
}

Practice Exercises

Exercise 1: The TWAP Shield (Beginner)

Scenario: You hold a 5% TWAP requirement. Attack: Flash Loan pumps price by 50% for 1 block (12s). Result: TWAP moves by 12s1800s×50%0.3%\frac{12s}{1800s} \times 50\% \approx 0.3\%. Attack failed.

Exercise 2: Confidence (Intermediate)

Scenario: Pyth reports BTC 20,000±20,000 \pm 1000. Task: User wants to borrow against BTC. LTV 80%. Logic: Protocol values BTC at 19,000(LowerBound).MaxBorrow=19,000 (Lower Bound). Max Borrow = 19,000 * 0.8 = $15,200.

Exercise 3: UMA Dispute (Advanced)

Scenario: A Prediction Market settles incorrectly. Action: You post a bond to dispute. Risk: If token holders are bribed or apathetic, you lose your bond.


Knowledge Check

  1. Why does V3 use Logarithms for TWAP?
  2. What is a Confidence Interval?
  3. Why are Optimistic Oracles slower?
  4. How does TWAP prevent Flash Loan attacks?
  5. What happens in a UMA dispute?
Answers
  1. Math. To accurately track the Geometric Mean of the price ratio.
  2. Uncertainty. The range within which the true price likely lies.
  3. Dispute Window. Humans need time to verify and challenge (e.g., 2 hours).
  4. Averaging. Short-duration spikes are diluted by the long-duration average.
  5. Voting. Token holders vote on the truth. Winner takes loser’s bond.

Summary

  • TWAP: Math Shield.
  • Pyth: High-Frequency Uncertainty.
  • UMA: Subjective Truth.

Questions about this lesson? Working on related infrastructure?

Let's discuss