You are viewing a single comment's thread from:

RE: Solidity开发指南

in #starnote3 days ago

为了一次性读取一个或多个合约的函数,快速得到结果。
主要是通到call 或 staticcall来读取合约数据。
calldata的计算:
abi.encodeWithSignature("test1()");
或是abi.encodeWithSelector(this.test1.selector);
eg:
targets.staticcall(calldata)
targets: ["0xd9145CCE52D386f254917e481eB44e9943F39138","0xd9145CCE52D386f254917e481eB44e9943F39138"]
calldata: ["0x6b59084d","0x66e41cb7"]

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

contract TestMultiCall {
    function test1() external view returns (uint,uint) {
        return (1, block.timestamp);
    }

    function test2() external view returns (uint,uint) {
        return (2, block.timestamp);
    }

    function getData1() external pure returns (bytes memory) {
        return abi.encodeWithSelector(this.test1.selector);
    }

    function getData2() external pure returns (bytes memory) {
        return abi.encodeWithSignature("test1()");
    }

    function getData3() external pure returns (bytes memory) {
        return abi.encodeWithSignature("test2()");
    }
}

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