Uniswap: From Zero to Infinity

CN
1 year ago

Uniswap has been constantly pushing boundaries, striving to solve these problems and enhance user experience.

Written by: 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 contributed to this article.

Preface

Undoubtedly, Uniswap is the most widely used decentralized application. It persistently pioneers innovative solutions and redefines industry rules. This article will delve into Uniswap's amazing journey of development, starting from scratch in the past and heading towards infinite possibilities in the future. By studying the features of each version of Uniswap, this article reveals how it effectively addresses various new challenges and adapts to evolving demands. Additionally, this article also explores how the latest developments in cryptocurrency are shaping the future of decentralized exchanges (DEX). Get ready to embark on this journey of development from zero to infinity.

v0: Proof of Concept

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

Many industry leaders (such as Alan Lu from Gnosis and Vitalik) 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 asset prices. In this formula, x represents the reserve of the traded asset, and y represents the reserve of the pricing asset. When tokens are withdrawn (bought) from the pool, a certain proportion of funds must be deposited (sold) to maintain the constant k. The ratio of tokens in the pool determines the token's price.

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.

Issues

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

  1. Only applicable to single ETH/ERC20 trading pairs.

  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 using internal tokens to track fees and collateral. The version uses a factory contract, allowing anyone to add any token for trading with native ETH. This version provides a functional DEX. However, there are still some issues that need to be addressed.

Issues

Since all tokens are traded paired with ETH, 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: when exchanging stablecoins such as DAI/USDT frequently, each exchange relies on ETH as an intermediary, which reduces efficiency. In this case, direct token pairs are preferred.

v2: Money Lego

In May 2020, Uniswap v2 was released, which made multiple upgrades to the Uniswap protocol, enhancing trading flexibility and expanding feasibility.

Features

ERC20/ERC20 Trading Pairs

A significant difference in Uniswap V2 is the ability to add LP liquidity pools for ERC20 tokens with other ERC20 tokens, rather than only 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 pricing positions, including stablecoin trading pairs.

Price Oracle

Uniswap v2 provides on-chain price information that can be used by numerous DeFi applications. This price information is difficult to manipulate and is therefore very valuable. This mechanism adds the price at the end of the block to the cumulative price variable of the core contract, which is weighted based on the specific price's duration. This variable essentially represents the sum of Uniswap prices per second over the entire history of the contract.

Source: Uniswap

External contracts can use this variable to accurately track the time-weighted average price (TWAP) within any specified time interval. By reading the cumulative prices of ERC20 token pairs at the start and end of the time interval, calculating their difference, and dividing by the interval length, the specific TWAP for that period can be obtained.

Source: Uniswap

Flash Swaps

Uniswap v2 also introduced flash swaps, which are a type of flash loan pioneered by the lending market AAVE. This feature allows any user to withdraw as much ERC20 tokens from the pool as possible without any upfront cost or the need to perform any operations, provided that an equivalent amount of tokens (plus fees) is returned at the end of the transaction.

Flash loans have gained notoriety because they are often associated with various attacks on DeFi protocols. However, the real issue lies not with flash loans, but with existing vulnerabilities in the protocols. The atomicity of flash loans eliminates the upfront capital requirements typically associated with pool arbitrage and obtaining margin leverage.

Issues

Despite the innovative nature of this AMM and its benefits in facilitating trading and liquidity for new markets, there are still efficiency issues. For example, when dealing with low volatility tokens, liquidity is only needed within a small price range. However, the current design evenly distributes liquidity across all price ranges.

v3: Capital Efficiency

Uniswap v3 adopts a groundbreaking concentrated liquidity design, aiming to be the most flexible and efficient AMM.

Features

Concentrated Liquidity (CL)

In Uniswap v2, liquidity is evenly distributed along the x*y=k price curve, providing liquidity for the entire price range from zero to infinity. However, for most pools, liquidity is not fully utilized.

In Uniswap v3, liquidity providers can concentrate their capital within specific price ranges to achieve higher liquidity at expected prices. Through this customization, liquidity providers can build personalized price curves that match their preferences. These individual positions will then aggregate into a single pool, creating a unified curve for users to trade against. The result is beneficial for both traders and liquidity providers: due to highly concentrated liquidity within custom ranges, traders experience less slippage, and liquidity providers can earn higher fees.

