diff --git a/src/libraries/Math.sol b/src/libraries/Math.sol new file mode 100644 index 0000000..bccadbb --- /dev/null +++ b/src/libraries/Math.sol @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.36; + +/// @title Math helpers for the constant-product core. +library Math { + function min(uint256 x, uint256 y) internal pure returns (uint256) { + return x < y ? x : y; + } + + /// @notice Babylonian integer square root. + function sqrt(uint256 y) internal pure returns (uint256 z) { + if (y > 3) { + z = y; + uint256 x = y / 2 + 1; + while (x < z) { + z = x; + x = (y / x + x) / 2; + } + } else if (y != 0) { + z = 1; + } + } +} diff --git a/src/libraries/UQ112x112.sol b/src/libraries/UQ112x112.sol new file mode 100644 index 0000000..ec1f9f5 --- /dev/null +++ b/src/libraries/UQ112x112.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.36; + +/// @title Fixed point unsigned Q112.112, used for price accumulators. +library UQ112x112 { + uint224 constant q112 = 2 ** 112; + + function encode(uint112 y) internal pure returns (uint224 z) { + unchecked { + z = uint224(y) * q112; + } + } + + function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { + z = x / uint224(y); + } +}