首页 > 解决方案 > 从已经部署的合约中调用函数?

问题描述

我想知道如何从已经部署的合约中调用一个函数。我尝试了以下一个,但它抛出了错误,并且需要不删除已部署的合同

 contract B {
    watch_addr = 0x1245689;
    function register(string _text) {
        watch_addr.call(bytes4(keccak256("register(string)")), _text);
    }
}

任何人都可以告诉我解决方案吗?

error:browser/delegate.sol:14:31: TypeError: Invalid type for argument in function call. Invalid implicit conversion from bytes4 to bytes memory requested. This function requires a single bytes argument. If all your arguments are value types, you can use abi.encode(...) to properly generate it.
       watch_addr.call(bytes4(keccak256(abi.encode("register(string)"))));

标签: solidity

解决方案


在 5.0 版中,Solidity 有一些重大变化

函数.call() ... 现在只接受一个字节参数。此外,该论点没有被填充。对此进行了更改,以使参数如何连接更加明确和清晰。更改 ... 每个.call(signature, a, b, c)以使用.call(abi.encodeWithSignature(signature, a, b, c))(最后一个仅适用于值类型)。...即使不是重大更改,但建议开发人员将x.call(bytes4(keccak256("f(uint256)"), a, b)更改为x.call(abi.encodeWithSignature("f( uint256)", a, b))

因此,调用其他合约的建议方法如下:

pragma solidity ^0.5.3;

contract test3 {       
    address watch_addr = address(0x1245689);
    function register(string memory _text) public {
        watch_addr.call(abi.encodeWithSignature("register(string)", _text));
    }
}

另请注意添加memory的关键字:您现在需要为复杂类型的函数参数指定数据位置:

结构、数组或映射类型的所有变量的显式数据位置现在是强制性的。这也适用于函数参数和返回变量。


推荐阅读