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 uses Bunzz's DeCipher feature to examine Multicall2.

DeCipher is an AI-based service for generating smart contract documentation.

For instructions on using it, see:

This article is based on my personal experience with DeCipher. If you notice an error, please let me know in the comments.

The DeCipher page used here:

The corresponding Etherscan page:

Overview

Multicall2 builds on the Multicall contract originally developed by MakerDAO. It provides an efficient way to execute multiple function calls on Ethereum.

Purpose

Multicall2 collects results from multiple calls. It is particularly useful when an application needs information from several contracts or functions. Batching calls can reduce the number of network requests and, depending on how the batch is executed, save time and costs.

Responsibilities

Batch function calls

The aggregate function accepts several calls. Each Call contains a target address and encoded call data. Calls are executed together, and a failure causes the batch to revert.

Retrieve block information

The contract exposes functions for retrieving information such as the current block number and timestamp.

Retrieve ETH balances

It provides a function for reading the Ether balance of a specified address.

Attempt multiple calls

The tryAggregate function executes a batch while allowing the caller to choose whether failures cause the whole operation to revert.

Combine block information with attempted calls

The tryBlockAndAggregate function combines batched calls with block information, specifically the block number and hash. Timestamp information is available through a separate helper.

Usage

Multicall2 combines the results of multiple calls. Applications can retrieve data from several functions in one RPC call using an appropriate simulation, or execute a batch in an on-chain transaction. This reduces the need for separate network requests.

1. Define the calls

Represent each call using a Call struct containing the target address and callData. Encode the function selector and arguments in the byte sequence.

2. Call aggregate

Pass the array to aggregate. It executes each call in order and stores the returned bytes in an array. If any call fails, the entire operation reverts.

Function signatures

A function signature identifies a function by its name and ordered parameter types. ABI definitions also describe the return types, which are required for decoding results. Unlike parameter types, return types are not part of the canonical signature used to calculate the selector.

  • Function name.
  • Parameter types and order.
    • The input types determine how arguments are encoded.
  • Return types.
    • These are part of the ABI description used to decode returned data.

3. Process return data

The function returns the execution block number and an array of byte sequences. Decode each result according to the called function's return types.

4. Use tryAggregate (optional)

When individual failures should not necessarily cause the entire batch to fail, use tryAggregate with requireSuccess set to false. Each Result contains a success flag and return data.

5. Use tryBlockAndAggregate (optional)

Use tryBlockAndAggregate to obtain the execution block number and the block-hash field together with the call results. Note that the EVM's BLOCKHASH operation does not expose the hash of the current block, so the current-block hash field in this historical implementation may be zero.

Parameters

None.

Contracts

Multicall2

Call

Call
solidity
struct Call {
    address target;
    bytes callData;
}

Overview

A struct describing an external function call.

Fields

  • target — the target contract address.
  • callData — bytes encoding the function selector and arguments.

Result

Result
solidity
struct Result {
    bool success;
    bytes returnData;
}

Overview

A struct containing the result of a call.

Fields

  • success — true if the call succeeded, otherwise false.
  • returnData — the returned bytes, which can also contain failure data.

aggregate

aggregate
solidity
function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) {
    blockNumber = block.number;
    returnData = new bytes[](calls.length);
    for(uint256 i = 0; i < calls.length; i++) {
        (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData);
        require(success, "Multicall aggregate: call failed");
        returnData[i] = ret;
    }
}

Overview

Executes multiple external calls and returns their results.

Details

Accepts an array of calls, records the current block number, allocates a byte-array result for each call, then executes the calls in order. Any failed call causes a revert.

Parameters

  • calls — the array of external calls.

Returns

  • blockNumber — the execution block number.
  • returnData — the array of returned byte sequences.

blockAndAggregate

blockAndAggregate
solidity
function blockAndAggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) {
    (blockNumber, blockHash, returnData) = tryBlockAndAggregate(true, calls);
}

Overview

Retrieves block information together with the external call results by invoking tryBlockAndAggregate.

Details

Delegates to tryBlockAndAggregate and assigns its results to the corresponding return values.

Parameters

  • calls — the array of external calls.

Returns

  • blockNumber — the execution block number.
  • blockHash — the block-hash field, subject to BLOCKHASH limitations.
  • returnData — the array of Result structs.

getBlockHash

getBlockHash
solidity
function getBlockHash(uint256 blockNumber) public view returns (bytes32 blockHash) {
    blockHash = blockhash(blockNumber);
}

Overview

Returns the hash of the specified block.

Details

Reads the block hash for the supplied block number, subject to EVM availability limits.

Parameters

  • blockNumber — the requested block number.

Returns

  • blockHash — the hash returned by the EVM.

getBlockNumber

getBlockNumber
solidity
function getBlockNumber() public view returns (uint256 blockNumber) {
    blockNumber = block.number;
}

Overview

Returns the current block number.

Details

Reads the current execution block number.

Returns

  • blockNumber — the current block number.

getCurrentBlockCoinbase

getCurrentBlockCoinbase
solidity
function getCurrentBlockCoinbase() public view returns (address coinbase) {
    coinbase = block.coinbase;
}

Overview

Returns the current block's coinbase address.

Details

Reads block.coinbase. Historically this was the mining beneficiary; on proof-of-stake Ethereum it is the execution-layer fee recipient.

Returns

  • coinbase — the current block's beneficiary address.

getCurrentBlockDifficulty

getCurrentBlockDifficulty
solidity
function getCurrentBlockDifficulty() public view returns (uint256 difficulty) {
    difficulty = block.difficulty;
}

