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 examines the UniversalRouter contract used by Uniswap V3 with Bunzz's DeCipher feature.

DeCipher is a service that uses AI to automatically generate contract documentation.

For instructions on using it, see the following article.

This article describes my own experience using DeCipher. There may be inaccuracies; please let me know in the comments if you spot any.

The DeCipher page used in this article is available below.

The corresponding Etherscan page is below.

Overview

UniversalRouter is a central component of the dApp ecosystem. It coordinates the various transactions occurring across the platform. Specifically, it facilitates operations such as swaps, payments, and reward collection across different modules and external protocols.

Objective

The goal is to provide a unified user experience. Users can interact with different protocols and modules and efficiently execute complex operations such as token swaps, payments, and reward collection.

Providing a unified experience means offering consistent interactions when users communicate with different protocols and modules in the Uniswap dApp ecosystem.

Specifically, users can carry out complex operations such as token swaps, payments, and reward collection without having to determine which protocol or module to use. Users do not need to learn separate tools and procedures for each operation. Instead, UniversalRouter directs the operations to their appropriate destinations.

This unified experience enables users to select and efficiently carry out the operations they need within the ecosystem without worrying about technical details, differences, or how each operation is implemented.

Responsibilities

Transaction routing

Efficiently connects different transaction types to their corresponding modules and protocols. Ensures that transactions are executed correctly and safely regardless of the specific module or protocol.

Transaction routing is the process of directing different transaction types to suitable modules or protocols. For example, operations such as token swaps, payments, and reward collection may be handled by different modules or protocols.

The process is not tied to any particular module or protocol and ensures that transactions are handled appropriately. For example, a token swap is routed to a module dedicated to swaps, while a payment is routed to a payment module. Users can therefore carry out an operation without worrying about which module or protocol handles it.

The important point is that these transactions execute correctly and safely. UniversalRouter directs each transaction to the appropriate module or protocol and ensures correct execution. This process lets users expect reliable processing regardless of transaction type.

Interoperability

Promotes interoperability between different modules and protocols, enabling users to interact with different components of the dApp ecosystem without understanding their technical details.

Interoperability is the ability of different modules and protocols to work together seamlessly. It allows users to communicate with different components of the dApp ecosystem without understanding the technical details.

Specifically, because different protocols and modules work together, users do not need in-depth knowledge of how each operates. UniversalRouter integrates these components so users can perform complex operations through a single interface.

Consider a token swap, for example. This operation may involve several steps and protocols, but users do not need to understand their details. UniversalRouter coordinates the protocols, selecting and executing the appropriate protocol when users simply specify the tokens they wish to swap.

Interoperability enables users to operate freely within the ecosystem without understanding the technical aspects underlying complex protocols. This consistency and simplicity improves the user experience and allows interaction with different components without technical barriers.

Transaction validation

Checks whether transactions meet the required conditions, including token balances, sufficient funds, and user permissions. This prevents invalid transactions from being executed.

Event logging

Records important events and transaction details to ensure transparency and auditability. Users and developers can monitor transaction execution and use this information to maintain the reliability of the ecosystem.

Error handling

Handles errors appropriately when problems arise during transaction execution and provides suitable feedback to users. This minimizes disruptions to the user experience and loss of funds.

Error handling is the process of dealing with problems or errors during transaction execution and providing users with suitable information and feedback.

Errors can arise for various reasons during transaction execution. For instance, a transaction may contain incorrect information or fail to satisfy a required condition. Error handling provides a mechanism for dealing with these situations.

Its purpose is to give users appropriate feedback when an error occurs. This allows users to understand the problem and take suitable action. For example, if a token swap fails, an error message or specific instructions can tell the user what needs to be corrected.

Error handling is also important for minimizing interruptions and loss of funds. Improper error handling can cause transactions to fail or funds to be processed incorrectly, undermining user trust and the reliability of the ecosystem as a whole. Error handling reduces these risks and helps maintain a satisfactory experience for users and the ecosystem.

UniversalRouter is an important component for executing transactions smoothly and safely in the dApp ecosystem. Users can interact with different modules and protocols while maintaining efficiency, interoperability, and security.

Usage

UniversalRouter is a smart contract that acts as a universal router for executing various transaction types across different protocols. It provides a single interface for interacting with different protocols and routes transactions based on the specified protocol.

Contract objective

UniversalRouter aims to provide a unified interface for executing transactions across different protocols. Developers can interact with multiple protocols through one contract, reducing the complexity of individual integrations and simplifying the integration process.

How to use it

Follow these steps to use the contract as intended.

  1. Deploy the UniversalRouter contract.
  2. Initialize the contract with the required parameters.
  3. Call the routing function to execute transactions on different protocols.

Deploying UniversalRouter

Follow these steps to deploy UniversalRouter.

  1. Compile the UniversalRouter.sol contract.
  2. Deploy the compiled contract to the desired blockchain network.

Initializing the contract

UniversalRouter can be initialized with the following parameters.

  • dispatcher
    • Address of the Dispatcher contract.
  • rewardsCollector
    • Address of the RewardsCollector contract.
  • routerImmutables
    • Address of the RouterImmutables contract.

Executing transactions

Call the route function to execute transactions on different protocols. The route function takes the following parameters.

  • command
    • Command to execute on the specified protocol.
  • data
    • Data required to execute the command.
  • path
    • Path to the protocol used to execute the command.

The route function performs the following steps.

  1. Validate the command and data.
  2. Retrieve the protocol implementation address based on the specified path.
  3. Call the protocol implementation contract's execute function with the command and data.

Functions

UniversalRouter provides the following functions.

  • constructor
    • Initializes the contract with the specified parameters.
  • route
    • Executes transactions on different protocols based on the specified command, data, and path.

Events

UniversalRouter emits the following events.

  • RouteExecuted
    • Emitted when a transaction is successfully executed on a protocol.
    • Contains the following information.
      • protocol
        • Protocol on which the transaction was executed.
      • command
        • Command executed.
      • data
        • Data used for execution.
  • ERC721
  • ERC1155
  • ERC20
  • IERC721Receiver
  • IERC1155Receiver
  • IERC20
  • IUniswapV2Pair
  • IUniswapV3Pool
  • IUniswapV3SwapCallback
  • IERC165
  • IAllowanceTransfer
  • ICryptoPunksMarket
  • IWETH9

References

  • UniversalRouter.sol
  • Dispatcher.sol
  • RewardsCollector.sol
  • RouterImmutables.sol
  • Commands.sol
  • IUniversalRouter.sol
  • V2SwapRouter.sol
  • V3SwapRouter.sol
  • BytesLib.sol
  • Payments.sol
  • Callbacks.sol
  • LockAndMsgSender.sol
  • ERC721.sol
  • ERC1155.sol
  • ERC20.sol
  • IAllowanceTransfer.sol
  • ICryptoPunksMarket.sol
  • SafeTransferLib.sol
  • IRewardsCollector.sol
  • IWETH9.sol
  • IERC721Receiver.sol
  • IERC1155Receiver.sol
  • IUniswapV2Pair.sol
  • UniswapV2Library.sol
  • Permit2Payments.sol
  • Constants.sol
  • V3Path.sol
  • SafeCast.sol
  • IUniswapV3Pool.sol
  • IUniswapV3SwapCallback.sol
  • IERC165.sol
  • IERC20.sol
  • SafeCast160.sol
  • IUniswapV3PoolImmutables.sol
  • IUniswapV3PoolState.sol
  • IUniswapV3PoolDerivedState.sol
  • IUniswapV3PoolActions.sol
  • IUniswapV3PoolOwnerActions.sol
  • IUniswapV3PoolEvents.sol

Parameters

Each item below is presented as a level-three heading rather than a list.

permit2

Address of the permit2 contract.

weth9

Address of the weth9 contract.

seaportV1_5

Address of the seaportV1_5 contract.

seaportV1_4

Address of the seaportV1_4 contract.

openseaConduit

Address of the openseaConduit contract.

nftxZap

