Introduction to ETH Transactions in Solidity
Solidity, Ethereum's programming language, enables smart contracts to handle Ether (ETH) transactions seamlessly. This guide explores foundational concepts for paying ETH to contracts and sending ETH from contracts using payable functions and transfer methods.
1. Contract Receiving ETH
To accept ETH payments, a contract must use the payable keyword:
pragma solidity >=0.7.0 <0.9.0;
contract Payable {
address payable public owner; // Payable address can send/receive ETH
constructor() {
owner = payable(msg.sender);
}
// Payable function accepts ETH deposits
function deposit() external payable {}
function getBalance() external view returns (uint) {
return address(this).balance;
}
}Key Features:
payablemodifier: Allows functions/addresses to process ETH.address(this).balance: Retrieves contract's ETH balance.
👉 Learn advanced Solidity techniques
2. Contract Sending ETH
Solidity offers three methods to send ETH:
Method 1: transfer()
- Gas: 2300 (fixed)
- Behavior: Reverts on failure.
_to.transfer(123);Method 2: send()
- Gas: 2300 (fixed)
- Returns:
boolindicating success.
bool sent = _to.send(123);
require(sent, "Send failed");Method 3: call()
- Gas: All remaining gas.
- Returns:
(bool success, bytes memory data).
(bool success, ) = _to.call{value: 123}("");
require(success, "Call failed");Example: ETH Receiver Contract
contract EthReceiver {
event Log(uint amount, uint gas);
receive() external payable {
emit Log(msg.value, gasleft());
}
}Comparison of ETH Transfer Methods
| Method | Gas Limit | Reverts on Failure? | Returns Data |
|---|---|---|---|
transfer | 2300 | Yes | No |
send | 2300 | No (check bool) | No |
call | All gas | No (check bool) | Yes (bytes data) |
Best Practices for ETH Transactions
- Security: Use
callwith checks for reentrancy attacks. - Gas Efficiency: Prefer
transferfor fixed costs. - Fallback Functions: Implement
receive()to handle incoming ETH.
👉 Explore secure smart contract patterns
FAQs
Q1: Why does transfer revert on failure?
A: It ensures atomicity—either the full amount is sent or the transaction is canceled.
Q2: When should I use send() over transfer?
A: Rarely. send requires manual checks, while transfer automates failure handling.
Q3: Is call unsafe?
A: It can be vulnerable to reentrancy if not properly secured (e.g., using checks-effects-interactions).
Conclusion
Mastering ETH transactions in Solidity involves understanding payable addresses, gas costs, and transfer methods. Choose transfer for simplicity, call for flexibility, and always prioritize security audits.