如何实现代理合约
代码
pragma solidity ^0.8;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract B{
uint public num;
uint public value;
function donate(uint _num) payable public{
num = _num;
value = SafeMath.add(value, msg.value);
}
}
contract A{
uint public num;
uint public value;
address public b;
function donate(uint _num) payable public{
(bool success, bytes memory data) = b.delegatecall(
abi.encodeWithSignature("donate(uint256)", _num)
);
}
function setB(address _b) external{
b = _b;
}
}
1、分别部署A合约、B合约
A合约地址:0x358AA13c52544ECCEF6B0ADD0f801012ADAD5eE3 B合约地址:0x9D7f74d0C41E726EC95884E0e97Fa6129e3b5E99
2、执行A.setB
执行A.setB(0x9D7f74d0C41E726EC95884E0e97Fa6129e3b5E99)
3、执行A.donate
A.donate(45),value=123
结果
4、升级合约
只要修改B的合约,重新发布,然后再在A合约执行A.setB(address b)设置一下新的B合约地址即可
总结
A.setB(address B)将A合约代理给B合约 A.donate(uint _num)执行A.donate实际上是执行了B.donate,当时由于delegatecall的机制,B中的 执行环境 属于A,所以改变的是A的环境变量值
|