Skip to main content

Gas-Efficient Ether Transfer With Call

Description

In Solidity, transferring ether from one contract to another can be done using several different methods, including call, send, and transfer. While all three methods can be used to transfer ether, using call is generally the most gas-efficient option, especially when transferring ether to a contract that may perform complex operations during the transaction.

The call method allows for more customization of the transaction, including specifying gas limits and return values. This can result in lower gas costs, as the transaction can be tailored to only use the gas needed to complete the intended operation.

Example Code

Before:

function withdraw() public {
msg.sender.transfer(address(this).balance);
}

After:

function withdraw() public {
(bool success,) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}

Recommendation

It is recommended to use call instead of send or transfer when transferring Ether. Additionally, be aware of any potential re-entrancy vulnerabilities when interacting with other contracts that may have a fallback function.