header-langage
简体中文
繁體中文
English
Tiếng Việt
한국어
日本語
ภาษาไทย
Türkçe
Scan to Download the APP

Uniswap: From Zero to Infinity

2023-12-07 17:00
Read this article in 24 Minutes
Original Title: "Uniswap: From Zero to Infinity"
Original Author: Luke, Investor and Researcher at SevenX Ventures


Special thanks to Alex from Maru Network, Brad from Uniswap Labs, Dong Mo from CelerNetwork, Shumo from Manta Network, and Suning from Hyperoracle for their valuable discussions, insights, and feedback on this article.


I am a practitioner in the encryption industry. Please translate the following Chinese text into English without considering the context or industry-specific terms and names. Do not omit any English words or phrases, including capitalized ones such as ZKS, STARK, and SCROLL. If there are English characters in an tag, do not translate them and return the tag as is. If the content consists only of punctuation marks, return them as is. Do not translate HTML tags such as

, , , and

. If an HTML tag contains English characters, omit the translation and return the tag as is. Please preserve the content within tags. Translate all Chinese characters. The text to be translated is:

Foreword


Undoubtedly, Uniswap is the most widely used decentralized application. It relentlessly pioneers innovative solutions and redefines industry rules. This article will delve into the amazing development journey of Uniswap, starting from scratch in the past and having unlimited possibilities in the future. By studying the features of each version of Uniswap, this article reveals how it effectively responds to various new challenges and adapts to constantly changing needs. In addition, this article also explores how the latest developments in cryptocurrency shape the future of decentralized exchanges (DEX). Get ready to embrace this journey of development from zero to infinity.


v0: Concept Verification


Before Uniswap, EtherDelta was the only decentralized exchange (DEX) that received attention. However, the user experience was very poor.


Many industry leaders (such as Alan Lu and Vitalik from Gnosis) have proposed the concept of Automated Market Making (AMM), which provides an alternative method for on-chain trading compared to the traditional order book model.


Features


Constant Product AMM


Uniswap uses the constant product formula (x * y = k) to calculate the price of assets. In this formula, x represents the reserve of the traded asset, and y represents the reserve of the priced asset. When tokens are withdrawn (bought) from the pool, a certain proportion of funds must be deposited (sold) to maintain k constant. The ratio of tokens in the pool determines the price of the tokens.


Source: Uniswap


It is worth noting that other AMMs use different mathematical formulas to represent liquidity curves. For example, Curve's Stableswap and Balancer's weighted pools.


Question


Uniswap v0 is essentially a proof of concept, which means there are still many unresolved issues. The two main issues are as follows:


1. Only applicable to a single ETH/ERC20 trading pair.


2. Only applicable to a single liquidity provider (LP).


v1: Functional Decentralized Exchange (DEX)


Features


On November 2, 2018, Uniswap v1 was launched on the Ethereum mainnet. This version supports multiple liquidity providers to track fees and collateral using internal tokens. The version uses a factory contract and allows anyone to add any token to trade with native ETH. This version provides a functional DEX. However, there are still some issues that need to be addressed.


Problem


As all tokens are paired with ETH for trading, users can easily exchange any ERC20 token for another ERC20 token using ETH as an intermediary in a single transaction. However, this method has a drawback: if frequent stablecoin exchanges such as DAI/USDT are involved, each exchange relies on ETH as an intermediary, which can lead to decreased efficiency. In this case, direct token-to-token exchanges are preferred.


v2: Money Lego


In May 2020, Uniswap v2 was launched, which upgraded the Uniswap protocol with multiple enhancements to improve trading flexibility and expand trading feasibility.


Features


ERC20/ERC20 trading pairs


The significant difference of Uniswap V2 is that it allows for the addition of LP liquidity pools for ERC20 tokens with other ERC20 tokens, rather than just pairing ERC20 tokens with ETH. This feature is more practical for liquidity providers as they can now maintain a more diverse range of ERC20 token valuation positions, including stablecoin trading pairs.


Price Oracle


Uniswap v2 provides on-chain price information that is valuable because it is difficult to manipulate. This mechanism adds the price at the end of each block to the cumulative price variable in the core contract, which is weighted based on the duration of time that a specific price persists. This variable essentially represents the sum of every second of Uniswap price in the contract's entire history.


Source: Uniswap


