DEV Community

Loading Blocks
Loading Blocks

Posted on

Sending & Receiving Ether

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:

  1. check -> validate conditions
  2. effects -> update internal state
  3. 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.")

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)