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, I use Bunzz’s DeCipher feature to examine the UniswapV2Router02 contract in Uniswap V2.

DeCipher uses AI to automatically generate smart contract documentation.

For instructions on using it, see the following article.

This article reflects my own experience using DeCipher. If you find any inaccuracies, please let me know in the comments.

The DeCipher page used in this article is linked below.

Overview

Summary

The UniswapV2Router02 contract is an important component of Uniswap, a decentralized exchange (DEX) built on the Ethereum blockchain. It facilitates adding and removing liquidity and swapping tokens within the Uniswap ecosystem.

Purpose of the contract

The primary purpose of UniswapV2Router02 is to enable seamless interaction with the Uniswap protocol. It provides a set of functions that allow users to add or remove liquidity from pools and swap tokens on the Ethereum blockchain.

The contract also interacts with the WETH (Wrapped Ether) contract, which represents a tokenized version of Ether conforming to ERC20. This improves compatibility with contracts that expect ERC20 tokens.

Contract responsibilities

Liquidity management

The contract provides functionality for adding and removing liquidity. The addLiquidity and addLiquidityETH functions allow users to deposit pairs of tokens into liquidity pools and receive liquidity tokens in return. These liquidity tokens represent users' shares in the pool.

The removeLiquidity function allows users to burn their liquidity tokens and withdraw their share of the tokens in the pool. This is useful when users want to close their positions.

Token swaps

The swap function allows users to exchange tokens directly on the Ethereum blockchain. This is a core feature of the Uniswap protocol and provides decentralized exchange functionality.

Integration with WETH

The contract interacts with the WETH contract to deposit and withdraw Ether. Users can convert Ether into WETH using deposit and convert WETH back into Ether using withdraw.

Contract initialization

The initialize function is used to configure the contract when it is first deployed. This function sets the addresses of the Factory and WETH contracts, which are used by many of the contract's functions.

For more on the Factory contract, see the following reference.

Safety measures

The contract includes a receive function that accepts Ether only when sent by the WETH contract. This safety measure prevents Ether from being sent in a way that the contract cannot handle.

The contract also includes an ensure modifier that checks whether the transaction deadline has passed. This prevents a transaction from executing successfully in a block after its deadline.

Summary

The UniswapV2Router02 contract is an important part of the Uniswap protocol and provides functionality required for users to interact with it. It handles liquidity provision and removal, token swaps, and integration with WETH, and includes safety measures to support secure operation of the protocol.

Usage

The UniswapV2Router02 contract is part of the Uniswap protocol, an automated liquidity protocol on Ethereum. It provides functions for adding and removing liquidity, swapping tokens, and querying information about token pairs.

The following are the steps for using the UniswapV2Router02 contract.

1. Deploy the contract

Deploy the UniswapV2Router02 contract on the Ethereum network. The constructor requires the addresses of the UniswapV2Factory and WETH contracts.

2. Add liquidity

Call addLiquidity or addLiquidityETH to add liquidity to a pair.

  • addLiquidity requires the addresses of two tokens, the desired and minimum amounts for each token, the address receiving the liquidity tokens, and a deadline.
  • addLiquidityETH is similar, but is used when one of the assets is Ether.

For more on the Pair contract, see the following reference.

3. Remove liquidity

Call removeLiquidity to remove liquidity from a pair. This function requires the addresses of two tokens, the amount of liquidity to remove, the minimum amount of each token to receive, the recipient address, and the transaction deadline.

4. Swap tokens

Call swap to swap tokens. This function requires the amounts of each token to swap, the recipient address, and additional data.

5. Query information

Call getReserves to retrieve the pair's reserve balances. Call price0CumulativeLast and price1CumulativeLast to retrieve the latest cumulative prices of the tokens in the pair. Call kLast to retrieve the last product of the pair's reserve balances.

6. Other functions

  • mint is used to mint liquidity tokens.

  • burn is used to burn liquidity tokens.

  • skim is used to remove excess tokens mistakenly sent to the contract.

  • sync is used to update the pair's reserve balances.

All functions that modify contract state require a transaction to be sent from an Ethereum account. The account must have sufficient funds to pay the transaction's gas fees.

Parameters

_factory

Address of the UniswapV2Factory contract. Used to create new pairs or retrieve existing pairs.

_WETH

Address of the Wrapped Ether (WETH) contract. Represents the ERC20 token version of Ether and is used in Uniswap trading pairs.

Constants and modifiers

Constants

WETH

solidity
address public immutable override WETH;

Constant storing the WETH token contract address.

factory

solidity
address public immutable override factory;

Constant storing the Factory contract address.

Modifiers

ensure

solidity
modifier ensure(uint deadline) {
        require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
        _;
}

A modifier that checks whether a specified deadline is still valid before an operation and rejects the operation if it has expired.

  1. Check the deadline parameter.
  2. If the current block timestamp is later than deadline, the condition is considered unsatisfied.
  3. If the condition is not satisfied, an exception is raised with the error message UniswapV2Router: EXPIRED.
  4. If the condition is satisfied, execution proceeds through _; in the modifier.

Other functionality

constructor

solidity
constructor(address _factory, address _WETH) public {
        factory = _factory;
        WETH = _WETH;
}

Receives and sets the addresses of the WETH and Factory contracts as constructor parameters.

receive

solidity
receive() external payable {
        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}

Provides a mechanism for accepting Ether sent only from the WETH contract.

  1. It is automatically called when ETH is sent to this contract from outside.
  2. The assert statement raises an exception when its condition is false. In this case, the condition is msg.sender == WETH.
  3. The condition msg.sender == WETH checks whether the address sending Ether is the WETH contract.
  4. If the sender is not the WETH contract, the condition fails, an exception occurs, and the transaction is reverted.
  5. If the sender is the WETH contract, the condition is satisfied and the ETH is accepted.

Functions

This section uses the word acceptable to refer to the minimum requirements for a trade. Specifying these conditions allows users to enforce minimum requirements when executing a particular transaction.

For example, suppose amountTokenMin is set to 100 and amountETHMin to 0.5. When the user calls the function, at least 100 tokens and 0.5 ETH must be added to the pool. These limits ensure the minimum trade conditions are met. If they are not satisfied, the function reverts.

READ

quote

Calculates the amount of token B equivalent to a specified amount of token A based on the given reserves of tokens A and B.

Parameters

  • amountA
    • Amount of token A.
    • The equivalent amount of token B is calculated from this amount.
  • reserveA
    • Reserve of token A (amount held).
    • The amount of token A held in the Uniswap pool.
  • reserveB
    • Reserve of token B (amount held).
    • The amount of token B held in the Uniswap pool.

Process

  1. Calculate the amount of token B equivalent to the specified amount of token A based on the reserves of tokens A and B.
  2. Return the calculated equivalent amount of token B as amountB.

getAmountOut

Calculates the expected amount of output tokens for a specified input amount based on the reserves of the input and output tokens.

Parameters

  • amountIn
    • Amount of input tokens.
    • Indicates the amount used in the exchange.
  • reserveIn
    • Input token reserve (amount held).
  • reserveOut
    • Output token reserve (amount held).

Process

  1. Calculate the expected output amount for the specified input amount based on the input and output token reserves.
  2. Return the calculated expected output amount as amountOut.

getAmountIn

Calculates the input amount required to obtain a specified output amount based on the reserves of the input and output tokens.

Parameters

  • amountOut - Amount of output tokens. - Indicates the desired output token amount.
  • reserveIn - Input token reserve (amount held).
  • reserveOut - Output token reserve (amount held).

Process

  1. Calculate the required input token amount for the specified output amount based on the input and output token reserves.
  2. Return the calculated required input amount as amountIn.

getAmountsOut

Calculates the expected amount of each token using a specified input token amount and a token path (the route between tokens).

Parameters

  • amountIn - Amount of input tokens. - Indicates how many input tokens are used in the exchange.
  • path - An array containing the addresses of the tokens in the order in which they are exchanged. - For example, when exchanging TokenA for TokenC through TokenB, as in [TokenA, TokenB, TokenC], the path is [TokenA address, TokenB address, TokenC address].

Process

  1. Using the specified input token amount and token path, calculate the expected amount of each token in the path array.
  2. Return the array of calculated expected amounts as amounts.
  3. This array contains the amount of each token in the path array and represents the token amounts after each exchange.

getAmountsIn

Calculates the required amount of each token using a specified output amount and a token path (the route between tokens).

Parameters

  • amountOut - Amount of output tokens. - Indicates the amount of output tokens obtained from the exchange.
  • path - An array containing the addresses of the tokens in the order in which they are exchanged. - For example, when exchanging TokenA for TokenC through TokenB, as in [TokenA, TokenB, TokenC], the path is [TokenA address, TokenB address, TokenC address].