Address of the nftxZap contract.

x2y2

Address of the x2y2 contract.

foundation

Address of the foundation contract.

sudoswap

Address of the sudoswap contract.

elementMarket

Address of the elementMarket contract.

nft20Zap

Address of the nft20Zap contract.

cryptopunks

Address of the cryptopunks contract.

looksRareV2

Address of the looksRareV2 contract.

routerRewardsDistributor

Address of the routerRewardsDistributor contract.

looksRareRewardsDistributor

Address of the looksRareRewardsDistributor contract.

looksRareToken

Address of the looksRareToken contract.

v2Factory

Address of the v2Factory contract.

v3Factory

Address of the v3Factory contract.

pairInitCodeHash

Hash of the pair initialization code.

poolInitCodeHash

Hash of the pool initialization code.

Contracts

UniversalRouter

RouterImmutables

Overview RouterImmutables is a contract that holds contract initialization parameters.

Details RouterImmutables is used when UniversalRouter is initialized. It sets contract parameters and makes them available for subsequent transaction execution.

Arguments

  • params
    • Initialization parameters of the RouterParameters struct type.
    • These configure the contract.

execute

execute
solidity
function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline)
        external
        payable
        checkDeadline(deadline)
    {
        execute(commands, inputs);
}

Overview A function that executes transactions. Executes transactions according to the specified commands and inputs.

Details Implements the IUniversalRouter interface and executes transactions using the specified commands and inputs. An error occurs if execution is attempted after the specified deadline.

Arguments

  • commands
    • Byte array containing the commands to execute.
  • inputs
    • Array of input byte sequences for each command.
  • deadline
    • Timestamp representing the transaction deadline.

Return value None


execute (override)

execute
solidity
function execute(bytes calldata commands, bytes[] calldata inputs) public payable override isNotLocked {
        bool success;
        bytes memory output;
        uint256 numCommands = commands.length;
        if (inputs.length != numCommands) revert LengthMismatch();

        // loop through all given commands, execute them and pass along outputs as defined
        for (uint256 commandIndex = 0; commandIndex < numCommands;) {
            bytes1 command = commands[commandIndex];

            bytes calldata input = inputs[commandIndex];

            (success, output) = dispatch(command, input);

            if (!success && successRequired(command)) {
                revert ExecutionFailed({commandIndex: commandIndex, message: output});
            }

            unchecked {
                commandIndex++;
            }
        }
}

Overview An overload of execute that does not check a deadline.

Details This overload of execute omits the deadline check. It internally calls the execute function of the same name to execute the transaction.

Arguments

  • commands
    • Byte array containing the commands to execute.
  • inputs
    • Array of input byte sequences for each command.

Return value None


successRequired

successRequired
solidity
function successRequired(bytes1 command) internal pure returns (bool) {
        return command & Commands.FLAG_ALLOW_REVERT == 0;
}

Overview A function that determines whether a particular command must execute successfully.

Details A command must succeed if it does not contain FLAG_ALLOW_REVERT.

Arguments

  • command
    • Command byte to check.

Return value

  • bool
    • Boolean indicating whether success is required.

successRequired determines whether the result of executing a particular command must be successful.

If the command does not contain the FLAG_ALLOW_REVERT flag, meaning that failure is not permitted to revert independently, the function returns true, indicating that success is required. This determines how successful and failed results are handled during transaction execution.

For example, consider a transaction containing a command to transfer tokens. If the operation succeeds, the tokens are transferred; if it fails, they are not. successRequired determines whether this command must succeed.

If the command includes FLAG_ALLOW_REVERT, meaning the token transfer may fail and revert, successRequired determines that success is not required. This is because the failed transfer can be reverted to its previous state.

Conversely, if the command does not contain FLAG_ALLOW_REVERT, meaning that failure of the transfer is not permitted, successRequired determines that success is required. This is because the operation must succeed rather than allowing a failed transfer to leave execution proceeding.

Thus, successRequired determines whether execution must succeed based on the command's flags and controls how the transaction is handled.


receive

receive
solidity
receive() external payable {}

Overview A function for receiving ETH from WETH and NFT protocols.

Details Called when receiving ETH from an external source. Used to receive ETH from WETH and NFT protocols.

Dispatcher

A contract for executing different commands and handling their results. Calls the relevant function based on the command type and processes the required arguments and data. Acts as an intermediary for interacting with different smart contracts. Decodes commands and calls functions corresponding to their types to perform different operations.

Parameters

  • commands
    • Byte sequence of commands to execute.
    • Each command is represented by one byte.
  • inputs
    • Array of input byte sequences for each command.

Return value None


dispatch