Concentrated liquidity is highly valuable for stablecoin trading pairs (such as stablecoins and liquidity pool derivative tokens) that often trade within smaller price ranges. However, for highly volatile token pairs, concentrated liquidity requires more advanced liquidity management techniques. For ordinary retail liquidity providers, effectively managing their positions continuously may be challenging.

Range Orders

With concentrated liquidity, this version introduces a new type of order called range orders as a supplement to market orders. Liquidity providers can deposit a single token within a custom price range (above or below the current price). If the market price enters the specified range, one asset can be sold for another along a smooth curve, while still earning trading fees in the process.

The functionality of range orders is similar to limit orders, but the drawback is that they are reversible - the order reverses when the price reverses. However, fees can still be earned during this process. Barry Fried (@BarryFried1) provides a detailed example of how to use range orders in this post.

Multiple Fee Tiers

Uniswap v3 no longer uses a single fee tier, but introduces three separate fee tiers for each trading pair - 0.05%, 0.30%, and 1.00%, allowing liquidity providers to be appropriately compensated for assuming different levels of risk.

Advanced Oracles

Uniswap v3 has made significant improvements to price oracles. This version no longer stores a single price cumulative variable, but a set of variables, making it easier and more cost-effective to create advanced oracles, including simple moving averages (SMA), exponential moving averages (EMA), outlier filtering, and more.

Issues

Lack of Flexibility

While concentrated liquidity and fee tiers provide greater flexibility for liquidity providers and facilitate the implementation of new strategies, Uniswap v3 has not been able to keep up with the ever-changing features and innovations of AMM and the market. To integrate additional features such as TWAP orders, limit orders, advanced oracles, and dynamic fee tiers, it is necessary to re-implement the core protocol.

Through certain features (such as price oracles initially introduced in Uniswap v2), integrators can leverage decentralized on-chain pricing data. However, the cost is an increase in gas costs for traders and a lack of customization options for integrators.

Complex Liquidity Management

As mentioned earlier, concentrated liquidity management is challenging for new liquidity providers, especially for highly volatile trading pairs. While there are several automatic liquidity management protocols, most of them use simple rebalancing strategies designed for pegged assets. Unfortunately, these strategies often prove ineffective for highly volatile trading pairs due to long block times, increased gas costs, and rising hedging costs.

Additionally, since each liquidity provider's concentrated liquidity position is unique, LP tokens are essentially non-fungible. They can only be represented by non-fungible tokens (NFTs), posing a challenge for other DeFi protocols looking to integrate with them.

Many excellent projects are actively utilizing various strategies (including rebalancing, dynamic hedging in money markets, perpetual contracts, and options) to address this issue. Atis Elsts (@atiselsts_eth) has written a series of excellent articles on LP strategies, highly recommended.

Value Leakage

Among all the issues, value leakage is the most critical. While this issue is not unique to Uniswap v3, it has garnered attention due to the increase in AMM trading volume and adoption since its launch. Value leakage mainly stems from the DEX system, as follows:

Traders end up paying higher slippage than necessary due to front-running and sandwich attacks.

Liquidity providers lose value through CEX-DEX arbitrage (also known as relative loss rebalancing).

To address the above issues, compared to Uniswap v3, we need to provide more customization and complex designs. We need a more expressive and powerful DEX platform.

v4: Ultimate Platform

Uniswap v4 is built on the AMM model introduced in previous generations and aims to be an efficient, customizable ultimate DEX platform by introducing "hooks".

Efficiency

Singleton

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

Flash Accounting

In Uniswap v4, the singleton model utilizes flash accounting to optimize asset transfers. Unlike in v3 where assets are moved in and out of the pool after each exchange, the v4 system transfers based on net balances, greatly reducing accounting costs. Through transient storage (proposed in EIP-1153), the cost of setting and clearing storage slots is lower, and storage slots are essential for flash accounting to operate effectively.

Source: Uniswap

Native ETH

Uniswap v4 reintroduces support for native ETH trading, which has several benefits: traders can enjoy lower gas costs, achieve lower transfer costs, and eliminate additional wrapping costs.

Customization

Hooks

Hook contracts (or hooks) are externally deployable contracts that execute predefined logic at specific points during pool execution. This is what makes v4 so expressive and customizable. Through hooks, previously protocol-embedded features (such as oracles) and new features that previously required independent protocols can be implemented.

Uniswap v4 currently supports the following eight hook callback functions:

  • beforeInitialize/afterInitialize

  • beforeModifyPosition/afterModifyPosition

  • beforeSwap/afterSwap

  • beforeDonate/afterDonate

