-
-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
blockchain_integration/pi_network/pi-network-layer2-scaling/contracts/libraries/MathLib.sol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
// SPDX-License-Identifier: MIT | ||
pragma solidity ^0.8.0; | ||
|
||
library MathLib { | ||
// Safe addition | ||
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { | ||
require(a + b >= a, "MathLib: addition overflow"); | ||
return a + b; | ||
} | ||
|
||
// Safe subtraction | ||
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { | ||
require(b <= a, "MathLib: subtraction underflow"); | ||
return a - b; | ||
} | ||
|
||
// Safe multiplication | ||
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { | ||
if (a == 0) { | ||
return 0; | ||
} | ||
require(a * b / a == b, "MathLib: multiplication overflow"); | ||
return a * b; | ||
} | ||
|
||
// Safe division | ||
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { | ||
require(b > 0, "MathLib: division by zero"); | ||
return a / b; | ||
} | ||
|
||
// Calculate the average of two numbers | ||
function average(uint256 a, uint256 b) internal pure returns (uint256) { | ||
return safeDiv(safeAdd(a, b), 2); | ||
} | ||
|
||
// Calculate the maximum of two numbers | ||
function max(uint256 a, uint256 b) internal pure returns (uint256) { | ||
return a >= b ? a : b; | ||
} | ||
|
||
// Calculate the minimum of two numbers | ||
function min(uint256 a, uint256 b) internal pure returns (uint256) { | ||
return a < b ? a : b; | ||
} | ||
} |