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 V3Migrator contract in Uniswap V3.

DeCipher uses AI to generate smart contract documentation automatically.

For instructions on using it, see the following article.

This article is based on my personal experience with DeCipher. There may be mistakes, so please point them out in the comments if you notice any. This translation preserves the original technical explanations from August 31, 2023; it is not an independently verified reference.

Here is the DeCipher page used in this article.

Here is the Etherscan link from the original article.

Overview

The V3Migrator contract is part of the Uniswap V3 protocol and helps users move their existing liquidity from Uniswap V2 to Uniswap V3.

The following article covers liquidity migration from Uniswap V1 to Uniswap V2.

Its main responsibilities are as follows.

  1. It works with the core Uniswap V3 contracts to process liquidity migration from Uniswap V2 to Uniswap V3. This allows users to put their existing liquidity to work in the new protocol.
  2. It uses the LowGasSafeMath library to perform arithmetic efficiently and with low gas consumption while keeping operations safe and reducing costs.
  3. It interacts with Uniswap V2 pair contracts to obtain liquidity information and process the move to the new protocol.
  4. It works with the NonfungiblePositionManager contract to manage and manipulate liquidity positions during migration.
  5. It uses the TransferHelper library to transfer tokens safely and minimize the risks associated with token transfers.
  6. It implements the IV3Migrator interface to provide compatibility and standardization, allowing different contracts to interact smoothly.
  7. It incorporates functionality from several base contracts to improve its capabilities and security.
  8. It interacts with external contracts and provides interfaces for different token standards so that various tokens can be handled during migration.

How to use it

V3Migrator is a smart contract that supports liquidity migration from Uniswap V2 to Uniswap V3. It also provides functionality related to managing and interacting with migrated liquidity. This allows liquidity providers to take advantage of features in Uniswap V3 such as concentrated liquidity and multiple fee tiers.

Steps

The procedure is as follows.

  1. Deploy the V3Migrator contract, which manages liquidity migration.
  2. Initialize the contract with the required parameters.
  3. Approve the V3Migrator contract to spend liquidity tokens from the Uniswap V2 pool so that the tokens can be migrated.
  4. Call the migration function on V3Migrator to initiate the migration.
  5. Monitor the process, handling events and errors to ensure the migration proceeds smoothly.
  6. Use the available functions and events to interact with the migrated liquidity in the Uniswap V3 pool and manage liquidity in the new pool.

Function calls

The following functions are involved in migrating liquidity from Uniswap V2 to Uniswap V3.

constructor

Initializes the V3Migrator contract with the required parameters.

approve

Approves V3Migrator to spend a specified amount of liquidity tokens from a Uniswap V2 pool in preparation for migration.

migrate

Migrates the specified liquidity from Uniswap V2 to Uniswap V3.

Usage

Migrating liquidity from Uniswap V2 to Uniswap V3.

  1. Deploy the V3Migrator contract.
  2. Initialize the contract with the required parameters.
  3. Approve V3Migrator to spend the specified amount of liquidity tokens to be migrated from the Uniswap V2 pool.
  4. Call the migrate function on V3Migrator with the required migration parameters to move the liquidity from Uniswap V2 to V3.

Interacting with migrated liquidity in Uniswap V3.

  1. Use the available functions to interact with migrated liquidity in the Uniswap V3 pool and carry out liquidity operations in the new pool.
  2. Monitor events emitted by the V3Migrator contract and respond appropriately to updates or changes involving migrated liquidity.
  • ERC20: Defines the standard interface for fungible tokens.
  • ERC721: Defines the standard interface for non-fungible tokens.
  • ERC165: Defines a standard interface for contract interface detection.
  • ERC721Metadata: Extends the ERC721 interface with metadata functions.
  • ERC721Enumerable: Extends the ERC721 interface with enumeration functions.
  • ERC20Permit: Defines a standard interface for ERC20 tokens that support permits.
  • IUniswapV2Pair: Interface for the Uniswap V2 pair contract.
  • INonfungiblePositionManager: Interface for the Uniswap V3 non-fungible position manager contract.
  • IUniswapV3Factory: Interface for the Uniswap V3 factory contract.
  • IUniswapV3Pool: Interface for the Uniswap V3 pool contract.
  • IUniswapV3PoolImmutables: Interface for immutable data in a Uniswap V3 pool.
  • IUniswapV3PoolState: Interface for the state of a Uniswap V3 pool.
  • IUniswapV3PoolDerivedState: Interface for derived state in a Uniswap V3 pool.
  • IUniswapV3PoolActions: Interface for Uniswap V3 pool actions.
  • IUniswapV3PoolOwnerActions: Interface for Uniswap V3 pool owner actions.
  • IUniswapV3PoolEvents: Interface for Uniswap V3 pool events.

