Skip to content

Instantly share code, notes, and snippets.

@MiloTruck
Created May 30, 2022 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiloTruck/6fe0a13c4d08689b8be8a55b9b14e7e1 to your computer and use it in GitHub Desktop.
Save MiloTruck/6fe0a13c4d08689b8be8a55b9b14e7e1 to your computer and use it in GitHub Desktop.
MockERC20 token that implements fee-on transfer.
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "solmate/tokens/ERC20.sol";
contract MockERC20Fee is ERC20 {
// 2% fee for all transfers
uint256 internal feeRate = (2 / 100) * 1 ether;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) ERC20(name_, symbol_, decimals_) {}
// Expose external mint function
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
function transfer(address to, uint256 amount) public override returns (bool) {
balanceOf[msg.sender] -= amount;
uint256 fee = (amount * feeRate) / 1 ether;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount - fee;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
uint256 fee = (amount * feeRate) / 1 ether;
unchecked {
balanceOf[to] += amount - fee;
}
emit Transfer(from, to, amount);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment