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.

This article explains Uniswap V3 through a translation and supplementary discussion of its official documentation.

The official documentation is available here.

Overview

Uniswap V3 is a decentralized exchange (DEX) protocol implemented using smart contracts. The protocol allows users to exchange different tokens and provide liquidity. The Uniswap V3 smart contract documentation provides the following resources.

Guides

If you are new to Uniswap V3 smart contracts, start with the fundamental concepts. These explain the protocol's basic operating principles and terminology. You can then set up a local environment and learn how to execute your first token swap.

Reference

For a deeper technical understanding, consult the technical reference documentation. It explains the smart contract specifications, functions, and methods in detail.

Resources

Various resources are available, including V3 Core and V3 Periphery. These resources provide more detailed information and practical code examples.

Uniswap V3 smart contracts are developed using languages such as Solidity. Developers can apply their skills to understanding these contracts and integrating them into applications. Pay attention to code quality and readability when developing liquidity strategies and token exchange mechanisms.

Guides

Swaps

Single swaps

Uniswap allows users to swap one cryptocurrency for another. The following examples explain two functions for performing swaps: swapExactInputSingle and swapExactOutputSingle.

swapExactInputSingle Use this function to exchange an exact amount of one token for another. For example, use it when you have a specified amount of ETH and want to obtain as much of another token as possible. Specify the swap details in ExactInputSingleParams and call exactInputSingle through Uniswap's ISwapRouter interface.

swapExactOutputSingle Use this function when you want to receive an exact amount of the output token. For example, use it when you want to obtain a specified token quantity while spending as little of the input token as possible. Specify the swap details in ExactOutputSingleParams and call exactOutputSingle through Uniswap's ISwapRouter interface.

The examples hardcode token addresses, but real applications may allow different tokens and pools to be selected for each transaction.

When integrating Uniswap into a smart contract, reliable price information independent of the immediate swap is essential. Without it, other traders may front-run a transaction and cause losses.

These examples are educational and are not production-ready code.

Contract setup

solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';

contract SwapExamples {
	// For the scope of these swap examples,
	// we will detail the design considerations when using `exactInput`, `exactInputSingle`, `exactOutput`, and  `exactOutputSingle`.
	// It should be noted that for the sake of these examples we pass in the swap router as a constructor argument instead of inheriting it.
	// More advanced example contracts will detail how to inherit the swap router safely.
	// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.

	ISwapRouter public immutable swapRouter;

	address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
	address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
	address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

	// For this example, we will set the pool fee to 0.3%.
	uint24 public constant poolFee = 3000;

	constructor(ISwapRouter _swapRouter) {
		swapRouter = _swapRouter;
	}
	
	...

The contract above hardcodes the token contract addresses and pool fee tier.

Exact input swaps

Follow these steps to obtain tokens and execute a swap from a smart contract. These steps include pulling tokens from the caller and granting the Uniswap router an allowance.

  1. Approve token spending First, the caller must approve the example contract to spend the caller's tokens; the example contract then approves the Uniswap router. This allows the example contract to obtain the caller's tokens and makes them available to the router for the swap.

  2. Transfer DAI Transfer the specified amount of DAI from the caller's address to the contract. Specify the amount of DAI to transfer.

solidity
	...
	
	/// @notice swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9
	/// using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router.
	/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
	/// @param amountIn The exact amount of DAI that will be swapped for WETH9.
	/// @return amountOut The amount of WETH9 received.
	function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
	// msg.sender must approve this contract

	// Transfer the specified amount of DAI to this contract.
	TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);

	// Approve the router to spend DAI.
	TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
	
	...
Parameters

To execute the swap, supply an ExactInputSingleParams struct. The parameters are described below.

  • tokenIn (input token)
    • Contract address of the token being exchanged.
  • tokenOut (output token)
    • Contract address of the token received from the swap.
  • fee (fee tier)
    • Pool fee information identifying the pool in which the swap will be performed.
  • recipient
    • Address receiving the output tokens.
  • deadline
    • Unix timestamp after which the swap reverts.
    • Prevents a transaction from being executed after an excessively long delay, when market conditions may have changed.
  • amountOutMinimum (minimum output amount)
    • The example uses 0, but this parameter is important in production.
    • Use a suitable SDK or reliable price oracle to determine a minimum acceptable output amount.
    • This limits exposure to unfavorable execution prices caused by front-running or price manipulation.
  • sqrtPriceLimitX96
    • The example uses 0 here as well. In production, configure a suitable price limit where appropriate.
    • This helps control the permitted price movement and supports price-dependent execution strategies.
Calling the function
solidity
	...
	
	// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
	// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
	ISwapRouter.ExactInputSingleParams memory params =
		ISwapRouter.ExactInputSingleParams({
			tokenIn: DAI,
			tokenOut: WETH9,
			fee: poolFee,
			recipient: msg.sender,
			deadline: block.timestamp,
			amountIn: amountIn,
			amountOutMinimum: 0,
			sqrtPriceLimitX96: 0
		});

	// The call to `exactInputSingle` executes the swap.
	amountOut = swapRouter.exactInputSingle(params);
	}
	
	...

Exact output swaps

An exact output swap exchanges the input token amount required to obtain a specified output amount, subject to a maximum input constraint.

For example, use an exact output swap when you need a particular quantity of a token. Specify the desired output amount so the router can calculate the input amount required to obtain it. The caller supplies a sufficient maximum input allowance, and the swap spends only the required amount within that limit.

The example refunds unused input tokens to the caller after the swap. This avoids retaining unnecessary tokens in the example contract.

Calling the function
solidity
	...
	
	/// @notice swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH.
	/// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
	/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
	/// @param amountOut The exact amount of WETH9 to receive from the swap.
	/// @param amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9.
	/// @return amountIn The amount of DAI actually spent in the swap.
	function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
	// Transfer the specified amount of DAI to this contract.
	TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);

	// Approve the router to spend the specified `amountInMaximum` of DAI.
	// In production, you should choose the maximum amount to spend based on oracles or other data sources to achieve a better swap.
	TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);

	ISwapRouter.ExactOutputSingleParams memory params =
		ISwapRouter.ExactOutputSingleParams({
			tokenIn: DAI,
			tokenOut: WETH9,
			fee: poolFee,
			recipient: msg.sender,
			deadline: block.timestamp,
			amountOut: amountOut,
			amountInMaximum: amountInMaximum,
			sqrtPriceLimitX96: 0
		});

	// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
	amountIn = swapRouter.exactOutputSingle(params);

	// For exact output swaps, the amountInMaximum may not have all been spent.
	// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
	if (amountIn < amountInMaximum) {
	    TransferHelper.safeApprove(DAI, address(swapRouter), 0);
	    TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn);
	}
}

Swap contract

The complete example swap contract is shown below.

SwapExamples.sol
solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';