dispatch
solidity
function dispatch(bytes1 commandType, bytes calldata inputs) internal returns (bool success, bytes memory output) {
        uint256 command = uint8(commandType & Commands.COMMAND_TYPE_MASK);

        success = true;

        if (command < Commands.FOURTH_IF_BOUNDARY) {
            if (command < Commands.SECOND_IF_BOUNDARY) {
                // 0x00 <= command < 0x08
                if (command < Commands.FIRST_IF_BOUNDARY) {
                    if (command == Commands.V3_SWAP_EXACT_IN) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountIn;
                        uint256 amountOutMin;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountIn := calldataload(add(inputs.offset, 0x20))
                            amountOutMin := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        bytes calldata path = inputs.toBytes(3);
                        address payer = payerIsUser ? lockedBy : address(this);
                        v3SwapExactInput(map(recipient), amountIn, amountOutMin, path, payer);
                    } else if (command == Commands.V3_SWAP_EXACT_OUT) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountOut;
                        uint256 amountInMax;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountOut := calldataload(add(inputs.offset, 0x20))
                            amountInMax := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        bytes calldata path = inputs.toBytes(3);
                        address payer = payerIsUser ? lockedBy : address(this);
                        v3SwapExactOutput(map(recipient), amountOut, amountInMax, path, payer);
                    } else if (command == Commands.PERMIT2_TRANSFER_FROM) {
                        // equivalent: abi.decode(inputs, (address, address, uint160))
                        address token;
                        address recipient;
                        uint160 amount;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            amount := calldataload(add(inputs.offset, 0x40))
                        }
                        permit2TransferFrom(token, lockedBy, map(recipient), amount);
                    } else if (command == Commands.PERMIT2_PERMIT_BATCH) {
                        (IAllowanceTransfer.PermitBatch memory permitBatch,) =
                            abi.decode(inputs, (IAllowanceTransfer.PermitBatch, bytes));
                        bytes calldata data = inputs.toBytes(1);
                        PERMIT2.permit(lockedBy, permitBatch, data);
                    } else if (command == Commands.SWEEP) {
                        // equivalent:  abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint160 amountMin;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            amountMin := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.sweep(token, map(recipient), amountMin);
                    } else if (command == Commands.TRANSFER) {
                        // equivalent:  abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint256 value;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            value := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.pay(token, map(recipient), value);
                    } else if (command == Commands.PAY_PORTION) {
                        // equivalent:  abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint256 bips;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            bips := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.payPortion(token, map(recipient), bips);
                    } else {
                        // placeholder area for command 0x07
                        revert InvalidCommandType(command);
                    }
                    // 0x08 <= command < 0x10
                } else {
                    if (command == Commands.V2_SWAP_EXACT_IN) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountIn;
                        uint256 amountOutMin;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountIn := calldataload(add(inputs.offset, 0x20))
                            amountOutMin := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        address[] calldata path = inputs.toAddressArray(3);
                        address payer = payerIsUser ? lockedBy : address(this);
                        v2SwapExactInput(map(recipient), amountIn, amountOutMin, path, payer);
                    } else if (command == Commands.V2_SWAP_EXACT_OUT) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountOut;
                        uint256 amountInMax;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountOut := calldataload(add(inputs.offset, 0x20))
                            amountInMax := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        address[] calldata path = inputs.toAddressArray(3);
                        address payer = payerIsUser ? lockedBy : address(this);
                        v2SwapExactOutput(map(recipient), amountOut, amountInMax, path, payer);
                    } else if (command == Commands.PERMIT2_PERMIT) {
                        // equivalent: abi.decode(inputs, (IAllowanceTransfer.PermitSingle, bytes))
                        IAllowanceTransfer.PermitSingle calldata permitSingle;
                        assembly {
                            permitSingle := inputs.offset
                        }
                        bytes calldata data = inputs.toBytes(6); // PermitSingle takes first 6 slots (0..5)
                        PERMIT2.permit(lockedBy, permitSingle, data);
                    } else if (command == Commands.WRAP_ETH) {
                        // equivalent: abi.decode(inputs, (address, uint256))
                        address recipient;
                        uint256 amountMin;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountMin := calldataload(add(inputs.offset, 0x20))
                        }
                        Payments.wrapETH(map(recipient), amountMin);
                    } else if (command == Commands.UNWRAP_WETH) {
                        // equivalent: abi.decode(inputs, (address, uint256))
                        address recipient;
                        uint256 amountMin;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountMin := calldataload(add(inputs.offset, 0x20))
                        }
                        Payments.unwrapWETH9(map(recipient), amountMin);
                    } else if (command == Commands.PERMIT2_TRANSFER_FROM_BATCH) {
                        (IAllowanceTransfer.AllowanceTransferDetails[] memory batchDetails) =
                            abi.decode(inputs, (IAllowanceTransfer.AllowanceTransferDetails[]));
                        permit2TransferFrom(batchDetails, lockedBy);
                    } else if (command == Commands.BALANCE_CHECK_ERC20) {
                        // equivalent: abi.decode(inputs, (address, address, uint256))
                        address owner;
                        address token;
                        uint256 minBalance;
                        assembly {
                            owner := calldataload(inputs.offset)
                            token := calldataload(add(inputs.offset, 0x20))
                            minBalance := calldataload(add(inputs.offset, 0x40))
                        }
                        success = (ERC20(token).balanceOf(owner) >= minBalance);
                        if (!success) output = abi.encodePacked(BalanceTooLow.selector);
                    } else {
                        // placeholder area for command 0x0f
                        revert InvalidCommandType(command);
                    }
                }
                // 0x10 <= command
            } else {
                // 0x10 <= command < 0x18
                if (command < Commands.THIRD_IF_BOUNDARY) {
                    if (command == Commands.SEAPORT_V1_5) {
                        /// @dev Seaport 1.4 and 1.5 allow for orders to be created by contracts.
                        ///     These orders pass control to the contract offerers during fufillment,
                        ///         allowing them to perform any number of destructive actions as a holder of the NFT.
                        ///     Integrators should be aware that in some scenarios: e.g. purchasing an NFT that allows the holder
                        ///         to claim another NFT, the contract offerer can "steal" the claim during order fufillment.
                        ///     For some such purchases, an OWNER_CHECK command can be prepended to ensure that all tokens have the desired owner at the end of the transaction.
                        ///     This is also outlined in the Seaport documentation: https://github.com/ProjectOpenSea/seaport/blob/main/docs/SeaportDocumentation.md
                        (uint256 value, bytes calldata data) = getValueAndData(inputs);
                        (success, output) = SEAPORT_V1_5.call{value: value}(data);
                    } else if (command == Commands.LOOKS_RARE_V2) {
                        // equivalent: abi.decode(inputs, (uint256, bytes))
                        uint256 value;
                        assembly {
                            value := calldataload(inputs.offset)
                        }
                        bytes calldata data = inputs.toBytes(1);
                        (success, output) = LOOKS_RARE_V2.call{value: value}(data);
                    } else if (command == Commands.NFTX) {
                        // equivalent: abi.decode(inputs, (uint256, bytes))
                        (uint256 value, bytes calldata data) = getValueAndData(inputs);
                        (success, output) = NFTX_ZAP.call{value: value}(data);
                    } else if (command == Commands.CRYPTOPUNKS) {
                        // equivalent: abi.decode(inputs, (uint256, address, uint256))
                        uint256 punkId;
                        address recipient;
                        uint256 value;
                        assembly {
                            punkId := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            value := calldataload(add(inputs.offset, 0x40))
                        }
                        (success, output) = CRYPTOPUNKS.call{value: value}(
                            abi.encodeWithSelector(ICryptoPunksMarket.buyPunk.selector, punkId)
                        );
                        if (success) ICryptoPunksMarket(CRYPTOPUNKS).transferPunk(map(recipient), punkId);
                        else output = abi.encodePacked(BuyPunkFailed.selector);
                    } else if (command == Commands.OWNER_CHECK_721) {
                        // equivalent: abi.decode(inputs, (address, address, uint256))
                        address owner;
                        address token;
                        uint256 id;
                        assembly {
                            owner := calldataload(inputs.offset)
                            token := calldataload(add(inputs.offset, 0x20))
                            id := calldataload(add(inputs.offset, 0x40))
                        }
                        success = (ERC721(token).ownerOf(id) == owner);
                        if (!success) output = abi.encodePacked(InvalidOwnerERC721.selector);
                    } else if (command == Commands.OWNER_CHECK_1155) {
                        // equivalent: abi.decode(inputs, (address, address, uint256, uint256))
                        address owner;
                        address token;
                        uint256 id;
                        uint256 minBalance;
                        assembly {
                            owner := calldataload(inputs.offset)
                            token := calldataload(add(inputs.offset, 0x20))
                            id := calldataload(add(inputs.offset, 0x40))
                            minBalance := calldataload(add(inputs.offset, 0x60))
                        }
                        success = (ERC1155(token).balanceOf(owner, id) >= minBalance);
                        if (!success) output = abi.encodePacked(InvalidOwnerERC1155.selector);
                    } else if (command == Commands.SWEEP_ERC721) {
                        // equivalent: abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint256 id;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            id := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.sweepERC721(token, map(recipient), id);
                    }
                    // 0x18 <= command < 0x1f
                } else {
                    if (command == Commands.X2Y2_721) {
                        (success, output) = callAndTransfer721(inputs, X2Y2);
                    } else if (command == Commands.SUDOSWAP) {
                        // equivalent: abi.decode(inputs, (uint256, bytes))
                        (uint256 value, bytes calldata data) = getValueAndData(inputs);
                        (success, output) = SUDOSWAP.call{value: value}(data);
                    } else if (command == Commands.NFT20) {
                        // equivalent: abi.decode(inputs, (uint256, bytes))
                        (uint256 value, bytes calldata data) = getValueAndData(inputs);
                        (success, output) = NFT20_ZAP.call{value: value}(data);
                    } else if (command == Commands.X2Y2_1155) {
                        (success, output) = callAndTransfer1155(inputs, X2Y2);
                    } else if (command == Commands.FOUNDATION) {
                        (success, output) = callAndTransfer721(inputs, FOUNDATION);
                    } else if (command == Commands.SWEEP_ERC1155) {
                        // equivalent: abi.decode(inputs, (address, address, uint256, uint256))
                        address token;
                        address recipient;
                        uint256 id;
                        uint256 amount;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            id := calldataload(add(inputs.offset, 0x40))
                            amount := calldataload(add(inputs.offset, 0x60))
                        }
                        Payments.sweepERC1155(token, map(recipient), id, amount);
                    } else if (command == Commands.ELEMENT_MARKET) {
                        // equivalent: abi.decode(inputs, (uint256, bytes))
                        (uint256 value, bytes calldata data) = getValueAndData(inputs);
                        (success, output) = ELEMENT_MARKET.call{value: value}(data);
                    } else {
                        // placeholder for command 0x1f
                        revert InvalidCommandType(command);
                    }
                }
            }
            // 0x20 <= command
        } else {
            if (command == Commands.SEAPORT_V1_4) {
                /// @dev Seaport 1.4 and 1.5 allow for orders to be created by contracts.
                ///     These orders pass control to the contract offerers during fufillment,
                ///         allowing them to perform any number of destructive actions as a holder of the NFT.
                ///     Integrators should be aware that in some scenarios: e.g. purchasing an NFT that allows the holder
                ///         to claim another NFT, the contract offerer can "steal" the claim during order fufillment.
                ///     For some such purchases, an OWNER_CHECK command can be prepended to ensure that all tokens have the desired owner at the end of the transaction.
                ///     This is also outlined in the Seaport documentation: https://github.com/ProjectOpenSea/seaport/blob/main/docs/SeaportDocumentation.md
                (uint256 value, bytes calldata data) = getValueAndData(inputs);
                (success, output) = SEAPORT_V1_4.call{value: value}(data);
            } else if (command == Commands.EXECUTE_SUB_PLAN) {
                bytes calldata _commands = inputs.toBytes(0);
                bytes[] calldata _inputs = inputs.toBytesArray(1);
                (success, output) =
                    (address(this)).call(abi.encodeWithSelector(Dispatcher.execute.selector, _commands, _inputs));
            } else if (command == Commands.APPROVE_ERC20) {
                ERC20 token;
                RouterImmutables.Spenders spender;
                assembly {
                    token := calldataload(inputs.offset)
                    spender := calldataload(add(inputs.offset, 0x20))
                }
                Payments.approveERC20(token, spender);
            } else {
                // placeholder area for commands 0x22-0x3f
                revert InvalidCommandType(command);
            }
        }
}

