Consider the following Solidity contract snippet. What happens when sendEther is called with 1 ether?
pragma solidity ^0.8.0;
contract TransferExample {
event Sent(address to, uint amount);
function sendEther(address payable recipient) public payable {
recipient.transfer(msg.value);
emit Sent(recipient, msg.value);
}
}Recall that transfer forwards a fixed gas stipend of 2300 gas.
The transfer method forwards exactly 2300 gas to the recipient. If the recipient's fallback or receive function requires more gas, the transaction reverts.
Given this contract snippet, what is the value of success after calling sendEther?
pragma solidity ^0.8.0; contract SendExample { function sendEther(address payable recipient) public payable returns (bool) { bool success = recipient.send(msg.value); return success; } }
Remember that send returns a boolean indicating success or failure.
The send method returns true if the Ether transfer succeeded, otherwise false. It does not revert on failure.
Analyze the following contract. What does the sendViaCall function return when called with 1 ether?
pragma solidity ^0.8.0; contract CallExample { event Sent(address to, uint amount, bool success); function sendViaCall(address payable recipient) public payable returns (bool) { (bool success, ) = recipient.call{value: msg.value}(""); emit Sent(recipient, msg.value, success); return success; } }
Recall that call returns a boolean success and forwards all remaining gas by default.
The call method returns a boolean indicating success or failure. It forwards all gas by default, so it does not revert due to gas stipend limits like transfer.
Choose the option that best explains the key difference between transfer, send, and call when sending Ether in Solidity.
Think about gas forwarding and error handling differences.
transfer and send forward a fixed 2300 gas stipend. transfer reverts on failure, send returns false. call forwards all remaining gas and returns a boolean success status.
Consider this contract snippet. The sendViaCall function returns false unexpectedly when sending Ether to a contract with a fallback function that uses more than 2300 gas. Why?
pragma solidity ^0.8.0; contract Receiver { fallback() external payable { // Uses more than 2300 gas for (uint i = 0; i < 1000; i++) {} } } contract Sender { function sendViaCall(address payable recipient) public payable returns (bool) { (bool success, ) = recipient.call{value: msg.value, gas: 2300}(""); return success; } }
Check the gas parameter in the call and the fallback function's gas usage.
The call explicitly sets gas to 2300, which is the minimum stipend. The fallback function uses more gas, so it runs out of gas and the call returns false.