delegatecall 怎么使用,具体作用是啥?

看了这个文档, 依旧不是很理解。 能否简单的一段代码说明一下。

请先 登录 后评论

最佳答案 2020-03-03 23:46

我刚在 stackexchange 找到一个很好的例子解释 委托调用 delegatecall:

contract D {
  uint public n;
  address public sender;

  function delegatecallSetN(address _e, uint _n) {
    _e.delegatecall(bytes4(keccak256("setN(uint256)")), _n); // D's storage is set, E is not modified 
  }
}

contract E {
  uint public n;
  address public sender;
  function setN(uint _n) {
    n = _n;
    sender = msg.sender;
  }
}

当用 C 调用 delegatecallSetN, D的 sender 设置为C (E 不会修改).

delegatecall 相当于把另外一个合约(或库)的函数“拉”到了当前合约(D)来执行,就像当前合约的内部函数一样。

委托调用一个经典用法是合约的升级, 如果合约数据与逻辑分开, 逻辑函数通过委托调用来实现,就很容易实现逻辑的升级。

请先 登录 后评论

其它 0 个回答