0

Ethereum wiki shows this example function:

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     }

Notice that there are two checks here: _amount > 0 and balances[_to] + _amount > balances[_to]. I understand these two are for preventing the integer overflow attack.

But isn't the balances[_to] + _amount > balances[_to] check enough? Can we remove the _amount > 0 check?

user10375
  • 177
  • 1
  • 6

2 Answers2

2

_amount > 0 is there to prevent people from transferring 0 tokens. If you take it out, a function call with 0 tokens will not fail but not do anything, except consuming all the gas provided and used as well as firing an event (if you had it) recording a Transfer of 0 tokens.

pabloruiz55
  • 7,686
  • 2
  • 17
  • 38
2

You are correct, it is not necessary. If you're worried about a spam of meaningless transfer events, it doesn't help at all because someone can just transfer 0.000000001 tokens many times.

Returning false on a transfer of 0 tokens is a very bad idea. One of the most important features of the EVM is that contracts can call functions in other contracts. If a contract calls transfer on a token contract with a dynamically calculated amount of tokens, it might sometimes transfer 0. If the token contract then returns false, the calling contract will think the transfer failed, even though nothing was wrong.

I would do this:

function transfer(address _to, uint256 _amount) returns (bool success) {
    if (_amount == 0) return true;
    // Rest of the transfer function...

That way transfer calls with _amount == 0 will succeed, and use as little gas as possible.

Jesbus
  • 10,478
  • 6
  • 35
  • 62