Solidity 练习:Call

2022-12-29 Web3 Solidity

# 一、题目说明

call 是调用其他合约的低级函数。下面给出被调用合约的内容。

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

contract TestCall {
    fallback() external payable {}

    function foo(
        string memory _message,
        uint _x
    ) external payable returns (bool) {
        return true;
    }

    bool public barWasCalled;

    function bar(uint _x, bool _b) external {
        barWasCalled = true;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 二、任务列表

  • 完成 callBar 函数。使用 call 去执行 TestCall.bar 并传入你选择的输入。

# 三、解答代码

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

contract Call {
    function callFoo(address payable _addr) external payable {
        // You can send ether and specify a custom gas amount
        // returns 2 outputs (bool, bytes)
        // bool - whether function executed successfully or not (there was an error)
        // bytes - any output returned from calling the function
        (bool success, bytes memory data) = _addr.call{
            value: msg.value,
            gas: 5000
        }(abi.encodeWithSignature("foo(string,uint256)", "call foo", 123));
        require(success, "tx failed");
    }

    // Calling a function that does not exist triggers the fallback function, if it exists.
    function callDoesNotExist(address _addr) external {
        (bool success, bytes memory data) = _addr.call(
            abi.encodeWithSignature("doesNotExist()")
        );
    }

    function callBar(address _addr) external {
        (bool success, ) = _addr.call(
            abi.encodeWithSignature("bar(uint256,bool)", 123, true)
        );
        require(success, "tx failed");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 四、参考资料

Last Updated: 2023-01-28 4:31:25