Parameters

_factory

The address of the Uniswap V3 factory contract. This contract creates Uniswap V3 pools. The address is referenced when creating a pool for a new trading pair.

_WETH9

The address of the WETH9 contract. WETH (Wrapped Ether) is a wrapped representation of Ethereum's native token, Ether (ETH), for trading and other operations through Ethereum smart contracts. This address is used for WETH9 token operations.

_nonfungiblePositionManager

The address of the non-fungible position manager contract. The Uniswap V3 non-fungible position manager provides functionality for users to manage and transfer their positions. This address is used when interacting with that contract.

Contracts

V3Migrator

nonfungiblePositionManager

nonfungiblePositionManager
solidity
address public immutable nonfungiblePositionManager;

Overview

The address of the non-fungible position manager contract.

Details

Stores the address of the Uniswap V3 non-fungible position manager contract, which provides functionality for managing Uniswap V3 liquidity positions. Because this variable is declared immutable, its value cannot be changed after deployment.

receive

receive
solidity
receive() external payable {
    require(msg.sender == WETH9, 'Not WETH9');
}

Overview

A function called when the contract receives ETH.

Details

This function is called automatically when ETH is sent to the contract. It verifies that the sender is the WETH9 contract and rejects ETH sent from any other address.

migrate

migrate
solidity
function migrate(MigrateParams calldata params) external override {
        require(params.percentageToMigrate > 0, 'Percentage too small');
        require(params.percentageToMigrate <= 100, 'Percentage too large');

        // burn v2 liquidity to this address
        IUniswapV2Pair(params.pair).transferFrom(msg.sender, params.pair, params.liquidityToMigrate);
        (uint256 amount0V2, uint256 amount1V2) = IUniswapV2Pair(params.pair).burn(address(this));

        // calculate the amounts to migrate to v3
        uint256 amount0V2ToMigrate = amount0V2.mul(params.percentageToMigrate) / 100;
        uint256 amount1V2ToMigrate = amount1V2.mul(params.percentageToMigrate) / 100;

        // approve the position manager up to the maximum token amounts
        TransferHelper.safeApprove(params.token0, nonfungiblePositionManager, amount0V2ToMigrate);
        TransferHelper.safeApprove(params.token1, nonfungiblePositionManager, amount1V2ToMigrate);

        // mint v3 position
        (, , uint256 amount0V3, uint256 amount1V3) =
            INonfungiblePositionManager(nonfungiblePositionManager).mint(
                INonfungiblePositionManager.MintParams({
                    token0: params.token0,
                    token1: params.token1,
                    fee: params.fee,
                    tickLower: params.tickLower,
                    tickUpper: params.tickUpper,
                    amount0Desired: amount0V2ToMigrate,
                    amount1Desired: amount1V2ToMigrate,
                    amount0Min: params.amount0Min,
                    amount1Min: params.amount1Min,
                    recipient: params.recipient,
                    deadline: params.deadline
                })
            );

        // if necessary, clear allowance and refund dust
        if (amount0V3 < amount0V2) {
            if (amount0V3 < amount0V2ToMigrate) {
                TransferHelper.safeApprove(params.token0, nonfungiblePositionManager, 0);
            }

            uint256 refund0 = amount0V2 - amount0V3;
            if (params.refundAsETH && params.token0 == WETH9) {
                IWETH9(WETH9).withdraw(refund0);
                TransferHelper.safeTransferETH(msg.sender, refund0);
            } else {
                TransferHelper.safeTransfer(params.token0, msg.sender, refund0);
            }
        }
        if (amount1V3 < amount1V2) {
            if (amount1V3 < amount1V2ToMigrate) {
                TransferHelper.safeApprove(params.token1, nonfungiblePositionManager, 0);
            }

            uint256 refund1 = amount1V2 - amount1V3;
            if (params.refundAsETH && params.token1 == WETH9) {
                IWETH9(WETH9).withdraw(refund1);
                TransferHelper.safeTransferETH(msg.sender, refund1);
            } else {
                TransferHelper.safeTransfer(params.token1, msg.sender, refund1);
            }
        }
}

Overview

Migrates liquidity from Uniswap V2 to Uniswap V3.

Details

Carries out the migration process based on the specified parameters. It accepts the required parameters and performs validation before executing the migration. Once migration is complete, a Uniswap V3 liquidity position is created, and assets are refunded as necessary.

Multicall

multicall

multicall
solidity
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
    results = new bytes[](data.length);
    for (uint256 i = 0; i < data.length; i++) {
        (bool success, bytes memory result) = address(this).delegatecall(data[i]);

        if (!success) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result.length < 68) revert();
            assembly {
                result := add(result, 0x04)
            }
            revert(abi.decode(result, (string)));
        }

        results[i] = result;
    }
}

