Solidity – Use of Body-Less ‘_beforeTokenTransfer’ Internal Virtual Function in ERC-20

erc-20solidity

Inside _transfer function there is a call goes to _beforeTokenTransfer(sender, recipient, amount); and that function is written as function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } with no body parts, then is is not useless ? or if it is useful what is purpose of calling a body less inter virtual function ?

Best Answer

Functionally, yes, it is useless since it doesn't do anything. But it does serve a purpose.

OpenZeppelin's architecture is such that you can easily plug in extra functionality. You are never meant to edit their templates, but only extend them. So, if you want to add your custom functionality to function _beforeTokenTransfer, you can override the function in a sub-contract and add whatever functionality you need. This way there's no need to modify the original OZ contract.

For example a contract:

contract MyToken is ERC20 {
    constructor(uint initialSupply, string memory name, string memory symbol) 
      ERC20(name, symbol) public {
          _mint(msg.sender, initialSupply);
    }

    function _beforeTokenTransfer(address from, address to, uint256 amount) 
        internal override {
        // do something, for example emit an event or check some conditions to make sure the transfer can be allowed. If not allowed, revert the transaction
    }
}
Related Topic