External contracts can use this variable to accurately track the time-weighted average price (TWAP) over any specified time interval. By reading the cumulative price of the ERC20 token pair at the beginning and end of the time interval, calculating the difference between the two, and dividing it by the length of the time interval, the TWAP for that specific period can be obtained.































v4: Ultimate Platform



Efficiency



In Uniswap v3, each pool is created as a separate contract through the factory contract. In Uniswap v4, however, all pools coexist within a single smart contract (also known as a singleton). This singleton pattern significantly reduces the costs associated with creating pools and executing multi-hop trades.




Source: Uniswap




Customization


Gouzi



Uniswap v4 currently supports the following eight hook callback functions:


beforeInitialize/afterInitialize


beforeModifyPosition/afterModifyPosition


beforeSwap/afterSwap


beforeDonate/afterDonate


The following diagram shows the logic flow of exchanging hooks. There is a dedicated boolean flag before and after the exchange, which allows for custom code to be executed at these specific points. This is the foundation for developing advanced features such as oracles, dynamic fee systems, auctions, and advanced order types. We will explore these concepts further in the following sections.


Redemption Hook Process

Oracle


In previous versions, the oracle was integrated into the Uniswap core protocol. Although this made it easier to integrate with other protocols and reduced integration costs, the cost was a reduction in custom options and an increase in exchange costs. However, with the introduction of hooks, the design possibilities for oracles have been greatly expanded. This provides an opportunity to create anti-manipulation oracles (such as truncated price oracles and volatility oracles). In addition, it is now possible to customize who bears the cost of updating the oracle. For example, a hook contract with an ETH balance can be used to pay gas fees instead of having the first trader bear the cost (which may not be sustainable). Despite optimization, oracle design still faces challenges. For example, TWAP oracles are sometimes susceptible to manipulation and often lag behind current prices.


Uniswap Labs has launched another interesting price oracle, namely the truncated price oracle. This oracle calculates the geometric mean price of assets in the liquidity pool and limits price changes within a single block. By truncating prices, this on-chain oracle mitigates the price impact of large trades and enhances resistance to manipulation attempts.


Dynamic fees


Although Uniswap v3 introduces additional fee tiers for liquidity providers to choose from, these fee structures are still static and do not take into account the current market conditions. As a result, liquidity providers are not fully compensated for their services.


Alex Nezlobin (@0x94305) proposed a simple and effective dynamic fee system that takes into account the price impact of the previous block and applies different fee standards to buyers and sellers. As shown in the figure below: when the CEX price moves to p*, which is higher than the current AMM price p_AMM, the selling fee decreases by δ, while the buying fee increases by δ. The value of δ is proportional to the change in AMM price. The purpose of this dynamic fee system is to distinguish arbitrageurs from uninformed capital flows. Arbitrage flows are more likely to be autocorrelated with price changes.


Source: https://twitter.com/0x94305/status/1674857993740111872


(Note: This content contains HTML tags and a hyperlink, which will not be translated. All Chinese characters will be translated.)

Designing a robust dynamic fee system presents several challenges. One challenge is how to integrate off-chain signals such as CEX prices, liquidity depth, and volatility. In addition, various on-chain signals (including address, size, and execution time) may be unreliable for distinguishing informed flows from uninformed flows, making it difficult to assess their effectiveness. Furthermore, it is important to ensure that fees do not fall below zero in order to limit losses for liquidity providers.


Auction


Hooks can also be used as a means of implementing auctions, which helps to redistribute value to liquidity providers. Depending on the timing, auctions can be divided into pre-auctions and post-auctions.


Pre-auction takes place before the auction block. This concept was initially proposed in a research article discussing MEV capture in AMM (McAMM). Under this approach, the right to make the first exchange in the AMM before a block is auctioned off is available, and the bid value will be redistributed afterwards. However, this bidding process also poses some challenges as it essentially involves option pricing, which can be very complex. In addition, there may be review issues due to the block proposer having the final decision on whether to accept blocks containing transactions. It has been proven that ensuring fair and effective allocation of bidding value is also a complex task. Moreover, there is no guarantee that the winning bidder will exercise their exchange rights first, which may lead to a deteriorating experience for other traders.


