One of the most critical pieces of the DeFi infrastructure is price Oracles. These little powerhouses serve as the backbone of the system, providing reliable and up-to-date pricing data for all dapps. Without them, the DeFi ecosystem would come to a screeching halt, leaving users and developers in the dark. In this article, let’s dive deep into Uniswap V3- arguably one of the best Oracles in DeFi.
What are Oracles?
Table of Contents
A Price Oracle is like a window into the world of asset prices.
In generous terms, a Price Oracle refers to any source you rely on to obtain price information. For instance, when Pam enquires about the worth of a Schrute Buck from Dwight, he essentially functions as a price Oracle.
Now let’s move to Web 3.
When integrating smart contracts with DeFi protocols, developers face the Blockchain Oracle Problem. They need to find the best way to retrieve the price of an asset on-chain.
Unfortunately, many Oracle designs are created on an ad-hoc basis, leading to varying levels of decentralization and security. It has resulted in high-profile hacks where the Oracle implementation is the primary attack vector.
According to Chainanlysis data, DeFi protocols lost over $400 million in 41 separate oracle manipulation attacks in 2022.
Source: Chainanalysis
But there is hope!
Uniswap offers a solution to build highly decentralized and manipulation-resistant on-chain price Oracles. While there is no one-size-fits-all solution, Uniswap’s approach may satisfy many seeking to build robust protocols.
Moreover, with Uniswap, developers can build confidently, knowing they have a reliable and secure price Oracle to support their smart contracts.
Why do we need Oracles in DeFi?
Price oracles are vital in the DeFi ecosystem, particularly in lending protocols where overcollateralized loans are prevalent.
However, the potential consequences of severe oracle failures are enormous, as they could jeopardize billions of dollars stored in DeFi contracts. This risk is amplified as most DeFi projects rely on a small set of price oracles, making the ecosystem highly vulnerable to a catastrophic event.
Therefore, the safe integration of reliable and secure price oracles is paramount for the continued growth and success of DeFi.
Oracle Attacks
Pricing systems that rely on oracles are susceptible to various vulnerabilities. Two common attacks include price oracle attacks and frontrunning the oracle feed.
1. Price Oracle Attacks
Price oracle attacks target vulnerable implementations of price data feeds. Centralized price oracles that rely on a single source of information are particularly vulnerable to such attacks.
Here, the attackers manipulate DEX market prices to corrupt the sole source of price information through a series of complex transactions, often completed within a single block using a flash loan.
As a result, the compromised oracle provides incorrect price feeds, leading to artificial arbitrage opportunities for attackers.
Moreover, such protocols execute several actions based on the incorrect price feed, including wrong price swaps, issued loans, and liquidations, leading to losses for both the protocol and its users. Scary, right?
Source: Chainlink
2. Frontrunning of the Oracle
Frontrunning, on the other hand, helps certain users gain a nearly risk-free advantage by accessing information before others.
On-chain frontrunning can take several forms, such as transaction reordering, sandwich attacks, and frontrunning of the Oracle fetch, which we will focus on here.
Due to a time delay between the current manipulation-resistant information and the most recent value of the data stream, the oracle’s price feed may not reflect the actual price at a given time, making it vulnerable to exploitation.
Moreover, frontrunning is particularly problematic on the Ethereum Mainnet, where the high gas and slow transactions discourage frequent updates to price data.
Uniswap V3- The Best Oracle?
Price oracles are available in different ‘flavours’, offering unique features.
ChainLink, the Open Price Feed, Uniswap time-weighted average prices (TWAP), and Maker Oracles are among the most notable names in the space.
Unveiled in Uniswap v2 and subsequently enhanced in Uniswap v3, TWAP oracles offer a favourable alternative to spot price oracles and off-chain oracles.
Since TWAP oracles obtain information on-chain, they are less vulnerable to attacks resulting from collusion among oracle operators, which could lead to incorrect price reporting.
Furthermore, TWAP oracles prove more resilient against short-term price fluctuations and the likelihood of flash loans. It also reduces the possibility of being front-run, as an initial order’s execution has a less drastic impact on the price.
However, before delving further into TWAP oracles, let’s quickly glimpse into Uniswap’s legacy.
Uniswap V1
Back in 2016, Vitalik Buterin, the founder of Ethereum, suggested the creation of a decentralized exchange coupled with an “on-chain automated market maker,” outlining some of the technical aspects on Reddit.
Taking this idea and running with it was Hayden Adams, a former Siemens mechanical engineer, who developed the fully-functional Uniswap platform.
Moreover, the project received funding from various sources, including a $100,000 grant from the Ethereum Foundation and a $1 million investment from Paradigm, a digital asset investment company.
Uniswap’s successful launch in November 2018 was a testament to the viability of an AMM decentralized exchange, which used simpler mathematical equations for LP transfers compared to other DEXs that relied on more complex equations to match traders.
Source: Uniswap
Uniswap’s asset pricing mechanism involves mathematical formulas, specifically, the CFMM (Constant Function/Product Market Maker), where the product of two assets in a trade equals a constant value represented as:
x*y=k.
In simpler terms, Uniswap ensures that traders can exchange ERC20 tokens with greater convenience and transparency while also increasing the liquidity reserve of tokens over time.
Moreover, LPs who engage in trading receive additional ERC20 tokens, which they can choose to burn or trade, thereby increasing the liquidity of the tokens.
Each exchange in this version incurs a 0.3% fee to the liquidity reserve. Besides, Uniswap V1 only supports ETH-ERC20 trading pairs, so users can only swap ETH for a single ERC20 token.
For instance, to swap USDC for DAI, one would first have to swap USDC for ETH and then go to the ETH-DAI pool to acquire DAI.
Uniswap V2
Uniswap V1 served as a prototype for a novel decentralized marketplace. Its early triumph was a green light for the team to quickly improve upon it, resulting in the launch of Uniswap V2 in May 2020.
This second version was an excellent upgrade, offering enhanced user-friendliness and solving the lack of ERC20-ERC20 token pools in V1. The absence of this feature had imposed higher costs and slippage on users seeking to exchange ERC20 tokens.
Moreover, Uniswap V2 facilitated the creation of ERC20-ERC20 token pools, significantly reducing slippage and streamlining token swapping. This advancement also allowed liquidity providers (LPs) to exchange ERC20 coins with other cryptos more efficiently.
Furthermore, to address the lack of ETH bridging, the platform introduced wrapped ERC20 tokens, replacing native ETH and maintaining price stability.
Uniswap V2 also introduced flash swaps, a quicker and more convenient trading method that allows the recipient to receive output tokens before enforcing tokens received by the other LP.
As the most significant innovation, Uniswap V2 incorporated Oracle data feeds, providing access to real-world information and ensuring greater precision and security in smart contracts.
Despite Uniswap V1 remaining operational after V2’s launch, liquidity providers quickly migrated to the new version.
Uniswap V2 went on to experience tremendous success, surpassing several renowned centralized exchanges in daily trading volume. Its popularity made it one of the most forked projects, with SushiSwap as its most significant competitor.
Uniswap V3
Uniswap is pioneering the DeFi landscape after achieving a zero-to-one transformation.
Its uniqueness stems from being among the earliest decentralized exchanges and its developers’ ingenuity in formulating the elegant x * y = k equation.
Uniswap V3 represents the latest iteration of the Uniswap Protocol. Launched in May 2021, Uniswap V3 boasts greater capital efficiency compared to previous versions.
The biggest upgrade was for Liquidity Providers (LP). LPs in V2 could only provide liquidity throughout the price range (0,∞). But LPs in V3 can customize the range, achieving the same liquidity with significantly less capital.
Uniswap V3 represents the next step in smart contract development, building on the business logic of Uniswap V2 (an implementation of the x * y = k equation) while incorporating complex mathematical formulas and an additional engineering layer.
Moreover, despite introducing several compelling features, Uniswap V3 remains essentially an AMM similar to previous versions, where the x * y = k equation defines the token inventories in a pool.
The only difference is that the entire price range (0,∞) is segmented into numerous ticks, requiring updates to the x * y = k equation each time the price crosses a tick boundary.
By allowing each liquidity provider to create a unique price curve, Uniswap eliminates fungibility and renders ERC20 LP tokens unsuitable for representing liquidity positions. Instead, the platform leverages ERC-721 NFTs for this purpose.
TWAP Oracles
Uniswap V2 paved the way for creating on-chain time-weighted average price (TWAP) oracles that are highly decentralized and resistant to manipulation, meeting the requirements for building robust protocols.
Meanwhile, Uniswap V3 builds on this foundation by improving TWAP oracles’ efficiency in calculation and gas consumption.
These trustless price feeds are a vital ecosystem component since several smart contracts can integrate them for price data. However, they are a prime target for bad actors as there is an economic incentive to manipulate them.
To operate in a Proof of Work (PoW) mode, the devs built Uniswap’s TWAP oracles with security measures that ensured manipulators would lose money due to back-runs.
While it may be possible to manipulate some Uniswap V3 TWAP oracles, bad actors would need enormous capital, and the profits must outweigh the fees and losses incurred. Validators with enough market share to attempt an attack are unlikely to do so, as it would jeopardize their place in the market and users’ trust in their role as neutral parties.
But would a fake set of validators emerge to attempt the manipulation? We would need to rely on the current system, but not for long. The biggest threat to TWAP is its mechanism itself.
TWAP oracles provide the average price of an asset instead of its spot price. Back in 2022, Ankr protocol was hacked for $5 million. The attacker minted 6 quadrillion $aBNBc.
Another wallet, seeing the price dump of $aBNBc, quickly bought the coin, deposited in Helio.money and borrowed $HAY stablecoin and eventually sold it to $BUSD. Reason? Helio gets its price feed from Chainlink!
But What Exactly are Uniswap V3 TWAP Oracles?
Uniswap V3 pair pools serve as a valuable source of price oracle data, providing historical price and liquidity information based on trades within the pool.
Uniswap stores this data as an array of Observations structs, which record relevant information about trades, such as block timestamp, tick accumulator, and seconds per liquidity.
Source: Uniswap
Observations are saved to memory on a per-block basis whenever a trade occurs. And using two Observations, we can calculate the time-weighted average price.
The absence of price begs the question: how do we derive it? The tickCumulative is the key. Let’s examine ticks and their role in price calculation. It’s why Uni-V3’s TWAP is much more reliable than others! because it tracks tick instead of price!
What are Ticks & Price?
In traditional finance, ticks are the most minor possible upward or downward movement in the price of a security.
Similarly, in Uniswap V3, the minimum price change between the previous and next values must be 0.01% or one basis point.
Simply; Price(tick) = 1.0001tick.
But what’s tickCumulative?
It is the product of the tick and the elapsed time in seconds for the pool’s life up to the observation timestamp. Confused? Let me explain.
Consider the following example: We have two observations taken ten seconds apart, with tickCumulatives t1=100,000 and t2=200,000.
The average tick for the period becomes
$(200,000-100,000)/10 = 10,000$, and the average price during that interval is
$Price(tick) == Price(10,000) === 1.0001 ** (10,000) ≅ 2.7181.$
Mindblowing, right? This answers why price is a lagging indicator, which should not be used as a base indicator, even in oracles.
Why is the TWAP Oracle necessary, though?
TWAP oracles offer a solution to a significant problem associated with using on-chain oracles: price manipulation.
Consider a lending protocol that employs spot prices from a DEX like Uniswap to determine the valuation of assets deposited as collateral. Usually, DEX prices are reliable because traders restore price parity through arbitrage. However, an attacker can manipulate the reported spot price of an asset using a flash loan.
This scenario poses a threat because flash loans are uncollateralized, enabling attackers to manipulate prices without risk.
Examples such as the bZx and Warp Finance attacks on lending protocols using on-chain price oracles highlight the severity of the problem.
However, TWAP oracles attempt to make such manipulation costly by increasing the difficulty of influencing a token’s price on a DEX (assuming adequate liquidity in the given pool). Two question marks exist;
- Difficulty to influence
- Adequate liquidity
The difficulty to influence can vary according to market conditions. For example, in a bull market, the liquidity is pretty high, making the difficulty relatively high. At the same time, in a bear market, hacks and attacks happen more often. The two questions become singular as time progress.
But how do we gauge an attacker’s ability to control a TWAP oracle’s price?
We consider two factors: funds and time.
The attacker must be able to pour a significant amount of money into the trading pool to move the price in the desired direction. However, even hundreds of millions of dollars may not be enough, as attackers can use flash loans to access these funds within a single block. Therefore, additional protection is required.
When interfacing with TWAP oracles, users must specify the desired time frame for the weighted average price. For example, a user requests the average weighted price over five minutes. In that case, attackers seeking to manipulate the price in the pool to a specific value must maintain that price for the entire five-minute period. This requirement increases an attack’s difficulty and helps protect against price manipulation.
However, flash loans cannot be extended over a single block. So, the attacker must maintain the desired price over multiple blocks, which presents a new challenge.
Now, the attacker must provide real liquidity and ensure the price manipulation remains undetected.
Assuming the attacker provides the necessary funds, their efforts will be short-lived. Once a block has been mined, any deviation in price will be visible to the entire network, and arbitrageurs will quickly take advantage of the opportunity.
Multiple bots will compete to close the arbitrage, forcing the attacker to drive the price against the market and dump more money into the pool.
Conclusion
Undoubtedly, Uniswap V3 Oracle has emerged as a critical cornerstone and powerhouse in the DeFi market. The introduction of Time Weighted Average Price in Uniswap v2, and its subsequent improvement in Uniswap v3, has led to the widespread utilization of the TWAP oracle feed for establishing a reference price for on-chain assets.
Compared to its predecessors, Uniswap V3 offers superior capital efficiency, enhanced security, and greater decentralization, driving its widespread adoption. It led to Uniswap becoming the most popular and utilized Ethereum contract in 2022, and Uniswap Labs, the parent company of Uniswap, achieving unicorn status.
Found value in the insights shared here? Check out our YouTube and Twitter, loaded with content meant to educate and entertain.
Follow our Telegram for a sneak peek at alpha; for an even deeper dive, join our Patreon community, where we share exclusive alpha for you to be the ‘early bird.’
Follow us today, and let’s explore Web3 together!