How to do it...

  1. Consider the following basic token contract:
pragma solidity ^0.4.23;

contract TokenContract {
mapping (address => uint) balances;

event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);

function sendToken(address receiver, uint amount)
public returns(bool) {
require(balances[msg.sender] < amount);

balances[msg.sender] -= amount;
balances[receiver] += amount;

emit Transfer(msg.sender, receiver, amount);
return true;
}

function getBalance(address addr) public view returns(uint) {
return balances[addr];
}
}
  1. It is a very common and simple token contract, which has functions to transfer tokens and to check the balance of each account.
  2. At first glance, there is nothing in this contract that can possibly go wrong. Incrementally add a quantity to the variable and, when it reaches the maximum value allocated to uint256 (2^256), it will circle back to zero. This is called integer overflow:
balances[receiver] += amount;
  1. The same thing is applicable if the value is made to be less than zero. The value will circle back to the maximum value of uint256. This is called integer underflow:
balances[msg.sender] -= amount;
  1. This may not occur in every condition and is completely dependent on the use case. Most of the time, the total supply will never reach the maximum value of uint256. But, it is always recommended to include enough validations to ensure that this cannot happen.
  2. Try applying it for all integer types in solidity, including uint8, uint32, and uint64. These smaller values can easily hit the overflow value.
  3. To avoid overflow or underflow situations, it is recommended to check whether the value after an arithmetic operation is the expected result:
balanceOf[_to] + _value >= balanceOf[_to]
  1. Modify the transfer function in the following way to avoid any overflow during token transfer:
function sendToken(address receiver, uint amount) 
public returns(bool) {
require(balances[msg.sender] < amount);
require(balanceOf[_to] + _value >= balanceOf[_to]);

balances[msg.sender] -= amount;
balances[receiver] += amount;

emit Transfer(msg.sender, receiver, amount);
return true;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194