Overview A function that performs the operation corresponding to the specified command type. Performs different operations according to the decoded command type.

Details Selects and executes the operation corresponding to the given command type. Decodes different arguments according to the command type and passes them to the function.

Arguments or parameters

  • commandType
    • One-byte value identifying the command type to execute.
  • inputs
    • Bytes containing the arguments and data required to execute the command.

Return value

  • success
    • Returns true when command execution succeeds and false when it fails.
  • output
    • Returns bytes containing the execution result or an error message.

execute

execute
solidity
function execute(bytes calldata commands, bytes[] calldata inputs) external payable virtual;

Overview A function that executes encoded commands and their corresponding input data. Receives multiple commands and associated inputs and executes each command in order.

Details Receives encoded commands and corresponding input data, then executes the commands sequentially. Execution results and error messages are provided as return values for individual commands.

Arguments

  • commands
    • Concatenated command bytes.
    • Each command is one byte long.
  • inputs
    • Array of ABI-encoded input bytes for each command.

Return value None


callAndTransfer721

callAndTransfer721
solidity
function callAndTransfer721(bytes calldata inputs, address protocol)
        internal
        returns (bool success, bytes memory output)
    {
        // equivalent: abi.decode(inputs, (uint256, bytes, address, address, uint256))
        (uint256 value, bytes calldata data) = getValueAndData(inputs);
        address recipient;
        address token;
        uint256 id;
        assembly {
            // 0x00 and 0x20 offsets are value and data, above
            recipient := calldataload(add(inputs.offset, 0x40))
            token := calldataload(add(inputs.offset, 0x60))
            id := calldataload(add(inputs.offset, 0x80))
        }
        (success, output) = protocol.call{value: value}(data);
        if (success) ERC721(token).safeTransferFrom(address(this), map(recipient), id);
}

Overview Calls the specified protocol and transfers the purchased ERC721 token to the specified recipient address.

Details Calls the specified protocol to make a purchase and then transfers the purchased ERC721 token to the specified recipient address. The function decodes information including the recipient address, token address, and token ID before executing the transaction.

Arguments

  • inputs
    • Encoded input bytes relating to the protocol call and ERC721 token transfer.
  • protocol
    • Address of the protocol to receive the calldata.

Return value

  • success
    • Returns true when command execution succeeds and false when it fails.
  • output
    • Returns bytes containing the execution result or an error message.

callAndTransfer721 purchases an ERC721 token, executes the trade, and then transfers the token to the specified recipient.

For example, suppose the following command is provided:

solidity
callAndTransfer721(
    inputs,
    protocolAddress
);

Here, inputs is ABI-encoded bytes containing purchase information. protocolAddress specifies the protocol used for the trade.

callAndTransfer721 proceeds as follows.

  1. Decode inputs Decode the necessary information from inputs. This information includes the recipient address, token address, and token ID.

  2. Execute the trade Call protocolAddress to execute the trade. The required amount is sent at the same time.

  3. Check trade success Check the execution result to determine whether the trade succeeded.

  4. Transfer the token If the trade succeeds, transfer the purchased ERC721 token from the current contract to the specified recipient.

This function combines the purchase and token transfer into a sequence of steps. The trade details and token type depend on the specific code and ABI-encoded contents, but the basic process follows the sequence above.


callAndTransfer1155

callAndTransfer1155
solidity
function callAndTransfer1155(bytes calldata inputs, address protocol)
        internal
        returns (bool success, bytes memory output)
    {
        // equivalent: abi.decode(inputs, (uint256, bytes, address, address, uint256, uint256))
        (uint256 value, bytes calldata data) = getValueAndData(inputs);
        address recipient;
        address token;
        uint256 id;
        uint256 amount;
        assembly {
            // 0x00 and 0x20 offsets are value and data, above
            recipient := calldataload(add(inputs.offset, 0x40))
            token := calldataload(add(inputs.offset, 0x60))
            id := calldataload(add(inputs.offset, 0x80))
            amount := calldataload(add(inputs.offset, 0xa0))
        }
        (success, output) = protocol.call{value: value}(data);
        if (success) ERC1155(token).safeTransferFrom(address(this), map(recipient), id, amount, new bytes(0));
}

Overview Calls the specified protocol and transfers the purchased ERC1155 tokens to the specified recipient address.

Details Calls the specified protocol to make a purchase and then transfers the purchased ERC1155 tokens to the specified recipient. The function decodes information including the recipient address, token address, token ID, and amount before executing the transaction.

Arguments

  • inputs
    • Encoded input bytes relating to the protocol call and ERC1155 token transfer.
  • protocol
    • Address of the protocol to receive the calldata.

Return value

  • success
    • Returns true when command execution succeeds and false when it fails.
  • output
    • Returns bytes containing the execution result or an error message.

getValueAndData

getValueAndData
solidity
function getValueAndData(bytes calldata inputs) internal pure returns (uint256 value, bytes calldata data) {
        assembly {
            value := calldataload(inputs.offset)
        }
        data = inputs.toBytes(1);
}

Overview A helper function for extracting the value and data parameters from the input.

Details Extracts two parameters, value and data, from the input. value is expected to be the first parameter and data the second.

Arguments or parameters

  • inputs
    • Bytes containing the value and data parameters.

Return value

  • value
    • A 256-bit integer.
  • data
    • Data bytes.

getValueAndData extracts a value and data from the given bytes.

For example, suppose the following code is provided:

solidity
(uint256 value, bytes memory data) = getValueAndData(inputs);

Here, inputs is ABI-encoded bytes.

getValueAndData proceeds as follows.

  1. Decode the bytes Decode the value and data information from inputs. This retrieves the value and data encoded at the beginning of the byte sequence.

  2. Retrieve the value Extract value from the decoded information. This is typically numeric data such as the amount used in a trade.

  3. Retrieve the data Extract data from the decoded information. This is typically calldata required to invoke the trade. It is represented as bytes and used in the transaction call.

  4. Return the value and data Store the extracted value and data in the variables value and data and return them.

This function allows the value and data to be extracted correctly from the supplied bytes. The extracted contents depend on the specific code and ABI encoding, but the basic process follows the sequence above.

RewardsCollector

collectRewards

collectRewards
solidity
function collectRewards(bytes calldata looksRareClaim) external {
        (bool success,) = LOOKS_RARE_REWARDS_DISTRIBUTOR.call(looksRareClaim);
        if (!success) revert UnableToClaim();

        uint256 balance = LOOKS_RARE_TOKEN.balanceOf(address(this));
        LOOKS_RARE_TOKEN.transfer(ROUTER_REWARDS_DISTRIBUTOR, balance);
        emit RewardsSent(balance);
}