contract SwapExamples {
    // For the scope of these swap examples,
    // we will detail the design considerations when using
    // `exactInput`, `exactInputSingle`, `exactOutput`, and  `exactOutputSingle`.

    // It should be noted that for the sake of these examples, we purposefully pass in the swap router instead of inherit the swap router for simplicity.
    // More advanced example contracts will detail how to inherit the swap router safely.

    ISwapRouter public immutable swapRouter;

    // This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.

    address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

    // For this example, we will set the pool fee to 0.3%.
    uint24 public constant poolFee = 3000;

    constructor(ISwapRouter _swapRouter) {
        swapRouter = _swapRouter;
    }

    /// @notice swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9
    /// using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router.
    /// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
    /// @param amountIn The exact amount of DAI that will be swapped for WETH9.
    /// @return amountOut The amount of WETH9 received.
    function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
        // msg.sender must approve this contract

        // Transfer the specified amount of DAI to this contract.
        TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);

        // Approve the router to spend DAI.
        TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);

        // Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
        // We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
        ISwapRouter.ExactInputSingleParams memory params =
            ISwapRouter.ExactInputSingleParams({
                tokenIn: DAI,
                tokenOut: WETH9,
                fee: poolFee,
                recipient: msg.sender,
                deadline: block.timestamp,
                amountIn: amountIn,
                amountOutMinimum: 0,
                sqrtPriceLimitX96: 0
            });

        // The call to `exactInputSingle` executes the swap.
        amountOut = swapRouter.exactInputSingle(params);
    }

    /// @notice swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH.
    /// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
    /// the calling address will need to approve for a slightly higher amount, anticipating some variance.
    /// @param amountOut The exact amount of WETH9 to receive from the swap.
    /// @param amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9.
    /// @return amountIn The amount of DAI actually spent in the swap.
    function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
        // Transfer the specified amount of DAI to this contract.
        TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);

        // Approve the router to spend the specifed `amountInMaximum` of DAI.
        // In production, you should choose the maximum amount to spend based on oracles or other data sources to acheive a better swap.
        TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);

        ISwapRouter.ExactOutputSingleParams memory params =
            ISwapRouter.ExactOutputSingleParams({
                tokenIn: DAI,
                tokenOut: WETH9,
                fee: poolFee,
                recipient: msg.sender,
                deadline: block.timestamp,
                amountOut: amountOut,
                amountInMaximum: amountInMaximum,
                sqrtPriceLimitX96: 0
            });

        // Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
        amountIn = swapRouter.exactOutputSingle(params);

        // For exact output swaps, the amountInMaximum may not have all been spent.
        // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
        if (amountIn < amountInMaximum) {
            TransferHelper.safeApprove(DAI, address(swapRouter), 0);
            TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn);
        }
    }
}

Multihop swaps

The following example demonstrates swapping across multiple token pairs in Uniswap V3.

These examples are educational and are not production-ready code.

Contract setup

solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';

contract SwapExamples {
	// For the scope of these swap examples,
	// we will detail the design considerations when using `exactInput`, `exactInputSingle`, `exactOutput`, and  `exactOutputSingle`.
	// It should be noted that for the sake of these examples we pass in the swap router as a constructor argument instead of inheriting it.
	// More advanced example contracts will detail how to inherit the swap router safely.
	// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.

	ISwapRouter public immutable swapRouter;
    
	address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
	address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
	address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

	// For this example, we will set the pool fee to 0.3%.
	uint24 public constant poolFee = 3000;

	constructor(ISwapRouter _swapRouter) {
		swapRouter = _swapRouter;
	}
	
	...

Exact input multihop swaps

The operation proceeds as follows.

  1. Start with a specified amount of the input token and seek an output amount along the chosen route.

  2. Intermediate steps may exchange different tokens before reaching the final output token. Each intermediate swap converts one token into the next token in the route and incurs its pool's fee (fee).

  3. The final output amount is determined by executing the specified sequence of intermediate swaps.

Parameters
  • path
    • Encodes the swap sequence using alternating token addresses and fee tiers, such as tokenAddress - fee - tokenAddress.
    • Each element identifies a token contract address or fee tier, determining the sequence of pools used by the swap.
  • recipient
    • Address receiving the output assets.
  • deadline
    • Unix timestamp after which the transaction reverts.
    • Limits the time for which a pending transaction can remain executable as market conditions change.
  • amountIn (input amount)
    • Quantity of the initial input asset supplied.
    • This amount is used as the swap input.
  • amountOutMin (minimum output amount)
    • Minimum amount of output assets required for the transaction to succeed.
    • The transaction reverts if the output is below this value.
    • Production integrations commonly use an SDK to estimate the expected output and may also use reliable on-chain price oracles for additional protection.
Calling the function
solidity
	...
	
	/// @notice swapExactInputMultihop swaps a fixed amount of DAI for a maximum possible amount of WETH9 through an intermediary pool.
	/// For this example, we will swap DAI to USDC, then USDC to WETH9 to achieve our desired output.
	/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
	/// @param amountIn The amount of DAI to be swapped.
	/// @return amountOut The amount of WETH9 received after the swap.
	function swapExactInputMultihop(uint256 amountIn) external returns (uint256 amountOut) {
	// Transfer `amountIn` of DAI to this contract.
	TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);

	// Approve the router to spend DAI.
	TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);

	// Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.
	// The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.
	// Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).
	ISwapRouter.ExactInputParams memory params =
		ISwapRouter.ExactInputParams({
			path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),
			recipient: msg.sender,
			deadline: block.timestamp,
			amountIn: amountIn,
			amountOutMinimum: 0
		});

	// Executes the swap.
	amountOut = swapRouter.exactInput(params);
	}
	
	...

Exact output multihop swaps

This swap mode exchanges a variable amount of an input token for a fixed output amount. It is used in particular multihop scenarios. Much of the code is similar to other swap modes, with one important difference. The path is encoded in reverse order. Because the output amount is fixed and the required input is variable, the route is encoded backwards to determine the input amounts.

Parameters
  • path

    • The path uses alternating tokenAddress Fee tokenAddress fields, starting with the desired output token and working backwards toward the input token.
    • These values identify the pool contract addresses along the route.
    • The multihop router uses them to locate the correct pools and execute the necessary swaps.
  • recipient

    • Recipient address for the output assets.
    • Specifies where the assets obtained through the swap are sent.
  • deadline

    • Unix timestamp after which the transaction reverts.
    • Limits the time for which a pending transaction can remain executable as market conditions change.
  • amountOut (desired output amount)

    • Amount of the token to receive, such as WETH9.
    • The swap seeks to obtain the specified amount of WETH9.
  • amountInMaximum (maximum input amount)

    • Maximum amount of DAI that may be spent to receive the specified amountOut of WETH9.
    • Prevents execution when unfavorable price movement would require more input than the caller is willing to spend.
Calling the function
solidity
	...

	/// @notice swapExactOutputMultihop swaps a minimum possible amount of DAI for a fixed amount of WETH through an intermediary pool.
	/// For this example, we want to swap DAI for WETH9 through a USDC pool but we specify the desired amountOut of WETH9. Notice how the path encoding is slightly different in for exact output swaps.
	/// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
	/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
	/// @param amountOut The desired amount of WETH9.
	/// @param amountInMaximum The maximum amount of DAI willing to be swapped for the specified amountOut of WETH9.
	/// @return amountIn The amountIn of DAI actually spent to receive the desired amountOut.
	function swapExactOutputMultihop(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
	// Transfer the specified `amountInMaximum` to this contract.
	TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
	// Approve the router to spend  `amountInMaximum`.
	TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);

	// The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn)
	// The tokenIn/tokenOut field is the shared token between the two pools used in the multiple pool swap. In this case USDC is the "shared" token.
	// For an exactOutput swap, the first swap that occurs is the swap which returns the eventual desired token.
	// In this case, our desired output token is WETH9 so that swap happens first, and is encoded in the path accordingly.
	ISwapRouter.ExactOutputParams memory params =
		ISwapRouter.ExactOutputParams({
			path: abi.encodePacked(WETH9, poolFee, USDC, poolFee, DAI),
			recipient: msg.sender,
			deadline: block.timestamp,
			amountOut: amountOut,
			amountInMaximum: amountInMaximum
		});

	// Executes the swap, returning the amountIn actually spent.
	amountIn = swapRouter.exactOutput(params);

	// If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0.
	if (amountIn < amountInMaximum) {
		TransferHelper.safeApprove(DAI, address(swapRouter), 0);
		TransferHelper.safeTransferFrom(DAI, address(this), msg.sender, amountInMaximum - amountIn);
	}
}

Multihop swap contract

SwapExamples.sol
solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';

