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.
In this article, we will explore Uniswap.
Uniswap is a decentralized exchange (DEX) that uses smart contracts on the Ethereum blockchain.
If you have learned the fundamentals of Solidity, ERC20, and ERC721, Uniswap is a natural next topic to study.
This article is intended for readers looking to deepen their understanding of smart contracts and improve their development skills.
If you are not yet familiar with ERC20 and ERC721, start with the following articles.
/articles/aeefe2d89dd5332c9f43
/articles/0570a8d05bc7c9b9593f
What is Uniswap?

Uniswap is an automated market maker (AMM) decentralized exchange (DEX) that uses smart contracts on Ethereum.
Let's examine some of these terms.
DEX
A DEX, or decentralized exchange, allows users to exchange cryptocurrencies and tokens without a centralized operator.
The following definition explains what a DEX is.
A decentralized exchange (DEX) is a peer-to-peer marketplace where cryptocurrency traders transact directly. DEXs fulfill one of crypto's core possibilities: facilitating financial transactions that are not handled by intermediaries such as banks or brokers. Popular DEXs such as Uniswap and SushiSwap operate on the Ethereum blockchain.
https://www.coinbase.com/ja/learn/crypto-basics/what-is-a-dex
Exchanges that rely on a central operator to coordinate cryptocurrency trading, much like a stock exchange, are called centralized exchanges (CEXs).
By contrast, Uniswap and other AMM-based DEXs determine asset prices through smart contracts rather than a central operator.
Advantages of DEXs
Access to more tokens
A DEX can support Ethereum-based tokens even if they are not listed on a centralized exchange, provided liquidity is available.
This gives traders access to tokens that may not yet be widely traded and could appreciate in the future.
No centralized intermediary fees
With no central operator, there are few or no additional intermediary fees payable to such an operator.
DEX users may therefore be able to reduce trading fees, although network and protocol fees still apply.
Reduced custodial hacking risk
DEX users generally hold their funds in their own wallets rather than in an exchange's custody, reducing the risk associated with hacking a centralized custodian.
Pseudonymity
Trading directly through a DEX generally does not require submitting personal information to the protocol.
This lowers the barrier to accessing DEX trading.
Access in emerging economies
Many people in emerging economies lack access to bank accounts.
Because DEX protocols generally do not require personal information, people with a smartphone, internet access, and a funded wallet can access them.
Disadvantages of DEXs
Smart contract vulnerabilities
Vulnerabilities in smart contracts may be exploited, resulting in the loss of funds.
The custodial advantage described earlier applies to funds users hold in their own wallets. Funds deposited into a DEX remain exposed to smart contract exploits.
Malicious tokens
As mentioned earlier, DEXs allow trading of tokens that have not been listed on centralized exchanges.
Because these tokens may not have undergone any review, their issuers could have created them for fraudulent purposes.
Before trading a token, examine its white paper and the developers' Twitter and Discord channels, among other sources.
High gas fees
Uniswap relies on the Ethereum blockchain. Even if exchange fees are low, the gas required to settle a transaction can be expensive.
What is DeFi?
DeFi, or decentralized finance, refers to financial applications that operate without a centralized administrator.
The following video provides an accessible explanation.
The difference between DeFi and DEXs can be summarized as follows.
A DEX is one type of functionality within the broader DeFi ecosystem.
DeFi and DEXs are often confused, so understanding the distinction is important.
AMM(Automated Market Maker)
ERC20 tokens can be exchanged directly through an AMM.
See the following article for more information about ERC20.
/articles/aeefe2d89dd5332c9f43
An AMM is a system that automatically executes trades according to a predefined algorithm (a set of rules).
Traditional exchanges encourage many people to participate in trading and submit orders, creating a market in which traders can buy or sell their desired quantities at their preferred times, subject to available liquidity.
An order book displays users' proposed buy and sell prices in real time. Traders can use it to understand the market and decide at which price levels to place orders.
However, early on-chain order book DEXs faced Ethereum gas costs every time a limit order was placed or canceled, which made it difficult to attract sufficient liquidity and trading activity.
Because frequent on-chain transactions were costly on Ethereum, order book DEXs lost favor in that setting.
AMMs then emerged as an alternative.
Users deposit cryptocurrencies for swapping into a liquidity pool. Instead of trading directly with another user, a trader exchanges tokens against the pool.
An algorithm automatically calculates the price of each swap.
This allows users to trade through the pool without a third-party intermediary.
The following video explains AMMs in an accessible way.
UNI
UNI is the native governance token of the Uniswap ecosystem.
It was issued as a governance token and can be used in votes concerning the Uniswap project.
The current UNI price is available on sites such as the following.
Swap
Exchanging one cryptocurrency or token for another is called a swap.
Liquidity mining (yield farming)
Liquidity mining, or yield farming, involves depositing ERC20 tokens into a Uniswap pool and, when an applicable incentive program is active, receiving UNI rewards.
Liquidity is generally provided in pairs of crypto assets, such as ETH-DAI, ETH-USDT, or ETH-WBTC.
Depositing tokens provides liquidity and helps create a market in which traders can buy or sell their desired quantities when needed.
Through a liquidity mining or yield farming program, liquidity providers may receive UNI as a reward.
This can provide additional rewards while maintaining exposure to the deposited assets, but it is not risk-free: impermanent loss, token price changes, and smart contract vulnerabilities can result in losses.
Uniswap versions

