DeFi Evaluation Method: Uniswap Iterative Review
Author: Arrow
Recently, I have been summarizing evaluation methods for the DeFi track. After studying some cases, whether from the perspective of influence or iterative logic, Uniswap is a typical representative. This article provides a comprehensive review of Uniswap.
From the iteration of Uniswap from V1 to V4, as well as the launch of the UniswapX protocol, its inherent logic is about functional innovation and mechanism optimization in DEX trading.
V1 initially practiced AMM in the crypto field, V2 reduced ETH risk exposure and introduced a price oracle that is harder to manipulate, V3 solved the problem of low capital efficiency through concentrated liquidity, and V4 implemented customizable DEX. The UniswapX protocol enhances the competitiveness of third-party aggregators through an auction mechanism, thereby optimizing price slippage.
Uniswap Development History
The status and influence of Uniswap need no elaboration. According to real-time data from Dune, Uniswap is still the DEX with the largest market share.
As a leading DEX, its time in the market is not very long, but it has undergone multiple iterations. Let's take a look at its development history:
In June 2017, Vitalik published the article "On Path Independence";
In November 2018, Uniswap V1 was released: supporting trading between ETH and ERC-20 tokens;
In March 2020, Uniswap V2 was released: supporting trading between any two ERC-20 tokens;
In May 2021, Uniswap V3 was released: improving LP capital utilization and introducing the concept of concentrated liquidity;
In June 2023, Uniswap V4 was launched: introducing Hooks contracts for customization to prevent value leakage;
In July 2023, Uniswap X was launched: aggregating on-chain and off-chain liquidity, MEV protection.
Uniswap V1: An Attempt at Automated Market Making
In 2017, Vitalik published the article "On Path Independence" on his personal website, which introduced the concept of Automated Market Makers (AMM) to the crypto field for the first time. This is a trading method different from CEX. Of course, this method had already been discussed in non-crypto fields (such as traditional finance).
We know that in the stock market, futures market, or existing CEX, most transactions are conducted using an Order Book model. Market makers (such as brokers and centralized exchanges) match buy and sell orders when prices align, thus facilitating trades between buyers and sellers.
However, in a decentralized context, problems arise because, in a DEX decentralized environment (where anyone can participate in creating markets), it is difficult to provide corresponding liquidity using an order book model, resulting in relatively poor transaction rates and experiences. Without sufficient liquidity, it is hard to match the operational efficiency of CEX.
In Vitalik's article, a novel concept was introduced to the crypto market: Automatic Market Maker (AMM). In this concept, asset pricing is accomplished through pricing algorithms rather than through traditional order book models.
In the AMM model, there is no need for market makers to quote prices or for systems to match orders; traders can directly utilize the liquidity in the pool to exchange assets.
TokenA and TokenB form a constant product relationship: tokenAbalance(p) * tokenBbalance(p) = K (K remains constant)
This is a liquidity-driven trading system, and this model is called Constant Product Market Maker (CPMM). Under this method, prices can be given by defining any (monotonic) relationship between tokenA and tokenB and calculating its derivatives at any time, thus forming a market maker that is path-independent.
Three Participants: LP, Traders, Arbitrageurs
In the AMM market-making mechanism, there are no specific counterparties like in an order book model; the actual value of assets is determined by the mathematical formula of constant product, which can be somewhat likened to the counterparty being a smart contract, thus enabling automatic trading of assets.
In the smart contract, someone needs to provide liquidity, and liquidity providers are LPs (Liquidity Providers). LPs provide liquidity for trading by injecting assets into the smart contract of the pool, thereby earning transaction fee revenue.
Once LPs have set up the initial liquidity pool, traders can exchange tokens through that pool, while arbitrageurs will actively come in to maintain the consistency of asset prices with market prices by arbitraging price differences between different markets.
In Uniswap V1, released in November 2018, all assets could be exchanged through ETH. Trading occurred between ETH and ERC-20 tokens, and anyone could add tokens to trade with native ETH, which served as the actual asset trading intermediary.
If we want to trade, what changes occur in a single pool?
Assuming one ETH is currently worth 100 TokenA, and an ETH/TokenA pool consists of 10 ETH and 1000 TokenA.
At this point, the value of 10 ETH and 1000 TokenA is the same, both worth 1000 USD, with an asset value ratio of 1:1.
k = 10 * 1000 = 10000, and this product remains unchanged without adding more liquidity.
Now, suppose I want to sell 5 ETH into the pool, then it should be:
y = 10000 / (10 + 5) = 666.67, the number of ETH in the pool increases to 15, and the number of USDC becomes 666.67, so I exchanged 5 ETH for 333.33 TokenA, making the price of a single ETH in the pool 666.67 / 15 = 44.44, meaning one ETH equals 44.44 TokenA.
Of course, if the price in a single pool differs significantly from other trading markets, arbitrageurs will rush in immediately to exploit the price difference. After all, the AMM mechanism can only produce trading prices but cannot discover market prices, so the role of arbitrageurs is very important.
Impermanent Loss, LP Token, and Slippage
When the price ratio of the tokens stored changes compared to when they were deposited into the pool, impermanent loss occurs. The greater the change, the greater the impermanent loss.
Now, as LPs, let's continue with an example:
The core formula of Uniswap V1: x * y = k
Now, as liquidity providers, we continue to add 10 ETH and 1000 TokenA as initial liquidity, at which point 1 ETH equals 100 TokenA, and the constant product of the two asset quantities is 10 * 1000 = 10000 (x * y = 10000, x = 100y).
At this point, if 1 ETH rises to 200 TokenA, we can calculate: x * y = 10000, x = 200y, thus finding x = 7.071, y = 1414.21.
The liquidity pool changes from the initial 10 ETH and 1000 TokenA to: 7.071 ETH and 1414.21 TokenA.
Do you see the problem?
If I redeem all my assets now, I will receive 7.071 ETH and 1414.21 TokenA, which, when valued in TokenA, amounts to 7.071 * 200 + 1414.21 = 2828.41, whereas if calculated based on the initial 10 ETH and 1000 TokenA, the current price should be 10 * 200 + 1000 = 3000 TokenA.
The difference in this profit (3000 - 2828.41 = 171.59 TokenA) is the impermanent loss.
Impermanent loss occurs because, under the automated market maker mechanism of decentralized exchanges, liquidity providers adjust their funds based on price fluctuations, leading to principal losses and missed gains.
Since they act as both buyers and sellers, when prices fall, they are forced to increase the amount of assets held, and when prices rise, they are forced to decrease the amount of assets held, resulting in losses.
Of course, you can also hedge by opening short/long contracts on ETH for risk management.
To incentivize users to act as LPs and provide liquidity, and to encourage them to bear price volatility, LP Tokens were created. This is a reward for liquidity providers, allowing them to earn a certain percentage of transaction fees for each trade (in Uniswap V1, traders pay a fee of 0.3% during trades, which goes entirely to liquidity providers). It also serves as a certificate for LPs to reclaim the liquidity they have added.
Another concept is slippage, which friends who frequently trade on DEX will definitely be familiar with. As a liquidity-driven trading system, the elegant constant product equation of AMM forms a smooth curve, and prices change constantly based on supply and demand.
If a large amount of Token is traded at this time, slippage will occur, resulting in a difference between your expected price and the actual price obtained from the pool. In other words, there will be a gap between the price you want and the execution price.
Uniswap V2: Adaptation, Oracles, and Flash Loans
Uniswap V1 only supported trading between ERC-20/ETH pairs, essentially using ETH as an intermediary currency for exchanging ERC-20 tokens. Although the trading path was simple, it created ETH risk exposure, impermanent loss, and slippage risks for LP providers.
In Uniswap V2, it is still based on the "Constant Product Market Maker" mechanism, but the V2 upgrade brought efficiency improvements, including: support for trading between any two ERC-20 token pairs, meaning that any ERC20-ERC20 pair can be created without needing to pair through an ETH intermediary.
This point will not be elaborated further. The V2 upgrade includes many aspects, with two particularly important points being: improved price oracles and the implementation of flash loans.
Improvement of Price Oracles
In the process of Uniswap V1, the price calculated by dividing the reserves of the two assets in the pool was not safe to use as an on-chain price oracle because it could easily be manipulated.
One of the goals of the V2 upgrade was to increase the cost and difficulty of price manipulation.
In V1, suppose other contracts used the current ETH-DAI price to settle derivatives; an attacker manipulating the calculated price could buy ETH from the ETH-DAI pair at an inflated price to trigger the settlement of the derivative contract, then sell the ETH back to the pair, returning the trade to the real price. In this case, the transaction could even be conducted as an atomic transaction or controlled by miners manipulating the order of transactions within the block.
In V2, to determine market price equilibrium, prices are updated every block, and the token exchange price is determined before the next block, meaning the token market price is based on the last transaction of the previous block.
In this upgrade, a new price oracle data was also provided: Time-Weighted Average Price (TWAP). At the beginning of each block, the relative prices of the two assets are accumulated, allowing other contracts on Ethereum to estimate the time-weighted average price of the two assets over any time interval.
More specifically, in Uniswap V2, the price is accumulated by tracking the total sum of prices when someone interacts with the contract at the beginning of each block. Each price is weighted based on the amount of time since the last update in the previous block. This means that the value of the accumulator at any given time (after being updated) should be the sum of the spot prices per second in the contract's history.
Users of the oracle can choose when to start and end this period, making it more costly for attackers to manipulate TWAP, thus making prices relatively harder to manipulate.
Implementation of Flash Loans
Flash loans are an absolute innovation compared to traditional finance, as real-world transactions cannot be rolled back like on the blockchain.
Flash Swaps were introduced in V2. Users can freely borrow assets from the pool and use them elsewhere on-chain, only needing to return the assets and pay the corresponding interest at the end of the transaction (within the same atomic transaction). If the repayment fails, the transaction is rolled back.
This essentially allows anyone to flash borrow any assets stored in the Uniswap pool. In V1, users were not allowed to receive and use the asset before paying for it; when buying asset B with asset A, they needed to send asset A to the contract first to obtain asset B.
There are also some other updates, including Uniswap V2 adjusting the new contract framework, using a simple binary fixed-point format to encode and handle prices (precision), updates to protocol fees, and supporting meta-transactions for minted pool shares.
Uniswap V3: Improvement of Capital Efficiency
Background: Uniswap V2 had liquidity issues. As mentioned in the introduction to the AMM mechanism, we can see that in V1 and V2, the liquidity in the pool is actually distributed over the range [0, +∞], meaning that in V2, trading at any price is allowed (referencing the smooth curve of the inverse function in AMM constant product).
At first glance, this seems like a good thing, as the trading range is large, but in reality, for trading pairs with different volatilities, there is not enough demand in those price ranges, leading to severe liquidity shortages outside of certain trading ranges and low asset utilization.
It is easy to imagine that providing liquidity far from the price range is meaningless and wasteful, as the price may never reach that point.
Concentrated Liquidity
In this case, to improve capital liquidity, Uniswap V3 introduced the concept of concentrated liquidity. This means:
Liquidity providers (LPs) can freely choose to provide liquidity in a specific price range, allowing liquidity to be better provided in high capital efficiency ranges while also enabling different configurations for asset pools with varying price volatilities.
Each small price range in V3 can be understood as a V2 in operation. During the trading process, prices move smoothly along the curve, and when the price reaches a certain segment of V2, it reaches the boundary point of the price range in V3, at which point the price point will slide to the next price range.
Understanding this concept, we can recognize the newly emerged term—Ticks, which is the core of V3.
Ticks, the minimum price movement, are the smallest incremental amounts at which securities can be traded. In V3, the price range of [0, +∞] is divided into countless fine-grained Ticks, limiting the upper and lower boundaries of each range.
By controlling granularity to aggregate liquidity, the entire price range in V3 is marked by discrete, uniformly distributed Ticks. Each Tick has an index and a corresponding price, and each Tick will have its own liquidity depth.
The mathematical principles of Uniswap V3 have changed, although they are similar to V2 at the underlying level:
L = √(xy)
L is referred to as the liquidity amount, and the liquidity in the pool is a combination of the quantities of the two token assets. Similarly, the product of the quantities of the two tokens equals K, but because each Tick has different liquidity depths, the equivalent formulations of different depths are no longer the same.
There is no need to elaborate on the mathematical principles here; below is a paper by Atis Elsts on the mathematical principles of V3, which interested readers can read on their own.
In Uniswap V2, the standard trading fee is still 0.3%, while in V3, due to the different granularity, three different fee tiers are provided: 0.05%, 0.3%, and 1%. At this point, LPs can concentrate capital efficiency in the most frequently traded ranges to maximize returns.
Additionally, V3 also underwent overall optimization of oracles based on V2, no longer storing just one price accumulation variable but rather a set of variables, which extends the usage period of the data, reduces gas fees, and saves costs.
Uniswap V4: Customizable DEX
Uniswap V4 is based on the concentrated liquidity model of Uniswap V3, allowing anyone to deploy new concentrated liquidity pools with custom functions on Uniswap, thus creating an efficient and customizable DEX platform.
In V4, the core point is the Hooks contract, with the vision of allowing anyone to make these trade-off decisions by introducing "hooks."
For each pool, the creator can define a "Hooks contract," which executes logic at key points in the lifecycle of the call. These Hooks can also manage the pool's swap fees and the withdrawal fees charged to liquidity providers.
Hooks & Custom Pools
Hooks are a set of contracts developed by third parties or Uniswap itself. When creating a pool, the pool can choose to bind a hook, and then at specific stages of the trade, the pool will automatically call the bound hook contract, which implements logic at key points in the lifecycle of the call.
In other words, hooks are externally deployed contracts that execute some developer-defined logic at specified points during the pool's execution. These hooks allow integrators to create concentrated liquidity pools with flexible and customizable execution. Hooks can modify pool parameters or add new features and functionalities.
Each Uniswap liquidity pool has a lifecycle: during the lifecycle of the liquidity pool, several things happen, including: creating the pool with default fee tiers, adding, removing, or rebalancing liquidity, and users can also swap tokens. In Uniswap V3, these lifecycle events are tightly coupled and executed in a very strict order.
However, to create space for customizable liquidity in Uniswap V4, Hooks contracts provide a method for pool deployers to introduce code, allowing specified operations to be executed at key points in the lifecycle of the pool, such as before and after swaps, or before and after LP position changes.
In summary, hooks are plugins used to customize pools, swaps, fees, and the interaction of LP positions. Through Hooks contracts, developers can innovate on top of the liquidity and security of the Uniswap protocol, creating customized AMM pools integrated with V4 smart contracts.
Examples of functionalities that can be implemented through hooks include:
- Executing large orders over time through TWAMM;
- On-chain limit orders executed at specified prices;
- Dynamic fees that change with volatility;
- Internal MEV allocation mechanisms for liquidity providers;
- Implementing median, truncation, or other custom oracles.
The core logic of Uniswap V4, like V3, is non-upgradable. Since each pool is now defined not only by tokens and fee tiers, a wide variety of pools can be constructed. Although each pool can use its own hook smart contract, hooks will be limited to specific permissions determined at the time of pool creation.
V4 also includes some architectural changes, such as Flash Accounting, which can significantly reduce gas fees. This feature is included in EIP-1153, introducing "transient" storage, which will be implemented after the Cancun upgrade (Ethereum Cancun).
Additionally, the V4 version includes improvements such as using a singleton pattern (storing all pool states in one contract), flash accounting (ensuring pool solvency), restoring support for native ETH, supporting ERC-1155 tokens, and enhancing governance mechanisms.
UniswapX: Strengthening Competition
UniswapX is a new permissionless, open-source (GPL), auction-based protocol for trading across AMMs and other liquidity sources.
The protocol will improve exchange functionality in several ways, including:
- Improving prices by aggregating liquidity sources
- Gasless swaps
- Preventing MEV (Maximum Extractable Value)
- No fees on failed trades
- In the coming months, UniswapX will expand to gasless cross-chain swaps.
Next-level Aggregation
Background: Continuous innovation in on-chain trading has led to a surge in liquidity pools, while new fee tiers, L2, and more on-chain protocols also disperse liquidity.
Solution: UniswapX aims to address this issue by outsourcing routing complexity to third-party open networks, which need to compete to fill trades using AMM pools or their own private inventories.
With UniswapX, traders will be able to use the Uniswap interface without worrying about whether they are getting the best price. Traders' transactions will always be transparently recorded and settled on-chain. All orders are supported by Uniswap's smart order router, forcing third parties to compete with Uniswap V1, V2, V3, and the launched V4.
Essentially, UniswapX strengthens the competitive mechanism by optimizing price slippage across various asset pools through third-party routing choices.
Additionally, UniswapX has introduced new attempts:
Gasless trading, with no fees for failed transactions. Traders sign a unique off-chain order, which is then submitted on-chain by a third party representing the trader, who pays the gas fees. The third party incorporates the gas fees into the transaction price but can compete for the best price and reduce trading costs by batch executing multiple orders.
MEV protection, returning the MEV originally obtained through arbitrage trading back to traders at better prices. UniswapX helps users avoid more explicit forms of MEV extraction: orders executed using third-party private assets cannot be "sandwich attacked," and third parties are incentivized to use private transaction relays when routing orders to on-chain liquidity pools.
The upcoming cross-chain version of UniswapX will seamlessly combine swaps and bridging into one operation. Using cross-chain UniswapX, traders will be able to swap between chains in seconds, and we can expect their progress.
Uniswap's Main Theme: Iteration
The iteration of Uniswap from V1 to V4, along with the launch of the UniswapX protocol, is fundamentally about functional innovation in DEX (AMM).
V1 initially practiced AMM in the crypto field, V2 reduced ETH risk exposure and introduced a price oracle that is harder to manipulate, V3 solved the problem of low capital efficiency through concentrated liquidity, V4 implemented customizable DEX, and the UniswapX protocol enhances the competitiveness of third-party aggregators through an auction mechanism, thereby optimizing price slippage.
We can see that every step Uniswap takes is a self-revolution—reducing borrowing costs, optimizing user experience, strengthening competitive awareness, and embracing emerging technologies. This iterative upgrade is the fundamental reason a good protocol can endure over time.