3

Here I have a function which deploys a Contract straight from bytecode, but let say my contract needs some arguments in the constructor, is it possible to pass them through create opcode?

function deployCode(bytes _code) returns (address deployedAddress) {
    assembly {
        deployedAddress := create(0, add(_code, 0x20), mload(_code))
        jumpi(invalidJumpLabel, iszero(extcodesize(deployedAddress)))
    }
    return deployedAddress
}
3

Constructor arguments are appended to the deployment byte code in the standard ABI format.

For example, this contract takes uint constructor argument.

contract Foo {
    uint a;
    function Foo(uint _a) public {
        a = _a;
    }
}

It compiles to the following deployment bytecode:

0x60606040523415600e57600080fd5b6040516020806073833981016040528080519060200190919050508060008190555050603580603e6000396000f3006060604052600080fd00a165627a7a72305820f8da2d5811af956ad9465b607d0bce8b63b85210cd2c6faf9af78ce7b2eb3d6f0029

If we want to pass the value 42 (0x2a) to the constructor then we append the 32-byte ABI version of 0x2a to the bytecode that we give to the CREATE operation. The constructor knows where to find it. I.e. Pass this to CREATE:

0x60606040523415600e57600080fd5b6040516020806073833981016040528080519060200190919050508060008190555050603580603e6000396000f3006060604052600080fd00a165627a7a72305820f8da2d5811af956ad9465b607d0bce8b63b85210cd2c6faf9af78ce7b2eb3d6f0029000000000000000000000000000000000000000000000000000000000000002a

When the contract is CREATEd, its storage will be immediately populated with 42.

This is exactly the same as passing constructor parameters when creating a contract from an Externally Owned Account.

  • 1
    You made my day! – AirUp Mar 21 '19 at 20:16

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.