TWAP Oracles Vs. Chainlink Price Feeds: A Comparative Analysis

This article was originally published on Smart Content and appears here with permission.

The announcement of Uniswap V3 has given rise to various questions regarding how Uniswap’s Time Weighted Average Price (TWAP) oracles compare to Chainlink LINK/USD Price Feeds. While both of these price oracle solutions provide exchange rates between various Ethereum-based tokens, there are many significant differences that are not immediately obvious but have serious consequences for users.

We present our analysis on why we believe TWAP oracles to be unsuitable for the vast majority of DeFi use cases, as well as how Chainlink Price Feeds overcome such limitations to provide a superior price oracle solution for the DeFi ecosystem. The main focuses of the comparison are as follows:

Price Precision

  • TWAP is a lagging indicator that becomes out of sync with the market-wide price during times of moderate to high volatility, leading to inaccurate data being consumed by smart contracts that put protocols at risk of under-collateralization.
  • Chainlink Price Feeds use a Volume Weighted Average Price (VWAP) to deliver accurate, real-time financial market data regardless of market volatility.

Security/Accuracy Optimization

  • TWAP oracles have an inverse relationship between tamper-resistance (security) and freshness (accuracy), meaning users need to optimize for one or the other, but cannot achieve both simultaneously.
  • Chainlink Price Feeds can maximize tamper-resistance (security) and freshness (accuracy) at the same time without an inverse correlation.

Market Coverage

  • TWAP oracles only consist of prices from a single exchange, resulting in a significant lack of market coverage that doesn’t account for liquidity fragmentation across trading pairs, CEXs, competing DEXs, differing DEX versions, or DEXs ported to other blockchain networks.
  • Chainlink Price Feeds provide full market coverage by tracking prices on all exchanges (CEXs & DEXs) and weighting them by real volume, serving as a future-proof, set-and-forget oracle mechanism that automatically tracks new liquidity fragmentation.

Scaling Security

  • TWAP oracles do not have scalable security, as the only methods of increasing security are either incredibly capital intensive or result in stale/inaccurate data during volatility.
  • Chainlink Price Feeds provide numerous ways for an oracle network to increase its security as it rises in value secured, such as adding more nodes, data sources, and crypto-economic security like higher node payments and implicit/explicit staking.

Feed Diversity

  • TWAP oracles only provide the exchange rate between two on-chain tokens, meaning it cannot provide financial market data on real-world assets like commodities, forex, stocks, indexes, or tokens priced in fiat currencies.
  • Chainlink oracle networks can connect smart contracts to any external data resource including any type of financial market data, real-world events, off-chain computation, data privacy solutions, and much more.

NOTES: The information presented applies to all TWAP oracles derived from AMM DEXs, not just Uniswap. The limitations of AMM DEXs as price oracles do not diminish their immense value proposition, particularly the ability to provide decentralized, permissionless, and non-custodial token swaps. Finally, for simplicity, we use “TWAP oracle” to mean any TWAP generated by an on-chain AMM DEX, even though technically a TWAP could be generated from any data source.

What is an AMM DEX?

Before examining the limitations of a TWAP, it’s important to understand what an AMM DEX is and how it generates exchange rates for users. If you are already familiar with this concept, feel free to skip this section.

A decentralized exchange (DEX) is an application powered by smart contracts that allow users to trade assets on a blockchain network in a decentralized, non-custodial, and peer-to-peer manner. However, instead of using traditional bid/ask order books to make liquidity available, most common in centralized exchanges (CEXs), an Automated Market Maker (AMM) uses pre-funded liquidity pools for all asset swaps on the DEX.

In simple AMM models, the liquidity pool is a smart contract that allows Liquidity Providers (LPs) to deposit equal amounts of two tokens (e.g., $100 of ETH and $100 of USDT for the ETH/USDT liquidity pool), which traders can use to swap between those two tokens. The LPs earn trading fees (e.g. 0.3% of each trade) in compensation for their liquidity provisioning and still hold the same cumulative value of assets post-swap (ignoring impermanent loss). As a result, users and other smart contracts are provided access to immediately available liquidity for just a small fee.

