Search code examples
functiontokenblockchainsoliditypragma

can anyone explain me this assert condition?


i would like to understand this assert condition in function send token.....i think the first assert for before adding tokenbalance is always gather then the up coming token but I don't sure about it....?

pragma solidity ^0.5.11;
contract EventExample {

 mapping(address => uint) public tokenBalance;

 event TokensSent(address _from, address _to, uint _amount);

 constructor() public {
 tokenBalance[msg.sender] = 100;
 }

 function sendToken(address _to, uint _amount) public returns(bool) {
 require(tokenBalance[msg.sender] >= _amount, "Not enough tokens");
 assert(tokenBalance[_to] + _amount >= tokenBalance[_to]);
 assert(tokenBalance[msg.sender] - _amount <= tokenBalance[msg.sender])
;
 tokenBalance[msg.sender] -= _amount;
 tokenBalance[_to] += _amount;

 emit TokensSent(msg.sender, _to, _amount);

 return true;
 }

}

Solution

  • These two assert conditions provide a way to prevent integer overflow and underflow.

    The max value of uint256 is 2^256-1, which is approx. 10^77. If you want to add two numbers that would result in a value larger that the max value, it would overflow the integer.


    Example with smaller values so it's easier to imagine:

    Largest value of uint8 is 255. So if you have a value 250 and you want to add 10, it overflows the max value, and becomes 4 (because 255 + 1 equals 0 in case of uint8).

    The same goes the other way around. You have a value 5 and want to subtract 10. Since it's an unsigned integer, there's no negative numbers, and it underflows and becomes 251 (because 5 - 5 is 0, and then the remaining 5 is subtracted from the "max value + 1").


    You can find more info about the integer overflow/underflow vulnerability in the SWC registry: https://swcregistry.io/docs/SWC-101