-
Notifications
You must be signed in to change notification settings - Fork 6
/
SafeMath.sol
61 lines (55 loc) · 1.68 KB
/
SafeMath.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
pragma solidity 0.4.24;
/**
* @title SafeMath
* @notice Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @notice Multiplies two numbers, throws on overflow.
* @param a Multiplier
* @param b Multiplicand
* @return {"result" : "Returns product"}
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 result) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "Error: Unsafe multiplication operation!");
return c;
}
/**
* @notice Integer division of two numbers, truncating the quotient.
* @param a Dividend
* @param b Divisor
* @return {"result" : "Returns quotient"}
*/
function div(uint256 a, uint256 b) internal pure returns (uint256 result) {
// @dev require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// @dev require(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @notice Subtracts two numbers, throws on underflow.
* @param a Subtrahend
* @param b Minuend
* @return {"result" : "Returns difference"}
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256 result) {
// @dev throws on overflow (i.e. if subtrahend is greater than minuend)
require(b <= a, "Error: Unsafe subtraction operation!");
return a - b;
}
/**
* @notice Adds two numbers, throws on overflow.
* @param a First addend
* @param b Second addend
* @return {"result" : "Returns summation"}
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 result) {
uint256 c = a + b;
require(c >= a, "Error: Unsafe addition operation!");
return c;
}
}