0

I was wondering how if(currentAllowance != type(uint256).max) worked in the following function from OpenZeppelin's ERC-20 template. I understand the purpose of this line -- to make sure there's no overflow from an allowance that exceeds the size of the number contained within uint256. I also read that type is a built-in solidity function that returns the unique ID of the interface but still have a few questions:

  1. Why is max being called on the unique ID of the interface?
  2. Where is the max function coming from -- I can't find it in either the solidity or ethers documentation.
  3. Why is this check needed? I thought after Solidity version 0.8.0 the compiler now checks for under/overflow?
  4. Why is type is being called on uint256 -- isn't this a variable type not an interface?

Thanks.

 function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

1 Answer 1

3

You are misunderstanding the purpose of that line since it is not there to protect against overflow. Overflow protection is default behaviour since 0.8.0 compiler. Some users provide protocols they trust a so-called infinite approval so they don't have to constantly sign approval transactions. This is usually implemented by setting the approval amount to the max value of uint256. OZ's contract is just checking whether user has provided infinite approval to the msg.sender, in which case it will skip the update of "remaining approval balance" to optimise gas.

See types in the documentation: https://docs.soliditylang.org/en/v0.8.11/types.html

Interface ID is a separate topic introduced in ERC165

1
  • Thanks, I saw an example using type(interface) and got confused
    – J. Doe
    Aug 29, 2022 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.