Solidity
使用 address.call() 設置值不起作用
我正在嘗試在呼叫者合約中執行一個 setter 函式(testCallBar),該函式應該使用呼叫方法執行接收者合約的 setVal()。但它不起作用。testCallFoo() 按預期工作,但 testCallBar() 總是返回 false。
我想要實現的是使用 call() 方法從呼叫者合約執行接收者合約的任何功能。
我在這裡做錯了什麼?此外,在這種情況下,使用 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); } }
testCallBar
只需在函式內部的呼叫中將分配的氣體從 5000 增加到 10000 即可。事實上,它比更新狀態變數 ( )
setVal
更昂貴。foo``bar