contract SwapExamples {
    // For the scope of these swap examples,
    // we will detail the design considerations when using
    // `exactInput`, `exactInputSingle`, `exactOutput`, and  `exactOutputSingle`.

    // It should be noted that for the sake of these examples, we purposefully pass in the swap router instead of inherit the swap router for simplicity.
    // More advanced example contracts will detail how to inherit the swap router safely.

    ISwapRouter public immutable swapRouter;

    // This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.

    address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

    // For this example, we will set the pool fee to 0.3%.
    uint24 public constant poolFee = 3000;

    constructor(ISwapRouter _swapRouter) {
        swapRouter = _swapRouter;
    }

    /// @notice swapInputMultiplePools swaps a fixed amount of DAI for a maximum possible amount of WETH9 through an intermediary pool.
    /// For this example, we will swap DAI to USDC, then USDC to WETH9 to achieve our desired output.
    /// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
    /// @param amountIn The amount of DAI to be swapped.
    /// @return amountOut The amount of WETH9 received after the swap.
    function swapExactInputMultihop(uint256 amountIn) external returns (uint256 amountOut) {
        // Transfer `amountIn` of DAI to this contract.
        TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);

        // Approve the router to spend DAI.
        TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);

        // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.
        // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.
        // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).
        ISwapRouter.ExactInputParams memory params =
            ISwapRouter.ExactInputParams({
                path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),
                recipient: msg.sender,
                deadline: block.timestamp,
                amountIn: amountIn,
                amountOutMinimum: 0
            });

        // Executes the swap.
        amountOut = swapRouter.exactInput(params);
    }

    /// @notice swapExactOutputMultihop swaps a minimum possible amount of DAI for a fixed amount of WETH through an intermediary pool.
    /// For this example, we want to swap DAI for WETH9 through a USDC pool but we specify the desired amountOut of WETH9. Notice how the path encoding is slightly different in for exact output swaps.
    /// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
    /// the calling address will need to approve for a slightly higher amount, anticipating some variance.
    /// @param amountOut The desired amount of WETH9.
    /// @param amountInMaximum The maximum amount of DAI willing to be swapped for the specified amountOut of WETH9.
    /// @return amountIn The amountIn of DAI actually spent to receive the desired amountOut.
    function swapExactOutputMultihop(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
        // Transfer the specified `amountInMaximum` to this contract.
        TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
        // Approve the router to spend  `amountInMaximum`.
        TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);

        // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn)
        // The tokenIn/tokenOut field is the shared token between the two pools used in the multiple pool swap. In this case USDC is the "shared" token.
        // For an exactOutput swap, the first swap that occurs is the swap which returns the eventual desired token.
        // In this case, our desired output token is WETH9 so that swap happpens first, and is encoded in the path accordingly.
        ISwapRouter.ExactOutputParams memory params =
            ISwapRouter.ExactOutputParams({
                path: abi.encodePacked(WETH9, poolFee, USDC, poolFee, DAI),
                recipient: msg.sender,
                deadline: block.timestamp,
                amountOut: amountOut,
                amountInMaximum: amountInMaximum
            });

        // Executes the swap, returning the amountIn actually spent.
        amountIn = swapRouter.exactOutput(params);

        // If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0.
        if (amountIn < amountInMaximum) {
            TransferHelper.safeApprove(DAI, address(swapRouter), 0);
            TransferHelper.safeTransferFrom(DAI, address(this), msg.sender, amountInMaximum - amountIn);
        }
    }
}

Providing liquidity

Contract setup

This example demonstrates a custodial contract for Uniswap V3 liquidity positions. The contract supports the following operations.

  • Mint a position
    • Create a liquidity position in Uniswap V3.
  • Add liquidity to a position
    • Supply additional tokens to an existing position.
  • Decrease liquidity
    • Remove some or all liquidity associated with a position.
  • Collect fees
    • Collect trading fees owed to the position.
solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/base/LiquidityManagement.sol';

contract LiquidityExamples is IERC721Receiver {

	address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
	address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

	uint24 public constant poolFee = 3000;
	
	INonfungiblePositionManager public immutable nonfungiblePositionManager;

	...

Interoperability with ERC721

Each NFT is identified by a unique tokenId within its ERC721 smart contract. Follow these steps to record deposits of ERC721 tokens.

  1. Define a Deposit struct Create a Deposit struct to store deposit information.

  2. Associate each NFT with a Deposit struct Create a mapping using each NFT's tokenId as the key and its Deposit struct as the value.

solidity
...

struct Deposit {
	address owner;
	uint128 liquidity;
	address token0;
	address token1;
}

mapping(uint256 => Deposit) public deposits;

...

Constructor

solidity
...

constructor(
	INonfungiblePositionManager _nonfungiblePositionManager,
	address _factory,
	address _WETH9
) PeripheryImmutableState(_factory, _WETH9) {
	nonfungiblePositionManager = _nonfungiblePositionManager;
}

...

Allow custody of ERC721 tokens

Implement onERC721Received from the inherited IERC721Receiver.sol interface so the contract can receive ERC721 tokens.

The example does not use the from parameter, so its name can be omitted.

solidity
...

function onERC721Received(
	address operator,
	address,
	uint256 tokenId,
	bytes calldata
) external override returns (bytes4) {
	// get position information
	_createDeposit(operator, tokenId);
	return this.onERC721Received.selector;
}

...

Create a deposit record

To add records to the deposits mapping, define an internal _createDeposit function and retrieve the position details using positions on the nonfungible position manager. Store the returned token0, token1, and liquidity information in deposits.

solidity
function _createDeposit(address owner, uint256 tokenId) internal {
	(, , address token0, address token1, , , , uint128 liquidity, , , , ) = nonfungiblePositionManager.positions(tokenId);

	// set the owner and data for position
	// operator is msg.sender
	deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1});
}

Liquidity management contract

LiquidityExamples.sol
solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '../libraries/TransferHelper.sol';
import '../interfaces/INonfungiblePositionManager.sol';
import '../base/LiquidityManagement.sol';

contract LiquidityExamples is IERC721Receiver {
    address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

    uint24 public constant poolFee = 3000;

    INonfungiblePositionManager public immutable nonfungiblePositionManager;

    /// @notice Represents the deposit of an NFT
    struct Deposit {
        address owner;
        uint128 liquidity;
        address token0;
        address token1;
    }

    /// @dev deposits[tokenId] => Deposit
    mapping(uint256 => Deposit) public deposits;

    constructor(
        INonfungiblePositionManager _nonfungiblePositionManager
    ) {
        nonfungiblePositionManager = _nonfungiblePositionManager;
    }

    // Implementing `onERC721Received` so this contract can receive custody of erc721 tokens
    function onERC721Received(
        address operator,
        address,
        uint256 tokenId,
        bytes calldata
    ) external override returns (bytes4) {
        // get position information

        _createDeposit(operator, tokenId);

        return this.onERC721Received.selector;
    }

    function _createDeposit(address owner, uint256 tokenId) internal {
        (, , address token0, address token1, , , , uint128 liquidity, , , , ) =
            nonfungiblePositionManager.positions(tokenId);

        // set the owner and data for position
        // operator is msg.sender
        deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1});
    }
}

Create a new position

Parameters

To create a new position, call mint on the nonfungible position manager.

This example hardcodes the amounts of tokens to supply.

These examples are educational and are not production-ready code.

