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

DeCipher uses AI to automatically generate smart contract documentation.

For instructions on using it, see the following article.

This article reflects my own experience using DeCipher. If you find any inaccuracies, please let me know in the comments.

The DeCipher page used in this article is linked below.

The Etherscan link is below.

Overview

The SwapRouter02 contract is an important component of the Uniswap decentralized trading protocol. It acts as a router for exchanging tokens on the Uniswap platform.

The primary purpose of SwapRouter02 is to enable efficient and secure token exchanges between users. It provides a straightforward interface for traders to execute token swaps at the best available price with minimal slippage.

The SwapRouter02 contract enables smooth, secure exchanges between tokens on the Uniswap decentralized trading platform. It helps users minimize slippage (the difference in price) and swap tokens at the best trading price.

For example, suppose you hold token A and want to exchange it for token B. The SwapRouter02 contract facilitates that exchange. By interacting with this contract, you can calculate the optimal trading route from token A to token B and execute the trade.

The contract emphasizes an accessible trading experience. Users can perform token swaps through simple steps without worrying about complex calculations or procedures.

The SwapRouter02 contract also takes security into consideration. It incorporates mechanisms intended to prevent unauthorized actions and price manipulation, allowing users to trade securely.

The SwapRouter02 contract serves the following important roles.

Token swaps

The contract enables users to exchange one token for another through Uniswap liquidity pools. It calculates the optimal swap route and executes the trade on the user's behalf.

Providing liquidity

The contract allows users to provide liquidity to Uniswap pools by depositing tokens. This ensures that sufficient liquidity is available for token swaps.

The SwapRouter02 contract provides a mechanism for users to participate in Uniswap liquidity pools and supply token liquidity. These pools provide the token quantities needed for exchanges and are an important component of smooth token swaps.

Consider a concrete example. Suppose you deposit tokens into a liquidity pool for token A and token B. This increases the supply of tokens A and B in the pool and the total quantity of tokens it holds.

As the token supply increases, more tokens are available when users want to exchange token A for token B. This reduces price movement during swaps and lowers slippage (the difference in price). As a result, users can execute token swaps at better trading prices.

Supplying tokens to liquidity pools is therefore an important way to improve the efficiency of token swaps. Depositing tokens into these pools increases liquidity across the platform and allows users to exchange tokens smoothly on more favorable terms.

Price calculation

The contract provides accurate, up-to-date price information for tokens on the Uniswap platform. Users can base their trading decisions on this price information.

The SwapRouter02 contract provides price information for tokens traded on Uniswap. This allows users to obtain accurate, current price information when executing token swaps.

For example, consider exchanging token A for token B. A user can obtain token price information through SwapRouter02 and check the current exchange rate between token A and token B. This lets the user understand the actual trading price and how much token B will be received in exchange for token A.

Accurate, up-to-date price information is important when executing token swaps. With accurate prices, users can plan their trading strategies and execute trades at the best time. They can also respond to sudden price movements and unauthorized manipulation.

The price information provided by SwapRouter02 helps users make informed decisions and improves reliability and security when swapping tokens.

Security and efficiency

The SwapRouter02 contract is designed to ensure the security and efficiency of token swaps. It incorporates mechanisms intended to prevent manipulation such as front-running and optimizes trade routes to minimize slippage and maximize liquidity.

The SwapRouter02 contract incorporates various measures to ensure security and efficiency during token swaps.

On the security side, it incorporates mechanisms intended to prevent improper actions such as front-running and price manipulation. Front-running means attempting to profit by executing a trade ahead of someone else. To prevent such behavior, the SwapRouter02 contract employs approaches such as managing transaction order and establishing priority through appropriate fees.

For efficiency, optimizing the trade route to minimize slippage and maximize liquidity is important. The SwapRouter02 contract selects an optimal route from multiple liquidity pools and token paths, enabling token swaps with minimal slippage. This increases the likelihood of users exchanging tokens at the best trading price.

In short, the SwapRouter02 contract aims to balance security and efficiency by incorporating mechanisms to prevent improper activity and selecting optimal routes to minimize slippage during swaps. This allows users to execute secure and efficient token swaps.

The SwapRouter02 contract therefore plays an important role in enabling smooth, secure token swaps on Uniswap. It offers users a reliable and efficient method while helping maintain the integrity and stability of the decentralized trading ecosystem.

Usage

The SwapRouter02 contract is a smart contract for performing token swaps on the Uniswap decentralized exchange. It implements the ISwapRouter02 interface and provides various token swap functions.

Purpose of the contract

The purpose of the SwapRouter02 contract is to enable users to swap tokens on the Uniswap decentralized exchange. It provides a convenient, efficient way to execute token swaps using Uniswap liquidity pools.

Procedure

The following steps are needed to swap tokens on Uniswap.

  1. Deploy the SwapRouter02 contract.
  2. Approve the contract to spend the tokens.
  3. Call exactInput or exactOutput to execute the token swap.

This enables users to swap tokens easily and take advantage of Uniswap liquidity pools for smooth exchanges.

Functions

The SwapRouter02 contract provides the following token swap functions.

exactInput

Executes a token swap with a specified input amount. A minimum output amount is also specified. The swap executes for the specified input amount while guaranteeing the corresponding minimum output.

