在solidity智能合约中管理天然气费用



我有一个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);
}

我在transfer函数中添加了if语句,以防用户在部署前指示每个事务的限额。我想知道这是否会影响转让代币时的汽油费,以便决定是否离开";通用的";ERC20智能合约模板,具有可指示的交易限额,或者如果没有指示交易限额,则编写新的模板,不包含if语句。

我想知道在转移代币时这是否会影响天然气费用

添加(ifrequire(条件会增加所使用的气体总量,但在父transfer()函数的其他操作的气体使用情况下,增加幅度很小。这是因为在覆盖函数中;只是";在存储器中再进行一次存储读取和少量其他操作。

执行transfer()函数需要花费54620天然气(包括父函数;假设require()条件没有失败(。而仅执行父CCD_ 10函数就要花费52320气体。


如果要调用父transfer()函数,则需要使用super.transfer(recipient, amount);。如果没有super关键字,您将在无限递归中锁定脚本,始终调用它自己。

此外,为了正确地覆盖父函数,您需要在public可见性修改器之前声明override修改器(如果您也计划覆盖此函数,则声明virtual(,并返回声明的值。

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

Petr Hejda建议的一切都是正确的。这里的额外改进是使require语句失败原因字符串更小、更精确,因为这将导致字节码更小,因此部署成本更低。

最新更新