Question about the design of ERC20 transferFrom function

In the OpenZeppelin ERC20 contract, the code is written in such a way that user must manually approve spenders to spend their tokens on the user's behalf.

This allowance is then checked when a transfer is made:

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;

However, the way it's currently written requires the user to approve themselves if they want to transfer their own tokens. Why is it written this way? Wouldn't a simple check for from == spender and then skipping _spendAllowance suffice?

Hey @greentriangles1
why a user should use transferFrom instead of transfer to send tokens by his own?

transferFrom usually is necessary only if it is called by someone different from the owner

Sure, transfer makes more sense, but the same logic still occurs

Are you sure? Please show where

User or EOA can directly call transfer() to transfer funds.
Approve and transferFrom are required when a smart contract needs to transfer funds on behalf of user.

There may be some confusion here because for ERC721 and ERC1155 all transfers are done through transferFrom, including user-initiated transfers. In ERC20 they are separate: transfer and transferFrom.

1 Like