solidity
/// @notice Calls the mint function defined in periphery, mints the same amount of each token. For this example we are providing 1000 DAI and 1000 USDC in liquidity
/// @return tokenId The id of the newly minted ERC721
/// @return liquidity The amount of liquidity for the position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mintNewPosition()
	external
	returns (
		uint256 tokenId,
		uint128 liquidity,
		uint256 amount0,
		uint256 amount1
	)
{
	// For this example, we will provide equal amounts of liquidity in both assets.
	// Providing liquidity in both assets means liquidity will be earning fees and is considered in-range.
	uint256 amount0ToMint = 1000;
	uint256 amount1ToMint = 1000;

Calling mint

Approve the nonfungible position manager to spend the contract's tokens and populate a MintParams struct assigned to params. Pass params to the nonfungible position manager when calling mint.

The example uses TickMath.MIN_TICK and TickMath.MAX_TICK to provide liquidity across the full usable tick range, adjusted for tick spacing.

In production, a narrower concentrated-liquidity position may be more appropriate.

The example sets amount0Min and amount1Min to 0, which is unsafe in production. A mint without slippage protection can be vulnerable to front-running that changes the price before the mint executes.

For a safer implementation, calculate suitable minimum token amounts using a slippage estimation process.

solidity
	// Approve the position manager
	TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), amount0ToMint);
	TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), amount1ToMint);

	INonfungiblePositionManager.MintParams memory params =
		INonfungiblePositionManager.MintParams({
			token0: DAI,
			token1: USDC,
			fee: poolFee,
			tickLower: TickMath.MIN_TICK,
			tickUpper: TickMath.MAX_TICK,
			amount0Desired: amount0ToMint,
			amount1Desired: amount1ToMint,
			amount0Min: 0,
			amount1Min: 0,
			recipient: address(this),
			deadline: block.timestamp
		});

	// Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint
	(tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager.mint(params);

Update the Deposit mapping and refund unused tokens

Call the internal function defined in the contract setup section. Refund unused token amounts from the mint operation to msg.sender.

solidity
	// Create a deposit
	_createDeposit(msg.sender, tokenId);

	// Remove allowance and refund in both assets.
	if (amount0 < amount0ToMint) {
		TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), 0);
		uint256 refund0 = amount0ToMint - amount0;
		TransferHelper.safeTransfer(DAI, msg.sender, refund0);
	}

	if (amount1 < amount1ToMint) {
		TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), 0);
		uint256 refund1 = amount1ToMint - amount1;
		TransferHelper.safeTransfer(USDC, msg.sender, refund1);
	}
}

Example contract

詳細
solidity
/// @notice Calls the mint function defined in periphery, mints the same amount of each token. For this example we are providing 1000 DAI and 1000 USDC in liquidity
/// @return tokenId The id of the newly minted ERC721
/// @return liquidity The amount of liquidity for the position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mintNewPosition()
external
returns (
	uint256 tokenId,
	uint128 liquidity,
	uint256 amount0,
	uint256 amount1
)
{
	// For this example, we will provide equal amounts of liquidity in both assets.
	// Providing liquidity in both assets means liquidity will be earning fees and is considered in-range.
	uint256 amount0ToMint = 1000;
	uint256 amount1ToMint = 1000;

	// Approve the position manager
	TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), amount0ToMint);
	TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), amount1ToMint);

	INonfungiblePositionManager.MintParams memory params =
		INonfungiblePositionManager.MintParams({
			token0: DAI,
			token1: USDC,
			fee: poolFee,
			tickLower: TickMath.MIN_TICK,
			tickUpper: TickMath.MAX_TICK,
			amount0Desired: amount0ToMint,
			amount1Desired: amount1ToMint,
			amount0Min: 0,
			amount1Min: 0,
			recipient: address(this),
			deadline: block.timestamp
		});

	// Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint
	(tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager.mint(params);

	// Create a deposit
	_createDeposit(msg.sender, tokenId);

	// Remove allowance and refund in both assets.
	if (amount0 < amount0ToMint) {
		TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), 0);
		uint256 refund0 = amount0ToMint - amount0;
		TransferHelper.safeTransfer(DAI, msg.sender, refund0);
	}

	if (amount1 < amount1ToMint) {
		TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), 0);
		uint256 refund1 = amount1ToMint - amount1;
		TransferHelper.safeTransfer(USDC, msg.sender, refund1);
	}
}

Collect fees

Fee collection

To interact with a liquidity position through this custodial contract, the contract must hold the position NFT. If the example function does not include an NFT deposit, it assumes that the contract already owns the NFT.

To collect fees for a position, transfer the NFT from the caller where necessary, retrieve its relevant information into local variables, and call collect on the nonfungible position manager.

The function collects the owed amounts and sends them to the NFT's recorded owner while maintaining custody of the position NFT.

solidity
/// @notice Collects the fees associated with provided liquidity
/// @dev The contract must hold the erc721 token before it can collect fees
/// @param tokenId The id of the erc721 token
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collectAllFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) {
// Caller must own the ERC721 position
// Call to safeTransfer will trigger `onERC721Received` which must return the selector else transfer will fail
nonfungiblePositionManager.safeTransferFrom(msg.sender, address(this), tokenId);

// set amount0Max and amount1Max to uint256.max to collect all fees
// alternatively can set recipient to msg.sender and avoid another transaction in `sendToOwner`
INonfungiblePositionManager.CollectParams memory params =
	INonfungiblePositionManager.CollectParams({
		tokenId: tokenId,
		recipient: address(this),
		amount0Max: type(uint128).max,
		amount1Max: type(uint128).max
	});

(amount0, amount1) = nonfungiblePositionManager.collect(params);

// send collected feed back to owner
	_sendToOwner(tokenId, amount0, amount1);
}

Send fees to the recorded owner

Send the relevant tokens, whether fees or position proceeds, to the NFT's owner.

The sendToOwner helper passes the collected token amounts to safeTransfer to send them to the recorded owner.

solidity
/// @notice Transfers funds to owner of NFT
/// @param tokenId The id of the erc721
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
function _sendToOwner(
	uint256 tokenId,
	uint256 amount0,
	uint256 amount1
) internal {
	// get owner of contract
	address owner = deposits[tokenId].owner;

	address token0 = deposits[tokenId].token0;
	address token1 = deposits[tokenId].token1;
	// send collected fees to owner
	TransferHelper.safeTransfer(token0, owner, amount0);
	TransferHelper.safeTransfer(token1, owner, amount1);
}

Decrease liquidity

Reduce a position's liquidity without necessarily withdrawing the entire position.

The example assumes that the contract already holds the position NFT and that the caller is the address that deposited it.

In production, configure amount0Min and amount1Min to protect against slippage.

Decreasing liquidity

