Why Yet Check User Balance For ERC20 Transfer

hi guys
i was free and check openzepplin erc20 solidity 0.8.0 version

    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, amount);

my question is why openzepplin erc20 check amount overflow also why use unchecked{} when solidity 0.8.0 dont have overflow,underflow problems does't this checks just increase gas usage?

1 Like

no one have answer for this question?

Hi, I am not sure for this, I have reminded the team member to have a look, they have something else to do, maybe later, they will answer this question.

Somebody built a "modern" version of ERC20 contract with no require statement here. Not sure about the security though.

My assumption is the following:

The require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); provides more information on why the transaction failed than a overflow/underflow error. Decrementing the balance inside an unchecked block is meant for gas savings. The check is already done on the require

1 Like

Yes as @helio.rosa said we have this require to provide a better error message, and we use unchecked because the compiler's overflow checking would be redundant.

1 Like