At the time of writing, Uniswap had three versions: Uniswap V1, Uniswap V2, and Uniswap V3.
This article focuses on Uniswap V2.
Here is why we are not starting with Uniswap V3.
Uniswap V1 is relatively simple and lacks newer features.
Uniswap V3 includes the core functionality of Uniswap V2, but improvements and optimizations make it more complex.
Understanding Uniswap V2 first provides a useful foundation for learning Uniswap V3, so this article focuses on V2.
Uniswap contract architecture

Let's examine the contract architecture of Uniswap V2.
The four main contracts covered here are divided into two groups: Core and Periphery.
Core
Core provides the following functionality.
Core functionality
- Holding tokens
- Exchanging tokens
- Adding tokens
- Earning fees
Core consists of the following three main contracts.
Core contracts
- UniswapV2Pair
- UniswapV2Factory
- UniswapV2ERC20
Each provides the following functionality.
UniswapV2Pair
A pair contract is created for each pair of tokens.
UniswapV2Pair
- Swapping tokens
- Minting liquidity tokens
- Burning liquidity tokens
UniswapV2Factory
Creates a contract for each token pair.
UniswapV2ERC20
This contract manages ownership of the pool.
When liquidity providers add funds to the pool, they receive pool ownership tokens in return.
To withdraw funds from the pool, liquidity providers redeem their pool ownership tokens and receive their share of the assets and accumulated fees.
This contract tracks the pool ownership tokens.
Periphery
These contracts interact with the Core contracts.
Most user-facing Uniswap operations, such as token swaps and liquidity provision, are executed through these contracts.
Oracle
Uniswap makes price information for the two traded tokens available over time.
An oracle is used to obtain information about the relative prices of the two tokens on-chain.
However, depending on a single information provider introduces vulnerabilities, so countermeasures are necessary.
Uniswap accumulates price information over time, allowing a price oracle to use observations spanning multiple blocks to approximate the market price while increasing the cost of deliberate price manipulation.
UniswapV2Pair

Let's start with the code in UniswapV2Pair.sol.
The code is available below.
We will examine it line by line.
Imports
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';First, the code specifies the Solidity version and imports the libraries and interface files.
The corresponding source files are available below.
IUniswapV2Pair.sol
UniswapV2ERC20.sol
Math.sol
UQ112x112.sol
IERC20.sol
IUniswapV2Factory.sol
IUniswapV2Callee.sol
Contract and library declarations
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;This section first declares the UniswapV2Pair contract.
It implements the IUniswapV2Pair interface and inherits the UniswapV2ERC20 contract.
The SafeMath library protects against overflow and underflow.
For more information about overflow and underflow, see the following article.
[Solidity-Bug Bounty] Understanding overflow and underflow from scratch
The UQ112x112 library provides fixed-point arithmetic for representing fractional values.
Solidity does not natively support usable floating-point arithmetic here, so the UQ112x112 library is used.
Variable declarations
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;MINIMUM_LIQUIDITY
Depositing tokens into a liquidity pool can cause the value of the smallest unit of pool ownership (1e-18 pool shares) to increase over time.
This can make it impossible to provide small amounts of liquidity.
To mitigate this problem, 1e-15 (0.000000000000001) pool shares are permanently locked.
This is a negligible cost for most token pairs.
SELECTOR
This is the ERC20 contract ABI (Application Binary Interface) function selector.
It is used when transferring either of the two ERC20 tokens.
factory
The address of the UniswapV2Factory contract that created the pool.
token0 & token1
The contract addresses of the two ERC20 tokens that can be exchanged in this pool.
The token addresses are sorted according to a fixed algorithm to determine which is stored in token0 and which in token1.
reserve0 & reserve1
Store the recorded quantities of token0 and token1 in the pool.
Although reserve0 and reserve1 can have different numerical values, their values are equal when measured at the pool's implied price.
The relationship between Japanese yen and US dollars provides a useful analogy.
Example: 1 USD = 132 JPY
blockTimestampLast
Stores the timestamp of the most recent reserve update.
Incidentally, reserve0, reserve1, and blockTimestampLast are stored in the same storage slot.
reserve0 + reserve1 + blockTimestampLast = 112 + 112 + 32 = 256
See the following article for more information about storage slots.
[Solidity-Bug Bounty] Understanding access to private data from scratch
price0CumulativeLast & price1CumulativeLast
These variables track cumulative prices for token0 and token1 over time.
They are used to calculate average exchange rates over a specified period.
kLast
Stores the product reserve0 * reserve1 according to the x * y = K formula after the most recent liquidity event when protocol fees are enabled.
unlocked
During an ERC20 token transfer or external callback, a malicious contract may attempt to call the pair contract again before the original operation finishes.
Setting unlocked to 0 when processing begins prevents reentrant calls to functions protected by the lock.
The following article explains this in more detail.
[Solidity-Bug Bounty] Understanding reentrancy attacks from scratch
Modifier declaration
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}This modifier implements the mechanism described earlier for the unlocked variable.
The second line checks whether another protected operation is in progress and reverts if so.
Lines 3–5 set unlocked to 0 (locking the contract) if no protected operation is in progress, execute the function body using the _ placeholder, and then set unlocked to 1 to release the lock.
getReserves
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}Returns the values of reserve0, reserve1, and blockTimestampLast.
_safeTransfer
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}Transfers the ERC20 token specified by token, in the amount specified by value, to the address specified by to.
The operation reverts unless both of the following conditions are satisfied.
Conditions
- The return value
successfrom the ERC20 transfer istrue. - The return data
datais empty, or decodingdatayieldstrue.
Events
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);Four events are defined.
Mint
Emitted when a liquidity provider deposits ERC20 tokens.
Parameters
sender= Address calling the function.amount0= Amount oftoken0.amount1= Amount oftoken1.
Burn
Emitted when a liquidity provider withdraws ERC20 tokens.
Parameters
sender= Address calling the function.amount0= Amount oftoken0.amount1= Amount oftoken1.to= Address receiving the ERC20 tokens.
Swap
Emitted when ERC20 tokens are swapped.
Sync
Emitted whenever reserves are updated, including when ERC20 tokens are added or withdrawn.
It provides updated reserves, from which the latest pool exchange rate can be derived.
Constructor
constructor() public {
factory = msg.sender;
}This function executes once when the contract is deployed.
The factory variable stores the address of the UniswapV2Factory contract that created the token pair.
initialize
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}Specifies the two ERC20 tokens that the newly created UniswapV2Pair contract will exchange.
_update
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}Called when ERC20 tokens enter or leave the pool.
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');Checks whether balance0 and balance1 would overflow the reserve variables.
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}If timeElapsed (time since the last reserve update) is not 0, this is the first update in a block with a new timestamp.
In this case, the values of price0CumulativeLast and price1CumulativeLast are updated, provided both previous reserves are nonzero.
The increment is (_reserve1 / _reserve0 or _reserve0 / _reserve1) x timeElapsed, using fixed-point arithmetic.
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);Finally, the values of reserve0, reserve1, and blockTimestampLast are updated, and a Sync event is emitted.
_mintFee
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}This function calculates the protocol fee payable to the address specified by the UniswapV2Factory contract when protocol fees are enabled.
Uniswap V2 charges a 0.3% trading fee. When the protocol fee is enabled, part of this fee accrues to the address specified by UniswapV2Factory and the remainder to liquidity providers.
The calculation implements a protocol share equivalent to 1/6 of the trading fees, collected through liquidity-token minting during liquidity events.
address feeTo = IUniswapV2Factory(factory).feeTo();Retrieves the fee recipient address specified by the UniswapV2Factory contract that created the ERC20 token pair and stores it in feeTo.
uint _kLast = kLast; // gas savingsCaching the value of kLast in the local variable _kLast saves gas by avoiding repeated storage reads.
if (feeOn) {
if (_kLast != 0) {If the fee recipient is not the zero address and _kLast is not 0, the following logic executes.
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}When the growth in the reserve product causes rootK to exceed rootKLast, the protocol fee can be collected.
Although the calculation looks complex, it determines how many liquidity provider (LP) tokens to mint for the address specified by UniswapV2Factory.
kLast = 0;When the protocol fee is disabled, the value of kLast is reset to 0 if necessary.
At the time Uniswap V2 was created, clearing nonzero storage could earn a gas refund, which was another reason to clear unused state.
See the following article for more information.
https://learnblockchain.cn/article/3987
mint
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}Called when a liquidity provider deposits ERC20 tokens. It mints liquidity tokens.
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);Retrieves _reserve0, _reserve1, balance0, and balance1, then stores the amounts of each token added in amount0 and amount1.
bool feeOn = _mintFee(_reserve0, _reserve1);Executes the _mintFee function described earlier, calculating any protocol fee due and minting liquidity tokens accordingly.
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokensRetrieves the totalSupply variable from UniswapV2ERC20 and caches the total supply of the pair's LP tokens in _totalSupply.
On the first deposit, MINIMUM_LIQUIDITY LP tokens are minted to the zero address.
These tokens cannot be redeemed, so a portion of pool ownership remains permanently locked.
On the first deposit, the relative value of the two tokens is established by the deposited amounts, and the geometric mean is calculated by taking the square root of their product.
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}On subsequent deposits, the relative value of the two tokens is already established by the reserves, so liquidity providers are expected to deposit them in the corresponding ratio.
If the deposit is not proportional, the amount of LP tokens minted is limited by the token with the smaller proportional contribution.
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);Uses _mint in UniswapV2ERC20 to mint LP tokens to the address specified by to.
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);Updates the reserves and, when applicable, kLast, then emits the Mint event.
burn
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}Allows a liquidity provider to withdraw deposited ERC20 tokens by burning the corresponding LP tokens.
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];Retrieves _reserve0, _reserve1, balance0, and balance1, and stores the amount of LP tokens to burn in liquidity.
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFeeExecutes _mintFee, calculating any protocol fee due and minting liquidity tokens accordingly.
Retrieves totalSupply from UniswapV2ERC20 and caches the pair's total LP token supply in _totalSupply.
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');Calculates the amounts of the two tokens to withdraw, stores them in amount0 and amount1, and verifies that both are greater than 0.
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));Burns liquidity LP tokens and transfers amount0 of _token0 and amount1 of _token1 to the address specified by to.
Stores the balances of _token0 and _token1 in balance0 and balance1, respectively.
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);Updates the reserves and, when applicable, kLast, then emits the Burn event.
swap
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}This function is intended to be called by a Periphery contract when a trader deposits one ERC20 token into the pool and withdraws the other.
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;Checks that at least one of the amounts to withdraw is greater than 0.
Retrieves _reserve0 and _reserve1 and checks that each recorded reserve is greater than the corresponding output amount, amount0Out or amount1Out.
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokensRetrieves token0 and token1 and checks that the address specified by to is not either token contract.
Transfers amount0Out and/or amount1Out of the requested ERC20 tokens to the address specified by to.
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);If data is nonempty, the recipient is notified of the swap through a callback.
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}Retrieves the current balances of _token0 and _token1.
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}Checks that the swap has not violated the constant-product invariant.
The fee-adjusted product must not fall below _reserve0 * _reserve1.
Multiplies balance0 and balance1 by 1000 and subtracts 3 times the corresponding input amount.
Each adjusted balance therefore accounts for the fee on the incoming tokens.
This represents a 0.3% (3/1000 = 0.003 = 0.3%) fee on the input amount.
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);Updates the reserves and emits the Swap event.
sync
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}Actual token balances can differ from the reserves recorded by the contract, so this function updates reserve0 and reserve1 to match the actual balances.
It synchronizes the recorded reserves with the current ERC20 balances rather than transferring tokens.
skim
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}Actual token balances can differ from the reserves recorded by the contract, so this function addresses excess balances.
It withdraws excess ERC20 tokens above the recorded reserves.
Because the pair does not track who deposited excess ERC20 tokens, this function can be called by any account.
UniswapV2Factory

Next, let's examine the UniswapV2Factory contract.
The code is available below.
We will examine it line by line.
Imports
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';Specifies the Solidity version and imports the necessary interfaces and contracts.
IUniswapV2Factory.sol
UniswapV2Pair.sol
Contract declaration and inheritance
contract UniswapV2Factory is IUniswapV2Factory {Declares UniswapV2Factory, implementing the IUniswapV2Factory interface.
Variable declarations
address public feeTo;
address public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;feeTo
The address that receives protocol-fee liquidity tokens.
feeToSetter
The address authorized to change the feeTo address.
getPair
Stores the address of the pair contract used to swap two given ERC20 tokens.
It can be retrieved using getPair[tokenA address][tokenB address].
allPairs
An array containing the addresses of ERC20 token pair contracts (UniswapV2Pair) created by this UniswapV2Factory contract.
Events
event PairCreated(address indexed token0, address indexed token1, address pair, uint);Emitted when a new ERC20 token pair is created.
Constructor
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}This function executes once when the contract is deployed.
Stores the address specified by _feeToSetter in feeToSetter.
allPairsLength
function allPairsLength() external view returns (uint) {
return allPairs.length;
}Returns the number of ERC20 token pairs created.
createPair
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}Creates a pair contract for two ERC20 tokens.
No permission from Uniswap is required; anyone can call it.
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);Checks that tokenA and tokenB are not identical.
Sorts the two token addresses consistently: the numerically smaller address becomes token0, and the larger becomes token1.
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficientChecks whether a pair for these ERC20 tokens already exists.
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}This is one of the opcodes used to create a new contract.
The deterministic address derivation allows each token pair to be assigned a predictable contract address; deployment fails if the destination is already occupied by a contract.
IUniswapV2Pair(pair).initialize(token0, token1);Calls initialize on the newly created UniswapV2Pair contract and passes the two token addresses.
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);Stores the new pair information in the getPair mapping and emits the PairCreated event.
setFeeTo
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}Only the address stored in feeToSetter can call this function, which stores the address specified by _feeTo in feeTo.
It allows the account receiving the protocol fee to be changed.
setFeeToSetter
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}Only the address stored in feeToSetter can call this function, which stores the address specified by _feeToSetter in feeToSetter.
UniswapV2ERC20