exactOutput

Executes a token swap with a specified output amount. A maximum input amount is also specified. It calculates the maximum input amount needed to achieve the specified output and uses it to perform the token swap.

refundETH

Refunds excess ETH sent to the contract. This function refunds unnecessary ETH sent during a token swap.

WETH9

Returns the address of the WETH9 token contract. Use this function to obtain the address of WETH9 (Wrapped Ether).

Usage

Executing an exact-input swap.

  1. Approve the SwapRouter02 contract to spend the specified amount of input tokens.
  2. Call exactInput with the following parameters.
    • amountIn
      • Exact input token amount.
    • amountOutMin
      • Minimum output token amount.
      • Guarantees the minimum output amount for the swap.
    • path
      • Array of token addresses for the token swap.
      • Specifies the swap path between the given tokens.
    • to
      • Address receiving the output tokens.
    • deadline
      • Deadline for executing the swap.

Executing an exact-output swap.

  1. Approve the SwapRouter02 contract to spend the maximum input token amount.
  2. Call exactOutput with the following parameters.
    • amountOut
      • Exact output token amount.
    • amountInMax
      • Maximum input token amount.
      • Specifies the maximum input used in the swap.
    • path
      • Array of token addresses for the token swap.
      • Specifies the swap path between the given tokens.
    • to
      • Address receiving the output tokens.
    • deadline
      • Deadline for executing the swap.

Events

Swap

An event indicating that a token swap was executed.

  • sender
    • Address that initiated the swap.
  • amount0In
    • Input amount of token 0.
  • amount1In
    • Input amount of token 1.
  • amount0Out
    • Output amount of token 0.
  • amount1Out
    • Output amount of token 1.
  • to
    • Address that received the output tokens.

RefundETH

An event indicating that excess ETH was refunded.

  • amount
    • Amount of ETH refunded.
  • to
    • Address receiving the refund.

https://chaldene.net/erc20

https://chaldene.net/erc721

https://chaldene.net/erc721-extension

Parameters

_factoryV2

Address of the V2 factory contract.

  • The V2 factory contract creates and manages Uniswap V2 pools.
  • It creates token liquidity pools and enables token swaps.

_factoryV3

Address of the V3 factory contract.

  • The V3 factory contract creates and manages Uniswap V3 pools.
  • V3 supports more precise price ranges, enabling efficient token swaps.

_positionManager

Address of the position manager contract.

  • The position manager contract manages positions within Uniswap V3 liquidity pools.
  • Users can provide and manage token liquidity through this contract.

_WETH9

Address of the WETH9 contract.

  • WETH9 (Wrapped Ether) is an ERC20 tokenized version of Ethereum's native ETH.
  • It allows ETH to be handled as a token, which is useful when swapping tokens on decentralized exchanges and similar platforms.

The Uniswap V2 and Uniswap V3 factory contracts support different versions of the Uniswap protocol. These factory contracts are used to create and manage features and pools specific to their respective versions.

Choosing between them depends on the differences and characteristics of the Uniswap V2 and Uniswap V3 factories.

Uniswap V2 factory contract

Version stability Uniswap V2 is a relatively old version used by many users. Established token pools already exist, and their liquidity is available for use.

General usage Uniswap V2 is widely used for ordinary token swaps and liquidity provision. In particular, if a V2 token pool already exists and is widely used, it may make sense to continue using V2.

Uniswap V3 factory contract

Price range optimization Uniswap V3 supports fine-grained configuration of more precise price ranges. This allows users to swap tokens more efficiently within particular price ranges.

Concentrated liquidity With Uniswap V3, liquidity can be concentrated within particular price ranges. This enables efficient token swaps within those ranges.

Advanced features Uniswap V3 adds advanced features for managing various activities. These enable more granular control and optimization of token swaps.

Choose the appropriate version according to the purpose and requirements of the token swap.

Contracts

SwapRouter02

SwapRouter02
solidity
contract SwapRouter02 is ISwapRouter02, V2SwapRouter, V3SwapRouter, ApproveAndCall, MulticallExtended, SelfPermit {
    constructor(
        address _factoryV2,
        address factoryV3,
        address _positionManager,
        address _WETH9
    ) ImmutableState(_factoryV2, _positionManager) PeripheryImmutableState(factoryV3, _WETH9) {}
}

ISwapRouter02

Implements the ISwapRouter02 interface. This allows the SwapRouter02 contract to provide the functionality defined by the interface, including the ISwapRouter02 methods.

V2SwapRouter

A contract providing Uniswap V2 swap router functionality. V2SwapRouter implements swap-related functionality specific to Uniswap V2.

V3SwapRouter

A contract providing Uniswap V3 swap router functionality. V3SwapRouter implements swap-related functionality specific to Uniswap V3.

ApproveAndCall

Allows users to perform a call together with an approval to the contract. This makes swap operations more efficient.

ApproveAndCall provides a mechanism for executing a specific function together with a token approval. This allows users to combine token approvals and token operations (such as swaps) in one transaction.

Ordinarily, when users want to perform an operation using tokens (such as a swap), the following steps are required.

  1. The user approves the contract that will operate on the tokens. This authorizes the contract to spend a specific quantity of tokens.
  2. After approval, the user calls a separate function to perform the actual token operation (such as a swap).

