openzeppelin-contracts
openzeppelin-contracts copied to clipboard
ERC20: Optimize Gas Usage for _spendAllowance
🧐 Motivation With a maximum value of type uint256, a non-optimal comparison operator is used.
📝 Details No number can be greater than the maximum value of type uint256 so NOT EQUAL can be replaced by LESS-THAN. LESS-THAN (LT => one instruction) will be cheaper than NOT EQUAL (NOT+EQ => 2 instructions):
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
You're right, using the < (less-than) operator instead of the != operator in Solidity can optimize gas costs. Since the maximum value of uint256 is known and constant (type(uint256).max), we can utilize this information to make the logic of your smart contract more efficient.