Payable, receive & fallback (ETH flows)
Receive ETH via payable functions and the receive/fallback hooks.
Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract EthVault {
receive() external payable {
// called on plain ETH transfer (no calldata)
}
fallback() external payable {
// called when no function signature matches
}
function deposit() external payable {
require(msg.value > 0, "send eth");
}
function withdraw(uint256 amount) external {
payable(msg.sender).transfer(amount); // 2300 gas stub, reverts on failure
}
function withdrawCall(uint256 amount) external {
(bool ok, ) = payable(msg.sender).call{value: amount}("");
require(ok, "transfer failed");
}
function balance() external view returns (uint256) {
return address(this).balance;
}
}Explanation
payable marks functions that accept ETH; msg.value is in wei (1 ETH = 1e18 wei). receive() triggers on empty-calldata ETH transfers; fallback() triggers on unknown function signatures or non-empty calldata transfers. transfer/send forward only 2300 gas (a stub) and revert on failure — safe against reentrancy but breaks with gas-consuming recipients. call{value:...} forwards all gas and returns a bool; always check the return value. Prefer call for withdrawals and guard reentrancy with a mutex.
More Solidity Snippets
Contract Basics
Define a basic smart contract with state and functions.
Functions and Visibility
Function visibility, payable, and return values.
Modifiers and Access Control
Reuse validation logic with modifiers.
Events and Logs
Emit events for off-chain listeners.
Mappings, Structs & Nested Storage
Group related data with structs and look it up by key with mappings.
Inheritance, Abstract & Interfaces
Reuse logic via inheritance; define contracts with abstract and interface.