ApproveAndCall performs these steps in a single transaction. Specifically, the user calls a function to perform token approval and the operation together. This function works as follows:

  1. The user calls the ApproveAndCall function, providing information about the approval amount and intended operation.
  2. The contract checks the user's token approval and performs the specified operation.

Users can therefore combine token approvals and operations in one transaction instead of waiting for several transactions, making operations such as swaps more efficient.

MulticallExtended

Allows multiple function calls to be executed in one transaction. Combining multiple operations in one transaction helps save gas.

SelfPermit

Provides token approval functionality for the contract itself based on Ethereum's EIP-2612.

SelfPermit is a feature implemented based on Ethereum's EIP-2612 proposal that allows a contract to approve itself to spend tokens.

Ordinarily, when a user approves a contract to operate on tokens, a separate step is required to establish that the user is the token owner. However, EIP-2612 simplifies this process by providing a mechanism for a contract to approve itself to spend tokens without requiring a separate approval transaction from the token owner. The contract can thus obtain the approval required to operate directly on a specific token without further intervention by the token owner.

Specifically, with SelfPermit, the contract follows these steps.

  1. The contract creates data requesting approval for itself to spend tokens.
  2. The token owner signs the data to express consent.
  3. The contract uses the signed data to approve itself to spend the tokens.

This allows the token owner to authorize a contract to operate on a specific token with one approval and can improve security.

SelfPermit provides an efficient, secure way for a contract to obtain token approval for itself, streamlining token operations.

constructor

The contract's constructor function. It receives the addresses of the Uniswap V2 and V3 factory contracts, the position manager contract, and the WETH9 token contract. These addresses are configured during contract initialization and used for swap operations and related functionality.

V2SwapRouter

See the following article for a detailed explanation.

V3SwapRouter

See the following article for a detailed explanation.

ApproveAndCall

An abstract contract that provides functionality for executing a specific function together with a token approval. It provides a mechanism for users to perform a token approval and function call together. This combines token approval and the operation in one transaction, improving operational efficiency.


tryApprove

tryApprove
solidity
function tryApprove(address token, uint256 amount) private returns (bool) {
        (bool success, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.approve.selector, positionManager, amount));
        return success && (data.length == 0 || abi.decode(data, (bool)));
}

Overview A function that approves PositionManager to spend a specified token.

Parameters

  • token
    • Address of the token to approve.
  • amount
    • Quantity of tokens to approve.

Return value

  • bool
    • Whether approval succeeded.

getApprovalType

getApprovalType
solidity
function getApprovalType(address token, uint256 amount) external override returns (ApprovalType) {
        // check existing approval
        if (IERC20(token).allowance(address(this), positionManager) >= amount) return ApprovalType.NOT_REQUIRED;

        // try type(uint256).max / type(uint256).max - 1
        if (tryApprove(token, type(uint256).max)) return ApprovalType.MAX;
        if (tryApprove(token, type(uint256).max - 1)) return ApprovalType.MAX_MINUS_ONE;

        // set approval to 0 (must succeed)
        require(tryApprove(token, 0));

        // try type(uint256).max / type(uint256).max - 1
        if (tryApprove(token, type(uint256).max)) return ApprovalType.ZERO_THEN_MAX;
        if (tryApprove(token, type(uint256).max - 1)) return ApprovalType.ZERO_THEN_MAX_MINUS_ONE;

        revert();
}

Overview A function that obtains the token approval type.

Details Determines whether approval is required for a particular token and which approval type is necessary. It attempts multiple approval methods and returns the appropriate approval type.

Parameters

  • token
    • Address of the token to be approved.
  • amount
    • Quantity of tokens to approve.

Return value

  • ApprovalType
    • Approval type (NOT_REQUIRED, MAX, MAX_MINUS_ONE, ZERO_THEN_MAX, or ZERO_THEN_MAX_MINUS_ONE).

NOT_REQUIRED

This approval type indicates that sufficient approval already exists and no new approval is required.

MAX

This approval type indicates that the maximum token quantity should be approved.

MAX_MINUS_ONE

This approval type indicates that the maximum token quantity minus one should be approved. A quantity slightly below the maximum token quantity can be approved.

ZERO_THEN_MAX

This approval type indicates that the token allowance is first set to 0 and then the maximum quantity is approved. Token spending can be temporarily restricted, after which the maximum quantity can be approved for the required operation.

ZERO_THEN_MAX_MINUS_ONE

This approval type indicates that the token allowance is first set to 0 and then the maximum quantity minus one is approved. Token spending can be temporarily restricted, after which a quantity slightly below the maximum can be approved for the required operation.


approveMax

approveMax
solidity
function approveMax(address token) external payable override {
        require(tryApprove(token, type(uint256).max));
}

Overview A function that approves the maximum token quantity.

Parameters

  • token
    • Address of the token to be approved.

approveMaxMinusOne

approveMaxMinusOne
solidity
function approveMaxMinusOne(address token) external payable override {
        require(tryApprove(token, type(uint256).max - 1));
}

Overview A function that approves the maximum token quantity minus one.

Parameters

  • token
    • Address of the token to be approved.

approveZeroThenMax

