Skip to content

Instantly share code, notes, and snippets.

@samlaf
Last active March 11, 2022 21:07
Show Gist options
  • Save samlaf/fb9cf0e2001d30fc2a14715201723601 to your computer and use it in GitHub Desktop.
Save samlaf/fb9cf0e2001d30fc2a14715201723601 to your computer and use it in GitHub Desktop.
Sending Ether (transfer, send, call)
// In https://solidity-by-example.org/sending-ether/
// They say: call in combination with re-entrancy guard is the recommended method to use after December 2019.
// (see https://consensys.github.io/smart-contract-best-practices/recommendations/#dont-use-transfer-or-send for an explanation)
// and compare the gas fees of the 3 methods:
// transfer (2300 gas, throws error)
// send (2300 gas, returns bool)
// call (forward all gas or set gas, returns bool)
// I tested all 3 methods, by sending 10 eth to a contract and then withdrawing using these functions:
// total gas used: 28098
function withdrawWithTransfer() public {
payable(msg.sender).transfer(address(this).balance);
}
// total gas used: 28081
function withdrawWithSend() public {
bool sent = payable(msg.sender).send(address(this).balance);
require(sent, "Failed to send Ether");
}
// total gas used: 28171
function withdrawWithCall() public {
(bool sent,) = payable(msg.sender).call{value: address(this).balance}("");
require(sent, "Failed to send Ether");
}
// Conclusion
// They are all similar in gas fees. call is actually the most expensive one, but not by a lot.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment