Currently, I am planning to implement an ERC20 compliant transfer function in my ERC20 compliant contract as follows:
function transfer(address _to, uint256 _amount) public returns (bool success)
{
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to])
{
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
I would prefer to use "require" for the if block and not use the else, but then if it's false, I don't see how I'd then return a false. It would return an error or exception - correct?
Perhaps that would be the preferred behavior, but is it OK that a "false" does not get returned by the function when the require logic is not met?
I've also asked two instructors on Udemy, and I do believe that either of their answers would work, but their answers were different. Thus, it seems an important question to have discussed on record for our community.
I also plan to add openzepplin's safe math library functions as needed.
_amount == 0
. In fact, it is counterproductive. Consider the case where a contract wants to transfer a varying amount of tokens. Its calculation might end up with 0. There's nothing inherently wrong with that, so there's no reason to make a calling contract think the transfer failed. Throwing on 0 is a common anti-pattern in Solidity development which hurts the equal treatment of contracts and humans.