我试图在Caller契约中运行一个setter函数(testCallBar),它应该使用call方法运行接收方合同的setVal()。但它不起作用。testCallFoo()按预期工作,但testCallBar()总是返回false。
我想要实现的是使用call()方法从Caller契约运行任何接收方契约的功能。
我在这里做错什么了?此外,在这种情况下,使用address.call()方法运行任何具有数据类型参数的函数的更好方法是什么?
pragma solidity ^0.8.3;
contract Receiver {
event Received(address caller, uint256 amount, string message);
uint256 bar = 9;
function foo(string memory _message, uint _x) public payable returns (uint256) {
emit Received(msg.sender, msg.value, _message);
return _x + 1;
}
function getVal() public view returns(uint256) {
return bar;
}
function setVal(uint256 _bar) public payable returns (uint256) {
bar = _bar;
return bar;
}
}
contract Caller {
event Response(bool success, bytes data);
// Let's imagine that contract B does not have the source code for
// contract A, but we do know the address of A and the function to call.
function testCallFoo(address payable _addr, uint256 z) public payable {
// You can send ether and specify a custom gas amount
(bool success, bytes memory data) = _addr.call{value: msg.value, gas: 5000}(
abi.encodeWithSignature("foo(string,uint256)", "call foo", z)
);
emit Response(success, data);
}
function testCallBar(address payable _addr, uint256 z) public payable {
// You can send ether and specify a custom gas amount
(bool success, bytes memory data) = _addr.call{value: msg.value, gas: 5000}(
abi.encodeWithSignature("setVal(uint256)", z)
);
emit Response(success, data);
}
}发布于 2021-04-05 10:07:18
只需在testCallBar函数内的调用中将分配的气体从5,000增加到10000,它就会工作。
实际上,setVal比foo更昂贵,因为它更新了状态变量(bar)。
https://ethereum.stackexchange.com/questions/96726
复制相似问题