Overview

Returns the value exposed by the historical difficulty opcode.

Details

Reads the current block's difficulty field. On post-Merge Ethereum, the opcode instead exposes PREVRANDAO, so the historical name does not describe its modern semantics.

Returns

  • difficulty — the value returned by the opcode.

getCurrentBlockGasLimit

getCurrentBlockGasLimit
solidity
function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) {
    gaslimit = block.gaslimit;
}

Overview

Returns the current block's gas limit.

Details

Reads the gas limit of the execution block.

Returns

  • gaslimit — the block gas limit.

getCurrentBlockTimestamp

getCurrentBlockTimestamp
solidity
function getCurrentBlockTimestamp() public view returns (uint256 timestamp) {
    timestamp = block.timestamp;
}

Overview

Returns the current block's timestamp.

Details

Reads the timestamp of the execution block.

Returns

  • timestamp — the block timestamp.

getEthBalance

getEthBalance
solidity
function getEthBalance(address addr) public view returns (uint256 balance) {
    balance = addr.balance;
}

Overview

Returns the native Ether balance of an address.

Details

Reads the balance of the specified address.

Parameters

  • addr — the address to query.

Returns

  • balance — its native ETH balance.

getLastBlockHash

getLastBlockHash
solidity
function getLastBlockHash() public view returns (bytes32 blockHash) {
    blockHash = blockhash(block.number - 1);
}

Overview

Returns the previous block's hash.

Details

Reads the hash of the block immediately preceding the execution block.

Returns

  • blockHash — the previous block's hash.

tryAggregate

tryAggregate
solidity
function tryAggregate(bool requireSuccess, Call[] memory calls) public returns (Result[] memory returnData) {
    returnData = new Result[](calls.length);
    for(uint256 i = 0; i < calls.length; i++) {
        (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData);

        if (requireSuccess) {
            require(success, "Multicall2 aggregate: call failed");
        }

        returnData[i] = Result(success, ret);
    }
}

Overview

Executes external calls in order and collects their results.

Details

If requireSuccess is true, any failed call causes a revert. Otherwise each call's success flag and returned bytes are recorded in a Result struct.

Parameters

  • requireSuccess — whether every call must succeed.
  • calls — the array of external calls.

Returns

  • returnData — the array of Result structs.

tryBlockAndAggregate

tryBlockAndAggregate
solidity
function tryBlockAndAggregate(bool requireSuccess, Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) {
    blockNumber = block.number;
    blockHash = blockhash(block.number);
    returnData = tryAggregate(requireSuccess, calls);
}

Overview

Executes external calls and collects block information and individual results.

Details

Records the execution block number and block-hash field, executes the calls, and returns each result. If requireSuccess is true, failures cause a revert. The current block's hash is unavailable through BLOCKHASH.

Parameters

  • requireSuccess — whether every call must succeed.
  • calls — the array of external calls.

Returns

  • blockNumber — the execution block number.
  • blockHash — the block-hash field.
  • returnData — the array of Result structs.

Code

Multicall2.sol

Multicall2.sol
solidity
/**
 *Submitted for verification at Etherscan.io on 2021-03-23
*/

pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;

/// @title Multicall2 - Aggregate results from multiple read-only function calls
/// @author Michael Elliot <mike@makerdao.com>
/// @author Joshua Levine <joshua@makerdao.com>
/// @author Nick Johnson <arachnid@notdot.net>

contract Multicall2 {
    struct Call {
        address target;
        bytes callData;
    }
    struct Result {
        bool success;
        bytes returnData;
    }

    function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) {
        blockNumber = block.number;
        returnData = new bytes[](calls.length);
        for(uint256 i = 0; i < calls.length; i++) {
            (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData);
            require(success, "Multicall aggregate: call failed");
            returnData[i] = ret;
        }
    }
    function blockAndAggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) {
        (blockNumber, blockHash, returnData) = tryBlockAndAggregate(true, calls);
    }
    function getBlockHash(uint256 blockNumber) public view returns (bytes32 blockHash) {
        blockHash = blockhash(blockNumber);
    }
    function getBlockNumber() public view returns (uint256 blockNumber) {
        blockNumber = block.number;
    }
    function getCurrentBlockCoinbase() public view returns (address coinbase) {
        coinbase = block.coinbase;
    }
    function getCurrentBlockDifficulty() public view returns (uint256 difficulty) {
        difficulty = block.difficulty;
    }
    function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) {
        gaslimit = block.gaslimit;
    }
    function getCurrentBlockTimestamp() public view returns (uint256 timestamp) {
        timestamp = block.timestamp;
    }
    function getEthBalance(address addr) public view returns (uint256 balance) {
        balance = addr.balance;
    }
    function getLastBlockHash() public view returns (bytes32 blockHash) {
        blockHash = blockhash(block.number - 1);
    }
    function tryAggregate(bool requireSuccess, Call[] memory calls) public returns (Result[] memory returnData) {
        returnData = new Result[](calls.length);
        for(uint256 i = 0; i < calls.length; i++) {
            (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData);

            if (requireSuccess) {
                require(success, "Multicall2 aggregate: call failed");
            }

            returnData[i] = Result(success, ret);
        }
    }
    function tryBlockAndAggregate(bool requireSuccess, Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) {
        blockNumber = block.number;
        blockHash = blockhash(block.number);
        returnData = tryAggregate(requireSuccess, calls);
    }
}

Conclusion

This article used Bunzz DeCipher to examine Multicall2. I plan to continue exploring individual NFT and smart contract implementations in future articles.

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

https://chaldene.net/