approveZeroThenMax
solidity
function approveZeroThenMax(address token) external payable override {
        require(tryApprove(token, 0));
        require(tryApprove(token, type(uint256).max));
}

Overview A function that first sets the token allowance to 0, then approves the maximum quantity.

Parameters

  • token
    • Address of the token to be approved.

approveZeroThenMaxMinusOne

approveZeroThenMaxMinusOne
solidity
function approveZeroThenMaxMinusOne(address token) external payable override {
        require(tryApprove(token, 0));
        require(tryApprove(token, type(uint256).max - 1));
}

Overview A function that first sets the token allowance to 0, then approves the maximum quantity minus one.

Parameters

  • token
    • Address of the token to be approved.

callPositionManager

callPositionManager
solidity
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
        bool success;
        (success, result) = positionManager.call(data);

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

Overview A function that calls a specific function on the PositionManager contract.

Details It calls a specific function on PositionManager and returns the result. If the function call fails, an error message is returned.

Parameters

  • data
    • Encoded data containing the function and arguments to call.

Return value

  • bytes memory
    • Result of the function call.

balanceOf

balanceOf
solidity
function balanceOf(address token) private view returns (uint256) {
        return IERC20(token).balanceOf(address(this));
}

Overview A function that obtains the balance of a specified token.

Parameters

  • token
    • Address of the token whose balance is requested.

Return value

  • uint256
    • Token balance.

mint

mint
solidity
function mint(MintParams calldata params) external payable override returns (bytes memory result) {
        return
            callPositionManager(
                abi.encodeWithSelector(
                    INonfungiblePositionManager.mint.selector,
                    INonfungiblePositionManager.MintParams({
                        token0: params.token0,
                        token1: params.token1,
                        fee: params.fee,
                        tickLower: params.tickLower,
                        tickUpper: params.tickUpper,
                        amount0Desired: balanceOf(params.token0),
                        amount1Desired: balanceOf(params.token1),
                        amount0Min: params.amount0Min,
                        amount1Min: params.amount1Min,
                        recipient: params.recipient,
                        deadline: type(uint256).max // deadline should be checked via multicall
                    })
                )
            );
}

Overview A function that creates a new Uniswap V3 position.

Details This function creates a new Uniswap V3 position based on the specified parameters. The parameters specify information about token 0 and token 1, the fee, the trading pair's price range (tick range), desired quantities of token 0 and token 1, minimum quantities of token 0 and token 1, and the recipient address. Token approval follows the methods described above.

Parameters

  • params
    • Struct containing the parameters of the position to create.

Return value

  • result
    • Data representing the result of creating the position.

increaseLiquidity

increaseLiquidity
solidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        override
        returns (bytes memory result)
    {
        return
            callPositionManager(
                abi.encodeWithSelector(
                    INonfungiblePositionManager.increaseLiquidity.selector,
                    INonfungiblePositionManager.IncreaseLiquidityParams({
                        tokenId: params.tokenId,
                        amount0Desired: balanceOf(params.token0),
                        amount1Desired: balanceOf(params.token1),
                        amount0Min: params.amount0Min,
                        amount1Min: params.amount1Min,
                        deadline: type(uint256).max // deadline should be checked via multicall
                    })
                )
            );
}

Overview A function that adds liquidity to an existing Uniswap V3 position.

Details Adds liquidity to an existing Uniswap V3 position based on the specified parameters. The parameters specify information about the position's token 0 and token 1, the quantities of both tokens to add, and their minimum quantities. Token approval follows the methods described above.

Parameters

  • params
    • Struct containing the parameters of the position to which liquidity will be added.

Return value

  • result
    • Data representing the result of adding liquidity.

MulticallExtended

multicall

multicall
solidity
function multicall(uint256 deadline, bytes[] calldata data)
        external
        payable
        override
        checkDeadline(deadline)
        returns (bytes[] memory)
    {
        return multicall(data);
}

Overview A function that executes multiple calls together.

Details This function executes multiple calls contained in the specified array of data together. It also checks the deadline or previous block hash. The execution result is returned as an array containing the result of each call.

Parameters

  • deadline
    • Execution deadline.
  • data
    • Array of data for the calls to execute.

Return value

  • bytes[] memory
    • Array of data representing the result of each call.

multicall (previousBlockhash version)

multicall
solidity
function multicall(bytes32 previousBlockhash, bytes[] calldata data)
        external
        payable
        override
        checkPreviousBlockhash(previousBlockhash)
        returns (bytes[] memory)
    {
        return multicall(data);
}

Overview A function that executes multiple calls together.

Details This function executes multiple calls contained in the specified array of data together. In this version, the previous block hash is checked. The execution result is returned as an array containing the result of each call.

Parameters

  • previousBlockhash
    • Block hash preceding execution.
  • data
    • Array of data for the calls to execute.

Return value

  • bytes[] memory
    • Array of data representing the result of each call.

Here is an explanation of the difference between the two multicall functions.

multicall

Overview A function that executes multiple calls contained in the specified array of data together.

Applicable condition A deadline is specified.

Details Executes multiple calls contained in the specified array of data together. The deadline is checked to ensure it has not passed. The execution result is returned as an array containing the result of each call.

multicall (previousBlockhash version)

Overview A function that executes multiple calls contained in the specified array of data together.

