I have a ERC20 smart contract with edited transfer
function
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if(_transactionMaxValue > 0){
require(_transactionMaxValue >= amount, "You can not transfer more than 1000000 tokens at once!");
}
transfer(recipient, amount);
}
I have added if
statement in transfer
function, in case user indicates limit per single transaction before deploying. I was wondering if this would affect gas fees when transferring tokens, in order to decide weather to leave the "universal" ERC20 smart contract template with indictable transaction limit or compose new one, with no if
statement, if no transaction limit was indicated.
I was wondering if this would affect gas fees when transferring tokens
Adding the (if
and require
) conditions increases the total amount of gas used, but the increase is small in the context of gas usage of other operations of the parent transfer()
function. It's because in the overriding function, you're performing "just" one more storage read and few other operations in memory.
Execution of your transfer()
function costs 54,620 gas (including the parent function; assuming the require()
condition doesn't fail). While execution of just the parent transfer()
function costs 52,320 gas.
You need to use super.transfer(recipient, amount);
if you want to invoke the parent transfer()
function. Without the super
keyword, you'd lock the script in an infinite recursion, always invoking itself.
Also, in order to correctly override the parent function, you need to state the override
modifier (and virtual
if you are planning to override this function as well) before the public
visibility modifier, and to return the value as declared.
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
uint256 _transactionMaxValue = 1000000;
constructor() ERC20("MyToken", "MyT") {
_mint(msg.sender, 1000000);
}
// moved the `override virtual` before the `public` modifier
function transfer(address recipient, uint256 amount) override virtual public returns (bool) {
if(_transactionMaxValue > 0){
require(_transactionMaxValue >= amount, "You can not transfer more than 1000000 tokens at once!");
}
// added `return super.`
return super.transfer(recipient, amount);
}
}