Next, let's examine the UniswapV2ERC20 contract.
The code is available below.
We will examine it line by line.
Imports
pragma solidity =0.5.16;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';Specifies the Solidity version and imports the necessary interfaces and contracts.
IUniswapV2ERC20.sol
SafeMath.sol
Contract and library declarations
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;Declares UniswapV2ERC20, implementing the IUniswapV2ERC20 interface.
The SafeMath library protects against overflow and underflow.
See the following article for more information about overflow and underflow.
[Solidity-Bug Bounty] Understanding overflow and underflow from scratch
Variable declarations
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;name
Stores the ERC20 token name.
symbol
Stores the ERC20 token symbol.
decimals
Stores the number of decimal places used by the token.
totalSupply
Stores the total token supply.
balanceOf
A mapping that stores the token balance of each address.
allowance
A mapping that stores how many tokens an address A has authorized another address B to spend on its behalf.
DOMAIN_SEPARATOR
An EIP-712 domain separator that separates this contract's signature domain from those of other applications.
For approval signatures, Uniswap relies on EIP-712, a widely supported standard for structured data signing, to improve security and wallet compatibility.
PERMIT_TYPEHASH
The type hash of the permit structure, defined as a compile-time constant.
The author has not explored DOMAIN_SEPARATOR and PERMIT_TYPEHASH in depth, so please refer to the following resources for more information.
nonces
Although forging a valid digital signature is computationally infeasible under standard assumptions, replaying a previously signed message is straightforward.
The following article is a related reference.
[Solidity-Bug Bounty] Understanding reentrancy attacks from scratch
To prevent replay, the contract uses a mapping keyed by address to store a number called a nonce. Each successful permit consumes the current nonce and increments it by one.
Events
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);Approval
Emitted when owner authorizes spender to spend up to value of the owner's ERC20 tokens.
Transfer
Emitted when value ERC20 tokens are transferred from the address specified by from to the address specified by to.
Constructor
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}This function executes once when the contract is deployed.
constructor() public {
uint chainId;
assembly {
chainId := chainid
}Retrieves Ethereum's chainId.
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);Calculates the EIP-712 domain separator.
The values inside abi.encode are ABI-encoded together and hashed.
The following functions are standard ERC20 functionality. See the following article for further explanation.
/articles/aeefe2d89dd5332c9f43
ERC20 functions
_mint_burn_approve_transfer_approvetransfertrandferFrom
permit
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}Implements signature-based token approvals.
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');The transaction reverts if the deadline has passed.
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);Constructs the signed message digest using DOMAIN_SEPARATOR.
address recoveredAddress = ecrecover(digest, v, r, s);Uses ecrecover to recover the address that signed the message.
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);After verifying that the recovered signer is nonzero and matches owner, calls _approve to grant the address specified by spender permission to spend value of the owner's ERC20 tokens.
UniswapV2Router02

