欢迎订阅专栏:3分钟Solidity--智能合约--Web3区块链技术必学
如需获取本内容的最新版本,请参见 Cyfrin.io 上的多代理通话(代码示例)
一个合约对目标智能合约进行 delegatecall 时,会在自己的环境中执行目标合约的逻辑。 一种思维模型是它复制目标智能合约的代码并自行运行该代码。目标智能合约通常被称为“实现合约”。
使用 delegatecall通过单笔交易调用多个函数的示例。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract MultiDelegatecall {
error DelegatecallFailed();
function multiDelegatecall(bytes[] memory data)
external
payable
returns (bytes[] memory results)
{
results = new bytes[](data.length);
for (uint256 i; i < data.length; i++) {
(bool ok, bytes memory res) = address(this).delegatecall(data[i]);
if (!ok) {
revert DelegatecallFailed();
}
results[i] = res;
}
}
}
// 为什么要使用多重委托调用?为什么不使用多重调用?
// alice -> multi call --- call ---> test (msg.sender = multi call)
// alice -> test --- delegatecall ---> test (msg.sender = alice)
contract TestMultiDelegatecall is MultiDelegatecall {
event Log(address caller, string func, uint256 i);
function func1(uint256 x, uint256 y) external {
// msg.sender = alice
emit Log(msg.sender, "func1", x + y);
}
function func2() external returns (uint256) {
// msg.sender = alice
emit Log(msg.sender, "func2", 2);
return 111;
}
mapping(address => uint256) public balanceOf;
// WARNING: 在多委托调用中使用不安全代码
// 用户可以多次铸造,价格为msg.value
function mint() external payable {
balanceOf[msg.sender] += msg.value;
}
}
contract Helper {
function getFunc1Data(uint256 x, uint256 y)
external
pure
returns (bytes memory)
{
return
abi.encodeWithSelector(TestMultiDelegatecall.func1.selector, x, y);
}
function getFunc2Data() external pure returns (bytes memory) {
return abi.encodeWithSelector(TestMultiDelegatecall.func2.selector);
}
function getMintData() external pure returns (bytes memory) {
return abi.encodeWithSelector(TestMultiDelegatecall.mint.selector);
}
}
Remix Lite 尝试一下