0
0
Blockchain / Solidityprogramming~30 mins

Receive and fallback functions in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Receive and fallback functions
📖 Scenario: You are creating a simple smart contract on Ethereum that can receive Ether payments. Sometimes, Ether is sent directly without calling any function, and sometimes it is sent with data that does not match any function. Your contract needs to handle both cases safely.
🎯 Goal: Build a Solidity contract that uses receive() and fallback() functions to accept Ether payments and log when each function is called.
📋 What You'll Learn
Create a contract named PaymentReceiver
Add a receive() function to accept plain Ether transfers
Add a fallback() function to accept Ether with unknown data
Emit events inside both functions to log which function was triggered
Test sending Ether with and without data to see which function runs
💡 Why This Matters
🌍 Real World
Smart contracts often need to accept payments safely. Using receive() and fallback() functions ensures the contract can handle Ether sent in different ways.
💼 Career
Understanding receive() and fallback() is essential for blockchain developers to write secure and reliable contracts that interact with Ether transfers.
Progress0 / 4 steps
1
Create the contract and event
Create a contract called PaymentReceiver and inside it, declare an event named ReceivedEther that logs an address sender and a uint amount.
Blockchain / Solidity
Need a hint?

Use the event keyword to declare an event inside the contract.

2
Add the receive() function
Inside the PaymentReceiver contract, add a receive() external payable function that emits the ReceivedEther event with msg.sender and msg.value.
Blockchain / Solidity
Need a hint?

The receive() function has no name and no arguments. It must be marked external payable.

3
Add the fallback() function
Inside the PaymentReceiver contract, add a fallback() external payable function that emits an event named FallbackCalled with msg.sender and msg.value. Declare the FallbackCalled event above.
Blockchain / Solidity
Need a hint?

The fallback() function is called when no other function matches. It must be external payable to accept Ether.

4
Test sending Ether and print logs
Add a public view function named getBalance() that returns the contract's Ether balance as uint. Then add a print statement to display the balance after deployment and after sending Ether (simulate this in your test environment).
Blockchain / Solidity
Need a hint?

Use address(this).balance to get the contract's Ether balance.