In traditional finance, there are many different measures of an asset's average price. It is advisable to be aware of those mechanisms in the DeFi oracles as well, because of the security mitigation they bring.

The TWAP (time-weighted average price) is believed to be a reliable average price that can be applied securely to DeFi protocols. How does it work and what pros and cons does it have?

Is there any better alternative to use?

Let’s discuss time-weighted average prices

We all already know that spot price, calculated as the ratio between the assets’ reserves, is extremely prone to manipulation. Past cases indicate that smart contracts using them as oracles can be effortlessly rekt (hooray flash loans) by a sandwich attack.

To deal with this problem, UniswapV2 first introduced the concept of time-weighted average prices (TWAPs in short), which is used amongst decentralized oracles. In Layman’s terms, it’s about calculating the average price based on some chosen period of time with the use of the cumulative price (cumulative tick in the case of UniswapV3). This value reflects the sum of the spot prices at each second of the entire trading pair’s existence.

TWAP can be calculated for the chosen ERC20 tokens pair by dividing the cumulative price by the length of the desired interval from the beginning and the end of this interval. So if the price rate comes from multiple blocks the attacker has to keep the manipulation for the entire duration of the readout.

TWAP V2

TWAP mechanism was improved in UniswapV3 by calculating the geometric mean of relative prices for both assets in an arbitrary pool. Instead of accumulating the sum of prices, it tracks the sum of the logarithm of the prices (the price in V3 is stored as the square root without calculating it in the contracts). Uniswap V3 uses concentrated liquidity though. This approach lowers price slippage by making sure that most of the liquidity is provided at a small range around the effective, real price.

Unfortunately, it also makes it easier for manipulation attacks.

In DeFi oracles manipulation exploits, the attackers swap a large amount of one asset in the pool, to create an inflated oracle update. For the attack to be effective, the manipulated price should be kept for several blocks (at least one - therefore attack can’t work with flash loans), so as to the higher asset price corporate in the TWAP value. After that, they need to redeem incurred costs by making a reverse exchange in the next block. The attack’s success depends on the achieved deviation between the wider-market spot price and the manipulated spot price, and how many blocks the price manipulation is held for.

From the security perspective, the TWAP approach is based on the assumption that arbitrageurs will front-run de-manipulating transactions and keep the attack very expensive and not profitable for the attacker.

Among the advantages of TWAPs, one can point to the simplicity of calculations, inexpensive executions, and certainly better protection against price manipulation than the spot price. However, there are some tradeoffs that put the user experience or even funds at risk.

Data feed accuracy and freshness

Using the price average over many blocks increases the costs of manipulation, while a shorter TWAP value follows closely the sport price. It’s fine at the time of low fluctuations, but it becomes problematic in the high volatile time because the TWAP does not respond to the real condition of the market. So in case of rapid price shifts, the TWAP will deliver β€œoutdated”, stale prices derived from past quotations. This may be the case during rug-pulls, rapid market collapses, and growths or exploits. Sadly, inverse proportionality between data accuracy and security is inevitable in this case.

Scalability of security

This inverse proportionality leads to the impossibility to optimize both outside data accuracy and security at the same time, making it hard to scale the security in the long term. So, the only, but capital-inefficient way for scaling this solution is to increase the liquidity on the tracked market, making it more expensive to manipulate, because the attack will require more assets to occur. It is especially important to have some liquidity across the entire range in the case of Uniswap V3 which implements concentrated liquidity - it significantly increases the cost of potential attack. However, there is no certainty that the liquidity will not change over time.

Market coverage

TWAPs have another limitation - they can only represent the price action from a single trading environment, such as AMM DEX. It means that the delivered price data don’t reflect the global markets. Furthermore, a sufficient level of security is dependent on a sufficient level of liquidity, which can shift over time.

Concentrated liquidity even significantly lowers the cost of manipulation, compared to the full-range method.

TWAT

Based on x*y=k equation, if somebody wants to move the price, the price impact increases. When the liquidity is concentrated between some limited price range, attackers can push out an asset’s price out of that narrow range, up to max tick limit (practically to infinity). In addition, due to the lower slippage, attackers have much less risk of being arbitrage (as seen in the case of one of the Rari exploits).

Diversity of assets