Process

  1. Using the specified output token amount and token path, calculate the required amount of each token in the path array.
  2. Return the array of calculated required amounts as amounts.
  3. This array contains the amount of each token in the path array and represents the token amounts after each exchange.

WRITE

_addLiquidity

Implements the logic for adding liquidity to Uniswap. Used to add tokens to a liquidity pool. Calculates appropriate amounts based on the token exchange rate and reserve balances to provide liquidity. It can also add token pairs that do not yet exist by creating new pairs.

Parameters

  • tokenA
    • Address of token A to add to the liquidity pool.
  • tokenB
    • Address of token B to add to the liquidity pool.
  • amountADesired
    • Amount of token A to deposit.
  • amountBDesired
    • Amount of token B to deposit.
  • amountAMin
    • Minimum acceptable amount of token A.
  • amountBMin
    • Minimum acceptable amount of token B.

Process

  1. If the pair does not exist, create a pair for the specified tokens A and B. This may create the liquidity pool for the first time.
  2. Retrieve the reserves of the specified tokens A and B.
  3. If both token reserves are zero, use the desired deposit amounts directly.
  4. If the reserves are nonzero, calculate the optimal amounts. Calculate the optimal amount of token B corresponding to the specified amount of token A. If the optimal amount of token B is no greater than the desired amount, check whether it meets the minimum amount. If the condition is satisfied, set the amounts of tokens A and B.
  5. Otherwise, calculate the optimal amount of token A corresponding to the specified amount of token B. Check the calculated optimal amount against the desired and minimum amounts. If the condition is satisfied, set the amounts of tokens A and B.

addLiquidity

Adds liquidity to Uniswap. Supplies tokens to the liquidity pool based on the specified amounts of tokens A and B and receives the corresponding liquidity tokens.

Parameters

  • tokenA
    • Address of token A to add to the liquidity pool.
  • tokenB
    • Address of token B to add to the liquidity pool.
  • amountADesired
    • Amount of token A to deposit.
  • amountBDesired
    • Amount of token B to deposit.
  • amountAMin
    • Minimum acceptable amount of token A.
  • amountBMin
    • Minimum acceptable amount of token B.
  • to
    • Address receiving the liquidity tokens.
  • deadline
    • Transaction deadline.

Process

  1. Check the deadline. The ensure modifier is applied to ensure that the transaction is executed before the deadline.
  2. Call the internal _addLiquidity function to calculate the optimal trade amounts and token quantities to supply based on the specified parameters.
  3. Once the amounts of tokens A and B have been calculated, use TransferHelper.safeTransferFrom to transfer the tokens to the specified liquidity pool.
  4. Finally, call IUniswapV2Pair(pair).mint(to) to mint liquidity tokens using the calculated amounts and the specified recipient address to. This operation mints new liquidity tokens and sends them to the liquidity provider.

addLiquidityETH

Adds liquidity to Uniswap using ETH (Ether) and a token. This function is used when supplying a token and ETH to Uniswap, allowing ETH to be received alongside the token.

Parameters

  • token
    • Address of the token to add to the liquidity pool.
  • amountTokenDesired
    • Amount of tokens to deposit.
  • amountTokenMin
    • Minimum acceptable token amount.
  • amountETHMin
    • Minimum acceptable ETH amount.
  • to
    • Address receiving the liquidity tokens.
  • deadline
    • Transaction deadline.

Process

  1. Check the deadline. The ensure modifier is applied to ensure that the transaction is executed before the deadline.
  2. Call the internal _addLiquidity function to calculate the optimal amounts of tokens and ETH to supply based on the specified parameters. This function takes both the token and ETH and calculates the amounts for providing them to the liquidity pool.
  3. Once the token and ETH amounts have been calculated, use TransferHelper.safeTransferFrom to transfer the token to the specified liquidity pool. To handle ETH, it also calls IWETH(WETH).deposit{value: amountETH}() and IWETH(WETH).transfer(pair, amountETH) internally.
  4. Finally, call IUniswapV2Pair(pair).mint(to) to mint liquidity tokens using the calculated amounts and the specified recipient address to. This operation mints new liquidity tokens and sends them to the liquidity provider.
  5. If the transaction includes excess ETH, the excess ETH is refunded.

removeLiquidity

Removes liquidity from Uniswap. Burns a specified amount of liquidity tokens and returns the corresponding amounts of tokens A and B.