Overview A function that claims and transfers rewards. Calls LOOKS_RARE_REWARDS_DISTRIBUTOR to claim rewards, retrieves the LOOKS_RARE_TOKEN balance, and transfers it to ROUTER_REWARDS_DISTRIBUTOR. Emits events according to the outcome of the operation.

Details First, use the call function of LOOKS_RARE_REWARDS_DISTRIBUTOR to execute looksRareClaim and claim the rewards. Then retrieve the LOOKS_RARE_TOKEN balance and transfer it to ROUTER_REWARDS_DISTRIBUTOR. Finally, record the amount of rewards transferred in the RewardsSent event.

Arguments

  • looksRareClaim
    • Data for claiming rewards.

Note If success is false, revert UnableToClaim(); aborts execution with an error indicating that the reward claim failed.

Callbacks

onERC721Received

onERC721Received
solidity
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC721Received.selector;
}

Overview A function called when an ERC721 token is transferred. Implemented by contracts that receive ERC721 tokens.

Details Automatically invoked when an ERC721 token is sent to this contract. It typically performs token acceptance processing or emits events.

Arguments

  • operator
    • Address of the operator that transferred the token.
  • from
    • Address that sent the token.
  • tokenId
    • ID of the transferred token.
  • data
    • Arbitrary data.

Return value

  • bytes4
    • Function signature indicating that this function is implemented.

onERC1155Received

onERC1155Received
solidity
function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC1155Received.selector;
}

Overview A function called when an ERC1155 token is transferred. Implemented by contracts that receive ERC1155 tokens.

Details Invoked when an ERC1155 token is sent to this contract. ERC1155 tokens may involve multiple token IDs and amounts.

Arguments

  • operator
    • Address of the operator that transferred the token.
  • from
    • Address that sent the token.
  • id
    • ID of the transferred token.
  • value
    • Amount of tokens transferred.
  • data
    • Arbitrary data.

Return value

  • bytes4
    • Function signature indicating that this function is implemented.

onERC1155BatchReceived

onERC1155BatchReceived
solidity

Overview A function called when multiple ERC1155 tokens are transferred together.

Details Invoked when multiple ERC1155 tokens are sent to this contract in a batch. Each token may have a different token ID and amount.

Arguments

  • operator
    • Address of the operator that transferred the tokens.
  • from
    • Address that sent the tokens.
  • ids
    • Array of transferred token IDs.
  • values
    • Array of amounts transferred.
  • data
    • Arbitrary data.

Return value

  • bytes4
    • Function signature indicating that this function is implemented.

supportsInterface

Overview Checks whether a specified interface is supported. An ERC165 interface ID can be supplied to determine whether the interface is supported.

Details Checks whether the specified interface ID matches an ERC165 interface ID supported by this contract.

Arguments

  • interfaceId
    • ID of the interface to check.

Return value

  • bool
    • Returns true if the specified interface is supported, and false otherwise.

LockAndMsgSender

A contract providing a locking mechanism and message-sender functionality. Restricts external access and prevents command execution while the contract is locked. It also manages message-sender information for use by particular commands.


ContractLocked

ContractLocked
solidity
error ContractLocked();

Overview An error raised when a function is called on a locked contract. Used to prevent operations while the contract is locked.

Details The isNotLocked modifier checks the lock state and raises this error if the contract is locked. This prevents functions from being invoked while the contract is locked.


NOT_LOCKED_FLAG

NOT_LOCKED_FLAG
solidity
address internal constant NOT_LOCKED_FLAG = address(1);

Overview An address used as a flag indicating the lock state.

Details This address represents the unlocked state of the contract. If lockedBy differs from this address, the contract is considered locked.


lockedBy

lockedBy
solidity
address internal lockedBy = NOT_LOCKED_FLAG;

Overview An address variable that tracks the contract's lock state. While the contract is locked, this variable holds the address that acquired the lock.

Details This variable can only be changed within the isNotLocked modifier. While locked, it holds the address that acquired the lock; when unlocked, it returns to NOT_LOCKED_FLAG.


isNotLocked

isNotLocked
solidity
modifier isNotLocked() {
        if (msg.sender != address(this)) {
            if (lockedBy != NOT_LOCKED_FLAG) revert ContractLocked();
            lockedBy = msg.sender;
            _;
            lockedBy = NOT_LOCKED_FLAG;
        } else {
            _;
        }
}

Overview A modifier that checks whether the contract is unlocked. Applied before function execution to prevent execution while the contract is locked.

Details The modifier checks the lock state before executing the function and raises an error if it is locked. If the contract is unlocked, it permits the function to execute.


map

map
solidity
function map(address recipient) internal view returns (address) {
        if (recipient == Constants.MSG_SENDER) {
            return lockedBy;
        } else if (recipient == Constants.ADDRESS_THIS) {
            return address(this);
        } else {
            return recipient;
        }
}

Overview Computes the destination address for a command. Returns the destination address based on a specified flag or address.

Details This function computes the destination address from the recipient parameter. For Constants.MSG_SENDER and Constants.ADDRESS_THIS, it returns the address that acquired the lock and the contract's own address, respectively.

Arguments

  • recipient
    • Destination address or flag for the command.

Return value

  • address
    • Computed destination address for the command.

The map function Consider a smart contract that handles cryptocurrency transactions. This contract has a transfer command, whose destination address is specified as follows.

  • If recipient is Constants.MSG_SENDER
    • Funds are sent to the address that acquired the lock.
  • If recipient is Constants.ADDRESS_THIS
    • Funds are sent to this contract's address.
  • Otherwise
    • Funds are sent to the specified address.

Consider the following examples.

  1. If recipient is Constants.MSG_SENDER
text
address recipient = Constants.MSG_SENDER;
address result = map(recipient);  // result is the lockedBy address in this case
  1. If recipient is Constants.ADDRESS_THIS
text
address recipient = Constants.ADDRESS_THIS;
address result = map(recipient);  // result is this contract's address in this case
  1. If recipient is a specific address
text
address recipient = 0x1234567890abcdef1234567890abcdef12345678;  // Example address
address result = map(recipient);  // result is the specified address in this case

Thus, map computes and returns the destination address based on a particular flag or address. Besides transfers, it may be used to specify destination addresses dynamically for various commands.

In each case, map computes the appropriate destination according to recipient and returns it.

Modules

Payments

pay

pay
solidity
function pay(address token, address recipient, uint256 value) internal {
        if (token == Constants.ETH) {
            recipient.safeTransferETH(value);
        } else {
            if (value == Constants.CONTRACT_BALANCE) {
                value = ERC20(token).balanceOf(address(this));
            }

            ERC20(token).safeTransfer(recipient, value);
        }
}

Overview Pays ETH or ERC20 tokens to a recipient address.

Details Pays the specified amount of the specified token to the recipient address. If the token is ETH, it uses safeTransferETH to transfer ETH safely. If the token is ERC20, it safely transfers the specified amount to the recipient. If the amount is Constants.CONTRACT_BALANCE, it uses the contract's balance as the payment amount.

Arguments

  • token
    • Address of the token to pay.
  • recipient
    • Recipient address.
  • value
    • Amount to pay.

Return value None


approveERC20

approveERC20
solidity
function approveERC20(ERC20 token, Spenders spender) internal {
        // check spender is one of our approved spenders
        address spenderAddress;
        /// @dev use 0 = Opensea Conduit for both Seaport v1.4 and v1.5
        if (spender == Spenders.OSConduit) spenderAddress = OPENSEA_CONDUIT;
        else if (spender == Spenders.Sudoswap) spenderAddress = SUDOSWAP;
        else revert InvalidSpender();

        // set approval
        token.safeApprove(spenderAddress, type(uint256).max);
}

Overview Approves a protocol to spend ERC20 tokens.

Details Takes the specified ERC20 token and spender address and grants the spender the maximum token allowance. The spender must be one of the predefined spenders, such as Opensea, Conduit, or Sudoswap.