Finally, let's examine UniswapV2Router02, one of the Periphery contracts.
Periphery contracts provide interfaces for calls from other contracts and decentralized applications.
It is possible to call Core contracts directly, but doing so is more complex, and mistakes can lead to loss of funds.
Core contracts primarily enforce protocol invariants; they do not provide all the user-facing checks needed to protect an individual trade.
Periphery contracts perform additional checks, so interacting directly with Core is generally not recommended unless the caller implements equivalent safeguards.
The code is available below.
Imports
pragma solidity =0.6.6;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/IUniswapV2Router02.sol';
import './libraries/UniswapV2Library.sol';
import './libraries/SafeMath.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';IUniswapV2Factory.sol
TransferHelper.sol
IUniswapV2Router02.sol
UniswapV2Library.sol
SafeMath.sol
IERC20.sol
IWETH.sol
Uniswap V2 can exchange arbitrary pairs of ERC20 tokens, but ETH itself is not an ERC20 token.
WETH was introduced to make ETH usable in contracts that work with the ERC20 token standard.
Depositing ETH into this contract creates an equivalent amount of WETH.
WETH can also be redeemed for ETH by burning the WETH.
Contract and library declarations
contract UniswapV2Router02 is IUniswapV2Router02 {
using SafeMath for uint;Declares UniswapV2Router02, implementing the IUniswapV2Router02 interface.
The SafeMath library protects against overflow and underflow.
See the following article for more information about overflow and underflow.
[Solidity-Bug Bounty] Understanding overflow and underflow from scratch
Variable declarations
address public immutable override factory;
address public immutable override WETH;Stores the addresses of the factory and WETH contracts.
As indicated by immutable, these values cannot be changed after initialization.
Modifier declaration
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}Functions using this modifier can impose a time limit on a transaction.
The deadline must be at or after the current block timestamp.
Constructor
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}This function executes once when the contract is deployed.
It specifies which factory and WETH contracts to use.
receive
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}This receive function is invoked when ETH is received from the WETH contract during unwrapping.
Only the WETH contract is permitted to send ETH through this receive function.
_addLiquidity
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}Adds liquidity to a pool by depositing a pair of ERC20 tokens.
address tokenA,
address tokenB,The addresses of the ERC20 tokens.
uint amountADesired,
uint amountBDesired,The desired amounts of ERC20 tokens that the liquidity provider wishes to deposit.
uint amountAMin,
uint amountBMinThe minimum acceptable deposit amounts.
If these minimum amounts cannot be satisfied, the transaction reverts.
If this protection is not needed, a minimum value of zero can be specified.
However, liquidity providers normally specify minimum deposit amounts.
They do so to restrict the deposit to an acceptable range around the current price.
If the price changes significantly, the deposit amounts may differ considerably from those originally expected.
Minimum deposit amounts are therefore generally set so that the transaction executes only within the acceptable range.
) internal virtual returns (uint amountA, uint amountB) {Returns the amounts that the liquidity provider should deposit to match the current ratio of the ERC20 token reserves.
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}If the pair for tokenA and tokenB does not exist, creates it.
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);Retrieves the current amounts deposited in the specified token pair's pool.
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);If no liquidity has been provided yet, the deposit amounts equal the amounts the liquidity provider wishes to deposit.
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);Uses the quote function of UniswapV2Library to determine the deposit amounts.
The amounts match the current ratio of the two ERC20 tokens.
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);If amountBOptimal is smaller than the amount the liquidity provider wants to deposit, less tokenB is required to match the desired amount of tokenA at the current reserve ratio.
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}Conversely, if amountBOptimal is larger than the desired amount of tokenB, more tokenB would be required to match the desired amount of tokenA.
Because that exceeds the desired deposit, the router instead fixes the desired amount of tokenB and calculates the required amount of tokenA.
The following graph summarizes these relationships.

Suppose we want to deposit 1000 tokenA (blue line) and 1000 tokenB (red line).
The x-axis represents the relative exchange rate, tokenA/tokenB, as defined in the example.
When x = 1, both tokens have equal value, so we deposit 1000 of each.
When x = 2, tokenA is worth twice as much as tokenB, so 500 tokenA should be deposited for 1000 tokenB.
Conversely, when x = 0.5, 500 tokenB should be deposited for 1000 tokenA.
Liquidity can also be provided directly to Core, but Core primarily enforces its own invariants. If the exchange rate changes between transaction submission and execution, the liquidity provider risks losing value.
Using Periphery, the required deposit amounts are calculated immediately before depositing within the same transaction. Minimum-amount checks help protect against unfavorable changes in the exchange rate before execution.
addLiquidity
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}Called to provide liquidity.
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadlineMost arguments are the same as those of _addLiquidity.
to
The address receiving the liquidity provider (LP) tokens issued for the deposit.
deadline
The transaction deadline.
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);Calls _addLiquidity to calculate the actual deposit amounts, then uses pairFor in UniswapV2Library to obtain the deposit destination address without querying the factory directly, saving gas.
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);Deposits amountA of tokenA and amountB of tokenB into the pair address obtained earlier.
liquidity = IUniswapV2Pair(pair).mint(to);The liquidity provider receives LP tokens in return for providing liquidity.
The amount of LP tokens received depends on the amounts of ERC20 tokens deposited.
addLiquidityETH
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}Adds liquidity when a liquidity provider deposits an ERC20 token and ETH, wrapping the ETH as part of the process.
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));Most of the processing is the same as in addLiquidity.
The difference is that ETH is converted into the ERC20 token WETH, which is then deposited alongside token as a pair.
If the transfer fails and the transaction reverts, the WETH conversion is reverted as well.
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);The liquidity provider receives LP tokens in return for providing liquidity.
If the user sent more ETH than was needed for the WETH deposit, the excess is returned to the user.
removeLiquidity
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}Withdraws deposited tokens.
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {Much of the processing follows the same pattern as addLiquidity.
The liquidity provider specifies the minimum acceptable amounts of each token to withdraw. The transaction also reverts if it is executed after the deadline.
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);Burns the deposited LP tokens in exchange for the two underlying tokens.
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);Sorts tokenA and tokenB and retrieves only the first token address.
Only one value is needed, which saves gas.
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);If the token0 obtained earlier equals tokenA, assign amount0 to amountA and amount1 to amountB; otherwise, reverse the assignments.
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');Checks that neither of the withdrawn token amounts is below the liquidity provider's specified minimum.
Even if tokens are transferred to the liquidity provider first, the transaction can revert the entire state change if the conditions are not satisfied.
removeLiquidityETH
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}Withdraws a deposited ERC20 token and ETH pair.
The operation is largely the same as removeLiquidity.
The difference is that the WETH received is converted into ETH before being returned to the liquidity provider.
removeLiquidityWithPermit
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}Executes removeLiquidity to withdraw deposited ERC20 tokens without requiring a separate approval transaction.
removeLiquidityETHWithPermit
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}Withdraws the deposited ERC20 token and ETH using a permit instead of a separate approval transaction.
removeLiquidityETHSupportingFeeOnTransferTokens
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}Called when withdrawing an ERC20 token and ETH pair involving a token that charges a transfer fee.
Calls removeLiquidity to withdraw the ERC20 token and WETH, then transfers the actual ERC20 balance and unwraps the specified WETH amount into ETH.
removeLiquidityETHWithPermitSupportingFeeOnTransferTokens
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}Uses a permit to execute removeLiquidityETHSupportingFeeOnTransferTokens without a separate approval transaction, allowing withdrawal of an ERC20 token and ETH when the token charges a transfer fee.
_swap
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}Performs the internal processing required by the user-facing functions for swapping ERC20 tokens.
for (uint i; i < path.length - 1; i++) {Suppose there are four tokens, A, B, C, and D, with pairs A-B, B-C, and C-D.
Using a swap path, a swap from A to D can be performed through A → B, B → C, and C → D, without requiring a direct A-D pair.
Swap steps
- Sell
24.69 token Aand receive25.30 token B. - Sell
24.69 token Band receive25.30 token C, retaining approximately0.61 token B. - Sell
24.69 token Cand receive25.30 token A, retaining approximately0.61 token C. - Retain approximately
0.61 token A(the difference between the25.30 token Areceived and the24.69 token Ainitially committed), before any additional costs. This is a hypothetical triangular trading example rather than a guaranteed profit.
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];Retrieves and sorts the ERC20 token pair being processed.
Then retrieves the calculated output amount for the current hop.
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));Assigns the expected output amount to the appropriate output token based on token ordering.
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;For the final swap, sends the received ERC20 tokens to the recipient address; otherwise, sends them to the next pair.
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);Executes the ERC20 token swap.
swapExactTokensForTokens
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}A user-facing function for swapping ERC20 tokens.
uint amountIn,
uint amountOutMin,
address[] calldata path,As described in the _swap section, the path array stores the sequence of token addresses needed to exchange the currently held token for the desired token through one or more pairs.
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');Calculates the expected token output at each swap.
If the final output amount is below the user's minimum acceptable value, the transaction reverts.
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);Transfers the initial ERC20 tokens to the first pair and calls _swap.
swapTokensForExactTokens
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}Performs the complementary exact-output swap to swapExactTokensForTokens.
The swapExactTokensForTokens function described earlier lets users specify the exact input amount and the minimum output amount they are willing to receive.
Here, users specify the exact output amount they want to receive and the maximum input amount they are willing to pay.
swapExactETHForTokens
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}Specifies the exact ETH input, deposits ETH, and receives ERC20 tokens.
swapTokensForExactETH
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}Specifies the exact ETH output, deposits ERC20 tokens, and receives ETH.
swapExactTokensForETH
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}Specifies the exact ERC20 token input, deposits ERC20 tokens, and receives ETH.
swapETHForExactTokens
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}Specifies the exact ERC20 token output, deposits ETH, and receives ERC20 tokens.
_swapSupportingFeeOnTransferTokens
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}A function for swapping ERC20 tokens that charge fees on transfers.
The user first transfers the ERC20 tokens, and the actual amount received by each pair is measured from its balance before calculating the output.
The regular _swap function uses precomputed amounts, which may not account for transfer fees that reduce the actual amount received.
The fee-on-transfer implementation consumes additional gas and is intended for tokens with this behavior.
swapExactTokensForTokensSupportingFeeOnTransferTokens
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}Performs an operation analogous to swapExactTokensForTokens while supporting ERC20 tokens that charge a transfer fee.
swapExactETHForTokensSupportingFeeOnTransferTokens
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}Performs an operation analogous to swapExactETHForTokens while supporting tokens that charge a fee on transfer.
swapExactTokensForETHSupportingFeeOnTransferTokens
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}Performs an operation analogous to swapExactTokensForETH while supporting tokens that charge a fee on transfer.
quote
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}Calls quote in UniswapV2Library.
Given an amount of a particular ERC20 token, returns the equivalent amount of the other token at the current reserve ratio.
getAmountOut
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}Calls getAmountOut in UniswapV2Library.
Given the input token amount, returns the maximum amount of the other token that can be received, taking the swap fee into account.
getAmountIn
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}Calls getAmountIn in UniswapV2Library.
Returns the minimum input token amount required to receive the specified output amount, taking the swap fee into account.
getAmountsOut
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}Calls getAmountsOut in UniswapV2Library.
Given an input token amount and the path array of token addresses, calls getReserves for each adjacent pair in the path and uses getAmountOut to calculate the maximum output amount for each hop.
getAmountsIn
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}Calls getAmountsIn in UniswapV2Library.
Given a desired output token amount and the path array of token addresses, calls getReserves for each adjacent pair and works backward using getAmountIn to calculate the input amount required at each hop.
UniswapV2Library

