-
-
Save JuanXavier/dfd289739107fd45f560056242d31b4c to your computer and use it in GitHub Desktop.
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
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
library FixedPoint { | |
uint256 internal constant WAD = 1e18; | |
/// @dev Equivalent to `(x * y) / WAD` rounded down. | |
function mulWad(uint256 x, uint256 y) public pure returns (uint256 z) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. | |
if mul(y, gt(x, div(not(0), y))) { | |
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. | |
revert(0x1c, 0x04) | |
} | |
z := div(mul(x, y), WAD) | |
} | |
} | |
/// @dev Equivalent to `(x * y) / WAD` rounded up. | |
function mulWadUp(uint256 x, uint256 y) public pure returns (uint256 z) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. | |
if mul(y, gt(x, div(not(0), y))) { | |
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. | |
revert(0x1c, 0x04) | |
} | |
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) | |
} | |
} | |
/// @dev Equivalent to `(x * WAD) / y` rounded down. | |
function divWad(uint256 x, uint256 y) public pure returns (uint256 z) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
// Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`. | |
if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) { | |
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. | |
revert(0x1c, 0x04) | |
} | |
z := div(mul(x, WAD), y) | |
} | |
} | |
/// @dev Equivalent to `(x * WAD) / y` rounded up. | |
function divWadUp(uint256 x, uint256 y) public pure returns (uint256 z) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
// Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`. | |
if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) { | |
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. | |
revert(0x1c, 0x04) | |
} | |
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment