创建合约实例(Creating Contracts via `new`)

优质
小牛编辑
119浏览
2023-12-01

一个合约可以通过new关键字来创建一个合约。要创建合约的完整代码,必须提前知道,所以递归创建依赖是不可能的。

pragma solidity ^0.4.0;
contract Account{
    uint accId;
    
    //construction?
    function Account(uint accountId) payable{
        accId = accountId;
    }
}
contract Initialize{
    Account account = new Account(10);
    
    function newAccount(uint accountId){
        account = new Account(accountId);
    }
    
    function newAccountWithEther(uint accountId, uint amount){
        account = (new Account).value(amount)(accountId);
    }
}

从上面的例子可以看出来,可以在创建合约中,发送ether,但不能限制gas的使用。如果创建因为out-of-stack,或无足够的余额以及其它任何问题,会抛出一个异常。