Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
This article explores the official Uniswap V2 documentation with supplementary explanations.
The official documentation is available below.
This article focuses on concepts rather than detailed technical implementation.
Overview
Uniswap V2 is the second version of the decentralized exchange protocol. Its documentation covers the protocol's concepts and technical design.
The whitepaper is available below.
https://docs.uniswap.org/whitepaper.pdf
For developers, the protocol is organized into two repositories.
uniswap-v2-core
uniswap-v2-periphery
SDKs are also available to help developers integrate with Uniswap V2.
uniswap-sdk
uniswap-sdk-core
Concepts
Protocol overview
How Uniswap works
Source: https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/how-uniswap-works
Uniswap is an automated liquidity protocol based on a constant-product formula, implemented through a system of non-upgradeable smart contracts on Ethereum. It removes the need for a trusted intermediary for swaps and prioritizes decentralization, censorship resistance, and security. The protocol is available as open-source software under the GPL.
For background on the GPL, see the following source.
The GPL is known for its copyleft licensing requirements. It is used by WordPress and many other software projects. Copyleft, associated with Richard Stallman, protects users' rights to use, modify, and redistribute software by requiring covered derivative works to preserve those freedoms under applicable license conditions.
Each Uniswap pair contract manages a liquidity pool holding reserves of two ERC20 tokens.
Reserves are the recorded quantities of tokens in the pool.
Anyone can become a liquidity provider (LP) by depositing the two tokens in the appropriate reserve ratio in exchange for pool tokens. The provider receives an LP share proportional to the contribution and can redeem pool tokens for the corresponding share of the current reserves.
An LP share represents a liquidity provider's proportional interest in the pool. It measures the provider's ownership share of the pool's total reserves.
Source: https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/how-uniswap-works
A Uniswap pair acts as an automated market maker. One token can be exchanged for the other subject to the constant-product invariant, accounting for swap fees.
Ignoring fees, the simplified formula x * y = k requires the product of the reserve quantities to remain constant across a swap.
The product k is therefore called the invariant in this simplified model.
Larger trades relative to pool reserves execute at increasingly unfavorable average rates because of the nonlinear pricing curve.
In the V2 design, swaps incur a 0.30% fee that remains in the reserves.
As a result, the reserve product generally increases with each fee-paying swap.
These fees accrue to liquidity providers, who realize their share by burning pool tokens and withdrawing a proportion of the reserves.
The historical design also allows an optional protocol fee equivalent to 0.05% of trade volume, reducing the effective LP share of the 0.30% swap fee to 0.25%.
In short, Uniswap pairs operate as automated market makers based on a constant-product invariant. Swap fees accrue to the pool and compensate LPs under the applicable protocol-fee configuration. The distribution of fees can depend on the protocol-fee setting.
Consider the following constant-product calculation, ignoring fees. The reserve quantities in the original example need to be distinguished from the quantities traded.
- A user supplies tokens X and Y.
Token X reserve (
x):2units Token Y reserve (y):25units
k = x * y = 2 * 25 = 50The initial marginal reserve price is 12.5 token Y per token X. The original claim that one X exchanges for 25 Y is incorrect.
- Withdraw one token X and supply token Y, moving from the initial reserves.
Token X reserve (x): 1 unit
Token Y reserve (y): 50 units (correcting the original 25-unit label to match the calculation below)
k = x * y = 1 * 50 = 50The new marginal price is 50 Y per X; the trade withdraws 1 X in exchange for 25 Y before fees.
- In a separate example starting from the initial reserves, withdraw five token Y and supply token X.
Token X reserve (x): 2.5 units
Token Y reserve (y): 20 units
k = x * y = 2.5 * 20 = 50The new marginal price is 8 Y per X. This trade supplies 0.5 X to withdraw 5 Y before fees.
Source: https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/how-uniswap-works
Because token exchanges occur within liquidity pools, the price of a token pair changes as swaps alter its reserves. When a Uniswap price diverges from external market prices, arbitrage opportunities can arise. Arbitrage tends to move the pool price toward the prevailing market price.
To learn more about token exchanges and the swap lifecycle, see Swaps. For more about liquidity pools, see Pools.
Uniswap operates through smart contract code executed on Ethereum. These contracts automate swaps and liquidity management. See Smart Contracts for implementation details.
Uniswap's reserve-based prices change through trading, with arbitrage helping bring them toward market prices. This mechanism encourages alignment between pool prices and external markets, although differences can persist.
Ecosystem participants
Source: https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/ecosystem-participants
The Uniswap ecosystem has three principal participant groups.
- Liquidity providers.
- Traders.
- Developers.
Liquidity providers contribute ERC20 tokens to shared liquidity pools.
Traders can exchange these tokens for a fixed 0.30% swap fee, which accrues to liquidity providers subject to the protocol-fee configuration.
Developers can integrate directly with Uniswap contracts to build token integrations, trading interfaces, and other user experiences.
Interactions between these groups can reinforce the ecosystem by establishing shared mechanisms for pooling, trading, and using tokens.
This creates opportunities for continued ecosystem development.
Liquidity providers
Liquidity providers are not a homogeneous group. Different types of LPs have different objectives and approaches.
Passive LPs Token holders seeking income from their assets. They aim to accumulate trading fees by providing liquidity.
Professional LPs Participants who specialize in market-making strategies. They often develop custom tools and methods to manage liquidity positions across DeFi projects.
Token projects Some token projects choose to provide liquidity for their own tokens. This can facilitate trading and integration with other DeFi projects through Uniswap.
DeFi pioneers Some explore more complex strategies, such as incentivized liquidity provision or using liquidity positions as collateral. Uniswap provides an open protocol on which such ideas can be explored.
Different LP groups contribute to available liquidity and market operation. Together, they help make token trading and use possible within the ecosystem.
Traders
Several types of traders participate in the Uniswap ecosystem. They use the protocol in different ways.
Speculators Speculators use available liquidity to exchange tokens. They use community-built tools and products to pursue opportunities arising from changes in token prices.
Arbitrage bots Arbitrage bots seek opportunities arising from price differences between platforms. They exploit differences in market prices. This activity can help align prices across Ethereum markets.
DApp users DApp users acquire tokens through Uniswap for use in other Ethereum applications. This makes it easier to obtain assets required by those applications.
Smart contracts Smart contracts can execute swaps through Uniswap. Examples include DEX aggregators and custom Solidity integrations. They enable automated token exchanges within broader on-chain workflows.
V2 charges the same pool-level swap fee rate regardless of trader type, creating incentives for liquidity provision. Together with arbitrage, this supports token exchange and market pricing.
Developers and projects
Uniswap is integrated in many ways throughout the Ethereum ecosystem. Examples include the following.
Open-source and permissionless design Uniswap's open-source, accessible design enables independent interfaces and user experiences. Many DeFi dashboards integrate Uniswap functionality. The community also develops tools specifically for Uniswap.
Wallets Many wallets integrate token swaps and liquidity-management features. Users can access Uniswap through wallet interfaces to exchange tokens or provide liquidity.
DEX aggregators Aggregators access several liquidity protocols to seek favorable execution prices for traders. They may split trades among liquidity sources; Uniswap has historically been an important decentralized liquidity source for these integrations.
Smart contract developers Developers use available functions to build DeFi tools and experimental applications. Unisocks and Zora are examples of projects that have explored such ideas.
The Uniswap team and community
The team and broader community contribute to protocol and ecosystem development. Their work supports Uniswap's evolution.
Smart contracts
Uniswap V2 separates its smart contract system into core and periphery. Core contracts enforce fundamental invariants for parties interacting with Uniswap. Periphery contracts interact with core contracts but are not themselves part of the core.
Core The core consists of a singleton factory and multiple pairs. The factory creates and indexes pairs. These contracts are deliberately minimal. Smaller, simpler contracts can be easier to reason about and review. One benefit is that important system invariants are enforced directly in the code. The trade-off is that core contracts are not designed primarily for user convenience. Direct interaction with them is generally not recommended for common use cases. Use an appropriate periphery contract instead.
-
Factory.
- The factory contains the bytecode needed to create pairs.
- Its primary role is to deploy a single pair contract per unique unordered token pair.
- It also contains the configuration for enabling the optional protocol fee.
-
Pair.
- A pair acts as an automated market maker and tracks balances of liquidity tokens.
- It also exposes data that can be used to construct decentralized price oracles.
Periphery The periphery consists of contracts facilitating interactions between the core and particular applications. Because Uniswap is permissionless, the following contracts have no special core privileges and represent only some possible periphery implementations. They illustrate convenient and safe approaches to interacting with Uniswap V2.
- Library.
- Provides helper functions for retrieving data and calculating amounts or prices.
- Router.
- Uses the library to support trading and liquidity-management operations commonly required by frontends.
- Supports multihop trades, native ETH handling through WETH, and signed permits for removing liquidity.
Design decisions The following describes important Uniswap V2 design decisions. Readers can skip this section unless they want a deeper understanding of V2 or plan to integrate its smart contracts.
- Sending tokens.
- Contracts requiring tokens commonly use an ERC20 allowance and then call
transferFromon the token contract. - V2 pairs accept tokens differently.
- The pair compares actual token balances with stored reserves, taking account of outputs where applicable, to determine the amounts supplied.
- See the whitepaper for details.
- Contracts requiring tokens commonly use an ERC20 allowance and then call
- WETH
- Unlike Uniswap V1, V2 pairs do not directly support native ETH; ETH-to-ERC20 pairs are represented using WETH.
- This removes ETH-specific logic from the core and keeps it simpler.
- Periphery contracts wrap and unwrap ETH so users can interact without managing this detail themselves.
- Minimum liquidity.
- During the initial liquidity provision,
MINIMUM_LIQUIDITYpool-token units are permanently locked at the zero address to reduce susceptibility to liquidity-share inflation and granularity problems, rather than to adjust a V3-style tick size. - This imposes a minimum permanently locked supply of LP tokens.
- The locked amount is negligible for many pools.
- The locking occurs automatically at initial liquidity provision, establishing a permanent lower bound on the pool-token supply.
- During the initial liquidity provision,
Glossary
Automated market maker An automated market maker is a smart contract maintaining on-chain liquidity reserves. Users trade against these reserves at prices determined by the market-making formula.
Constant-product formula The automated market-making algorithm used by Uniswap V2.
ERC20 ERC20 tokens are fungible tokens on Ethereum. Uniswap supports standard ERC20 token interactions, with some token behaviors requiring special handling.
For more about ERC20, see the following resource.
Factory A smart contract deploying a separate pair contract for each ERC20/ERC20 trading pair.
Pair A contract deployed by the Uniswap V2 factory that enables trading between two ERC20 tokens.
Pool Liquidity in a pair is pooled among its liquidity providers.
Liquidity provider / LP An LP supplies two ERC20 tokens to a pool in the appropriate ratio. LPs assume price-related risks and earn a share of trading fees.
Mid price The marginal price at a given moment, before accounting for the effect of a particular trade. In Uniswap V2, it is derived from the ratio of the two reserves.
Price impact The difference between a trade's execution price and the mid price.
Slippage The change between an expected trade price and the actual execution price due to changes before execution.
Core The smart contracts essential to Uniswap's operation. Moving to a new core version requires migration of liquidity.
Periphery External smart contracts that assist interaction with the core. New periphery contracts can be deployed without migrating liquidity.
Flash swap A swap that delivers output tokens before the corresponding payment is settled within the same transaction.
x * y = k The constant-product formula.
Invariant
The value k in the constant-product formula.
Core concepts
Swaps
Source: https://docs.uniswap.org/contracts/v2/concepts/core-concepts/swaps
Uniswap token swaps exchange one ERC20 token for another.
For users, the process is straightforward. The user selects the input and output tokens and specifies an input amount. An integration estimates the output amount. When the user authorizes and submits the swap, a successful transaction delivers the output tokens to the recipient.
This guide examines the protocol-level behavior of swaps.
Uniswap swaps differ from trading on conventional order-book platforms. The protocol does not use an order book to represent liquidity and prices. Instead, an automated market-making mechanism allows integrations to calculate rates and price impact.
As described in the overview, each pair is backed by a liquidity pool. The pool contract holds balances of two distinct tokens and enforces rules governing deposits and withdrawals.
The central rule is the constant-product invariant. When one token is withdrawn, sufficient input must be supplied to satisfy the fee-adjusted invariant.
Anatomy of a swap
At the core level, Uniswap V2 swaps use the swap function.
Its signature is shown below.
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data);Receiving tokens
The swap caller specifies the requested output quantities through the amount{0,1}Out parameters.
These correspond to the desired amounts of token{0,1}.
Sending tokens
How the pair receives payment for a swap is less obvious.
A contract using ERC20 tokens commonly requires an approval and calls transferFrom to obtain them.
V2 pairs do not use that model directly.
Instead, the pair checks its token balances when executing the operation.
It compares the actual balances, adjusted for requested outputs, with the stored reserves to determine the input amounts.
See the whitepaper for more details.
For ordinary swaps, transfer the input tokens to the pair before invoking its swap function; flash swaps allow payment within the callback.
To perform the ordinary transfer and swap atomically, use a router or another suitable smart contract.
Transferring tokens to the pair in a separate transaction before calling swap is unsafe because others may exploit the unaccounted-for balance.
Pools
Source: https://docs.uniswap.org/contracts/v2/concepts/core-concepts/pools
Introduction
Each Uniswap liquidity pool provides a market for a pair of ERC20 tokens. When a pair contract is created, its recorded reserves start at zero. Before trading can begin, liquidity providers must supply both tokens. The first liquidity provider establishes the initial reserve ratio and thus the initial marginal price. There is an incentive to deposit the tokens at approximately equal external market values. A ratio differing from the prevailing market rate creates an immediate arbitrage opportunity at the initial provider's expense.
Subsequent liquidity providers should add tokens in proportion to the existing reserves. A disproportionate contribution may create value that others can capture through trading. If providers believe the pool price is incorrect, they can trade to adjust the ratio before adding liquidity at the new price.
Pool tokens
Source: https://docs.uniswap.org/contracts/v2/concepts/core-concepts/pools
When liquidity is supplied, the pair mints fungible liquidity tokens to the designated recipient.
These tokens represent the holder's share of the pool.
The quantity of liquidity tokens minted depends on the contribution relative to existing liquidity.
For initial liquidity amounts x and y, the initial supply is based on sqrt(x * y), with MINIMUM_LIQUIDITY units permanently locked rather than delivered to the provider.
Each swap incurs a 0.3% fee.
Fees remain in the reserves, benefiting LPs proportionally to their shares, subject to any enabled protocol fee.
To withdraw their share of reserves and accrued fees, LPs burn their liquidity tokens. The redemption returns a proportional share of the current reserves.
Liquidity tokens are transferable assets and can be sold, transferred, or used in other integrations.
Why use pools?
Uniswap does not rely on an order book to derive prices or match buyers and sellers. Instead, it uses liquidity pools.
Traditional order books represent liquidity as discrete orders submitted by participants. Market makers generally need to manage orders actively and update them in response to market activity.
Order books are fundamental financial mechanisms suitable for many use cases, but have trade-offs. These are especially relevant in decentralized or blockchain-native environments. Traditional order books may require infrastructure to host and match orders. Such infrastructure can introduce additional complexity and points of control. Active order management may also require specialized market-making expertise. The traditional order-book model may be less suitable for an ecosystem where anyone can create new tokens and many tokens have limited liquidity. Given Ethereum's infrastructure trade-offs, an automated liquidity protocol offers a different approach to blockchain-native trading. Uniswap uses Ethereum's strengths to reconsider how token exchanges are implemented.
Blockchain-native liquidity protocols can benefit from deterministic code execution, persistent shared state, and open access that allows new assets and applications to emerge.
A pool is a smart contract whose behavior is triggered through calls.
Token swaps execute by calling swap on the pair.
Liquidity provision transfers the tokens and calls the pair's mint function, commonly through the router's addLiquidity interface; the original reference to deposit is not a V2 pair function.
Just as users access Uniswap through interfaces, developers can integrate its contracts directly without requiring authorization from an intermediary.
Flash swaps
A Uniswap flash swap allows a caller to withdraw tokens up to the pool's available liquidity, subject to the pair's output and settlement constraints, and perform other logic before paying for them. The transaction must satisfy the required settlement conditions before the swap completes.
- Pay for the withdrawn ERC20 tokens using the corresponding paired token.
- Return the withdrawn ERC20 tokens together with the applicable fee.
Flash swaps do not require the caller to hold all the necessary input tokens at the beginning of the transaction. Instead, the caller receives output tokens and can use them in other operations before completing settlement.
This can simplify multi-step operations by removing some upfront capital requirements and intermediate steps.
Example
Arbitrage without upfront trade capital
One application of flash swaps is arbitrage without upfront trade capital. Uniswap's design gives arbitrageurs an incentive to bring pool prices closer to external market prices. Without a mechanism for obtaining temporary liquidity, arbitrageurs need capital to pursue these opportunities. Flash swaps remove some of this upfront capital requirement, although transaction fees, execution risk, and repayment constraints remain.
Obtaining ETH through Uniswap
In the historical example, obtain 1 ETH worth of liquidity through a Uniswap flash swap (using WETH at the V2 pair level).
The borrowed asset is used in the arbitrage operation.
The example assumes the following conditions.
- The
1ETH quantity was previously calculated as the profit-maximizing trade size. - The prices on Uniswap and Oasis have not changed since the calculation.
- The optimal trade size may instead need to be determined during execution.
- One possible approach calculates a trade against an assumed external price, such as the average execution price of one or more Oasis orders.
- When the Uniswap price differs sufficiently from that external price, this example illustrates calculating a swap size for a specified target price.
Trading on an external exchange
In the historical illustration, the temporary 1 ETH can be exchanged for 220 DAI on Oasis.
The Uniswap pair must then be repaid.
Assume that settling the 1 ETH output requires 200 DAI, including the applicable swap terms.
After paying 200 DAI to the pair, 20 DAI remains before transaction costs and other expenses.
Instant leverage
Flash swaps can also simplify the construction of leveraged positions using a lending protocol and Uniswap.
Consider a simplified historical Maker-style model. The system issues DAI against ETH collateral, requiring the collateral value to be at least 150% of the issued debt.
Suppose a user supplies 3 ETH and issues the maximum permitted amount of DAI.
At 1 ETH / 200 DAI, the model permits 400 DAI of debt.
The position could be increased by exchanging DAI for additional ETH.
The acquired ETH could then be added as collateral to issue more DAI, repeating the process toward a desired leverage ratio.
Uniswap can provide liquidity for the DAI-to-ETH exchanges. Repeatedly interacting with both protocols, however, adds complexity and gas costs.
A flash swap can instead provide the required additional ETH upfront within the transaction.
In the simplified example, doubling gross ETH exposure from an initial 3 ETH requires obtaining another 3 ETH temporarily and supplying 6 ETH as collateral.
At the assumed price and collateral ratio, the maximum DAI issuance is 800 DAI.
The user issues enough DAI to settle the flash swap while retaining an appropriate collateral margin. This illustration ignores practical fees and liquidation risks; the difference between maximum borrowing and actual debt is not itself a guarantee of safety.
Oracles
Introduction
A price oracle provides price information about an asset. A smartphone displaying a stock price is a familiar example of a device providing access to price information. Applications can obtain and aggregate prices from multiple sources. These data sources can serve as oracles.
Developers building smart contracts that integrate DeFi protocols often need reliable price information. How should an asset price be obtained on-chain?
Many early Ethereum oracle designs were built on an ad hoc basis, with differing degrees of decentralization and security. Oracle weaknesses have consequently been an important source of security incidents. Some historical examples are discussed here.
No oracle design fits every application, but Uniswap V2 provides building blocks for decentralized on-chain price oracles designed to resist manipulation.
The Uniswap V2 approach
Uniswap V2 introduces improvements supporting public price feeds with greater manipulation resistance.
Each pair accumulates the price implied by the stored reserves over elapsed time, reflecting the price in effect before the first reserve-changing operation of a new block.
This price is determined by the preceding reserve-changing operation, such as mint, swap, or burn.
In the historical threat model, distorting that observed price requires bearing the cost of moving the price before the observation, without assurance of recovering the loss in the following block. The historical documentation discusses the difficulty of controlling consecutive blocks under proof of work. Its observations about attacks refer to that historical context and are not a guarantee against manipulation.
This measure alone is insufficient. When substantial value depends on an oracle reading, the benefit of manipulating it can exceed the cost.
Uniswap V2 therefore maintains cumulative price variables in the pair contract. These accumulate the relevant reserve prices weighted by elapsed time.
Source: https://docs.uniswap.org/contracts/v2/concepts/core-concepts/oracles
External contracts can use these cumulative values to track a time-weighted average price (TWAP) over an interval.
Read the relevant cumulative price at the beginning and end of the interval.
Divide the difference by the elapsed time to obtain the TWAP.
Source: https://docs.uniswap.org/contracts/v2/concepts/core-concepts/oracles
A TWAP can be used directly or as an input to other moving averages, such as EMAs and SMAs.
Consider the following points.
- For a fixed ten-minute TWAP, sample every ten minutes.
- For a fixed one-week TWAP, sample every week.
- Under the simplified model, the cost of sustained manipulation increases roughly with liquidity and averaging duration.
- The historical documentation gives approximate ways to reason about this cost.
- A persistent five-percent deviation over a one-hour TWAP can impose repeated arbitrage and fee losses, though actual costs depend on liquidity, market activity, and block production.
When using Uniswap V2 as an oracle, consider its manipulation-resistance assumptions carefully. The whitepaper discusses these considerations in more detail. The original documentation also anticipated additional oracle development guides.
Manipulation resistance
Manipulation costs can be approximated in terms of arbitrage losses and fees incurred in maintaining a distorted price throughout the observation period. Greater pool liquidity and longer observation periods generally increase the cost, but security depends on the value at risk and actual market conditions.
Factors such as network congestion can change these costs.
Advanced topics
Fees
Liquidity provider fees
Token swaps incur a 0.3% fee.
The fees benefit LPs in proportion to their liquidity shares, subject to the protocol-fee configuration.
Swap fees remain in the liquidity reserves. This increases the reserves attributable to each liquidity token relative to a fee-free swap. Providers realize their share by burning liquidity tokens and withdrawing their proportional reserves.
Because fees remain in the pool, the reserve product generally increases after fee-paying swaps.
The invariant is the reserve product token0_pool * token1_pool, not the reserve ratio token0_pool / token1_pool, which expresses the marginal price in one direction.
Community-built tools can help estimate LP returns. The documentation also explains how to reason about liquidity-provider returns.
Protocol fees
In the historical documentation, the optional protocol fee was described as disabled.
The design allows a fee equivalent to 0.05% of swap volume when enabled.
See the historical discussion of protocol fees for background.
Calculating the protocol fee
The optional protocol charge is designed to capture an amount equivalent to 0.05% of trade volume.
This corresponds to approximately one-sixth (16.6̅%) of the 0.30% swap fee.
A nonzero feeTo address (rather than address(0), or 0x0000000000000000000000000000000000000000) identifies the protocol-fee recipient and enables the fee mechanism.
The setting does not increase the swap fee paid by traders, but reduces the proportion attributable to other LPs.
Rather than calculating and transferring a protocol fee on each swap, V2 realizes the fee by minting LP tokens to feeTo during liquidity minting or burning, based on growth in the square root of the reserve product.
See the whitepaper for the precise formula.
Pricing
How prices are determined
As described in the protocol overview, Uniswap pairs are backed by liquidity pools. Each pool holds two distinct token balances and enforces rules for deposits and withdrawals. The main rule is the constant-product invariant. Withdrawing one token requires sufficient input of the paired token to satisfy the fee-adjusted invariant. The reserve quantities and invariant determine the execution price for a specified trade.
How Uniswap handles pricing
Uniswap V1 calculated the available execution price for a requested swap. Its implementation used different formulas for two swap types. The calculation depended on whether the input amount or output amount was specified. Although the formulas were closely related, the distinction introduced complexity into the core. V2's designers decided not to expose these pricing calculations as core swap functions. Instead, a pair checks that the fee-adjusted invariant holds after each swap. This separates pricing calculations from the core contract's enforcement of its invariant. The separation also accommodates variations such as swapping toward a target price.
In V2, integrations such as routers calculate the amounts for a requested swap. The periphery library supplies helper functions, and router swap functions use these calculations.
Users typically execute swaps through a router. The router provides a smart contract interface for coordinating swap execution. Users supply the swap parameters to the router, and the token exchange occurs if the submitted transaction succeeds.
Similar considerations apply to specifying execution constraints. Actual execution depends on pool state when the transaction is processed. Users can specify a minimum output or maximum input to constrain acceptable execution rather than unconditionally obtaining a requested market price.
Pricing a trade
Traders typically either exchange an exact input amount for the greatest available output or seek an exact output amount with the least required input. Estimating these quantities requires the current reserves of the relevant pairs. However, relying solely on an instantaneous reserve observation within the transaction is unsafe when a fair-price constraint is needed.
Consider a contract swapping 10 DAI through a DAI/WETH pair for WETH based only on its current reserve ratio.
A naive implementation that queries the price and executes without an independent constraint is vulnerable to adverse transaction ordering.
A manipulated pool price can cause the swap to execute at an unfavorable rate; surrounding trades may restore the earlier price while capturing value at the user's expense.
The economic impact depends on liquidity, transaction ordering, fees, and execution conditions.
Protect against this by establishing a reasonable price expectation independently of the potentially manipulated execution-time reserve ratio.
An oracle or other reliable reference can help determine acceptable execution bounds.
In some workflows, this reference is an off-chain observation of the pool or broader market price.
Arbitrage often keeps reserve ratios near external market prices, but instantaneous prices are not inherently trustworthy.
Users can constrain adverse execution by submitting transactions with suitable slippage limits based on their observations.
This is the general approach used by swap interfaces.
Estimate the input or output amount from observed prices and instruct the router to revert if execution is worse than the permitted slippage tolerance.
In the historical frontend example, x represents a user-selected tolerance with a default of 0.5%.
Other oracle options include V2's cumulative-price mechanism.
Exact input
Use getAmountsOut to estimate the output for a specified input amount along a route.
The SDK provides getOutputAmount and, for slippage protection, minimumAmountOut.
Exact output
Use getAmountsIn to estimate the input required for a specified output amount along a route.
The SDK provides getInputAmount and, for slippage protection, maximumAmountIn.
Swapping toward a target price For this more advanced use case, see ExampleSwapToPrice.sol.
Understanding returns
Uniswap incentivizes liquidity provision by allocating trading fees to liquidity providers. However, market making is a complex activity. Large, sustained price changes can cause a liquidity position to underperform simply holding the assets.
Risks For an explanation of liquidity-position risks, see https://medium.com/@pintail/uniswap-a-good-deal-for-liquidity-providers-104c0b6816f2.
Example adapted from the article
Suppose an LP contributes 10,000 DAI and 100 WETH, worth $20,000 in total, bringing the pool reserves to 100,000 DAI and 1,000 ETH. The contribution represents 10% of the pool, so the provider receives liquidity tokens recording that share. Subsequent deposits and withdrawals mint or burn tokens to preserve the proportional accounting. The LP tokens represent a redeemable interest in the pool and can themselves be transferred.
Suppose the ETH price on Coinbase changes from $100 to $150. Arbitrage moves the Uniswap reserve ratio toward 150 DAI per ETH as traders add DAI and withdraw ETH. Ignoring fees and rounding, the pool now contains about 122,400 DAI and 817 ETH (their product is approximately 100,000,000, and their ratio is approximately 150). Redeeming a 10% share yields roughly 12,240 DAI and 81.7 ETH, worth about $24,500. Holding the initial assets would instead be worth $25,000, a difference of about $500.
Liquidity providers receive compensation through swap fees. In the example, a 0.3% fee accrues proportionally to LPs, remaining in the reserves until redeemed. Whether fee income offsets divergence from a holding strategy depends on trading volume and the path of prices.
Why might a liquidity position be worth less than simply holding the deposited assets?
To understand why a liquidity position can underperform holding despite fee income, examine the trading formula. Ignoring fees, the reserve product is constant:
- eth_liquidity_pool * token_liquidity_pool = constant_product The amounts exchanged in a trade are determined so that the product of the two reserve quantities
remains the same before and after the trade. For a trade that is very small relative to pool liquidity, the marginal price is approximately:
eth_price = token_liquidity_pool / eth_liquidity_pool Combining these two equations gives each reserve quantity for a particular price, assuming a constant reserve product:
eth_liquidity_pool = sqrt(constant_product / eth_price)
token_liquidity_pool = sqrt(constant_product * eth_price) Now consider an LP who supplies 1 ETH and 100 DAI to a pool containing 100 ETH and 10,000 DAI, giving a 1% share at an initial price of 100 DAI per ETH. Ignoring fees, let the ETH price rise to 120 DAI. Substituting into the preceding equations gives:
eth_liquidity_pool = 91.2871
dai_liquidity_pool = 10954.4511 The LP's 1% share now corresponds to 0.9129 ETH and 109.54 DAI. At 120 DAI per ETH, this position is worth approximately 219.09 DAI. Holding the original 1 ETH and 100 DAI would be worth 220 DAI, so the liquidity position underperforms holding by about 0.91 DAI.
If the relative price returns to its initial value, this divergence disappears in the fee-free model, hence the term impermanent loss. Its magnitude can be calculated from the ratio of the current price to the initial price:
Impermanent loss (signed relative return) = 2 * sqrt(price_ratio) / (1+price_ratio) — 1
Plotting the expression illustrates the magnitude of impermanent loss at different price ratios.
Expressed as losses relative to holding:
- A 1.25-fold price change produces a 0.6% loss.
- A 1.50-fold change produces a 2.0% loss.
- A 1.75-fold change produces a 3.8% loss.
- A twofold change produces a 5.7% loss.
- A threefold change produces a 13.4% loss.
- A fourfold change produces a 20.0% loss.
- A fivefold change produces a 25.5% loss. Note that the loss is symmetric under reciprocal price ratios: doubling and halving produce the same relative loss in this model.
Source: https://pintail.medium.com/uniswap-a-good-deal-for-liquidity-providers-104c0b6816f2
Conclusion
This article explored the Uniswap documentation.
The focus on concepts rather than detailed implementation makes it accessible to readers without an engineering background.
I also publish articles about blockchain and AI on my blog and Qiita.



