Solidity 练习:Delegatecall

2022-12-29 Web3 Solidity

# 一、题目说明

delegatecall 就像 call 一样,只是被调用者的代码在调用者内部执行。

例如,合约 A 在合约 B 上调用 delegatecall。B 内部的代码是使用 A 的上下文执行的,例如 storage,msg.sender 和 msg.value。

下面给出被调用合约的内容。

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

contract TestDelegateCall {
    // Storage layout must be the same as contract A
    uint public num;
    address public sender;
    uint public value;

    function setVars(uint _num) external payable {
        num = _num;
        sender = msg.sender;
        value = msg.value;
    }

    function setNum(uint _num) external {
        num = _num;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 二、任务列表

  • 完成函数 setNum。该函数将使用 delegatecall 调用 TestDelegateCall.setNum。

# 三、解答代码

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

contract DelegateCall {
    uint public num;
    address public sender;
    uint public value;

    function setVars(address _test, uint _num) external payable {
        // This contract's storage is updated, TestDelegateCall's storage is not modified.
        (bool success, bytes memory data) = _test.delegatecall(
            abi.encodeWithSignature("setVars(uint256)", _num)
        );
        require(success, "tx failed");
    }

    function setNum(address _test, uint _num) external {
        (bool success, ) = _test.delegatecall(
            abi.encodeWithSignature("setNum(uint256)", _num)
        );
        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

# 四、参考资料

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