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?

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.

  • use as little gas as possible. +1 – user10375 Dec 28 '17 at 2:01
1

_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.

  • balances[_to] + _amount > balances[_to] already can handle this 0-value scenario. _amount > 0 is not necessary and adds gas costs. Agree? – user10375 Dec 28 '17 at 1:58
  • You are right, my bad. – pabloruiz55 Dec 28 '17 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.