【Solidity】call和delegatecall的区别
我们都知道call是一个去调用其他合约的方法,那delegatecall又有什么区别呢?
从以下的代码范例可以看到ContractA去调用ContractB,如果是用normallCall的话,数据是保存在ContractB的,但是如果你用delegateCall的话,数据就会存在ContractA而不是ContractB,这就是call和delegatecall的区别。
基本上合约一旦部署在区块链后就无法更改了,万一如果你的function写不好想要增加新的function来代替旧function,那么可以通过这个delegatecall技术手段达到合约升级
注意:ContractB和ContractA的变量名称必须相同,否则调用delegatecall了之后数据也是没存入ContractA的。
代码范例
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract ContractA{
uint private num;
function addOne()public{
num+=1;
}
function checkNum()public view returns(uint){
return num;
}
function normallCall(address contractAddress)public {
(bool result,) = contractAddress.call(
abi.encodeWithSignature("addTwo()")
);
if(!result) revert();
}
function delegateCall(address contractAddress)public{
(bool result,) = contractAddress.delegatecall(
abi.encodeWithSignature("addTwo()")
);
if(!result) revert();
}
}
contract ContractB{
uint private num;
function addTwo()public{
num+=2;
}
function checkNum()public view returns(uint){
return num;
}
}
![]()
Facebook评论