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 invaluable discussions, insights, and feedback on this article.
Undoubtedly, Uniswap stands as one of the most widely used decentralized applications. It relentlessly pioneers innovative solutions that redefine the game. In this article, I will delve into Uniswap's awe-inspiring journey from the past to a limitless future. By examining the features of each version of Uniswap, I uncover how it effectively tackles new challenges and adapts to ever-changing demands. Additionally, I explore how the latest advancements in crypto are shaping the future of decentralized exchanges (DEX). Prepare for a journey from zero to infinity.
Prior to Uniswap, EtherDelta was the only decentralized exchange (DEX) that gained traction. However, the user experience was poor.
The concept of an Automated Market Maker (AMM), proposed by many industry leaders (Alan Lu of Gnosis and Vitalik), offers an alternative approach to on-chain trading compared to traditional order-book models.
Constant Product AMM
Uniswap utilizes a constant product formula (x * y = k) to calculate the price of an asset. In this formula, x represents the reserve of the base asset, while y represents the reserve of the quote asset. When a token is withdrawn (bought) from a pool, a proportional amount must be deposited (sold) to ensure that the constant k is maintained. The ratio of tokens in the pool determines the price of a token.
It's worth noting that other AMMs utilize different mathematical formulas to represent liquidity curves. Some examples include Curve's Stableswap and Balancer's weighted pools.
Uniswap v0 is essentially a Proof-of-Concept, meaning there are still many unresolved issues. The two major problems are as follows:
It only worked for a single ETH/ERC20 pair.
It only worked for a single liquidity provider (LP).
Uniswap v1 launched on Ethereum mainnet on November 2, 2018. It supports multiple liquidity providers using an internal token to track fees and collateral. It utilizes a factory contract that enables anyone to add any token for trading against native ETH. This version provides a functional DEX. However, there are certain issues that need to be addressed.
Since all tokens are paired with ETH, users can easily swap any ERC20 token for another ERC20 token by using ETH as an intermediary in a single transaction. However, there is a drawback: when it comes to frequent stablecoin swaps like DAI/USDT, relying on ETH as an intermediary for every swap becomes inefficient. In this case, a direct token pair is preferred.
In May 2020, Uniswap v2 was launched, introducing numerous upgrades to the Uniswap Protocol. These enhancements increased its flexibility and expanded the range of trades possible.
In Uniswap V2, there is a notable difference: instead of only pairing ERC20 tokens with ETH, now any ERC20 token can be directly pooled with any other ERC20 token. This feature offers great utility for liquidity providers as they can now maintain more diverse ERC20 token-denominated positions, including Stablecoin pairs.
Uniswap v2 offers on-chain price feeds that can be utilized by numerous DeFi applications. These price feeds are resistant to manipulation, making them highly valuable. The mechanism involves adding the end-of-block price to a cumulative-price variable in the core contract, which is weighted by the duration of time that particular price existed. This variable essentially represents the sum of Uniswap prices for every second throughout the contract's entire history.
This variable can be utilized by external contracts to accurately track time-weighted average prices (TWAPs) over any given time interval. The process involves reading the cumulative price from an ERC20 token pair at the start and end of the interval. By calculating the difference in this cumulative price and dividing it by the length of the interval, a TWAP for that specific period can be generated.
Uniswap v2 also introduces Flash Swaps, which is a type of flash loan pioneered by the lending market AAVE. This feature allows any user to withdraw as much as ERC20 token in a pool with no upfront cost and do arbitrary actions, provided that by the end of the transaction execution equivalent values (plus fees) are returned.
Flash loan features get its bad reputation as it comes often in headline with various kinds of attacks on DeFi protocols. But flash loans are not the problem. The real issues are existing vulnerabilities in a protocol. The atomic nature of flash loans eliminates the need for upfront capital requirements typically associated with operations such as arbitraging between pools and obtaining margin leverage.
Although the AMM is innovative and beneficial for bootstrapping trading and liquidity in new markets, it still has some inefficiencies. For instance, when dealing with low volatility tokens, liquidity is only necessary within a narrow price range. However, the current design distributes liquidity uniformly across all price ranges.
Uniswap v3 aims to be the most flexible and efficient AMM due to its groundbreaking concentrated liquidity design.
In Uniswap v2, liquidity is evenly distributed across an x*y=k price curve, encompassing all prices from 0 to infinity. However, in most pools, a significant portion of this liquidity remains unused.
In Uniswap v3, liquidity providers (LPs) have the ability to concentrate their capital within specific price ranges, allowing for increased liquidity at desired prices. This customization enables LPs to construct personalized price curves that align with their preferences. These individual positions are then aggregated into a single pool, creating a unified curve against which users can trade. The outcome is mutually beneficial for both traders and liquidity providers: Traders experience reduced slippage and LPs earn greater fees, thanks to the higher concentration of liquidity within a customized range.
CL is incredibly valuable for stable pairs, such as stablecoins and liquid staking derivative tokens. These assets tend to be traded within a narrow price range. However, for more volatile token pairs, CL requires more advanced liquidity management techniques. It may be challenging for average retail liquidity providers to consistently manage their positions effectively.
With CL, a novel order type called range orders are introduced to complement market orders. LPs have the ability to deposit a single token within a custom price range, either above or below the current price. If the market price falls within their specified range, they can sell one asset for another along a smooth curve, all while earning swap fees.
A range order functions similarly to a 'limit order,' but with the drawback of reversibility- when the price reverses, the order is also reversed. However, fees are still earned in the process. Barry Fried (@BarryFried1) offers a detailed example of how to use range orders in this thread.
Instead of having one fee tier, Uniswap v3 introduces three separate fee tiers per pair — 0.05%, 0.30%, and 1.00%, allowing LPs to be appropriately compensated for taking on varying degrees of risk
Uniswap v3 offers significant improvements to the price oracle. Instead of storing only one price cumulative variable, v3 stores an array of variables, making it far easier and cheaper to create more advanced oracles that include simple-moving averages (SMA), exponential moving averages (EMA), outlier filtering, and more.
Although concentrated liquidity and fee tiers provided more flexibility for liquidity providers and enabled the implementation of new strategies, Uniswap v3 fell short in accommodating the evolving functionalities and innovations in AMMs and markets. To incorporate additional features such as TWAP orders, limit orders, advanced oracles, and dynamic fees, it would have been necessary to re-implement the core protocol.
Certain features, such as the price oracle initially introduced in Uniswap v2, enabled integrators to utilize decentralized on-chain pricing data. However, this came at the expense of increased gas costs for swappers and lacked customization options for integrators.
As mentioned earlier, concentrated liquidity is challenging to manage for unsophisticated liquidity providers, particularly for volatile pairs. While several automatic liquidity management protocols have emerged, they mostly consist of simple rebalancing strategies designed for pegged assets. Unfortunately, these strategies are ineffective when it comes to volatile pairs because of the limitations imposed by long block times, gas costs, hedging costs, etc.
Moreover, since the concentrated liquidity position varies for each liquidity provider, the LP token is inherently non-fungible. It can only be represented by a non-fungible token (NFT), which presents a challenge for other DeFi protocols looking to integrate with it.
Numerous outstanding projects are actively addressing this issue using a range of strategies, including rebalancing, dynamic hedging with money markets, perpetuals, and options. Atis Elsts (@atiselsts_eth) has written a series of excellent articles on LP strategies that are highly recommended.
The issue of value leakage is the most significant problem of all. While this is not unique to Uniswap v3, it has gained attention due to the increased volumes and wider adoption of AMMs since the launch of v3. This value leaks out of the DEX system in forms of
Traders end up paying higher slippage than necessary due to front running and sandwich attacks.
Liquidity providers lose value through CEX-DEX arbitrages (a.k.a. Loss-versus-Rebalancing)
To address these problems, we need more customized and sophisticated designs that go beyond what Uniswap v3 currently offers. We require a DEX platform that is more expressive and powerful.
Uniswap v4 builds on top of AMM models introduced in previous generations and through the introduction of 'hooks', it aims to be the ultimate DEX platform with high efficiency and customization.
In Uniswap v3, every pool is created as an individual contract through a factory contract. On the other hand, in v4, all pools coexist within a single smart contract (known as a singleton). This singleton model significantly decreases the expenses associated with creating pools and executing multi-hop trades.
In v4, the singleton utilizes flash accounting to optimize asset transfers. Unlike in v3, where assets are moved in and out of pools after every swap, the v4 system only transfers based on net balances. This significantly reduces the cost of accounting. Transient storage (proposed in EIP-1153) makes it cheaper to set and clear a storage slot which is necessary for flash accounting to operate effectively.
Uniswap v4 reintroduces support for trading against native ETH, which brings several benefits. Traders can enjoy reduced gas costs for cheaper transfers and the elimination of additional wrapping costs.
Hook contracts (or hooks), are externally deployed contracts that execute pre-defined logic at specific points during the execution of a pool. This is what makes v4 so expressive and customizable. Hooks allow for the implementation of features that were previously built into the protocol, such as oracles, as well as new features that previously required independent protocol implementations.
Uniswap v4 currently supports eight such hook callbacks:
beforeInitialize/afterInitialize
beforeModifyPosition/afterModifyPosition
beforeSwap/afterSwap
beforeDonate/afterDonate
The figure below illustrates the logic flow for a Swap Hook. Before and after executing a swap, there is a dedicated boolean flag that enables the execution of custom code at these specific points. This serves as the basis for developing advanced features like oracles, dynamic fee structures, auctions, and advanced order types, etc. We will delve deeper into these concepts in the following sections.
In previous versions, oracles were integrated into the core Uniswap protocol. While this made integration easier and cheaper for other protocols, it came at the expense of customization options and higher costs for swappers. However, with the introduction of hooks, the design possibilities for oracles have significantly expanded. This opens up the opportunity to create manipulation-resistant oracles such as winsorized price oracles as well as volatility oracles. Additionally, the choice of who bears the costs of updating oracles can now be customized. For example, instead of burdening the first swapper with the cost, which may not be sustainable, a hook contract with an ETH balance could be used for gas payment. Despite these advancements, designing oracles still presents challenges. For instance, TWAP oracles are sometimes susceptible to manipulation and tend to lag behind current prices.
Uniswap Labs has introduced another intriguing price oracle known as the truncated price oracle. This oracle calculates the geometric mean price of an asset in a liquidity pool and imposes a limit on price movement within a single block. By truncating the price, this on-chain oracle mitigates the price impact of significant trades, enhancing resistance to manipulation attempts.
While Uniswap v3 introduced additional fee tiers for LPs to select from, these fee structures remain static and do not consider current market conditions. Consequently, LPs are not adequately compensated for their services.
Alex Nezlobin (@0x94305) proposed a simple yet effective dynamic fee structure that considers the price impact of the previous block and applies different fees for buyers and sellers. The following figure illustrates an example: when the CEX price moves to p*, which is higher than the current AMM price p_AMM, the fee for sales decreases by δ, while the fee for buys increases by δ. The value of δ is proportional to the change in AMM price. The purpose of this dynamic fee structure is to differentiate between arbitrageurs and uninformed flows. Arbitrage flows are more likely to be autocorrelated with price movements.
Designing a robust dynamic fee structure presents several challenges. One challenge is how to incorporate off-chain signals, such as CEX price, liquidity depth, and volatility. Additionally, various on-chain signals, including address, size, and execution time, can be unreliable for differentiating between informed and uninformed flow, making it difficult to assess their effectiveness. Furthermore, it is important to ensure that fees do not go below zero in order to limit losses for LPs.
Hooks can also serve as a means to implement auctions, which can aid in redistributing value back to LPs. Depending on the timing, auctions can be categorized as either ex ante or ex post auctions.
Ex ante auctions take place prior to the block. This concept was initially introduced in a research article that discussed MEV capturing AMM (McAMM). In this approach, the right to make the first swap in an AMM before a block is auctioned off, and the bid values are subsequently redistributed. However, there are challenges associated with this bidding process, as it essentially involves pricing an option, which can be highly complex. Additionally, since block proposers hold the ultimate decision-making power regarding whether to accept a block containing the trades, issues of censorship may arise. Ensuring fair and efficient distribution of bid values can also prove to be a complicated task. Moreover, there is no guarantee that the winners of the bids would exercise their right to swap first, potentially resulting in a deteriorating experience for other traders.
Ex post auctions are conducted after volatility has been realized, meaning that CEX prices have already moved but before the subsequent block has been committed. The advantage of these auctions is their increased effectiveness. However, they pose challenges as they require off-chain infrastructure that relies either on trusted parties or trustless systems. If trusted parties are used, concerns arise regarding censorship and bid privacy. On the other hand, designing trustless systems is much more complex. Ex post auctions also face the issue of proposers potentially playing games with bidders, such as excluding arbitrage trades from being included in a timely manner. Additionally, there is the significant problem of extra latency involved in bidding, running consensus on winning bids, and distributing those bids to block builders—all of which need to be completed before the subsequent block is committed. Finally, it may be difficult to ensure sufficient competitive conditions in these auctions to capture enough value. Sorella Labs (@SorellaLabs) is leading the charge in addressing these challenges by leveraging its advanced infrastructure and mechanism designs.
The Dimond Protocol was initially designed as an LVR-minimizing AMM. In Diamond, block producers conduct auctions to capture any arbitrage opportunities between the external market price of a Diamond pool and the pool's own price. The proceeds from these auctions are shared between the Diamond pool and the block producer in a manner that remains incentive compatible for the block producer.
A variation of the Dimond Protocol, as discussed in this post, involves implementing a collateral pool to maintain the end-of-block price in accordance with the committed price by block producers. Swaps will only execute if there is sufficient collateral available to restore the price to the committed value. Arrakis (@ArrakisFinance) is currently collaborating with Conor McMenamin (@ConorMcMenamin9), one of the authors of the Diamond Protocol, to develop an implementation using v4 hooks.
Advanced Order Types
Hooks could also enable more advanced order types that greatly improve trader experience. Some common order types include limit orders, stop loss, take-profit, TWAP
Limit Orders
Traders have the option to submit on-chain limit orders to the hook contract. When the price reaches the specified tick price, the order is filled. However, these on-chain limit orders have a significant disadvantage compared to traditional finance (tradfi) limit orders. This is primarily because on-chain orders cannot be cancelled without incurring gas fees. As a result, this creates a problem known as a low order-to-trade ratio.
TWAMM
One possible solution for facilitating the execution of large orders over time is to implement a time-weighted average market maker (TWAMM). This approach involves breaking down large orders into smaller blocks and ensuring they are executed as the first trades, thus preventing sandwich attacks. Additionally, reducing TWAP order fees could be considered since they typically involve uninformed flow. However, a challenge arises with the high gas costs and determining who should bear these expenses.
Other Hooks
There are several other features that could be implemented using hooks. Here are some ideas:
A yield-bearing hook that lends out-of-range liquidity into money markets to increase capital efficiency.
A pool with both xy=k liquidity curve and concentrated liquidity.
A pool with withdrawal fees for LPs to reduce Just-in-time liquidity attacks.
Suning (@msfew_eth) provides an awesome curation of hook ideas and implementations on Github. Aiden (@aiden0x4) also publishes a nice open directory for hooks.
ZK Coprocessors empower smart contracts with the ability to access data insights akin to those offered by Dune Analytics, all without compromising trust due to the application of Zero-Knowledge (ZK) Proof technologies. The utilization of zk Coprocessors in AMM designs has been an emerging and actively researched area. The introduction of hooks now allows for the seamless integration of zk proofs into Uniswap v4, ushering in a new era of zero knowledge AMMs, or zkAMMs.
HyperOracle (@HyperOracle) demonstrates an implementation of zkAMM based on Uniswap v2, where the addLiquidity computation is offloaded off-chain. When a user adds liquidity, the token amount, price, and LP token shares need to be computed. In this particular implementation, HyperOracle's zkGraph captures the addLiquidity event, performs the necessary computation, generates the proof, and publishes it. This implementation of zkAMM includes an integrated automation layer that verifies the proof and mints the LP token for the user.
Diego (@0xfuturistic) introduces an implementation of zkAMM (zkUniswap) based on Uniswap v3 where a portion of the AMM swap computation is offloaded to the Risc Zero (@RiscZero) zkVM. When a user performs a swap in a pool, several parameters need to be calculated to finalize the swap. These parameters include the amount to be swapped in and out, the fee, and the price after swapping. Originally, this computation was performed within the solidity contract through EVM. However, with the new implementation, the swap inputs are picked up by the relayer, and the computation is carried out off-chain. The relayer then posts the output and the proof. The AMM verifies the proof and settles the swap. zkUniswap implements a lock auction mechanism to ensure concurrency control. While its current performance is comparable to that of the EVM, the efficiency could be significantly enhanced through parallelization for batched swaps.
Proof of volume serves as another use case for AMMs. Brevis (@brevis_zk) provides an interesting example where a fee rebate hook could be designed based on users' historical trading volume, similar to trading-volume-based fee rebates on centralized exchanges (CEXes). VIP traders now have the ability to calculate their monthly trading volume off-chain and then submit a low-cost ZK proof to the blockchain for asynchronous verification of their VIP status. Once verified, subsequent trades can utilize post-swap hooks to access a "VIP fee-tier table" populated by the ZK Coprocessors. This allows for automatic application of the appropriate fee rebates. Maru Network (@marunetwork) is currently developing trustless volume oracles as their initial use case for their zk Coprocessor network. By implementing a trustless volume oracle, DEXes would be able to distribute rewards in a fair and transparent manner. This approach allows for proportional incentivization of liquidity and user activities, fostering a positive flywheel effect. The cost of proof verification can be reduced by using zero-knowledge proof aggregation services such as NEBRA (@nebrazkp) UPA (Universal Proof Aggregation), which aggregates proofs from different circuits and different parties to a single proof to achieve reduced amortized verification cost.
In summary, the concept of zkAMMs involves utilizing zkCoprocessors or zkOracles to shift computations away from the EVM and verify the proof of computation on-chain. These computations can be significantly more intricate than those related to swaps and liquidity adjustments. For instance, they could involve calculating dynamic fees based on recent market volatility, proving historic volumes of users in a given pool or implementing rebalancing strategies using complex machine learning algorithms. The possibilities are endless, as any computation ultimately results in an O(1) verification cost, no longer constrained by the computational resources of the EVM.
Uniswap v4 introduces efficiency and customization to the AMM design space, enabling the creation of pools with diverse features and functionalities. However, this advancement comes with a foreseeable trade-off: an increase in liquidity fragmentation due to the proliferation of pools. As a result, routing becomes significantly more challenging.
UniswapX aims to tackle the issue of liquidity fragmentation by outsourcing the complexity of routing to a open network of third-party fillers. These fillers compete with each other to execute swaps using on-chain liquidity like AMM pools or their own private inventory. This design is intent-centric, allowing users to simply state their desired outcomes and rely on professionals to fulfill them.
These fillers are sophisticated agents equipped with advanced routing algorithms, high computational power, and substantial financial capital. They compete with each other under a predetermined auction mechanism to offer users the best possible execution. Users may also receive price improvement, ensuring that their executions are at least as good as trades directly from Uniswap AMM pools.
The architecture of the UniswapX protocol is depicted below. Swappers submit their intent orders, which are structured as Permit2 executable off-chain signatures, through the Uniswap API. Permit2 is an elegant model that ensures the safe movement of tokens held by users. Fillers devise strategies to fulfill these orders using any liquidity venue available to them, whether on-chain or off-chain. Finally, Order Reactors settle UniswapX orders. They are responsible for validating orders of a specific type, resolving them into inputs and outputs, executing them based on the filler's strategy, and verifying successful fulfillment of the order.
In the current Uniswap Labs interface implementation of UniswapX, the protocol is broken into two phases. The first is the RFQ phase, where whitelisted 'quoters' respond with quotes to the orders. The winner of the quote then has an exclusivity period to fill the order. If they don't, then it enters the second phase, the Dutch Auction phase, which is a auction that any filler can take part in. The plan is to make the quoting system fully permissionless in the near future.
The intent-centric design offers several benefits.
Aggregating liquidity sources for better prices.
No requirement for gas tokens, even for cross-chain swaps.
Internalization of MEV through price improvement.
No cost incurred for failed transactions.
Making the quoting system permissionless, e.g. Using an effective reputation system.
Attracting more fillers to ensure a competitive and permissionless auction environment.
The development of DEXes doesn't stop here. In order for crypto to achieve mass adoption, there are several other issues that need to be addressed. Markus Schmitt (@_haikane_) from PropellerHeads (@PropellerSwap), in collaboration with Frontier Research (@FrontierDotTech), has written an outstanding article that delves into what constitutes a good DEX and identifies the remaining problems that need to be solved. According to his perspective, a good exchange should offer:
Trust: Ensuring transparency and minimizing custody risks before, during, and after transactions.
Best Prices: Providing confidence in obtaining the best or competitive prices consistently, eliminating the need to search elsewhere.
Fairness: Preventing abuse of orders and ensuring equal treatment regarding pricing and fees for all users.
Speed and Availability: Offering fast transaction processing and maintaining high availability to avoid delays and inconveniences.
Information: Assisting users in making informed decisions by providing order monitoring, settlement price estimates, and helpful suggestions for limit orders and slippage.
Liquidity: Demonstrating a robust liquidity pool across various asset pairs, instilling confidence in obtaining favorable prices.
If the smart contracts of DEXes are considered safe, trust is already built-in. DEXes don't hold users' assets. The information available to traders is quite extensive now. The permissionless nature of AMMs enables users to create and trade any asset pairs. However, due to blockchain characteristics, ensuring the best prices, fairness, speed, and availability is not always guaranteed. Gas fees, stale prices, and fragmented liquidity all contribute to impacting users' experience.
To address these issues, we are witnessing a proliferation of L2s and DEXes on L2s. Additionally, we are seeing more sophisticated routing, order batching, and Request-for-quotes systems. To prevent front-running and ensure fair value distribution, more MEV-aware channels are being employed. Moreover, efforts are underway to develop order flow auction markets that minimize value leakage for DEX users. The introduction of hooks and zk Coprocessors also significantly expands the design possibilities for AMMs, allowing for more complex logic and heavy computations without compromising trust.
Additionally, there is a suite of protocols that build upon AMMs, effectively stacking the “money lego”. These protocols include liquidity managers that assist unsophisticated users in automating liquidity rebalancing or leveraging farming. There are also protocols that utilize Concentrated Liquidity (CL) positions to create margin trading, perpetuals, options, and structured products.
AMMs have witnessed exponential growth thanks to their permissionless listing, passive liquidity, and ease of trading. However, this convenience also brings along several issues that we have explored so far. Uniswap is consistently pushing the boundaries to address these issues and enhance the user experience. As Dan Robinson (@danrobinson) aptly puts it in his speech at SBC23, DEX design is an infinite game. With increased adoption of DEXes in the future, new challenges and problems are likely to arise, necessitating innovative solutions.