Receiving Ether means your smart contract can accept money sent to it. This is important to handle payments or donations.
0
0
Receiving Ether in Blockchain / Solidity
Introduction
When you want your contract to accept payments from users.
When building a crowdfunding contract that collects Ether.
When creating a contract that sells tokens or services for Ether.
When you want to receive donations or tips in Ether.
When your contract needs to hold Ether for later use.
Syntax
Blockchain / Solidity
receive() external payable {
// code to run when Ether is received
}The receive function is special and runs automatically when Ether is sent without data.
It must be marked external and payable to accept Ether.
Examples
This simple receive function allows the contract to accept Ether but does nothing else.
Blockchain / Solidity
receive() external payable {
// Accept Ether without any action
}This example emits an event when Ether is received, so you can track deposits.
Blockchain / Solidity
receive() external payable {
emit Received(msg.sender, msg.value);
}If Ether is sent with data, the fallback function runs instead of receive.
Blockchain / Solidity
fallback() external payable {
// fallback function to accept Ether with data
}Sample Program
This contract accepts Ether using the receive function and emits an event each time Ether is received. It also has a function to check the contract's balance.
Blockchain / Solidity
pragma solidity ^0.8.0; contract ReceiveEtherExample { event Received(address sender, uint amount); receive() external payable { emit Received(msg.sender, msg.value); } function getBalance() public view returns (uint) { return address(this).balance; } }
OutputSuccess
Important Notes
If your contract does not have a receive or payable fallback function, it will reject incoming Ether.
Use msg.value to know how much Ether was sent.
Always mark the receive function as payable to accept Ether.
Summary
The receive function lets your contract accept Ether sent without data.
It must be external and payable.
Use events to track received Ether easily.