Solidity, the programming language for Ethereum smart contracts, offers three primary methods to send Ether: transfer, send, and call. This guide explores their differences, use cases, and best practices for secure transactions.
Key Methods for Sending Ether
1. transfer
- Gas Limit: 2300 units
- Behavior: Reverts transaction on failure
- Use Case: Simple transfers where fixed gas suffices
👉 Learn more about gas optimization
2. send
- Gas Limit: 2300 units
- Behavior: Returns
falseon failure - Use Case: Scenarios requiring manual failure handling
3. call
- Flexibility: Customizable gas
- Behavior: Returns success status and data
- Use Case: Complex interactions (recommended post-Solidity 0.6.0)
Code Examples
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract SendEther {
function sendViaTransfer(address payable _to) public payable {
_to.transfer(msg.value);
}
function sendViaSend(address payable _to) public payable {
bool sent = _to.send(msg.value);
require(sent, "Failed to send Ether");
}
function sendViaCall(address payable _to) public payable {
(bool sent, bytes memory data) = _to.call{value: msg.value}("");
require(sent, "Failed to send Ether");
}
}Receiving Ether
Contracts must implement:
receive(): For plain Ether transfersfallback(): For calls with data/no matching function
contract ReceiveEther {
receive() external payable {}
fallback() external payable {}
}Error Handling
| Function | Purpose | Reverts? |
|---|---|---|
require | Validate conditions | Yes |
assert | Test internal errors | Yes |
revert | Custom error messages | Yes |
Security Best Practices
Reentrancy Protection
- Change state before external calls
- Use reentrancy guard modifiers
Gas Limits
- Avoid fixed gas (
transfer/send) for complex fallbacks
- Avoid fixed gas (
Validation
- Always check
call/sendreturn values
- Always check
👉 Explore advanced security techniques
FAQ
Q: Which method is safest for sending Ether?
A: call (with reentrancy guards) is recommended due to gas flexibility and explicit return handling.
Q: Why did transfer become less safe?
A: Its 2300 gas limit may fail if receivers require more gas, leading to stuck funds.
Q: How does receive differ from fallback?
A: receive handles plain Ether transfers; fallback processes calls with data or unknown functions.
Q: Can a contract without receive or fallback get Ether?
A: No—such contracts reject regular Ether transfers.
Conclusion
Mastering Ether transfer methods is critical for Solidity developers. Prioritize call with robust error handling and reentrancy protection for secure contracts. Always test gas requirements and failure scenarios comprehensively.
For further reading, explore our guides on Solidity functions and security patterns.