SafeMath library for multiple uint variables — Solidity (Ethereum)

Alber Erre
⏱️ 3 min Blockchain
2 min readApr 18, 2018

--

It’s a normal practice to use SafeMath library while applying basic mathematical operations on Ethereum smart contracts.

However, once we want to optimize our code, by reducing Gas consumption, we have to implement these mathematical transformation using a different uint variables (uint32, uint16, unit8) , apart from uint256.

Fortunately, here is the code.

uint32

library SafeMath32 {function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint32 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn’t hold
return c;
}
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a — b;
}
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}

uint16

library SafeMath16 {function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 c = a * b;
assert(c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn’t hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a — b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}

uint8

library SafeMath8 {function mul(uint8 a, uint8 b) internal pure returns (uint8) {
if (a == 0) {
return 0;
}
uint8 c = a * b;
assert(c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn’t hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a — b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}

Now, you just need to use the corresponding library inside your contract.

e.g.

 using SafeMath for uint256;
using SafeMath32 for uint32;
using SafeMath16 for uint16;
using SafeMath8 for uint8;

Hope this helps!

Cheers, Alber Erre.

--

--

Alber Erre
⏱️ 3 min Blockchain

Messy Blockchain Adventures 🚀 & Front End Development