Post-auction is conducted after volatility has been realized, which means that the CEX price has already changed but the subsequent blocks have not yet been submitted. The advantage of such auctions is that they improve efficiency, but they also bring challenges because they rely on off-chain infrastructure of trusted parties or trustless systems. If trusted parties are used, there may be issues with review and bidding privacy. On the other hand, designing a trustless system is much more complex. Post-auctions also face the problem of proposers and bidders playing tricks, such as timely exclusion of arbitrage transactions. In addition, there is a major problem that the bidding, consensus on winning bids, and distribution of these bids to block builders may be delayed, and all of these processes need to be completed before submitting subsequent blocks. Finally, it may be difficult to ensure that there are sufficient competitive conditions in these auctions to obtain sufficient value. Sorella Labs (@SorellaLabs) is taking a leading role in addressing these challenges with its advanced infrastructure and mechanism design.


Diamond Hook


The Diamond protocol was originally designed as an AMM that minimizes LVR. Under the Diamond protocol, block producers conduct auctions to capture arbitrage opportunities between the external market price of the Diamond mining pool and the pool's own price. The proceeds from these auctions are shared in a way that maintains incentive compatibility between the Diamond mining pool and the block producers.


As discussed in this article, a variant of the Diamond protocol includes the implementation of a collateral pool to maintain the end-of-block price based on the price promised by the block producer. The exchange will only be executed when there is sufficient collateral to restore the price to the promised value. Arrakis (@ArrakisFinance) is currently working with one of the authors of the Diamond protocol, Conor McMenamin (@ConorMcMenamin9), to develop a hook contract using v4 to achieve this goal.


Advanced Order Type


The hook also supports more advanced order types, greatly improving the trader's experience. Some common order types include limit orders, stop loss orders, take profit orders, and TWAP.


Limit Order


Traders can choose to submit on-chain limit orders to the hook contract. The order will be executed when the price reaches the specified minimum price change. However, compared to traditional finance (tradfi) limit orders, these on-chain limit orders have significant disadvantages. This is mainly because on-chain orders cannot be canceled without incurring gas fees. Therefore, this creates a problem of lower order transaction volume.


Time Weighted Average Market Maker (TWAMM)


One feasible solution is to implement Time-Weighted Average Market Maker (TWAMM) to facilitate the execution of large orders. This method divides large orders into small blocks and ensures that they are executed as the first batch of trades, thus preventing sandwich attacks. In addition, it may be considered to reduce the cost of TWAP orders, as they often involve uninformed processes. However, the accompanying challenges are high gas costs and the decision of who should bear these fees.


Other Hooks














UniswapX





Source: Uniswap



Source: Hayden Adams' "On-Chain Transactions" speech at EthCC conference



·Aggregate liquidity sources to obtain more appropriate prices.





Challenge




Future: Infinite Games


The development of DEX has not stopped here. In order to popularize encryption technology on a large scale, there are several other issues that need to be addressed urgently. Markus Schmitt (@_haikane_) of PropellerHeads (@PropellerSwap) and Frontier Research (@FrontierDotTech) have collaborated to write an excellent article that delves into the essential elements of a great DEX and clarifies the outstanding issues. According to the article, a great exchange should provide:


·Trust: Ensure transparency before, during, and after transactions and minimize custodial risks.


·The most suitable price: Continuously provide the most suitable or competitive price.



·Speed and availability: Provide fast transaction processing and maintain high availability to avoid delays and inconvenience.


·Information: By providing order monitoring, estimated settlement prices, and useful advice for limit orders and slippage, we help users make wise decisions.





In addition, there are a series of AMM-based protocols that effectively stack "money Lego". Some protocols help novice users automate liquidity rebalancing or leverage mining, such as liquidity managers. There are also protocols that use centralized liquidity (CL) positions to create margin trading, perpetual trading, options, and structured products.


AMM has achieved exponential growth due to its characteristics such as no need for permission to list, passive liquidity, and easy trading. However, this convenience also brings several issues that we have discussed earlier. Uniswap has been constantly pushing boundaries to solve these problems and enhance user experience. As Dan Robinson (@danrobinson) pointed out in his speech at SBC23, DEX design is an infinite game. As DEX becomes more popular in the future, new challenges and problems may arise, requiring innovative solutions.


This article is from a submission and does not represent the views of BlockBeats.


Welcome to join the official BlockBeats community:

Telegram Subscription Group: https://t.me/theblockbeats

Telegram Discussion Group: https://t.me/BlockBeats_App

Official Twitter Account: https://twitter.com/BlockBeatsAsia

This platform has fully integrated the Farcaster protocol. If you have a Farcaster account, you canLogin to comment
Choose Library
Add Library
Cancel
Finish
Add Library
Visible to myself only
Public
Save
Correction/Report
Submit