1

In solidity, if we have defined contracts already, its simple to create an contract in contract by using the keyword: new, like this:

contract FatherContract {
    function createChild() public {        
        new ChildContract();
    }
}

contract ChildContract {
    constructor() public {
        //...
    }
}

but what if I want to create an contract from binary data, like this:

contract FatherContract {
    function createChild(bytes contractDataInfo) public {        
        // any way to create a new contract in this method 
        // using contractDataInfo?
    }
}

If the contractDataInfo is contract creation info, any way to create a new contract in method createChild?

3

Yes, but you have to write just a little bit of assembly:

bytes memory bytecode = contractDataInfo; // need to copy into memory
address addr;
uint256 value = 0; // change if you want to attach ether

assembly {
    addr := create(value, add(bytecode, 0x20), mload(bytecode))
}

require(addr != 0, "Contract creation failed.");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.