Applicable condition A previous block hash is specified.

Details Executes multiple calls contained in the specified array of data together. The previous block hash is checked to ensure that the block hash preceding execution matches the specified previous block hash. The execution result is returned as an array containing the result of each call.

The two functions differ in their execution constraints. The first checks the deadline and the second checks the previous block hash to ensure safe execution.

ImmutableState

factoryV2

factoryV2
solidity
address public immutable override factoryV2;

Overview A variable storing the address of the Uniswap V2 factory contract.

Details Stores the address of the Uniswap V2 factory contract in an immutable, publicly accessible variable. The Uniswap V2 factory contract is the underlying contract for managing token trading.


positionManager

positionManager
solidity
address public immutable override positionManager;

Overview A variable storing the address of the position manager contract.

Details This variable stores the position manager contract address in an immutable, publicly accessible form. The position manager contract manages Uniswap V3 positions.


constructor

constructor
solidity
constructor(address _factoryV2, address _positionManager) {
        factoryV2 = _factoryV2;
        positionManager = _positionManager;
}

Overview The contract constructor is executed during initialization and sets the initial variable values.

Details This constructor initializes the factoryV2 and positionManager variables. The addresses provided when deploying the contract are assigned to the corresponding variables.

Parameters:

  • _factoryV2
    • Address of the Uniswap V2 factory contract.
  • _positionManager
    • Address of the position manager contract.

PeripheryPaymentsWithFeeExtended

unwrapWETH9WithFee

unwrapWETH9WithFee
solidity
function unwrapWETH9WithFee(
        uint256 amountMinimum,
        uint256 feeBips,
        address feeRecipient
    ) external payable override {
        unwrapWETH9WithFee(amountMinimum, msg.sender, feeBips, feeRecipient);
}

Overview A function that unwraps WETH9 tokens with a fee.

Details Unwraps at least the specified minimum quantity of WETH9 tokens. After the fee is deducted, the remaining tokens are sent to the specified address.

Parameters:

  • amountMinimum
    • Quantity of WETH9 required as the minimum amount to unwrap.
  • feeBips
    • Fee in basis points.
  • feeRecipient
    • Address receiving the fee.

Return value: None


sweepTokenWithFee

sweepTokenWithFee
solidity
function sweepTokenWithFee(
        address token,
        uint256 amountMinimum,
        uint256 feeBips,
        address feeRecipient
    ) external payable override {
        sweepTokenWithFee(token, amountMinimum, msg.sender, feeBips, feeRecipient);
}

Overview A function that sweeps a specified token with a fee.

Details The specified tokens are unwrapped, a fee is deducted, and the remaining tokens are sent to the specified address.

Parameters:

  • token: Address of the token to sweep.
  • amountMinimum: Minimum quantity of tokens required for the sweep.
  • feeBips: Fee in basis points.
  • feeRecipient: Address receiving the fee.

Return value: None

The PeripheryPaymentsWithFeeExtended contract extends token unwrapping (conversion to ETH) and token sweeping (sending tokens to a specified address) with fee functionality. Consider a concrete example.

Suppose a DeFi platform allows users to unwrap or sweep tokens. The platform may charge a fee when users unwrap tokens into ETH or send a particular token to a specified address.

In this case, the PeripheryPaymentsWithFeeExtended contract could be used. Users can unwrap or sweep tokens through this contract while accounting for fees. The following are examples.

Token unwrapping (Unwrap)

When a user wants to unwrap tokens into ETH on the platform, they can make a call such as the following.

solidity
contractInstance.unwrapWETH9WithFee(amountMinimum, feeBips, feeRecipient);

Here, amountMinimum is the minimum quantity to unwrap, feeBips is the fee rate, and feeRecipient is the address receiving the fee.

Token sweeping (Sweep)

When a user wants to send a particular token to a specified address, they can make a call such as the following.

solidity
contractInstance.sweepTokenWithFee(token, amountMinimum, feeBips, feeRecipient);

Here, token is the address of the token to send, amountMinimum is the minimum quantity to send, feeBips is the fee rate, and feeRecipient is the address receiving the fee.

The PeripheryPaymentsWithFeeExtended contract is used when users want to unwrap or sweep tokens while accounting for fees, making it easier to pay fees and specify the recipient.

PeripheryPaymentsExtended

unwrapWETH9

unwrapWETH9
solidity
function unwrapWETH9(uint256 amountMinimum) external payable override {
        unwrapWETH9(amountMinimum, msg.sender);
}

Overview A function that unwraps WETH (Wrapped Ether) tokens into their underlying ETH.

Details It allows users to unwrap WETH tokens and receive at least the required amount of ETH. The minimum quantity of WETH to unwrap must be specified.

Parameters:

  • amountMinimum
    • Minimum quantity of WETH to unwrap.

wrapETH

wrapETH
solidity
function wrapETH(uint256 value) external payable override {
        IWETH9(WETH9).deposit{value: value}();
}

Overview A function that converts ETH into WETH (Wrapped Ether) tokens.

Parameters:

  • value
    • Amount of ETH to convert.

sweepToken

sweepToken
solidity
function sweepToken(address token, uint256 amountMinimum) external payable override {
        sweepToken(token, amountMinimum, msg.sender);
}

