receiving Ether
receive() external payable -> triggered when contract receives ETH with empty msg.data
fallback() external payable -> runs when no function matches, or receives plain ETH without receive.
sending ether
.transfer() / send() -> (⚠️not recommended): only forwards 2300 gas, may fail.
.call{value: amount}("") (✅ recommended):forwards all gas, more flexible, Must check success.
security pattern
checks-effects-interactions:
- check -> validate conditions
- effects -> update internal state
- interactions -> finally transfer Ether
mapping(address => uint) public balances
function withdraw(uint amount) public {
//1.Checks
require(balances[msg.sender] >= amount, "Insufficient balance")
//2. Effects
balances[msg.sender] -= amount
//3. interactions
(bool sent, ) = msg.sender.call{value: amount}("");
require(sent, "failed to send Ether.")
}
Top comments (0)