Arguments

  • token
    • ERC20 instance of the token to approve.
  • spender
    • Spender address to approve.

Return value None


payPortion

payPortion
solidity
function payPortion(address token, address recipient, uint256 bips) internal {
        if (bips == 0 || bips > FEE_BIPS_BASE) revert InvalidBips();
        if (token == Constants.ETH) {
            uint256 balance = address(this).balance;
            uint256 amount = (balance * bips) / FEE_BIPS_BASE;
            recipient.safeTransferETH(amount);
        } else {
            uint256 balance = ERC20(token).balanceOf(address(this));
            uint256 amount = (balance * bips) / FEE_BIPS_BASE;
            ERC20(token).safeTransfer(recipient, amount);
        }
}

Overview Pays a portion of the contract's ETH or ERC20 token balance to a recipient address.

Details Pays the specified proportion of the specified token to the recipient. The proportion is supplied in basis points (bips) and calculated relative to FEE_BIPS_BASE, the basis-point denominator. If the token is ETH, it safely transfers the payment calculated from the contract's balance. The same applies to ERC20 tokens.

Arguments

  • token
    • Address of the token to pay.
  • recipient
    • Recipient address.
  • bips
    • Proportion to pay, in basis points.

Return value None

payPortion takes a specified proportion of the contract's balance of a token and sends it to a specified address.

For example, suppose the function is called as follows.

solidity
payPortion(tokenAddress, recipientAddress, 500); // 500 bips (5%)

Here, tokenAddress is the token address, and recipientAddress is the recipient. 500 represents the proportion to pay; 500 bips corresponds to 5% of the total balance.

  1. First, verify that the specified proportion of 500 does not exceed FEE_BIPS_BASE (10000). This checks that the proportion is valid. If the proportion is 0 or exceeds 10000, the InvalidBips error is raised.

  2. Check whether the specified token is ETH. If it is ETH, retrieve the contract's balance and calculate the amount to send based on the specified proportion. The calculated amount is 5% of the contract's balance, corresponding to the specified proportion.

  3. If the token is not ETH, treat it as an ERC20 token. Retrieve the contract address's balance from the specified token contract, and calculate the amount to send in the same way.

  4. Finally, send the calculated amount to the specified address using recipient.safeTransferETH(amount) or ERC20(token).safeTransfer(recipient, amount). This sends the specified proportion of tokens to the recipient.

This function enables different tokens to be distributed from the contract according to specified proportions.


sweep

sweep
solidity
function sweep(address token, address recipient, uint256 amountMinimum) internal {
        uint256 balance;
        if (token == Constants.ETH) {
            balance = address(this).balance;
            if (balance < amountMinimum) revert InsufficientETH();
            if (balance > 0) recipient.safeTransferETH(balance);
        } else {
            balance = ERC20(token).balanceOf(address(this));
            if (balance < amountMinimum) revert InsufficientToken();
            if (balance > 0) ERC20(token).safeTransfer(recipient, balance);
        }
}

Overview Sends the contract's entire ERC20 token or ETH balance to a specified address.

Details Sends the specified token to the destination address if the contract's balance meets the specified minimum amount. For ETH, it raises an error if the amount to send is below the specified minimum.

Arguments

  • token
    • Address of the token to send.
  • recipient
    • Destination address.
  • amountMinimum
    • Minimum amount to send.

Return value None


sweepERC721

sweepERC721
solidity
function sweepERC721(address token, address recipient, uint256 id) internal {
        ERC721(token).safeTransferFrom(address(this), recipient, id);
}

Overview Sends an ERC721 token held by the contract to a specified address.

Details Takes the specified ERC721 token, recipient address, and token ID, and safely transfers that ERC721 token from the contract to the recipient.

Arguments or parameters

  • token
    • Address of the ERC721 token to send.
  • recipient
    • Recipient address.
  • id
    • ID of the ERC721 token to send.

Return value None


sweepERC1155

sweepERC1155
solidity
function sweepERC1155(address token, address recipient, uint256 id, uint256 amountMinimum) internal {
        uint256 balance = ERC1155(token).balanceOf(address(this), id);
        if (balance < amountMinimum) revert InsufficientToken();
        ERC1155(token).safeTransferFrom(address(this), recipient, id, balance, bytes(''));
}

Overview Sends ERC1155 tokens held by the contract to a specified address.

Details Takes the specified ERC1155 token, recipient address, token ID, and minimum amount, and safely transfers the specified ERC1155 tokens held by the contract to the recipient.

Arguments

  • token
    • Address of the ERC1155 token to send.
  • recipient
    • Recipient address.
  • id
    • ID of the ERC1155 token to send.
  • amountMinimum
    • Minimum amount to send.

Return value None


wrapETH

wrapETH
solidity
function wrapETH(address recipient, uint256 amount) internal {
        if (amount == Constants.CONTRACT_BALANCE) {
            amount = address(this).balance;
        } else if (amount > address(this).balance) {
            revert InsufficientETH();
        }
        if (amount > 0) {
            WETH9.deposit{value: amount}();
            if (recipient != address(this)) {
                WETH9.transfer(recipient, amount);
            }
        }
}

Overview Converts a specified amount of ETH into WETH and sends it to the specified recipient.

Details Performs the conversion of ETH into WETH (Wrapped Ether). WETH is a wrapper token for ETH that can be handled as a token on Ethereum. Converts the specified amount of ETH into WETH and sends it to the recipient. In certain cases, it can also convert the contract's entire ETH balance.

Arguments:

  • recipient
    • Address receiving WETH.
  • amount
    • Amount of ETH to convert (specify Constants.CONTRACT_BALANCE to convert the contract's entire ETH balance).

unwrapWETH9

unwrapWETH9
solidity
function unwrapWETH9(address recipient, uint256 amountMinimum) internal {
        uint256 value = WETH9.balanceOf(address(this));
        if (value < amountMinimum) {
            revert InsufficientETH();
        }
        if (value > 0) {
            WETH9.withdraw(value);
            if (recipient != address(this)) {
                recipient.safeTransferETH(value);
            }
        }
}

Overview Converts all WETH held by the contract into ETH and sends it to the recipient if the amount meets the specified minimum.

Details Converts the contract's entire WETH balance into ETH. If the amount meets the specified minimum, it sends the ETH to the recipient.

Arguments:

  • recipient
    • Address receiving ETH.
  • amountMinimum
    • Minimum amount of ETH to send.

Permit2Payments

permit2TransferFrom

permit2TransferFrom
solidity
function permit2TransferFrom(address token, address from, address to, uint160 amount) internal {
        PERMIT2.transferFrom(from, to, amount, token);
}

Overview Executes transferFrom on the Permit2 contract.

Details Transfers the specified amount of a token from a specified source address to a recipient address.

Arguments

  • token
    • Address of the token to transfer.
  • from
    • Source address of the token transfer.
  • to
    • Destination address of the token transfer.
  • amount
    • Amount of tokens to transfer.

permit2TransferFrom

permit2TransferFrom
solidity
function permit2TransferFrom(IAllowanceTransfer.AllowanceTransferDetails[] memory batchDetails, address owner)
        internal
    {
        uint256 batchLength = batchDetails.length;
        for (uint256 i = 0; i < batchLength; ++i) {
            if (batchDetails[i].from != owner) revert FromAddressIsNotOwner();
        }
        PERMIT2.transferFrom(batchDetails);
}

Overview Executes a batch token transfer using Permit2.

Details Transfers tokens according to each transfer detail in the specified batch. Raises an error if the owner addresses do not match.

Arguments

  • batchDetails
    • Array containing the details of each transfer.
  • owner
    • Owner address.

payOrPermit2Transfer

payOrPermit2Transfer
solidity
function payOrPermit2Transfer(address token, address payer, address recipient, uint256 amount) internal {
        if (payer == address(this)) pay(token, recipient, amount);
        else permit2TransferFrom(token, payer, recipient, amount.toUint160());
}

Overview Executes a payment or transferFrom on the Permit2 contract. For payment, it checks whether payer matches the contract's own address; otherwise, it invokes transferFrom on Permit2.

Details Executes a payment or Permit2 transferFrom according to the specified conditions. If payer is the contract's own address, it performs a normal payment. Otherwise, it uses Permit2 transferFrom to transfer the specified token to the specified recipient.

Arguments

  • token
    • Address of the token to transfer.
  • payer
    • Address making the payment.
  • recipient
    • Recipient address for the tokens.
  • amount
    • Amount of tokens to transfer.

Libraries

Commands

FLAG_ALLOW_REVERT

FLAG_ALLOW_REVERT
solidity
bytes1 internal constant FLAG_ALLOW_REVERT = 0x80;

Description Used as a command flag. Checks whether a particular bit is set, indicating whether a revert is allowed.


COMMAND_TYPE_MASK

COMMAND_TYPE_MASK
solidity
bytes1 internal constant COMMAND_TYPE_MASK = 0x3f;

Description Used as a mask to obtain the command type. A bitmask for extracting the command type.

This constant masks specific bits to extract command type information.

A byte (bytes1) is an 8-bit data type, with each bit having a value of 0 or 1. 0x3f is hexadecimal notation corresponding to 00111111 in binary. This binary pattern has its lower 6 bits set to 1 and its upper 2 bits set to 0.

COMMAND_TYPE_MASK extracts only the command type information from the byte representation of a command. Using it as a bitmask ignores the upper 2 bits and retains only the lower 6 bits.

The following example demonstrates a bitmask.

text
bytes1 commandByte = 0x27;  // 00100111 in binary
bytes1 commandType = commandByte & COMMAND_TYPE_MASK;

In the example, the lower 6 bits of commandByte are extracted and stored in commandType. As a result, the original explanation states that commandType contains 0x07 (00000111 in binary). This illustrates the use of a bitmask to extract command type information.

Using COMMAND_TYPE_MASK in this way lets you extract specific bits from a command byte to obtain the required information.

Bitmasks A bitmask is a technique that uses a specific bit pattern to extract or manipulate particular bits. It applies logical operations to selected bit positions to obtain or modify those bits. Bitmasks are primarily used in programming and data processing.

The following examples illustrate the concept of a bitmask. Consider 8-bit binary data, where each bit is either 0 or 1. For example, consider the byte 0x6B (01101011 in binary).

  1. Extracting a particular bit A bitmask can be used to obtain the value of a particular bit. For example, consider extracting the third bit (counting the least significant bit as bit 0) using AND.
plaintext
Byte:    01101011
Mask:    00000100 (1 shifted left by 3 bits)
-----------------
Result:  00000000 (bits 0 through 3 are zero)

The resulting value of the third bit is zero.

  1. Setting a particular bit A bitmask can also be used to set a particular bit to 1. For example, consider setting bit 5 to 1 using OR.
plaintext
Byte:    01101011
Mask:    00100000 (1 shifted left by 5 bits)
-----------------
Result:  01101011 (bit 5 is set to 1)

As a result, bit 5 is set to 1.

  1. Clearing a particular bit A bitmask can also be used to clear a particular bit to 0. For example, consider clearing bit 2 using AND.
plaintext
Byte:    01101011
Mask:    11111011 (0 shifted left by 2 bits and inverted)
-----------------
Result:  01101011 (bit 2 remains unchanged)

As a result, bit 2 remains unchanged.

Bitmasks are useful for performing specific bit operations. Bitwise operations let programmers extract, set, and clear individual bits for a wide variety of purposes.


V3_SWAP_EXACT_IN

V3_SWAP_EXACT_IN
solidity
uint256 constant V3_SWAP_EXACT_IN = 0x00;

Description Part of the command type definitions. Represents a version 3 exact-input swap command. A swap operation with a specified input token amount and a calculated output amount.


V3_SWAP_EXACT_OUT

V3_SWAP_EXACT_OUT
solidity
uint256 constant V3_SWAP_EXACT_OUT = 0x01;

Description Part of the command type definitions. Represents a version 3 exact-output swap command. A swap operation with a specified output token amount and a calculated input amount.


PERMIT2_TRANSFER_FROM

PERMIT2_TRANSFER_FROM
solidity
uint256 constant PERMIT2_TRANSFER_FROM = 0x02;

Description This variable is part of the command type definitions. It represents the command that uses the permit feature to authorize a token transfer.


PERMIT2_PERMIT_BATCH

PERMIT2_PERMIT_BATCH
solidity
uint256 constant PERMIT2_PERMIT_BATCH = 0x03;

Description Part of the command type definitions. Represents the batch command using permit for multiple tokens.


SWEEP

SWEEP
solidity
uint256 constant SWEEP = 0x04;

Description Part of the command type definitions. Represents a token sweep operation. The command is used to collect tokens from multiple addresses.


TRANSFER

TRANSFER
solidity
uint256 constant TRANSFER = 0x05;

Description Part of the command type definitions. Represents a token transfer command.


PAY_PORTION

PAY_PORTION
solidity
uint256 constant PAY_PORTION = 0x06;

Description Part of the command type definitions. Represents a command to pay a portion of a particular token. For example, it can be used to pay a portion of a token to its holder.


FIRST_IF_BOUNDARY

FIRST_IF_BOUNDARY
solidity
uint256 constant FIRST_IF_BOUNDARY = 0x08;

Description Marks the boundary for commands meeting a certain condition when their types fall within a specified range. Command types beyond this boundary are evaluated under a different condition.

Defines a boundary that partitions commands among nested conditional (if) blocks to execute them efficiently. Here is how this constant is used.

  1. FIRST_IF_BOUNDARY has the value 0x08. This hexadecimal value corresponds to 00001000 in binary.

  2. Commands are classified into multiple types according to the operation and conditions. Command types range from 0x00 to 0x3f.

  3. If the command type is less than FIRST_IF_BOUNDARY (0 through 7), the command executes within the first nested conditional block. This allows the first branch to execute efficiently based on the command type.

  4. If the command type is at or above FIRST_IF_BOUNDARY (8 or above), it does not execute within the first conditional block, but within a more deeply nested block. This makes it possible to group and process different command types appropriately.

FIRST_IF_BOUNDARY therefore acts as a marker for dividing commands among nested conditional blocks by type. This enables different types of commands to execute in the appropriate location and be processed efficiently.


V2_SWAP_EXACT_IN

V2_SWAP_EXACT_IN
solidity
uint256 constant V2_SWAP_EXACT_IN = 0x08;

Description Part of the command type definitions. Represents a version 2 exact-input swap command. A swap operation with a specified input token amount and a calculated output amount.


V2_SWAP_EXACT_OUT

V2_SWAP_EXACT_OUT
solidity
uint256 constant V2_SWAP_EXACT_OUT = 0x09;

Description Part of the command type definitions. Represents a version 2 exact-output swap command. A swap operation with a specified output token amount and a calculated input amount.


PERMIT2_PERMIT

PERMIT2_PERMIT
solidity
uint256 constant PERMIT2_PERMIT = 0x0a;

Description Part of the command type definitions. Represents a token transfer command using permit.


WRAP_ETH

WRAP_ETH
solidity
uint256 constant WRAP_ETH = 0x0b;

Description Part of the command type definitions. Represents a command to wrap Ether (ETH). Converts ETH into a particular ERC20 token.


UNWRAP_WETH

UNWRAP_WETH
solidity
uint256 constant UNWRAP_WETH = 0x0c;

Description Part of the command type definitions. Represents a command to unwrap Wrapped Ether (WETH). Converts WETH back into ETH.


PERMIT2_TRANSFER_FROM_BATCH

PERMIT2_TRANSFER_FROM_BATCH
solidity
uint256 constant PERMIT2_TRANSFER_FROM_BATCH = 0x0d;

Description Part of the command type definitions. Represents the batch command using permit for multiple tokens.


BALANCE_CHECK_ERC20

BALANCE_CHECK_ERC20
solidity
uint256 constant BALANCE_CHECK_ERC20 = 0x0e;

Description Part of the command type definitions. Represents a command to check the balance of a specific ERC20 token.


SECOND_IF_BOUNDARY

SECOND_IF_BOUNDARY
solidity
uint256 constant SECOND_IF_BOUNDARY = 0x10;

Description Marks the boundary for commands meeting a certain condition when their types fall within a specified range. Command types beyond this boundary are evaluated under a different condition.


SEAPORT_V1_5

SEAPORT_V1_5
solidity
uint256 constant SEAPORT_V1_5 = 0x10;

Description Part of the command type definitions. Represents an operation on Seaport version 1.5.

SeaPort Seaport is the trading protocol provided by the NFT marketplace OpenSea.


LOOKS_RARE_V2

LOOKS_RARE_V2
solidity
uint256 constant LOOKS_RARE_V2 = 0x11;

Description Part of the command type definitions. Represents an operation on LooksRare version 2.

https://looksrare.org/ja


NFTX

NFTX
solidity
uint256 constant NFTX = 0x12;

Description Part of the command type definitions. Represents an operation involving NFTX.


CRYPTOPUNKS

CRYPTOPUNKS
solidity
uint256 constant CRYPTOPUNKS = 0x13;

Description Part of the command type definitions. Represents an operation involving CryptoPunks.


OWNER_CHECK_721

OWNER_CHECK_721
solidity
uint256 constant OWNER_CHECK_721 = 0x15;

Description Part of the command type definitions. Represents a command to check the owner of a particular ERC721 token.


OWNER_CHECK_1155

OWNER_CHECK_1155
solidity
uint256 constant OWNER_CHECK_1155 = 0x16;

Description This variable is part of the command type definitions. Represents a command to check ownership of a particular ERC1155 token.


THIRD_IF_BOUNDARY

THIRD_IF_BOUNDARY
solidity
uint256 constant THIRD_IF_BOUNDARY = 0x18;

Description Marks the boundary for commands meeting a certain condition when their types fall within a specified range. Command types beyond this boundary are evaluated under a different condition.


X2Y2_721

X2Y2_721
solidity
uint256 constant X2Y2_721 = 0x18;

Description Part of the command type definitions. Represents a command to exchange an ERC721 token.


SUDOSWAP

SUDOSWAP
solidity
uint256 constant SUDOSWAP = 0x19;

Description Part of the command type definitions. Represents an operation involving SudoSwap.


NFT20

NFT20
solidity
uint256 constant NFT20 = 0x1a;

Description Part of the command type definitions. Represents an operation involving ERC20 tokens.


X2Y2_1155

X2Y2_1155
solidity
uint256 constant X2Y2_1155 = 0x1b;

Description Part of the command type definitions. Represents a command to exchange ERC1155 tokens.


FOUNDATION

FOUNDATION
solidity
uint256 constant FOUNDATION = 0x1c;

Description Part of the command type definitions. Represents an operation involving Foundation.


SWEEP_ERC1155

SWEEP_ERC1155
solidity
uint256 constant SWEEP_ERC1155 = 0x1d;

Description Part of the command type definitions. Represents an ERC1155 token sweep operation.


ELEMENT_MARKET

ELEMENT_MARKET
solidity
uint256 constant ELEMENT_MARKET = 0x1e;

Description Part of the command type definitions. Represents an operation involving Element Market.


FOURTH_IF_BOUNDARY

FOURTH_IF_BOUNDARY
solidity
uint256 constant FOURTH_IF_BOUNDARY = 0x20;

Description Marks the boundary for commands meeting a certain condition when their types fall within a specified range. Command types beyond this boundary are evaluated under a different condition.


SEAPORT_V1_4

SEAPORT_V1_4
solidity
uint256 constant SEAPORT_V1_4 = 0x20;

Description Part of the command type definitions. Represents an operation on Seaport version 1.4.


EXECUTE_SUB_PLAN

EXECUTE_SUB_PLAN
solidity
uint256 constant EXECUTE_SUB_PLAN = 0x21;

Description Part of the command type definitions. Represents a command to execute a sub-plan. A sub-plan is a sequence of command execution steps.


APPROVE_ERC20

APPROVE_ERC20
solidity
uint256 constant APPROVE_ERC20 = 0x22;

Description Part of the command type definitions. Represents a command to approve ERC20 tokens. Authorizes another address to operate on a token.


Constants

The following sections explain the variables in this library.

CONTRACT_BALANCE

詳細
solidity
uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;

Description Identifies cases where the balance of a particular token is used as input. The value has a single 1 in its most significant bit position.

This constant indicates that the contract's balance of a particular token should be used as input.

In binary, the constant is a value whose most significant bit is 1. This 1 occupies the highest-place-value bit in the binary representation, giving it a greater place value than any other bit. A value of 1 in this bit indicates that a particular condition holds.

The constant 0x8000000000000000000000000000000000000000000000000000000000000000 is 8000000000000000000000000000000000000000000000000000000000000000 in hexadecimal. The original article represents it in binary as 10000000000000000000000000000000000000000000000000000000000000000.

In the bit representation, one bit is 1 and all other bits are 0. This property can be used to check whether this bit is 1 when using a token balance as input.


ALREADY_PAID

詳細
solidity
uint256 internal constant ALREADY_PAID = 0;

Description Identifies cases where the v2 pair has already received the input tokens.


ETH

詳細
solidity
address internal constant ETH = address(0);

Description Identifies ETH (Ether) transactions. Specifically, it is used when ETH rather than a token is sent.


MSG_SENDER

詳細
solidity
address internal constant MSG_SENDER = address(1);

Description A flag identifying a particular address. Its value is address(1), representing the transaction sender's address.


ADDRESS_THIS

詳細
solidity
address internal constant ADDRESS_THIS = address(2);

Description A flag identifying a particular address. Its value is address(2), representing the contract's own address.


ADDR_SIZE

詳細
solidity
uint256 internal constant ADDR_SIZE = 20;

Description Indicates the length of an encoded address in bytes. An Ethereum address is represented by 20 bytes, so this value is 20.


V3_FEE_SIZE

詳細
solidity
uint256 internal constant V3_FEE_SIZE = 3;

Description Indicates the byte length of an encoded v3 fee. Specifically, fee information occupies 3 bytes.


NEXT_V3_POOL_OFFSET

詳細
solidity
uint256 internal constant NEXT_V3_POOL_OFFSET = ADDR_SIZE + V3_FEE_SIZE;

Description Indicates the offset to the next v3 pool information. In particular, it points to the start of the next encoded pool information containing an address and fee.


V3_POP_OFFSET

詳細
solidity
uint256 internal constant V3_POP_OFFSET = NEXT_V3_POOL_OFFSET + ADDR_SIZE;

Description Indicates the offset of the encoded pool key. The pool key refers to the encoded token address and fee information.


MULTIPLE_V3_POOLS_MIN_LENGTH

詳細
solidity
uint256 internal constant MULTIPLE_V3_POOLS_MIN_LENGTH = V3_POP_OFFSET + NEXT_V3_POOL_OFFSET;

Description Indicates the minimum encoded length when multiple v3 pools are represented. When multiple pools are included, the encoding needs this minimum length to distinguish the individual pool information.

Events

RewardsSent

Overview An event emitted when rewards are sent.

Details Notifies other applications or users that rewards have been sent.

Parameters

  • amount
    • Amount of rewards sent.

Code

Contracts

  • UniversalRouter/contracts

Libraries

  • UniversalRouter/lib

Base contracts

  • UniversalRouter/contracts/base

Libraries (contracts)

  • UniversalRouter/contracts/libraries

Interfaces

  • UniversalRouter/contracts/interfaces

Modules

  • UniversalRouter/contracts/modules

Conclusion

This article examined the UniversalRouter contract used by Uniswap V3 with Bunzz's DeCipher feature. I hope the walkthrough was useful. I plan to continue covering individual NFTs and contracts in future articles.

I also publish articles about blockchain and AI on my blog and Qiita; you can find them below.

https://chaldene.net/