Overview
Uniswap is a decentralized exchange that is fully run by an AMM (Automated Market Maker) algorithm that allows users to create pools, or token pairs, and fill them with liquidity to let users exchange tokens.
Uniswap allows anyone to become a market maker, democratizing liquidity provision and reducing centralization risks. By enabling asset swaps, the protocol also serves as a price oracle, attracting arbitrageurs to keep its token prices in line with those on other centralized or decentralized exchanges.
In traditional centralized markets, market makers play a critical role to facilitate trades and offering favorable liquidity conditions for traders to swap assets with as low price slippage as possible. In this context, liquidity refers to the availability of trading assets in the market, and without it, trades cannot occur. For example, some trading pairs, such as BTC-USDT, have high liquidity, while others, like certain low-quality altcoins, may have low or no liquidity at all.
To properly function, Decentralized exchanges (DEXs) need ample liquidity to serve as a viable alternative to centralized exchanges. One approach to achieving this liquidity is for DEX developers to use their own funds or investor capital to act as market makers. However, this method is not realistic due to the large amount of capital needed to provide liquidity for all token pairs. Additionally, it would lead to centralization, as developers would have significant control over the exchange. Uniswap makes it possible to remove that risk and offer a more effective solution by utilizing an automated market maker (AMM) model. This model allows any user to deposit funds into a trading pair, effectively serving as a market maker and benefiting from it.
Liquidity pools are the backbone of the Uniswap platform. They consist of tokens locked in a smart contract to facilitate trading and earn fees in return. The larger the liquidity pool, the deeper the liquidity and, therefore, the lower the slippage and higher the overall trading efficiency. Users can trade any token pair, as long as there is a liquidity pool available for that pair, trading prices are determined by the AMM’s pricing formula.
There are 3 versions of Uniswap, with Uniswap V4 currency being actively worked on and in a status of the draft:
- Uniswap V1 was launched in November 2018 and it allowed only swaps between ETH and another asset. Chained swaps were also possible to allow token-token swaps.
- Uniswap V2 was launched in March 2020 and it allowed direct swaps between any ERC20 tokens, as well as chained swaps between any pairs.
- Uniswap V3 was launched in May 2021 and it significantly improved capital efficiency. With concentrated liquidity, it allowed liquidity providers to remove a bigger portion of their liquidity from pools and still keep getting the same rewards (or squeeze the capital in smaller price ranges and get up to 4000x of profits).
- The vision for Uniswap v4 is to increase the expressiveness of the underlying primitives. Announced as public infrastructure for the Ethereum ecosystem, the goal of Uniswap V4 is to empower developers with the appropriate tools to build unprecedented primitives. Instead of making the tradeoff decisions itself, the protocol will allow anyone to choose what they want to build and how they want to build it.
Although Uniswap is a popular example of an AMM, the concept behind it has been studied in academic literature for over a decade. Most AMMs were initially designed for information aggregation and implemented in prediction markets, where payoffs depend on the future state of the world.
The most well-known AMM is the LMSR (Logarithmic Market Scoring Rule), developed in 2002 and used in prediction markets such as Augur V1 and Gnosis. Other AMM approaches for information aggregation include Bayesian market makers (adequate for binary outcomes) and dynamic pari-mutuel market makers (often used in horse racing).
Uniswap employs a “constant product market maker” model, a type of AMM referred to as a CFMM (Constant Function Market Maker). It is important to differentiate CFMMs from other AMMs. One common misconception is to use “bonding curve” interchangeably with CFMM.
- Bonding curves define the relationship between price and token supply.
- CFMMs define the relationship between two or more tokens.
Constant Function Market Makers (CFMMs) are a type of automated market maker with a unique characteristic: any trade must change the reserves in a way that the product of those reserves remains constant. This model takes into account 3 main participants: traders, liquidity providers, and arbitrageurs.
- Traders exchange one asset for another within the CFMM by swapping tokens based on the current exchange rates determined by the constant function mechanism.
- Liquidity providers willingly accept trades against their portfolio in exchange for a fee. They contribute to the reserves of assets in the CFMM, facilitating trades and earning fees as compensation for their provided liquidity.
- Arbitrageurs maintain the price of assets within the CFMM in accordance with the market price by taking advantage of price discrepancies between the CFMM and other marketplaces. They buy and sell assets to profit from these differences, indirectly contributing to the price stability of assets within the CFMM. They basically act as market makers for the DEX.
CFMMs are commonly used for secondary market trading and tend to accurately reflect the price of individual assets on reference markets, thanks to arbitrage. For example, if the CFMM price is lower than the reference market price, arbitrageurs will buy the asset on the CFMM and sell it on an order book-based exchange, profiting from the price difference.
Benefits of Constant Function Market Makers
- Fast exchange of assets, since CFMMs allow for immediate token swaps, overcoming the coincidence of wants problem present in traditional orderbook exchanges.
- Bootstrapping liquidity is simpler than in order book-based exchanges. CFMMs encourage passive market participants to lend their assets to pools, making liquidity provision significantly easier.
- On-chain oracles derived from a pricing function make it possible for the AMM to measure asset prices without the need for a central third party. This is because agents interacting with CFMMs are incentivized to report asset prices accurately, providing a reliable on-chain price oracle for other smart contracts.
- Path independence means that the price of any two quantities depends only on those quantities and not on the path between them. This offers two key benefits:
- No need for trade strategizing, since traders receive the same price for a single large trade as they would for a series of smaller trades.
- Minimal state representation, since only the quantity of assets is required for the pricing process.
Drawbacks of Constant Function Market Makers
- Slippage is the tendency of prices to move against a trader’s actions as the trader absorbs liquidity. The larger the trade, the greater the slippage.
- CFMMs incur large slippage costs, making them more suitable for smaller order sizes.
- Exotic financial risk
- Impermanent loss, which describes the losses experienced by liquidity providers due to the price divergence of a pool’s asset prices.
- Short volatility. Since the Uniswap payoff curve is concave, this means that liquidity providers are profitable within a certain price bound and will lose money in large price movements.
- High volatility/volume correlation
Constant Product Market Maker
Automated market makers (AMMs) are decentralized algorithms responsible for creating and maintaining liquid markets for various assets. In the case of Uniswap, this was originally achieved with a constant product function that would impact pricing calculation based on the ratio of asset balances in a liquidity pool.
x * y = k
- x represents the reserve of one asset (e.g., ETH) in the liquidity pool.
- y represents the reserve of the other asset (e.g., an ERC-20 token) in the pool.
- k is a constant value.
Uniswap’s AMM model ensures that the value of k remains constant, regardless of the amount of x or y reserves in the pool. When a trade occurs, users deposit one asset and receive the other in return. Accordingly, Uniswap adjusts the reserves to maintain the constant product (k) after each trade. Since the smart contract does not interact with centralized providers or other exchanges, the contract acts as the price oracle itself. The formula states that k remains constant no matter what the reserves of each asset are. Every trade increases a reserve of either one token or the token and decreases a reserve of either one token or the other.
(x+x)(y-y)=xy where x is the number of tokens being traded for y, which are the tokens that the user gets in exchange.
y=yxx+x
The constant product formula has two main implications:
- The price function causes price slippage: the bigger the number of tokens traded relative to reserves, the higher the price would be.
- The function’s curvature is a hyperbola that never crosses the x or y axis, thus making the reserves infinite.
Together, this mechanism protects pools from being drained and also aligns with the law of supply and demand
- The higher the demand (the bigger the output amount you want to get) relative to the supply (the reserves), the higher the price (the less you get).
Uniswap V1
Uniswap V1 was written in Vyper (a Python-like smart contract language) and incorporated a unique mechanism using factory and registry contracts. Each Uniswap v1 pair stores pooled reserves of two assets, and provides liquidity for those two assets, maintaining the invariant that the product of the reserves cannot decrease. This approach would allow for individual exchange contracts for each ERC20 token, with ETH serving as an intermediary for direct ERC20 to ERC20 trades. This way, users could trade ERC20 tokens directly without converting them to ETH first, simplifying the trading process and reducing transaction costs.
- The factory contract in Uniswap is responsible for creating separate exchange contracts for each ERC20 token. When a new ERC20 token is added to the platform, the factory contract deploys a new exchange contract specific to that token.
- Each exchange contract holds a reserve of ETH and the associated ERC20 token. This reserve allows for trades between the two assets based on their relative supply. The automated market maker algorithm maintains the liquidity and adjusts the token reserves in these contracts to facilitate trading.
- The registry contract serves as a directory that links all the individual exchange contracts. This linkage enables users to perform direct ERC20 to ERC20 trades between any tokens on the platform, using ETH as an intermediary.
Providing Liquidity
In Uniswap V1, adding liquidity to a pool involves depositing an equivalent value of ETH and ERC20 tokens into the associated exchange contract.
The first liquidity provider to join a pool sets the initial exchange rate by depositing an equivalent value of ETH and ERC20 tokens. If this ratio is incorrect, arbitrage traders will step in and bring the prices to equilibrium at the expense of the initial liquidity provider.
All future liquidity providers deposit ETH and ERC20 tokens using the exchange rate at the time of their deposit. If the exchange rate is unfavorable, profitable arbitrage opportunities will arise, correcting the price.
When a user provides liquidity, liquidity tokens (LP tokens) are minted to track the relative proportion of total reserves that each liquidity provider has contributed to the market. The number of liquidity tokens minted is determined by the amount of ETH sent to the function. In other words, the number of LP tokens received is proportional to the user’s share of liquidity in the pool’s reserves.
amountMinted = totalAmount * ethDepositedethPool
And depositing ETH into reserves requires depositing an equivalent value of ERC20 tokens as well.
tokensDeposited = tokenPool * ethDepositedethPool
Liquidity tokens can be burned at any time, enabling liquidity providers to withdraw a proportional share of the market’s liquidity based on their token holdings.
ethWithdrawn = ethPool * amountBurnedtotalAmount
tokensWithdrawn = tokenPool * amountBurnedtotalAmount
Note that ETH and ERC20 tokens are withdrawn at the current exchange rate (reserve ratio), not the ratio of their original investment. This means some value can be lost from market fluctuations and arbitrage. Also, fees taken during trades are added to total liquidity pools without minting new liquidity tokens. Because of this, ethWithdrawn and tokensWithdrawn include a proportional share of all fees collected since the liquidity was first added.
- Transaction fees generated in the liquidity pool are distributed among LP token holders.
- The share of fees each LP-token holder receives is proportional to the number of tokens they hold.
- LP tokens can be exchanged back for the initial liquidity provided plus the accumulated transaction fees.
When a liquidity provider decides to remove their liquidity, they receive both assets (ETH and tokens) according to the current ratio in the pool. This can result in a different proportion of assets compared to what was initially deposited. If the value of the received assets in USD is lower than the value of the assets if they had been held in a wallet, the liquidity provider experiences an impermanent loss.
Trading
As an example of how swaps take place, we can use a fee of 0.25%, and assume a liquidity pool with 10 ETH and 500 OMG tokens, such that k = 5,000.
- An OMG buyer sends 1 ETH to the contract.
- A 0.25% fee is taken out to reward liquidity providers and the remaining 0.9975 ETH are added to the pool.
- Next, the invariant is divided by the new amount of ETH in the liquidity pool to determine the new size of OMG.
- The remaining OMG is sent to the buyer.
- The fee is added back into the liquidity pool to act as the payout for liquidity providers when they remove liquidity from the market.
Note that since the fee is added after price calculation, the invariant increases slightly with every trade, making the system profitable for liquidity providers.
Asset purchases that are large relative to the total size of the liquidity pools will cause price slippage. Assuming efficient markets, arbitrageurs will ensure that the price will not shift too far from that of other exchanges.
Given that ETH is used as a common pair for all ERC20 tokens, it can be used as an intermediary for direct ERC20 to ERC20 token swaps.
Uniswap V2
Uniswap V2 is written in Solidity and builds on the success of Uniswap V1 by introducing new features and improvements:
- Arbitrary ERC20/ERC20 pairs: Uniswap V2 allows users to create liquidity pools and trade between any two ERC20 tokens, instead of being limited to ERC20 and ETH pairs as in Uniswap V1.
- When assets are correlated, this greatly reduces impermanent loss.
- Hardened price oracle: Uniswap V2 provides a more secure and reliable price oracle that records the relative price of the two assets in a pair at the beginning of each block. This enables other contracts on the Ethereum network to estimate the time-weighted average price (TWAP) for the assets over arbitrary time intervals, which can be useful for various decentralized finance (DeFi) applications.
Uniswap V1 was not safe to use as an on-chain price oracle because it was easily manipulated. An attacker could trade on Uniswap, trigger a settlement on a derivative contract, and then trade back, causing the contract to settle based on the inflated price. This issue is especially problematic if it can be done as an atomic transaction or by a miner who controls the ordering of transactions within a block.
Uniswap V2 improves upon this by measuring and recording the price before the first trade of each block (or after the last trade of the previous block). This makes the price more difficult to manipulate, as arbitrageurs can trade back immediately afterward in the same block if the attacker tries to manipulate the price. However, if a miner or attacker uses enough gas to fill an entire block, they could still manipulate the price at the end of a block. This would be less advantageous for them, as they might not be able to arbitrage the trade back unless they mine the next block as well.
Uniswap V2 adds an end-of-block price to a single cumulative price variable in the core contract weighted by the amount of time the price existed. This variable represents a sum of the Uniswap price for every second in the entire history of the contract. The variable can then be used by external contracts to track accurate time-weighted average prices (TWAPs) across any time interval and for both simple and exponential moving averages.
- For a 10-minute TWAP, sample once every 10 minutes. For a 1-week TWAP, sample once every week, and so on
- For a simple TWAP, the cost of manipulation increases (approx. linear) with liquidity on Uniswap, as well as (approx. linear) with the length of time over which you average.
- The cost of an attack can be estimated as well. Moving the price 5% on a 1-hour TWAP is approximately equal to the amount lost to arbitrage and fees for moving the price 5% every block for 1 hour.
Users of the oracle can choose when to start and end this period, which affects the cost of manipulation for an attacker and the up-to-date nature of the price. Uniswap V2 also tracks both the price of asset A in terms of asset B and the price of asset B in terms of asset A, as the mean price of one asset in terms of the other is not equal to the reciprocal of the mean price of the other asset in terms of the first.
- Flash swaps: Uniswap V2 introduces flash swaps, a feature that allows users to receive assets from a liquidity pool without paying for it, as long as they make the payment within the same atomic transaction. Effectively, flash loans are the equivalent of an unlimited and uncollateralized loan that must be repaid in the same transaction. This opens up new opportunities for arbitrage, liquidations, and other financial operations that can be executed within a single transaction.
- Meta transactions for pool shares: Uniswap v2 pairs support meta transactions for pool shares, which allows users to authorize the transfer of their pool shares with a signature instead of an on-chain transaction from their address. This works by having users sign a message that authorizes a specific transfer of their pool shares. The signature can then be submitted on the user’s behalf by anyone who calls the permit function. This third party can pay the gas fees and potentially perform other actions in the same transaction.
At its core, the architecture of Uniswap V2 is centered around the idea of pooling, where liquidity providers stake their assets in a contract. This staked liquidity enables decentralized trading, with traders paying a small fee that gets accumulated in the contract and shared among liquidity providers.
The primary contract in Uniswap V2 is the UniswapV2Pair, which acts as a pooling contract that accepts tokens from users and uses the accumulated reserves to facilitate swaps. Each UniswapV2Pair contract can pool only one pair of tokens and allows swaps exclusively between those two tokens.
The codebase for Uniswap V2 contracts is divided into two repositories: core and periphery.
- The core contains the following contracts:
- UniswapV2ERC20: An extended ERC20 implementation used for LP-tokens, which also implements EIP-2612 for off-chain approval of transfers.
- UniswapV2Factory: A factory contract that creates pair contracts and serves as a registry for them, using create2 to generate pair addresses. This contract avoids having pairs of identical tokens and liquidity split into multiple identical pairs. Create2 is an opcode that was added in EIP-1014 and enables the generation of new contract addresses deterministically.
- UniswapV2Pair: The main contract responsible for the core logic, allowing only unique pairs to avoid liquidity dilution.
- The periphery contains the following contracts:
- UniswapV2Router: The main entry point for Uniswap’s user interface and other applications built on top of Uniswap, with a similar interface to the exchange contract in Uniswap V1. This contract simplifies the process to create pairs, adding and removing liquidity, calculating prices for all possible swap variations, and performing actual swaps.
- UniswapV2Library: A collection of helper functions that implement essential calculations.
In Uniswap V2, the seller sends the asset to the core contract before calling the swap function. Then, the contract calculates how much of the asset it has received, by comparing the last recorded balance to its current balance.
When trading against the constant product formula, price can be defined as the amount of one token that you get in exchange for 1 unit of another token.
Unlike Uniswap V1, which subtracted the trading fee from the amount paid to the contract before enforcing the constant product invariant, the contract implicitly enforces the following formula:
With flash swaps, V2 introduces the possibility that xin and yin might both be non-zero (when a user wants to pay the pair back using the same asset, instead of swapping). To handle those scenarios, the contract is written to enforce the invariant below:
To simplify the calculation on-chain, each side of the inequality is multiplied by 1,000,000:
Uniswap v2 incorporates two bail-out functions, sync() and skim(), to safeguard against potential issues caused by specific token implementations or the limits of the uint112 storage slots for reserves.
- sync(): This function serves as a recovery mechanism in cases where a token asynchronously deflates the balance of a pair. When this happens, trades may receive suboptimal rates, and if no liquidity provider is willing to rectify the situation, the pair remains stuck. The `sync()` function resolves this issue by updating the reserves of the contract to match the current balances, allowing a more graceful recovery from such situations.
- skim(): This function acts as a recovery mechanism for scenarios in which enough tokens are sent to a pair that the two uint112 storage slots for reserves overflow. If this occurs, trades could fail. The `skim()` function enables a user to withdraw the difference between the current balance of the pair and 2^112 – 1 to the caller if that difference is greater than 0. This helps to prevent potential issues related to overflowing storage slots for reserves.
Both of these functions play essential roles in maintaining the stability and security of Uniswap v2, ensuring that the platform can recover from potential problems caused by token implementations or storage limitations.
Providing Liquidity
Similar to V1, no trades are possible without liquidity. For that, liquidity pools will represent smart contracts that store token liquidity amounts and allow to perform swaps using this liquidity. When liquidity is added to a pair, the contract mints LP tokens, and when liquidity is removed, LP tokens are burned.
Initial Pool Deposit
Note that liquidity is calculated differently when initially deposited into the pool (how many LP tokens are issued when there is no liquidity in the pool?). Uniswap V1 indeed used the amount of deposited ethers to determine the initial amount of LP-tokens, and it relied on the liquidity providers to deposit at a ratio that reflects the actual prices at that moment. This approach had its limitations and could potentially lead to inaccurate pricing if the initial liquidity providers did not deposit at the correct ratio. Uniswap V2 introduced support for arbitrary ERC20 token pairs, eliminating the strict dependence on ETH as the base currency for trading pairs. This feature allows for more flexible and diverse trading options within the ecosystem. However, this also means that there might not always be a direct price reference in ETH for certain token pairs.
Liquidity=Amount0*Amount1
The main advantage of the equation above is that such a formula ensures that the initial liquidity ratio doesn’t affect the value of a pool share.
Pools Deposits on Initialized Pools
When there is already some liquidity, the main requirement is to ensure that the liquidity ratio does not affect the value of a pool share./ Hence, the requirement must satisfy that the amount is:
- Proportional to the deposited amount.
- Proportional to the total issued amount of LP-tokens.
Liquidityminted=TotalSupplyLP* AmountdepositedReserve
The formula above is similar to V1, however, V2 introduces two underlying tokens. Either of them could be used, but V2 aims to prevent price manipulation through liquidity provision by choosing the smaller LP-token amount when calculating the minted LP-tokens for a new liquidity provider. This approach discourages unbalanced liquidity provision, as liquidity providers who deposit at an incorrect ratio will receive fewer LP tokens.
When it comes to removing liquidity, the process is the opposite of liquidity provision. Likewise, burning is the opposite of mining. Therefore, removing liquidity means burning LP tokens in exchange for receiving a proportional amount of the underlying tokens.
Amounttoken= Reservetoken*BalanceLPTotalSupplyLP
The formula above shows that the amount of tokens returned is proportional to the number of LP tokens held over the total supply of LP tokens. As a result, the bigger your share of LP-tokens, the bigger share of reserve you get after burning.
Trading
In the context of Uniswap V2, the actual token exchange is handled by the pair contract, which acts as a mediator to ensure correct exchange rates and full payment for each swap. Similar to V1, the constant product formula is used to guarantee the conditions for a successful swap, maintaining a constant product of reserves throughout the exchange process.
In Uniswap v1, Ethereum’s native asset, $ETH, was directly supported due to its presence in every trading pair. This made handling $ETH directly more gas-efficient. However, Uniswap v2 supports arbitrary ERC-20 pairs, which means that directly supporting unwrapped $ETH is no longer practical.
Supporting unwrapped $ETH in Uniswap v2 would double the size of the core codebase and risk fragmenting liquidity between $ETH and $WETH pairs. To address this issue, Uniswap v2 requires native $ETH to be wrapped into $WETH (Wrapped Ether) before it can be traded on the platform.
Wrapped Ether ($WETH) is an ERC-20 token that represents $ETH, with each $WETH token being equal in value to 1 $ETH.
Fees
Uniswap V2 contracts are non-upgradeable. The protocol charges fees on input amounts. By default, a 30 basis-point fee is charged on trades. However, there is a private key that has the ability to update a variable on the factory contract to turn on an on-chain 5-basis-point fee on trades. This fee has been initially turned off but could be turned on in the future, after which liquidity providers would earn 25 basis points on every trade, rather than 30 basis points, with the remaining 5 basis points possibly going to $UNI token holders via staking.
Uniswap V3
Uniswap v3, launched in May 2021, introduced several significant improvements and features over Uniswap v2, which aim to increase capital efficiency, improve flexibility, and provide more control to liquidity providers (LPs).
1. Concentrated Liquidity: In Uniswap v2, liquidity was spread across the entire price curve, from 0 to infinity. Uniswap v3 allows LPs to concentrate their liquidity within custom price ranges. This means LPs can set minimum and maximum prices for their capital to be used between, making capital more efficient.
- When the market price of the trading pair is within the specified range, the LPs earn fees just like in v2.
- When the price is outside this range, the LP isn’t participating in the market and hence doesn’t earn fees.
2. Multiple Fee Tiers: Uniswap v3 introduces multiple fee tiers per pair to compensate LPs for taking on varying degrees of risk. This differs from v2, which had a flat fee of 0.3% for all trades. In v3, LPs can choose between three different fee tiers per pair: 0.05%, 0.3%, and 1%. This allows LPs to better align their risk level with expected returns.
3. Improved Price Oracle: Uniswap v3 features an improved price oracle that provides more accurate and timely price information. The v3 oracle accumulates prices on a per-second basis, providing a TWAP (Time-Weighted Average Price) over any interval, which reduces the possibility of manipulation.
4. Non-Fungible Liquidity: In Uniswap v2, LPs received fungible LP tokens in return for providing liquidity, which could be used in other DeFi protocols. However, in Uniswap v3, LPs receive non-fungible tokens (NFTs) that represent their position, including the price range. This makes positions not directly comparable and hence non-fungible. This can limit the use (composability) of v3 LP tokens in other DeFi protocols.
5. Range Orders: Uniswap v3 introduces a new type of limit order called a “range order.” LPs can deposit a single token in a custom price range above or below the current price. If the market price enters into their specified range, their deposited token is sold for the other at their specified price (similar to a limit order enabled by a single-side liquidity deposit).
By slicing the price range [0,∞] into numerous granular ticks, trading on V3 is highly similar to trading on order book exchanges, with only three differences:
- The price range of each tick is predefined by the system instead of being proposed by users.
- Trades that happen within a tick still follow the pricing function of the AMM, but the equation has to be updated once the price crosses the tick.
- Orders can be executed with any price within the price range, instead of being fulfilled at the same price on order book exchanges.
Concentrated Liquidity
When liquidity is provided on a spectrum from zero to infinity, much of the liquidity provided by LPs could be considered idle or underutilized. This lack of capital efficiency is particularly noticeable in stablecoin pairs like DAI/USDC, where the price range is naturally very tight. The majority of the trading volume for such pairs occurs within a very narrow price band (for instance, between $0.99 and $1.01). However, only a tiny fraction of the total pool liquidity is used for trades within this range, while the majority of capital sits idle waiting for extreme price movements that rarely occur. This leads to lower returns for LPs, as they earn fees only on the portion of their capital that is actively used in trades.
As an example, we can assume two users, Alice and Bob, want to provide liquidity to an $ETH/$DAI pool on Uniswap V3. Each of them has $1M and the current price of $ETH is 1,500 $DAI.
- Alice deploys capital across the entire price range, like in V2:
- 500,000 $DAI
- 333.33 $ETH
- The deposit is worth $1M
- Bob creates a concentrated liquidity position, depositing only within the price range from 1,000 to 2,500
- 91,751 $DAI
- 61.17 $ETH
- The deposit is worth $183,500 and he keeps $816,500 for himself.
While Alice has put down 5.44x as much capital as Bob, they will earn the same amount of fees as long as the $ETH/$DAI price stays within the 1,000 to 2,500 range.
Bob’s position also acts as a stop-loss. Both Alice and Bob will be entirely denominated in $ETH if the price of $ETH falls to $0. However, Bob will have lost just $159,000 vs Alilce’s $1M.
With concentrated liquidity, it is only required to keep necessary liquidity within a specific range in order to support trading like a constant product pool with larger reserves.
When users specify a price range, they are essentially setting a lower and upper price bound:
- The lower bound is the price at which all of the first asset is converted into the second.
- The upper bound is where all the second asset is converted into the first.
More specifically, a position only needs to hold enough of asset X to cover price movement to its upper bound, because upwards price movements correspond to the depletion of fake X reserves.
When the price exits a position’s range, the position’s liquidity is no longer active, and no longer earns fees. At that point, the liquidity is composed entirely of one asset, because the reserves of the other asset have been depleted. If the price enters the range again, the liquidity becomes active again as well.
Liquidity providers can create as many positions as they see fit, each in their own price range. This way, LPs can approximate any desired distribution of liquidity in the price space.
Active Liquidity
Uniswap V3 also introduces the concept of active liquidity: if the price of assets trading in a specific liquidity pool moves outside of the LPs price range, the LPs liquidity is removed from the pool and stops earning fees. When this happens, the LP’s liquidity shifts completely towards one of the assets, such that the position ends up holding only one asset. At this point, the LP can choose to either wait until the market price returns to the specified price range or to update its range to account for current prices.
Even though it is possible that there is no liquidity at a specific price range, this is impractical because this would create a great opportunity for liquidity providers to step in and provide liquidity in that price range to start collecting trading fees.
With concentrated liquidity, a position only needs to maintain enough reserves to support trading within its range and therefore can act like a constant product pool with larger reserves within that range.
Ticks and Ranges
In Uniswap v3, liquidity provision is made more flexible with the introduction of ticks and ranges. Unlike Uniswap v2 where liquidity is uniform across all price ranges, in v3, liquidity providers (LPs) can provide liquidity in a specific price range between any two ticks. This concept is referred to as concentrated liquidity and allows LPs to position their liquidity at specific price ranges where they think trading activity will happen.
A “tick” in Uniswap v3 represents a price point at which the virtual liquidity of the contract can change. The space of possible prices is divided into these discrete ticks and the prices are always expressed as the price of one of the tokens (token0) in terms of the other token (token1).
Conceptually, there is a tick at every price that is an integer power of 1.0001. Conceptually, compared to the previous/next price, the price change should always be 1 basis point. Identifying ticks by an integer index , the price at each tick is given by:
p(i)=1.0001i
This ensures that each tick is a .01% (1 basis point) price movement away from each of its neighboring ticks.
However, pools in Uniswap v3 actually track ticks at every square root price that is an integer power of √1.0001. This is represented as:
p(i)=1.0001i=1.0001i/2
This allows for more granularity in the price ranges that LPs can choose to provide liquidity to. When an LP adds liquidity to a range, if one or both of the ticks is not already used as a bound in an existing position, that tick is initialized.
Not every tick can be initialized. The pool is instantiated with a parameter, tickSpacing ( ), and only ticks with indexes that are divisible by tickSpacing can be initialized. This balances the need for precision with the potential gas cost for transactions.
When the price of the trading pair crosses an initialized tick, the virtual liquidity changes — it’s either “kicked in” or “kicked out”. This ensures that the right amount of liquidity is present when ticks are crossed and that each position earns its proportional share of the fees that were accrued while it was within range. The pool contract uses storage variables to track state at a global (per-pool) level, at a per-tick level, and at a per-position level.
The global state of the contract includes seven storage variables relevant to swaps and liquidity provision:
- liquidity ( ): A uint128 variable that represents the total liquidity provided to the pool.
- sqrtPriceX96 (√ ): A uint160 variable that represents the square root of the current price, shifted left by 96 bits (for precision purposes).
- tick (ic): An int24 variable that represents the current tick index.
- feeGrowthGlobal0X128 ( ,0) and feeGrowthGlobal1X128 ( ,1): uint256 variables that track the cumulative fee growth per unit of liquidity, for token0 and token1 respectively. This is used to calculate the fees accrued by liquidity providers.
- protocolFees.token0 ( ,0) and protocolFees.token1 ( ,1): uint128 variables that track the protocol fees collected, for token0 and token1 respectively. These fees are potentially distributed to $UNI token holders if the protocol fee switch is turned on by governance.
In Uniswap V3, each pool has a global state that tracks the liquidity (L) and square root price (√ ).
- Liquidity (L): Liquidity is the amount of capital that is provided to a pool. It represents the overall capacity of the pool to handle swaps without incurring major price slippage. In terms of virtual reserves, liquidity is calculated as the square root of the product of x and y (the reserves of token0 and token1 respectively). Mathematically, this is represented as:
Using these two variables, virtual reserves can be calculated as:
– = / √
– = * √
These variables are chosen as they only change one at a time. When swapping within a tick, the price changes, and when crossing a tick or when minting/burning liquidity, the liquidity changes.
- In a “price/liquidity coordinate system” system, a Uniswap v3 concentrated liquidity position is represented as a single bar, because liquidity is concentrated between two specific prices.
- In contrast, the “amount of tokens” coordinate system represents the number of each type of token in the pool, again with the price on the x-axis but this time the number of tokens on the y-axis. In this system, the position is represented as a segment of a hyperbola between two points (A and B), where A and B represent the lower and upper prices at which the liquidity provider is willing to trade.
The shape of this hyperbola is invariant to liquidity, meaning it does not change as liquidity changes. This is because the shape of the curve is determined by the mathematical properties of the constant product formula (x*y=k) used in Uniswap, rather than the amount of liquidity in the pool.
Consequently, any position in the same price range will have the same shape as the hyperbola, regardless of the amount of liquidity it has. Essentially, this characteristic allows a liquidity provider to precisely specify their risk and reward by setting the range of prices (A and B) at which they are willing to provide liquidity. This is the fundamental advantage of Uniswap v3’s concentrated liquidity feature: it allows liquidity providers to be much more capital efficient by focusing their liquidity at the price ranges where it is most likely to be needed.
In the concentrated liquidity approach, a liquidity position has only a single token x or y if the price range of the position does not cover the current price. This means that, when translated to real reserves, the goal is to move the curve segment between points A(ax, ay) and B(bx, by) to points A’ and B’.
And the goal is to translate the coordinates to the “token balances” coordinates system.
- The price P of y in terms of x corresponds to the slope of the line y=Px on which the point sits
- The liquidity L of the position determines the distance from the coordinate center on that pice line.
As an example, assuming a point (P, L) in the price/liquidity coordinate system, the coordinates in the “token balances” system can be found by looking at the intersection between the price line and the liquidity curve, which is expressed by the system of equations below:
- y=P*x
- L2=x*y
Fees: Each pool has an associated fee ( ) which is the fee paid by swappers. There is also a protocol fee ( ) which is the fraction of the fees paid by swappers that currently go to the protocol rather than to liquidity providers. Fees are paid by users who swap tokens, where a small amount is subtracted from the input token and accumulated on the pool’s balance.
Fee Growth: The global state tracks feeGrowthGlobal0 ( ,0) and feeGrowthGlobal1 ( ,1). These represent the total amount of fees that have been earned per unit of virtual liquidity ( ), over the entire history of the contract.
Protocol Fees: The global state also tracks the total accumulated uncollected protocol fee in each token, protocolFees0 ( ,0) and protocolFees1 ( ,1). These can be collected by UNI governance.
- Each pool has state variables that track the total amount of fees accumulated per unit of liquidity (fee amount divided by the pool’s liquidity).
- Ticks keep records of fees accumulated outside of them. When creating a new position and activating a tick (adding liquidity to a tick that was empty before), the tick records how many fees were accumulated outside of it.
- When a tick is activated, the fees accumulated outside of the tick are updated as the difference between global fees accumulated outside of the tick since the last time it was crossed.
- Having ticks that know how much fees were accumulated outside of them makes it possible to calculate how much fees were accumulated inside of a position (where a position is a range between two ticks)
- Knowing how much fees were accumulated inside a position makes it possible to calculate the shares of fees that liquidity providers are eligible for. For instance, a position that has not been involved in swapping will have zero fees accumulated inside of it and, therefore, its liquidity providers will have no profits from it.
Swapping Within a Single Tick
In Uniswap V3, when a swap occurs that does not move the price past a tick (i.e., the price movement is small), the contracts behave like a constant product model ( · = ), which is characteristic of Uniswap V2.
The formulas below are only applicable for swaps that do not push √ past the price of the next initialized tick. If the swap would cause √ to move past that next initialized tick, the contract must only go up to that tick, then cross the tick, before continuing with the rest of the swap.
Assuming is the fee, typically 0.003, and yin is the amount of token1 sent into the pool.
When a swap occurs, the global fee growth (feeGrowthGlobal1) and the protocol fees (protocolFees1) are increased:
Here, Δ ,1 and Δ ,1 denote the changes in the global fee growth and the protocol fees respectively. is the protocol fee fraction.
Δ , which is the increase in (after the fee is taken out), is calculated as:
Δ = · (1 − )
In Uniswap V3, the contract tracks liquidity ( ) and the square root of price (√ ) instead of and . Therefore, to compute the amount of token0 sent out, the following formula can be used:
xend = · / ( + Δ )
However, since the contracts track and √ , the formulas that describe the relationship between Δ√ and Δ , and between Δ1/√ and Δ can be used instead:
Δ√ = Δ /
Δ = Δ√ *
Δ1/√ = Δ /
Δ = Δ1/√ *
Thus, when a swap occurs, the contract first calculates the new √ , and then it calculates the amount of token0 or token1 to send out.
Tick-Indexed State
With concentrated liquidity, the Uniswap V3 contract needs to store information about each tick in order to track the amount of net liquidity that must be added or removed when the tick is crossed, as well as to track the fees earned above and below the tick.
The contract stores a mapping from tick indexes (int24) to the following seven values:
Type | Variable name | Notation |
int128 | liquidityNet | ΔL |
uint128 | liquidityGross | Lg |
uint256 | feeGrowthOutside0x128 | f0,0 |
uint256 | feeGrowthOutside1x128 | f0,1 |
uint256 | secondsOutside | so |
uint256 | tickCumulativeOutside | io |
uint256 | secondsPerLiquidityOutsidex128 | sl |
- liquidityNet (Δ ): This is the net change in liquidity at a particular tick index due to liquidity events (minting/burning).
- liquidityGross ( ): This is the total amount of liquidity that was added at this tick.
- feeGrowthOutside0X128 ( ,0): This tracks the total fees collected in token0 for all liquidity that is outside of the current tick range.
- feeGrowthOutside1X128 ( ,1): This tracks the total fees collected in token1 for all liquidity that is outside of the current tick range.
- secondsOutside ( ): This is the cumulative seconds that the pool price has been outside this tick.
- tickCumulativeOutside ( ): This is the cumulative tick value when the pool’s price was outside this tick.
- secondsPerLiquidityOutsideX128 ( ): This is a measure of the time-weighted liquidity outside this tick, which is used for calculating fees.
Each tick tracks Δ , which is the total amount of liquidity that should be added or removed when the tick is crossed. The tick only needs to track one signed integer: the amount of liquidity added (or, if negative, removed) when the tick is crossed from left to right. This value does not need to be updated when the tick is crossed but only when a position with a bound at that tick is updated.
A tick can be uninitialized when there is no longer any liquidity referencing that tick. To track this, liquidityGross is used. This value allows the protocol to know if a tick is referenced by at least one underlying position or not, which tells us whether to update the tick bitmap.
feeGrowthOutside{0,1} are used to track how many fees were accumulated within a given range. This value needs to be updated each time the tick is crossed. The fees earned per unit of liquidity in token 0 above (fa)and below (fb) a tick i can be calculated with a formula that depends on whether the price is currently within or outside that range (that is, whether the current tick index ic is greater than or equal to i)
Position-Indexed State
Two main arguments are required to call the setPosition function —lowerTick and upperTick— when combined with the msg.sender. This allows Uniswap to map a user’s position with a lower bound and an upper bound.
Liquidity, l, refers to the amount of virtual liquidity that the position represented the last time this position was touched. More specifically, liquidity is represented as √ · √ , where and are the amounts of virtual token0 and virtual token1 that the position contributes to the pool when the price is within the range set by the position.
This representation of liquidity differs from Uniswap V2, where liquidity was represented as shares in the pool, and the value of each share increased over time as fees were accumulated. In Uniswap V3, the units for liquidity do not change as fees are accumulated. Instead, they are always measured as √ · √ , where and are quantities of token0 and token1, respectively.
The setPosition function then proceeds to update the position’s liquidity by adding liquidityDelta. This value is also added to the liquidityNet value of the lower tick and subtracted from the liquidityNet value of the upper tick. This is done to reflect the addition of new liquidity when the price crosses the lower tick going up, and the removal of liquidity when the price crosses the upper tick going up.
If the current price of the pool is within the range of this position, the contract also adds liquidityDelta to the contract’s global liquidity value.
The function then proceeds to transfer tokens from (or to, if liquidityDelta is negative) the user, corresponding to the amount of liquidity that is burned (if negative) or minted (if positive).
The amount of token0 (Δ ) or token1 (Δ ) that needs to be deposited by the user can be thought of as the amount that would be sold from the position if the price were to move from the current price ( ) to the upper tick (for token0) or lower tick (for token1).
Multiple Pools Per Pair
In Uniswap V1 and V2, every pair of tokens corresponds to a single liquidity pool, which applies a uniform fee of 0.3% to all swaps. V3, however, introduces multiple pools for each pair of tokens, each with a different swap fee. The factory contract initially allows pools to be
created at three fee tiers: 0.05%, 0.30%, and 1%. Additional fee tiers
can be enabled by $UNI governance.
Autorouter
Uniswap implements an autorouter algorithm that finds the shortest path between two tokens that don’t have a pool. Furthermore, it also splits one payment into multiple smaller payments to find the best average exchange rate.
Flexible Fees
In order to incentivize liquidity providers, traders need to pay a small fee for executing swaps. UniswapV3 makes it possible to create fee tiers per pair – 0.05%, 0.3%, and 1%. This makes it possible to better align the risk (price volatility of an asset pair) with the potential rewards (from trading fees).
For example, pairs involving stablecoins (like $USDC/$DAI), or correlated assets (like $stETH/$ETH) that have low volatility and are less risky are likely to attract LPs to the 0.05% fee tier. On the other hand, more volatile pairs (like $ETH/$DAI) might attract LPs to the 0.30% fee tier. Similarly, exotic or highly volatile assets might find the 1.00% fee tier more appropriate.
In addition to these fee tiers, Uniswap v3 also introduces a flexible protocol fee structure. While Uniswap v2 had a protocol fee switch that could enable a flat 5 basis point fee (which is 16.66% of LP fees), v3 allows for protocol fees to be turned on by governance on a per-pool basis and set anywhere between 10% and 25% of LP fees. This provides the Uniswap governance community more control and flexibility in determining the protocol’s revenue structure.
Swap fees are collected only when a price range is used for trading. Hence, the protocol is responsible for tracking the moments when price range boundaries get crossed.
- When the price is increasing and a tick is crossed from left to right.
- When the price is decreasing and a tick is crossed from right to left.
Similarly, a price range becomes inactive when:
- Price is increasing and a tick is crossed from right to left.
- Price is decreasing and a tick is crossed from left to right.
Advanced Oracles
Uniswap V2 introduced TWAP oracles, which record the cumulative sum of a price pair on a per-second basis and could be used to compute an accurate TWAP over any time period. Uniswap V3 iterates upon this model and improves by making it possible for users to calculate any recent TWAP within the past 9 days with a single on-chain call. Additionally, the gas costs associated with this feature were reduced by ~50%.
- Accumulator Checkpoints in Core: In Uniswap v2, external contracts wanting to compute on-chain TWAPs needed to store checkpoints of the accumulator value. Uniswap v3 has brought these accumulator checkpoints into the core of the protocol, allowing external contracts to calculate on-chain TWAPs over recent periods without storing these checkpoints. The pool exposes the array of past observations to users and also provides a convenience function for finding the (interpolated) accumulator value at any historical timestamp within the checkpointed period. This enables users to calculate any recent TWAP within the past ~9 days in a single on-chain call, vastly improving the flexibility and precision of price oracles on Uniswap.
- In Uniswap v2, the price accumulator only stored the most recent value — the value as of the last block in which a swap occurred. Computing average prices in v2 required the external caller to provide the previous value of the price accumulator. This meant that each user had to create their own method for checkpointing previous accumulator values or coordinate a shared method to reduce costs. This system had limitations, as not every block that touched the pool could be reflected in the accumulator.
- Uniswap v3 improved upon the previous model by implementing accumulator checkpoints. Now, the pool stores a list of previous values for the price accumulator (and a new liquidity accumulator). These values are automatically checkpointed every time the pool is touched for the first time in a block. This is done by cycling through an array where the oldest checkpoint is eventually overwritten by a new one, creating a system akin to a circular buffer. Initially, this array only has room for a single checkpoint, but it can be extended to as many as 65,536 checkpoints. Anyone can initialize additional storage slots to lengthen the array, imposing the one-time gas cost of initializing additional storage slots for this array on whoever wants this pair to checkpoint more slots.
- Geometric Mean TWAP: Uniswap v2 accumulated the sum of prices, which allowed users to compute the arithmetic mean TWAP. Uniswap v3, however, tracks the sum of log prices, allowing users to compute the geometric mean TWAP. This can provide a more accurate representation of price over time, particularly for volatile assets.
- In Uniswap v2, two price accumulators were maintained — one for the price of token0 in terms of token1, and one for the price of token1 in terms of token0. This was because the time-weighted arithmetic mean price of token0 is not equivalent to the reciprocal of the time-weighted arithmetic mean price of token1.
- Uniswap v3 only needs to maintain one price accumulator due to the properties of the geometric mean. The geometric mean of a set of ratios is the reciprocal of the geometric mean of their reciprocals. This allows Uniswap v3 to maintain a single price accumulator.
- Liquidity Accumulator: Uniswap v3 introduces a liquidity accumulator that is tracked alongside the price accumulator. This liquidity accumulator accumulates 1/L for each second, where L represents the pool’s liquidity. This feature is useful for external contracts implementing liquidity mining on top of Uniswap v3. The liquidity accumulator can also be used by other contracts to determine which pool for a pair will provide the most reliable TWAP.
Non-Fungible Liquidity
Since each LP will have its own price curve, the liquidity positions are no longer fungible and cannot be represented with standard ERC20 LP tokens. Instead, ERC-721 NFTs are used.
- In previous versions, fees earned by the protocol were continuously deposited in the pool as liquidity. This meant that liquidity in the pool would grow over time, even without explicit deposits, and that fee earnings compounded. In V3, due to the nature of NFTs, this is no longer possible, and fee earnings are stored separately and held as the tokens in which the fees are paid.
- In Uniswap V1 and V2, the pool contract is an ERC-20 contract whose tokens represent the liquidity held in the pool. While this is convenient, this discourages the creation of improved ERC-20 token wrappers.
In V3, fees are collected and held by the pool as individual tokens, rather than automatically reinvested as liquidity in the pool. As a result, the pool contract in V3 does not implement the ERC-20 standard.
Range Orders
Range orders are a feature enabled by concentrated liquidity. With range orders, liquidity providers can provide liquidity at custom price ranges above or below the current market price. When the market price enters that range, their liquidity will become active such that one asset is sold for another along a smooth curve, all while still earning fees along the process.
For example, assuming that $DAI/$USDC is trading below 1, a liquidity provider can choose to deposit $DAI liquidity in a narrow price range between 1.001 and 1.002. Once $DAI trades above 1.002 $DAI/$USDC, the whole liquidity is converted into $USDC and the LP has to withdraw its liquidity to avoid automatically converting back into $DAI once $DAI/$USDC goes back to trading below 1.002.
Slippage Protection
Slippage and sandwich attacks are significant concerns when trading on Dexes like Uniswap.
- Slippage can be particularly problematic on Dexes due to factors like network congestion and variable gas costs. Slippage refers to the difference between the price that you see on the screen when initiating a transaction and the actual price the swap is executed at. This occurs because of the short delay between when a transaction is initiated and when it’s mined, which can result in a discrepancy between the expected and actual execution price.
- A solution for this issue is to set a maximum acceptable slippage before confirming the transaction. If the slippage exceeds this maximum, the transaction will fail.
- Sandwich attacks are a more specific issue to decentralized exchanges. In this type of front-running attack, a malicious actor observes a pending transaction on the network (specifically on the mempool) and places a transaction with a higher gas price to get it confirmed before the original. The attacker then places another transaction to execute after the original transaction. As a result, the first transaction modifies the pool state to make the original transaction unprofitable, and the second transaction reverts the pool to its original state. The attacker thus profits from the manipulated prices.
- To mitigate sandwich attacks, some protocols implement mechanisms like transaction ordering protection and private transaction submissions. However, completely eliminating the possibility of sandwich attacks is a complex challenge that remains to be fully addressed.
To protect against these issues, Uniswap V3 sets slippage tolerance to 0.1% by default. This means that a swap is executed only if the price at the moment of execution is not smaller than 99.9% of the price the user saw in the browser.
Slippage protection is also required when adding liquidity. The reason for that is that price cannot be changed when adding liquidity – liquidity must be proportional to the current price.
Uniswap V4
Uniswap v1 and v2 were the first two iterations of the Uniswap Protocol, facilitating ERC-20 <> ETH and ERC-20 <> ERC-20 transactions, respectively, both using a constant product market maker (CPMM) model. Uniswap v3 introduced concentrated liquidity, providing more capital-efficient liquidity through the use of positions that provide liquidity within a limited price range, and introduced multiple fee tiers.
While concentrated liquidity and fee tiers increased flexibility for liquidity providers and allowed for new strategies to be implemented, Uniswap v3 was not flexible enough to support new functionalities that were invented, as AMMs and markets evolved. For example, v3 enshrined oracles allowed builders to integrate real-time, on-chain pricing data, but this came at the expense of some increased costs for swappers. Something similar occurs with concentrated liquidity, where most passive LPs lose money due to the time and gas costs that come with actively managing positions.
The vision for Uniswap v4 is to increase the expressiveness of the underlying primitives. Announced as public infrastructure for the Ethereum ecosystem, the goal of Uniswap V4 is to empower developers with the appropriate tools to build unprecedented primitives. Instead of making the tradeoff decisions itself, the protocol will allow anyone to choose what they want to build and how they want to build it.
Hooks
Hooks are the most notable feature of Uniswap’s new version. These are contracts that run at various points of a pool action’s lifecycle. This way, it will be up to external builders to add totally new functionality at their own discretion.
Hooks are customizable functions that can be added to a pool in order to modify its behavior. With hooks, developers can customize and augment the capabilities of the concentrated liquidity model. This makes it possible to create new pools with specified hooks that can execute before or after particular pool actions. The whitepaper and source code shows that there are currently 8 different steps.
To fully understand the potential of hooks, it is worth noting that each Uniswap liquidity pool has a lifecycle: a pool is created with a fee tier, liquidity is added, removed, or readjusted, and users swap tokens. In previous deployments, these lifecycle events are tightly coupled and must be executed in a very strict sequence.
Uniswap v4 improves upon the old implementations by allowing developers to design custom “plugins” that will perform a designated action at key points throughout the pool’s lifecycle – during pool creation, before or after a swap, before or after an LP position is changed…
Hooks make it possible to dynamically adjust fees, create new order types, such as TWAP (Time-Weighted Average Price) or *TWAMM orders, facilitate on-chain limit orders, lend idle liquidity (out-of-range) to money markets, autocompound LP fees, or distribute internalized MEV profits back to LPs.
*TWAMM stands for Time-Weighted Average Market Maker. Instead of performing a swap across many pools, the AMM takes a dollar-cost-average approach to swap funds over a period of time.
TWAMM Hook
TWAMMs are a type of swap that reduces the price impact of larger orders by breaking them into small pieces over time.
TWAMM gets swappers better prices by splitting a large single swap order into smaller ones that steadily execute over time. These smaller swaps are less likely to move the market price.
In Uniswap v4, each pool can insert hooks that run at various points of a pool action’s lifecycle. These hooks are smart contracts distinct from the core v4 liquidity contract. Orders are deposited into the TWAMM hook, and the user sets the duration they want their order to execute over. These two parameters instruct the TWAMM hook to swap at the price of each block until the expiration.
TWAMM orders are always the first pool action in a block, meaning they happen before any swaps or LP positions are adjusted. The first time someone swaps or LPs in a block, the pool will first check whether the TWAMM orders have been fulfilled. If there are any open TWAMM orders, the TWAMM hook will settle those orders before continuing on to complete any swaps or LP transactions before repeating the process with the next block. Executing TWAMM orders as the first pool action in the block protects users from frontrunning MEV.
TWAMMs can be used for the following
- Recurring investments
The TWAMM hook is great for longer-term investors who want “set it and forget it” recurring investments. Also known as dollar-cost average (DCA) is a popular trading strategy for passive buyers to invest the same amount at regular intervals. The steady cadence of investments offsets daily market volatility by averaging the purchases over time. - A DAO converting its treasury
The TWAMM hook can let DAOs market sell large portions of their treasuries. If Alice’s DAO can split their order over time, they could sell smaller quantities of tokens until the date they set, letting the market smoothly adjust to thousands of swaps instead of doing it in one go. Using the TWAMM hooks, the DAO’s $10M order can execute at every block for the next 30 days.
Singleton and Flash Accounting
Along with the improvements in terms of customization, the new protocol architecture significantly reduces transaction costs. Uniswap v4 employs a singleton model where all pools are managed by a single contract, significantly reducing the cost of pool creation by ~99%. In other words, all pools live within a single smart contract that will enable more efficient routing across many pools. This design fully aligns with the EVM’s construction of stateful contracts, leading to a better developer experience.
Flash accounting further optimizes gas usage. Since pools are managed by the singleton contract, the protocol only needs to update an internal balance instead of executing immediate transfers from one contract to another at the end of each operation. This is specially relevant for multi-hop asset swaps implemented by the Uniswap router, where an intermediary swap is executed in order to swap the input asset for the requested output asset.
The design for flash accounting uses “transient storage” which will be enabled by EIP-1153 in the Ethereum Cancun hard fork. Pool creators will no longer be restricted to selecting from a predefined range of fee tiers. Instead, they can choose whatever fee ratio they see most competitive and even customize them with a dynamic fee hook that reacts to volatility or other market indicators.
V4 also introduces support for native $ETH in trading pairs, further reducing gas costs even more, since native $ETH transfers are cheaper than ERC-20 transfers. This was not the case in v2 and v3, where $ETH had to be wrapped into $WETH.
ERC 1155 Accounting
Uniswap v4 supports the minting and burning of ERC-1155 tokens for token accounting within the singleton. By allowing users to keep tokens in the singleton contract, they can avoid ERC-20 transfers to and from the contract, thereby making the process of swapping significantly more gas efficient.
Fees
The protocol fee mechanism is modeled after v3. V4 comes with two separate governance mechanisms: swap fees and withdrawal fees. Governance will be able to vote to adjust the fees of any particular pool, up to a capped percentage of the swap amount.
With v4, if hooks initially choose to turn on withdrawal fees for a pool, governance also has the ability to take up to a capped percentage of that withdrawal fee. Unlike in Uniswap v3, governance does not control the permissible fee tiers or tick spacings.
The full list of fees is:
- protocolSwapFeeToken0
- protocolSwapFeeToken1
- protocolWithdrawFeeToken0
- protocolWithdrawFeeToken1
- hookSwapFeeToken0
- hookSwapFeeToken1
- hookWithdrawFeeToken0
- hookWithdrawFeeToken1
UniswapX
Since its initial release in 2018, the Uniswap Protocol has witnessed remarkable growth in on-chain trading. It has expanded its support to millions of users, catered to numerous use cases, and facilitated an impressive trading volume of $1.5 trillion on Uniswap alone.
UniswapX was introduced on July 17, 2023 as an opt-in beta, available on Ethereum Mainnet and expanding to other chains and the Uniswap Wallet in the future.
Its main function is as a new permissionless, open source (GPL), Dutch auction-based protocol for trading across AMMs and other liquidity sources, helping to grow on-chain trading and improve self-custody swapping.
UniswapX is expected to improve the swapping process in the following ways:
- Better prices by aggregating liquidity sources
- Gas-free swapping
- Protection against MEV (Maximal Extractable Value)
- No cost for failed transactions
- Gas-free cross-chain swaps.
Uniswap X represents a significant evolution in the DEX and DEX aggregator design space, offering a unique solution that combines the efficiency of Dutch auctions with the power of on-chain and off-chain liquidity aggregation.
Despite many claims of taking huge inspiration from 1inch Fusion or Cowswap, Uniswap’s approach improves the handling of MEV at the protocol level and makes it possible to offer gas-free and cross-chain trading for protocol users.
By creating a competitive marketplace for trade execution, Uniswap X is not only improving the trading experience for swappers but also democratizing the process of liquidity provision.
Finally, there are no primary or second-order effects as a result of UniswapX that will impact the $UNI token.
Next-Level Aggregation
As on-chain trading continues to evolve, on-chain routing has become a progressively significant and complex challenge. The growth of liquidity pools, the introduction of new fee tiers, the emergence of Layer 2 solutions, and the proliferation of on-chain protocols have resulted in liquidity fragmentation. Anticipated future developments, such as the creation of thousands of customized pool designs on Uniswap v4, will further complicate the routing process. Sustaining competitive pricing throughout such an environment requires manual integration, ongoing maintenance, and substantial effort.
To tackle these complexities, UniswapX proposes a solution that delegates routing complexity to an open network of third-party fillers who compete to execute swaps using on-chain liquidity from AMM pools or their private inventories.
UniswapX offers swappers the convenience of utilizing the Uniswap interface without concerns about obtaining the best price. Additionally, all transactions are transparently recorded and settled on-chain. The Uniswap Smart Order Router acts as a backstop for all orders, compelling fillers to compete with Uniswap versions 1, 2, 3, and, in the future, version 4.
Gas-Free Swapping
With UniswapX, swappers initiate the process by signing a unique off-chain order. Subsequently, fillers take the responsibility of submitting the order on-chain, and they bear the gas fees on behalf of the swappers. This eliminates the need for swappers to possess the native network token of a chain (e.g., ETH, MATIC) or incur any costs for failed transactions. Fillers incorporate the gas fee into the swap price and have the flexibility to optimize transaction costs by batching multiple orders to achieve the best possible price.
It’s important to note that there are specific circumstances where users still need to pay for gas. For instance, gas is required for the initial token approval of Permit2. Additionally, when selling, native network tokens need to be wrapped, which incurs gas costs.
MEV Protection
One of the significant challenges in on-chain swapping is the issue of Miner Extractable Value (MEV), which often leads to unfavorable prices for swappers.
UniswapX addresses this concern by redirecting the MEV that would typically be captured by arbitrage transactions back to swappers, resulting in improved prices. Additionally, UniswapX mitigates the risk of more explicitly extractive forms of MEV. Orders executed using fillers’ inventory are protected from sandwich attacks, a common MEV strategy. Moreover, fillers are incentivized to utilize private transaction relays when routing orders to on-chain liquidity venues, further minimizing the potential for exploitative MEV practices.
Cross-Chain
In the near future, there are plans to introduce a cross-chain version of UniswapX that integrates swapping and bridging functionalities into a unified and streamlined process. This upcoming feature will enable swappers to swiftly exchange assets between different chains within seconds.
A notable advantage of cross-chain UniswapX is that swappers will have the flexibility to select the specific assets they wish to receive on the destination chain, instead of being limited to a bridge-specific token.
Why the Project was Created
There are multiple approaches to how an exchange can be designed. All centralized exchanges rely on order books that offer a similar experience to how trading works in traditional finance with stocks and commodities. An order book is just a journal that stores all the sell and buy orders that traders want to make. Each order in this book contains a price the order must be executed at and the amount that must be bought or sold.
For trading to happen, there must be liquidity. This liquidity is accumulated at different price ranges in the orderbook. When there’s no liquidity, but markets are still interested in trades, market makers come into play. A market maker is a firm or an individual who provides liquidity to markets, that is someone who has a lot of money and who buys different assets to sell them on exchanges. For this job market makers are paid by exchanges. Market makers make money by providing liquidity to exchanges.
In traditional finance, order books dominate the scene for asset exchanges. These mechanisms rely on a list of buy and sell orders to match trades, but this approach has limitations when applied in a smart contract or blockchain environment. Some of the challenges include:
- High Costs: The order book mechanism requires a large state to represent all the outstanding orders, which can be expensive in a smart contract environment where users have to pay for space and computing power.
- Complex Matching Logic: Traditional order books support a variety of order types like iceberg orders, limit orders, and stop-limit orders. Implementing these in a smart contract environment can be quite complex.
To navigate these challenges, some decentralized exchanges have used blockchain for settlement while executing trades off-chain. However, this approach also has drawbacks:
- Front-running: The complex interaction between off-chain and on-chain mechanisms, along with transaction ordering ambiguity in blockchain systems, can lead to front-running, where an entity can exploit the knowledge of pending transactions for their gain.
- Latency Arbitrage: When the order book state is maintained by multiple participants (for instance, ‘relayers’ in the case of 0x), it often leads to stale orders and latency arbitrage opportunities, which can be exploited to profit from delayed price information.
- Complex Threat Model: Decentralized exchanges interacting with off-chain systems have a more complex threat model than smart contracts that operate solely on-chain. This complexity can necessitate additional security precautions for users and can complicate the process of releasing funds.
Automated Market Makers (AMMs) like Uniswap provide a solution to these challenges. By replacing the order book with a liquidity pool and a pricing function, they offer a simplified and more efficient trading model suitable for the blockchain environment
At a very high level, an AMM replaces the buy and sell orders in an order book market with a liquidity pool of two assets, both valued relative to each other. As one asset is traded for the other, the relative prices of the two assets shift and a new market rate for both is determined. This brings advantages such as the creation of permissionless and decentralized markets, and having constant liquidity, although this comes at the expense of impermanent loss, slippage, and smart contract risk among others.
The term “automated market maker” initially referred to algorithms used in prediction markets, which allow users to profit from accurate predictions of future events. These algorithms were designed to create liquid markets for event outcomes by adjusting the odds and payouts automatically.
Uniswap and other on-chain exchanges have evolved from these original algorithms and adapted them for use in decentralized finance (DeFi). The primary goal of AMMs in DeFi is to maintain liquidity and facilitate token trading without relying on traditional order books.
The original proposal on Reddit by Vitalik Buterin outlined an alternative paradigm for decentralized exchanges, borrowing ideas from Nick Johnson’s proposal and prediction markets like Gnosis and Augur. The primary goal of this new mechanism would be to address the high spreads and gas fees associated with market-making in existing decentralized exchanges at the time. This would be achieved with a mechanism that could maintain the following components:
- Internal state that represents the current market price of a token.
- Parameters that set a transaction fee for each trade as well the liquidity depth for each market.
- Order execution such that when users buy tokens, they raise the price to (PRICE + ORDER_AMOUNT / DEPTH) and pay the corresponding amount (ORDER_AMOUNT * (PRICE + ORDER_AMOUNT / DEPTH / 2) * (1 + FEE). This simulates buying an infinitesimal number of tokens at every price point between the old and new prices.
- Initial deposit to set up the market.
At the time, Uniswap was the most efficient decentralized exchange, mostly due to its simplistic design. For ETH to ERC20 trades it used almost 10x less gas than Bancor and could perform ERC20 to ERC20 trades more efficiently than 0x, also offering significant gas reductions when compared to on-chain order book exchanges, such as EtherDelta and IDEX.
In November 2018, Uniswap V1 was deployed as a proof of concept for what an on-chain AMM would work like. Two years later, in May 2020, V2 was released introducing new features and optimizations. This set the stage for the exponential growth in AMM adoption. Less than one year later, more than $100bn had been traded in Uniswap, making it the largest decentralized exchange in the industry.
Roadmap
Uniswap does not have an official roadmap, users can either track their social media channels for the latest updates or join the governance forums to keep track of the relevant proposals.
Some of the relevant proposals that have gained strong traction include:
- Making Protocol Fees Operation
- Propose implementing a protocol fee equal to ⅕ of the pool fee across all* Uniswap v3 pools and turning on the fee switch for Uniswap v2.
- *All pools with regular volumes that would generate an annualized income over $10,000 for the protocol.
- Deploy Uniswap v3 on Moonbeam (2023)
- To reinstate the deployment of Uniswap v3 on Polkadot’s EVM-compatible para chain, Moonbeam.
- Deploy Uniswap v3 on Avalanche
- Importance of Uniswap v3 expansion to popular EVM chains.
- Temperature Check: Deploy Uniswap v3 on Scroll
- To authorize the deployment of Uniswap V3 on Scroll testnet.
Sector Outlook
Uniswap V3 was launched with a business license that expired in Q1 2023. This allowed Uniswap to take advantage of being the only protocol able to offer concentrated liquidity for some time. As time went by, since external protocols could not fork the codebase, they were forced to come up with their own solutions for concentrated liquidity, such as Trader Joe’s liquidity book. Now that the license has expired, anyone can fork and implement their own copy of the AMM engine, however, Uniswap has already managed to achieve network effects and get a first-mover advantage on its unique offering.
Prior to the development of V3, and while V3 was under a business license, the majority of CFMM-based (constant-function market maker) Dexes implemented the constant product market-making formula pioneered by Uniswap V2. This model is capital inefficient since only a portion of the total pool assets is available at a given time. There have also been prior attempts at solving the capital inefficiencies issue, such as Curve and the Yieldspace AMM, but they involve building pools that use different functions to describe the relationship between reserves. This requires all liquidity providers in a given pool to adhere to a single formula and could result in liquidity fragmentation if liquidity providers want to provide liquidity within different price ranges.
One of the things that have helped Uniswap stand out against other competitors was its first-mover advantage in capturing the opportunity of allowing anyone to create a permissionless market for any token. These tokens are often not accessible on centralized exchanges and can be traded without KYC. Many token pairs are created on Uniswap first and, since the only way to trade them is through the AMM, Uniswap often experiences high volumes of its unique token pair offerings, whether they are meme coins or new tokens that just entered the market.
Platform | Fees | Chains | Notable features |
Uniswap | Stable pairs – 0.05%
Standard – 0.3% Exotic – 1% |
6 chains.
V1 – Ethereum V2 – Ethereum V3 – Ethereum, Arbiturm, Polygon, Optimism, BSC, CELO. |
The first Ethereum-based DEX.
Innovator of V3’s concentrated liquidity. |
Curve | 0.04% on all pools, of which 50% goes to the LP, and 50% to veCRV holders. | 12 chains.
Ethereum, Arbitrum, Aurora, Avalanche, Fantom, Harmony, Optimism, Polygon, xDai, Moonbeam, Kava, Celo. |
Special focus on efficient stablecoin trading with low slippage. |
Balancer | Customisable by pool creator. Can be either permanent upon pool creation, or dynamic by allowing Balancer Governance to adjust.
The protocol takes 50% of all swap fees.
|
4 chains.
Ethereum, Gnosis, Polygon, Arbitrum. |
Customizable pools like Weighted pools (eg 80/20 weightings) or Boosted Pools (idle liquidity in LP can be deposited into Aave) |
Pancakeswap | V2 – Fixed 0.25% trading fee
V3 – 0.01%, 0.05%, 0.25% or 1% |
3 chains.
Ethereum, BSC, Aptos. |
Biggest protocol on BSC according to TVL. |
Sushiswap | 0.3% fee, with 0.25% going back to the LP pool. | 18 chains.
Ethereum, Arbitrum, Arbitrum Nova, POlygon, Gnosis, Fantom, Moonriver, Harmony, Avalanche, Optimism, Moonbeam, Fuse, BSC, Kava, Metis, Telos EVM, Celo, Boba Avax. |
|
Velodrome | 0.02% to 0.05% | Optimism | Solidly fork and the only one on Optimism..
Biggest protocol on Optimism according to TVL. |
Trader Joe | Base fee: Configured by protocol owner
Variable fee: Depends on the volatility of the market. |
3 chains.
Avalanche, Arbitrum, BSC. |
Integration with its NFT branch, JoePEGs. |
Centralized Exchanges vs. Decentralized Exchanges
A centralized exchange (CEX) offers cryptocurrency exchange services to registered users. Its primary service typically matches buyers and sellers with an order book, though a CEX may offer its verified users various crypto products. For beginners, a CEX provides the simplest way to get started without needing in-depth knowledge of blockchain infrastructure and tools.
A decentralized exchange (DEX) uses on-chain smart contracts to run its exchange services. In most cases, users swap tokens from liquidity pools, with liquidity provided by other users in exchange for swap fees.
You don’t need to register for a DEX, meaning they’re open to anyone with a wallet and some crypto. DEXs are the gateway to the decentralized finance (DeFi) world and provide users with a lot of freedom. However, they lack the support a CEX can give, and it can be easy to make irreversible mistakes when using them.
CEX
The following are the pros and cons of using a CEX.
- User-friendly – CEXs tend to have better user-friendliness, with detailed guides ranging from account setting up, to troubleshooting.
- Support and protection – Customer support is usually available, and users do not have to bother with gas fees or smart contracts vulnerabilities. In the event of a funds dispute or an error in the transaction, there is a higher chance of reclaiming these funds.
- Liquidity – There tends to be the largest liquidity in the top CEXs, making it better for users transacting in large amounts.
- Vulnerability to attacks – As CEXs are centralized, they become easy targets for attacks by malicious actors, including hacks or denial of services.
- Transaction fees – There are many fees in the usage of CEXs, including transaction fees, currency conversions, etc.
- No custody of assets – When using a CEX, you must deposit your crypto into its wallet. This means you relinquish custody of your funds by entrusting them to the CEX. As such, you may be unable to withdraw them whenever you please. This is problematic if an exchange becomes insolvent and can lead to you losing your funds entirely. This situation is similar to storing your cash with a bank — during a run on the bank, you may not be able to access your funds.
DEX
The following are the pros and cons of using a DEX.
- Custody of funds – When using a DEX, you never lose custody of your funds until a trade or interaction is complete. This means you can move and store them as you wish. If your crypto is stored in a wallet whose seed phrase only you can access, you have total control over your assets. To decentralization advocates, this is one of the most critical factors.
- Data protection and privacy – When using a DEX, there’s no need to supply personal, identifying information and trust it to be stored securely. This means your personal data is safe from bad actors who want to steal your identity. Note that when using an exchange, you are still bound by local regulations and laws.
- Lower barriers to entry – Using a DEX requires only a wallet and some crypto to trade and pay gas fees. This makes DEXs highly accessible to a larger group of people globally. For decentralization fans, this is a huge benefit, and many value the more private nature of a DEX. Of course, this should also be considered in the context of local legislation, as well as relevant debates on crypto regulation.
- Complex to use and enter – For a first-time user, understanding how to navigate and use a DEX can be challenging. Gas fees, liquidity pools, wallets, and slippage are all possible hurdles to overcome. It takes time to grasp how a DEX works confidently and to invest responsibly, you should always understand your tools.
- Lack of fiat on and off ramps – Historically, buying your first coin or token was one of the most significant barriers to gaining crypto exposure. CEXs now, as a standard, offer credit and debit card options for buying crypto. Although some DEXs are beginning to offer this service with third-party providers, most still don’t allow credit or debit card usage.
- Liquidity struggles – DEXs, on average, have smaller volumes and less liquidity than large CEXs. Market depth can be smaller, and large trades on a DEX may have a more significant price impact than if done on a CEX. Traders or investors making large volume orders can often find a better price doing over-the-counter (OTC) trades or using a CEX with deep order books.
Chains
Uniswap currently has 3 versions, as V1 and V2 will continue to work as long as Ethereum exists. However, V1 and V2 are only available on the Ethereum Mainnet, while V3 is available on the following chains:
- Ethereum
- Polygon
- Optimism
- Arbitrum
- Celo
- BNB Chain
It is assumed that more liquidity will continue to be drawn towards V3 over time.
There are also proposals to expand Uniswap to the following chains:
- Deploy Uniswap v3 on Moonbeam (2023)
- Deploy Uniswap v3 on Avalanche
- Temperature Check: Deploy Uniswap v3 on Scroll
Users
There are two main actors with conflicting interests:
- Traders want low fees and liquidity to be highly concentrated relative to volatility.
- LPs: want to earn fees and prefer liquidity concentration to be low relative to volatility.
Recent research shows that at least in the most popular Uniswap v3 pool (USDC/WETH 0.05%), LPs have been suffering large losses. However, this is not necessarily indicative that providing liquidity is an irrational action that is expected to disappear over time. This is explained because most PnL analyses are sometimes misinterpreted and applied more broadly than they actually should. For instance, it is not realistic to expect a single one-size-fits-all pool for all traders and liquidity providers.
Currently, most metrics measure EV (Expected Value) in USD terms relative to HODL, hence the prominence of impermanent loss. However, this is not always the right measure to determine the success of a liquidity provider. As an example, the image below shows that even for the ETH/USDC pair, the expected PnL is quite different depending on the pool.
Investors
The benchmark selected for running and evaluating a strategy depends on the personal goals of the liquidity providers: composite position of stable and volatile assets, holding only volatile assets, holding only stable assets… There are advanced strategies that can be put into practice with automated bots, such as rebalancing (buying and selling assets to reach a specific balance in a portfolio), just-in-time LP, running arbitrage bots…
Volatility
When asset prices move, LP positions collect fees. As a rule of thumb, more volatile pools collect more fees. However, larger volatility should be compensated with larger fees. Mathematically, the increase in fees should be proportional to the square of the increase in variance. For example, an asset pair that is 3 times more volatile than another should generate 9 times more fees, all else being equal. To capture this volatility, LPs can opt into higher fee pools or increase the range of their positions in the case of V3 positions.
- Implied volatility is calculated from daily fees.
- Realized volatility is calculated from the multi-day rolling average of daily returns.
The results calculated for the dashboards below follow calculations using daily volumes and liquidity information taken from Uniswap v3 pools directly to extract the implied volatility of any asset. Further research can be found in the paper Panoptic: a perpetual, oracle-free options protocol by Guillaume Lambert and Jesper Kristensen.
Ethereum pools: https://dune.com/queries/2410783/3956867
Arbitrum pools: https://dune.com/queries/2410794/3956882
Optimism pools: https://dune.com/queries/2410817/3956914
Polygon pools: https://dune.com/queries/2410868/3956983
Capital Efficiency
The main function of liquidity pools is to enable trading activity. All else being equal, a pool is more attractive for traders if it has deeper liquidity. The reason for that is that deeper liquidity offers lower slippage and reduced price impact for trades.
The design of Uniswap V3 indeed focuses on capital efficiency and this is achieved through the concept of concentrated liquidity. In Uniswap V2, liquidity providers (LPs) had to provide liquidity across the entire price spectrum, which meant that a significant portion of their capital was underutilized. With Uniswap V3, LPs can specify price ranges for their capital to be used, concentrating their liquidity at the prices they believe will be most traded.
In this case, the result would be x=0 ETH and y=2000 DAI. Hence, the user would need to provide 2000 DAI to achieve the same liquidity depth as in Uniswap V2, but they wouldn’t need to provide any ETH.
In terms of capital efficiency:
- For a [P / 2, P * 2] price range ($1,000-$4,000), the capital efficiency would be approximately 3.41x.
- For a [P / 1.2, P * 1.2] price range ($1,667-$2,400), the capital efficiency would be approximately 11.48x.
- For a [P / 1.1, P * 1.1] price range ($1,818-$2,182), the capital efficiency would be approximately 21.49x.
- For a [P / 1.05, P * 1.05] price range ($1,905-$2,100), the capital efficiency would be approximately 41.49x.
- For a [P / 1.01, P * 1.01] price range ($1,980-$2,020), the capital efficiency would be approximately 201.5x.
This opens up a lot of possibilities for LPs to optimize their capital usage based on their view of the market. For instance, if an LP has a strong belief that the price of an asset will remain relatively stable, it can set a very narrow price range, thereby increasing its capital efficiency significantly. This also means that they will earn more in fees per unit of capital deployed compared to a V2 pool.
Therefore, depending on how narrow the user sets their price range, they can be significantly more capital efficient in Uniswap V3 compared to Uniswap V2. However, there’s a trade-off: the narrower the price range, the higher the risk that the price will move out of this range, at which point the capital will no longer earn fees. As a result, this increased capital efficiency comes with its own risks. If the price moves out of the specified range, the LP’s capital will no longer earn fees until the price moves back into the range. Additionally, if the price moves significantly away from the range, the LP could end up with all of one asset, a situation known as impermanent loss. Hence, while Uniswap V3 offers increased capital efficiency, it also necessitates a more active and strategic approach to providing liquidity.
Providing Liquidity in Uniswap V2
The value of an LP position is:
V(P):=xP+y
Where the price P is defined as P:= y/x
Assuming a constant product market maker, the relation between the amounts of assets in a position is defined as xy=k, where k is a constant. The pool’s liquidity L is defined such that L^2:=k
Then it follows that:
Where V(P) changes when P changes.
Hence, the value function of an LP position is a square root function.
Following the Black Scholes model, we can use:
- (delta) to denote the price-dependence of the value function, and
- (gamma) to denote the price dependence of the delta.
- Comparison between the delta of LP and HODL
- If the asset price increases, then LP’s delta is lower than the delta of a 50:50 HODL position
- If the asset price decreases, then LP’s delta is higher than the delta of a 50:50 HODL position
The LP position is underexposed to price increases and overexposed to price decreases. In other words, when the price goes up, the gain of the LP is reduced.
This is not a problem specific to Uniswap. The LP gamma is expected to be negative in all reasonable AMMs.
- Comparison between the gamma of LP and HODL
When assessing Uniswap V2 LP positions, the question to ask is whether the depositor wants to be exposed to something that changes in value with the square root of price. In some cases, the answer might be that this is a desirable form of rebalancing. However, for the majority of use cases, there are better risk-reward functions for the user’s risk tolerance levels (due to the complexity of maximizing this function).
The figure above shows the shape of the LP value function relative to the benchmarks. The orange area shows a loss relative to the initial value, and the green area shows a gain or neutral value.
Investing Strategies in Uniswap V3
The situation for V3 positions can get more extreme due to the narrow ranges used by LPs. This can lead to a high-risk position if left unmanaged:
While the fees earned by the concentrated liquidity positions can be much higher than those of v2-style full-range positions. These fees are accrued only when the position is in range, meaning that losses due to large price volatility are unlikely to be fully compensated with matching increases in LP fees.
50:50 HODL
This is analogous to positions in Uniswap V2 pools, where the liquidity is provided across the entire range.
Single Asset Exposure
If an LP is bullish on one asset and wants to maintain exposure to it, it can place its liquidity range such that it includes the current price and extends towards the asset they are bullish on. This way, they are more likely to end up with more of the asset they prefer if the price moves in that direction.
Exposure to Multiple Fees and Ranges
LPs can diversify their risk by providing liquidity in multiple pools. This helps mitigate risks associated with any single pool. This also allows LPs to adjust their ranges based on the fees they expect to earn. For pools with high volatility, the fees are often higher. Therefore, an LP could choose to provide liquidity in a high-volatility pool within a narrow range to maximize fee returns. However, this comes with the risk of being priced out of the range. This could be offset with wider ranges on lower volatile pools.
Liquidity Mirroring
Liquidity mirroring refers to the strategy by which LPs set their liquidity one range above and one range below the current market price. This way they can earn fees on both sides of the current price and increase their chances of staying in the range.
Range Shifting
This strategy consists in actively shifting the liquidity ranges of a position to stay close to the current price. This requires being more active but can result in more fees since trades are likely to occur near the current price.
Trustless Market-Making Strategies on Uniswap V3 – Arrakis
Arrakis is a protocol that aims to solve the tradeoff between the increased capital efficiency that can be achieved with Uniswap v3 and the complexity that comes with actively managing liquidity. Arrakis is a trustless market-making infrastructure protocol that runs sophisticated algorithmic strategies on Uniswap V3. Liquidity providers can deposit liquidity into Arrakis Vaults to manage their liquidity in an automated, capital-efficient, transparent, and non-custodial manner.
Arrakis V2 introduces features such as:
- Multiple Concentrated Liquidity Positions with any arbitrary combination of liquidity positions in a Uniswap v3 pool.
- Cross Fee Tier Vaults across pools with different fee tiers.
- Fungible positions wrapped using the ERC20 token standard. This makes Arrakis vaults composable with other DeFi protocols.
- Non-custodial positions where the liquidity can only be withdrawn by the original depositor.
Automated Liquidity Management on Uniswap V3
Although improvements have been made for LPs, providing liquidity still remains a complex and time-consuming process. One must consider price ranges, fee tiers, and the risk of impermanent loss.
Active liquidity management (ALM) are strategies that actively adjust the liquidity parameters on behalf of the LP.
Some of the available ALMs include:
Mellow Protocol
A permissionless ecosystem for active liquidity management and building trustless automatic DeFi strategies.
Mellow has a “Uni V3 Boosted strategy” that provides a risk profile very similar to a fixed UniV3 position but with higher returns.
The idea of the strategy is to optimize a Uniswap V3 position (domain interval) by using an equally profitable Uniswap V3 position of a smaller size (short interval) and depositing the remaining tokens into yield protocols. This is based on the fact that positions with the same liquidity (in terms of Uniswap V3) receive the same fees and suffer the same impermanent losses.
However, the number of tokens required for equal liquidity on a smaller interval is less. So, the remaining tokens are deposited into yield protocols, increasing final APY and reducing non-permanent losses compared to storing tokens in a domain interval on Uniswap V3.
Gamma Strategies
A protocol for active liquidity management and market-making strategies.
Gamma is built with modular components consisting of a Uniswap position manager contract called a hypervisor, which contains a set of functions that are able to be called by an active manager or Supervisor contract. The hypervisor functions include rebalancing ranges, depositing liquidity, collecting and re-investing fees, and redeeming LP tokens for the underlying assets.
When the user deposits their token into a hypervisor, a fungible ERC-20 liquidity provider token is minted, which represents their fractional ownership of the pool. If they want to withdraw tokens from the pool, the LP token is burned. The hypervisor structure allows for multiple parties to pool their tokens into a single actively-managed position.
Gamma’s vault contracts automatically manage the price ranges, rebalance assets, and re-invest earned fees to generate yields optimally. This active approach is superior to a passive LP option.
Orange Finance
An automatic Liquidity-Management protocol on Uniswap v3 with the delta hedging strategy.
Orange Finance’s unique combination of delta hedging and automated price range setting makes it a compelling option for LPs looking for higher capital efficiency and lower risk.
Orange Finance’s delta hedging strategy is a unique feature that sets it apart from other liquidity management protocols. To put it simply, the vault offsets LP losses incurred due to the price movement and frequent rebalancing by making a short position of $ETH on Aave.
In the event of a downward market movement, for example, the short position on Aave makes a profit, which offsets the loss in LP value.
Therefore, LPs are able to earn trading fees from Uni v3 while minimizing the loss risk of their LP value.
Popsicle Finance (WAGMI)
The Wagmi protocol is a comprehensive solution for the decentralized finance (DeFi) ecosystem that aims to provide a seamless experience for trading, liquidity provision (LPing), swapping and strategy generation.
The initial implementation of the Wagmi protocol will take place on the ZKera mainnet, which is a highly secure and scalable blockchain network. This will serve as a foundation for the protocol and will be a crucial step in ensuring the stability and security of the platform. Once the protocol is thoroughly tested and refined on the ZKera mainnet, it will be deployed on other blockchain networks via the omni layer allowing for greater decentralization and accessibility.
The central concept of WAGMI is focused liquidity, where liquidity is assigned within a specific price range, with active liquidity management called Sorbetto Fragola.
Sorbetto Fragola is a cutting-edge solution designed specifically for Uniswap v3 that enables active liquidity management. By optimizing the price range based on historical volatility, Sorbetto Fragola ensures that users’ funds are always in the most traded utilization zone, maximizing trading fee returns and profitability. While this strategy is optimized for trading fee yield, it’s important for users to consider Impermanent Loss (IL) as well.
Arrakis Finance
Arrakis is web3’s trustless market-making infrastructure protocol that enables running sophisticated algorithmic strategies on Uniswap V3. Liquidity providers can utilize Arrakis Vaults to have their liquidity managed in an automated, capital-efficient, non-custodial, and transparent manner. Arrakis PALM is the automated management product of the protocol.
PALM helps protocols bootstrap liquidity, without having to conduct any liquidity mining or OTC deals (e.g. bond sale), but rather through active market making on UniV3. PALM sets UniV3 positions to be able to average in and out of base assets or governance tokens, with an aim to help protocols get equal liquidity on both the buy and sell sides.
Instead of having to provide liquidity between governance token and base asset in a 50:50 ratio, projects can seed the initial liquidity in any ratio, e.g. 95:5, and PALM will progressively pull it towards 50:50. After having acquired a robust amount of base asset, the focus then is to ensure sustainable and deep liquidity that can support the ongoing trading volumes around the current price.
OTM short put / covered call
The current price of $ETH is $2200. A user bets on $ETH staying in the range or going up and places $2000 USDC in the USDC/ETH pool, at a highly concentrated liquidity position with strike price K=$2000, where K=√(PriceUpper⋅PriceLower).
The image below shows some example payoffs. When price decreases to ~$2000, swap fees are collected.
OTM short call / covered put
Simulating a short call requires one more step. The user starts by depositing $3000 in a lending protocol, which they use to borrow 1 ETH for the LP position. The strike price once again is K=$2000. Now the main risk is price going up, since the borrowed ETH will be sold at the strike price. This strategy is suitable for hedging long ETH exposure elsewhere.
Other types of positions
- Single-sided LP using owned ETH to is similar to an ITM short put.
- Single-sided LP using borrowed USDC is similar to an ITM short call.
- Using normal, double sided LP positions is similar to a combined portfolio of one ATM/near OTM put & one call, since the double sided position can be thought of as two single-sided ones.
- A wide range position can be conceptualized as the sum of multiple options with different strike prices.
Hedging LP Positions
Entering into unhedged LP positions can be a high-risk strategy (the risk increases with narrower ranges) and may often be unprofitable.
An LP position can be hedged by putting in funds as collateral to borrow the volatile asset. 100% or less of the volatile asset can be borrowed (the rest owned) depending on the position’s desired value function and payoff function.
For full-range LP positions, using borrowed assets reduces the downside risk when the price goes down, and the cost of increasing the downside risk when the price goes up.
For narrow-range positions, the downside risk on price decreases can be perfectly hedged when 100% of the volatile asset is borrowed. However, the PnL would still be negative when compared to just holding stablecoins. To match the PnL of stablecoins, one would have to borrow 200% of the volatile asset initially required for the pool and short-sell the half left over after initializing the LP position.
A similar idea would be to short-sell the volatile asset in a margin-trading platform. This is potentially more capital efficient since there is no need to over-collateralize. However, under normal market conditions, overcollateralized borrowing is likely to have a positive net APR, while the funding rate for margin trading is likely to be negative. Nonetheless, liquidation risk is present in both strategies.
There is a symmetrical strategy that can protect the gains in case the asset price goes up. This strategy can be used if the user is bullish on the price of the volatile asset. Instead of borrowing and shorting it, the user would either buy the asset and borrow stablecoins against it or long it on margin. The payoffs are symmetrical to the ones discussed above but with the x-axis inverted.
Hedging for Sideways Markets
To come up with delta-neutral strategies, the user must take into account that the payoff function of an LP is concave. Besides, providing liquidity with borrowed assets does not change this. What’s more, hedging via borrowing assets still leaves exposure to unlimited downside risk while limiting the max payoff.
Uniswap’s payoff function is quite similar to that of option sellers. For instance, buying both a put and call option for the same asset results in a long straddle (profit on volatility) position. When combined with a partially hedged LP position, as shown in the figure above (partial hedge of 0.45), it can result in a delta-neutral (flat) total payoff. In other words, Uniswap LPs are selling volatility, while straddles are buying volatility. Altogether, the positions should cancel each other out.
Summary of Payoffs
- Uniswap pools offer a real-yield opportunity for liquidity providers.
- Entering unprotected LP positions, especially those with narrow ranges, are rarely a good strategy
- A 50:50 HODL position might not always be the benchmark the LP wants to use.
- Downside risks can be hedged using borrowed funds or by short-selling the volatile asset.
Dynamic Hedging
The payoff of HODL positions follows a linear partner where the value function resembles a straight line. This remains true for all HDL positions:
- the payoff of holding only stablecoins is a horizontal line
- the payoff of a 50:50% HODL portfolio is the y=x/2 + const line
- the payoff of 100% volatile asset is the y=1·x line
- longing the volatile asset through 10x leverage trading has y=10·x payoff and shorting it with 10x leverage has y= — 10·x payoff (up to the point of liquidation, and assuming a zero funding rate for simplicity).
In contrast, the payoff of an LP position is nonlinear:
- The value of a full range LP position – Uniswap v2 style – grows with the square root of the price.
- The value and payoff for Uniswap V3 positions cause the outcome to be more extreme, due to concentrated liquidity, including the non-linearity of the LP value and payoff functions.
When a linear function is added to a non-linear one, the result is always another nonlinear function. This means that LP positions cannot be perfectly hedged by just longing or shorting the volatile asset once. This type of nonlinearity is present in most AMMs (as mathematically demonstrated in this paper), not just Uniswap’s xy=k type of AMM.
There are AMMs with bonding curves that are close to a line for some values of the price. Curve is the most well-known of these. However, while Curve offers nice properties for stable swaps, it has higher slippage and risks for LPs at the extremes of the bonding curve (when the price deviates too much from the stable region. In other words, Curve reduces the likelihood of losses, but increases the severity of the losses if they do occur.
For context, the convex payoff is better than the linear payoff whether the price goes up or down; a concave payoff is the opposite:
To understand dynamic hedging, it is worth keeping in mind the Greeks in a financial context:
- The first derivative of the portfolio’s value function with respect to price is the delta. This represents the rate of change of the portfolio’s value in relation to price.
- The second derivative of the portfolio’s value function with respect to price is the gamma. This represents the rate of change of delta with respect to price.
Example values of the Greeks:
- All HODL portfolios have zero gamma, and the delta for HODL portfolios that don’t have loans or leverage ranges from the delta-neutral 0 to 1.
- All LP positions have negative gamma. In the case of full-range LP positions, the gamma is inversely proportional to, where is the change in price relative to the initial price at which the position was created.
Example Concave Payoff
Example Convex Payoff
In a dynamic hedging strategy, the goal of the LP is to fight negative gamma. This can be done with the following;
- Maximizing fee income. LPs are profitable relative to HODL when fee income is greater than the divergence loss.
- Using less volatile pairs. The expected value of impermanent loss is a function of volatility (source 1, source 2).
- Hedge the position using financial instruments that offer exposure to positive gamma, like options and perpetuals.
- Use dynamic hedging, i.e. dynamically re-hedge the position whenever the price changes.
In order to maximize fees, it is worth noting the importance of selecting a good pool with an optimal fee tier. In this step, the pool’s APY is not enough, and it is also recommended to check other indicators like implied volatility or to compute the pool’s Sharpe ratio.
Up-and-coming protocols will make it possible to generate additional fees, such as lending out LP positions, like Gammaswap, or locking them in other ways to earn additional fees, like Infinity Pools and Panoptic.
When it comes to less volatile positions, stablecoin pairs offer a great alternative to avoid suffering from impermanent loss (although there is a depeg risk).
With respect to financial instruments, it is worth noting that Uniswap V3 concentrated liquidity positions have a similar payoff to selling options. A way to hedge is by buying options. An alternative might be to use power perpetuals of protocols like Gammaswap and Smilee Finance.
For dynamic hedging, however, there is no need to use financial exotic instruments. Instead, it is sufficient to rebalance the hedge whenever the price changes.
For example, if a pool has assets A and B, and the position is hedged, one could use borrowed LPs such that if the price of A relative to B moves a bit, the hedge almost perfectly covers the position, and the loss or gain from the price move is low. Alternatively, if the price moves a lot, the hedge is out of sync with the assets in the pool and it no longer is a good hedge for the position.
However, rebalancing the hedge on price changes also has an associated cost. Rebalancing requires trading and this involves paying swap and transaction fees.
Example
- A user starts with 5,000 $USDC and provides liquidity in the $USDC/$ETH pool. The initial price of $ETH is 1,000 $USDC.
- The user puts 4,000 $USDC in Aave and borrows 1 $ETH, and puts the assets 50:50 in a full range Uniswap position.
The initial capital of 5,000 $USDC is now divided between the hedge, with a value of 3,000 $USDC, and the pool, with a value of 2,000 $USDC.
- V_collateral = 4000
- V_debt = 1000
- V_hedge = 4000–1000 = 3000
- V_capital = V_pool + V_hedge = 5000
- The price of $ETH increases by 2x and reaches 2,000 $USDC. Now the value in the pool is 2,000 2 $USDC but the value of the hedge decreases to 2,000 $USDC.
- V_collateral = 4000
- V_debt = 2000
- V_hedge = 4000–2000 = 2000
- V_capital = V_pool + V_hedge = 2000 ·(1 + sqrt(2)) = 4828 USDC
- There is a 3.4% loss with the same initial capital and strategy
Now take the example of a user who starts with the same capital and strategy but, when ETH reaches 1,500 USDC, notices that the liquidity now contains less than 1 ETH and that some of the borrowed ETH can be repaid while keeping the position fully hedged. In this case, the user removes some USDC from Aave, swaps for ETH, and repays ETH so that the amount of ETH borrowed is exactly equal to the amount of ETH in the liquidity position. When ETH reaches 2,000 USDC, the user would still have some loss, but it would be much lower than the loss of the first user.
The key takeaways are that by hedging and periodically rebalancing the hedge, the LPs can protect their capital from both price decreases and price increases, meaning that delta-neutral positions are possible. Similarly, LPs can minimize divergence loss if they use the “price changes for x%” as a trigger for the hedge rebalancing process. The smaller the price step used to trigger an update of the hedge, the smaller the remaining divergence loss. However, using a smaller rebalancing step leads to higher operational costs.
Toxic Flow
From a cost-benefit analysis point of view, the benefit for LPs comes from fee revenue and liquidity mining incentives. This comes at the expense of adverse selection of orders. Since AMMs do not rely on external oracles, they rely on arbitrageurs for price discovery. This concept is often denominated “toxic flow”, and represents the fact that the price marked to the future is worse than the execution price after taking into account the impact of fees and price impact. In other words, toxicity is the result of the adverse selection that passive market makers on Uniswap suffer at the expense of market takers – when there are informed traders with better information about an asset’s price than the AMM’s LPs. As a result, LPs end up taking the wrong side of trades at stale inferior prices. For example, arbitrageurs intervene in an AMM to bring the price to the real market price. They do this by taking advantage of price differentials in other Dexes.
- LPs in AMMs profit when fees > impermanent loss
- LPs in AMMs lose when fees < impermanent loss
Impermanent loss is the DeFi term to refer to the adverse selection that occurs when users provide passive liquidity in an AMM.
At first glance, one approach to calculating the PnL is to compare the LP’s portfolio value at deposit versus withdrawal. However, this can obscure the costs of adverse selection. Normally, this loss is measured by accounting for impermanent loss. But this is also problematic because it fails to take into account the trajectory of price movements. For instance, if ETH aggressively moves from $1,000 to $2,000, arbitrageurs keep making profits in their attempt to align the AMM price with the true market price on other exchanges. From an impermanent loss perspective, LPs seem to suffer no loss. However, arbitrageurs are making extra profits at the expense of LPs. As a result, greater volatility can offer more arbitrage opportunities and higher adverse selection costs.
If the fee of a pool is small, the pool is expected to get a lot more volume than a pool with a higher fee. Most of that volume will be “toxic”, but as an AMM LP, you don’t care, since the position is there to fill volume and collect fees for being a maker. Nevertheless, that does not avoid being exposed to price directionality. As makers, LPs are buying the assets that swappers want less of, and if that trend of one asset losing value happens too far in one direction, then it is harder to profit as a non-directional LP.
In practice, LPs should be aware of the fee tier they are in, but that does not imply that LPs are trying to avoid toxic flow. LPs are agnostic to flow toxicity, and more volume will translate into more fees.
As a rule of thumb, higher fees lead to fewer losses to arbitrageurs, whereas the opposite occurs with lower fees.
As a hypothetical scenario, we can assume a V2 AMM pool with 1 ETH and 1,000 USDC when ETH is trading at $1,000. Supposing that ETH goes to $4,000, the LPs will have sold 0.5 ETH when the ETH price is $2,000. This outcome is worse than simply selling at $4,000. Next, if we take a rebalancing strategy where LPs buy/sell assets based on the market price on other exchanges, we can infer that instead of selling 0.5ETH at $2,000, this strategy would sell ETH at $4,000. In this scenario, the total portfolio value would be 0.5 ETH + 3,000 USDC, which amounts to $5,000. Hence, we can observe that the Loss Versus Rebalancing (LVR) is $5,000 (in the rebalancing strategy) – $4,000 (LP in the AMM) = $1,000. That means that, in the event that ETH jumped from $1,000 to $4,000, LPs end up losing a $1,000 cost that reflects the cost of adverse selection to informed traders or arbitrageurs.
It is worth noting that directional price movements are related to market sentiment, and have nothing to do with toxic flow from arbitrageurs.
Loss Versus Rebalancing (LVR) is a term that describes the loss in value of a CFMM (Constant Function Market Maker) reserves relative to the value that would have been achieved with a rebalancing strategy. This metric is used to measure how much worse LPs do versus if they actively traded the underlying assets.
It can be helpful to think of LVR as the maximum profits extracted by arbitrageurs given infinite liquidity at the market price (and therefore no slippage) with no fees.
Most LP positions on Uniswap are unprofitable. This is a consequence of the AMM design. A CFMM like Uniswap is in essence an automated rebalancing strategy that sets spot prices along a bonding curve in order to keep the same USD value for both sides of the pool (the AMM forces trades to stay at a level that maintains the xy=k invariant).
In fact, liquidity providers supply immediacy to DEXs: they sell when someone wants to buy and buy when someone wants to sell. That comes at the expense of selling too cheap and buying too expensive from better-informed market actors.
LVR describes how arbitrageurs extract value from LPs. This is done by describing their order flow as “toxic”, as it forces the LPs to buy or sell against the market. The other flow, presumably mostly retail-driven, is considered “uniformed”. If the uniform flow dominates over the toxic flow, the pool does not suffer from the LVR problem.
Unlike impermanent loss, LVR depends on price trajectory and increases with every trade. LVR is also larger for Uniswap V3 due to the presence of more marginal liquidity if the price falls within a certain price range.
The chart below shows the quality of trades execution across many time horizons. The negative PnL suggests that passive liquidity providers consistently lose money against the toxic flow from arbitrageurs. Nonetheless, providing liquidity can make sense for LPs that want to express an opinion that matches the LP return profile. As a matter of fact, LPs are making a bet about how a pair will behave in terms of price movement and trade volume, regardless of whether the pool has a toxic flow or not. Therefore, what matters is the entry price, the fees collected, and the exit. Whether arbitrageurs make money as the price moves during that time period is not relevant to the LPs PnL.
Similar to a short straddle position, LPs in a CFMM sell the volatile asset when it increases in price, and buy it when it decreases in price.
- Short straddle positions lose money when the final price level is very different from strike prices.
- CFMM LP positions lose money if the final price is very different from the initial price at the time of the deposit
By that analogy, LP positions can be thought of as giving away a short straddle position without collecting the upfront option premium. This is one of the reasons why most passive LPs are unprofitable, because unlike option sellers, they are not sufficiently compensated for the risk they are taking. To fully compensate those positions, a revised AMM would include a dynamic fee structure that increases with volatility to ensure that LPs are fairly compensated.
Just-In-Time Liquidity (JIT)
Just-In-Time liquidity is a special form of liquidity provision where an LP mints and burns a concentrated position immediately before and after a swap. This is a strategy where liquidity providers (LPs) add their liquidity to a pool only when they see a profitable trading opportunity, and remove it as soon as the trade is complete. This is a form of MEV, as these liquidity providers take advantage of information about pending transactions in the Ethereum mempool (where all the transactions wait to be processed) to generate profits.
- An LP position was minted and burnt in the same block
- The mint transaction and burn transaction are exactly 2 positions apart in the block
- The transaction between mint and burn is a swap transaction in the same pool
In the image above, all 3 transactions took place in the same block in a sequential manner. The LP bundled all 3 transactions and submitted the bundle through Flashbots.
Here’s a hypothetical example to illustrate this:
A JIT LP has both ETH and USDC in its wallet and on a centralized exchange (CEX). They see a large $ETH -> $USDC trade about to occur on Uniswap (by observing the mempool), they quickly add a liquidity position to the Uniswap pool and simultaneously submit an $ETH buy order on the CEX. This is because they anticipate the price of $ETH to increase due to the large trade.
Assuming the fees and price impact (change in price due to trade) are less on the CEX than on Uniswap, the LP ends up with the same amount of $ETH and $USDC as before but with additional profits from the difference in fees and price impact.
A study suggests that many JIT LPs aren’t profitable, with about 37% of all JIT positions leading to losses. Furthermore, many JIT LP positions have very low profits, likely lower than safer, “risk-free” DeFi activities such as staking or supplying stablecoins on platforms like Aave.
The problems when analyzing these trades come from the fact that only one side of the trade is visible on the blockchain as a swap, whereas the other part occurs on a centralized exchange. Furthermore, the methodology for computing the divergence loss (loss due to price divergence between assets in a pair) may be flawed as it doesn’t account for the price impact of a swap correctly.
JIT LPs may also be more exposed to “toxic order flow” – large orders that are likely to result in losses. Most trades are profitable for LPs, but larger ones can often have a negative expected value due to the slippage.

Two necessary conditions need to be met for LPs to price supply JIT liquidity:
- There is + EV (Positive Expected Value).
- The LP can outbid other MEV opportunities in Flashbot auctions.
The revenue of the trade is:
Revenue = LiquiditySuppliedPoolFeeRate + PriceImpact
And the cost of the trade is:
Cost = LiquiditySupplied OtherLiquidityVenueFeeRate
+ PriceImpactOnOtherLiquidityVenues
+ GasFeeOfAddingLiquidity
+ GasFeeOfRemovingLiquidity
+ ProfitShareWithMiner
Starting with the assumption that there is no arbitrage opportunity at the start of the trade (meaning the pricing on Uniswap is the same as on other liquidity venues), a JIT LP aims to maximize fee earnings. They do this by providing enough liquidity to accommodate the entire swap and concentrating all the liquidity in one tick space (a range of prices in Uniswap v3). This results in a near-zero price impact on the Uniswap pool in the tick space where JIT liquidity is minted. This refers to the second item from the Revenue formula, which is zero if the JIT LP mints in the current tick, or a small amount (d) if they mint in the next tick.
As for costs, the fee rates on other exchanges are assumed to be non-negative, providing a lower bound of zero for the first cost item. This first cost item refers to the amount of liquidity supplied times the fee rate of other liquidity venues. In addition, it’s assumed that the JIT LP will cause some price impact (also known as slippage) while hedging, also leading to a non-negative cost.
This leads to an upper bound on the expected profit from a JIT transaction, which is the difference between revenue and cost. The maximum profit would be the liquidity supplied times the Uniswap fee rate minus the total gas cost and the miner’s share of the transaction fees. Since JIT LPs require a positive expected profit, the maximum miner share that the JIT LP would be willing to pay can also be determined. This is equal to the liquidity supplied times the Uniswap fee rate minus the total gas cost.
The idea of an “inverse-JIT” strategy could be a possible solution as a hedge. Here, an LP would monitor the mempool and remove their liquidity whenever a potentially loss-making trade appears. Once the trade is executed, they would add their liquidity back, potentially at a different price range. This could work on Layer-2 solutions where gas fees are lower.
However, JIT transactions are very rare; there were a little over 8,000 JIT transactions between May 2021 and July 2022, and JIT liquidity accounts for a fraction of a percent of Uniswap v3’s total liquidity provided. Because JIT liquidity provision has significant fixed costs, it is usually only used against very large swaps, improving the execution quality of trades that would otherwise suffer high degrees of price impact.
It is also worth noting that having a positive expected profit is not a sufficient condition for a JIT transaction to take place. Since JIT transactions are often submitted through a Flashbots bundle, the LP needs to outbid other searchers who also want to include the swap as part of their bundle. With perfect information and rational players, this should only happen when a JIT transaction is more profitable than all other possible MEV bundles using the same swap (such as sandwich attacks, back-running arbitrage, etc).
The expected profit of an MEV searcher can be calculated as:
Profit =SwapSize(SwapPriceImpact-PoolFeeRate)
-TotalGas-MinerShare
And to ensure positive value (profit):
MinerShare SwapSize(SwapPriceImpact-PoolFeeRate)-TotalGas
Hence, for aJIT to happen, the expected profit needs to be greater than that of a back-running swap:
JITLiquiditySupplied x PoolFeeRate-JITGasfee
JITLiquiditySupplied x (SwapPriceImpact-PoolFeeRate)
Canceling out JITLiquiditySupplied:
2 x PoolFeeRate >= SwapPriceImpact
And since the price impact of the swap with JIT is close to 0, the right-hand side is basically the price improvement that the trader gets from JIT liquidity. Using those simplified assumptions, the process above derives an upper bound of price improvement: two times the fee rate in the Uniswap pool that the swap is going through. Nevertheless, the result is just an upper bound and is not guaranteed to be (likely not) the actual tight upper bound. For example, instead of simply back-running the large swap, an MEV searcher could potentially generate more profit from a sandwich attack. However, the bound we derived should still hold true.

Economics
Coingecko: https://www.coingecko.com/en/coins/uniswap
Token terminal: https://tokenterminal.com/terminal/projects/uniswap
Fee Breakdown
Swap fees
- Uniswap V2 contracts are non-upgradeable. The protocol charges fees on input amounts. By default, a 30 basis-point fee is charged on trades. However, there is a private key that has the ability to update a variable on the factory contract to turn on an on-chain 5-basis-point fee on trades. This fee has been initially turned off but could be turned on in the future, after which liquidity providers would earn 25 basis points on every trade, rather than 30 basis points, with the remaining 5 basis points possibly going to $UNI token holders via staking.
- V3 introduces multiple pools for each pair of tokens, each with a different swap fee. The factory contract initially allows pools to be created at three fee tiers: 0.05%, 0.30%, and 1%. Additional fee tiers can be enabled by UNI governance.
Protocol Fees
At the moment there are no protocol fees. However, it is possible for a 0.05% fee to be turned on in the future. If enabled, a protocol-wide charge of 1/6th of the swap fee would take effect. For instance, for a 0.3% swap fee, 0.05% would go to the protocol.
Operating Expenses
Team
LinkedIn indicates that there are around 130 employees, although there is no official data regarding the actual numbers and salaries involved.
Emissions
According to the initial $UNI allocation on September 16, 2020, the relevant emissions are as follows:
- 43% retained by the governance treasury to distribute on an ongoing basis through contributor grants, community initiatives, liquidity mining, and other programs at 430,000,000 $UNI.
- 21.266% to team members and future employees with 4-year vesting at 212,660,000 $UNI.
- 18.044% to investors with 4-year vesting at 180,440,000 $UNI.
- 0.69% to advisors with 4-year vesting at 6,900,000 $UNI.
- A perpetual inflation rate of 2% per year will start after 4 years, ensuring continued participation and contribution to Uniswap at the expense of passive $UNI holders.
The following are the estimated cost of emissions on May 21 2023 price of $5.24:
- Governance treasury:
- Year 1 – 40% of the allocation, 172,000,000 $UNI.
- Year 2 – 30% of the allocation, 129000,000 $UNI.
- Year 3 – 20% of the allocation, 86,000,000 $UNI = $450,640,000.
- Year 4 – 10% of the allocation, 43,000,000 $UNI = $225,320,000.
- Team members and future employees
- Total = 212,660,000 UNI = $1,114,338,400.
- Investors
- Total = 180,440,000 UNI = $945,505,600.
- Advisors
- Total = 6,900,000 UNI = $36,156,000.
- Perpetual inflation rate
- Assuming that the 2% is based on a total supply of 1 billion UNI, there would be around $209,600,000 worth of emissions in the 5th year.
The liquidity mining program which started on September 18 2020 ended on November 17, 2020. The community has since not voted on additional liquidity mining incentives using $UNI tokens.
Tokenomics
The $UNI token is an ERC-20 token deployed on the Ethereum mainnet to propose and vote on changes to the protocol.
Token Allocation
According to the initial $UNI allocation on September 16, 2020, the distributions were as follows:
- 60% of the initial 1 billion $UNI minted at Genesis would be given to community members at 600,000,000 $UNI
- 15% of that is claimable immediately at that point.
- 43% retained by the governance treasury to distribute on an ongoing basis through contributor grants, community initiatives, liquidity mining, and other programs.
- 21.266% to team members and future employees with 4-year vesting at 212,660,000 $UNI
- 18.044% to investors with 4-year vesting at 180,440,000 $UNI
- 0.69% to advisors with 4-year vesting at 6,900,000 $UNI
Supply Schedule
Apart from the initial 1 billion minted at Genesis, there is a perpetual inflation rate of 2% per year that starts after 4 years, ensuring continued participation and contribution to Uniswap at the expense of passive UNI holders.
Token Distribution of Holders
Governance
Uniswap’s factory has an owner that is controlled by UNI token holders. This owner does not have the ability to halt the operation of any of the core smart contracts but can enable and turn on a protocol fee.
- Protocol fee: This is a fee that can be turned on by $UNI governance. It’s a percentage of the swap fees that go to the protocol itself. In Uniswap V3, $UNI governance can set this fee to any fraction 1/N where N ranges from 4 to 10, or even set it to 0. This essentially means that the protocol fee can be set between 10% and 25% of swap fees, or turned off entirely. This can be adjusted for each individual pool.
- Additional fee tiers: Uniswap V3 initially comes with three fee tiers – 0.05%, 0.30%, and 1%. $UNI governance has the ability to add new fee tiers as needed. Each fee tier corresponds to a certain level of risk and expected return and is designed to attract liquidity providers with different risk/return profiles.
- Tick spacing: When a new fee tier is added, $UNI governance can also define the tick spacing for that tier. Tick spacing is related to the price granularity of liquidity provision. The initial tick spacings are set at levels that correspond to price movements of approximately 0.10%, 0.60%, and 2.02% for the 0.05%, 0.30%, and 1% fee tiers, respectively.
- Transfer of ownership: $UNI governance also has the power to transfer the ownership of the protocol to another address. This means that the community of $UNI token holders can decide to delegate the administration of the protocol to a different entity if they so choose. This is a powerful feature that ensures the protocol can remain decentralized and under the control of its community.
Governance Process
1. A forum discussion takes place on a Discourse-hosted forum. Community members must register for an account before sharing or liking posts and new members are required to enter 4 topics and read 15 posts over the course of 10 minutes before they are permitted to post themselves.
- https://gov.uniswap.org/
2. Snapshot voting to signal sentiment by voting off-chain. Votes on snapshots are weighted by the amount of UNI delegated to the address that is used to vote.
- https://snapshot.page/#/uniswap
3. Votes are cast on the governance portal, which is accessible in the Uniswap app interface.
- https://app.uniswap.org/#/vote
Phase 1: Temperature Check – Discourse / Snapshot
The purpose of the Temperature Check is to determine if there is sufficient will to make changes to the status quo.
To create a Temperature Check:
- Ask a general, non-biased question to the community on gov.uniswap.org about a potential change (example: “Should Uniswap governance add liquidity mining for XYZ token?”). Forum posts should be labeled as follows: “Temperature Check – [Your Title Here]”. The forum post should include a link to the associated Snapshot poll.
- Voters use Snapshot to indicate their interest in bringing it forward to the next stage. Snapshot poll lengths should be set to 2 days.
At the end of the 2 days, a majority vote with a 25k $UNI yes-vote threshold wins.
If the Temperature check does not suggest a change from the status quo, the topic will be closed on the governance site. If the Temperature Check does suggest a change, proceed to Stage 2: Consensus Check.
Phase 2: Consensus Check – Discourse / Snapshot
The purpose of the Consensus Check is to establish a formal discussion around a potential proposal.
To create a Consensus Check:
- Use feedback from the Temperature Check post and create a new Snapshot poll that covers the options which have gained support. This poll can either be binary or multiple choice but you are required to include the option “Make no change” or its equivalent. Set the poll duration to 5 days.
- Create a new topic in the Proposal Discussion category on gov.uniswap.org titled “Consensus Check — [Your Title Here]”. This will alert the community that this topic has already passed Temperature Check. Any topics beginning with Consensus Check that have not passed Temperature Check will immediately be removed by moderators. Make sure that the discussion thread links to the new Snapshot poll and the Temperature Check thread.
- Reach out to your network to build support for the proposal. Discuss the proposal and actively solicit delegates to vote on it. Be willing to respond to questions on the Consensus Check topic. Share your viewpoint, although try to remain as impartial as possible.
At the end of 5 days, whichever option has the majority of votes wins, and can be included in a governance proposal for Stage 3. A 50k $UNI yes-vote quorum is required for the Consensus Check to pass.
If the option “Make no change” wins, the Consensus Check topic will be closed by the moderators.
Phase 3: Governance Proposal – Governance Portal
Phase 3 — Governance Proposal — is the final step of the governance process. The proposal should be based on the winning outcome from the Consensus Check and can consist of one or multiple actions, up to a maximum of 10 actions per proposal.
To create a Governance Proposal:
- Write the code for your proposal, which will be voted on through the Governance Portal. More resources can be found here. All proposed codes should be audited by a professional auditor. This auditing process may be paid or reimbursed by the community treasury.
- Ensure that you have at least 2.5 million UNI delegated to your address in order to submit a proposal, or find someone who has enough UNI to meet the proposal threshold to propose on your behalf.
- Create a topic in the Proposal Discussion category on gov.uniswap.org titled “Governance Proposal — [Your Title Here]” and link to any relevant Snapshot polls/discussion threads as well as the code audit report. Topics that begin with “Governance Proposal” that have not successfully passed through the Temperature Check and Consensus Check stages will be removed by moderators.
- Call the propose() function of the Governor Bravo to deploy your proposal.
Once the propose() function has been called, a two-day voting delay will start. After the voting delay is finished a seven-day voting period begins. Ongoing discussion can take place in the gov.uniswap.org forum. If the proposal passes successfully, a two-day timelock will follow before the proposed code is executed.
Soft Governance
The process described above lays out a structure for those wishing to host a formal vote around a particular issue.
However, governing this system also requires a degree of “meta governance”, discussions that inform the direction of and the implementation processes behind policy but which don’t qualify as policy themselves.
The community may discuss new ideas and strategies for governance — including changes to the three-step process outlined above — in the “Governance-Meta” category. On-chain voting is not necessary to make updates to off-chain processes.
Governance Glossary
UNI: An ERC-20 token that designates the weight of a user’s voting rights. The more UNI a user has in their wallet, the more weight their delegation or vote on a proposal holds.
Delegation: UNI holders cannot vote or create proposals until they delegate their voting rights to an address. Delegation can be given to one address at a time, including the holder’s own address. Note that delegation does not lock tokens; it simply adds votes to the chosen delegation address.
Proposal: A proposal is an executable code that modifies the governance contract or treasury and how they work. In order to create a proposal, a user must have at least 0.25% (2.5M UNI) of all UNI delegated to their address. Proposals are stored in the “proposals” mapping of the Governor smart contract. All proposals are subject to a 7-day voting period. If the proposer does not maintain their vote weight balance throughout the voting period, the proposal may be canceled by anyone.
Quorum: In order for a vote to pass, it must achieve a quorum of 4% of all UNI (40M) voting in the affirmative. The purpose of the quorum is to ensure that the only measures that pass have adequate voter participation.
Voting: Users can vote for or against single proposals once they have voting rights delegated to their address. Votes can be cast while a proposal is in the “Active” state. Votes can be submitted immediately using “castVote” or submitted later with “castVoteBySig” (For more info on castVoteBySig and offline signatures, see EIP-712). If the majority of votes (and a 4% quorum of UNI) vote for a proposal, the proposal may be queued in the Timelock.
Voting Period: Once a proposal has been put forward, Uniswap community members will have a seven-day period (the Voting Period) to cast their votes.
Timelock: All governance and other administrative actions are required to sit in the Timelock for a minimum of 2 days, after which they can be implemented.
Uniswap beginners guide to voting
Adversarial Governance Circumstances
This section explores some adversarial circumstances that Uniswap Governance may encounter in the future. Its goal is to help those interested in Uniswap Governance understand the reasoning behind some of its design, its limitations, and potential avenues for growth.
Scenario 1
A good faith proposal is brought to vote but is found to have an exploitable edge case. A bad faith actor uses a series of DeFi leveraging strategies to quickly buy enough $UNI during the voting period to sway the vote in favor of the proposal, passing it and exploiting the vulnerability.
Circumvention
$UNI voting power must be delegated to an address either entirely before a proposal has been submitted or during the proposal delay period. For now, the proposal delay is set to one block, which is about 15 seconds. A proposal delay of one block leaves no opportunity for a third party to find an exploitable edge case and opportunistically purchase uni, self delegate and sway the vote.
In the future, Uniswap Governance may vote to increase the proposal delay. While there are obvious benefits to an increased proposal delay, It may introduce some potential adverse outcomes such as opportunistic edge case exploitation.
Scenario 2
A bad faith proposal is crafted and submitted to vote, which is unambiguously not in the best interest of Uniswap Governance. Multiple parties collude ahead of time to corner the $UNI market to force the proposal through, gain access to the $UNI reserves, and drain the funds.
Circumvention
Since $UNI is a freely tradable asset, anyone can attempt a governance takeover via market buying. That said, to force-pass a bad-faith vote would require a minimum of 40 million $UNI. If not outright impossible, this amount would be prohibitively expensive and likely cost more when accounting for price fluctuation than the net gain from the attack.
If a group somehow achieved a bad-faith takeover, Timelock’s delay would give affected agents time to withdraw their assets from the protocol. This would also be an opportunity to fork the protocol, a path that would likely be taken by the remaining good-faith actors.
Scenario 3
A single party uses a flash loan to push through a proposal, potentially creating a pseudo-DDOS attack by spamming governance with proposals and preventing effective use.
Circumvention
A delegated balance of 2.5 million $UNI is required to submit a vote, but the balance check is set exactly one block in the past. This prevents any flash loan proposals from being created, as flash loans cannot execute outside of a single block.
The proposer must also maintain a minimum balance of 2.5 million $UNI throughout the voting period, or anyone may cancel the proposal. This balance maintenance check prevents many highly leveraged proposal techniques that may span several blocks.
Scenario 4
A bad-faith proposal is created, which will genuinely incentivize bad-faith voting.
Example: “The treasury will be drained. Any votes in favor will be sent to the balance of the treasury. Any votes opposed will be locked from the funds of the treasury.”
Circumvention
No mechanism explicitly prevents this type of scenario, but market forces disincentivize it.
Because the treasury is comprised of $UNI tokens exclusively, the market would react appropriately if a vote were to pass that would jeopardize the economic viability of Uniswap Governance and the $UNI token. By the time the vote would pass, $UNI’s price would have fallen so low as to make the attack fruitless.
UNI acting as the only asset of the governance treasury disincentivizes this form of bad-faith voting. Uniswap Governance may choose in the future to diversify governance assets. While there are many benefits to this path, some fringe possibilities such as incentivized bad-faith voting may appear.
Risks
- Impermanent loss can affect the returns of liquidity providers when the price of the assets in the pool changes. If the prices diverge significantly, the liquidity providers may end up with less value than if they had just held the assets. This is a unique risk faced by liquidity providers in AMMs.
- Slippage and price volatility might lead to order executions at different prices than what is initially displayed to the user on screen. In case there isn’t enough liquidity in the pool when you want to trade or withdraw your assets, you may face high slippage or be unable to execute your trade.
- Regulatory risk, which is especially concerning in the event that the fee switch is activated and the protocol shares revenue with UNI holders. This might potentially make it a security.
- Smart contract risks, since they represent autonomous and self-executing code that might contain bugs or vulnerabilities that can be exploited by malicious actors.
- Front-running and MEV, where MEV searchers might observe a user’s transaction in the mempool and profit at the expense of the user with front-running or sandwich attacks.
- Sybil attack risk is due to the use of governance tokens for voting. There’s a risk that an entity could own the majority of the tokens or create multiple accounts to gain a disproportionately large influence.
Security
Audits
Uniswap V1 Audits
- Formalized Model and Code Spec – October 24, 2018 – Yi Zhang, Xiaohong Chen, Daejun Park
- High-level code review – RV
Uniswap V2 Audits
- Uniswap V2 Audit Report – dapp.org
- Medium – 2
- Low – 1
- Improvement – 7
Uniswap V3 Audits
- Uniswap V3 Core Security Assessment – March 12, 2021 – Trail of Bits
- High – 2
- Medium – 4
- Low – 1
- Informational 3
- Smart Contract Audit – 23 March 2021 – abdk.consulting
- No critical bugs were found except for a few moderate issues.
- Most of them were eventually downgraded to minor ones.
- A full audit from Samczsun, no report available.
- An auditing and review process from the engineering team.
- A comprehensive test suite, including the automated tools Echidna and Manticore
UniswapX Audits
- Smart Contract Audit – July 17, 2023 – ABDK Consulting
- Major – 14 (7 Fixed, 7 Active)
- Moderate – 5 (2 Fixed, 3 Active)
- Minor – 75 (31 Fixed, 44 Active)
Bug Bounty
Uniswap also has a bug bounty program.
Rewards will be allocated based on the severity of the bug disclosed and evaluated for rewards up to 2,250,000 USDC.
The Program includes the following 4-level severity scale:
- Critical Issues that could impact numerous users and have serious reputational, legal, or financial implications. An example would be being able to lock contracts permanently or take funds from all users.
- High Issues that impact individual users where exploitation would pose a reputational, legal, or moderate financial risk to the user.
- Medium, the risk is relatively small and does not pose a threat to user funds.
- Low/Informational, the issue does not pose an immediate risk but is relevant to security best practices.
Rewards will be given based on the above severity as well as the likelihood of the bug being triggered or exploited, to be determined at the sole discretion of Uniswap Labs. You can find out more about this scale on the OWASP risk rating methodology page.
Dependencies and Access Controls
None of the core contract operations can be halted by the UNI-controlled factory contract, which minimizes the impact of potential governance attacks. The protocol has a permissionless and immutable design, which means that the protocol’s services are entirely open for public use, with no ability to selectively restrict who can or cannot use them. Anyone can swap, provide liquidity, or create new markets at will.
The protocol contracts being immutable means that no party is able to pause the contracts, reverse trade execution, or otherwise change the behavior of the protocol in any way.
Like v2, the v3 protocol fee can be turned on via governance. In v3, each pool has a parameter that can be set for % of swap fees that are allocated to the protocol, ¼, ⅕, ⅙, …etc. up to 1/10. Governance can add new fee tiers, add new price ranges to curves, and transfer ownership to a new address.
Liquidity Risk
Impermanent Loss in Uniswap V2
Liquidity providers may experience impermanent loss when the relative price of tokens in the pool diverges from the initial deposit ratio. Impermanent loss occurs when liquidity providers (LPs) deposit assets into a liquidity pool and the relative price of the tokens in the pool changes compared to when they were initially deposited. This results in a temporary loss in value for the LPs compared to just holding the tokens in their original form. It’s called “impermanent” because the loss can be minimized or reversed if the token prices return to their original ratio.
Impermanent loss is a direct consequence of the constant product formula (x * y = k) used by Uniswap’s AMM model to maintain liquidity pools. When token prices change, the AMM adjusts the token ratio in the pool to maintain the constant product (k). This adjustment causes the value of the LP’s share of the pool to deviate from the value of the original deposit.
Consider an example where an LP deposits 100 $ETH and 10,000 $USDC (assuming an initial price of 1 $ETH = 100 $USDC) into a Uniswap liquidity pool. If the price of $ETH doubles to 200 $USDC, the AMM adjusts the ratio in the pool to maintain the constant product. In this scenario, the pool might now contain 66.67 $ETH and 15,000 $USDC.
If the LP decides to withdraw its share from the pool at this point, it would receive fewer $ETH and more $USDC than its initial deposit. While the overall value in USD may be similar, the LP has experienced an impermanent loss due to the opportunity cost of holding fewer $ETH, which appreciated in value.
LPs can mitigate impermanent loss by closely monitoring the market conditions and being prepared to withdraw their liquidity when the token prices approach their original ratio. Additionally, liquidity providers can consider focusing on pools with more stable and less volatile tokens, reducing the likelihood of significant price fluctuations and subsequent impermanent loss.
Impermanent Loss in Uniswap V3
Impermanent loss (IL) essentially functions the same in V3 with the exception of being amplified due to it being concentrated.
Using the example given in V2, IL is accumulated during any price movement as the V2 pool rebalances itself, while still staying in range and earning fees as the LP encompasses the “entire range”, regardless of if $ETH goes to $1 or $10,000.
In the picture shown, the range of this V3 position is set from a minimum price of $1747.7 per ETH to a maximum of $2612.4 per ETH.
In a V3 position, the range is concentrated according to the user’s choice. In this case, if the ETH price increases to $2615, which is outside of the maximum range, the LP will shift entirely to being fully composed of $USDC and becomes out of range where it does not earn any fees at all. In this case, impermanent loss comprises the user losing out on further price value compared to just holding ETH on its own.
V3 LPs can attempt to mitigate IL by making use of active management or delegating it to automated strategies from dedicated protocols. It is important to note that, unlike the case of V2, rebalancing V3 pools is essentially the same as realizing the IL.
Team
Uniswap was founded in November 2018 by Hayden Adams, who previously worked as a mechanical engineer at Siemens.
According to LinkedIn, there are currently 130 employees at Uniswap Labs. Some of them include:
- Hayden Adams, Founder & CEO
- Previously an Engineer at Siemens.
- B. Salman Banaei, Head of Policy
- Previously Co-Head of Public Policy at Chainalysis Inc and Commodities & Derivatives Law Subject Matter expert and lecturer at the University of Colorado Denver Business School.
- Marvin Ammori, Chief Legal Officer
- Previously Volunteered at Biden-Harris Innovation Policy Committee and General Counsel at Protocol Labs.
- Mary-Catherine Lader, Chief Operating officer
- Previously Term Member at Council on Foreign Relations and Managing Director & Global Head of Aladdin Sustainability at BlackRock.
- Sarina Siddhanti, Head of Growth
- Builder at OrangeDAO.
- Scott Gray, Head of NFT Product
- Founder of Genie.
- Will Ruben, VP, of Product
- Previously Senior Direct, Product Management at Coinbase and Director of Product Management, Feed & Relevance at Instagram.
- Padmini Pyapali, Director of Engineering
- Previously Operator Network at January Ventures.
- Matteo Leibowitz, Ventures Lead
- Previously Research Analyst at The Block.
- Andrew MacPherson, Staff Security Engineer
- Previously Review board member at Black Hat and Staff Security Engineer at Robinhood.
Project Investors
Uniswap started development with funding from an Ethereum foundation grant and has raised $176M through a seed round and two funding rounds.
- Ethereum Foundation Grant (August 17, 2018)
- $100k for DEX framework.
- Seed Round (April 24, 2019)
- Although the final amount was not disclosed, Paradigm was stated to have been looking to raise over $1M.
- Series A Round (August 6, 2020)
- $11M raised, led by Andreessen Horowitz.
- Participants include USV, Paradigm, Version One, Variant, Parafi Capital, SV Angel, and A.Capital.
- Series B Round (October 13, 2022)
- $165M raised, led by Polychain Capital.
- Participants include a16z crypto, Paradigm, SV Angel, and Variant.
Additional Information
Resources
- Uniswap V2 Visualization
- Uniswap V3 Visualization
- Uniswap V3 (Multiple Positions) Visualization
- V2 / V3 Calculations
- Uniswap calculator for LPs
- Impermanent loss calculator
- Sandwich attacks on Uniswap V2
- Uniswap V3 impermanent loss calculator
- Uniswap V3 fees calculator
- Uniswap V3 strategy simulator
- Insights for Uniswap V3 positions
Glossary
Automated Market Maker
An automated market maker is a smart contract on Ethereum that holds liquidity reserves. Users can trade against these reserves at prices determined by a fixed formula. Anyone may contribute liquidity to these smart contracts, earning pro-rata trading fees in return.
Asset
While a digital asset can take many forms, the Uniswap Protocol supports ERC-20 token pairs and represents a position in the form of an NFT (ERC-721).
Concentrated Liquidity
Liquidity that is allocated within a determined price range.
Constant Product Formula
The automated market-making algorithm used by Uniswap. In v1 and v2, this was x*y=k.
Core
These are smart contracts that are considered foundational and essential for Uniswap to exist. Upgrading to a new version of the core would require deploying an entirely new set of smart contracts on Ethereum and would be considered a new version of the Uniswap Protocol.
ERC20
ERC20 tokens are fungible tokens on Ethereum. Uniswap supports all standard ERC20 implementations.
Factory
A smart contract that deploys a unique smart contract for any ERC20/ERC20 trading pair.
Flash Swap
A trade that uses the tokens purchased before paying for them.
Invariant
The “k” value in the constant product formula X*Y=K
Liquidity Provider / “LP”
A liquidity provider is someone who deposits ERC20 tokens into a given liquidity pool. Liquidity providers take on price risk and are compensated with trading fees.
Liquidity
Digital assets that are stored in a Uniswap pool contract, and are able to be traded against by traders.
Mid Price
The price between the available buy and sell prices. In Uniswap V1 and V2, this is the ratio of the two ERC20 token reserves. In V3, this is the ratio of the two ERC20 token reserves available within the current active tick.
Observation
An instance of historical price and liquidity data of a given pair.
Pair
A smart contract deployed from a Uniswap V1 or V2 factory contract that enables trading between two ERC20 tokens. Pair contracts are now called Pools in V3.
Periphery
External smart contracts that are useful, but not required for Uniswap to exist. New periphery contracts can always be deployed without migrating liquidity.
Pool
A contract deployed by the V3 factory that pairs two ERC-20 assets. Different pools may have different fees despite containing the same token pair. Pools were previously called Pairs before the introduction of multiple fee options.
Position
An instance of liquidity is defined by upper and lower tick. And the amount of liquidity contained therein.
Price Impact
The difference between the mid-price and the execution price of a trade.
Protocol Fees
Fees that are rewarded to the protocol itself, rather than to liquidity providers.
Range
Any interval between two ticks of any distance.
Range Order
An approximation of a limit order, in which a single asset is provided as liquidity across a specified range, and is continuously swapped to the destination address as the spot price crosses the range.
Reserves
The liquidity available within a pair. This was more commonly referenced before concentrated liquidity was introduced.
Slippage
The amount the price moves in a trading pair between when a transaction is submitted and when it is executed.
Spot Price
The current price of a token relative to another within a given pair.
Swap Fees
The fees collected upon swapping are rewarded to liquidity providers.
Tick Interval
The price space between the two nearest ticks.
Tick
The boundaries between discrete areas in price space.
FAQ
Swapping tokens
What is the Uniswap tokens page?
- The tokens page allows you to discover and evaluate ERC-20 tokens to make informed decisions when buying or selling a token on Ethereum and supported Layer 2 networks.
- Using the Tokens page you can view:
- Token name and icon.
- Token price with real-time data.
- Token price with historical data.
- Token volume on Uniswap.
- Total value locked (TVL).
What are token warnings?
- You may see either red or yellow Token Warnings while swapping and navigating throughout the site. These warnings are to alert you to the potentially heightened risk in trading these tokens.
- Token Warnings are available for Ethereum (ERC-20) tokens and supported Layer 2 tokens.
- Labels include:
- No warning – Any token that has been listed by a US-based centralized exchange, such as Coinbase, Kraken, or Gemini. In very rare cases, a token is separately reviewed and approved by Uniswap Labs (e.g., Unisocks, Euro Coin).
- Caution – Any token that is frequently swapped on Uniswap (and has satisfied other basic quantitative criteria) but is not traded on a leading U.S. centralized exchange. We plan to update these criteria over time.
- Warning – Any token that is not frequently swapped on Uniswap (and has not satisfied other basic quantitative criteria) and is also not traded on a leading U.S. centralized exchange.
- Not available – Manually curated by Uniswap Labs to block tokens that violate trademarks, that have proven to be scams, or otherwise based on legal considerations.
Price Impact vs. Price Slippage
- Price Impact – The change in token price directly caused by your trade. Price Impact is reflected as the difference between the current market price and how your trade impacts the total liquidity in a pool.
- Price Slippage – The change in token price caused by the total movement of the entire current market. Price Slippage is reflected as the difference between the price you expect to receive after swapping vs what you actually receive after the swap is complete.
My transaction has been pending for a long time. What can I do?
- If your Uniswap transaction has been pending for a long time, you have three available options.
- Wait — the Uniswap interface has a default transaction deadline setting of 20 minutes, after which the transaction will automatically fail. Once the transaction has failed, you can resubmit your transaction.
- Speed up — wallets can offer users the ability to speed up their transactions by re-submitting them with a higher gas price. This is not necessarily guaranteed to work. (Metamask guide)
- Cancel — wallets can also offer users the ability to cancel their transactions by submitting an ‘empty’ transaction with a higher gas price. This is not necessarily guaranteed to work.
- Note that all three options will have an associated transaction fee.
Uniswap Wallet
How to create a new wallet in the Uniswap Wallet
- When using the Uniswap Wallet, you can have more than one wallet available to you to swap or view in the app. However, the Uniswap Wallet can only store one recovery phrase at a time.
- How to create a new wallet in the Uniswap Wallet with the same recovery phrase:
- Open the wallet selection menu.
- Select “Add Wallet”.
- Select “Create a new wallet”.
How to add a view-only wallet
- A view-only wallet is a great way to follow a wallet that has a different recovery phrase. You can follow the wallet’s transactions, and view the tokens and NFTs held.
- To add a view-only wallet, follow these steps:
- Open the wallet selection menu. Next, select “Add Wallet”, then “Add a view-only wallet.”
- Enter the wallet address you would like to view, then select “Continue”
- Confirm the wallet has been added.
How to send funds from an exchange to Uniswap Wallet
- With the release of the Uniswap Wallet, you can now send tokens from a centralized exchange to your Uniswap Wallet.
- There are two ways you can do this:
- The “send” feature in your centralized exchange account/wallet
- If you have a Coinbase wallet, here are the instructions for sending tokens to another wallet.
- Please note if you are using Binance, the Uniswap Wallet does not currently support tokens on the BNB chain. You will not be able to view or interact with tokens on the BNB Chain when using the Uniswap Wallet app.
- The “receive” feature in your Uniswap Wallet
- Press “receive”
- Select to copy the wallet address
- Once you see “copied to clipboard”, this means the wallet address is now ready to be pasted
- Paste your Uniswap Wallet address when you are prompted from the account/wallet you are sending from
- We recommend checking the last four digits of your wallet address to ensure you are sending it to the correct address. Transactions on the blockchain are permanent and cannot be reversed.
How to backup your recovery phrase manually
- Your recovery phrase is the master password that grants access to your crypto wallet.
- Since you are the only one in control of your wallet, keeping your recovery phrase safe is up to you. Losing this phrase results in losing access to your wallet and the assets inside.
- You can choose to back up your recovery phrase on iCloud, or you can back it up manually.
- How to back up recovery phrases manually in the Uniswap Wallet:
- Select the “Settings” icon.
- Select your wallet, then select “Recovery Phrase.”
- Select “View phrase” and write down your recovery phrase.
How to export my recovery phrase from the Uniswap Wallet
- Before exporting your recovery phrase, make sure you are in a safe and private location. No one should be able to see your recovery phrase.
- How to export my recovery phrase from the Uniswap Wallet:
- Select the “Settings” icon. Next, select your wallet, then select “Recovery Phrase.”
- Select “View phrase” and write down your recovery phrase. Select “Hide your recovery phrase” when you’re done.
Providing Liquidity
What is a liquidity pool?
- A liquidity pool is a group of tokens that are locked in a smart contract and used for trading between assets on a decentralized exchange (DEX) like Uniswap.
- In traditional finance, liquidity is organized using a central limit order book where buyers and sellers create orders (trade) organized by price and demand.
- The Uniswap Protocol takes a different approach, using an Automatic Market Maker (AMM) to replace the traditional order book method with a liquidity pool of two assets, where the price is determined by an AMM.
- These pooled tokens are provided by liquidity providers (LPs) who receive an LP token in exchange for providing liquidity.
- The Uniswap Protocol AMM sets prices for liquidity pools using the mathematical formula x*y=k.
- Prices are determined by the amount of each token in a pool, with x and y representing the two tokens in a liquidity pool. You can read more about this here: How are prices determined?
- It is important to evaluate the liquidity available in a pool before swapping. A pool with low liquidity will not give you an optimal price, and could potentially result in a loss.
- To evaluate the liquidity available in a liquidity pool, visit here and search for the pool or token you would like to swap.
Why is my LP deposit not a 50/50 split between the two tokens?
- This occurs when your price range is not balanced 50/50 around the market price.
- In many cases, it is not possible to balance exactly 50/50 due to the logarithmic spacing between price ticks. Generally, if the ratio is close to 50/50, there is no reason to worry.
- Under the hood, the Uniswap v3 protocol divides prices up into discrete intervals known as ‘ticks’. These ticks use logarithmic space.
- The size of the tick is a function of the fee tier — generally, the tick is double the size of the fee tier (e.g. a tick for a 0.30% fee tier pool will be 0.60% in size and there will be a tick every price 1.006^n where n is an integer and price is the relative price between token0 and token1).
- In order to deposit at 50/50 values, a user has to find two ticks that are equidistant (in log space) from the current price: as an example, if the current price of an asset is 1,000, a 50/50 deposit with a +/- 10% range would require prices at 900 and 1,100. However, there may not be ticks at exactly 900 and 1,100, which produces an even deposit value.
Do I get “liquidated” if the price goes outside of my range?
- No — there are no liquidations in Uniswap v3.
- If the price goes outside of your LP position price range, then your position will be singularly concentrated in the less valuable asset.
- As an example, if a price range of 1,000 — 5,000 for $ETH/$USDC and $ETH falls to 900, then your balance will be entirely concentrated in $ETH. Conversely, if $ETH appreciates to 6,000, then your balance will be entirely concentrated in $USDC.
- While the price remains outside of your price range, your position will be “inactive”. This means your position will not earn fees until when the price comes back in range.
- For a visual explanation, please see the examples in this blog post.
Why does the price input automatically round to a seemingly random number?
- When providing liquidity, your input min and max price will always automatically round to the nearest tick.
- Under the hood, the Uniswap v3 protocol divides prices up into discrete intervals known as ‘ticks’. These ticks use logarithmic space.
- The size of the tick is a function of the fee tier — generally, the tick is double the size of the fee tier (e.g. a tick for a 0.30% fee tier pool will be 0.60% in size and there will be a tick every price 1.006^n where n is an integer and price is the relative price between token0 and token1).
- As an example, take an LP that wishes to deposit into the $ETH/$USDC pool with a 0.30% fee tier. The LP would like to provide liquidity within a range of 1,000 to 5,000.
- The nearest available ticks in this instance are 1,155 (1.006^1155 = 1,001.538) and 1,424 (1.006^1424 = 5,006.388), so the LPs price inputs will be automatically rounded to 1,001.538 and 5,006.388.
Can I provide liquidity over the full range of V3?
- Yes, you can provide liquidity over the full price range like in Uniswap v2, but your rate of return will be significantly lower than a similar position with a more narrow price range.
Uniswap V2 vs Uniswap V3
The major upgrade is the introduction of range-bound liquidity, which enables the following:
- More fees for liquidity providers with less liquidity
- Reduced risk for liquidity providers
- Deeper liquidity for swappers.
LPs can earn more swap fees by concentrating the liquidity in the areas where swaps are more likely to occur. Previously, LP positions spanned the entire xy=k curve and provided liquidity across that whole curve. As a result, to collect fees from a small range of price action, they had to provide liquidity for the entire curve.
With V3, liquidity providers now require less capital to provide the same amount of liquidity for only a certain range – and collect fees from that range.
By only providing liquidity in a specific price range, liquidity providers can avoid being exposed to extreme price movements that occur outside of that range. This way, liquidity providers can protect themselves from impermanent loss when the supply of tokens in the pool diverges outside of their position range. However, since impermanent loss can be significantly worse than in V2 in some cases, Uniswap V3 introduces fee tiers. This allows LPs to hedge their losses by taking a higher percentage of fees from more volatile pairs.
Ticks are simply discrete marks that break up the xy=k curve into granular sections that can be used for LPs to determine the price ranges where they want to provide liquidity.
Every tick is determined by the following equation:
By this definition, a tick is a representation of the power that you must raise 1 and 1 basis point (0.01%) to in order to get P, which is the price.
This can be rewritten as:
Using this formula it is possible to divide up the entire xy=k curve into discrete ticks that are 1 basis point percentage (1.0001) away from each other.
Knowing the current tick, the price can be computed. For instance, if the current tick in the $ETH/$USDC pool is 200957, then the tick is going to give us the price of $USDC in terms of $ETH.
This represents the amount of $ETH that the user gets for 1 $USDC (note that $ETH has 18 decimals of precision).
When this is inverted, we can obtain the amount of $USDC for 1 $ETH.
Since USDC has 6 decimals of precision, that gives a price of $1,874.92
The result above is not the exact market price. The reason for that is that the price of the pools is not directly derived from a particular tick. Instead, the actual price of the pool is somewhere between the current tick and the next tick.
Community Links
- Website: https://app.uniswap.org/#/?intro=true
- Analytics: https://info.uniswap.org/#/
- Help Centre: https://support.uniswap.org/hc/en-us
- Documentation: https://docs.uniswap.org/
- Github: https://github.com/Uniswap
- Discord: https://discord.com/invite/FCfyBSbCU5
- Twitter: https://twitter.com/Uniswap
- Reddit: https://www.reddit.com/r/UniSwap/
- Blog: https://blog.uniswap.org/
- Jobs: https://boards.greenhouse.io/uniswaplabs
- Uniswap Foundation: https://www.uniswapfoundation.org/
- CoinGecko: https://www.coingecko.com/en/coins/uniswap
- Smart Contracts: https://docs.uniswap.org/contracts/v3/overview
Revision History
Version 0.0 | May. 24, 2023 – Initial Release
Version 0.1 | Jun. 02, 2023 – Dynamic Hedging
Version 0.2 | Jun. 26, 2023 – Uniswap V4
Version 0.3 | July. 18, 2023 – Added UniswapX, Audit
Version 0.4 | October 10, 2023 – Updated strategies, uniswapx, uniswap v4