solidity
/// @notice A function that decreases the current liquidity by half. An example to show how to call the `decreaseLiquidity` function defined in periphery.
/// @param tokenId The id of the erc721 token
/// @return amount0 The amount received back in token0
/// @return amount1 The amount returned back in token1
function decreaseLiquidityInHalf(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) {
	// caller must be the owner of the NFT
	require(msg.sender == deposits[tokenId].owner, 'Not the owner');
	// get liquidity data for tokenId
	uint128 liquidity = deposits[tokenId].liquidity;
	uint128 halfLiquidity = liquidity / 2;

	// amount0Min and amount1Min are price slippage checks
	// if the amount received after burning is not greater than these minimums, transaction will fail
	INonfungiblePositionManager.DecreaseLiquidityParams memory params =
		INonfungiblePositionManager.DecreaseLiquidityParams({
			tokenId: tokenId,
			liquidity: halfLiquidity,
			amount0Min: 0,
			amount1Min: 0,
			deadline: block.timestamp
		});

	(amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(params);

	//send liquidity back to owner
	_sendToOwner(tokenId, amount0, amount1);
}

Send fees to the recorded owner

This helper sends relevant tokens, such as fees or position proceeds, to the NFT's owner.

The sendToOwner helper passes the collected token amounts to safeTransfer to send them to the recorded owner.

solidity
/// @notice Transfers funds to owner of NFT
/// @param tokenId The id of the erc721
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
function _sendToOwner(
	uint256 tokenId,
	uint256 amount0,
	uint256 amount1
) internal {
	// get owner of contract
	address owner = deposits[tokenId].owner;

	address token0 = deposits[tokenId].token0;
	address token1 = deposits[tokenId].token1;
	// send collected fees to owner
	TransferHelper.safeTransfer(token0, owner, amount0);
	TransferHelper.safeTransfer(token1, owner, amount1);
}

Increase liquidity

Increasing liquidity within the position's range

The example assumes that the contract already holds the position NFT.

Uniswap V3 does not allow changing the tick boundaries of an existing liquidity position.

In production, configure amount0Min and amount1Min to protect against slippage.

solidity
/// @notice Increases liquidity in the current range
/// @dev Pool must be initialized already to add liquidity
/// @param tokenId The id of the erc721 token
/// @param amount0 The amount to add of token0
/// @param amount1 The amount to add of token1
function increaseLiquidityCurrentRange(
	uint256 tokenId,
	uint256 amountAdd0,
	uint256 amountAdd1
)
external
returns (
	uint128 liquidity,
	uint256 amount0,
	uint256 amount1
)
{
	INonfungiblePositionManager.IncreaseLiquidityParams memory params =
		INonfungiblePositionManager.IncreaseLiquidityParams({
			tokenId: tokenId,
			amount0Desired: amountAdd0,
			amount1Desired: amountAdd1,
			amount0Min: 0,
			amount1Min: 0,
			deadline: block.timestamp
		});

	(liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params);
}

Complete contract

This contract holds Uniswap V3 position NFTs and supports managing positions through fee collection, liquidity increases and decreases, and creation of new positions.

LiquidityExamples.sol
solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '../libraries/TransferHelper.sol';
import '../interfaces/INonfungiblePositionManager.sol';
import '../base/LiquidityManagement.sol';

contract LiquidityExamples is IERC721Receiver {
    address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

    uint24 public constant poolFee = 3000;

    INonfungiblePositionManager public immutable nonfungiblePositionManager;

    /// @notice Represents the deposit of an NFT
    struct Deposit {
        address owner;
        uint128 liquidity;
        address token0;
        address token1;
    }

    /// @dev deposits[tokenId] => Deposit
    mapping(uint256 => Deposit) public deposits;

    constructor(
        INonfungiblePositionManager _nonfungiblePositionManager
    ) {
        nonfungiblePositionManager = _nonfungiblePositionManager;
    }

    // Implementing `onERC721Received` so this contract can receive custody of erc721 tokens
    function onERC721Received(
        address operator,
        address,
        uint256 tokenId,
        bytes calldata
    ) external override returns (bytes4) {
        // get position information

        _createDeposit(operator, tokenId);

        return this.onERC721Received.selector;
    }

    function _createDeposit(address owner, uint256 tokenId) internal {
        (, , address token0, address token1, , , , uint128 liquidity, , , , ) =
            nonfungiblePositionManager.positions(tokenId);

        // set the owner and data for position
        // operator is msg.sender
        deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1});
    }

    /// @notice Calls the mint function defined in periphery, mints the same amount of each token.
    /// For this example we are providing 1000 DAI and 1000 USDC in liquidity
    /// @return tokenId The id of the newly minted ERC721
    /// @return liquidity The amount of liquidity for the position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mintNewPosition()
        external
        returns (
            uint256 tokenId,
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        )
    {
        // For this example, we will provide equal amounts of liquidity in both assets.
        // Providing liquidity in both assets means liquidity will be earning fees and is considered in-range.
        uint256 amount0ToMint = 1000;
        uint256 amount1ToMint = 1000;

        // transfer tokens to contract
        TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amount0ToMint);
        TransferHelper.safeTransferFrom(USDC, msg.sender, address(this), amount1ToMint);

        // Approve the position manager
        TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), amount0ToMint);
        TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), amount1ToMint);

        INonfungiblePositionManager.MintParams memory params =
            INonfungiblePositionManager.MintParams({
                token0: DAI,
                token1: USDC,
                fee: poolFee,
                tickLower: TickMath.MIN_TICK,
                tickUpper: TickMath.MAX_TICK,
                amount0Desired: amount0ToMint,
                amount1Desired: amount1ToMint,
                amount0Min: 0,
                amount1Min: 0,
                recipient: address(this),
                deadline: block.timestamp
            });

        // Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint
        (tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager.mint(params);

        // Create a deposit
        _createDeposit(msg.sender, tokenId);

        // Remove allowance and refund in both assets.
        if (amount0 < amount0ToMint) {
            TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), 0);
            uint256 refund0 = amount0ToMint - amount0;
            TransferHelper.safeTransfer(DAI, msg.sender, refund0);
        }

        if (amount1 < amount1ToMint) {
            TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), 0);
            uint256 refund1 = amount1ToMint - amount1;
            TransferHelper.safeTransfer(USDC, msg.sender, refund1);
        }
    }

    /// @notice Collects the fees associated with provided liquidity
    /// @dev The contract must hold the erc721 token before it can collect fees
    /// @param tokenId The id of the erc721 token
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collectAllFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) {
        // Caller must own the ERC721 position, meaning it must be a deposit

        // set amount0Max and amount1Max to uint256.max to collect all fees
        // alternatively can set recipient to msg.sender and avoid another transaction in `sendToOwner`
        INonfungiblePositionManager.CollectParams memory params =
            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: address(this),
                amount0Max: type(uint128).max,
                amount1Max: type(uint128).max
            });

        (amount0, amount1) = nonfungiblePositionManager.collect(params);

        // send collected feed back to owner
        _sendToOwner(tokenId, amount0, amount1);
    }

    /// @notice A function that decreases the current liquidity by half. An example to show how to call the `decreaseLiquidity` function defined in periphery.
    /// @param tokenId The id of the erc721 token
    /// @return amount0 The amount received back in token0
    /// @return amount1 The amount returned back in token1
    function decreaseLiquidityInHalf(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) {
        // caller must be the owner of the NFT
        require(msg.sender == deposits[tokenId].owner, 'Not the owner');
        // get liquidity data for tokenId
        uint128 liquidity = deposits[tokenId].liquidity;
        uint128 halfLiquidity = liquidity / 2;

        // amount0Min and amount1Min are price slippage checks
        // if the amount received after burning is not greater than these minimums, transaction will fail
        INonfungiblePositionManager.DecreaseLiquidityParams memory params =
            INonfungiblePositionManager.DecreaseLiquidityParams({
                tokenId: tokenId,
                liquidity: halfLiquidity,
                amount0Min: 0,
                amount1Min: 0,
                deadline: block.timestamp
            });

        (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(params);

        //send liquidity back to owner
        _sendToOwner(tokenId, amount0, amount1);
    }

    /// @notice Increases liquidity in the current range
    /// @dev Pool must be initialized already to add liquidity
    /// @param tokenId The id of the erc721 token
    /// @param amount0 The amount to add of token0
    /// @param amount1 The amount to add of token1
    function increaseLiquidityCurrentRange(
        uint256 tokenId,
        uint256 amountAdd0,
        uint256 amountAdd1
    )
        external
        returns (
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        ) {

        TransferHelper.safeTransferFrom(deposits[tokenId].token0, msg.sender, address(this), amountAdd0);
        TransferHelper.safeTransferFrom(deposits[tokenId].token1, msg.sender, address(this), amountAdd1);

        TransferHelper.safeApprove(deposits[tokenId].token0, address(nonfungiblePositionManager), amountAdd0);
        TransferHelper.safeApprove(deposits[tokenId].token1, address(nonfungiblePositionManager), amountAdd1);

        INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager.IncreaseLiquidityParams({
            tokenId: tokenId,
            amount0Desired: amountAdd0,
            amount1Desired: amountAdd1,
            amount0Min: 0,
            amount1Min: 0,
            deadline: block.timestamp
        });

        (liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params);

    }

    /// @notice Transfers funds to owner of NFT
    /// @param tokenId The id of the erc721
    /// @param amount0 The amount of token0
    /// @param amount1 The amount of token1
    function _sendToOwner(
        uint256 tokenId,
        uint256 amount0,
        uint256 amount1
    ) internal {
        // get owner of contract
        address owner = deposits[tokenId].owner;

        address token0 = deposits[tokenId].token0;
        address token1 = deposits[tokenId].token1;
        // send collected fees to owner
        TransferHelper.safeTransfer(token0, owner, amount0);
        TransferHelper.safeTransfer(token1, owner, amount1);
    }

    /// @notice Transfers the NFT to the owner
    /// @param tokenId The id of the erc721
    function retrieveNFT(uint256 tokenId) external {
        // must be the owner of the NFT
        require(msg.sender == deposits[tokenId].owner, 'Not the owner');
        // transfer ownership to original owner
        nonfungiblePositionManager.safeTransferFrom(address(this), msg.sender, tokenId);
        //remove information related to tokenId
        delete deposits[tokenId];
    }
}

