Use WETH gas optimization for ERC-20 transferFrom
🧐 Motivation
The Wrapped Ether (WETH) ERC-20 contract has a gas optimization that does not update the allowance if it is the max uint. I'd like to incorporate this into OpenZeppelin to save 5000 gas per transferFrom call when a max approve is used.
📝 Details
The transferFrom code for WETH is:
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
The key line is if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {. If the allowance is the max uint (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff), then the WETH contract does not update the allowance mapping. This saves 5000 gas for the SSTORE. The only downside is that this changes the abstraction for approvals; if you set the approval to the maximum amount, then the contract can spend more than the max uint of your token. However, this doesn't seem like a risk, as users wanting to actually specify that amount can simply do the max uint minus 1.
My proposed change is to incorporate this into . This could save 5000 gas (or 10-20%) per ERC-20 transferFrom, which is used all across Unsiwap, Compound, and other big protocols.