Consider the following Solidity contract that can receive Ether. What will be the value of received after sending 1 Ether?
pragma solidity ^0.8.0; contract Receiver { uint public received = 0; receive() external payable { received = msg.value; } }
The receive() function is called when Ether is sent without data. msg.value holds the amount of Ether sent in wei.
The receive() function updates received with msg.value, which is the amount of Ether sent in wei. Sending 1 Ether means msg.value is 1000000000000000000 wei.
Given this contract, what happens when it receives Ether?
pragma solidity ^0.8.0; contract NoReceive { uint public balance = 0; }
Contracts without receive() or payable fallback() cannot accept plain Ether transfers.
Without a receive() or payable fallback(), the contract cannot accept Ether sent without data, so the transaction reverts.
Examine the contract below. It is supposed to receive Ether and update receivedAmount. Why does sending Ether fail?
pragma solidity ^0.8.0;
contract ReceiverFail {
uint public receivedAmount;
fallback() external {
receivedAmount = msg.value;
}
}To accept Ether, fallback or receive functions must be marked payable.
The fallback function is missing the payable keyword, so it cannot accept Ether and the transaction reverts.
What is wrong with this receive function code?
receive() external {
// receive Ether
}Receive functions must be able to accept Ether.
Receive functions must be declared payable to accept Ether transfers. Missing payable causes a syntax error.
Consider this contract deployed on Ethereum. A user sends 0.5 Ether twice in separate transactions. How many times is the receive() function called?
pragma solidity ^0.8.0; contract MultiReceive { uint public count = 0; receive() external payable { count++; } }
The receive() function is triggered every time Ether is sent without data.
Each Ether transfer triggers the receive() function, so sending Ether twice calls it twice, incrementing count twice.