payable() function In solidity

  • I have read many examples of payable functions, but I didn't understand any of them. Also, they talked about modifier in payable. My questions are:

    1. What exactly does payable() function do?
    2. Does this function take arguments?
  • First, payable is a modifier that can be added to a function. What you are most likely misinterpreting is a use case like:

    function () public payable {}  
    

    It's impossible to have payable() as a function name as it is a reserved keyword. You may use payable only in addition to existing functions like:

    function deposit() payable {}
    function register(address sender) payable {}
    

    Second, payable allows a function to receive ether while being called as stated in docs. It's mandatory to include the payable keyword from Solidity 0.4.x. If you try to send ether using call, as follows:

    token.foo.call.value("ETH_TO_BE_SENT")("ADDITIONAL_DATA")
    

    to a function without a payable keyword, the transaction will be rejected.

    Usually, there is a no name function to accept ether to be sent to a contract which is called a fallback function:

    function () payable {}
    

    But you may have more than one payable annotated functions that are used to perform different tasks, like registering a deposit to your contract:

    function deposit() payable {
      deposits[msg.sender] += msg.value;
    };
    

    you mean payable() is fallback function ? According to Solidity document fallback function is that function which avoid from accident of transaction to unknown contract. Please make me clear .

    Thx for spotting that. I've misspelt it in a hurry, it's all corrected now.

    you mean without , p.recipient.call.value(p.amount)(p.data) , payable() function cannot be called?

    The fallback function is mandatory for contracts to be able to receive ether transfers from solidity 0.4.x. Then, if you always throw inside this function your contract won't be able to accept any ether - preventing accidental sending. If you leave the body empty or add any non-throwing code you will keep the ether on contract balance. I hope it answers your question?

    yes you are absolutely correct . But what if in the case of payable() ?

    I've moved the content from discussion to the answer. Let me know if it's clear and helps to solve your problem.

    @Gopalojha This should be marked as the accepted answer in my opinion.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM