3

Here is the first example token.

pragma solidity ^0.4.20;

contract MyToken {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function MyToken(
        uint256 initialSupply
        ) public {
        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) public {
        require(balanceOf[msg.sender] >= _value);           // Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
        balanceOf[msg.sender] -= _value;                    // Subtract from the sender
        balanceOf[_to] += _value;                           // Add the same to the recipient
    }
}

I don't understand this line code:

require(balanceOf[_to] + _value >= balanceOf[_to]);

Because _value is an unint, why do we need to check if the final amount of recipient is greater than or equal to the previous amount? I see that this line of code always returns true, I do believe I miss something here. If you know why we need to check this, please let me know. Thanks!

1

I see that this line of code always returns true

No, This is true unless it overflows. When unit overflow happens that's false. Here the unit used unit256 will have a max value of 2**256-1.

This gist shows example of unit overflow and underflow.

/* demonstrating uint overflow and underflow in ethereum solidity
   this is why you need guards like: 
     if (balances[_to] + _amount < balances[_to]) throw; 
*/ 
contract C {
    // (2**256 - 1) + 1 = 0
    function overflow() returns (uint256 _overflow) {
        uint256 max = 2**256 - 1;
        return max + 1;
    }

    // 0 - 1 = 2**256 - 1
    function underflow() returns (uint256 _underflow) {
        uint256 min = 0;
        return min - 1;
    }
}

So this check is required.

| improve this answer | |

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.