【问题标题】:Can I send eth to a contract through its constructor from another contract.我可以通过另一个合约的构造函数将 eth 发送到一个合约吗?
【发布时间】:2017-09-28 21:33:09
【问题描述】:
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 的构造函数。

【问题讨论】:

  • 您可以将创建第二个合约并将 Eth 发​​送给它分成两个单独的语句。只需创建一个包含这两行代码的单独函数。当你调用这个函数时,如果一行失败,整个事务将被还原。

标签: ethereum solidity truffle


【解决方案1】:

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

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
    }
}

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 2021-11-14
    • 2019-01-15
    • 1970-01-01
    • 2021-12-29
    • 2021-03-06
    • 2022-01-02
    • 2019-10-14
    • 2021-08-14
    相关资源
    最近更新 更多