Parameters

  • tokenA
    • Address of token A to withdraw from the liquidity pool.
  • tokenB
    • Address of token B to withdraw from the liquidity pool.
  • liquidity
    • Amount of liquidity tokens to withdraw.
  • amountAMin
    • Minimum acceptable amount of token A.
  • amountBMin
    • Minimum acceptable amount of token B.
  • to
    • Address receiving the deposited tokens.
  • deadline
    • Transaction deadline.

Process

  1. Check the deadline. The ensure modifier is applied to ensure that the transaction is executed before the deadline.
  2. Calculate the address of the corresponding liquidity pool using the addresses of tokens A and B.
  3. Call IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity) to transfer the specified amount of liquidity tokens from the user to the liquidity pool. This returns the specified amount of liquidity tokens to the pool.
  4. Call IUniswapV2Pair(pair).burn(to) to withdraw tokens A and B from the pool to the specified recipient address to. This operation calculates the amounts of tokens A and B.
  5. Sort the addresses of tokens A and B to determine which corresponds to token A. Assign the quantities to amountA and amountB accordingly.
  6. Finally, check amountAMin and amountBMin to ensure that the token amounts withdrawn are no less than the minimum acceptable amounts. If the conditions are not satisfied, the transaction reverts.

removeLiquidityETH

Removes liquidity from a pair consisting of ETH and an arbitrary token. It burns liquidity tokens for an ETH-token pair and receives the corresponding amounts of the token and ETH.

Parameters

  • token
    • Address of the token to withdraw.
  • liquidity
    • Amount of liquidity tokens to withdraw.
  • amountTokenMin
    • Minimum acceptable token amount.
  • amountETHMin
    • Minimum acceptable ETH amount.
  • to
    • Address receiving the withdrawn tokens and ETH.
  • deadline
    • Transaction deadline.

Process

  1. Check the deadline. The ensure modifier is applied to ensure that the transaction is executed before the deadline.
  2. Call the internally defined removeLiquidity function to remove the specified amount of liquidity for the token and ETH pair. In addition to the specified token argument, pass WETH (wrapped ETH) as an argument.
  3. Use amountToken and amountETH returned by removeLiquidity to send the specified amounts of tokens and ETH to the recipient address to.
  4. Because the withdrawn ETH is wrapped as WETH, call IWETH(WETH).withdraw(amountETH) to unwrap it. This withdraws the specified amount of ETH from WETH.
  5. Finally, use TransferHelper.safeTransferETH(to, amountETH) to send the specified amount of ETH to the recipient address to. This sends the withdrawn ETH to the recipient address.

removeLiquidityWithPermit

Executes a transaction to withdraw tokens from a UniswapV2 pool using an authorization signed in advance by the token owner. It allows tokens to be withdrawn from the pool after the token owner grants authorization using a signature.

Parameters

  • tokenA
    • Address of token A to withdraw.
  • tokenB
    • Address of token B to withdraw.
  • liquidity
    • Amount of liquidity tokens to withdraw.
  • amountAMin
    • Minimum acceptable amount of token A.
  • amountBMin
    • Minimum acceptable amount of token B.
  • to
    • Address receiving the withdrawn tokens.
  • deadline
    • Transaction deadline.
  • approveMax
    • Flag determining the amount authorized by the signature.
    • If true, authorization is unlimited; if false, it covers the amount specified by liquidity.
  • v, r, s
    • Signature parameters.

Process

  1. Use the addresses of tokenA and tokenB to obtain the pool's pair address in pair.
  2. If approveMax is true, set value to the maximum (2^256 - 1); otherwise, use the value of liquidity. This specifies the token allowance amount.
  3. Call IUniswapV2Pair's permit function to use the authorization signed in advance by the token owner.
  4. Call removeLiquidity to perform the actual token withdrawal. This function withdraws tokens while taking the token amounts and minimum acceptable amounts into account.
  5. Finally, assign the amounts of withdrawn tokens to amountA and amountB, which are returned by the function.

removeLiquidityETHWithPermit

Executes a transaction to withdraw both tokens and ETH from a UniswapV2 pool using authorization signed in advance by the token owner.

Parameters

  • token
    • Address of the token to withdraw.
  • liquidity
    • Amount of liquidity tokens to withdraw.
  • amountTokenMin
    • Minimum acceptable token amount.
  • amountETHMin
    • Minimum acceptable ETH amount.
  • to
    • Address receiving the withdrawn tokens and ETH.
  • deadline
    • Transaction deadline.
  • approveMax
    • Flag determining the amount authorized by the signature.
    • If true, authorization is unlimited; if false, it covers the amount specified by liquidity.
  • v, r, s
    • Signature parameters.

