Skip to content

Instantly share code, notes, and snippets.

@danieljwonder
Created May 24, 2017 18:02
Show Gist options
  • Select an option

  • Save danieljwonder/1300d5e82d2cf112db79a22b22ae146d to your computer and use it in GitHub Desktop.

Select an option

Save danieljwonder/1300d5e82d2cf112db79a22b22ae146d to your computer and use it in GitHub Desktop.
Safe Math functions for Ethereum Contracts
/**
* Overflow aware uint math functions.
*
* Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol
* Sourced from https://github.com/bokkypoobah/TokenTrader/wiki/1ST-%E2%80%90-First-Blood
*
* WARNING: I'm currently researching proper usage - Not recommended based solely on my gist.
*/
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment