0
0
Blockchain / Solidityprogramming~30 mins

Payable functions in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Payable Functions in Solidity
📖 Scenario: You are creating a simple smart contract on the Ethereum blockchain. This contract will accept payments and keep track of the total amount of Ether received.
🎯 Goal: Build a Solidity contract with a payable function that allows users to send Ether to the contract and updates the total balance received.
📋 What You'll Learn
Create a contract named PaymentReceiver
Add a public state variable totalReceived of type uint to store total Ether received
Write a payable function named receivePayment that updates totalReceived by the amount of Ether sent
Add a function to get the current totalReceived value
Print the totalReceived value after a payment
💡 Why This Matters
🌍 Real World
Smart contracts often need to accept payments in Ether. Payable functions allow contracts to receive and handle these payments securely.
💼 Career
Understanding payable functions is essential for blockchain developers working with Ethereum smart contracts, enabling them to build decentralized applications that handle money.
Progress0 / 4 steps
1
Create the contract and state variable
Create a Solidity contract named PaymentReceiver and inside it declare a public uint variable called totalReceived initialized to 0.
Blockchain / Solidity
Need a hint?

Use contract keyword to define the contract and declare totalReceived as public uint initialized to zero.

2
Add a payable function to receive Ether
Inside the PaymentReceiver contract, add a payable function named receivePayment with no parameters.
Blockchain / Solidity
Need a hint?

Define a function with payable keyword so it can accept Ether.

3
Update totalReceived inside the payable function
Inside the receivePayment function, add code to increase totalReceived by msg.value.
Blockchain / Solidity
Need a hint?

Use msg.value to get the amount of Ether sent with the transaction.

4
Add a function to get totalReceived and print it
Add a public view function named getTotalReceived that returns totalReceived. Then, write a line to print totalReceived after calling receivePayment (simulate printing by returning the value).
Blockchain / Solidity
Need a hint?

Create a view function to read the totalReceived value without changing state.