Safemath Solidity
Safemath Solidity
• Let's say we have a uint8, which can only have 8 bits. That means the largest
number we can store is
binary 11111111 (or in decimal, 2^8 1 255.
• Take a look at the following code. What is number equal to at the end?
Using SafeMath
• To prevent this, OpenZeppelin has created a library called SafeMath that prevents
these issues by
default.
• But before we get into that... What's a library?
A library is a special type of contract in Solidity. One of the things it is useful for is to
attach functions to
native data types.
• For example, with the SafeMath library, we'll use the syntax using SafeMath for
uint256. The SafeMath library has 4 functions — add, sub, mul, and div. And now we
can access these functions from uint256 as follows:
using SafeMath for uint256;
uint256 a = 5;
uint256 b = a.add(3); // 5 + 3 = 8
uint256 c = a.mul(2); // 5 * 2 = 1
safemath code
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't
hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
Reentrancy attack
attack
victim
• low level method call in solidity msg.sender.call.value(amount)("") ;
attacker
protect
victim
Context
• context.sol is a calling contract
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}