I am currently summarizing the evaluation methods for the DeFi track. After studying some cases, I found that Uniswap is a typical representative in terms of both influence and iterative logic.
The iteration of Uniswap from V1 to V4, as well as the launch of the UniswapX protocol, has the inherent logic of functional innovation and mechanism optimization of DEX transactions.
V1 initially put AMM into practice in the crypto field, V2 reduced ETH risk exposure and launched a price oracle that was more difficult to manipulate, V3 solved the problem of capital inefficiency by concentrating liquidity, V4 implemented customizable DEX, and the UniswapX protocol strengthened the competitiveness of third-party aggregators through an auction mechanism, thereby optimizing price slippage.
History of Uniswap
There is no need to elaborate on Uniswap's status and influence. According to Dune's real-time data, Uniswap is still the DEX with the largest market share.
As a leading DEX, it has not been around for long, but it has undergone many iterations. Let’s take a look at its development history:
In June 2017, Vitalik published an article On Path Independence;
In November 2018, Uniswap V1 was released: supporting transactions between ETH and ERC-20 tokens;
In March 2020, Uniswap V2 was released: supporting trading of any two ERC-20 token pairs;
In May 2021, Uniswap V3 was released: improving the utilization rate of LP funds and proposing the concept of aggregated liquidity;
In June 2023, Uniswap V4 was launched: introducing customized Hooks contracts 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 an article titled "On Path Independence" on his personal website, which introduced the automated market maker (AMM) in the crypto field for the first time. This is a trading method different from CEX. Of course, this method has long been discussed in non-crypto circles (such as traditional finance).
We know that in the stock market, futures market or existing CEX, most transactions are conducted in the Order Book mode. Market makers (such as brokerages and centralized exchanges) match the buyer's buy orders and the seller's sell orders when the prices match, thereby completing the transaction between the buyer and the seller.
However, problems arose in the decentralized environment of DEX (anyone can participate in creating the market), and it is difficult to provide corresponding liquidity through matching transactions in the order book model. The transaction rate and user experience are relatively poor. Without sufficient liquidity, it is difficult to match the operational utility of CEX.
In this article by Vitalik, a novel concept was introduced to the crypto market: Automatic Market Maker.
In this concept, asset pricing is completed through pricing algorithms instead of the traditional order book model. In the AMM model, there is no need for market makers to quote or system matching, and traders can directly use the liquidity in the pool to exchange assets.
TokenA and TokenB form a constant product relationship:
tokenA_balance(p) *tokenB_balance(p)=K (K remains unchanged)
This is a liquidity-driven trading system, and the model is called a constant product market maker (CPMM).
This approach allows a path-independent market maker to be formed by defining any (monotonic) relationship between tokenA and tokenB and calculating their derivatives at any time to give a price.
Three participants: LP, traders, and arbitrageurs
In the AMM's market-making mechanism, there is no specific counterparty like the order book model. The actual value of the asset is determined by a mathematical formula of a constant product. To a certain extent, it can be compared to the counterparty being a smart contract, which can realize automatic trading of assets.
Someone needs to provide liquidity in smart contracts. The liquidity provider is the LP (Liquidity Provider). LP injects assets into the smart contract in the pool to provide liquidity for transactions, thereby obtaining transaction fee income. After the LP builds the initial liquidity pool, traders can exchange tokens through the pool. At the same time, arbitrageurs will actively come to maintain the consistency of asset prices with market prices through price arbitrage between different markets.
In Uniswap V1 released in November 2018, all assets can be exchanged through ETH. Transactions are conducted between ETH and ERC-20 tokens. Anyone can add tokens to trade with native ETH. ETH is the de facto intermediary for asset transactions.
If we want to trade, what changes will happen in a single pool?
Assume that one ETH is now worth 100 TokenA, and an ETH/TokenA pool consists of 10 ETH and 1,000 TokenA.
At this point, 10 ETH and 1,000 TokenA are worth the same, both $1,000, and the asset value ratio is 1:1. k=10 *1000=10,000, and this product remains unchanged without adding more liquidity.
Now suppose I want to sell 5 ETH to the pool, then it should be:
y=10000/(10+5)=666.67,
The number of ETH in the pool increased to 15, and the number of USDC at this time became 666.67, so I exchanged 5 ETH for 333.33 TokenA.
At this time, the price of a single ETH in the pool is
666.67/15=44.44,
That is, one ETH is equal to 44.44 TokenA.
Of course, if the price in a single pool changes significantly from other trading markets, arbitrageurs will immediately flock in until they eat up the price difference. After all, the AMM mechanism can only generate transaction prices, but cannot discover market prices, so the role of arbitrageurs is very important.
Impermanent loss, LP tokens, and transaction slippage
Impermanent loss occurs when the price ratio of the deposited tokens changes compared to when they were deposited into the pool. The greater the change, the greater the impermanent loss.
Now as LP, let’s continue with the example:
UniswapV1 core formula: x∗y=k
Now, as a liquidity provider, we continue to add 10 ETH and 1,000 TokenA to the pool as initial liquidity. At this time, 1 ETH is equal to 100 TokenA.
The constant product of the two asset quantities is 10*1000=10000 (x*y=10000,x=100y).
At this time, if the price of 1 ETH increases to 200 TokenA,
We can do the conversion:
x*y=10000,x=200y,
Thus we can calculate x=7.071,y=1414.21.
At this time, the liquidity pool has changed from 10 ETH and 1000 TokenA at the beginning to: 7.071 ETH and 1414.21 TokenA.
Found the problem?
At this time, if I redeem all the assets, I will get 7.071 ETH and 1414.21 TokenA. The actual value of TokenA is
7.071*200+1414.21=2828.41,
If we calculate based on the initial 10 ETH and 1,000 TokenA, the current price should be
10*200+1000=3000TokenA。
The difference in this part of the profit (3000-2828.41=171.59TokenA) 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, resulting in loss of their principal and missed returns.
Since they act as both buyers and sellers, they are forced to increase the amount of assets they hold when prices fall, and are forced to reduce the amount of assets they hold when prices rise, resulting in losses. Of course, you can also choose hedging and manage risks by opening short/long contracts on ETH.
In order to motivate users to act as LPs to provide liquidity and encourage them to bear the price volatility, LP Token came into being. This is a reward for liquidity providers, who can obtain a certain percentage of the transaction fee (UniswapV1, traders pay 0.3% of the fee in the transaction, which belongs to the liquidity provider). It also serves as a certificate for LPs to retrieve the liquidity they have added.
Another concept is transaction slippage, which is familiar to those who often do DEX transactions. As a liquidity-driven trading system, AMM has a beautiful constant product equation that is a smooth curve, and the price changes all the time according to the supply and demand relationship.
If you trade a large number of tokens at this time, slippage will occur, and there will be a certain difference between your expected price and the actual price you get from the pool. In other words, there will be a gap between the price you want and the transaction price.
Uniswap V2: Adaptation, Oracle, Flash Loans
Uniswap V1 only supports transactions between ERC-20/ETH trading pairs. In essence, it uses ETH as a transitional currency intermediary to exchange ERC-20 tokens. Although the transaction path is simple, it creates ETH risk exposure, impermanent loss and slippage risk for LP providers.
In Uniswap V2, it is still based on the "constant product market maker" mechanism, but the upgrade of V2 brings efficiency improvements, including: supporting any two ERC-20 token pairs for trading, which means that any ERC20-ERC20 pairs can be created without the need to pair through the ETH transition path.
I will not elaborate on this point. The upgrade of V2 includes many aspects, and two more important points are: improving price oracles and realizing flash loans.
Improvements to Price Oracle
In the Uniswap V1 process, the price calculated by dividing the reserves of two assets in the pool is not safe if used as an on-chain price oracle because it can be easily manipulated.
One of the goals of this V2 upgrade is to increase the cost and difficulty of price manipulation. In V1, assuming that other contracts use the current ETH-DAI price to settle derivatives, an attacker who manipulates the measured price can buy ETH from the ETH-DAI pair, trigger the settlement of the derivative contract at an artificially high price, and then sell ETH back to the pair to return its transaction to the real price. In this case, transactions can even be conducted in an atomic transaction manner, or the order of transactions within the block can be controlled by miners.
In V2, in order to determine the market price balance, the price is updated once in each block, and the token exchange price is determined before the next block, that is, the token market price is based on the last transaction in the previous block.
In this upgrade, a new price oracle data is also provided: the time-weighted average price TWAP. The relative price of two assets is accumulated at the beginning of each block, allowing other contracts on Ethereum to estimate the time-weighted average price of two assets at any time interval.
More specifically, in Uniswap V2, the price is accumulated by tracking the cumulative sum of prices at the start of each block when someone interacts with the contract. Based on the block timestamp, each price is weighted by the amount of time since the last block was updated. This means that the value of the accumulator at any given time (after being updated) should be the sum of the spot prices for every second in the history of the contract.
Users of the oracle can choose when to start and end this period, making it more costly for an attacker to manipulate TWAP and making prices less susceptible to manipulation.
Flash Loans
Flash loans are an absolute innovation compared to traditional finance. After all, 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 the chain, only returning the assets and paying the corresponding interest at the end of the transaction (payment in the same atomic transaction). If the payment is not made normally, the transaction will be rolled back.
In fact, it is equivalent to allowing anyone to flash lend any asset stored in the Uniswap pool. In V1, users are not allowed to receive and use assets before paying for them. When using asset A to purchase asset B, asset A must be sent to the contract before asset B can be obtained.
There are some other updates: including Uniswap V2 adjusting the new contract framework, using a simple binary fixed-point format to encode and process prices (precision), updating protocol fees, supporting meta transactions for minted pool shares, etc.
Uniswap V3: Improved capital efficiency
Background: Uniswap V2 has liquidity issues.
Based on the above introduction to the AMM mechanism, we can see that in V1 and V2, the liquidity of the pool is actually distributed in the [0, +∞] area, that is, in the V2 pool, transactions of any price are actually allowed to occur (refer to the inverse function smooth curve in the AMM constant product).
At first glance, this seems to be a good thing, as the trading range is very large. However, in reality, there is not enough demand for the price range of trading pairs with different volatility, which results in severe liquidity shortage and low asset utilization outside of some trading ranges.
As you can imagine, it is pointless and wasteful to provide liquidity at a price point far out of the price range, as the price may never reach that point.
Concentrated liquidity
In this situation, in order to improve the liquidity of funds, Uniswap V3 introduced the concept of concentrated liquidity.
That is: Liquidity providers (LPs) can freely choose to provide liquidity in a certain price range. This can better provide liquidity and operate within a high capital efficiency range. At the same time, in terms of application, different configurations can be made for asset pools with different price volatility.
Each small price range in V3 can be understood as a V2 at work. During the transaction, the price will move smoothly along the curve. When the price reaches a certain section of V2, that is, it reaches the interval point of the price range of V3, then at this time, the price point will slide to the next price range.
After understanding the above concept, we can get to know the new term - the core of V3 is Ticks.
Ticks, the minimum price change, is the minimum incremental amount that can be traded. In V3, by dividing the price range of [0, +∞] into countless fine-grained ticks, the upper and lower endpoints of each interval are restricted. Liquidity is aggregated by granular control. In V3, the entire price range is calibrated by discrete, evenly distributed ticks. Each tick has an index and a corresponding price, and each tick has its own liquidity depth.
The mathematical principles of Uniswap V3 have changed, although the underlying structure is similar to V2:
L = square root of xy
L is called the liquidity quantity, and the liquidity in the pool is the combination of the two token asset quantities. Similarly, the product of the two token quantities is K, but because the liquidity depth of each Tick is different, the equivalent formulas of different depths are no longer the same.
I will not go into details about the mathematical principles. Below is a paper by Atis Elsts on the mathematical principles of V3. Friends who are interested can read it for themselves.
Uniswap V2 still has a standard 0.3% transaction fee, but V3 provides three different fee levels due to different granularity, namely 0.05%, 0.3% and 1%. At this time, LPs can focus their capital efficiency on the most frequently traded interval to obtain the maximum benefits.
In addition, V3 has further optimized the oracle based on V2. It no longer stores only one price accumulation variable, but a group of variables, which can extend the use period of data, reduce Gas fees, and save costs.
Uniswap V4: Customizable DEX
Uniswap V4 is based on the centralized liquidity model of Uniswap V3, allowing anyone to deploy new centralized liquidity pools on Uniswap using custom functions, thereby becoming an efficient and customizable DEX platform.
In V4, the core point is the Hooks contract, and the vision is to allow anyone to make these trade-off decisions by introducing "hooks". For each pool, the creator can define a "Hooks contract" that executes logic at key points in the life cycle of the call.
These Hooks can also manage the pool’s swap fees and withdrawal fees charged to liquidity providers.
Hooks & Custom Pools
Hooks are a set of contracts developed by a third party or Uniswap official. When creating a pool, the pool can choose to bind a hook. Later, at a specific stage of the transaction, the pool will automatically call the bound hook contract, which implements the logic at key points in the call life cycle.
In other words, hooks are externally deployed contracts that execute some developer-defined logic at specified points in the pool's execution. These hooks allow integrators to create centralized liquidity pools with flexible and customizable execution. Hooks can modify pool parameters, or add new features and functionality.
Each Uniswap liquidity pool has a lifecycle: During the lifecycle of a liquidity pool, several things happen, including: the pool is created with the default fee tier, liquidity is added, removed, or readjusted, users can also exchange tokens, etc.
In Uniswap v3, these lifecycle events are tightly coupled and executed in a very strict order. But in Uniswap V4, we create space for customizable liquidity.
The Hooks contract creates a code introduction method for pool deployers, so that specified operations can be performed at key points in the pool life cycle, such as before and after swaps, or before and after LP position changes.
In summary, hooks are plugins for customizing how pools, swaps, fees, and LP positions interact. Through the Hooks contract, developers can innovate on top of the liquidity and security of the Uniswap protocol and create customized AMM pools through hooks integrated with v4 smart contracts.
Example functions that can be implemented via hook contracts include:
Execute large orders over a period of time through TWAMM; On-chain limit orders that execute at a specified price; Dynamic fees that change with volatility; Internalized MEV allocation mechanism for liquidity providers; Implement median, truncated, or other custom oracles.
The core logic of Uniswap V4 is the same as V3 and is not upgradeable. Since each pool is now defined not only by tokens and fee layers, a wide variety of pools can be built from it. And while each pool can use its own hook smart contract, the hook will be limited to specific permissions determined when the pool is created.
There are also some architectural changes in V4, such as Flash Accounting, which can significantly reduce gas fees. This feature is included in EIP-1153 to introduce "transient" storage, which will be implemented after the Cancun upgrade (Ethereum Cancun).
In addition, the V4 version also has improvements such as the use of singleton mode (saving all pool states in one contract), lightning accounting (ensuring the solvency of the pool), restoration of support for native ETH, support for ERC-1155 tokens, and increased governance mechanisms.
UniswapX: Intensifying Competition
UniswapX is a new permissionless, open source (GPL), auction-based protocol for trading across AMMs and other liquidity sources. The protocol will improve swap functionality in multiple ways, including: Higher prices by pooling liquidity sources Gas-free swaps MEV (Maximum Extractable Value) prevention No fees for failed trades In the coming months, UniswapX will expand to gas-free cross-chain swaps.
Next-level aggregation
Background: On-chain transactions continue to innovate, leading to a surge in liquidity pools, and new fee tiers, L2, and more on-chain protocols will also disperse liquidity. Solution: UniswapX aims to solve this problem by outsourcing routing complexity to an open network of third parties, who need to compete to fill transactions using on-chain liquidity such as AMM pools or their own private inventories.
With UniswapX, traders will be able to use the Uniswap interface without having to worry about whether they are getting the best price. Traders’ trades will always be transparently recorded and settled on-chain. All orders are backed by the Uniswap smart order router, which forces third parties to compete with Uniswap V1, V2, V3, and V4 after launch.
In essence, UniswapX strengthens the competition mechanism and optimizes the price slippage of each asset pool through third-party routing selection.
In addition, UniswapX has also launched a new attempt: Gas-free transactions, no fees for failure. Traders sign a unique off-chain order, and then a third party who pays Gas on behalf of the trader submits the order on the chain. The third party includes the Gas fee in the transaction price, but can compete for the best price and reduce transaction costs by executing multiple orders in batches. MEV protection returns the MEV originally obtained through arbitrage transactions to traders at a better price.
UniswapX helps users avoid more explicit forms of MEV extraction: orders executed using third-party private assets cannot be "sandwiched", 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 combine swaps and bridges into one seamless operation. Using cross-chain UniswapX, swappers will be able to swap between chains in seconds, and you can look forward to their progress.
Uniswap theme: iteration
The iteration of Uniswap from V1 to V4 and the launch of the UniswapX protocol are both functional innovations of DEX (AMM).
V1 initially put AMM into practice in the crypto field, V2 reduced ETH risk exposure and launched a price oracle that was more difficult to manipulate, V3 solved the problem of capital inefficiency by concentrating liquidity, V4 implemented customizable DEX, and the UniswapX protocol strengthened the competitiveness of third-party aggregators through an auction mechanism, thereby optimizing price slippage.
We can see that every step taken by Uniswap is an innovation of itself - reducing borrowing costs, optimizing user experience, strengthening competitive awareness, and embracing emerging technologies. This kind of iterative upgrade is the foundation for a good protocol to be long-lasting.