Overview

Provides a mechanism for calling several contract functions in a single batch. It performs delegate calls using the specified array of data and returns the results of the individual function calls.

Details

The function allows multiple contract functions to be called together. The data array contains the calldata for each function to invoke. The return data is stored in the results array and returned to the caller. The function uses delegatecall to invoke each function and obtain its result and success status.

Arguments

  • data
    • An array of calldata for the function calls.

Return value

  • results
    • An array of byte strings containing the return data for each function call.

SelfPermit

selfPermit

selfPermit
solidity
function selfPermit(
    address token,
    uint256 value,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
) public payable override {
    IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}

Overview

Allows a token owner to grant the SelfPermit contract permission to transfer tokens.

Details

Uses a message signed by the token owner to grant token spending permission to the SelfPermit contract.

Arguments

  • token
    • The token address.
  • value
    • The amount of tokens to approve.
  • deadline
    • The signature deadline.
  • v, r, s
    • Signature parameters.

selfPermitIfNecessary

selfPermitIfNecessary
solidity
function selfPermitIfNecessary(
    address token,
    uint256 value,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
) external payable override {
    if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}

Overview

Allows the SelfPermit contract to obtain token spending permission only when necessary.

Details

Calls selfPermit to grant permission only when the existing token allowance is less than the required amount. It checks the allowance and calls selfPermit if the allowance is insufficient.

Arguments

  • token
    • The token address.
  • value
    • The amount of tokens to approve.
  • deadline
    • The signature deadline.
  • v, r, s
    • Signature parameters.

selfPermitAllowed

selfPermitAllowed
solidity
function selfPermitAllowed(
    address token,
    uint256 nonce,
    uint256 expiry,
    uint8 v,
    bytes32 r,
    bytes32 s
) public payable override {
    IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}

Overview

Provides an extended mechanism for a token owner to grant token spending permission to the SelfPermit contract.

Details

The token owner can use a signature to call the function and authorize the contract to spend tokens under the specified conditions.

Arguments

  • token
    • The token address.
  • nonce
    • A number used to ensure transaction uniqueness.
  • expiry
    • The signature expiration time.
  • v, r, s
    • Signature parameters.

selfPermitAllowedIfNecessary

selfPermitAllowedIfNecessary
solidity
function selfPermitAllowedIfNecessary(
    address token,
    uint256 nonce,
    uint256 expiry,
    uint8 v,
    bytes32 r,
    bytes32 s
) external payable override {
    if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
        selfPermitAllowed(token, nonce, expiry, v, r, s);
}

Overview

Provides an extended mechanism for granting token spending permission to the SelfPermit contract only when necessary.

Details

Calls selfPermitAllowed to grant permission when the allowance is below the maximum value. It checks the allowance and calls selfPermitAllowed if the maximum allowance has not already been granted.

Arguments

  • token
    • The token address.
  • nonce
    • A number used to ensure transaction uniqueness.
  • expiry
    • The signature expiration time.
  • v, r, s
    • Signature parameters.

PoolInitializer

createAndInitializePoolIfNecessary

createAndInitializePoolIfNecessary
solidity
function createAndInitializePoolIfNecessary(
    address token0,
    address token1,
    uint24 fee,
    uint160 sqrtPriceX96
) external payable override returns (address pool) {
    require(token0 < token1);
    pool = IUniswapV3Factory(factory).getPool(token0, token1, fee);

    if (pool == address(0)) {
        pool = IUniswapV3Factory(factory).createPool(token0, token1, fee);
        IUniswapV3Pool(pool).initialize(sqrtPriceX96);
    } else {
        (uint160 sqrtPriceX96Existing, , , , , , ) = IUniswapV3Pool(pool).slot0();
        if (sqrtPriceX96Existing == 0) {
            IUniswapV3Pool(pool).initialize(sqrtPriceX96);
        }
    }
}

Overview

Provides a mechanism for creating and initializing a Uniswap V3 pool as needed.

Details

Checks whether a Uniswap V3 pool exists for the specified tokens and fee tier. If no such pool exists, it creates and initializes one. If the pool already exists, the function retrieves its slot 0 information to determine whether it has been initialized. It initializes the pool if necessary.

Arguments

  • token0
    • The address of token0.
  • token1
    • The address of token1.
  • fee
    • The fee tier.
  • sqrtPriceX96
    • The initial square-root price.

Return value

  • pool
    • The address of the Uniswap V3 pool created or initialized.

sqrtPriceX96 is an important value representing price information in a Uniswap V3 pool. Uniswap V3 represents prices using sqrtPriceX96.

What is sqrtPriceX96?

sqrtPriceX96 is a numerical representation of price information in a Uniswap V3 pool, specifically the price of the trading pair formed by token0 and token1. The original explanation relates this value to the constant-product pricing function X * Y = K, where X and Y are the balances of token0 and token1 and K is a constant.

