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 then-new DeCipher feature to examine the UniswapV2Migrator contract in Uniswap V2.

DeCipher uses AI to generate smart contract documentation automatically.

For details on how to use it, see the following article.

This article reflects my personal experience using DeCipher. It may contain inaccuracies; please let me know in the comments if you spot any.

The DeCipher page used in this article is available here.

Overview

UniswapV2Migrator is an important component of Uniswap, a decentralized exchange (DEX) protocol built on Ethereum. It is designed to make liquidity migration from Uniswap V1 to Uniswap V2 straightforward and efficient.

Purpose of the Contract

The primary purpose of UniswapV2Migrator is to provide liquidity providers with an efficient way to migrate their liquidity from Uniswap V1 to Uniswap V2. The transition is useful because the upgrade from version 1 to version 2 of Uniswap introduced several features and improvements.

Migration involves removing liquidity from a V1 exchange and adding it to a V2 exchange. The intention is to transfer the liquidity provider's position without losing the underlying funds during the migration. The resulting share of the V2 pool depends on that pool's existing reserves and liquidity.

Responsibilities of the Contract

UniswapV2Migrator has several important responsibilities.

Integration with Uniswap V1 and V2

The contract interacts with both versions of the Uniswap protocol. It retrieves the exchange for a particular token from the V1 factory and uses the V2 router to add liquidity to a V2 exchange.

Transferring Liquidity

The contract handles the transfer of liquidity from a V1 exchange to a V2 exchange. It removes liquidity from the V1 exchange and adds it to the V2 exchange.

Ensuring Safe Migration

The contract includes checks designed to make migration secure. It checks whether the transfer of V1 liquidity succeeded and uses safeApprove to authorize the V2 router to spend tokens safely.

Handling ETH

The contract has a receive function that allows it to receive ETH. This is needed because the migration removes liquidity to obtain the underlying tokens and ETH, then uses them to supply liquidity to the V2 exchange.

In short, UniswapV2Migrator facilitates the migration of liquidity from V1 to V2. Its checks and transfer mechanisms help protect the migration process and maintain the integrity of the Uniswap ecosystem.

Usage

UniswapV2Migrator was designed to support liquidity migration from Uniswap V1 to Uniswap V2. It is primarily used by liquidity providers who want to move their liquidity to the updated protocol.

The following steps describe how to use the UniswapV2Migrator contract.

1. Deploy the Contract

The first step is to deploy the UniswapV2Migrator contract to Ethereum. The addresses of the Uniswap V1 factory and Uniswap V2 router are required as constructor arguments.

2. Prepare for Migration

Before calling migrate, the liquidity provider must authorize UniswapV2Migrator to transfer liquidity tokens from the Uniswap V1 exchange.

3. Call the Migrate Function

The liquidity provider can then call migrate. The function takes the following parameters.

  • token
    • The address of the token in the liquidity pair.
  • amountTokenMin
    • The minimum amount of tokens to be added to the liquidity pool.
  • amountETHMin
    • The minimum amount of ETH to be added to the liquidity pool.
  • to
    • The address that will receive the new liquidity tokens.
  • deadline
    • The latest time at which migration may be executed.

4. Migration Process

The migrate function performs the following steps.

  • Retrieves the amount of liquidity the caller holds in the Uniswap V1 exchange.
  • Transfers that liquidity to the migrator.
  • Removes liquidity from the Uniswap V1 exchange and receives the underlying assets in return.
  • Authorizes the Uniswap V2 router to spend the tokens.
  • Adds the tokens and ETH to the Uniswap V2 exchange in return for liquidity tokens.

5. Receive Liquidity Tokens

After migration, the new liquidity tokens are sent to the to address specified in the call to migrate.

The overall process can require multiple transactions, including approval, so users need sufficient ETH to pay gas fees. Migration is not reversible through this contract. Once liquidity has been migrated to Uniswap V2, the migrator does not provide a function to return it to Uniswap V1.

Parameters

_factoryV1

The address of the Uniswap V1 factory contract. This factory is used to create and manage Uniswap V1 exchanges. It plays an important role in creating liquidity pools for tokens and setting up exchanges.

_router

The address of the Uniswap V2 router contract. The router is used to swap tokens and provide liquidity on Uniswap V2. It handles token swaps efficiently and executes transactions that supply liquidity.

Functions

WRITE

migrate

Migrates liquidity from Uniswap V1 to Uniswap V2.

Arguments

  • token
    • The address of the token being migrated.
  • amountTokenMin
    • The minimum token amount the user wants to contribute during migration.
  • amountETHMin
    • The minimum ETH amount the user wants to contribute during migration.
  • to
    • The address receiving the migrated liquidity tokens.
  • deadline
    • The deadline for executing the migration.

The function first retrieves the Uniswap V1 exchange for the specified token using factoryV1.getExchange. It then checks the caller's liquidity token balance in that exchange.

It uses transferFrom to transfer the caller's liquidity tokens from the Uniswap V1 exchange to the migrator contract.

It then removes liquidity from the Uniswap V1 exchange using removeLiquidity.

The safeApprove function authorizes the Uniswap V2 router to spend amountTokenV1 tokens.

The function then uses the router's addLiquidityETH function to add liquidity to Uniswap V2. The amount of ETH available for the addition is amountETHV1.