Quite an obvious thing is that TWAP pricing is limited only to feeds for ERC20 tokens against other ERC20 tokens that are available on specific exchanges. It is impossible to receive information about TradFi stock prices, real-world events, commodities or even fiats exchange rates.

Remember to not assume the USD exchange rate based on any stablecoin price - it can result in false output during high volatility/deppeg time.

What does price manipulation look like in PoS world ?

The easiest way to manipulate the calculated average is to manipulate a single block, instead of doing that in all blocks of the TWAP period. Euler Finance released a tool, which basically give an answer to following question:

The price of an attack

At the time of writing (crypto winter ~1550 USD/ETH), capital required to move the DAI price up 30% in one block attack in ETH/DAI UniswapV3 pool for 30-min (144 block TWAP) is equal to $4,7 trillions of WETH.

Put in another way, it is far too expensive to ever be done.

Target TWAP

However, the merge on Ethereum mainnet changed some principal assumptions for TWAP price oracles. During the PoW time it was impossible to know who would mine the next block. The next miner was unknown until the current block would be accepted by the network. Manipulators then need to compete in the open auction in order to backrun their manipulation.

In PoS Ethereum, time is divided into slots (12 seconds) and epochs (32 slots). Validator is randomly selected in every slot to be a block proposer. The block proposer has to know one epoch before if they will be proposing the next block. That is to say, the information who will propose the current and next epoch is publicly available. Thus, if validators know what block they will be proposing, it may allow them to create manipulation in the previous block with no cost and arbitrage risk as they control ordering in the next block.

It is also theoretically possible for an attacker who runs a validator to know that they propose 2 blocks in a row or even more. In that case, an attacker can manipulate the market in the first, keep manipulation during all the controlled blocks and send a transaction to rebalance the price at the beginning of the last controlled block, avoiding arbitrage.

What is more, it’s not that difficult to propose two blocks in a row. The cost of attack decreases significantly the more blocks we control in a row. However, at the time of writing, that attack did not occur yet. Perform risk analysis and take into account the fact that the TWAP price can be manipulated.

OK, let’s point out another approach - VWAP.

The other approach, different from TWAPs, is called Volume-Weighted Average Price (VWAP) and it is widely used across traditional finance. In DeFi it was firstly introduced by Chainlink Price Feeds.

In this mechanism, the price of assets is calculated by taking price data from multiple environments. This algorithm requires information from various sources, so it resolves the problem of feed centralization. Each delivered price is weighted by the volume from each market that this asset is trading on. This mechanism makes it easier to mitigate the majority of issues known from TWAPs.

VWAP calculations are based on assumptions, including reflecting the assets price from both centralized and decentralized exchanges, weighting it by real transactions volume, without fake values, to better reflect the global supply and demand of the asset. The VWAP algorithm is more resistant to manipulation, because it relies on multiple entities, thus making it harder for attackers to manipulate the majority of asset’s trading market.

Be aware that data feed in this approach isn’t gathered directly from the source, but is transmitted by centralized relayers - it is a requirement that off-chain oracles have to work properly.

If you want to use that oracle, check how the process of becoming a trusted relayer looks like.

Summary

It is crucial for DeFi protocols to obtain accurate, tamper-proof, and real-world data. The most important thing is to be aware of limitations, disadvantages and advantages of different mechanisms we use.

The security level of TWAP feed mostly depends on how much liquidity is in the pool and how effective arbitrageurs will be in returning the manipulated price back to the wider-market counterpart.

From the security viewpoint, you must ensure that the attacker's cost to back-running is greater than the value gained from manipulation.

If you rely on UniswapV3 TWAP remember, that in case of concentrated liquidity even small amounts of liquidity deposited across the entire range can significantly increase an attacker's cost for inflating a price in the pool.

Regardless of the price feeds you are using, always consider risk factors in your threat analysis. To help you with that we have created special categories I3 and C3 in the Smart Contract Security Verification Standard v2, check them out!

Jakub ZmysΕ‚owski

Jakub ZmysΕ‚owski

Smart Contract Security Auditor

About the author

White Hat and smart contract security researcher. Participant of the first edition of Secureum Bootcamp. Professionally dealing with security since 2021. Passionate about DeFi.

View all posts (2)