Process

  1. Use the addresses of token and WETH (wrapped Ether) to obtain the pool's pair address in pair.
  2. If approveMax is true, set value to the maximum (2^256 - 1); otherwise, use the value of liquidity. This specifies the token allowance amount.
  3. Call IUniswapV2Pair's permit function to use the authorization signed in advance by the token owner.
  4. Call removeLiquidityETH to perform the actual withdrawal of both tokens and ETH. This function withdraws the token and ETH while taking their amounts and minimum acceptable amounts into account.
  5. Finally, assign the amounts of withdrawn tokens and ETH to amountToken and amountETH, which are returned by the function.

removeLiquidityETHSupportingFeeOnTransferTokens

Supports fee-on-transfer tokens when withdrawing both tokens and ETH from a UniswapV2 pool.

Parameters

  • token
    • Address of the token to withdraw.
  • liquidity
    • Amount of liquidity tokens to withdraw.
  • amountTokenMin
    • Minimum acceptable token amount.
  • amountETHMin
    • Minimum acceptable ETH amount.
  • to
    • Address receiving the withdrawn tokens and ETH.
  • deadline
    • Transaction deadline.

Process

  1. Call removeLiquidity to withdraw the token and ETH. The function's return value, amountETH, indicates the amount of ETH withdrawn.
  2. Retrieve the token balance and use TransferHelper.safeTransfer to send the tokens to the specified address. This prepares for the receipt of fee-on-transfer tokens.
  3. Call the WETH contract's withdraw function to unwrap the withdrawn ETH back into native Ether.
  4. Use TransferHelper.safeTransferETH to send the withdrawn ETH to the specified address. This sends the ETH to the recipient.

removeLiquidityETHWithPermitSupportingFeeOnTransferTokens

Withdraws both tokens and ETH from a UniswapV2 pool while supporting fee-on-transfer tokens.

Parameters

  • token
    • Address of the token to withdraw.
  • liquidity
    • Amount of liquidity tokens to withdraw.
  • amountTokenMin
    • Minimum acceptable token amount.
  • amountETHMin
    • Minimum acceptable ETH amount.
  • to
    • Address receiving the withdrawn tokens and ETH.
  • deadline
    • Transaction deadline.
  • approveMax
    • Flag determining the amount authorized by the signature.
    • If true, authorization is unlimited; if false, it covers the amount specified by liquidity.
  • v, r, s
    • Signature parameters.

Process

  1. Use pairFor to obtain the address of the token and WETH pair.
  2. Set the amount authorized by permit according to approveMax. If approveMax is true, grant an unlimited allowance; if false, authorize the amount specified by liquidity.
  3. Call the permit function of the IUniswapV2Pair interface to authorize token spending. This grants the approval used for the fee-on-transfer token withdrawal.
  4. Call removeLiquidityETHSupportingFeeOnTransferTokens to withdraw both tokens and ETH. Return the function's return value, amountETH.

_swap

Swaps tokens in a UniswapV2 pool.

Parameters

  • amounts
    • Array of token amounts for the swap.
    • amounts[0] is the input token amount and amounts[n] is the output token amount (where n represents the number of tokens in the swap, as described in the source).
  • path
    • Array specifying the swap path.
    • The path specifies the token order from the input token to the output token.
  • _to
    • Address receiving the swapped tokens.

Process

  1. Repeat path.length - 1 times, which is the number of elements in path minus 1. This processes each consecutive token pair in the path.
  2. Retrieve the current and next tokens as input and output, and determine their sorted order. Sorting determines the correct ordering of the tokens in the pair.
  3. Set the output token amount for this swap to amountOut.
  4. Determine whether input or output is token 0 and set amount0Out and amount1Out accordingly. This accounts for the different token output amounts associated with the swap pair.
  5. Determine the recipient address to for the swap result based on the current and next tokens. If i is less than path.length - 2, use the next pair's address; otherwise, use _to.
  6. Use UniswapV2Library.pairFor to obtain the pair address for the current and next tokens.
  7. Call swap on the IUniswapV2Pair interface to perform the token swap. The appropriate token amounts are swapped according to amount0Out and amount1Out.

swapExactTokensForTokens

Swaps tokens in UniswapV2 pools to obtain output tokens for a specified input token amount.

Parameters

  • amountIn
    • Amount of input tokens.
  • amountOutMin
    • Minimum acceptable output token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline
    • Transaction deadline.

