openzeppelin-contracts icon indicating copy to clipboard operation
openzeppelin-contracts copied to clipboard

ERC20: Optimize Gas Usage for _spendAllowance

Open XZSt4nce opened this issue 1 year ago • 1 comments

🧐 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);
        }
    }
}

XZSt4nce avatar Oct 12 '24 06:10 XZSt4nce

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.

etherbiln avatar Oct 14 '24 11:10 etherbiln