What are the special receive and fallback functions, and when is each triggered?
Both handle ether/native currency sent to a contract without a normal function call. receive() fires when the call data is empty; fallback() fires when data is sent but matches no function (or when there is no receive).
* Empty calldata routes to receive() (or fallback() if none exists); calldata that matches no function routes to fallback() *
receive() external payable { fund(); }
fallback() external payable { fund(); }
Neither uses the function keyword — Solidity recognises them specially, and both must be external payable. The routing logic:
| Incoming call | Handler |
|---|---|
Empty call data, receive exists |
receive() |
Empty call data, no receive |
fallback() |
| Non-empty data, no matching function | fallback() |
Their practical use: if someone sends the contract money without calling fund() (e.g. a plain transfer), receive/fallback can forward them into fund() so they still get credited, rather than the ether landing silently untracked.
Go deeper:
Solidity docs: receive ether function — exactly when
receive()is invoked.Solidity docs: fallback function — the catch-all handler and its rules.