1

Aren`t constructors used to initialize variable at the time of contract creation? In common patterns section in solidity documentation, payable constructor is used for withdrawal pattern example.

    function WithdrawalContract() public payable {
    richest = msg.sender;
    mostSent = msg.value;
}

What is the significance of this cant we hard code the value or initialize it with some other function?

5

payable means that you can transfer ether with the transaction. If the contract is designed that it needs an ether deposit on construction, then you can not hard code this. You have to allow the transaction sender to indeed send this ether to the contract.

  • But if I am deploying the contract why would i need ether for its creation? Can you suggest a use case? For instance I am creating a dapp and selling some collectibles, while creation of contract it doesnot make sense to to deposit the ether. Thanks – Anam Nizami Mar 1 '18 at 10:56
  • 1
    You don't have to, if this is not your usecase. You could have a separate function deposit() payable {..}. But there are usecases where you need this. Example could be an unidirectional payment channel, where you put some ether in escrow on the channel instantiation. – ivicaa Mar 1 '18 at 11:01
  • 1
    I'll give you an example. If you make a dapp where a user can send ether and bet on a number between 1-5 where he gets like 4.90x his money back when he's right you would need to preload the contract with Ether. If you don't the contract will throw when a user picks the right number on the first try as there will be no ether in the contract to pay the user. – Nico Mar 1 '18 at 11:17

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.