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.
addLiquidityrequires the addresses of two tokens, the desired and minimum amounts for each token, the address receiving the liquidity tokens, and a deadline.addLiquidityETHis 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
-
mintis used to mint liquidity tokens. -
burnis used to burn liquidity tokens. -
skimis used to remove excess tokens mistakenly sent to the contract. -
syncis 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
address public immutable override WETH;Constant storing the WETH token contract address.
factory
address public immutable override factory;Constant storing the Factory contract address.
Modifiers
ensure
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.
- Check the
deadlineparameter. - If the current block timestamp is later than
deadline, the condition is considered unsatisfied. - If the condition is not satisfied, an exception is raised with the error message UniswapV2Router: EXPIRED.
- If the condition is satisfied, execution proceeds through _; in the modifier.
Other functionality
constructor
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
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.
- It is automatically called when ETH is sent to this contract from outside.
- The
assertstatement raises an exception when its condition is false. In this case, the condition ismsg.sender == WETH. - The condition
msg.sender == WETHchecks whether the address sending Ether is the WETH contract. - If the sender is not the WETH contract, the condition fails, an exception occurs, and the transaction is reverted.
- 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
- Calculate the amount of token B equivalent to the specified amount of token A based on the reserves of tokens A and B.
- 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
- Calculate the expected output amount for the specified input amount based on the input and output token reserves.
- 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
- Calculate the required input token amount for the specified output amount based on the input and output token reserves.
- 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
- Using the specified input token amount and token path, calculate the expected amount of each token in the
patharray. - Return the array of calculated expected amounts as
amounts. - This array contains the amount of each token in the
patharray 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
- Using the specified output token amount and token path, calculate the required amount of each token in the
patharray. - Return the array of calculated required amounts as
amounts. - This array contains the amount of each token in the
patharray 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
- 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.
- Retrieve the reserves of the specified tokens A and B.
- If both token reserves are zero, use the desired deposit amounts directly.
- 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.
- 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
- Check the deadline.
The
ensuremodifier is applied to ensure that the transaction is executed before the deadline. - Call the internal
_addLiquidityfunction to calculate the optimal trade amounts and token quantities to supply based on the specified parameters. - Once the amounts of tokens A and B have been calculated, use
TransferHelper.safeTransferFromto transfer the tokens to the specified liquidity pool. - Finally, call
IUniswapV2Pair(pair).mint(to)to mint liquidity tokens using the calculated amounts and the specified recipient addressto. 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
- Check the deadline.
The
ensuremodifier is applied to ensure that the transaction is executed before the deadline. - Call the internal
_addLiquidityfunction 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. - Once the token and ETH amounts have been calculated, use
TransferHelper.safeTransferFromto transfer the token to the specified liquidity pool. To handle ETH, it also callsIWETH(WETH).deposit{value: amountETH}()andIWETH(WETH).transfer(pair, amountETH)internally. - Finally, call
IUniswapV2Pair(pair).mint(to)to mint liquidity tokens using the calculated amounts and the specified recipient addressto. This operation mints new liquidity tokens and sends them to the liquidity provider. - 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
- Check the deadline.
The
ensuremodifier is applied to ensure that the transaction is executed before the deadline. - Calculate the address of the corresponding liquidity pool using the addresses of tokens A and B.
- 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. - Call
IUniswapV2Pair(pair).burn(to)to withdraw tokens A and B from the pool to the specified recipient addressto. This operation calculates the amounts of tokens A and B. - Sort the addresses of tokens A and B to determine which corresponds to token A.
Assign the quantities to
amountAandamountBaccordingly. - Finally, check
amountAMinandamountBMinto 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
- Check the deadline.
The
ensuremodifier is applied to ensure that the transaction is executed before the deadline. - Call the internally defined
removeLiquidityfunction to remove the specified amount of liquidity for the token and ETH pair. In addition to the specifiedtokenargument, pass WETH (wrapped ETH) as an argument. - Use
amountTokenandamountETHreturned byremoveLiquidityto send the specified amounts of tokens and ETH to the recipient addressto. - 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. - Finally, use
TransferHelper.safeTransferETH(to, amountETH)to send the specified amount of ETH to the recipient addressto. 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; iffalse, it covers the amount specified byliquidity.
v,r,s- Signature parameters.
Process
- Use the addresses of
tokenAandtokenBto obtain the pool's pair address inpair. - If
approveMaxistrue, setvalueto the maximum (2^256 - 1); otherwise, use the value ofliquidity. This specifies the token allowance amount. - Call
IUniswapV2Pair'spermitfunction to use the authorization signed in advance by the token owner. - Call
removeLiquidityto perform the actual token withdrawal. This function withdraws tokens while taking the token amounts and minimum acceptable amounts into account. - Finally, assign the amounts of withdrawn tokens to
amountAandamountB, 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; iffalse, it covers the amount specified byliquidity.
v,r,s- Signature parameters.
Process
- Use the addresses of
tokenand WETH (wrapped Ether) to obtain the pool's pair address inpair. - If
approveMaxistrue, setvalueto the maximum (2^256 - 1); otherwise, use the value ofliquidity. This specifies the token allowance amount. - Call
IUniswapV2Pair'spermitfunction to use the authorization signed in advance by the token owner. - Call
removeLiquidityETHto 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. - Finally, assign the amounts of withdrawn tokens and ETH to
amountTokenandamountETH, 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
- Call
removeLiquidityto withdraw the token and ETH. The function's return value,amountETH, indicates the amount of ETH withdrawn. - Retrieve the token balance and use
TransferHelper.safeTransferto send the tokens to the specified address. This prepares for the receipt of fee-on-transfer tokens. - Call the WETH contract's
withdrawfunction to unwrap the withdrawn ETH back into native Ether. - Use
TransferHelper.safeTransferETHto 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; iffalse, it covers the amount specified byliquidity.
v,r,s- Signature parameters.
Process
- Use
pairForto obtain the address of the token and WETH pair. - Set the amount authorized by
permitaccording toapproveMax. IfapproveMaxistrue, grant an unlimited allowance; iffalse, authorize the amount specified byliquidity. - Call the
permitfunction of the IUniswapV2Pair interface to authorize token spending. This grants the approval used for the fee-on-transfer token withdrawal. - Call
removeLiquidityETHSupportingFeeOnTransferTokensto 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 andamounts[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
- Repeat
path.length - 1times, which is the number of elements inpathminus1. This processes each consecutive token pair in the path. - Retrieve the current and next tokens as
inputandoutput, and determine their sorted order. Sorting determines the correct ordering of the tokens in the pair. - Set the output token amount for this swap to
amountOut. - Determine whether
inputoroutputis token0and setamount0Outandamount1Outaccordingly. This accounts for the different token output amounts associated with the swap pair. - Determine the recipient address
tofor the swap result based on the current and next tokens. Ifiis less thanpath.length - 2, use the next pair's address; otherwise, use_to. - Use
UniswapV2Library.pairForto obtain the pair address for the current and next tokens. - Call
swapon the IUniswapV2Pair interface to perform the token swap. The appropriate token amounts are swapped according toamount0Outandamount1Out.
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
- Use
UniswapV2Library.getAmountsOutto obtain the arrayamountsof 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, andamounts[n]represents the final output token amount. - Verify that the last element of
amounts(amounts[amounts.length - 1]) is at leastamountOutMin. This ensures that the minimum required output token amount is met. - Use
TransferHelper.safeTransferFromto transfer the input tokens. Specifically, transfer the specified input token amount frommsg.senderto the address of the first swap pair. - Call
_swapto 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
- Use
UniswapV2Library.getAmountsInto obtain the arrayamountsof required token amounts based on the specified output amount and token path.amounts[0]represents the amount at the start of the swap path, andamounts[n]represents the final output token amount. - Verify that the first element of
amounts(amounts[0]) is no greater thanamountInMax. This ensures that the maximum acceptable input token amount is not exceeded. - Use
TransferHelper.safeTransferFromto transfer the input tokens. Specifically, transfer the input token amount frommsg.senderto the first swap pair, subject to the specified maximum. - Call
_swapto 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
- Verify that the first element of
pathis WETH (wrapped ETH). This ensures that the specified path starts with ETH and proceeds to tokens. - Use
UniswapV2Library.getAmountsOutto calculate the arrayamountsof 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, andamounts[n]is the final token amount obtained through the swap. - Verify that the last element of
amounts(amounts[amounts.length - 1]) is at leastamountOutMin. This ensures that the desired minimum output token amount is met. - Use
IWETH(WETH).deposit{value: amounts[0]}()to wrap the specified ETH amount and receive WETH. - Use
assert(IWETH(WETH).transfer(...))to send WETH to the first swap pair. - Call
_swapto 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
- Verify that the first element of
pathis WETH (wrapped ETH). This ensures that the specified path swaps tokens for ETH. - Use
UniswapV2Library.getAmountsInto calculate the arrayamountsof required token amounts based on the specified output ETH amount and token path.amounts[0]is the input token amount required for the swap, andamounts[n]is the ETH amount obtained at the end of the swap. - Verify that
amounts[0]is no greater thanamountInMax. This ensures that the swap stays within the specified maximum input token amount. - Use
TransferHelper.safeTransferFromto send the specified input tokens to the pair. - Call
_swapto perform the token swap. This swaps tokens for ETH along the specified token path. - Use
IWETH(WETH).withdrawto unwrap WETH into ETH and obtain the output ETH amount. - Use
TransferHelper.safeTransferETHto 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
- Verify that the first element of
pathis WETH (wrapped ETH). This ensures that the specified path swaps tokens for ETH. - Use
UniswapV2Library.getAmountsOutto calculate the arrayamountsof 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, andamounts[n]is the ETH amount obtained at the end of the swap. - Verify that
amounts[n]is at leastamountOutMin. This ensures that the swap meets the specified minimum output ETH amount. - Use
TransferHelper.safeTransferFromto send the specified input tokens to the pair. - Call
_swapto perform the token swap. This swaps tokens for ETH along the specified token path. - Use
IWETH(WETH).withdrawto unwrap WETH into ETH and obtain the output ETH amount. - Use
TransferHelper.safeTransferETHto 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
- Verify that the first element of
pathis WETH (wrapped ETH). This ensures that the specified path starts with ETH and proceeds to tokens. - Use
UniswapV2Library.getAmountsInto calculate the arrayamountsof required amounts based on the specified output token amount and token path.amounts[0]is the input ETH amount required for the swap, andamounts[n]represents the amount at the output end of the path. - Verify that
amounts[0]is no greater thanmsg.value. This ensures that the swap does not exceed the ETH supplied as input. - Use
IWETH(WETH).depositto wrap ETH and hold the input ETH amount as WETH. - Use
IWETH(WETH).transferto send WETH to the specified pair. This enables the swap from WETH to tokens. - Call
_swapto perform the token swap. This swaps ETH for tokens along the specified token path. - 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
- Use a
forloop to execute each swap along the path in order. - Inside the loop, assign the current and next elements of
pathtoinputandoutput. - Use
UniswapV2Library.sortTokensto determine the ordering ofinputandoutputastoken0andtoken1. - Use the IUniswapV2Pair interface to retrieve the reserves (amounts held) of the swap pair.
- Use
IERC20(input).balanceOf(address(pair))to retrieve the balance of theinputtoken held by the swap pair. Subtract the reserve from this balance to determineamountInput, the token amount supplied for the swap. - Use
UniswapV2Library.getAmountOutto calculate the amount ofoutputtokens obtained by swappingamountInputinput tokens. - Set
amount0Outandamount1Outaccording to the ordering of theinputandoutputtokens. - Use
UniswapV2Library.pairForto calculate the next pair address and determine the recipienttofor the swap result. - Use
pair.swapto execute the actual token swap. This sends the swapped tokens toto.
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
- Use
TransferHelper.safeTransferFromto transfer the input tokens frommsg.sender. The amount transferred is specified byamountIn. - Use
UniswapV2Library.pairForto calculate the address of the token pair for the swap. Send the input tokens to this address. - Before the swap, retrieve the
path[path.length - 1]token balance at addresstoand store it asbalanceBefore. - Call
_swapSupportingFeeOnTransferTokensto swap the tokens while supporting fee-on-transfer tokens. - After the swap, retrieve the
path[path.length - 1]token balance attoagain and calculate the increase in tokens obtained through the swap. - Compare the increase with
amountOutMinto 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
- Verify that
path[0]is WETH (Wrapped Ether). WETH is a wrapped version of ETH represented as a token on Ethereum. - Store the ETH amount obtained from
msg.valueasamountIn. - Use
IWETH(WETH).depositto wrap ETH into WETH, withamountInrepresenting the WETH amount. - Use
IWETH(WETH).transferto send WETH to the first swap pair, whose input token ispath[0]. - Before the swap, retrieve the
path[path.length - 1]token balance attoand store it asbalanceBefore. - Call
_swapSupportingFeeOnTransferTokensto swap the tokens while supporting fee-on-transfer tokens. - After the swap, retrieve the
path[path.length - 1]token balance attoagain and calculate the increase in tokens obtained through the swap. - Compare that increase with
amountOutMinto 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
- Verify that
path[path.length - 1]is WETH (Wrapped Ether). WETH represents ETH in token form. - Send
amountInof the token atpath[0]to the specified pair. - Call
_swapSupportingFeeOnTransferTokensto swap the tokens while supporting fee-on-transfer tokens. - After the swap, retrieve the WETH balance at
address(this)and store it asamountOut. - Verify that
amountOutmeets the minimum amountamountOutMin. If it is not met, revert with an error. - Use
IWETH(WETH).withdrawto unwrap WETH into ETH and withdraw that amount. - Use
TransferHelper.safeTransferETHto send ETH to the specified addressto.
Events
None in particular.
Code
Due to the article's length limit, functions shared with UniswapV2Router01 are omitted.
IUniswapV2Router02
IUniswapV2Router02
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
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
// 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
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.






