Modify ERC20 contract to collect a fee

My goal is to collect a 1% fee of custom ERC20 being transferred for each transfer.

I’m currently using the ERC20PresetMinterPauser.sol contract and have modified the ERC20.sol that is imported.

Specifically, I’ve modified the _transfer function in ERC20.sol and calculate the fee and attempt to transfer the fee there.

My tests transfer the full amount sent. Fee deduction and transfer do not happen.

My code for the _transfer function is below. I’m using Remix and deploying on Ropsten. Thanks for looking!

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");

    require(amount%100 == 0);
    uint256 fee = amount/100; // for 1% fee
    
    address feerecipient = 0x3007D804B9EA75e6e2A7D00c97E4A8941a8DC746;
    require(feerecipient != address(0), "ERC20: transfer to the zero address");

    _beforeTokenTransfer(sender, recipient, amount);
    
    uint256 senderBalance = _balances[sender];
    require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
    _balances[sender] = senderBalance - amount;
    uint256 amountnew = amount - fee;
    _balances[recipient] += (amountnew);
    
    if (fee>0) {
    _balances[feerecipient] += (fee);
    emit Transfer(sender, feerecipient, fee);
    }
    
    emit Transfer(sender, recipient, amountnew);
}

Hello @voldeckm welcome to the OpenZeppelin community, feel free to Introduce yourself here!

I suggest you check out Create deflationary ERC20 token
and How would I create a function where 3% of transactions gets sent to an address I assign?.