57-Solidity8.0-Multi Call多重呼叫合约

923 阅读1分钟

使用 for 循环聚合多个查询的合约示例和staticcall.

源码:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract MultiCall {
    function multiCall(address[] calldata targets, bytes[] calldata data)
        external
        view
        returns (bytes[] memory)
    {
        require(targets.length == data.length, "target length != data length");

        bytes[] memory results = new bytes[](data.length);

        for (uint i; i < targets.length; i++) {
            (bool success, bytes memory result) = targets[i].staticcall(data[i]);
            require(success, "call failed");
            results[i] = result;
        }

        return results;
    }
}

测试合同MultiCall

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract TestMultiCall {
    function test(uint _i) external pure returns (uint) {
        return _i;
    }

    function getData(uint _i) external pure returns (bytes memory) {
        return abi.encodeWithSelector(this.test.selector, _i);
    }
}