Solidity Contract Development – How to Deploy a Contract from Another Contract

contract-deploymentcontract-developmentsolidity

I'm new to Solidity and the whole blockchain environment. Learning it from a course.

I have been assigned a task which is to:

Make a parent contract that has the ability to deploy child contracts.

Can someone please guide or refer me to some resource that can help me? Thanks!

Best Answer

For create a new instance of contract you must to use the word 'new' and the name of the contract like:

[NameContract] contract = new [NameContract]();

With this statement you could use it to create a new child contract in a function or in parent contract's constructor. See this example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

contract ParentContract {
    // State variable ParentContract
    ChildContract private child;

    constructor() {
        // Create a new Child contract 
        child = new ChildContract("Test", 30);
    }
}

contract ChildContract {
    // State variables Child contract
    string name;
    uint age;

    constructor(string memory _name, uint _age) {
        name = _name;
        age = _age;
    }
}

If you want more details, see here.

Related Topic