The exchange rate in an AMM liquidity pool is determined by a bonding curve, which depends on the relative amount of liquidity on each side of the pool. While there are different types of bonding curves with various design considerations, as explored in this Chainlink article, the concepts within this article apply to all types of AMMs. Uniswap in particular uses an X*Y=K bonding curve where K is a constant value 1, X is the amount of token0, and Y is the amount of token1. If the amount of token0 increases, then the amount of token1 must decrease (and therefore the exchange rate changes proportionally) and vice versa.

Different types of AMM curves which determine the exchange rate of tokens based on the relative amount of tokens in each side of the pool (source)

The exchange rate offered by an AMM is managed through arbitrage, where automated bots have a self-interested economic incentive (aka profit) to rebalance the pool’s exchange rates to match other exchanges. For example, this can take the form of buying a token on an AMM with a lower price and selling it on a different exchange with a higher price, both earning a profit and creating equilibrium across the two exchanges. Arbitrage is the reason why AMMs usually provide users with fair market value on swaps (ignoring slippage).

Because AMMs manage an exchange rate (which is already on-chain) for each trading pair, some have assumed that this data could be used as a censorship-resistant price oracle within DeFi protocols. However, it’s not so straightforward and comes with numerous hidden limitations that put users’ funds at serious risk.

Why TWAP?

The naive way to use an AMM liquidity pool as a price oracle is by simply dividing the number of tokens currently residing within each side of the pool to get an exchange rate.

Example: a pool with 2 WBTC and 120,000 USDT would generate a price of 60,000 USDT per WBTC and 1/60,000 WBTC per USDT.

While this does provide the current spot price of the liquidity pool, it’s extremely vulnerable to manipulation. Smart contracts using AMM spot prices as oracles can be easily exploited through sandwich attacks — an attack vector where a malicious entity makes a large trade within an AMM liquidity pool to shift the price in their favor, then uses that distorted pricing to unfairly siphon value from smart contracts using that AMM liquidity pool as a spot price oracle.

Normally, such an attack would only be possible by well-capitalized entities like whales, but flash loans — temporary uncollateralized loans which are only valid if paid back in full before the end of the transaction — allow anyone in the world to become a temporary whale and perform such a sandwich attack. This is not a theoretical issue either; millions of dollars in user funds have already been lost due to protocols relying on an AMM spot price as an oracle (e.g., warp.finance and bZx, who both upgraded to Chainlink to resolve this issue). It is therefore highly recommended, even by Uniswap, to avoid using AMM spot prices as oracles because they can (and will) be manipulated, resulting in user losses.

A theoretical example is shown below of how a flash loan can be used to manipulate and siphon funds from a money market DeFi protocol by manipulating the price of a single DEX; all of these steps happen in a single transaction. (source)

To mitigate sandwich attacks, AMM DEXs began offering Time Weighted Average Price (TWAP) oracles. TWAP is a pricing methodology that calculates the mean price of an asset during a specified period of time. For example, a “one-hour TWAP” means taking the average price over a defined hour of time. Since flash loans only exist within a single block, taking a TWAP value over multiple blocks is immune to such attacks.

The most widely known TWAP oracle is from Uniswap, both in its current V2 and upcoming V3 release. A common TWAP implementation used in both Uniswap versions involves taking two snapshots at different points in time, tracking both the timestamp and historical sum of prices for each, and using this information to calculate a final TWAP data point (shown in the image below). In V2, snapshotting is a manual process (or outsourced to Keep3r), while V3 outsources the process to Uniswap traders. By default, Uniswap V3 supports a ~13-second TWAP, but can be extended up to ~nine days by paying a one-time gas fee per trading pool.

The TWAP calculation methodology supported by the Uniswap V2 AMM (source)

While using on-chain data as your price oracle sounds idealistic, in practice, there are a number of trade-offs that exist. These limitations put user funds at risk, ultimately preventing the usage of TWAP oracles at scale for the vast majority of DeFi applications. These issues are simply inherent limitations of TWAPs calculated from AMM DEXs, meaning they can only be solved by using a non-TWAP and non-AMM oracle solution like Chainlink Price Feeds. We explore such limitations below and how Chainlink Price Feeds mitigate them.

The Limitations of TWAP Oracles

Freshness/Accuracy

By design, a TWAP is a lagging indicator and does not provide the current spot price, but instead an average value taken over a previous time period. This is largely fine during periods of low volatility (as the price value doesn’t change much), but it can become a significant issue during times of moderate-to-high volatility because the TWAP becomes out-of-sync with the global market-wide price. If the price of an asset rapidly shifts in one direction, the TWAP will deliver stale pricing data since it’s derived from the past and not enough time has gone by for it to catch up. This dynamic results in tamper-resistance (security) being inversely correlated with freshness (accuracy), meaning developers are forced to prioritize one property or the other, but cannot realistically achieve both simultaneously.

Adjusting the length of time that a TWAP covers (e.g. 10-minute TWAP vs. 10-hour TWAP) has the following implications:

  • Longer TWAP: higher tamper-resistance (more expensive to manipulate) but less accurate data (becomes stale during volatility).
  • Shorter TWAP: more accurate data (stays fresh during volatility) but reduced tamper-resistance (lowering the cost of manipulation).

The inverse correlation between security and accuracy is inevitable in a TWAP, making it highly undesirable since DeFi applications require price oracles that are simultaneously maximally tamper-resistant and accurate. Because a low level of tamper-resistance is a non-starter for high-value applications, the majority of TWAP oracles tend towards tamper-resistance by using a time sample between 30 minutes to 12 hours. While a TWAP time sample in this range may work during periods of low volatility, moderate volatility is common in cryptocurrency markets, and both extreme volatility (e.g. Black Thursday) and rug-pulls/exit-scams (e.g. Compounder) have numerous historical examples that result in asset prices rapidly changing (often in the form of a collapsing valuation). In each case, the TWAP will return stale data that is inaccurate during such volatility.

Data showing the deviation between Uniswap v2's ETH/USDC 10 minute TWAP oracle and Chainlink’s ETH/USD Price Feed (Source)

To showcase the implications, let’s look at a theoretical, but plausible example of a decentralized money market using a one-hour Uniswap TWAP. The money market appears to be working during times of low volatility. However, market volatility suddenly increases and the price of a token used as loan collateral drops 50% linearly in ten minutes (this is crypto, it can happen). Normally, the protocol would have plenty of time to liquidate this position before the collateral drops too far in value (Ethereum produces ~48 blocks in ten minutes). However, because a TWAP of one hour was used, it has not had enough time to catch up and only reports a drop of 5% after this ten-minute period (a 62% deviation from the true market-wide price).

Because of the TWAP pricing deviation, the protocol is unable to liquidate the position within an adequate amount of time and the debt is now worth more than the underlying collateral, resulting in an undercollateralized position. Even when the TWAP oracle catches up and reports the correct price, it will be too late and the position cannot be fully liquidated. The lenders will have to eat the loss due to it being a toxic debt position, as the borrower has zero incentive to pay it back because their loan is now worth more than their collateral.

While an extreme example, this is the exact type of issue that can occur if a TWAP oracle is used during times of volatility, as well as during less drastic situations. Reducing the time sample down to ten minutes or below is not an adequate solution either because it would reduce the price oracle’s tamper-resistance by at least an order of magnitude. Such inaccurate pricing during volatility can also adversely affect other categories of DeFi applications such as algorithmic stablecoins and rebase tokens whose monetary supply relies upon pricing data to ensure a peg is properly held.

Chainlink Price Feeds avoid the issue of stale price data by not using a TWAP calculation methodology, instead opting for the Volume-Weighted Average Price (VWAP) based on data from aggregators. VWAP calculations from data aggregators involve fetching price data from all liquid exchanges (both centralized and decentralized exchanges), weighting it by real volume, and removing outliers and fake volume to arrive at a single price point that reflects the global market price. These Price Feeds update on a deviation threshold basis (e.g. every 0.3% movement in price) and on a heartbeat basis (e.g. every 1 hour) to ensure accurate data is always available to smart contract applications at any point in time.

Chainlink ETH/USD Price Feed with 0.5% deviation threshold and 3hr heartbeat on the Ethereum Mainnet (source)

Since price data is fetched from off-chain sources and delivered on-chain asynchronously, flash loans have zero effect on Chainlink Price Feeds (as flash loans only exist on-chain within a single block). This prevents the issues that TWAP oracles attempt to solve, without compromising on accuracy during market volatility. While TWAP oracles have niche use cases, the real-time, volume-weighted price is what the majority of DeFi applications require to keep user funds safe.

