ethereum - 我可以通过另一个合约的构造函数将 eth 发送到合约吗?

标签 ethereum solidity truffle

contract FirstContract {

    function createOtherContract() payable returns(address) {
        // this function is payable. I want to take this 
        // value and use it when creating an instance of 
        // SecondContract
    }
}

contract SecondContract {
    function SecondContract() payable { 
        // SecondContract's constructor which is also payable
    }

    function acceptEther() payable {
        // Some function which accepts ether
    }
}

当用户单击网站上的按钮时,将从 js 应用程序创建 FirstContract。然后我想创建第二个合约的实例并将以太传递给新合约。我不知道如何在发送以太币时从第一个合约调用 SecondContract 的构造函数。

最佳答案

编辑:我找到了解决方案:

pragma solidity ^0.4.0;

contract B {
    function B() payable {}
}

contract A {
    address child;

    function test() {
        child = (new B).value(10)(); //construct a new B with 10 wei
    }
}

来源:http://solidity.readthedocs.io/en/develop/frequently-asked-questions.html#how-do-i-initialize-a-contract-with-only-a-specific-amount-of-wei

使用您的代码,它看起来如下所示:

pragma solidity ^0.4.0;

contract FirstContract {

    function createOtherContract() payable returns(address) {
        return (new SecondContract).value(msg.value)();
    }
}

contract SecondContract {
    function SecondContract() payable { 
    }

    function acceptEther() payable {
        // Some function which accepts ether
    }
}

关于ethereum - 我可以通过另一个合约的构造函数将 eth 发送到合约吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478646/

相关文章:

random - Solidity - 生成不依赖于输入的不可预测的随机数

javascript - 为什么我们不能从运行在智能合约上的 sendTransaction() 获得返回值?

javascript - 测试 Solidity 合约时如何从 Javascript 初始化结构?

javascript - 如何在 Truffle 中配置不同的轮询间隔?

blockchain - 以去中心化方式从 Chainlink 获取代币历史价格数据的最佳方式是什么?

测试智能合约需要 Truffle : transaction reverted if function isnt void

c# - Poloniex C# API - 尝试提取 ETH 时出错

javascript - web3使用什么哈希加密算法? ethereumjs-util Sha3 返回不同的结果

ethereum - uint 发起什么操作?

php - 使用 PHP 将 ERC20 代币从一个账户转移到另一个账户