Halborn Logo

// Blog

Why TWAP Oracles Are Key to DeFi Security


profile

Rob Behnke

January 25th, 2023


TWAP oracles, pioneered by Uniswap v2 and v3 implementations, have become critical infrastructure for many DeFi applications. But what security benefits do these oracles offer, especially in comparison to other oracle implementations? 

In our prior article, we provided an overview of TWAP oracles. In this article, we’ll explore how TWAP oracles improve security for DeFi protocols. We also compare TWAP oracles with VWAP oracles and similar implementations such as spot price oracles. 

TWAP vs VWAP oracles 

In the previous article, we explained that TWAP (Time Weighted Average Price) oracles are queried by smart contracts for the average price of certain tokens across a predefined time frame. TWAP oracles sum the price of an asset at different points in time and divide by the total duration to arrive at an average price. 

We also explained that TWAP oracles are similar to VWAP oracles (made prominent by Chainlink) as both use weights in calculating values. In a VWAP (Volume Weighted Average Price) oracle, the weight refers to the volume of an asset traded on a particular exchange during a specific period. 

A VWAP oracle multiplies the price of an asset (as quoted by an exchange) by the volume of the asset traded on the exchange during that period. These values are summed and then divided by the total volume of the asset on all exchanges surveyed. This formula takes the form of (V1 x P1 + V2 x P2…+ Vn x Pn) / n where V and P and n are volume, price, and total volume, respectively. 

We calculate the current average price of ETH during a specific trading period using the VWAP mechanism in the example below to illustrate the concept. Note that this is a simplified example and may not cover more technical details about the VWAP implementation:

  1. Exchange 1 sold 150 ETH tokens at $1,300. V1 (150) x P1 (1300) = 195,000
  2. Exchange 2 sold 200 ETH tokens at $1,200. V2 (200) x P2 (1200) = 240,000 
  3. Exchange 3 sold 100 ETH tokens at $1,250. V3 (100) x P3 (1250) = 125,000. 
  4. Using the VWAP formula gives $1,244 as the average price of ETH. This is calculated by dividing the sum of the product of volume and prices (560,000) by the total volume (450).

Having explored how VWAP oracles work, let’s dive into the reasons a TWAP oracle may be a better option for developers in certain cases. 

Advantages of TWAP oracles 

Simplicity and efficiency 

TWAP oracles use a simple algorithm for calculating asset prices, making them simple and cost-effective to implement on-chain. Other oracle implementations like VWAP oracles have more complex mechanisms that involve off-chain and on-chain components. Although this isn’t bad per se, the simplicity and efficiency of TWAP oracles might make them suitable for certain applications. 

Decentralization and censorship resistance 

VWAP oracles have some advantages over TWAP oracles. For example, TWAP oracles cannot give prices of an asset over a small interval, as this reduces the cost of a price manipulation attack. Also, TWAP oracles are restricted to providing prices of assets sold on one exchange whereas VWAP oracles can source data from multiple trading environments. 

However, a key feature TWAP oracles have is decentralization and censorship resistance. TWAP oracles are solely controlled by smart contracts and don’t rely on oracle nodes to provide trusted information about the price of an asset. 

This also makes them resistant to censorship. A VWAP oracle cannot function if off-chain oracle nodes refuse to update prices, leading to DeFi smart contracts executing with stale prices. 

Safety from collusion 

Some VWAP oracles implement staking to prevent malicious activity among reporters. The idea is that if a reporter provides inaccurate prices or withholds the information, they can be slashed. 

However, the security of this approach relies on the assumption that some reporters are honest. But all reporters can collude and feed the oracle with false information in which case no one will try to report misbehavior. 

A TWAP oracle solely relies on trading data stored in the DEX’s smart contracts when calculating prices. Since the information is on-chain, the possibility of actors colluding to deceive the oracle into reporting incorrect prices is reduced. 

Protection against flash loan attacks 

Spot price oracles (provided by AMM DEXes) calculate the price of an asset by simply dividing the amount of the asset against another asset  in a two-asset liquidity pool. 

The problem with this approach? An attacker could drain liquidity from one side of the pool using a flash loan and thus trigger the price oracle to quote an abnormally high price for an asset. Since flash loans are typically borrowed without any collateral, spot price oracles become targets of risk-free manipulation attempts

A TWAP oracle programmed to measure prices over a long interval is protected to some degree against flash loan attacks. The TWAP algorithm takes into account the price of an asset at the end of the previous block; hence, this rules out the single-transaction exploit where an attacker drains liquidity via a flash loan and promptly sells an asset at an inflated price in the same transaction. 

Are there any downsides to using TWAP oracles? 

As explained, TWAP oracles provide the average price of an asset measured during a previous trading period, not the spot price. This may be a non-issue, particularly if the market experiences low-to-mild volatility (which means prices are relatively stable). 

However, lagging indicators from a TWAP oracle can be problematic when market conditions cause increased price volatility. Prices from a TWAP oracle would thus fail to reflect market-wide changes in trading conditions—an issue that could affect a variety of DeFi applications. 

For example, consider a lending protocol that uses a one-hour TWAP to calculate the value of assets. Now imagine the price of a collateral asset falls sharply—say, by 50%—in 15 minutes. This occurred in the case of the Ankr and Helio hacks where an attacker exploited the lagging price oracle used by Helio to steal $19 million from the protocol.

Typically, protocols (via arbitrageurs) would liquidate the borrower’s position before the collateral becomes extremely undervalued. But since the TWAP oracle measures prices over a one-hour interval, it only reports a mild change (for example, 5-10%), which is a large deviation from the current market price. 

Thus the debt position becomes unprofitable to liquidate since the debt is worth more than the underlying collateral. Moreover, debtors would have little incentive to liquidate their positions, saddling the system with bad debt and forcing lenders to take a loss. 

The issue of TWAPs deviating from market-wide prices isn’t restricted to lending protocols, but can also affect DeFi applications like algorithmic stablecoins and rebase tokens. These applications need access to up-to-date information about the value of certain assets to monetary policy—something TWAP oracles can hardly provide. 

Conclusion

TWAP oracles have great qualities like being simpler to use and providing a fully on-chain and censorship-resistant source of information for DeFi smart contracts. Using a TWAP oracle does come with drawbacks such the inability to get the most up-to-date prices or get prices for a broader range of assets (including off-chain assets like the US dollar). 

Besides, TWAP oracles aren’t totally immune to any form of manipulation. Particularly with the switch to Proof of Stake, the possibility of manipulating TWAP oracles over multiple blocks has increased—but an economic attack of this type is considered largely infeasible for the most part. 

One way to avoid the issues with TWAP oracles is to use a VWAP oracle (like Chainlink) in normal situations and use a TWAP oracle as a fallback in case oracle nodes start acting maliciously. This gives developers the best of both worlds: access to fresh prices and broad market coverage that VWAP oracles provide and the decentralization and censorship resistance of TWAP oracles.

© Halborn 2024. All rights reserved.