The logic flow of the swap hook is shown in the figure below. There is a dedicated boolean flag before and after the swap, allowing custom code to be executed at these specific points. This forms the basis for developing advanced features such as oracles, dynamic fee systems, auctions, and advanced order types. We will delve deeper into these concepts in the following sections.

Swap hook flow

Oracles

In previous versions, oracles were integrated into the core Uniswap protocol. While this made it easier to integrate with other protocols and reduced integration costs, it also reduced customization options and increased costs for traders. However, with the introduction of hooks, the design possibilities for oracles have been greatly expanded. This provides an opportunity to create manipulation-resistant oracles (such as truncated price oracles and volatility oracles). Additionally, 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 making the first trader bear the cost (which may not be sustainable). Despite optimizations, oracle design still faces challenges. For example, TWAP oracles are sometimes susceptible to manipulation and often lag behind the current price.

Uniswap Labs has introduced another interesting price oracle, 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.

Dynamic Fees

While Uniswap v3 introduced additional fee tiers for liquidity providers to choose from, these fee systems are still static and do not consider current market conditions. As a result, liquidity providers are not fully compensated for their services.

Alex Nezlobin (@0x94305) has 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 the AMM price. The purpose of this dynamic fee system is to differentiate arbitrageurs from uninformed fund flows. Arbitrage flows are more likely to be autocorrelated with price movements.

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. Additionally, various on-chain signals (including addresses, sizes, and execution times) may be unreliable for distinguishing informed flows from uninformed flows, making it difficult to assess their effectiveness. Furthermore, it is important to limit the losses of liquidity providers and ensure that fees do not fall below zero.

Auctions

Hooks can also serve as a means to implement auctions, which helps redistribute value to liquidity providers. Auctions can be divided into pre-auctions and post-auctions based on time.

Pre-auctions take place before the auction block. This concept was initially proposed in a research paper discussing MEV-capturing AMM (McAMM). In this approach, the right to make the first exchange in the AMM before a block is auctioned can be allocated, and the bidding value is then redistributed. However, this bidding process also presents some challenges, as it essentially involves option pricing, which can be very complex. Additionally, there may be issues with review and bidding privacy, as the final decision on whether to include transactions in a block lies with the block proposer. Ensuring fair and effective allocation of bidding value has proven to be a complex task. Furthermore, there is no guarantee that the winning bidder will exercise their exchange right first, which could lead to a deteriorating experience for other traders.

Post-auctions take place after volatility has occurred, meaning that the CEX price has already changed, but subsequent blocks have not been submitted. The advantage of these auctions is increased efficiency, but they also present challenges as they rely on trusted parties or off-chain infrastructure for trustlessness. 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 issue of proposers playing tricks with bidders, such as promptly excluding arbitrage trades. Additionally, there is a significant issue with the process of bidding, reaching consensus on winning bids, and distributing these bids to block builders, all of which need to be completed before submitting subsequent blocks. Finally, it may be difficult to ensure sufficient competitive conditions in these auctions to capture enough value. Sorella Labs (@SorellaLabs) is taking a leading role in addressing these challenges with its advanced infrastructure and mechanism design.

Diamond Hooks

The Diamond protocol was initially designed for LVR-minimizing AMM. Under the Diamond protocol, block producers conduct auctions to capture arbitrage opportunities between the external market price of the Diamond pool and the pool's own price. The proceeds from these auctions are shared between the Diamond pool and the block producers in a way that maintains incentives compatibility.

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. Exchanges are only executed when there is enough collateral to restore the price to the promised value. Arrakis (@ArrakisFinance) is currently collaborating with one of the authors of the Diamond protocol, Conor McMenamin (@ConorMcMenamin9), to develop the use of v4 hook contracts to achieve this goal.

Advanced Order Types

Hooks also support more advanced order types, greatly enhancing the trading experience. Some common order types include limit orders, stop-loss orders, take-profit orders, and TWAP.

Limit Orders

Traders can choose to submit on-chain limit orders to hook contracts. The order is executed when the price reaches the specified minimum price change. However, these on-chain limit orders have significant disadvantages compared to traditional finance (tradfi) limit orders. This is mainly because on-chain orders cannot be canceled without incurring gas fees. This results in a lower order-to-trade ratio issue.

Time-Weighted Average Market Maker (TWAMM)

