欢迎订阅专栏:3分钟Solidity--Web3区块链技术必学
如需获取本内容的最新版本,请参见 Cyfrin.io 上的“调用其他合约(代码示例)”
合约可以通过两种方式调用其他合约。
最简单的方式是直接调用,比如A.foo(x, y, z)。
另一种调用其他合约的方式是使用底层调用。
不建议使用这种方法。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract Callee {
uint256 public x;
uint256 public value;
function setX(uint256 _x) public returns (uint256) {
x = _x;
return x;
}
function setXandSendEther(uint256 _x)
public
payable
returns (uint256, uint256)
{
x = _x;
value = msg.value;
return (x, value);
}
}
contract Caller {
function setX(Callee _callee, uint256 _x) public {
uint256 x = _callee.setX(_x);
}
function setXFromAddress(address _addr, uint256 _x) public {
Callee callee = Callee(_addr);
callee.setX(_x);
}
function setXandSendEther(Callee _callee, uint256 _x) public payable {
(uint256 x, uint256 value) =
_callee.setXandSendEther{value: msg.value}(_x);
}
}
Remix Lite 尝试一下
END