Liquidity mining

Overview

Introduction

DeFi projects, token issuers, and other participants may want to incentivize liquidity provision within the price range of a Uniswap V3 pool. This section explains one particular incentive scheme.

Background

First, define the terminology. A program that incentivizes liquidity is referred to here as an Incentive.

  • rewardToken (reward token)
    • The incentive creator selects the ERC20 token to distribute as a reward for liquidity provision.
  • pool
    • Address of the Uniswap V3 pool for which liquidity is incentivized.
  • startTime (start time)
    • Unix timestamp at which reward distribution starts.
  • endTime (end time)
    • Unix timestamp marking the scheduled end of the incentive.
  • refundee
    • Address entitled to claim remaining rewards after the incentive concludes.

Each incentive has an associated reward allocation: the total amount of reward tokens available for distribution over its lifetime.

Reward calculation

With the incentive defined, consider how rewards are allocated among participants.

The incentive creator selects the reward amount and program duration. This determines the quantity of reward tokens to distribute per second. This quantity is called the reward rate. For each second between startTime and endTime, the reward rate is distributed proportionally across all liquidity that is in range during that second. Importantly, the calculation accounts for all in-range liquidity, not only liquidity that has opted into the program. The incentive creator must therefore choose a reward rate appropriate for potentially rewarding every in-range liquidity provider during the program.

Staking

To participate in an incentive, a user deposits their position NFT into the staking contract. The staking contract must ensure that liquidity cannot be removed from a participating position while it is staked.

Once deposited, the NFT may be staked in any number of active incentives associated with its Uniswap V3 pool. Staking may occur atomically with the initial deposit. A staked NFT begins earning rewards according to the allocation mechanism described above. Users can claim rewards as they become available after the relevant staking operations, or wait until the end of the program to reduce overhead.

The first step in joining an incentive program is to deposit a position NFT into the designated staking contract. This temporarily transfers custody of the NFT to the contract. Custody prevents the position's liquidity from being removed while the NFT is participating in the incentive.

Once deposited, the NFT may be staked in active incentives associated with its Uniswap V3 pool. This may also be done as part of the initial deposit. The staked NFT then begins earning rewards according to the algorithm described above. Users can realize rewards during the program by unstaking and claiming, as permitted by the staking implementation. Alternatively, they can wait until the program ends to reduce transaction overhead.

Concluding the program

Conditions for ending the program

  1. block.timestamp >= endTime (the timestamp has reached or passed the scheduled end time). The scheduled program period must have ended. However, reaching the scheduled end time does not itself conclude the program. Some users may still have positions staked near or after the scheduled end. This leads to the second condition.

  2. All NFTs have been unstaked. The program can conclude only after every participating NFT has been unstaked. To make this possible, anyone may unstake an NFT after the scheduled end. However, doing so does not grant that caller the right to claim another owner's outstanding rewards. This allows the program to conclude even if individual users do not unstake their NFTs themselves.

When unallocated rewards remain

Remaining rewards can be understood by considering that the reward rate accounts for all in-range liquidity. Because only participating liquidity providers can claim rewards, a program may have reward tokens that remain unclaimed. The designated refundees therefore have an incentive to conclude the program. This design reflects the difficulty of allocating rewards consistently according to Uniswap V3 liquidity.

Finally, the rewards of positions that remain staked after the scheduled end may increase or decrease. The magnitude depends on the staker's share of active liquidity, how long the position remains staked after the end time, and the order in which positions are unstaked. In an adverse case, rewards may decrease inversely with the elapsed duration, with half the original amount remaining after twice the duration and one-third after three times the duration.

  • Suppose a program has a duration of one week (seven days), with rewards considered over that interval.
  • If user A leaves their position staked beyond the scheduled end, the eventual allocation can change while the position remains staked.
  • Two weeks after the program ends, user A unstakes the position and claims the reward.

In this example, user A's reward may have decreased by the time the position is unstaked. The delayed unstaking may result in a lower final allocation, depending on the incentive's reward calculations.

The magnitude of the change depends on the following factors.

  • The staker's share of total active liquidity.
    • The percentage of active liquidity attributable to user A.
  • Time staked after the scheduled end.
    • How long user A waits before unstaking.
  • Unstaking order.
    • The sequence in which other participants unstake.

In an adverse case, the reward can decrease inversely with elapsed time.

  • After twice the relevant duration, the reward may be half the original amount.
  • After three times the duration, it may be one-third of the original amount.

From a game-theoretic perspective, stakers have an incentive to unstake and claim in a timely manner to protect their rewards. Refundees are also interested in reclaiming remaining rewards and may initiate unstaking of positions that remain staked after the scheduled end.

Flash swaps

Introduction

This example contract invokes the flash operation on a V3 pool to borrow specified quantities of token0 and token1. It exchanges those tokens in other pools for the same token pair with different fee tiers. After the swaps, it repays the original pool and sends any remaining proceeds to the original caller.

Flash transaction overview

A flash transaction allows tokens to be transferred before the corresponding settlement requirements have been satisfied. In a swap, this can mean transferring the output before the pool receives the input.

Ordinary token transfers require conditions such as a sufficient source balance, and on-chain execution requires gas. A flash operation allows the borrowing or settlement requirements to be satisfied later in the same transaction. This provides flexibility for composing multiple operations atomically; it does not remove balance or gas requirements.

In a swap, output tokens may be transferred before the corresponding input is paid. This allows the recipient to compose operations before completing settlement in the same transaction.

Uniswap V3 pool contracts provide a function called flash. flash transfers specified amounts of token0 and token1 to the designated recipient. Fees are calculated on the borrowed amounts. The borrowed amounts and applicable fees must be repaid to the pool before the flash operation completes. The fourth parameter, data, carries arbitrary encoded information that can be decoded in the callback.

solidity
function flash(
	address recipient,
	uint256 amount0,
	uint256 amount1,
	bytes calldata data
) external override lock noDelegateCall {

Flash callback

To understand how tokens borrowed through flash are repaid, examine the function implementation. The following snippet is part of the flash function.

solidity
IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);

The pool invokes the flash callback on the contract that called it (msg.sender). It passes the fees required to calculate the amounts owed to the pool and the arbitrary data supplied in the data parameter.

Uniswap V3 defines three callback interfaces that integrations can implement with custom logic.

  • uniswapV3SwapCallback
  • uniswapV3MintCallback
  • uniswapV3FlashCallback

The example calls flash and implements uniswapV3FlashCallback to execute the operations needed to complete the transaction.

Inheriting V3 contracts

Implement IUniswapV3FlashCallback and inherit PeripheryPayments to use the associated functionality. The inherited contracts may depend on other contracts and libraries. For example, LowGasSafeMath provides checked arithmetic helpers for uint256 and int256.

solidity
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';

import '@uniswap/v3-periphery/contracts/base/PeripheryPayments.sol';
import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';

