0

I need to deploy a contract within Solidity while also sending Ether to it.

To deploy a contract I do

contract NewContract {
  constructor() public payable {
    // I need to receive Ether here
  }  
}

contract Deployer {
  function deploy() {
    address nc = new NewContract();
  }
}

How can I also send some Ether while deploying? In the same transaction?

  • You may want to check ethereum.stackexchange.com/questions/15953/… to see if it provides any info – R.D Sep 20 '18 at 9:13
  • Thanks but those answers suggest creating another function that receives ether. I've improved my question and it's more explicit where I need to receive the Ether now – cleanunicorn Sep 20 '18 at 9:17
2

There are certainly cases where you want to feed contract ether in constructor only. In that case you can use .value to send some ether while constructing the contract.

contract A {
    function deployB() public payable returns (address) {
        B instance = (new B).value(msg.value)(42); // deploy B with `msg.value` wei, and put `42` as argument in constructor
        return instance;
    }
}

contract B {
    uint public num;
    constructor(uint _num) public payable {
        require(msg.value > 0); // value gets transferred from A when A deploys it
        num = _num; // num gets set to 42 when A deploys it
    }
}
  • I understand that the value sent is msg.value but what does (42) represent in your example? – cleanunicorn Sep 20 '18 at 9:28
  • It's the constructor argument in B – libertylocked Sep 20 '18 at 9:28

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.