I'm reading ERC20.sol source code. There's a question about the approve function.
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
In the function, it requires owner != address(0) and spender != address(0). I just wonder should we do the amount check in the function? Such as:
require(amount <= _balances[owner]);
Thanks.
should we do the amount check in the function?
Nope. Approve function only lets a third-party spender use your tokens on your behalf. You just allow someone or a smart contract to spend your ERC20 tokens. This does not mean that they can spend unlimited tokens.
Let's say that you let a Smart Contract spend 1000 of an ERC20 token. That smart contract will be able to spend, from your balance, on your behalf, up to 1000 tokens. But only if you have enough balance to make the transaction. So the allowed Smart Contract can call the transferFrom method, and send your tokens to another wallet only if you have enough balance and if the Smart Contract is allowed to spend enough tokens.
So no, you do not have to check if the wallet has enough balance at the moment of approval because the condition is only needed when transferring tokens.
Hope this info is useful :)