1

I have a contract that needs to be able to receive Ether. The contract includes a receive function to receive Ether but I wonder if it's good practice to also have a fallback function in case someone doesn't call the receive function. So I would have:

receive() external payable {
    emit Deposit(msg.sender,msg.value);
}

fallback() external payable {
    // check data length 0 so only used for sending money to contract 
    require(msg.data.length == 0);
    emit Deposit(msg.sender,msg.value);
}

or should my fallback function be something like the following so that the contract will only receive funds via the receive function:

fallback() external payable {
    revert();
}
1

1 Answer 1

1

If you don't intend to allow user sending ether with some "calldata" like the way you put require in the fallback function, you only need the receive function in your contract. You do not need to declare the fallback function:

receive() external payable {
    emit Deposit(msg.sender,msg.value);
}

With receive and without fallback, the behavior is like this (it's what you expect, according to what I understood):

  1. Users or contracts send eth to your contract directly, it triggers the receive function automatically
  2. Users or contracts send eth to your contract and add some calldata, it reverts because there is no fallback function to match this scenario.

Read more on the two functions, their priority and matching mechanism: https://docs.soliditylang.org/en/v0.8.17/contracts.html#receive-ether-function

Not the answer you're looking for? Browse other questions tagged or ask your own question.