The preceding sections covered the main Uniswap contracts.
Next, let's examine the code in UniswapV2Library.sol.
The code is available below.
We will examine it line by line.
Imports
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";First, specifies the Solidity version and imports the libraries and interfaces.
The corresponding source files are available below.
IUniswapV2Pair.sol
Math.sol
Contract and library declarations
library UniswapV2Library {
using SafeMath for uint;This section declares the library used with UniswapV2Pair.
It defines UniswapV2Library.
The SafeMath library protects against overflow and underflow.
See the following article for more information about overflow and underflow.
[Solidity-Bug Bounty] Understanding overflow and underflow from scratch
sortTokens
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}Sorts the addresses of two ERC20 tokens.
The same pair of addresses always produces the same ordering.
pairFor
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}Computes the address of the Pair contract used to swap two ERC20 tokens.
Given the parameters, the address can be computed using the same deterministic algorithm, saving gas compared with querying the factory contract.
getReserves
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}Given tokenA and tokenB, retrieves their reserves and returns them in the corresponding input order.
quote
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}Calculates the amount of tokenB equivalent to an amount of tokenA at the current reserve ratio.
It uses the supplied reserve ratio rather than predicting future exchange rate changes; it does not account for swap fees or price impact.
getAmountOut
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}Calculates the maximum amount of the other token that can be received for a given input token amount.
The returned amount accounts for the 0.3% swap fee.
getAmountIn
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}Given a desired output token amount, calculates how much of the paired token must be supplied.
The returned input amount accounts for the 0.3% swap fee.
getAmountsOut
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}Applies getAmountOut across multiple swap hops.
getAmountsIn
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}Applies getAmountIn across multiple swap hops, working backward from the desired output.
Conclusion

This article has walked through the code of Uniswap.
It was a fairly long and complex walkthrough, so thank you for reading this far.
Some parts may take more than one reading to understand. Feel free to use this article as a reference while doing your own research.
If you have any questions, feel free to send me a DM on Twitter.
You can also contact me through the channels below.
I regularly share information about Solidity, blockchain, and Web3.
I share interesting articles on Twitter, so feel free to follow me there.
References
https://www.caica.jp/media/crypto/uniswap-about/
https://zuu.co.jp/media/cryptocurrency/what-is-uniswap
https://betterprogramming.pub/uniswap-smart-contract-breakdown-ea20edf1a0ff
https://betterprogramming.pub/uniswap-smart-contract-breakdown-part-2-b9ea2fca65d1









