首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用address.call()设置值无效

使用address.call()设置值无效
EN

Ethereum用户
提问于 2021-04-05 09:51:50
回答 1查看 284关注 0票数 1

我试图在Caller契约中运行一个setter函数(testCallBar),它应该使用call方法运行接收方合同的setVal()。但它不起作用。testCallFoo()按预期工作,但testCallBar()总是返回false。

我想要实现的是使用call()方法从Caller契约运行任何接收方契约的功能。

我在这里做错什么了?此外,在这种情况下,使用address.call()方法运行任何具有数据类型参数的函数的更好方法是什么?

代码语言:javascript
复制
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);
    }
    
    
}
EN

回答 1

Ethereum用户

回答已采纳

发布于 2021-04-05 10:07:18

只需在testCallBar函数内的调用中将分配的气体从5,000增加到10000,它就会工作。

实际上,setValfoo更昂贵,因为它更新了状态变量(bar)。

票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/96726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档