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 explore UniswapV2Router01 from Uniswap V2 using Bunzz's DeCipher feature.
As noted in the official documentation, UniswapV2Router01 is deprecated, and UniswapV2Router02 is recommended instead.
UniswapV2Router01 should not be used any longer, because of the discovery of a low severity bug and the fact that some methods do not work with tokens that take fees on transfer. The current recommendation is to use UniswapV2Router02.
DeCipher is a service that automatically generates smart contract documentation using AI.
For a detailed guide to using the service, see the following article.
This article reflects my personal experience with DeCipher. If you notice any inaccuracies, please let me know in the comments.
The following is the DeCipher link used in this article.
Overview
UniswapV2Router01 is an important historical component of Uniswap, a decentralized exchange (DEX) protocol built on Ethereum. It facilitates adding liquidity to Uniswap and swapping tokens. It provides users with a standardized interface for interacting with the Uniswap protocol.
Contract purpose
The main purpose of UniswapV2Router01 is to provide an interface for interacting with the Uniswap protocol. This includes adding liquidity, swapping tokens, and withdrawing liquidity. The contract is designed to accommodate different tokens within the Uniswap ecosystem.
Contract responsibilities
UniswapV2Router01 has several principal responsibilities.
Adding liquidity
The contract provides functions for adding liquidity to Uniswap. This involves depositing a pair of tokens into a particular liquidity pool. The contract ensures that the appropriate amounts of both tokens are deposited and that the transaction is processed correctly.
Token swaps
The contract also supports token swaps. Tokens are exchanged based on the current reserves and exchange rate of the liquidity pool. The contract coordinates the swap and the corresponding token transfers.
Withdrawing liquidity
The contract allows users to withdraw liquidity from the exchange. This involves redeeming a specified amount of liquidity tokens in exchange for the underlying tokens. The contract coordinates the withdrawal so that the user receives the appropriate amounts of both tokens.
Interfacing with ERC20 tokens
The contract interacts with ERC20 tokens, a standard token type used on Ethereum. This involves token transfers, spending approvals, and checking account balances.
Transaction validity
The contract incorporates several safeguards to check transaction validity. These include checking that the deadline has not passed and that token amounts satisfy the specified conditions.
In summary, UniswapV2Router01 is a historical component of Uniswap that provides a standardized interface to the exchange. It coordinates transaction processing, liquidity deposits, and withdrawals, subject to the limitations noted in the deprecation warning above.
Usage
UniswapV2Router01 is part of Uniswap, a constant-product automated liquidity protocol implemented as a system of non-upgradeable smart contracts on Ethereum. The protocol aims to provide a decentralized, composable financial foundation on which anyone can create new markets.
A constant-product automated liquidity protocol provides a mechanism for decentralized exchanges (DEXs) and liquidity pools. Specifically, a pool enables exchanges between two tokens, typically of different types, at a rate determined by its reserves rather than a fixed 1:1 price. The key idea is that the product of the reserves of token A and token B is maintained by the constant-product invariant, excluding fee effects and liquidity changes. For example, reserves of 10 units of token A and 100 units of token B have a product of 1,000. In a simplified fee-free swap model, this product remains constant.
When a user exchanges token A for token B, the pool's reserve of token A increases and its reserve of token B decreases. Because the product remains constant in the simplified model, the exchange price is determined by the reserve ratio. This provides a mechanism for prices to adjust automatically as supply and demand change.
Users can also earn fees by supplying their tokens to a liquidity pool. Liquidity deposits adjust token reserves according to the pool's required ratio.
The advantage of this protocol is that exchange prices adjust automatically with supply and demand, without requiring market makers or liquidity providers to continuously manage individual orders. This enables a more decentralized and efficient trading environment.
UniswapV2Router01 aims to facilitate interactions with Uniswap V2 pairs. It provides functions for adding liquidity, removing liquidity, and swapping tokens.
The following steps describe how the contract works.
1. Deploy the contract
Deploy the historical UniswapV2Router01 contract to Ethereum. The constructor requires the addresses of the Uniswap factory and WETH contracts.
2. Add liquidity
Call addLiquidity or addLiquidityETH to add liquidity to a pair.
The call specifies the relevant token addresses, desired and minimum token amounts, the liquidity token recipient, and a deadline.
3. Remove liquidity
Call removeLiquidity or removeLiquidityETH to remove liquidity from a pair.
The call specifies the relevant token addresses, the amount of liquidity tokens to redeem, minimum received amounts, the recipient, and a deadline.
4. Swap tokens
Call swapExactTokensForTokens, swapTokensForExactTokens, swapExactETHForTokens, swapTokensForExactETH, swapExactTokensForETH, or swapETHForExactTokens to swap tokens.
Depending on the function, supply the input and output amount constraints, token path, output recipient, and deadline.
5. Handle received ETH
The contract implements a fallback function to accept ETH received from the WETH contract.
Functions that pull ERC20 tokens from the caller require prior approval from the token contract.
Call the token contract's approve with the UniswapV2Router01 contract address and the amount to approve.
Parameters
_factory
Address of the UniswapV2Factory contract. Used to create new token pairs and retrieve existing pairs.
For more about UniswapV2Factory, see the following resource.
_WETH
Address of the Wrapped Ether (WETH) contract. Used as the wrapped native currency in relevant Uniswap trading pairs. In other words, WETH represents Ethereum's ETH in token form, allowing it to be handled as a token within Uniswap.
Constants and modifiers
Constants
WETH
address public immutable override WETH;A constant containing the WETH token contract address.
factory
address public immutable override factory;A constant containing the Factory contract address.
Modifiers
ensure
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}A modifier that checks whether a supplied deadline remains valid before an operation and rejects the operation if the deadline has passed.
- Check the
deadlinepassed as an argument. - If the current block timestamp is later than
deadline, the condition is not satisfied. - If the condition fails, revert with the error message UniswapV2Router: EXPIRED.
- If the condition succeeds, execute the function body at the modifier's
_;placeholder.
Other components
constructor
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}Receives the WETH and Factory contract addresses as arguments and stores them.
receive
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}Provides a mechanism for accepting Ether only when sent by the WETH contract.
- The fallback is invoked automatically when ETH is sent to the contract.
- The
assertstatement raises an exception if its condition is not satisfied. In this case, the condition ismsg.sender == WETH. - The expression
msg.sender == WETHchecks whether the sender of the Ether is the WETH contract. - If the sender is not the WETH contract, the condition fails and the transaction is aborted.
- If the sender is the WETH contract, the condition succeeds and the ETH is accepted.
Functions
READ
getAmountIn
Calculates the input amount (amountIn) required to obtain a specified output amount (amountOut) in a token swap.
Parameters
amountOut- Target output token amount.
reserveIn- Input token reserve in the token pair.
- The reserve of the token supplied by the user in the swap.
reserveOut- Output token reserve in the token pair.
- The reserve of the token the user wishes to receive.
getAmountOut
Calculates the output token amount (amountOut) received when swapping a specified input amount (amountIn).
Parameters
amountOut- Input token amount for the swap.
reserveIn- Input token reserve in the token pair.
- The reserve of the token supplied by the user.
reserveOut- Output token reserve in the token pair.
- The reserve of the token the user wishes to receive.
getAmountsIn
Calculates the input token amount required to obtain a specified output token amount along a token path. Use this function to determine the required input amount for a desired swap output.
Parameters
amountOut- Target output token amount.
- The amount of the output token that the user wants to receive.
path- Token path.
- Array of addresses specifying the order of tokens in the swap.
For example, suppose a user wants to swap along the following token path.
Token path: [TokenA, TokenB, TokenC]
Output amount: 100 TokenC
This path starts with TokenA, passes through TokenB, and ends with TokenC.
The returned amounts array contains the required amount at each point in the path.
For example, amounts[0] is the required amount of TokenA and amounts[1] is the required amount of TokenB.
getAmountsOut
Calculates the output amount obtainable from a specified input amount along a token path.
Parameters
amountIn- Input token amount.
- The amount of tokens the user can supply.
path- Token path.
- Array of addresses specifying the order of tokens in the swap.
For example, suppose a user wishes to perform a swap along a particular token path.
The function returns an amounts array containing the expected output amounts for the token pairs along the path.
This allows the amounts involved in a swap to be estimated.
quote
Calculates the amount of token B corresponding to a given amount of token A based on their current Uniswap V2 pool reserves.
Parameters
amountA- Amount of token A.
reserveA- Current reserve of token A in the Uniswap V2 pool.
reserveB- Current reserve of token B in the Uniswap V2 pool.
It calculates the corresponding amount of token B using the given amount of token A and the current reserve ratio.
The result is returned as amountB. This is a proportional quote, not the fee- and price-impact-adjusted swap output.
WRITE
addLiquidity
Allows a user to add liquidity to a token pair on the decentralized exchange.
Parameters
tokenA- Address of the first token in the pair.
tokenB- Address of the second token in the pair.
amountADesired- Desired amount of token A to add as liquidity.
amountBDesired- Desired amount of token B to add as liquidity.
amountAMin- Minimum acceptable amount of token A to add.
amountBMin- Minimum acceptable amount of token B to add.
to- Address to receive the minted liquidity tokens.
deadline- Transaction deadline timestamp.
Return values
amountA- Actual amount of token A added as liquidity.
amountB- Actual amount of token B added as liquidity.
liquidity- Amount of liquidity tokens minted.
Provide liquidity by specifying the desired amounts of token A and token B. Also specify the minimum acceptable amounts of token A and token B to constrain execution. Liquidity tokens are minted and sent to the specified address. The transaction must execute by the specified deadline. It is invalid after the deadline has passed.
- Call
_addLiquidityto calculate the amounts of token A and token B to add. - Calculate and retrieve the pair address.
- Transfer the specified amounts of token A and token B from the user to the pair.
- Mint liquidity tokens through the pair and retrieve the amount minted.
amountAMin and amountBMin are useful in situations such as the following.
Limiting slippage from price changes
Because token prices fluctuate, the amounts added at execution may differ from the user's expectations.
For example, a sudden change in token A's price may result in less favorable execution conditions.
Setting amountAMin provides a degree of protection against such changes.
Improving execution reliability
An appropriate amountAMin helps protect against unfavorable conditions caused by other transactions or price changes.
By specifying minimum acceptable amounts, users can constrain the conditions under which a transaction succeeds.
Protection against manipulation Minimum transaction conditions can mitigate the impact of malicious attempts to distort execution prices.
addLiquidityETH
Adds liquidity to a token pair using a token and ETH, subject to minimum amount constraints.
Parameters
token- Address of the token to add as liquidity.
amountTokenDesired- Desired token amount to add as liquidity.
amountTokenMin- Minimum acceptable token amount.
amountETHMin- Minimum acceptable ETH amount.
to- Address receiving the liquidity tokens.
deadline- Transaction deadline timestamp.
Return values
amountToken- Actual token amount added.
amountETH- Actual ETH amount added.
liquidity- Amount of liquidity tokens minted.
Users can provide liquidity by specifying the desired token amount and supplying ETH subject to the minimum amount constraints. The actual token and ETH amounts are calculated using the desired amounts, minimum amounts, and current pool reserves. The corresponding liquidity tokens are minted to the address specified by the user.
- Call
_addLiquidityto calculate the token and ETH amounts to add. - Calculate and retrieve the pair address.
- Transfer the specified token amount from the user to the pair.
- Wrap ETH into WETH and transfer it to the pair.
- Mint liquidity tokens through the pair and retrieve the amount minted.
- Refund any excess ETH to the user.
removeLiquidity
Removes liquidity from a reserve pool.
Parameters
tokenA- Address of one token in the pool.
tokenB- Address of the other token in the pool.
liquidity- Amount of liquidity to remove.
amountAMin- Minimum amount of token A to receive.
amountBMin- Minimum amount of token B to receive.
to- Token recipient address.
deadline- Transaction deadline timestamp.
- Check whether the deadline has passed and revert if it has.
- Calculate and retrieve the pair address.
- Transfer the specified liquidity tokens from the user to the pair.
- Burn the liquidity tokens through the pair and retrieve the resulting token amounts.
- Sort the token A and token B addresses.
- Assign the returned amounts to their corresponding tokens.
- Check whether the withdrawn amounts meet the user's minimum requirements. If the conditions fail, the transaction reverts.
- If the conditions are satisfied, return the amounts withdrawn.
removeLiquidityETH
Removes liquidity from a token and ETH pair.
Parameters
token- Address of the token whose liquidity is being removed.
liquidity- Amount of liquidity tokens to redeem.
amountTokenMin- Minimum token amount to receive.
amountETHMin- Minimum ETH amount to receive.
to- Address receiving the token and ETH.
deadline- Transaction deadline timestamp.
- Retrieve the token and WETH amounts obtained by redeeming the liquidity tokens.
- Check the minimum token and ETH amounts to receive. If these conditions are not satisfied, the transaction reverts.
- Send the withdrawn tokens to the specified address (
to). - Unwrap the withdrawn WETH into ETH.
- Send the resulting ETH to
to.
removeLiquidityETHWithPermit
Authorizes and executes the removal of liquidity from an ERC20 token and ETH pair. The user can authorize the router using a signature, remove liquidity, and constrain the amounts of tokens and ETH received.
Parameters
token- Address of the token whose liquidity is being removed.
liquidity- Amount of liquidity tokens to redeem.
amountTokenMin- Minimum token amount to receive.
amountETHMin- Minimum ETH amount to receive.
to- Address receiving the token and ETH.
deadline- Transaction deadline timestamp.
approveMax- Flag indicating whether to approve the maximum amount.
v,r,s- Signature parameters used to grant approval.
- Retrieve the address of the specified token and WETH pair.
- If
approveMaxistrue, set the permitted liquidity token amount to the maximum value (unlimited approval). Otherwise, use the specified liquidity token amount. - Call
IUniswapV2Pair.permitto authorize the router to spend the user's liquidity tokens after signature verification. - Call
removeLiquidityETHto remove liquidity from the specified token and ETH pair. - Retrieve the withdrawn token and ETH amounts.
removeLiquidityWithPermit
Authorizes and executes the removal of ERC20 token pair liquidity.
Parameters
tokenA- Address of token A whose liquidity is being removed.
tokenB- Address of token B whose liquidity is being removed.
liquidity- Amount of liquidity tokens to redeem.
amountAMin- Minimum token A amount to receive.
amountBMin- Minimum token B amount to receive.
to- Token recipient address.
deadline- Transaction deadline timestamp.
approveMax- Flag indicating whether to approve the maximum amount.
v,r,s- Signature parameters used to grant approval.
- Retrieve the
paircontract address identifying the specified token A and token B pair. - Set the
valuevariable to either the specified liquidity amount or the maximum value based onapproveMax. - Use the IUniswapV2Pair(pair) interface to call
permitand grant the user's approval. This authorizes the router to remove the user's liquidity. - Call
removeLiquidityto remove the liquidity. - Retrieve token A and token B and return their amounts.
swapETHForExactTokens
Exchanges ETH for an exact specified amount of tokens.
Parameters
amountOut- Exact token amount the user wishes to receive.
path- Array of addresses specifying the swap path.
- The first address is WETH, representing the supplied ETH, and the last is the output token.
to- Address receiving the exchanged tokens.
deadline- Transaction deadline timestamp.
The router coordinates the swap through the relevant pair contracts.
swapExactETHForTokens
Swaps an exact amount of ETH for at least a minimum token amount.
Parameters
amountOutMin- Minimum token amount expected from the swap.
path- Array of addresses specifying the swap path.
- The first address is WETH, representing the supplied ETH, and the last is the desired output token.
to- Address receiving the exchanged tokens.
deadline- Transaction deadline timestamp.
amountOutMin specifies the minimum amount of tokens the user is willing to receive.
swapExactTokensForETH
Swaps an exact amount of tokens for ETH. It provides a procedure for exchanging a specified token amount for at least the minimum expected amount of ETH.
Parameters
amountIn- Amount of tokens to exchange.
amountOutMin- Minimum ETH amount expected from the swap.path- Array of addresses specifying the swap path. - The first address is the input token and the last is WETH.to- Address receiving the exchanged ETH.deadline- Transaction deadline timestamp.
- Check that the last address in the path is WETH (wrapped ETH).
- Calculate the expected ETH output from the specified input token amount and swap path.
- Check that the calculated output meets the minimum ETH amount specified by
amountOutMin. - Transfer the
path[0]token from the user to the first pair in the path. - Call
_swapto execute the token swaps. - Route the output of each hop to the next pair or final recipient as appropriate; for the ETH output, the router receives WETH.
- Execute the swaps along the
patharray. - Unwrap WETH using
withdrawand send the resulting ETH to the specified addressto.
swapExactTokensForTokens
Exchanges an exact input token amount for at least a specified output amount. It provides a procedure for exchanging a specified input token amount subject to a minimum output constraint.
Parameters
amountIn- Token amount to exchange.
amountOutMin- Minimum token amount expected from the swap.path- Array of addresses specifying the swap path. - The first address is the input token and the last is the output token.to- Address receiving the exchanged tokens.deadline- Transaction deadline timestamp.
- Calculate the expected output token amounts from the specified input token amount and swap path.
- Check that the calculated output meets the minimum specified by
amountOutMin. - Transfer the
path[0]token from the user to the first pair in the path. - Call
_swapto execute the token swaps. - Send the final output to
to. - Route intermediate swaps through the pairs along the
patharray.
swapTokensForExactETH
Swaps tokens for an exact specified amount of ETH. The user specifies an exact ETH output and a maximum input token amount, within which the swap must execute.
Parameters
amountOut- Exact ETH amount desired from the swap.
amountInMax- Maximum token amount to swap.path- Array of addresses specifying the swap path. - The first address is the input token and the last is WETH.to- Address receiving the exchanged ETH.deadline- Transaction deadline timestamp.
The differences between swapTokensForExactETH and swapExactTokensForETH are as follows.
swapTokensForExactETH
- The user specifies an exact desired ETH output, and tokens are exchanged to obtain that amount.
- The ETH output is specified exactly.
- The user specifies the maximum input token amount, and the swap must stay within that amount.
- The path runs from the input token to WETH.
swapExactTokensForETH
- The user specifies the exact token amount to exchange and the minimum ETH output acceptable for that amount.
- The minimum acceptable ETH output is specified.
- The actual ETH output is at least the specified minimum.
- The exact input token amount is specified.
- The path runs from the input token to WETH.
swapTokensForExactTokens
Performs a token swap to obtain a specified output amount while constraining the maximum amount of tokens used.
Parameters
amountOut- Exact token amount desired from the swap.
amountInMax- Maximum token amount to swap.path- Array of addresses specifying the swap path. - The first address is the input token and the last is the output token.to- Address receiving the exchanged tokens.deadline- Transaction deadline timestamp.
- Calculate the
amountsarray. UseUniswapV2Library.getAmountsInto calculate the required token amounts based onamountOutandpath. The array contains the amounts required at each step of the swap. - Check the maximum input constraint.
Verify that
amounts[0]does not exceedamountInMax. - Transfer tokens.
Transfer the input token from the user to the first pair along
path. This prepares the initial swap. - Call
_swap. Call_swapto execute the token swaps. This performs the swaps required to obtain the exact desired output amount. - Receive the exchanged tokens.
The final output tokens are sent to
to. - Route intermediate outputs through the successive pairs in the path.
Events
None.
Code
IUniswapV2Factory
IUniswapV2Factory
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}TransferHelper
TransferHelper
// File: @uniswap/lib/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}IUniswapV2Pair
IUniswapV2Pair
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}SafeMath
SafeMath
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.6.6;
// 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
// File: contracts/libraries/UniswapV2Library.sol
pragma solidity >=0.5.0;
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);
}
}
}IUniswapV2Router01
IUniswapV2Router01
// File: contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint 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 returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}IERC20
IERC20
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}IWETH
IWETH
// File: contracts/interfaces/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}UniswapV2Router01
UniswapV2Router01
// File: contracts/UniswapV2Router01.sol
pragma solidity =0.6.6;
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: @uniswap/lib/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.6.6;
// 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');
}
}
// File: contracts/libraries/UniswapV2Library.sol
pragma solidity >=0.5.0;
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);
}
}
}
// File: contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint 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 returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: contracts/UniswapV2Router01.sol
pragma solidity =0.6.6;
contract UniswapV2Router01 is IUniswapV2Router01 {
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
) private 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 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 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);
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); // refund dust eth, if any
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public 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 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 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 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);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) private {
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 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 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
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
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
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
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);
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); // refund dust eth, if any
}
function quote(uint amountA, uint reserveA, uint reserveB) public pure override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure override returns (uint amountOut) {
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure override returns (uint amountIn) {
return UniswapV2Library.getAmountOut(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path) public view override returns (uint[] memory amounts) {
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path) public view override returns (uint[] memory amounts) {
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}Conclusion
This article explored UniswapV2Router01 from Uniswap V2 using Bunzz's DeCipher feature. I hope it helped clarify the contract. I plan to continue covering particular NFTs and smart contracts.
I also publish articles about blockchain and AI on my blog and Qiita.




