Solidity

Solidity Contract Creation Via New

Solidity Contract Creation Via New Main Tips

  • In Solidity you can create contracts via the keyword new.
  • This way of creating a contract also allows you to forward Ether at the same time.

Solidity Contract Creation Via New

In Solidity, you can also create contracts using the keyword new. The complete code example of the contract created this way must be known before you begin, so recursive creation-dependencies are not viable.

Example

pragma solidity ^0.4.0;

contract C1 {
    uint x;
    function C1(uint y) payable {
        x = y;
    }
}

contract C2 {
    C1 d = new C1(4); // To be executed as a part of C2's constructor

    function createC1(uint arg) {
        C1 newC1 = new C1(arg);
    }

    function createAndEndowC1(uint arg, uint amount) payable {
        // Create and send the Ether
        C1 newC1 = (new C1).value(amount)(arg);
    }
}

 

Try on Remix Try live on Hosting 

As the example has shown, You can forward Ether meanwhile creating an instance of D with the option .value(), however, limiting the amount of gas is not possible. In case the creation fails (because of out-of-stack, insufficient balance or some other kinds of problems), an exception will be thrown.

Read previous post:
Solidity Function Calls

Solidity Function Calls Main Tips In Solidity you can call functions either internally or externally. Only the same contract's functions of...

Close