gpt4 book ai didi

ethereum - 使用unchecked有什么好处?

转载 作者:行者123 更新时间:2023-12-05 02:33:30 26 4
gpt4 key购买 nike

在OpenZeppelin ERC20实现中,有一个_transfer方法:

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

_beforeTokenTransfer(sender, recipient, amount);

uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;

emit Transfer(sender, recipient, amount);

_afterTokenTransfer(sender, recipient, amount);
}

为什么他们使用未经检查的算法来减少余额?我知道如果未选中,2-3 将返回 2**256-1 并且不会出现异常。但为什么我们需要这个?

最佳答案

unchecked 与常规算术运算相比生成更小的字节码,因为它不包含下溢/溢出验证。

因此,如果您想在发生溢出时自定义错误消息,则此代码的运行成本会更低

uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {

// no validation here as it's already validated in the `require()` condition
_balances[sender] = senderBalance - amount;
}

与这个相比

uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");

// redundant validation here
_balances[sender] = senderBalance - amount;

如果没有自定义消息,这将是最便宜但仍然安全的选项:

// contains the check and fails without custom message in case of underflow
_balances[sender] -= amount;

与上一个相比,这会更便宜。但它不安全,因为它不检查 undeflow:

unchecked {
// UNSAFE, DO NOT USE
_balances[sender] -= amount;
}

关于ethereum - 使用unchecked有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70986854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com