Blog

Everything you ever need to know about TWAP Oracles

Everything you ever need to know about TWAP Oracles

Time-Weighted Average Price, this is what a TWAP oracle is based on. Understanding their operation and potential vulnerabilities is important knowledge for auditors. Let's dive into the nuances of TWAP oracles, illustrating their function and highlighting the concerns that can arise, as evidenced by the recent exploit of Compound V2.


How TWAP Oracles Work

TWAP oracles are designed to provide a more stable and manipulation-resistant measure of asset prices over time. Unlike simple spot prices, which capture the price at a specific moment, TWAP calculates the average price of an asset over a specified period. This mechanism is often used by different protocols to prevent manipulation attacks.

The core idea behind a TWAP oracle is to accumulate price values over time, which requires tracking the cumulative price at various intervals. This is typically achieved by recording the cumulative price each time an event (like a swap) occurs, which affects the price. The calculation involves updating a cumulativePrice variable by adding the product of the current price and the time elapsed since the last update.

When you need to determine the average price between two points in time, the process involves fetching the cumulative prices at these moments, calculating the difference between them, and then dividing this by the time elapsed between the two points. The formula looks something like this:

This method smooths out price fluctuations over the specified period, providing a more consistent price metric that's less susceptible to momentary market manipulation.


The Problem with TWAP Oracles

Despite their benefits, TWAP oracles are not without their vulnerabilities. Two main issues stand out:

Lag in Reflecting Real-Time Prices:
Because TWAPs are based on historical data, there's an inherent delay in reflecting current market conditions. This can be problematic in volatile markets where prices change rapidly.

Potential for Manipulation:
Although TWAP oracles are designed to be more resistant to price manipulation, they are not immune. The mechanism that triggers the TWAP update can be exploited. For instance, if the oracle updates at fixed intervals, an attacker can execute trades that artificially inflate or deflate the price right before an update. This manipulation affects the cumulative price calculation, leading to a skewed TWAP.

The recent exploit of Compound V2 underscores the limited use-case of TWAP oracles. Not only due to their inherently incorrect price reflection but also by manipulating the price used by the TWAP oracle, attackers can create favorable conditions which can finally lead to sophisticated exploits.