|
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.13;\n\n/// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not\n/// always operate with SD59x18 and UD60x18 numbers.\n\n/*//////////////////////////////////////////////////////////////////////////\n CUSTOM ERRORS\n//////////////////////////////////////////////////////////////////////////*/\n\n/// @notice Emitted when the ending result in the fixed-point version of `mulDiv` would overflow uint256.\nerror PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);\n\n/// @notice Emitted when the ending result in `mulDiv` would overflow uint256.\nerror PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);\n\n/// @notice Emitted when attempting to run `mulDiv` with one of the inputs `type(int256).min`.\nerror PRBMath_MulDivSigned_InputTooSmall();\n\n/// @notice Emitted when the ending result in the signed version of `mulDiv` would overflow int256.\nerror PRBMath_MulDivSigned_Overflow(int256 x, int256 y);\n\n/*//////////////////////////////////////////////////////////////////////////\n CONSTANTS\n//////////////////////////////////////////////////////////////////////////*/\n\n/// @dev The maximum value an uint128 number can have.\nuint128 constant MAX_UINT128 = type(uint128).max;\n\n/// @dev The maximum value an uint40 number can have.\nuint40 constant MAX_UINT40 = type(uint40).max;\n\n/// @dev How many trailing decimals can be represented.\nuint256 constant UNIT = 1e18;\n\n/// @dev Largest power of two that is a divisor of `UNIT`.\nuint256 constant UNIT_LPOTD = 262144;\n\n/// @dev The `UNIT` number inverted mod 2^256.\nuint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;\n\n/*//////////////////////////////////////////////////////////////////////////\n FUNCTIONS\n//////////////////////////////////////////////////////////////////////////*/\n\n/// @notice Finds the zero-based index of the first one in the binary representation of x.\n/// @dev See the note on msb in the \"Find First Set\" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set\n///\n/// Each of the steps in this implementation is equivalent to this high-level code:\n///\n/// ```solidity\n/// if (x >= 2 ** 128) {\n/// x >>= 128;\n/// result += 128;\n/// }\n/// ```\n///\n/// Where 128 is swapped with each respective power of two factor. See the full high-level implementation here:\n/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948\n///\n/// A list of the Yul instructions used below:\n/// - \"gt\" is \"greater than\"\n/// - \"or\" is the OR bitwise operator\n/// - \"shl\" is \"shift left\"\n/// - \"shr\" is \"shift right\"\n///\n/// @param x The uint256 number for which to find the index of the most significant bit.\n/// @return result The index of the most significant bit as an uint256.\nfunction msb(uint256 x) pure returns (uint256 result) {\n // 2^128\n assembly (\"memory-safe\") {\n let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^64\n assembly (\"memory-safe\") {\n let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^32\n assembly (\"memory-safe\") {\n let factor := shl(5, gt(x, 0xFFFFFFFF))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^16\n assembly (\"memory-safe\") {\n let factor := shl(4, gt(x, 0xFFFF))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^8\n assembly (\"memory-safe\") {\n let factor := shl(3, gt(x, 0xFF))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^4\n assembly (\"memory-safe\") {\n let factor := shl(2, gt(x, 0xF))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^2\n assembly (\"memory-safe\") {\n let factor := shl(1, gt(x, 0x3))\n x := shr(factor, x)\n result := or(result, factor)\n }\n // 2^1\n // No need to shift x any more.\n assembly (\"memory-safe\") {\n let factor := gt(x, 0x1)\n result := or(result, factor)\n }\n}\n\n/// @notice Calculates floor(x*y÷denominator) with full precision.\n///\n/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.\n///\n/// Requirements:\n/// - The denominator cannot be zero.\n/// - The result must fit within uint256.\n///\n/// Caveats:\n/// - This function does not work with fixed-point numbers.\n///\n/// @param x The multiplicand as an uint256.\n/// @param y The multiplier as an uint256.\n/// @param denominator The divisor as an uint256.\n/// @return result The result as an uint256.\nfunction mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly (\"memory-safe\") {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n unchecked {\n return prod0 / denominator;\n }\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (prod1 >= denominator) {\n revert PRBMath_MulDiv_Overflow(x, y, denominator);\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly (\"memory-safe\") {\n // Compute remainder using the mulmod Yul instruction.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n unchecked {\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 lpotdod = denominator & (~denominator + 1);\n assembly (\"memory-safe\") {\n // Divide denominator by lpotdod.\n denominator := div(denominator, lpotdod)\n\n // Divide [prod1 prod0] by lpotdod.\n prod0 := div(prod0, lpotdod)\n\n // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.\n lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * lpotdod;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n }\n}\n\n/// @notice Calculates floor(x*y÷1e18) with full precision.\n///\n/// @dev Variant of `mulDiv` with constant folding, i.e. in which the denominator is always 1e18. Before returning the\n/// final result, we add 1 if `(x * y) % UNIT >= HALF_UNIT`. Without this adjustment, 6.6e-19 would be truncated to 0\n/// instead of being rounded to 1e-18. See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717.\n///\n/// Requirements:\n/// - The result must fit within uint256.\n///\n/// Caveats:\n/// - The body is purposely left uncommented; to understand how this works, see the NatSpec comments in `mulDiv`.\n/// - It is assumed that the result can never be `type(uint256).max` when x and y solve the following two equations:\n/// 1. x * y = type(uint256).max * UNIT\n/// 2. (x * y) % UNIT >= UNIT / 2\n///\n/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.\nfunction mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {\n uint256 prod0;\n uint256 prod1;\n assembly (\"memory-safe\") {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n if (prod1 >= UNIT) {\n revert PRBMath_MulDiv18_Overflow(x, y);\n }\n\n uint256 remainder;\n assembly (\"memory-safe\") {\n remainder := mulmod(x, y, UNIT)\n }\n\n if (prod1 == 0) {\n unchecked {\n return prod0 / UNIT;\n }\n }\n\n assembly (\"memory-safe\") {\n result := mul(\n or(\n div(sub(prod0, remainder), UNIT_LPOTD),\n mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))\n ),\n UNIT_INVERSE\n )\n }\n}\n\n/// @notice Calculates floor(x*y÷denominator) with full precision.\n///\n/// @dev An extension of `mulDiv` for signed numbers. Works by computing the signs and the absolute values separately.\n///\n/// Requirements:\n/// - None of the inputs can be `type(int256).min`.\n/// - The result must fit within int256.\n///\n/// @param x The multiplicand as an int256.\n/// @param y The multiplier as an int256.\n/// @param denominator The divisor as an int256.\n/// @return result The result as an int256.\nfunction mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {\n if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {\n revert PRBMath_MulDivSigned_InputTooSmall();\n }\n\n // Get hold of the absolute values of x, y and the denominator.\n uint256 absX;\n uint256 absY;\n uint256 absD;\n unchecked {\n absX = x < 0 ? uint256(-x) : uint256(x);\n absY = y < 0 ? uint256(-y) : uint256(y);\n absD = denominator < 0 ? uint256(-denominator) : uint256(denominator);\n }\n\n // Compute the absolute value of (x*y)÷denominator. The result must fit within int256.\n uint256 rAbs = mulDiv(absX, absY, absD);\n if (rAbs > uint256(type(int256).max)) {\n revert PRBMath_MulDivSigned_Overflow(x, y);\n }\n\n // Get the signs of x, y and the denominator.\n uint256 sx;\n uint256 sy;\n uint256 sd;\n assembly (\"memory-safe\") {\n // This works thanks to two's complement.\n // \"sgt\" stands for \"signed greater than\" and \"sub(0,1)\" is max uint256.\n sx := sgt(x, sub(0, 1))\n sy := sgt(y, sub(0, 1))\n sd := sgt(denominator, sub(0, 1))\n }\n\n // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.\n // If there are, the result should be negative. Otherwise, it should be positive.\n unchecked {\n result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);\n }\n}\n\n/// @notice Calculates the binary exponent of x using the binary fraction method.\n/// @dev Has to use 192.64-bit fixed-point numbers.\n/// See https://ethereum.stackexchange.com/a/96594/24693.\n/// @param x The exponent as an unsigned 192.64-bit fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.\nfunction prbExp2(uint256 x) pure returns (uint256 result) {\n unchecked {\n // Start from 0.5 in the 192.64-bit fixed-point format.\n result = 0x800000000000000000000000000000000000000000000000;\n\n // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows\n // because the initial result is 2^191 and all magic factors are less than 2^65.\n if (x & 0xFF00000000000000 > 0) {\n if (x & 0x8000000000000000 > 0) {\n result = (result * 0x16A09E667F3BCC909) >> 64;\n }\n if (x & 0x4000000000000000 > 0) {\n result = (result * 0x1306FE0A31B7152DF) >> 64;\n }\n if (x & 0x2000000000000000 > 0) {\n result = (result * 0x1172B83C7D517ADCE) >> 64;\n }\n if (x & 0x1000000000000000 > 0) {\n result = (result * 0x10B5586CF9890F62A) >> 64;\n }\n if (x & 0x800000000000000 > 0) {\n result = (result * 0x1059B0D31585743AE) >> 64;\n }\n if (x & 0x400000000000000 > 0) {\n result = (result * 0x102C9A3E778060EE7) >> 64;\n }\n if (x & 0x200000000000000 > 0) {\n result = (result * 0x10163DA9FB33356D8) >> 64;\n }\n if (x & 0x100000000000000 > 0) {\n result = (result * 0x100B1AFA5ABCBED61) >> 64;\n }\n }\n\n if (x & 0xFF000000000000 > 0) {\n if (x & 0x80000000000000 > 0) {\n result = (result * 0x10058C86DA1C09EA2) >> 64;\n }\n if (x & 0x40000000000000 > 0) {\n result = (result * 0x1002C605E2E8CEC50) >> 64;\n }\n if (x & 0x20000000000000 > 0) {\n result = (result * 0x100162F3904051FA1) >> 64;\n }\n if (x & 0x10000000000000 > 0) {\n result = (result * 0x1000B175EFFDC76BA) >> 64;\n }\n if (x & 0x8000000000000 > 0) {\n result = (result * 0x100058BA01FB9F96D) >> 64;\n }\n if (x & 0x4000000000000 > 0) {\n result = (result * 0x10002C5CC37DA9492) >> 64;\n }\n if (x & 0x2000000000000 > 0) {\n result = (result * 0x1000162E525EE0547) >> 64;\n }\n if (x & 0x1000000000000 > 0) {\n result = (result * 0x10000B17255775C04) >> 64;\n }\n }\n\n if (x & 0xFF0000000000 > 0) {\n if (x & 0x800000000000 > 0) {\n result = (result * 0x1000058B91B5BC9AE) >> 64;\n }\n if (x & 0x400000000000 > 0) {\n result = (result * 0x100002C5C89D5EC6D) >> 64;\n }\n if (x & 0x200000000000 > 0) {\n result = (result * 0x10000162E43F4F831) >> 64;\n }\n if (x & 0x100000000000 > 0) {\n result = (result * 0x100000B1721BCFC9A) >> 64;\n }\n if (x & 0x80000000000 > 0) {\n result = (result * 0x10000058B90CF1E6E) >> 64;\n }\n if (x & 0x40000000000 > 0) {\n result = (result * 0x1000002C5C863B73F) >> 64;\n }\n if (x & 0x20000000000 > 0) {\n result = (result * 0x100000162E430E5A2) >> 64;\n }\n if (x & 0x10000000000 > 0) {\n result = (result * 0x1000000B172183551) >> 64;\n }\n }\n\n if (x & 0xFF00000000 > 0) {\n if (x & 0x8000000000 > 0) {\n result = (result * 0x100000058B90C0B49) >> 64;\n }\n if (x & 0x4000000000 > 0) {\n result = (result * 0x10000002C5C8601CC) >> 64;\n }\n if (x & 0x2000000000 > 0) {\n result = (result * 0x1000000162E42FFF0) >> 64;\n }\n if (x & 0x1000000000 > 0) {\n result = (result * 0x10000000B17217FBB) >> 64;\n }\n if (x & 0x800000000 > 0) {\n result = (result * 0x1000000058B90BFCE) >> 64;\n }\n if (x & 0x400000000 > 0) {\n result = (result * 0x100000002C5C85FE3) >> 64;\n }\n if (x & 0x200000000 > 0) {\n result = (result * 0x10000000162E42FF1) >> 64;\n }\n if (x & 0x100000000 > 0) {\n result = (result * 0x100000000B17217F8) >> 64;\n }\n }\n\n if (x & 0xFF00000000 > 0) {\n if (x & 0x80000000 > 0) {\n result = (result * 0x10000000058B90BFC) >> 64;\n }\n if (x & 0x40000000 > 0) {\n result = (result * 0x1000000002C5C85FE) >> 64;\n }\n if (x & 0x20000000 > 0) {\n result = (result * 0x100000000162E42FF) >> 64;\n }\n if (x & 0x10000000 > 0) {\n result = (result * 0x1000000000B17217F) >> 64;\n }\n if (x & 0x8000000 > 0) {\n result = (result * 0x100000000058B90C0) >> 64;\n }\n if (x & 0x4000000 > 0) {\n result = (result * 0x10000000002C5C860) >> 64;\n }\n if (x & 0x2000000 > 0) {\n result = (result * 0x1000000000162E430) >> 64;\n }\n if (x & 0x1000000 > 0) {\n result = (result * 0x10000000000B17218) >> 64;\n }\n }\n\n if (x & 0xFF0000 > 0) {\n if (x & 0x800000 > 0) {\n result = (result * 0x1000000000058B90C) >> 64;\n }\n if (x & 0x400000 > 0) {\n result = (result * 0x100000000002C5C86) >> 64;\n }\n if (x & 0x200000 > 0) {\n result = (result * 0x10000000000162E43) >> 64;\n }\n if (x & 0x100000 > 0) {\n result = (result * 0x100000000000B1721) >> 64;\n }\n if (x & 0x80000 > 0) {\n result = (result * 0x10000000000058B91) >> 64;\n }\n if (x & 0x40000 > 0) {\n result = (result * 0x1000000000002C5C8) >> 64;\n }\n if (x & 0x20000 > 0) {\n result = (result * 0x100000000000162E4) >> 64;\n }\n if (x & 0x10000 > 0) {\n result = (result * 0x1000000000000B172) >> 64;\n }\n }\n\n if (x & 0xFF00 > 0) {\n if (x & 0x8000 > 0) {\n result = (result * 0x100000000000058B9) >> 64;\n }\n if (x & 0x4000 > 0) {\n result = (result * 0x10000000000002C5D) >> 64;\n }\n if (x & 0x2000 > 0) {\n result = (result * 0x1000000000000162E) >> 64;\n }\n if (x & 0x1000 > 0) {\n result = (result * 0x10000000000000B17) >> 64;\n }\n if (x & 0x800 > 0) {\n result = (result * 0x1000000000000058C) >> 64;\n }\n if (x & 0x400 > 0) {\n result = (result * 0x100000000000002C6) >> 64;\n }\n if (x & 0x200 > 0) {\n result = (result * 0x10000000000000163) >> 64;\n }\n if (x & 0x100 > 0) {\n result = (result * 0x100000000000000B1) >> 64;\n }\n }\n\n if (x & 0xFF > 0) {\n if (x & 0x80 > 0) {\n result = (result * 0x10000000000000059) >> 64;\n }\n if (x & 0x40 > 0) {\n result = (result * 0x1000000000000002C) >> 64;\n }\n if (x & 0x20 > 0) {\n result = (result * 0x10000000000000016) >> 64;\n }\n if (x & 0x10 > 0) {\n result = (result * 0x1000000000000000B) >> 64;\n }\n if (x & 0x8 > 0) {\n result = (result * 0x10000000000000006) >> 64;\n }\n if (x & 0x4 > 0) {\n result = (result * 0x10000000000000003) >> 64;\n }\n if (x & 0x2 > 0) {\n result = (result * 0x10000000000000001) >> 64;\n }\n if (x & 0x1 > 0) {\n result = (result * 0x10000000000000001) >> 64;\n }\n }\n\n // We're doing two things at the same time:\n //\n // 1. Multiply the result by 2^n + 1, where \"2^n\" is the integer part and the one is added to account for\n // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191\n // rather than 192.\n // 2. Convert the result to the unsigned 60.18-decimal fixed-point format.\n //\n // This works because 2^(191-ip) = 2^ip / 2^191, where \"ip\" is the integer part \"2^n\".\n result *= UNIT;\n result >>= (191 - (x >> 64));\n }\n}\n\n/// @notice Calculates the square root of x, rounding down if x is not a perfect square.\n/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n/// Credits to OpenZeppelin for the explanations in code comments below.\n///\n/// Caveats:\n/// - This function does not work with fixed-point numbers.\n///\n/// @param x The uint256 number for which to calculate the square root.\n/// @return result The result as an uint256.\nfunction prbSqrt(uint256 x) pure returns (uint256 result) {\n if (x == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of x.\n //\n // We know that the \"msb\" (most significant bit) of x is a power of 2 such that we have:\n //\n // $$\n // msb(x) <= x <= 2*msb(x)$\n // $$\n //\n // We write $msb(x)$ as $2^k$ and we get:\n //\n // $$\n // k = log_2(x)\n // $$\n //\n // Thus we can write the initial inequality as:\n //\n // $$\n // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\\\\n // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\\\\n // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}\n // $$\n //\n // Consequently, $2^{log_2(x) /2}` is a good first approximation of sqrt(x) with at least one correct bit.\n uint256 xAux = uint256(x);\n result = 1;\n if (xAux >= 2 ** 128) {\n xAux >>= 128;\n result <<= 64;\n }\n if (xAux >= 2 ** 64) {\n xAux >>= 64;\n result <<= 32;\n }\n if (xAux >= 2 ** 32) {\n xAux >>= 32;\n result <<= 16;\n }\n if (xAux >= 2 ** 16) {\n xAux >>= 16;\n result <<= 8;\n }\n if (xAux >= 2 ** 8) {\n xAux >>= 8;\n result <<= 4;\n }\n if (xAux >= 2 ** 4) {\n xAux >>= 4;\n result <<= 2;\n }\n if (xAux >= 2 ** 2) {\n result <<= 1;\n }\n\n // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at\n // most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision\n // doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of\n // precision into the expected uint128 result.\n unchecked {\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n\n // Round down the result in case x is not a perfect square.\n uint256 roundedDownResult = x / result;\n if (result >= roundedDownResult) {\n result = roundedDownResult;\n }\n }\n}\n"
|