3

I have seen this snippet in many online examples could you please explain what this is doing and why are we using it in a payable function?

function () public payable {
   revert () ; 
}   
3

The function without a name: function () is called the fallback function. It is executed when the contract receives some ETH without a function being explicitly called.

Putting revert(); in it means that you cannot send ETH to the contract without explicitly calling a payable function.

| improve this answer | |
  • 2
    See my answer as well. I don't think this is actually needed (anymore). – user19510 Dec 22 '17 at 14:13
6

I believe this pattern is not needed in versions of Solidity as old as 0.4.0 (released in September 2016). From https://github.com/ethereum/solidity/blob/develop/Changelog.md#040-2016-09-08 (my emphasis):

Contracts that want to receive Ether with a plain "send" have to implement a fallback function with the payable modifier. Contracts now throw if no payable fallback function is defined and no function matches the signature.

I believe that function () payable { revert(); } was a pattern used to prevent implicit acceptance of ether in Solidity versions older than 0.4.0, but today this is unneeded. I imagine that the practice has been carried forward largely by copy/paste.

| improve this answer | |
  • 1
    Just tested it on mainnet, this is correct. – Jesbus Dec 22 '17 at 14:20
2

The function above will basically prevent accounts from directly transferring ether to the contract.

The function above is what is called the Fallback function in solidity. If someone sends a transaction to the smart contract without specifying a function name (or the function name called doesn't match any existing function) that fallback function will be called.

So, if someone did contract.transfer(someValue); the fallback function would be executed, but since all it does is revert(), the function call fails and the gas unspent and ether sent is returned to the caller.

You'd want to do this to prevent people from mistakenly sending ether to your contract.

As a side note: This exact function can also be used by a malicious contract to attack some contracts like in the King Of Ether case: https://www.kingoftheether.com/postmortem.html#Causes

At that time the problem was caused by not limiting the gas stipends, but with the original logic (that doesn't use a withdrawal pattern) someone can code a contract that sends ether to become the king and then when this contract is dethroned and the KoE contract wants to send ether back to the contract it will always fail and rollback due to the fallback function rejecting any incoming transaction with the revert() call.

| improve this answer | |

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.