Ether and Gas
Sending and Receiving Ether
Beginner Level
Solidity provides multiple ways to send and receive Ether between contracts and accounts. Understanding these methods is essential for writing secure contracts.
1) Payable functions
- Functions marked with
payablecan receive Ether. - Non-payable functions reject any Ether sent, otherwise the transaction reverts.
Example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract PayableExample {
uint256 public balance;
// Function can receive Ether
function deposit() public payable {
balance += msg.value;
}
// Function cannot receive Ether
function notPayable() public {
// Any Ether sent here will revert
}
}
msg.valuecontains the amount of Ether sent.msg.senderis the address sending the Ether.
2) Sending Ether
Solidity provides three primary methods: transfer, send, and call.
a) transfer
- Sends Ether and reverts on failure.
- Forward gas limit: 2300 gas.
payable(recipient).transfer(1 ether);
b) send
- Sends Ether and returns a boolean indicating success.
- Forward gas limit: 2300 gas.
- Manual error handling is required.
bool success = payable(recipient).send(1 ether);
require(success, "Send failed");
c) call
- Low-level function, recommended in Solidity >= 0.6 for sending Ether.
- Forwards all remaining gas unless specified.
- Returns a boolean and data.
(bool success, ) = payable(recipient).call{value: 1 ether}("");
require(success, "Call failed");
Key points:
transferandsendare limited to 2300 gas, enough for a fallback function.callis flexible and safer for interacting with contracts that require more gas.
3) Receiving Ether
Contracts can receive Ether via receive or fallback functions:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract ReceiveEther {
event Received(address sender, uint256 amount);
// Triggered when contract receives Ether with empty calldata
receive() external payable {
emit Received(msg.sender, msg.value);
}
// Triggered for non-existent function calls or data sent
fallback() external payable {
emit Received(msg.sender, msg.value);
}
}
Continue Learning
Explore more topics in Solidity or browse other tutorials.