Process

  1. Use UniswapV2Library.getAmountsOut to obtain the array amounts of token amounts for the swap based on the specified input amount and token path. amounts[0] represents the amount at the start of the swap path, and amounts[n] represents the final output token amount.
  2. Verify that the last element of amounts (amounts[amounts.length - 1]) is at least amountOutMin. This ensures that the minimum required output token amount is met.
  3. Use TransferHelper.safeTransferFrom to transfer the input tokens. Specifically, transfer the specified input token amount from msg.sender to the address of the first swap pair.
  4. Call _swap to perform the actual token swap. This executes the swap along the specified token path.

swapTokensForExactTokens

Calculates the input token amount required for a specified output token amount, subject to a maximum input limit, and swaps the tokens using that amount.

Parameters

  • amountOut
    • Minimum acceptable output token amount.
  • amountInMax
    • Maximum acceptable input token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline
    • Transaction deadline.

Process

  1. Use UniswapV2Library.getAmountsIn to obtain the array amounts of required token amounts based on the specified output amount and token path. amounts[0] represents the amount at the start of the swap path, and amounts[n] represents the final output token amount.
  2. Verify that the first element of amounts (amounts[0]) is no greater than amountInMax. This ensures that the maximum acceptable input token amount is not exceeded.
  3. Use TransferHelper.safeTransferFrom to transfer the input tokens. Specifically, transfer the input token amount from msg.sender to the first swap pair, subject to the specified maximum.
  4. Call _swap to perform the actual token swap. This executes the swap along the specified token path.

swapExactETHForTokens

Swaps a specified amount of ETH for tokens.

Parameters

  • amountOutMin
    • Minimum acceptable output token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline
    • Transaction deadline.

Process

  1. Verify that the first element of path is WETH (wrapped ETH). This ensures that the specified path starts with ETH and proceeds to tokens.
  2. Use UniswapV2Library.getAmountsOut to calculate the array amounts of token amounts obtained through the swap based on the specified ETH amount and token path. amounts[0] is the ETH amount required for the swap, and amounts[n] is the final token amount obtained through the swap.
  3. Verify that the last element of amounts (amounts[amounts.length - 1]) is at least amountOutMin. This ensures that the desired minimum output token amount is met.
  4. Use IWETH(WETH).deposit{value: amounts[0]}() to wrap the specified ETH amount and receive WETH.
  5. Use assert(IWETH(WETH).transfer(...)) to send WETH to the first swap pair.
  6. Call _swap to perform the token swap. This swaps ETH for tokens along the specified token path.

swapTokensForExactETH

Swaps tokens for ETH using a specified token amount.

Parameters

  • amountOut
    • Minimum acceptable output ETH amount.
  • amountInMax
    • Maximum acceptable input token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the ETH obtained from the swap.
  • deadline
    • Transaction deadline.

Process

  1. Verify that the first element of path is WETH (wrapped ETH). This ensures that the specified path swaps tokens for ETH.
  2. Use UniswapV2Library.getAmountsIn to calculate the array amounts of required token amounts based on the specified output ETH amount and token path. amounts[0] is the input token amount required for the swap, and amounts[n] is the ETH amount obtained at the end of the swap.
  3. Verify that amounts[0] is no greater than amountInMax. This ensures that the swap stays within the specified maximum input token amount.
  4. Use TransferHelper.safeTransferFrom to send the specified input tokens to the pair.
  5. Call _swap to perform the token swap. This swaps tokens for ETH along the specified token path.
  6. Use IWETH(WETH).withdraw to unwrap WETH into ETH and obtain the output ETH amount.
  7. Use TransferHelper.safeTransferETH to send the output ETH amount to the specified address.

swapExactTokensForETH

Swaps tokens for ETH using a specified token amount.

Parameters

  • amountIn
    • Minimum acceptable input token amount.
  • amountInMax
    • Minimum acceptable ETH amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the ETH obtained from the swap.
  • deadline
    • Transaction deadline.

Process

  1. Verify that the first element of path is WETH (wrapped ETH). This ensures that the specified path swaps tokens for ETH.
  2. Use UniswapV2Library.getAmountsOut to calculate the array amounts of amounts along the token path and the ETH output obtained through the swap. amounts[0] represents the amount at the input side of the swap, and amounts[n] is the ETH amount obtained at the end of the swap.
  3. Verify that amounts[n] is at least amountOutMin. This ensures that the swap meets the specified minimum output ETH amount.
  4. Use TransferHelper.safeTransferFrom to send the specified input tokens to the pair.
  5. Call _swap to perform the token swap. This swaps tokens for ETH along the specified token path.
  6. Use IWETH(WETH).withdraw to unwrap WETH into ETH and obtain the output ETH amount.
  7. Use TransferHelper.safeTransferETH to send the output ETH amount to the specified address.