Important to note: AMM DEXs like Uniswap are limited to TWAP feeds, while Chainlink Price Feeds can leverage any pricing calculation methodology, including VWAP, TWAP, or various other custom calculations. However, VWAP is the most common pricing method not just in DeFi, but in traditional finance too.

Market Coverage

Another fundamental issue of TWAP oracles is their lack of market coverage — the number of exchanges an asset’s price takes into account relative to all the exchanges the asset currently trades within. A TWAP only represents the price action of a single AMM DEX, meaning any smart contract relying on this price data is only exposed to a small sliver of the total trading market. This lowers the difficulty of pulling off an attack, as a malicious actor only needs to manipulate a single exchange, rather than thousands of trading markets across hundreds of centralized and decentralized exchanges at the same time.

The tamper-resistance of a TWAP oracle can be increased by extending the time sample taken, but only at the expense of reduced accuracy, making it impractical as a long-term solution. Regardless, extending the time sample still doesn’t provide full market coverage because only a single exchange is being tracked. There are a number of other dynamics in regards to market coverage that need to be taken into consideration too beyond the time sample of the TWAP.

Even if the AMM DEX being used to calculate the TWAP oracle has a sufficient level of liquidity, there is no guarantee that the liquidity will not shift to a different exchange and unexpectedly lower the cost of manipulation. Increasing the TWAP time sample to compensate for such an attack would only result in stale pricing, making it a non-solution to the issue. The shifting of liquidity/volume across exchanges is a problem for all oracles that fetch prices from only a single exchange.

Single source oracles cannot account for volume/liquidity shifts across exchanges (source)

Especially with the rapid innovation in DeFi, it’s entirely unpredictable how on-chain liquidity will shift. New protocols and networks are being launched constantly, leading to several forms of liquidity fragmentation happening within DeFi today:

  • Competing DEXs: The competition in the AMM space is fierce, with some protocols even deploying vampire attacks to quickly siphon liquidity away from leading DEXs. This results in liquidity fragmentation, as existing and future AMMs compete for liquidity.
  • Same DEX, Different Versions: Some AMMs have opt-in versioning for updates, meaning when a new protocol version is released, such as Uniswap V3, liquidity can be fragmented across two different AMM versions before all LPs have switched over. This results in liquidity fragmentation for a period of time after a new version release.
  • Same DEX, Different Chains: In order to stay competitive, AMMs are launching support for new blockchains, such as Sushiswap’s expansion to Fantom, Polygon, xDai, BSC, and Moonbeam. Uniswap V3 will launch on both Ethereum and the Optimism layer-2 network, further fragmenting its own liquidity.
  • Same DEX, Different Trading Pair: AMMs use isolated trading pools, where a single asset may have liquidity for a specific token across several different pools (e.g. LINK/ETH, LINK/USDT, LINK/USDC, etc.), fragmenting liquidity for an asset within a single AMM.

Because TWAP oracles only track a single trading market on a single version of a single AMM on a single blockchain, liquidity fragmentation can have significant side effects for any smart contracts relying on this data as a source of truth on market pricing. In addition to these known unknowns, there are also unknown unknowns, where an entirely new type of decentralized exchange could be created that supersedes the AMM model, potentially resulting in a mass migration of liquidity. We cannot predict the future, and therefore it is never ideal to rely on price data sourced from a single exchange, especially if you hope to set and forget your oracle mechanism with the assumption it will always provide high-quality price data.

Aggregating TWAP oracles that track different AMMs and DEXs via a medianizer does not provide a sufficient solution to market coverage either, as the same inverse correlation between security and accuracy still exists. Mixing low-quality data points doesn’t result in a high-quality data point. Aggregating TWAPs can actually lower the cost of attack since only the most illiquid DEXs need to be manipulated to affect the final medianized data point. It also doesn’t take into account the majority of liquidity/volume that occurs on centralized exchanges. Achieving market coverage means tracking all trading venues (on-chain and off-chain), not just a particular type of exchange that is preferred by a specific set of users or developers. We have already seen what happens when protocols use price oracles that don’t provide full market coverage such as when Compound.finance falsely liquidated $85M of DAI loans based on a irregular price deviation from a single exchange.

