What if your contract could never miss a payment, no matter how it arrives?
Why Receive and fallback functions in Blockchain / Solidity? - Purpose & Use Cases
Imagine you run a digital wallet that accepts money from friends. Sometimes they send money directly, sometimes they send messages with money. Without a clear way to handle these different types of incoming transactions, your wallet might get confused or even lose money.
Manually checking every incoming transaction type is slow and risky. You might miss some payments or fail to respond correctly, causing errors or lost funds. It's like trying to catch every letter in a busy post office without a sorting system.
Receive and fallback functions act like a smart mail sorter for your wallet. They automatically catch plain money transfers and unexpected calls, ensuring your contract handles every incoming transaction safely and smoothly without missing a beat.
function() external payable { revert(); } // rejects all plain transfersreceive() external payable { /* accept plain transfers */ } fallback() external payable { /* handle unknown calls */ }It enables your smart contract to safely accept funds and handle unexpected calls without crashing or losing money.
A crowdfunding contract that must accept donations sent directly or via function calls, ensuring no contribution is lost regardless of how it arrives.
Receive function handles plain Ether transfers safely.
Fallback function catches unexpected calls or data.
Together, they protect your contract from errors and lost funds.