Overview A function that sends a specified token to a specified address.

Details It is used to send a specified token to a specified address. The token address and minimum quantity to send must be specified.

Parameters:

  • token
    • Address of the token to send.
  • amountMinimum
    • Minimum quantity of tokens to send.

pull

pull
solidity
function pull(address token, uint256 value) external payable override {
        TransferHelper.safeTransferFrom(token, msg.sender, address(this), value);
}

Overview A function that receives tokens from another address.

Details It is used to receive tokens from another address. The address and quantity of the token to receive must be specified.

Parameters:

  • token
    • Address of the token to receive.
  • value
    • Quantity of tokens to receive.

OracleSlippage

getBlockStartingAndCurrentTick

getBlockStartingAndCurrentTick
solidity
function getBlockStartingAndCurrentTick(IUniswapV3Pool pool)
        internal
        view
        returns (int24 blockStartingTick, int24 currentTick)
    {
        uint16 observationIndex;
        uint16 observationCardinality;
        (, currentTick, observationIndex, observationCardinality, , , ) = pool.slot0();

        // 2 observations are needed to reliably calculate the block starting tick
        require(observationCardinality > 1, 'NEO');

        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block
        // therefore the tick in `slot0` is the same as at the beginning of the current block.
        // We don't need to check if this observation is initialized - it is guaranteed to be.
        (uint32 observationTimestamp, int56 tickCumulative, , ) = pool.observations(observationIndex);
        if (observationTimestamp != uint32(_blockTimestamp())) {
            blockStartingTick = currentTick;
        } else {
            uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
            (uint32 prevObservationTimestamp, int56 prevTickCumulative, , bool prevInitialized) =
                pool.observations(prevIndex);

            require(prevInitialized, 'ONI');

            uint32 delta = observationTimestamp - prevObservationTimestamp;
            blockStartingTick = int24((tickCumulative - prevTickCumulative) / delta);
        }
}

Overview A function that returns the tick (a measure of price movement) at the beginning of the current block and at the present time.

Details Retrieves the current tick and the tick at the beginning of the block for a specified Uniswap V3 pool. This helps determine price movements within the block and evaluate slippage.

Parameters:

  • pool
    • Address of the Uniswap V3 pool being examined.

Return values:

  • blockStartingTick
    • Tick (measure of price movement) at the beginning of the block.
  • currentTick: Current tick (measure of price movement).

getPoolAddress

getPoolAddress
solidity
function getPoolAddress(
        address tokenA,
        address tokenB,
        uint24 fee
    ) internal view virtual returns (IUniswapV3Pool pool) {
        pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
}

Overview A function that obtains the pool address.

Details Obtains the pool address given token A, token B, and the fee rate.

Parameters:

  • tokenA
    • Address of token A.
  • tokenB
    • Address of token B.
  • fee
    • Pool fee rate.

Return values:

  • pool
    • Interface of the resulting pool.

getSyntheticTicks