swapETHForExactTokens

Obtains tokens using a specified amount of ETH.

Parameters

  • amountOut
    • Minimum acceptable output token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline
    • Transaction deadline.

Process

  1. Verify that the first element of path is WETH (wrapped ETH). This ensures that the specified path starts with ETH and proceeds to tokens.
  2. Use UniswapV2Library.getAmountsIn to calculate the array amounts of required amounts based on the specified output token amount and token path. amounts[0] is the input ETH amount required for the swap, and amounts[n] represents the amount at the output end of the path.
  3. Verify that amounts[0] is no greater than msg.value. This ensures that the swap does not exceed the ETH supplied as input.
  4. Use IWETH(WETH).deposit to wrap ETH and hold the input ETH amount as WETH.
  5. Use IWETH(WETH).transfer to send WETH to the specified pair. This enables the swap from WETH to tokens.
  6. Call _swap to perform the token swap. This swaps ETH for tokens along the specified token path.
  7. If the actual ETH sent exceeds the required input ETH amount, refund the excess ETH to the sender.

_swapSupportingFeeOnTransferTokens

Executes a swap that supports fee-on-transfer tokens.

Parameters

  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.

Process

  1. Use a for loop to execute each swap along the path in order.
  2. Inside the loop, assign the current and next elements of path to input and output.
  3. Use UniswapV2Library.sortTokens to determine the ordering of input and output as token0 and token1.
  4. Use the IUniswapV2Pair interface to retrieve the reserves (amounts held) of the swap pair.
  5. Use IERC20(input).balanceOf(address(pair)) to retrieve the balance of the input token held by the swap pair. Subtract the reserve from this balance to determine amountInput, the token amount supplied for the swap.
  6. Use UniswapV2Library.getAmountOut to calculate the amount of output tokens obtained by swapping amountInput input tokens.
  7. Set amount0Out and amount1Out according to the ordering of the input and output tokens.
  8. Use UniswapV2Library.pairFor to calculate the next pair address and determine the recipient to for the swap result.
  9. Use pair.swap to execute the actual token swap. This sends the swapped tokens to to.

swapExactTokensForTokensSupportingFeeOnTransferTokens

Swaps a fixed quantity of tokens for another token while supporting fee-on-transfer tokens.

Parameters

  • amountIn
    • Amount of input tokens to swap.
  • amountOutMin - Minimum acceptable output token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline - Transaction deadline.

Process

  1. Use TransferHelper.safeTransferFrom to transfer the input tokens from msg.sender. The amount transferred is specified by amountIn.
  2. Use UniswapV2Library.pairFor to calculate the address of the token pair for the swap. Send the input tokens to this address.
  3. Before the swap, retrieve the path[path.length - 1] token balance at address to and store it as balanceBefore.
  4. Call _swapSupportingFeeOnTransferTokens to swap the tokens while supporting fee-on-transfer tokens.
  5. After the swap, retrieve the path[path.length - 1] token balance at to again and calculate the increase in tokens obtained through the swap.
  6. Compare the increase with amountOutMin to verify that enough tokens were received. If the amount is insufficient, revert with an error.

swapExactETHForTokensSupportingFeeOnTransferTokens

Swaps a fixed amount of ETH for another token while supporting fee-on-transfer tokens.

Parameters

  • amountOutMin - Minimum acceptable output token amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline - Transaction deadline.

Process

  1. Verify that path[0] is WETH (Wrapped Ether). WETH is a wrapped version of ETH represented as a token on Ethereum.
  2. Store the ETH amount obtained from msg.value as amountIn.
  3. Use IWETH(WETH).deposit to wrap ETH into WETH, with amountIn representing the WETH amount.
  4. Use IWETH(WETH).transfer to send WETH to the first swap pair, whose input token is path[0].
  5. Before the swap, retrieve the path[path.length - 1] token balance at to and store it as balanceBefore.
  6. Call _swapSupportingFeeOnTransferTokens to swap the tokens while supporting fee-on-transfer tokens.
  7. After the swap, retrieve the path[path.length - 1] token balance at to again and calculate the increase in tokens obtained through the swap.
  8. Compare that increase with amountOutMin to verify that the minimum output amount is met. If it is not met, revert with an error.

swapExactTokensForETHSupportingFeeOnTransferTokens