If amountTokenV1 is greater than amountTokenV2, the function resets the token allowance to 0 using safeApprove and returns the excess tokens to the caller using safeTransfer.

If amountETHV1 is greater than amountETHV2, the function returns the excess ETH to the caller using safeTransferETH.

This function lets users migrate their liquidity from Uniswap V1 to Uniswap V2 and take advantage of the features of V2.

deadline specifies the latest time at which the liquidity migration may be executed. It prevents the transaction from executing beyond the specified time window. If execution is attempted after the specified deadline (a Unix timestamp), the transaction reverts. This mechanism enforces a time limit; it does not guarantee that the transaction will be included before that time.

For example, if a user calls migrate with a Unix timestamp one hour in the future, execution after that hour will fail. This limits the validity window of the migration and helps users avoid unexpectedly late execution.

Events

None.

Code

IUniswapV2Migrator

IUniswapV2Migrator
solidity
pragma solidity =0.6.6;

interface IUniswapV2Migrator {
    function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external;
}

IUniswapV1Factory

IUniswapV1Factory
solidity
interface IUniswapV1Factory {
    function getExchange(address) external view returns (address);
}

IUniswapV1Exchange

IUniswapV1Exchange
solidity
interface IUniswapV1Exchange {
    function balanceOf(address owner) external view returns (uint);
    function transferFrom(address from, address to, uint value) external returns (bool);
    function removeLiquidity(uint, uint, uint, uint) external returns (uint, uint);
    function tokenToEthSwapInput(uint, uint, uint) external returns (uint);
    function ethToTokenSwapInput(uint, uint) external payable returns (uint);
}

IUniswapV2Router01

IUniswapV2Router01
solidity
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
solidity
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);
}

UniswapV2Migrator

UniswapV2Migrator
solidity
contract UniswapV2Migrator is IUniswapV2Migrator {
    IUniswapV1Factory immutable factoryV1;
    IUniswapV2Router01 immutable router;

    constructor(address _factoryV1, address _router) public {
        factoryV1 = IUniswapV1Factory(_factoryV1);
        router = IUniswapV2Router01(_router);
    }

    // needs to accept ETH from any v1 exchange and the router. ideally this could be enforced, as in the router,
    // but it's not possible because it requires a call to the v1 factory, which takes too much gas
    receive() external payable {}

    function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
        external
        override
    {
        IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token));
        uint liquidityV1 = exchangeV1.balanceOf(msg.sender);
        require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED');
        (uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, uint(-1));
        TransferHelper.safeApprove(token, address(router), amountTokenV1);
        (uint amountTokenV2, uint amountETHV2,) = router.addLiquidityETH{value: amountETHV1}(
            token,
            amountTokenV1,
            amountTokenMin,
            amountETHMin,
            to,
            deadline
        );
        if (amountTokenV1 > amountTokenV2) {
            TransferHelper.safeApprove(token, address(router), 0); // be a good blockchain citizen, reset allowance to 0
            TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2);
        } else if (amountETHV1 > amountETHV2) {
            // addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
            TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2);
        }
    }
}

TransferHelper

TransferHelper
solidity
pragma solidity =0.6.6;

interface IUniswapV2Migrator {
    function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external;
}

interface IUniswapV1Factory {
    function getExchange(address) external view returns (address);
}

interface IUniswapV1Exchange {
    function balanceOf(address owner) external view returns (uint);
    function transferFrom(address from, address to, uint value) external returns (bool);
    function removeLiquidity(uint, uint, uint, uint) external returns (uint, uint);
    function tokenToEthSwapInput(uint, uint, uint) external returns (uint);
    function ethToTokenSwapInput(uint, uint) external payable returns (uint);
}

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);
}

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);
}

contract UniswapV2Migrator is IUniswapV2Migrator {
    IUniswapV1Factory immutable factoryV1;
    IUniswapV2Router01 immutable router;

    constructor(address _factoryV1, address _router) public {
        factoryV1 = IUniswapV1Factory(_factoryV1);
        router = IUniswapV2Router01(_router);
    }

    // needs to accept ETH from any v1 exchange and the router. ideally this could be enforced, as in the router,
    // but it's not possible because it requires a call to the v1 factory, which takes too much gas
    receive() external payable {}

    function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
        external
        override
    {
        IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token));
        uint liquidityV1 = exchangeV1.balanceOf(msg.sender);
        require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED');
        (uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, uint(-1));
        TransferHelper.safeApprove(token, address(router), amountTokenV1);
        (uint amountTokenV2, uint amountETHV2,) = router.addLiquidityETH{value: amountETHV1}(
            token,
            amountTokenV1,
            amountTokenMin,
            amountETHMin,
            to,
            deadline
        );
        if (amountTokenV1 > amountTokenV2) {
            TransferHelper.safeApprove(token, address(router), 0); // be a good blockchain citizen, reset allowance to 0
            TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2);
        } else if (amountETHV1 > amountETHV2) {
            // addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
            TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2);
        }
    }
}

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

Conclusion

This article examined the UniswapV2Migrator contract in Uniswap V2 using Bunzz's DeCipher feature. I plan to continue covering individual NFTs and smart contracts in future articles.

I also write about blockchain and AI on my blog and Qiita.

https://chaldene.net/