sqrtPriceX96 expresses price as a square root. This fits Uniswap V3's use of price ranges rather than a linear price representation.

Meaning and use of sqrtPriceX96

  • A higher sqrtPriceX96 means a higher price of token0 relative to token1.
  • A lower sqrtPriceX96 means a lower price of token0 relative to token1.
  • Changes in the pool's price are reflected in changes to sqrtPriceX96.
  • When the price moves to a different range, sqrtPriceX96 changes as well.

sqrtPriceX96 represents price information in a Uniswap V3 pool and is used to track price movements. It is an important metric for understanding trading prices in a pool and trading effectively.

TransferHelper

safeTransferFrom

safeTransferFrom
solidity
function safeTransferFrom(
    address token,
    address from,
    address to,
    uint256 value
) internal {
    (bool success, bytes memory data) =
        token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
    require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}

Overview

Safely transfers the specified token from the from address to the to address.

Details

Calls IERC20.transferFrom on the token contract at the token address to transfer tokens. It checks the success variable to determine whether the call succeeded and raises the STF error if the transfer fails.

Arguments

  • token
    • The token contract address.
  • from
    • The address from which tokens are transferred.
  • to
    • The address receiving the tokens.
  • value
    • The amount of tokens to transfer.

safeTransfer

safeTransfer
solidity
function safeTransfer(
    address token,
    address to,
    uint256 value
) internal {
    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
    require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}

Overview

Safely transfers tokens from msg.sender to the specified to address, as described in the original article.

Details

Calls IERC20.transfer on the token contract at the token address. It checks the success variable to determine whether the call succeeded and raises the ST error if the transfer fails.

Arguments

  • token
    • The token contract address.
  • to
    • The address receiving the tokens.
  • value
    • The amount of tokens to transfer.

safeApprove

safeApprove
solidity
function safeApprove(
    address token,
    address to,
    uint256 value
) internal {
    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
    require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}

Overview

Safely approves the specified to address to spend tokens.

Details

Calls IERC20.approve on the token contract at the token address to set an allowance. It checks the success variable and raises the SA error if the approval fails.

Arguments or parameters

  • token
    • The token contract address.
  • to
    • The address being approved.
  • value
    • The amount of tokens to approve.

safeTransferETH

safeTransferETH
solidity
function safeTransferETH(address to, uint256 value) internal {
    (bool success, ) = to.call{value: value}(new bytes(0));
    require(success, 'STE');
}

Overview

Safely transfers ETH to the specified to address.

Details

Transfers the specified amount of ETH to to. It checks the success variable and raises the STE error if the transfer fails.

Arguments

  • to
    • The address receiving ETH.
  • value
    • The amount of ETH to transfer.

PoolAddress

POOL_INIT_CODE_HASH

POOL_INIT_CODE_HASH
solidity
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;

Overview

A constant representing the hash of the pool's initialization code.

PoolKey

PoolKey
solidity
struct PoolKey {
    address token0;
    address token1;
    uint24 fee;
}

Overview

A struct representing the pool's identification key. It stores the pool's tokens and fee tier.

getPoolKey

getPoolKey
solidity
function getPoolKey(
    address tokenA,
    address tokenB,
    uint24 fee
) internal pure returns (PoolKey memory) {
    if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
    return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}

Overview

Obtains a pool key. It constructs the key from the given tokens and fee tier, sorting the token addresses in ascending order.

Arguments

  • tokenA
    • The first token in the pool.
  • tokenB
    • The second token in the pool.
  • fee
    • The pool's fee tier.

Return value

  • PoolKey
    • A PoolKey struct.
    • Contains the tokens in ascending order and the fee tier.

computeAddress

computeAddress
solidity
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
    require(key.token0 < key.token1);
    pool = address(
        uint256(
            keccak256(
                abi.encodePacked(
                    hex'ff',
                    factory,
                    keccak256(abi.encode(key.token0, key.token1, key.fee)),
                    POOL_INIT_CODE_HASH
                )
            )
        )
    );
}

Overview

Computes a pool address deterministically from the factory address and the pool key.

Arguments

  • factory
    • The address of the Uniswap V3 factory contract.
  • key
    • The pool key.

Return value

Returns the pool address.

Events

None.

Code

Interfaces

  • contracts/interfaces

Libraries

  • contracts/libraries

Base contracts

  • contracts/base

Final thoughts

In this article, we examined the Uniswap V3 V3Migrator contract using Bunzz's DeCipher feature. What did you think? I plan to continue exploring individual NFTs and smart contracts in future articles.

I also write about blockchain and AI on my blog and Qiita, so feel free to take a look.

https://chaldene.net/