Creating child contracts using the new keyword

Solidity contracts also have the capability to create a new child contract of any definition. This is achieved by using the new keyword. Sometimes, depending on your application's design, you will want to create a child contract and get its address registered in the main contract.

One requirement for the new keyword is that, when it is being executed in your main contract, it should know the complete definition of the child contract that it is going to create.

The following is an example MainContractwhich behaves as a register for every ChildContract it creates. When MainContract is deployed, it also deploys a ChildContract instance and assigns it to the ChildContract state variable. MainContract also provides two methods to create a ChildContract. These methods are createChildContract() and createChildAndPay():

contract ChildContract {
uint public id;
uint public balance;
constructor(uint _id) public payable {
id = _id;
balance = msg.value;
}
}

contract MainContract {
ChildContract[] public register;

//ChildContract will be created when MainContract is deployed
ChildContract public childContract = new ChildContract(100);

constructor() public {
register.push(childContract);
}

function createChildContract(uint _id) public returns(address) {
ChildContract newChild = new ChildContract(_id);
register.push(newChild);
return newChild;
}


//Send ether along with the ChildContract creation
function createChildAndPay(uint _id, uint _amount) public payable
returns(address) {
require(msg.value == _amount);
ChildContract newChild = (new ChildContract).value(_amount)(_id);
register.push(newChild);
return newChild;
}
}

As you can see, along with ChildContract creation, you can transfer ether to ChildContract using the .value() function. However, gas adjustments are not possible for constructor creation. If the contract creation fails because of an out-of-gas exception or due to any other issue, it will throw an exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.198.36