contract PairFlash is IUniswapV3FlashCallback, PeripheryPayments {
	using LowGasSafeMath for uint256;
	using LowGasSafeMath for int256;

	ISwapRouter public immutable swapRouter;

	constructor(
		ISwapRouter _swapRouter,
		address _factory,
		address _WETH9
	) PeripheryImmutableState(_factory, _WETH9) {
		swapRouter = _swapRouter;
	}

Calling flash

Parameter structs

Calling flash requires the initial flash parameters and any additional information to pass into the callback.

FlashParams contains the token addresses, amounts to borrow, and three fee tiers identifying the borrowing pool and the two swap pools.

solidity
struct FlashParams {
	address token0;
	address token1;
	uint24 fee1;
	uint256 amount0;
	uint256 amount1;
	uint24 fee2;
	uint24 fee3;
}

FlashCallbackData stores the information passed to the callback. It includes a poolKey returned by the PoolAddress library, identifying the sorted token pair and applicable fee tier.

solidity
struct FlashCallbackData {
	uint256 amount0;
	uint256 amount1;
	address payer;
	PoolAddress.PoolKey poolKey;
	uint24 poolFee2;
	uint24 poolFee3;
}

Pool key

Populate poolKey with the relevant fields of the FlashParams struct stored in memory as params.

solidity
function initFlash(FlashParams memory params) external {
	PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1});
}

Declare pool as an IUniswapV3Pool so the contract can invoke flash on the selected pool.

solidity
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));

Calling flash

Finally, call flash on the selected pool. Use abi.encode to encode a FlashCallbackData struct for the last argument. The callback decodes this data to obtain the information needed for subsequent operations.

solidity
pool.flash(
	address(this),
	params.amount0,
	params.amount1,
	abi.encode(
		FlashCallbackData({
			amount0: params.amount0,
			amount1: params.amount1,
			payer: msg.sender,
			poolKey: poolKey,
			poolFee2: params.fee2,
			poolFee3: params.fee3
		})
	)
);

The complete function is shown below.

solidity
//fee1 is the fee of the pool from the initial borrow
//fee2 is the fee of the first pool to arb from
//fee3 is the fee of the second pool to arb from
struct FlashParams {
	address token0;
	address token1;
	uint24 fee1;
	uint256 amount0;
	uint256 amount1;
	uint24 fee2;
	uint24 fee3;
}

// fee2 and fee3 are the two other fees associated with the two other pools of token0 and token1
struct FlashCallbackData {
	uint256 amount0;
	uint256 amount1;
	address payer;
	PoolAddress.PoolKey poolKey;
	uint24 poolFee2;
	uint24 poolFee3;
}

function initFlash(FlashParams memory params) external {
	PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1});
	IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
	pool.flash(
		address(this),
		params.amount0,
		params.amount1,
		abi.encode(
			FlashCallbackData({
				amount0: params.amount0,
				amount1: params.amount1,
				payer: msg.sender,
				poolKey: poolKey,
				poolFee2: params.fee2,
				poolFee3: params.fee3
			})
		)
	);
}

Flash callback

Implement custom flash callback logic to execute the required swaps, repay the pool, and transfer any remaining proceeds to the original payer.

Declare and implement the uniswapV3FlashCallback function.

solidity
function uniswapV3FlashCallback(
	uint256 fee0,
	uint256 fee1,
	bytes calldata data
) external override {
	FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData));

Each callback must verify that its caller is an authentic V3 pool. Without verification, an unauthorized caller could invoke the callback directly and misuse its token-handling logic.

solidity
CallbackValidation.verifyCallback(factory, decoded.poolKey);

Assign the token0 and token1 addresses to local variables so the router can interact with the borrowed tokens.

solidity
address token0 = decoded.poolKey.token0;
address token1 = decoded.poolKey.token1;

TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0);
TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1);

Calculate the minimum token amounts required from the two swaps. These constraints ensure that the swaps produce enough output to repay the corresponding borrowed principal and fees.

  • amount1Min
    • Minimum required amount of token1.
  • amount0Min
    • Minimum required amount of token0.

These values include the applicable fee on each borrowed amount. The fees are represented by fee0 and fee1, corresponding to token0 and token1. Including the fees in the minimum output amounts prevents swaps that cannot cover repayment; it does not guarantee a net profit after gas costs.

solidity
uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1);
uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0);

Starting the swaps

solidity
uint256 amountOut0 =
	swapRouter.exactInputSingle(
	ISwapRouter.ExactInputSingleParams({
		tokenIn: token1,
		tokenOut: token0,
		fee: decoded.poolFee2,
		recipient: address(this),
		deadline: block.timestamp + 200,
		amountIn: decoded.amount1,
		amountOutMinimum: amount0Min,
		sqrtPriceLimitX96: 0
	})
);

The preceding code invokes the first swap. It calls exactInputSingle through the router interface. It uses amount0Min as the minimum output amount in the illustrated implementation and stores the returned amount in amountOut0.

Two parameters are worth highlighting.

  • sqrtPriceLimitX96

    • Limits how far the swap may move the pool price.
    • The pool represents price through the ratio of token1 to token0, encoded as a square-root fixed-point value.
    • This parameter is useful when a caller wants to limit execution to a specified price boundary.
    • This example uses 0 to select the router's default price boundary.
  • deadline

    • Timestamp after which the transaction reverts.
    • Limits the time window for execution when market conditions may change.
    • The educational example uses a permissive deadline; it should not be treated as a production deadline policy.

The first swap uses the borrowed amount1 as an exact input amount in exchange for token0.

It exchanges the borrowed token1 for token0 along the chosen pool.

This call uses a pool for the same token pair. The selected pool has the fee tier specified for this swap in the example parameters.

Fee tiers identify pools with different swap fee rates.

Different pools for the same token pair may have fee tiers such as 0.05%, 0.3%, or 1%. The selected fee tier affects trading costs and execution results. The swap uses the configured pool and accounts for its fees.

solidity
uint256 amountOut1 = swapRouter.exactInputSingle(
	ISwapRouter.ExactInputSingleParams({
		tokenIn: token0,
		tokenOut: token1,
		fee: decoded.poolFee3,
		recipient: address(this),
		deadline: block.timestamp + 200,
		amountIn: decoded.amount0,
		amountOutMinimum: amount1Min,
		sqrtPriceLimitX96: 0
	})
);

The preceding code configures the second swap. It uses the third configured fee tier and the amount0 borrowed from the original pool.

The second swap performs the following steps.

  1. Select the third configured fee tier The first swap used a pool with one fee tier; the second swap uses the other fee tier specified in the parameters. This identifies the pool in which the second swap is executed.

  2. Use the borrowed amount0 Use the previously borrowed token0 amount (amount0) as the input for this swap. The second swap therefore exchanges token0 obtained from the original pool for token1.

The second swap uses the pool identified by the third configured fee tier and consumes the borrowed token0. The example attempts to obtain sufficient output to repay the original pool and retain any surplus.

Repaying the pool

To repay the original pool, calculate the amounts owed and prepare the token payment operations. The following code illustrates this process.

solidity
uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0);
uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1);

TransferHelper.safeApprove(token0, address(this), amount0Owed);
TransferHelper.safeApprove(token1, address(this), amount1Owed);
  1. Calculate amount0Owed and amount1Owed Calculate the token balances payable to the original pool. Add each fee (fee0 and fee1) to the corresponding borrowed amount, amount0 and amount1.

  2. Configure approvals The example prepares token approvals while setting up the payments back to the original pool. It uses TransferHelper.safeApprove. The example approves the contract itself for the calculated amounts (amount0Owed and amount1Owed). The actual repayment uses the payment helper; when the contract itself is the payer, it can transfer tokens directly.

This establishes the repayment amounts and prepares the token payments.

If an amount is owed, call the pay helper. The callback is externally callable by the pool after verification, and it can invoke the inherited internal pay function.

solidity
if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed);
if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed);
  1. Check amount0Owed and amount1Owed Check whether each of the amounts owed for token0 and token1 is nonzero. A nonzero amount indicates that payment is required.

  2. Call pay Call the pay function for each nonzero amount. This helper performs the token payment. Supply the corresponding token address and amount owed, along with the payer and recipient. The call transfers the required tokens to settle the payment.

This code illustrates how pay settles the nonzero amounts owed to the pool.

The initFlash function initiates the flash transaction, and the callback sends any surplus to the original caller identified by the decoded payer field.

solidity
if (amountOut0 > amount0Owed) {
	uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed);

	TransferHelper.safeApprove(token0, address(this), profit0);
	pay(token0, address(this), decoded.payer, profit0);
}

