SevenX Ventures: The Growth Story of Uniswap - From Zero to Infinity

SevenX Ventures
2023-12-26 17:55:32
Collection
By studying the features of each version of Uniswap, it reveals how it effectively responds to various new challenges and adapts to changing demands.

This article is an original work by the SevenX research team, intended for communication and learning purposes only, and does not constitute any investment advice. Please cite the source if you wish to reference it.

The original English report was published on the SevenX Mirror platform in October 2023. For more Chinese investment research content, please follow the WeChat public account 【SevenXVentures】.

Author: Luke

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

There is no doubt that Uniswap is the most widely used decentralized application. It relentlessly pioneers innovative solutions, redefining industry rules. This article will delve into the astonishing journey of Uniswap, starting from zero and heading towards infinite possibilities in the future. By examining the features of each version of Uniswap, this article reveals how it effectively addresses various new challenges and adapts to changing demands. Additionally, it explores how the latest developments in cryptocurrency shape the future of decentralized exchanges (DEXs). Get ready to embark on this journey from zero to infinity.

v0: Proof of Concept

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

Many industry leaders (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 traditional order book models.

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 trading asset, and y represents the reserve of the pricing asset. When tokens are withdrawn (bought) from the pool, a certain proportion must be deposited (sold) to maintain k constant. The ratio of tokens in the pool determines the price of the tokens.

Uniswap Growth History: From Zero to Infinity

Notably, other AMMs use different mathematical formulas to represent liquidity curves. For example, Curve's Stableswap and Balancer's weighted pools.

Problems

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

  • Only applicable to single ETH/ERC 20 trading pairs.
  • Only applicable to single liquidity providers (LPs).

v1: Functional Decentralized Exchange (DEX)

Features

On November 2, 2018, Uniswap v1 went live on the mainnet. This version supports multiple liquidity providers using internal tokens to track fees and collateral. It uses factory contracts, allowing anyone to add any token for trading against native ETH. This version provides a functional DEX. However, some issues still need to be addressed.

Problems

Since all tokens are paired with ETH, users can easily exchange any ERC20 token for another ERC20 token in a single transaction using ETH as an intermediary. However, this method has a drawback: when exchanging stablecoins like DAI/USDT that are frequently traded, relying on ETH as an intermediary for each exchange can become inefficient. In such cases, direct token pairs are preferred.

v2: Money Lego

In May 2020, Uniswap v2 was launched, which included multiple upgrades to the Uniswap protocol, enhancing trading flexibility and expanding trading possibilities.

Features

ERC20/ERC20 Trading Pairs

A significant difference in Uniswap v2 is that it allows the addition of LP liquidity pools for ERC20 tokens paired 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 diversified portfolio of ERC20 token positions, including stablecoin trading pairs.

Price Oracles

Uniswap v2 provides on-chain price information for numerous DeFi applications. These price feeds are difficult to manipulate, making them very valuable. The 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 specific price persistence. This variable essentially represents the sum of the Uniswap price per second over the entire history of the contract.

Uniswap Growth History: From Zero to Infinity

External contracts can utilize 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 start and end of the interval, calculating the difference, and dividing it by the length of the interval, the TWAP for that specific period can be obtained.

Uniswap Growth History: From Zero to Infinity

Flash Swaps

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

Flash loans have gained notoriety as 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 atomic nature of flash loans eliminates the upfront capital requirements typically associated with inter-pool arbitrage and obtaining margin leverage.

Problems

Despite the innovative nature of this AMM and its facilitation of trading and liquidity in new markets, inefficiencies still exist. For instance, when dealing with low-volatility tokens, liquidity is only needed within a smaller price range. However, the current design distributes liquidity evenly 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 across the entire 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, achieving higher liquidity at expected prices. Through this customization, liquidity providers can build personalized price curves that align with their preferences. These individual positions then aggregate into a single pool, creating a unified curve that users can trade against. The result benefits both traders and liquidity providers: with liquidity highly concentrated within the customized range, traders experience less slippage, and liquidity providers can earn higher fees.

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

Range Orders

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

The functionality of range orders is similar to that of "limit orders," but with the drawback of being reversible—when the price reverses, the order also 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 receive appropriate compensation for taking on different levels of risk.

Advanced Oracles

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

Problems

Lack of Flexibility

Although concentrated liquidity and fee tiers provide greater flexibility for liquidity providers and facilitate the implementation of new strategies, Uniswap v3 has failed to adapt to the rapidly evolving functionalities and innovations in AMMs and markets. To integrate additional features such as TWAP orders, limit orders, advanced oracles, and dynamic fees, a reimplementation of the core protocol is necessary.

Through certain features (like the price oracles initially introduced in Uniswap v2), integrators can leverage decentralized on-chain pricing data. However, this comes at the cost of increased gas costs for traders and a lack of customization options for integrators.

Complex Liquidity Management

As previously mentioned, managing concentrated liquidity can be challenging for new liquidity providers, especially for volatile trading pairs. Although several automated liquidity management protocols have emerged, most employ simple rebalancing strategies designed for pegged assets. Unfortunately, these strategies often prove ineffective for volatile trading pairs, as long block times, increased gas costs, and rising hedging costs limit their effectiveness.

Additionally, since each liquidity provider's concentrated liquidity positions differ, LP tokens are essentially non-fungible. They can only be represented by non-fungible tokens (NFTs), which poses challenges for other DeFi protocols wishing to integrate with them.

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

Value Leakage

Among all the issues, value leakage is of paramount importance. While this problem is not unique to Uniswap v3, it has garnered attention due to the increase in AMM trading volumes and adoption rates since its launch. Value leakage primarily stems from the DEX system, taking the following forms:

Due to front-running and sandwich attacks, traders end up paying higher slippage than actually required.

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

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

v4: The Ultimate Platform

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

Efficiency

Singleton

In Uniswap v3, each pool is created as a separate contract through factory contracts. 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 only transfers based on net balances, greatly reducing accounting costs. With transient storage (proposed in EIP-1153), the costs of setting and clearing storage slots are lower, and storage slots are essential for the effective operation of flash accounting.

Uniswap Growth History: From Zero to Infinity

Native ETH

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

Customization

Hooks

Hook contracts (or hooks) are externally deployed contracts that execute predefined logic at specific points during pool execution. This is why v4 is so expressive and customizable. Through hooks, features previously built into the protocol (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 diagram below illustrates the logical flow of swap hooks. Before and after executing a swap, there is a dedicated boolean flag that allows 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 explore these concepts in more depth later.

Uniswap Growth History: From Zero to Infinity

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 came at the cost of reduced customization options and increased costs for traders. However, with the introduction of hooks, the design possibilities for oracles have greatly expanded. This opens up opportunities 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 pay gas fees instead of placing the burden on the first trader (which may not be sustainable). Despite optimizations, oracle design still faces challenges. For instance, TWAP oracles can sometimes be easily manipulated and often lag behind current prices.

Uniswap Labs has introduced another interesting price oracle, the truncated price oracle. This oracle calculates the geometric average 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 significant trades and enhances resistance to manipulation attempts.

Dynamic Fees

While Uniswap v3 introduced additional fee tiers for liquidity providers to choose from, these fee structures remain static and do not account for current market conditions. As a result, liquidity providers' services are not adequately compensated.

Alex Nezlobin (@0x94305) proposed a simple yet effective dynamic fee system that considers the price impact of the previous block and applies different fee standards to buyers and sellers. As shown in the diagram below: when the CEX price moves to p*, which is above the current AMM price p_AMM, the sell fee decreases by δ, while the buy fee increases by δ. The value of δ is proportional to the change in the AMM price. The purpose of this dynamic fee system is to distinguish between arbitrageurs and uninformed capital flows. Arbitrage flows are more likely to be autocorrelated with price movements.

Uniswap Growth History: From Zero to Infinity

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 crucial to ensure that fees do not fall below zero to limit liquidity providers' losses.

Auctions

Hooks can also serve as a means to implement auctions, which help redistribute value to liquidity providers. Depending on the timing, auctions can be categorized into pre-auctions and post-auctions.

Pre-auctions occur before the auction block. This concept was initially proposed in a research paper discussing MEV capture AMMs (McAMM). In this approach, the right to perform the first swap in the AMM before a block is auctioned is granted, and the bidding value is then redistributed. However, this bidding process also presents challenges, as it essentially involves option pricing, which can be very complex. Additionally, since block proposers have the final decision on whether to accept blocks containing trades, censorship issues may arise. Ensuring that bidding values are fairly and effectively distributed has also proven to be a complex task. Moreover, there is no guarantee that the winning bidder will be the first to exercise their swap rights, which could lead to a deteriorating experience for other traders.

Post-auctions occur after volatility has been realized, meaning that CEX prices have changed, but subsequent blocks have not yet been submitted. The advantage of this type of auction is increased efficiency, but it also presents challenges as they rely on trusted parties or off-chain infrastructure for trustlessness. If a trusted party is used, issues of censorship and bidding privacy arise. On the other hand, designing a trustless system is much more complex. Post-auctions also face the significant issue of proposers potentially colluding with bidders, such as timely excluding arbitrage trades. Furthermore, there is a major problem with delays in the bidding, consensus on winning bids, and distributing these bids to block builders, all of which must be completed before submitting subsequent blocks. Finally, it may be challenging to ensure that there are sufficient competitive conditions in these auctions to capture enough value. Sorella Labs (@SorellaLabs) is taking the lead in addressing these challenges with its advanced infrastructure and mechanism design.

Diamond Hooks

The Diamond protocol was initially designed as an AMM that minimizes LVR. Under the Diamond protocol, block proposers 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 between the Diamond mining pool and block proposers in a way that maintains incentive compatibility.

As discussed in this article, a variant of the Diamond protocol includes implementing a collateral pool to maintain the block-end price based on the price promised by the block proposer. Swaps will only be executed if there is sufficient 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 a hook contract using v4 to achieve this goal.

Advanced Order Types

Hooks also support more advanced order types, greatly enhancing the trader 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 the hook contract. When the price reaches the specified minimum tick, the order is executed. 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. Thus, this creates the issue of low order trading volume.
  • Time-Weighted Average Market Maker (TWAMM)
  • A viable solution is to implement a Time-Weighted Average Market Maker (TWAMM) to facilitate the execution of large orders. This method can break large orders into smaller chunks and ensure they are executed as the first trades, preventing sandwich attacks. Additionally, it may be considered to lower TWAP order fees, as they typically involve uninformed processes. However, the accompanying challenge is the high gas costs and determining who should bear these costs.

Other Hooks

Using hooks can also enable several other functionalities. Here are some ideas:

  • A hook that generates yield by borrowing out-of-range liquidity to money markets to improve capital efficiency.
  • Pools that have both xy=k liquidity curves and concentrated liquidity.
  • Pools that provide withdrawal fees for liquidity providers to reduce immediate liquidity attacks.

Suning (@msfew_eth) has shared some intriguing ideas about hooks on GitHub. Aiden (@aiden0x4) has also published 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. With the introduction of hooks, seamless integration of zero-knowledge proofs into Uniswap v4 is now possible, ushering in a new era of zkAMM.

HyperOracle (@HyperOracle) demonstrated a zkAMM implementation based on Uniswap v2, where the addLiquidity calculation is transferred off-chain. When users add liquidity, the number of tokens, 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 proofs, and publishes them. This implementation of zkAMM includes an integrated automation layer to verify the proof and mint LP tokens for users.

Diego (@0xfuturistic) introduced a zkAMM (zkUniswap) implementation based on Uniswap v3, where part of the AMM swap calculations is transferred to the RiscZero (@RiscZero) zkVM. When users execute swaps in the pool, several parameters need to be calculated to complete the swap. These parameters include the amount to be swapped, fees, and the price after the swap. Initially, this calculation was performed through EVM in Solidity contracts. However, in the new implementation, the swap input is picked up by a relayer, and the calculations are performed off-chain. The relayer then publishes the output and proof. The AMM verifies the proof and settles the swap. zkUniswap implements a lock auction mechanism to ensure concurrent control. While its current performance is comparable to EVM, parallelization of batch swaps can significantly improve efficiency.

Proof of trading volume is another use case for AMMs. Brevis (@brevis_zk) provides an interesting example of designing a fee rebate hook based on users' historical trading volumes, similar to volume-based fee rebates on centralized exchanges (CEXs). VIP traders can now calculate their monthly trading volume off-chain and then submit low-cost zero-knowledge proofs to the blockchain to asynchronously verify their VIP status. Once verified, subsequent trades can access the "VIP fee tier table" populated by zero-knowledge coprocessors through the post-swap hook. This allows for the automatic application of appropriate fee rebates. Maru Network (@marunetwork) is currently developing a trustless trading volume oracle as an initial use case for its ZK coprocessor network. By implementing a trustless trading volume oracle, DEXs will be able to allocate rewards in a fair and transparent manner. This approach can proportionally incentivize liquidity and user activity, creating a positive feedback loop. By utilizing zero-knowledge proof aggregation services like NEBRA (@nebrazkp) UPA (Universal Proof Aggregation), the costs of proof verification can be reduced, as NEBRA UPA aggregates proofs from various loops and parties into a single proof to lower amortized verification costs.

In summary, the concept of zkAMM involves leveraging ZK coprocessors or ZK oracles to transfer calculations from the EVM and verify proofs of on-chain calculations. Compared to calculations related to swaps and liquidity adjustments, these calculations can be much more complex. For example, these calculations may involve computing dynamic fees based on recent market fluctuations, proving the historical number of users in a specified pool, or implementing rebalancing strategies using complex machine learning algorithms. There will be infinite possibilities, as any calculation will ultimately lead to O(1) verification costs, no longer constrained 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 the trade-off is foreseeable: with the surge in the number of pools, liquidity fragmentation intensifies, making routing more challenging.

UniswapX

UniswapX aims to address the issue of liquidity fragmentation by outsourcing the complexity of routing to an open network of third-party fillers. These fillers compete with each other to execute swaps using on-chain liquidity (such as AMM pools or their own private inventories). This design is goal-oriented, allowing users to simply state the results they want and rely on professionals to fill the orders.

These fillers are advanced agents equipped with sophisticated routing algorithms, high computational power, and substantial financial capital. They compete under a predetermined auction mechanism to provide users with the best execution methods. Users can also benefit from price optimization, ensuring that their execution is at least as good as trading directly from Uniswap AMM pools.

The architecture of the UniswapX protocol is illustrated below. Traders 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 complete these orders using any available liquidity venue, whether on-chain or off-chain. Finally, order reactors resolve UniswapX orders. They are responsible for verifying specific types of orders, parsing them into inputs and outputs, executing orders according to fillers' strategies, and verifying whether the orders were successfully fulfilled.

Uniswap Growth History: From Zero to Infinity

Currently, in Uniswap Labs' interface implementation of UniswapX, the protocol is divided into two phases. The first is the RFQ phase, where "quoters" on the whitelist respond to orders with quotes. The winning quote then has an exclusivity 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. A fully permissionless quoting system is planned for the near future.

Uniswap Growth History: From Zero to Infinity

The goal-oriented design offers the following benefits:

  • Aggregating liquidity sources for better pricing.
  • No need for gas tokens even for cross-chain swaps.
  • Internalizing maximum extractable value through price optimization.
  • No fees incurred for failed trades.

Challenges

  • Making the quoting system permissionless, for example, by using an effective reputation system.
  • Attracting more fillers to ensure a competitive and permissionless auction environment.

Future: Infinite Game

The development of DEXs does not stop here. To achieve widespread adoption of crypto technology, several other issues remain to be addressed. Markus Schmitt (@haikane) from PropellerHeads (@PropellerSwap) collaborated with FrontierResearch (@FrontierDotTech) to write an excellent article that delves into the components of a great DEX and identifies the outstanding issues. According to the article, an excellent exchange should provide:

  • Trust: Ensuring transparency before, during, and after trades while minimizing custodial risks.
  • Best Pricing: Continuously offering the best or competitive prices.
  • Fairness: Preventing order abuse and ensuring all users enjoy equal treatment in pricing and fees.
  • Speed and Availability: Providing fast transaction processing and maintaining high availability to avoid delays and inconveniences.
  • Information: Helping users make informed decisions by providing order monitoring, settlement price estimates, and useful suggestions regarding limit orders and slippage.
  • Liquidity: Demonstrating strong liquidity pools across various asset pairs to instill confidence in obtaining favorable prices.

If the smart contracts of DEXs are deemed secure, trust can be established. DEXs do not hold users' assets. Nowadays, the information available to traders is quite extensive. The permissionless nature of AMMs allows users to create and trade any asset pair. However, due to the characteristics of blockchains, the best prices, fairness, speed, and availability cannot always be guaranteed. Gas fees, lagging prices, and fragmented liquidity can all impact the user experience.

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

Moreover, a range of AMM-based protocols effectively stack "money legos." Some protocols help novice users automate liquidity rebalancing or leverage mining, such as liquidity managers. Others utilize concentrated liquidity (CL) positions to create margin trading, perpetual trading, options, and structured products.

AMMs have achieved exponential growth due to their permissionless listing of tokens, passive liquidity, and ease of trading. However, this convenience has also brought about several issues we discussed earlier. Uniswap has been continuously pushing boundaries to address these problems and enhance user experience. As Dan Robinson (@danrobinson) pointed out in his speech at the SBC 23 conference, DEX design is an infinite game. As DEXs become more prevalent in the future, new challenges and issues may arise, necessitating innovative solutions.

ChainCatcher reminds readers to view blockchain rationally, enhance risk awareness, and be cautious of various virtual token issuances and speculations. All content on this site is solely market information or related party opinions, and does not constitute any form of investment advice. If you find sensitive information in the content, please click "Report", and we will handle it promptly.
banner
ChainCatcher Building the Web3 world with innovators