There's more...

There are best practices and reusable code that can be used to avoid such bugs in your smart contract. One perfect example is the SafeMath library of openzeppelin. This library  introduces a few functions that can be used instead of the regular arithmetic operators. These functions include conditions to ensure that no overflow or underflow can happen:

pragma solidity ^0.4.24;

library SafeMath {
/**
* @dev Function to add two numbers
*/
function add(uint256 a, uint256 b)
internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}

function sub(...) { ... }
function mul(...) { ... }
function div(...) { ... }
}

To use this library, import SafeMath from the openzeppelin GitHub repository at https://github.com/OpenZeppelin/openzeppelin-solidity:

import "./contracts/math/SafeMath.sol";

Assign the library to the integer type you wish to use:

using SafeMath for uint256;

Now, all functions of the SafeMath library are part of the unsigned integer and are accessible directly. The transfer function can be modified as follows to use the SafeMath library:

function sendToken(address receiver, uint amount) 
public returns(bool) {
require(balances[msg.sender] < amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[receiver] = balances[receiver].add(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
3.133.156.251