Chainlink Price Feeds solves these issues and ensures robust market coverage by leveraging three layers of aggregation: 1) data providers, 2) node operators, and 3) oracle networks.

Chainlink sources VWAP data from multiple professional data aggregators, such as BraveNewCoin, Kaiko, CoinGecko, CryptoCompare, Amberdata, and more. These data aggregators have large full-time teams solely focused on generating high-quality price feeds that reflect global asset prices. Each data aggregator tracks all on-chain and off-chain exchanges, weights each by real volume using refined methodologies to prevent manipulation, fake volume, and other forms of data corruption. Because each Chainlink Price Feed uses multiple data aggregators, a diversity of VWAP-based price calculation methodologies are used to further add resistance to any malicious actors/traders attempting to shift the final aggregated price point.

Chainlink Price Feeds achieve full market coverage using Price Data Aggregators (source)

Each Chainlink node fetches data from at least three independent data aggregators and takes the median value, both preventing API downtime and avoiding any single source of truth. Even more, each Chainlink node generates its median value from a different set of data aggregators to further harden network security. Each oracle network then takes the median value from a multitude of independent nodes to further prevent oracle downtime and malicious/inaccurate node responses. Through these three layers of aggregation, full market coverage is achieved without compromising on tamper-resistance, liveness, or accuracy.

Scalability of Security

If your smart contract application increases in total value locked (e.g. from $10M to $1B TVL), how would you increase the tamper-resistance of your price oracle to enhance protections of user funds? With TWAP oracles, there are two basic ways to achieve this, extending the time sample of the TWAP and/or increasing the amount of liquidity in the AMM pool. Increasing the time sample of the TWAP runs into the same inverse correlation issues of achieving security but reducing price accuracy. Price oracle accuracy during volatility becomes increasingly important as a protocol scales because more user funds are at stake, meaning the length of a TWAP sample can only be increased marginally. Thus, extending the TWAP time sample does not serve as a long-term solution for DeFi protocols scaling in TVL.

The other method is adding liquidity to the AMM pool, but this comes with its own tradeoffs. First, developers deploying their limited capital into an AMM pool is an extremely capital-inefficient way to scale up their oracle’s security. Second, a pool with a relatively high level of liquidity (but security still needs to increase) will be even more expensive to scale in terms of increasing security by a predefined percentage. Finally, users don’t receive strong assurances because liquidity can be removed from an AMM pool just as easily as it can be added. This could occur because of malicious reasons (e.g. a rug-pull) or be entirely driven by economic incentives, such as liquidity moving to a different AMM protocol that provides a higher yield for LPs. LPs are not necessarily loyal to any single AMM protocol.

It results in a double-edged sword: capital is added with the collective knowledge that it may be removed at any point in time, or a time-lockup is enforced to prevent liquidity rug-pulls, but creates an opportunity cost and doesn’t solve the risk that a significant portion of unlocked liquidity goes to competing exchanges. As a result, developers have very few options when it comes to scaling the security of their TWAP oracles.

Chainlink offers a much more flexible and multi-faceted approach to scaling Price Feed security. As the value secured by a Price Feed increases, data requesters have the ability to:

  • Increase the number of premium data sources, further decentralizing the data sourcing and aggregation processes.
  • Increase the number of independent node operators, further decentralizing the data delivery and validation processes.
  • Switch to more expensive but higher quality data APIs and node operators who provide superior guarantees.
  • Pay each node operator more LINK fees per request fulfilled, establishing a higher opportunity cost for malicious activity.
  • Aggregate fees with other users who need the same data, creating shared, collectively funded oracle networks that are more secure than what any project could afford on their own.
  • Upon mainnet implementation, utilize additional security methods like DECO for zero-knowledge proofs and Town Crier for trusted hardware.
  • After the explicit staking launch, require nodes to stake more LINK in a service agreement to create greater crypto-economic incentives for honest behavior.

Overview of the Chainlink Network operating at scale with implicit and explicit staking, user fee pool contract, governance contract, and service agreements (source)

These methods provide developers using Chainlink oracle networks with a wide range of adjustable tools and variables to seamlessly scale the security of a Price Feed. Chainlink security scaling methods are more capital-efficient than TWAP methods and don’t require tradeoffs in price accuracy.

