blockchain - 动态调用外部合约

标签 blockchain ethereum solidity

我正在尝试使契约(Contract)具有能够调用另一个契约(Contract)的功能的功能。我的目标的关键部分是,如果没有任何 import 语句,合约应该无法部署,并且默认情况下不会知道合约的名称。换句话说,该合约的用户将输入被调用的合约数据(即地址、名称)作为参数。实现这一目标的最佳方法是什么?

最佳答案

您可以按照 Rob Hitchens 的建议使用接口(interface)来执行此操作,或者您可以动态定义接口(interface)并使用 .call、.callcode、.delegatecall 执行方法。

这是一个例子:

contract ContractsCaller {

    function execute(address contractAt, uint _i, bytes32 _b) returns (bool) {
        return contractAt.call(bytes4(sha3("testMethod(uint256,bytes32)")), _i, _b);
    }
}

contract Test {

    uint256 public i;
    bytes32 public b;

    function testMethod(uint256 _i, bytes32 _b) {
        i = _i;
        b = _b;
    }
}

可以在单独的文件中定义测试。 ContractsCaller 不需要知道任何关于 Test 的信息,除了它的地址和它正在调用的方法的签名。

方法的签名是方法名称的前 4 个字节及其参数的类型:
bytes4(sha3("testMethod(uint256,bytes32)"))

More information about .call, .callcode, .delegatecall.

关于blockchain - 动态调用外部合约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106483/

相关文章:

node.js - 币安测试网部署错误 : Could not create addresses from your mnemonic or private key(s)

android - 智能合约包装器的交易哈希和超时异常

ethereum - 如何在没有控制台的情况下运行geth?

node.js - ETH 交易可以取消吗?

testing - Truffle testing - 尝试使用 web3 来测试 EIP712,有没有其他选择?

hyperledger-fabric - Endorsing 策略存储在哪里?

hyperledger-fabric - Hyperledger Explorer 配置错误

command - Truffle 迁移命令引用错误 : Migrations not defined?

blockchain - 在 remix Ide 中,这个通知是什么意思? "You have not set a script to run. Set it with @custom:dev-run-script NatSpec tag"

npm - Solidity - 输入 JSON 描述的 Solidity 代码