伊瑟姆维基展示了这个示例函数:
14 // Transfer the balance from owner's account to another account
15 function transfer(address _to, uint256 _amount) returns (bool success) {
16 if (balances[msg.sender] >= _amount
17 && _amount > 0
18 && balances[_to] + _amount > balances[_to]) {
19 balances[msg.sender] -= _amount;
20 balances[_to] += _amount;
21 return true;
22 } else {
23 return false;
24 }
25 }注意,这里有两个检查:_amount > 0和balances[_to] + _amount > balances[_to]。我知道这两件事都是为了防止整数溢出攻击。
但是balances[_to] + _amount > balances[_to]检查还不够吗?我们能移除_amount > 0检查吗?
发布于 2017-12-27 15:38:47
你说得对,没有必要。如果您担心垃圾邮件中的无意义的传输事件,这一点都没有用,因为有人可以多次传输0.000000001令牌。
在0标记的传输上返回false是一个非常糟糕的主意。EVM最重要的特性之一是契约可以调用其他契约中的函数。如果一个契约使用动态计算出的令牌数量调用令牌契约上的transfer,它有时可能会传输0。如果令牌契约然后返回false,则调用合同将认为传输失败,即使没有任何错误。
我会这么做:
function transfer(address _to, uint256 _amount) returns (bool success) {
if (_amount == 0) return true;
// Rest of the transfer function...这样,transfer与_amount == 0的调用就会成功,并且使用尽可能少的气体。
发布于 2017-12-27 13:40:31
_amount > 0的存在是为了防止人们传输0令牌。如果您取出它,带有0标记的函数调用将不会失败,但不会做任何事情,除了消耗所提供和使用的所有气体,以及触发一个事件(如果有),记录0令牌的传输。
https://ethereum.stackexchange.com/questions/34507
复制相似问题