Solidity – Can Multiple Functions Be Payable?

ethersolidity

I'm trying to understand open zepplins crowd sale contract code: https://github.com/OpenZeppelin/zeppelin-solidity

I understand that if someone sends ether to the contract address that it responds with:

   // fallback function can be used to buy tokens
  function () public payable {
    proxyPayment(msg.sender);
  }

But I'm a little confused about how "payable" works. Can only one function per contract be "payable"? And is that function basically just an event listener for when the contract receives ether?

Thanks

Best Answer

payable is a modifier that allow a function to be called with a non zero value (that you can access via msg.value ) .

function canReceiveEther() payable {
 /// some code here
}

Exemple above will be able to be called and deal with any amount of ether sent to it .

If you do not mark your function as payable but someone do a call to it it will be rejected .

Now the function that you mentionned in your post is kinda a special one, it's what we call the fallback function (see the official doc here) That's the only function that can be unnamed and will be executed if you call the contract but none of the function match the parameters or if you don't provide data.

So in short :

  • More than one function can be marked as payable but only one can be the fallback function .
  • The fallback function will be called when :
    • No functions match the data you provided .
    • You call the contract with no data .
    • You call the contract with send or transfer.

Note : fallback function only have access to a really limited amount of gas (2300 , see doc) . So it's better to keep the cost of the function as cheap as possible .

Related Topic