if (amountOut1 > amount1Owed) {
	uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed);
	TransferHelper.safeApprove(token0, address(this), profit1);
	pay(token1, address(this), decoded.payer, profit1);
}
  1. Check amountOut0 and amountOut1 Check whether the output amounts of token0 and token1 exceed the respective repayment amounts (amount0Owed and amount1Owed). A positive difference represents a surplus of the corresponding token.

  2. Calculate the surplus Calculate each surplus if it is positive. Subtract amount0Owed from amountOut0 to obtain profit0, and subtract amount1Owed from amountOut1 to obtain profit1 where applicable.

  3. Approve and pay For any positive surplus, the example calls safeApprove and then uses pay to transfer the surplus to decoded.payer, the original caller of initFlash.

Complete function code

uniswapV3FlashCallback
solidity
function uniswapV3FlashCallback(
	uint256 fee0,
	uint256 fee1,
	bytes calldata data
) external override {
	FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData));
	CallbackValidation.verifyCallback(factory, decoded.poolKey);

	address token0 = decoded.poolKey.token0;
	address token1 = decoded.poolKey.token1;

	TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0);
	TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1);

	// profitable check
	// exactInputSingle will fail if this amount not met
	uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1);
	uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0);

	// call exactInputSingle for swapping token1 for token0 in pool w/fee2
	uint256 amountOut0 =
	swapRouter.exactInputSingle(
		ISwapRouter.ExactInputSingleParams({
			tokenIn: token1,
			tokenOut: token0,
			fee: decoded.poolFee2,
			recipient: address(this),
			deadline: block.timestamp + 200,
			amountIn: decoded.amount1,
			amountOutMinimum: amount0Min,
			sqrtPriceLimitX96: 0
		})
	);

	// call exactInputSingle for swapping token0 for token 1 in pool w/fee3
	uint256 amountOut1 =
	swapRouter.exactInputSingle(
		ISwapRouter.ExactInputSingleParams({
			tokenIn: token0,
			tokenOut: token1,
			fee: decoded.poolFee3,
			recipient: address(this),
			deadline: block.timestamp + 200,
			amountIn: decoded.amount0,
			amountOutMinimum: amount1Min,
			sqrtPriceLimitX96: 0
		})
	);

	// end up with amountOut0 of token0 from first swap and amountOut1 of token1 from second swap
	uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0);
	uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1);

	TransferHelper.safeApprove(token0, address(this), amount0Owed);
	TransferHelper.safeApprove(token1, address(this), amount1Owed);

	if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed);
	if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed);

	// if profitable pay profits to payer
	if (amountOut0 > amount0Owed) {
		uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed);

		TransferHelper.safeApprove(token0, address(this), profit0);
		pay(token0, address(this), decoded.payer, profit0);
	}
	if (amountOut1 > amount1Owed) {
		uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed);
		TransferHelper.safeApprove(token0, address(this), profit1);
		pay(token1, address(this), decoded.payer, profit1);
	}
}

Complete contract

PairFlash.sol
solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';

import '@uniswap/v3-periphery/contracts/base/PeripheryPayments.sol';
import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';

/// @title Flash contract implementation
/// @notice An example contract using the Uniswap V3 flash function
contract PairFlash is IUniswapV3FlashCallback, PeripheryImmutableState, PeripheryPayments {
    using LowGasSafeMath for uint256;
    using LowGasSafeMath for int256;

    ISwapRouter public immutable swapRouter;

    constructor(
        ISwapRouter _swapRouter,
        address _factory,
        address _WETH9
    ) PeripheryImmutableState(_factory, _WETH9) {
        swapRouter = _swapRouter;
    }

    /// @param fee0 The fee from calling flash for token0
    /// @param fee1 The fee from calling flash for token1
    /// @param data The data needed in the callback passed as FlashCallbackData from `initFlash`
    /// @notice implements the callback called from flash
    /// @dev fails if the flash is not profitable, meaning the amountOut from the flash is less than the amount borrowed
    function uniswapV3FlashCallback(
        uint256 fee0,
        uint256 fee1,
        bytes calldata data
    ) external override {
        FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData));
        CallbackValidation.verifyCallback(factory, decoded.poolKey);

        address token0 = decoded.poolKey.token0;
        address token1 = decoded.poolKey.token1;

        TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0);
        TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1);

        // profitable check
        // exactInputSingle will fail if this amount not met
        uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1);
        uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0);

        // call exactInputSingle for swapping token1 for token0 in pool w/fee2
        uint256 amountOut0 =
            swapRouter.exactInputSingle(
                ISwapRouter.ExactInputSingleParams({
                    tokenIn: token1,
                    tokenOut: token0,
                    fee: decoded.poolFee2,
                    recipient: address(this),
                    deadline: block.timestamp,
                    amountIn: decoded.amount1,
                    amountOutMinimum: amount0Min,
                    sqrtPriceLimitX96: 0
                })
            );

        // call exactInputSingle for swapping token0 for token 1 in pool w/fee3
        uint256 amountOut1 =
            swapRouter.exactInputSingle(
                ISwapRouter.ExactInputSingleParams({
                    tokenIn: token0,
                    tokenOut: token1,
                    fee: decoded.poolFee3,
                    recipient: address(this),
                    deadline: block.timestamp,
                    amountIn: decoded.amount0,
                    amountOutMinimum: amount1Min,
                    sqrtPriceLimitX96: 0
                })
            );

        // end up with amountOut0 of token0 from first swap and amountOut1 of token1 from second swap
        uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0);
        uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1);

        TransferHelper.safeApprove(token0, address(this), amount0Owed);
        TransferHelper.safeApprove(token1, address(this), amount1Owed);

        if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed);
        if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed);

        // if profitable pay profits to payer
        if (amountOut0 > amount0Owed) {
            uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed);

            TransferHelper.safeApprove(token0, address(this), profit0);
            pay(token0, address(this), decoded.payer, profit0);
        }
        if (amountOut1 > amount1Owed) {
            uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed);
            TransferHelper.safeApprove(token0, address(this), profit1);
            pay(token1, address(this), decoded.payer, profit1);
        }
    }

    //fee1 is the fee of the pool from the initial borrow
    //fee2 is the fee of the first pool to arb from
    //fee3 is the fee of the second pool to arb from
    struct FlashParams {
        address token0;
        address token1;
        uint24 fee1;
        uint256 amount0;
        uint256 amount1;
        uint24 fee2;
        uint24 fee3;
    }
    // fee2 and fee3 are the two other fees associated with the two other pools of token0 and token1
    struct FlashCallbackData {
        uint256 amount0;
        uint256 amount1;
        address payer;
        PoolAddress.PoolKey poolKey;
        uint24 poolFee2;
        uint24 poolFee3;
    }

    /// @param params The parameters necessary for flash and the callback, passed in as FlashParams
    /// @notice Calls the pools flash function with data needed in `uniswapV3FlashCallback`
    function initFlash(FlashParams memory params) external {
        PoolAddress.PoolKey memory poolKey =
            PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1});
        IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
        // recipient of borrowed amounts
        // amount of token0 requested to borrow
        // amount of token1 requested to borrow
        // need amount 0 and amount1 in callback to pay back pool
        // recipient of flash should be THIS contract
        pool.flash(
            address(this),
            params.amount0,
            params.amount1,
            abi.encode(
                FlashCallbackData({
                    amount0: params.amount0,
                    amount1: params.amount1,
                    payer: msg.sender,
                    poolKey: poolKey,
                    poolFee2: params.fee2,
                    poolFee3: params.fee3
                })
            )
        );
    }
}

Conclusion

This article examined the official Uniswap V3 documentation through translation and supplementary explanations.

I hope it helped clarify the protocol's developer interfaces.

I also publish articles on blockchain and AI on my blog and Qiita.

https://chaldene.net/