【智能合约】delegatecall

  • address.delegatecall(bytes calldata)
  • delegatecall是将另一个合约的一个函数take over拿来当作自己合约内部函数来用;
  • 从函数执行上下文来看,形式上跨合约,实质上没有跨合约,拷贝了message,sender、value不变,但data和gaslimit可以变化
    如下图:
    【智能合约】delegatecall_第1张图片
    代码实例:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
// NOTE: Deploy this contract first
contract B {
 // NOTE: storage layout must be the same as contract A
 uint public num;
 address public sender;
 uint public value;
 bytes public cdata;
 function setVars(uint _num) public payable {
 num = _num;
 sender = msg.sender;
 value = msg.value;
 cdata = msg.data;
 }
}
contract A {
 uint public num;
 address public sender;
 uint public value;
 bytes public cdata;
 function setVars(address _contract, uint _num) public payable {
 // A's storage is set, B is not modified.
 (bool success, bytes memory data) = _contract.delegatecall(
 abi.encodeWithSignature("setVars(uint256)", _num)
 );
 }
 function setNum(uint _num) public payable {
 num = _num;
 cdata = msg.data;
 sender = msg.sender;
 value = msg.value;
 }
 function setNumIndirect(uint _num) public {
 setNum(_num);
 }
 function setNumIndirectByCall(uint _num) public {
 address(this).call(abi.encodeWithSignature("setNum(uint256)", _num));
 }
}

你可能感兴趣的:(区块链,智能合约,区块链)