Swaps a fixed quantity of tokens for ETH while supporting fee-on-transfer tokens.

Parameters

  • amountIn
    • Amount of tokens to swap.
  • amountOutMin - Minimum acceptable output ETH amount.
  • path - Array specifying the swap path. - The path specifies the token order from the input token to the output token.
  • to - Address receiving the swapped tokens.
  • deadline - Transaction deadline.

Process

  1. Verify that path[path.length - 1] is WETH (Wrapped Ether). WETH represents ETH in token form.
  2. Send amountIn of the token at path[0] to the specified pair.
  3. Call _swapSupportingFeeOnTransferTokens to swap the tokens while supporting fee-on-transfer tokens.
  4. After the swap, retrieve the WETH balance at address(this) and store it as amountOut.
  5. Verify that amountOut meets the minimum amount amountOutMin. If it is not met, revert with an error.
  6. Use IWETH(WETH).withdraw to unwrap WETH into ETH and withdraw that amount.
  7. Use TransferHelper.safeTransferETH to send ETH to the specified address to.

Events

None in particular.

Code

Due to the article's length limit, functions shared with UniswapV2Router01 are omitted.

IUniswapV2Router02

IUniswapV2Router02
solidity
interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

UniswapV2Router02

UniswapV2Router02
solidity
contract UniswapV2Router02 is IUniswapV2Router02 {
    using SafeMath for uint;

    address public immutable override factory;
    address public immutable override WETH;

    modifier ensure(uint deadline) {
        require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
        _;
    }

    constructor(address _factory, address _WETH) public {
        factory = _factory;
        WETH = _WETH;
    }

    receive() external payable {
        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
    }

    // **** ADD LIQUIDITY ****
    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);
            }
        }
    }
    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);
    }
    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);
    }

    // **** REMOVE LIQUIDITY ****
    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');
    }
    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);
    }
    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);
    }
    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);
    }

    // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
    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);
    }
    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
        );
    }

    // **** SWAP ****
    // requires the initial amount to have already been sent to the first pair
    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)
            );
        }
    }
    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);
    }
    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);
    }
    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);
    }
    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]);
    }
    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]);
    }
    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]);
    }

    // **** SWAP (supporting fee-on-transfer tokens) ****
    // requires the initial amount to have already been sent to the first pair
    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));
        }
    }
    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'
        );
    }
    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'
        );
    }
    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);
    }

    // **** LIBRARY FUNCTIONS ****
    function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
        return UniswapV2Library.quote(amountA, reserveA, reserveB);
    }

    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
        public
        pure
        virtual
        override
        returns (uint amountOut)
    {
        return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
    }

    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
        public
        pure
        virtual
        override
        returns (uint amountIn)
    {
        return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
    }

    function getAmountsOut(uint amountIn, address[] memory path)
        public
        view
        virtual
        override
        returns (uint[] memory amounts)
    {
        return UniswapV2Library.getAmountsOut(factory, amountIn, path);
    }

    function getAmountsIn(uint amountOut, address[] memory path)
        public
        view
        virtual
        override
        returns (uint[] memory amounts)
    {
        return UniswapV2Library.getAmountsIn(factory, amountOut, path);
    }
}

SafeMath

SafeMath
solidity
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)

library SafeMath {
    function add(uint x, uint y) internal pure returns (uint z) {
        require((z = x + y) >= x, 'ds-math-add-overflow');
    }

    function sub(uint x, uint y) internal pure returns (uint z) {
        require((z = x - y) <= x, 'ds-math-sub-underflow');
    }

    function mul(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
    }
}

UniswapV2Library

UniswapV2Library
solidity
library UniswapV2Library {
    using SafeMath for uint;

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    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');
    }

    // calculates the CREATE2 address for a pair without making any external calls
    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
            ))));
    }

    // fetches and sorts the reserves for a pair
    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 some amount of an asset and pair reserves, returns an equivalent amount of the other asset
    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;
    }

    // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
    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;
    }

    // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
    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);
    }

    // performs chained getAmountOut calculations on any number of pairs
    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);
        }
    }

    // performs chained getAmountIn calculations on any number of pairs
    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);
        }
    }
}

Conclusion

In this article, we examined the UniswapV2Router02 contract in Uniswap V2 using Bunzz’s DeCipher feature. I hope you found it useful. I plan to continue covering selected NFTs and contracts.

I also publish blockchain and AI articles on my blog and Qiita if you would like to explore them.

https://chaldene.net/