0

If it is not possible to over/underflow in this transfer due to a check at the mint function, then why are these 2 lines (236/237) not within the unchecked field?

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L236

4
  • What do you mean with "a check at the mint function"? Usually amount is user supplied so it could be an invalid amount.
    – Ismael
    Oct 19, 2022 at 23:42
  • It can't be invalid because it's passed as a uint256. Try passing an overflow value in remix. You will get "value out-of-bounds" if it's wrapped with unchecked or not.
    – Nat
    Oct 19, 2022 at 23:52
  • You cannot transfer more than existing balance, so a check is needed. If the existing balance is 10 you cannot transfer 12.
    – Ismael
    Oct 20, 2022 at 1:49
  • Yes but there is no chance of over/under flow in those 2 lines. The uint256 is checked as it is passed to the function so it cannot over/underflow. So this doesn't explain why it needs to be outside the unchecked statement. To your example, if you're dealing with a uint8 let's say you cannot pass 256 as you will get the error above, nor could you pass the same max for uint256. So you cannot pass the 12 and even if you did it would still assert. Unchecked simply forgoes over/underflow check to save gas.
    – Nat
    Oct 20, 2022 at 16:01

1 Answer 1

1

Those two lines do not perform an arithmetic operation, so moving them inside the unchecked block doesn't provide any benefit. Perhaps it will make the code a little harder to read:

    uint256 fromBalance = _balances[from];
    require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
    unchecked {
        _balances[from] = fromBalance - amount;
        // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
        // decrementing then incrementing.
        _balances[to] += amount;
    }
1
  • Yup you're right, I tried this in remix, the gas is exactly the same inside or outside.
    – Nat
    Oct 20, 2022 at 21:27

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.