Implementation details of _beforeTokenTransfer

I’m implementing _beforeTokenTransfer in a derived contract from ERC1155 spec and curious about the call to the parents beforeTokenTransfer i see in most examples:

function _beforeTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal override {
    // wondering about this
    super._beforeTokenTransfer(operator, from, to, ids, amounts, data); 

    // logic goes here
}

Is there a need to call super._beforeTokenTransfer() at the start of the function considering the parent contracts function is empty ?

1 Like

Ive since loaded up a ERC721 contract in Remix to test how _beforeTokenTransfer is actually working and there seems to be no difference between these two implementations:

bool public flag = false;

function _beforeTokenTransfer(address from, address to, uint256 tokenId)
    internal
    override(ERC721, ERC721Enumerable)
{
    super._beforeTokenTransfer(from, to, tokenId);
    flag = true;
    
}

and this

bool public flag = false;

function _beforeTokenTransfer(address, address, uint256)
    internal
    override(ERC721, ERC721Enumerable)
{
    flag = true;
}

In both cases after a mint/transfer the flag gets set to true. So im left wondering is there some other reasons for implementing the first way?

1 Like

Hi @dylkil,

The recommendation is to:

Always call the parent’s hook in your override using super . This will make sure all hooks in the inheritance tree are called: contracts like ERC20Pausable rely on this behavior.

From: https://docs.openzeppelin.com/contracts/4.x/extending-contracts#rules_of_hooks

We need to to this whenever we use extensions that add behavior also using hooks.

You can use the Contracts Wizard to experiment with different features: https://docs.openzeppelin.com/contracts/4.x/wizard

Ok makes sense, I was confused as I had not come across any openzepplin contracts which had an implementation for _beforeTokenTransfer() but i had not seen ERC20Pausable.

I took a look at it this morning its fantastic

Thanks, @abcoathup

1 Like