在0.4.26版本的solidity中,delegatecall的返回值只有1个,表示delegatecall是否调用成功的布尔变量。
在0.6.8版本的solidity中,delegatecall的返回值有2个,一个是表示delegatecall是否调用成功的布尔变量,另一个则是被调用函数的返回值。
通过delegatecall调用逻辑合约来修改数据合约中的状态变量,从而实现数据和逻辑分离。后面可以通过升级逻辑合约来改变业务逻辑,但数据合约不能升级。
下面通过例子来说明在0.6.8版本的solidity中如何使用delegatecall进行合约升级。
pragma solidity ^0.6.8;
// 数据合约
contract DataContract {
uint256 public num1;
uint256 public num2;
uint256 public num3;
address public issuer;
event Log(string str, bool result);
event Log2(string str, uint256 result);
constructor() public {
issuer = msg.sender;
num1 = 1;
num2 = 2;
num3 = 3;
}
function callLogicContract(address logicContractAddr) public {
bool r;
bytes memory s;
// 通过delegatecall调用逻辑合约来修改数据合约中的状态变量,从而实现数据和逻辑分离。后面可以通过升级逻辑合约来改变业务逻辑,但数据合约不能升级
(r, s) = logicContractAddr.delegatecall(abi.encodeWithSignature("test(address)", this));
emit Log("delegatecall return ", r); // r为true或false
uint256 result = bytesToUint(s);
emit Log2("test() return ", result);
}
function bytesToUint(bytes memory b) public pure returns (uint256){
uint256 number;
for(uint i= 0; i
升级合约后,调用合约LogicContract2的test函数的日志输出
logs [
{
"from": "0x4abfb9d52f63834b2a30b42202be4f43c8cc8b48",
"topic": "0xdd970dd9b5bfe707922155b058a407655cb18288b807e2216442bca8ad83d6b5",
"event": "Log",
"args": {
"0": "after upgrading contract, num3=",
"1": "9000",
"str": "after upgrading contract, num3=",
"num": "9000",
"length": 2
}
},
{
"from": "0x4abfb9d52f63834b2a30b42202be4f43c8cc8b48",
"topic": "0x953bb7c6c7f939308a523ff2ce38248d9a26e7e8212c5f982fd8dffaca3fc523",
"event": "Log2",
"args": {
"0": "dataContract=",
"1": "0x4ABFb9D52f63834b2A30B42202Be4F43C8CC8b48",
"str": "dataContract=",
"addr": "0x4ABFb9D52f63834b2A30B42202Be4F43C8CC8b48",
"length": 2
}
},
{
"from": "0x4abfb9d52f63834b2a30b42202be4f43c8cc8b48",
"topic": "0x953bb7c6c7f939308a523ff2ce38248d9a26e7e8212c5f982fd8dffaca3fc523",
"event": "Log2",
"args": {
"0": "caller=",
"1": "0xC264358Ef94b48B62e7F94ce10795255f8b9EED7",
"str": "caller=",
"addr": "0xC264358Ef94b48B62e7F94ce10795255f8b9EED7",
"length": 2
}
},
{
"from": "0x4abfb9d52f63834b2a30b42202be4f43c8cc8b48",
"topic": "0x52dd9d08c343f72c69027ade2a075f6242dba2eeca3a3c61bfd8d00d32f6bd20",
"event": "Log",
"args": {
"0": "delegatecall return ",
"1": true,
"str": "delegatecall return ",
"result": true,
"length": 2
}
},
{
"from": "0x4abfb9d52f63834b2a30b42202be4f43c8cc8b48",
"topic": "0x0c231cace93330e81aabd308eaecd9a98302e543efad0c88d0b99732e7c2ef5f",
"event": "Log2",
"args": {
"0": "test() return ",
"1": "9000",
"str": "test() return ",
"result": "9000",
"length": 2
}
}
]