Chainlink Price Feeds have already begun to scale their security to match their increased responsibilities throughout DeFi, such as the ETH/USD Price Feed increasing from 3 nodes initially to 31 nodes currently, and the LINK/USD Price Feed expanding from 9 nodes at launch to now also 31 nodes. With the release of explicit staking, the security of Chainlink oracle networks can be further scaled and quantified for even stronger crypto-economic guarantees. Combining all its security scaling methodologies, Chainlink provides a future-proof oracle solution that better services DeFi’s growing TVL.

Feed Diversity

The final point, and likely the most self-evident, is that TWAP oracles only provide price feeds for ERC20 tokens priced against other ERC20 tokens. For example, a Uniswap pool with AAVE and DAI can provide the AAVE/DAI and DAI/AAVE time-weighted price of that specific liquidity pool. What TWAP oracles cannot do is provide the price of assets that reside off-chain, such as commodities like crude oil and grain, stocks like MSFT and AAPL, forex pairs like GBP/USD and EUR/JPY, real estate like residential and commercial properties, or any other financial market data beyond ERC20 tokens.

Synthetic tokens like sTSLA and mTSLA, both of which track the price of Tesla stock, already use oracle networks to function. Thus, adding these synthetic tokens to an AMM pool to take the TWAP value is a completely unnecessary step. Even when more assets get tokenized and brought directly on-chain (i.e. not just a synthetic), using the TWAP would still not be a suitable solution due to all of the issues explored above.

The market cap of cryptocurrency is $2T+ and the value secured in DeFi is $50B+, however, off-chain markets are still orders of magnitude larger (source)

TWAP oracles also cannot provide the USD/fiat exchange rate of tokens. It is true that stablecoins like USDT, USDC, GUSD, DAI, and sUSD act as a proxy for US dollars, but their peg does not always hold 1:1. The peg of stablecoins are largely dependent on the amount of liquidity in the market and public confidence in the stablecoin’s backing. Using a TWAP oracle for the USD/fiat price is a large assumption around the stablecoin’s peg, which can result in false outputs from a DeFi application if the peg breaks, like during black swan volatility.

As a decentralized oracle network, Chainlink nodes do not have such issues because they can fetch data from any off-chain data source, therefore, can provide the prices on any tradeable asset in the world, whether it resides predominantly on-chain or off-chain. This allows for the creation of Data Feeds on a variety of real-world assets, as well as a wide range of events like the weather, GPS locations, verifiable randomness, and much more (further explored in our Beyond Price Feeds article). Chainlink oracles will also maintain the confidentiality of these datasets while still making the data usable within the execution of smart contracts via technologies like Town Crier, DECO, and Mixicles.

The ability to get virtually any off-chain dataset and off-chain computation through Chainlink makes smart contract development much easier since data feeds can be easily added, adjusted, or switched out with minimal integration work. It also means users don’t have to worry about some part of their protocol using an oracle network with different security and accuracy assumptions, especially when they are much weaker than Chainlink; i.e., TWAP.

Conclusion

Whether its inaccurate price feeds during times of market volatility, extremely weak market coverage, limited options for scaling an oracle’s security, or a lack of feed diversity, TWAP oracles are not suitable for the vast majority of DeFi applications that secure user funds.

While financial market data is only a small part of Chainlink’s generalized utility as a decentralized oracle network, Chainlink Price Feeds provide DeFi with the highest quality price data, backed by the most robust oracle security. These Price Feeds have been time-tested during times of extreme market volatility and blockchain network congestion, continuing to secure billions of dollars of user funds for numerous leading DeFi protocols like Aave, Synthetix, and more. It’s why Chainlink Price Feeds are being adopted at an accelerated pace, and why they have become and continue to be the standard price oracle solution for DeFi ecosystems across all blockchains.

Market News and Data brought to you by Benzinga APIs
Posted In: CryptocurrencyMarketsAMM DEXChainlink Price FeedscontributorsTWAP Oracles
Benzinga simplifies the market for smarter investing

Trade confidently with insights and alerts from analyst ratings, free reports and breaking news that affects the stocks you care about.

Join Now: Free!

Loading...