getSyntheticTicks
solidity
function getSyntheticTicks(bytes memory path, uint32 secondsAgo)
        internal
        view
        returns (int256 syntheticAverageTick, int256 syntheticCurrentTick)
    {
        bool lowerTicksAreWorse;

        uint256 numPools = path.numPools();
        address previousTokenIn;
        for (uint256 i = 0; i < numPools; i++) {
            // this assumes the path is sorted in swap order
            (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
            IUniswapV3Pool pool = getPoolAddress(tokenIn, tokenOut, fee);

            // get the average and current ticks for the current pool
            int256 averageTick;
            int256 currentTick;
            if (secondsAgo == 0) {
                // we optimize for the secondsAgo == 0 case, i.e. since the beginning of the block
                (averageTick, currentTick) = getBlockStartingAndCurrentTick(pool);
            } else {
                (averageTick, ) = OracleLibrary.consult(address(pool), secondsAgo);
                (, currentTick, , , , , ) = IUniswapV3Pool(pool).slot0();
            }

            if (i == numPools - 1) {
                // if we're here, this is the last pool in the path, meaning tokenOut represents the
                // destination token. so, if tokenIn < tokenOut, then tokenIn is token0 of the last pool,
                // meaning the current running ticks are going to represent tokenOut/tokenIn prices.
                // so, the lower these prices get, the worse of a price the swap will get
                lowerTicksAreWorse = tokenIn < tokenOut;
            } else {
                // if we're here, we need to iterate over the next pool in the path
                path = path.skipToken();
                previousTokenIn = tokenIn;
            }

            // accumulate the ticks derived from the current pool into the running synthetic ticks,
            // ensuring that intermediate tokens "cancel out"
            bool add = (i == 0) || (previousTokenIn < tokenIn ? tokenIn < tokenOut : tokenOut < tokenIn);
            if (add) {
                syntheticAverageTick += averageTick;
                syntheticCurrentTick += currentTick;
            } else {
                syntheticAverageTick -= averageTick;
                syntheticCurrentTick -= currentTick;
            }
        }

        // flip the sign of the ticks if necessary, to ensure that the lower ticks are always worse
        if (!lowerTicksAreWorse) {
            syntheticAverageTick *= -1;
            syntheticCurrentTick *= -1;
        }
}

Overview A function that obtains the synthetic time-weighted average tick for a specified path and time interval.

Details Obtains the synthetic time-weighted average tick over the specified time interval for the given path (route between tokens). It also obtains the current tick. The synthetic tick is used to assess slippage.

Parameters:

  • path
    • Byte string representing the route between tokens.
  • secondsAgo
    • Lookback period in seconds.

Return values:

  • syntheticAverageTick
    • Synthetic time-weighted average tick.
  • syntheticCurrentTick
    • Current tick.

Synthetic time-weighted average tick

Suppose we have the following route (path) between tokens.

text
トークンA → トークンB → トークンC

This path represents a swap from token A to token B, followed by a swap from token B to token C. The synthetic time-weighted average tick can be calculated by obtaining the average tick and current tick for each swap.

For example, suppose the average tick for the Token A → Token B swap is 100 and the current tick is 105, while the average tick for the Token B → Token C swap is 110 and the current tick is 115.

In this case, calculate the synthetic time-weighted average tick taking the weight of each swap into account. If the Token A → Token B swap is more important than the Token B → Token C swap, the synthetic time-weighted average tick is (100 + 110) / 2 = 105. Conversely, if the Token B → Token C swap is more important, the synthetic time-weighted average tick is (105 + 115) / 2 = 110.

In this way, a synthetic time-weighted average tick can be calculated while accounting for the influence of ticks across multiple swap paths. The synthetic time-weighted average tick is used to evaluate price movements across swaps and helps predict slippage and optimize trades.


toInt24

toInt24
solidity
function toInt24(int256 y) private pure returns (int24 z) {
        require((z = int24(y)) == y);
}

Overview A function that casts int256 to int24.

Details Casts int256 to int24. It reverts (raises an error) if overflow or underflow occurs.

Parameters:

  • y
    • The int256 value to cast.

Return values:

  • z
    • The resulting int24 value.

The toInt24 function is used to cast values of type int256 to int24. An int24 represents integers from -2^23 to 2^23-1, whereas int256 represents integers over a much wider range. When casting, verify that the value fits within the range of int24.

The following example illustrates when toInt24 is useful.

Consider the following situation.

solidity
function calculateTotal(uint256[] memory values) external pure returns (int24) {
    int256 total = 0;
    for (uint256 i = 0; i < values.length; i++) {
        total += int256(values[i]);
    }
    return toInt24(total);
}

This function calculates the sum of integer values in the values array and returns the sum as an int24.

For example, if values is [100, 200, -150], the sum is 150. Although the sum fits within int256, casting it to int24 requires it to fall between -2^23 and 2^23-1. Use toInt24 to check the value when casting. If the sum falls outside this range, the function reverts and raises an error.

The toInt24 function thus ensures that an integer value is within the specified range when casting. This prevents out-of-range values from producing incorrect results.


getSyntheticTicks

getSyntheticTicks
solidity
function getSyntheticTicks(
        bytes[] memory paths,
        uint128[] memory amounts,
        uint32 secondsAgo
    ) internal view returns (int256 averageSyntheticAverageTick, int256 averageSyntheticCurrentTick) {
        require(paths.length == amounts.length);

        OracleLibrary.WeightedTickData[] memory weightedSyntheticAverageTicks =
            new OracleLibrary.WeightedTickData[](paths.length);
        OracleLibrary.WeightedTickData[] memory weightedSyntheticCurrentTicks =
            new OracleLibrary.WeightedTickData[](paths.length);

        for (uint256 i = 0; i < paths.length; i++) {
            (int256 syntheticAverageTick, int256 syntheticCurrentTick) = getSyntheticTicks(paths[i], secondsAgo);
            weightedSyntheticAverageTicks[i].tick = toInt24(syntheticAverageTick);
            weightedSyntheticCurrentTicks[i].tick = toInt24(syntheticCurrentTick);
            weightedSyntheticAverageTicks[i].weight = amounts[i];
            weightedSyntheticCurrentTicks[i].weight = amounts[i];
        }

        averageSyntheticAverageTick = OracleLibrary.getWeightedArithmeticMeanTick(weightedSyntheticAverageTicks);
        averageSyntheticCurrentTick = OracleLibrary.getWeightedArithmeticMeanTick(weightedSyntheticCurrentTicks);
}

Overview A function that obtains synthetic time-weighted average ticks across multiple paths and calculates their weighted average.

Details Obtains synthetic time-weighted average ticks across multiple paths over a specified time interval and calculates their weighted average. It is used when assessing slippage across different routes. All paths must begin and end with the same tokens.

Parameters:

  • paths
    • Array of byte strings representing multiple routes between tokens.
  • amounts
    • Input amounts for the respective routes (an array of amounts).
  • secondsAgo
    • Lookback period in seconds.

Return values:

  • averageSyntheticAverageTick
    • Weighted average synthetic time-weighted average tick.
  • averageSyntheticCurrentTick
    • Weighted average current tick.

checkOracleSlippage

checkOracleSlippage
solidity
function checkOracleSlippage(
        bytes memory path,
        uint24 maximumTickDivergence,
        uint32 secondsAgo
    ) external view override {
        (int256 syntheticAverageTick, int256 syntheticCurrentTick) = getSyntheticTicks(path, secondsAgo);
        require(syntheticAverageTick - syntheticCurrentTick < maximumTickDivergence, 'TD');
}

Overview A function that evaluates slippage and checks whether it exceeds the specified maximum tick divergence.

Details Evaluates tick divergence for a specified path and time interval and raises an error if the maximum divergence is exceeded. It is used to control slippage.

Parameters:

  • path
    • Byte string representing the route between tokens.
  • maximumTickDivergence
    • Maximum tick divergence.

Divergence value.

  • secondsAgo
    • Lookback period in seconds.

The checkOracleSlippage function checks whether the oracle tick movement along a specified path is within a specified maximum tick deviation. The following example illustrates how it works.

Suppose we have the following function.

solidity
function tradeWithSlippage(bytes memory path, uint24 maximumTickDivergence, uint32 secondsAgo) external view {
    OracleSlippage oracle = OracleSlippage(addressOfOracle); // 仮のアドレスです

    // オラクルスリッページをチェック
    oracle.checkOracleSlippage(path, maximumTickDivergence, secondsAgo);

    // ここにトレードのロジックを記述する
    // ...
}

This function receives a specified path (token route), maximum tick deviation, and lookback period in seconds. Inside the function, an instance of the OracleSlippage contract is created and its checkOracleSlippage function is called.

The purpose of the function is to ensure that oracle tick movement along the specified path does not exceed the specified maximum tick deviation. This allows users to check whether tick movement is within the acceptable range before executing a trade.

Consider a concrete example. Suppose path is [TokenA, TokenB], maximumTickDivergence is 100, and secondsAgo is 3600 (using data from one hour ago). The function uses data from one hour ago to check tick movement for the specified path and determine whether the maximum tick deviation is at most 100. If tick movement exceeds the specified deviation, the function raises an error and cancels the trade.

The checkOracleSlippage function thus provides an important way to check oracle tick movement before trading. Excessive tick movement may lead to unexpected trading results, so this function can be used to manage that risk.


checkOracleSlippage

checkOracleSlippage
solidity
function checkOracleSlippage(
        bytes[] memory paths,
        uint128[] memory amounts,
        uint24 maximumTickDivergence,
        uint32 secondsAgo
    ) external view override {
        (int256 averageSyntheticAverageTick, int256 averageSyntheticCurrentTick) =
            getSyntheticTicks(paths, amounts, secondsAgo);
        require(averageSyntheticAverageTick - averageSyntheticCurrentTick < maximumTickDivergence, 'TD');
}

Overview A function that evaluates slippage across multiple paths and checks whether it exceeds the specified maximum tick divergence.

Details Evaluates tick divergence across multiple paths over a specified time interval and raises an error if the maximum divergence is exceeded. It is used when assessing slippage across different routes.

Parameters:

  • paths
    • Array of byte strings representing multiple routes between tokens.
  • amounts
    • Input amounts for the respective routes (an array of amounts).
  • maximumTickDivergence
    • Maximum tick divergence value.
  • secondsAgo
    • Lookback period in seconds.

PeripheryValidationExtended

checkPreviousBlockhash

checkPreviousBlockhash
solidity
modifier checkPreviousBlockhash(bytes32 previousBlockhash) {
        require(blockhash(block.number - 1) == previousBlockhash, 'Blockhash');
        _;
}

checkPreviousBlockhash provides a control structure that checks a specific condition before a function executes and proceeds with execution only if that condition is satisfied.

Consider the following example.

solidity
abstract contract PeripheryValidationExtended is PeripheryValidation {
    modifier checkPreviousBlockhash(bytes32 previousBlockhash) {
        require(blockhash(block.number - 1) == previousBlockhash, 'Blockhash');
        _; // チェックを通過したら関数本体を実行
    }
}

The checkPreviousBlockhash modifier checks whether the previous block's hash matches the specified hash before the function is called. If the hashes do not match, the call fails with the error message 'Blockhash', which indicates the reason for failure.

Consider an example.

solidity
contract MyContract is PeripheryValidationExtended {
    bytes32 private previousBlockhash;

    function setPreviousBlockhash(bytes32 _blockhash) external {
        previousBlockhash = _blockhash;
    }

    function performAction() external checkPreviousBlockhash(previousBlockhash) {
        // ブロックハッシュのチェックをパスした場合にのみ実行される
        // ...
    }
}

In the MyContract contract above, performAction uses the checkPreviousBlockhash(previousBlockhash) modifier. This modifier checks whether the specified previousBlockhash matches the previous block's hash and executes the function if they match. If they do not match, the function does not execute and an error occurs.

This allows function execution conditions to be checked when the previous block's hash must match a particular value.

Events

None in particular.

Code

Interfaces

  • SwapRouter02/contracts/interfaces

Base contracts

  • SwapRouter02/contracts/base

Libraries

  • SwapRouter02/contracts/libraries

uniswap core

  • SwapRouter02/@uniswap

openzeppelin contract

  • SwapRouter02/@openzeppelin`

Conclusion

In this article, we examined the SwapRouter02 contract in Uniswap V3 using Bunzz’s DeCipher feature. I hope you found it useful. I plan to continue covering selected NFTs and contracts.

I also publish blockchain and AI articles on my blog and Qiita if you would like to explore them.

https://chaldene.net/