-1

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 https://ethereum.stackexchange.com/questions/15953/send-ethers-from-one-contract-to-another to see if it provides any info – R.D Sep 20 '18 at 09: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 – Daniel Luca CleanUnicorn Sep 20 '18 at 09:17

1 Answers1

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
    }
}
libertylocked
  • 1,368
  • 8
  • 16