An alternative solution is to implement a time-weighted average market maker (TWAMM) to facilitate the execution of large orders. This approach divides large orders into small blocks and ensures that they are executed as the first batch of trades, preventing sandwich attacks. Additionally, consideration can be given to reducing TWAP order fees, as they typically involve uninformed flows. However, the accompanying challenges are high gas costs and determining who should bear these costs.

Other Hooks

Several other functionalities can be implemented using hooks. Here are some ideas:

  • A revenue-generating hook that borrows liquidity beyond the range in the money market to improve capital efficiency.

  • Pools with both xy=k liquidity curves and concentrated liquidity.

  • Pools that provide withdrawal fees to liquidity providers to reduce immediate liquidity attacks.

Suning (@msfew_eth) has shared some intriguing ideas about hooks on Github. Aiden (@aiden0x4) has also released a great open directory for hooks.

zkAMM and zkHooks

ZK Coprocessors empower smart contracts to access data insights similar to those provided by Dune Analytics, all without compromising trust due to the application of zero-knowledge (ZK) proof technology. The application of ZK Coprocessors in AMM design is an emerging research area. By introducing hooks, zero-knowledge proofs can now be seamlessly integrated into Uniswap v4, ushering in a new era of zkAMM.

HyperOracle (@HyperOracle) has demonstrated a zkAMM implementation based on Uniswap v2, where addLiquidity calculations are moved off-chain. When users add liquidity, token quantities, prices, and LP token shares need to be calculated. In this specific implementation, HyperOracle's zkGraph captures the addLiquidity event, performs the necessary calculations, generates a proof, and publishes it. This implementation of zkAMM includes an integrated automation layer for verifying the proof and minting LP tokens for users.

Diego (@0xfuturistic) has introduced a zkAMM (zkUniswap) implementation based on Uniswap v3, where a portion of the AMM exchange calculations is moved to Risc Zero (@RiscZero) zkVM. When users execute exchanges in the pool, several parameters need to be calculated to complete the exchange. These parameters include the quantity to be exchanged, fees, and the resulting price. Initially, this calculation was performed in a Solidity contract on the EVM. However, in the new implementation, exchange inputs are picked up by relayers, and the calculation is performed off-chain. Subsequently, the relayers publish the output and proof. The AMM verifies the proof and settles the exchange. zkUniswap implements a lock auction mechanism to ensure concurrency control. While its current performance is comparable to the EVM, efficiency can be greatly improved through parallelization of batch exchanges.

Trade volume proof is another use case for AMM. Brevis (@brevis_zk) provides an interesting example of designing fee rebate hooks based on a user's historical trade volume, similar to volume-based fee rebates on centralized exchanges (CEX). VIP traders can now calculate their monthly trade volume off-chain and then submit low-cost zero-knowledge proofs to the blockchain for asynchronous verification of their VIP status. Once verified, subsequent trades can access the "VIP fee tier table" filled by zero-knowledge coprocessors through the post-exchange hook, allowing for automatic application of appropriate fee rebates. Maru Network (@marunetwork) is currently developing a trustless trade volume oracle as the initial use case for its ZK coprocessor network. By implementing a trustless trade volume oracle, DEX will be able to distribute rewards in a fair and transparent manner, incentivizing liquidity and user activity proportionally, creating a positive feedback loop. The use of zero-knowledge proof aggregation services such as NEBRA (@nebrazkp) UPA (Universal Proof Aggregator) can reduce the cost of proof verification, as NEBRA UPA aggregates proofs from various sources and parties into a single proof to lower the amortized verification cost.

In summary, the concept of zkAMM involves using ZK coprocessors or ZK oracles to offload computations from the EVM and verify proofs of on-chain computations. These computations may be much more complex compared to those related to exchanges and liquidity adjustments. For example, these computations may involve calculating dynamic fees based on recent market volatility, proving the historical user count in a specified pool, or implementing complex machine learning algorithms for rebalancing strategies. The possibilities are endless, as any computation ultimately leads to O(1) verification cost, no longer limited by EVM computational resources.

v4 Challenges

Uniswap v4 brings efficiency and customization to the AMM design space, supporting the creation of pools with different characteristics and functionalities. This is a significant advancement, but it comes with foreseeable costs: as the number of pools increases, liquidity fragmentation intensifies, making routing more challenging.

UniswapX

UniswapX aims to address liquidity fragmentation by outsourcing the complexity of routing to an open network of third-party fillers. These fillers compete with each other, using on-chain liquidity (such as AMM pools or their own private inventory) to execute exchanges. This design is user-centric, as users only need to declare their desired outcome and rely on professionals to fill the orders.

These fillers act as advanced agents equipped with advanced routing algorithms, high computational power, and significant financial capital. They compete with each other in a scheduled auction mechanism to provide the best execution for users. Users also benefit from price optimization, ensuring that their execution is at least as good as a trade directly from the Uniswap AMM pool.

The architecture of the UniswapX protocol is as follows. Exchangers submit their intent orders through the Uniswap API, structured as Permit2 executable off-chain signatures. Permit2 is a well-designed model that ensures the secure transfer of tokens held by users. Fillers design various strategies to fulfill these orders using any available liquidity venue, whether on-chain or off-chain. Finally, order reactors settle UniswapX orders. They are responsible for verifying specific types of orders, parsing them into inputs and outputs, executing orders based on fillers' strategies, and verifying the successful fulfillment of orders.

Source: Uniswap

Currently, in the Uniswap Labs' implementation of the UniswapX interface, the protocol is divided into two phases. The first is the RFQ phase, where "quoters" on the whitelist respond to orders with quotes. The winner of the quote has an exclusive period to fulfill the order. If the order is not fulfilled, it enters the second phase—the Dutch auction phase, where any filler can participate in the auction. The plan is to make the quoting system completely permissionless in the near future.

Information Source: Hayden Adams' "On-Chain Trading" presentation at EthCC conference

The user-centric design offers the following benefits:

  • Aggregating liquidity sources to obtain more suitable prices.

  • No need for Gas tokens even for cross-chain exchanges.

  • Internalizing the maximum extractable value through price optimization.

  • No cost incurred for failed transactions.

Challenges

  • Making the quoting system permissionless, for example, using an effective reputation system.

  • Attracting more fillers to ensure a competitive and permissionless auction environment.

Future: Infinite Game

The development of DEX does not stop here. Several other issues need to be addressed to achieve widespread adoption of cryptographic technology. Markus Schmitt (@haikane) of PropellerHeads (@PropellerSwap) and Frontier Research (@FrontierDotTech) have collaborated on an excellent article that delves into the essential components of an outstanding DEX and clarifies the remaining issues. According to the article, an excellent exchange should provide:

  • Trust: Ensuring transparency before, during, and after transactions and minimizing custodial risks.

  • Best prices: Continuously providing the best or competitive prices.

  • Fairness: Preventing order abuse and ensuring equal treatment for all users in pricing and fees.

  • Speed and availability: Providing fast transaction processing and maintaining high availability to avoid delays and inconvenience.

  • Information: Assisting users in making informed decisions by providing order monitoring, settlement price estimates, and useful advice for limit orders and slippage.

If DEX smart contracts are considered secure, trust can be established. DEX does not hold users' assets. Today, there is a wide range of information available to traders. The permissionless nature of AMM allows users to create and trade any asset pair. However, due to the nature of blockchain, the most suitable prices, fairness, speed, and availability cannot always be guaranteed. Gas fees, delayed prices, and fragmented liquidity can all impact the user experience.

To address these issues, the number of L2 and L2-based DEXs is increasing. Additionally, routing, order batching, and quote request systems are becoming more complex. To prevent front-running and ensure fair value distribution, more channels with MEV awareness are being used. Furthermore, efforts are being made to develop order flow auction markets to minimize value leakage for DEX users. The introduction of hooks and ZK coprocessors also greatly expands the design possibilities of AMM, supporting more complex logic and heavy computations without compromising trust.

Furthermore, there is a range of AMM-based protocols that effectively stack "money Legos." Some protocols help novice users automate liquidity rebalancing or leverage mining, such as liquidity managers. Other protocols use centralized liquidity (CL) positions to create margin trading, perpetual trading, options, and structured products.

AMM has experienced exponential growth due to its features such as permissionless listing, passive liquidity, and ease of trading. However, this convenience also brings several issues discussed earlier. Uniswap has been continuously pushing boundaries to address these issues and enhance the user experience. As Dan Robinson (@danrobinson) pointed out in his speech at SBC23, DEX design is an infinite game. As DEX becomes more widespread in the future, new challenges and issues may arise, requiring innovative solutions.

免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。

Bitget:注册返10%, 送$100
Ad
Share To
APP

X

Telegram

Facebook

Reddit

CopyLink