我有一个带有编辑过的ERC20函数的transfer智能契约
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);
}我在if函数中添加了transfer语句,以防用户在部署之前指示每个事务的限制。我想知道,在转让令牌时,这是否会影响煤气费,以便决定是否保留带有可起诉事务限制的“通用”ERC20智能合同模板,或者编写新的模板,如果没有指示事务限制,则不使用if语句。
发布于 2021-12-14 10:48:36
我想知道这是否会影响转让代币时的煤气费
添加(if和require)条件会增加所用气体的总量,但在父transfer()函数的其他操作的气体使用情况下,增加的幅度较小。这是因为在覆盖函数中,您只需要再执行一次存储读取,在内存中执行很少的其他操作。
执行transfer()函数需要花费54 620个gas (包括父函数;假设require()条件没有失败)。而仅执行父transfer()函数的代价是52,320 gas。
如果要调用父super.transfer(recipient, amount);函数,则需要使用transfer()。如果没有super关键字,就会将脚本锁定为无限递归,始终调用自身。
此外,为了正确地重写父函数,需要在override可见修饰符之前声明public修饰符(如果也打算重写该函数,则需要声明public修饰符),并返回声明的值。
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);
}
}发布于 2021-12-15 09:01:27
Petr Hejda建议的一切都是正确的。这里的其他改进是使require语句失败原因字符串更小、更精确,因为它将导致字节码更小,从而降低部署成本。
https://stackoverflow.com/questions/70345373
复制相似问题