Math.sol 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
  3. pragma solidity ^0.8.0;
  4. /**
  5. * @dev Standard math utilities missing in the Solidity language.
  6. */
  7. library Math {
  8. enum Rounding {
  9. Down, // Toward negative infinity
  10. Up, // Toward infinity
  11. Zero // Toward zero
  12. }
  13. /**
  14. * @dev Returns the largest of two numbers.
  15. */
  16. function max(uint256 a, uint256 b) internal pure returns (uint256) {
  17. return a > b ? a : b;
  18. }
  19. /**
  20. * @dev Returns the smallest of two numbers.
  21. */
  22. function min(uint256 a, uint256 b) internal pure returns (uint256) {
  23. return a < b ? a : b;
  24. }
  25. /**
  26. * @dev Returns the average of two numbers. The result is rounded towards
  27. * zero.
  28. */
  29. function average(uint256 a, uint256 b) internal pure returns (uint256) {
  30. // (a + b) / 2 can overflow.
  31. return (a & b) + (a ^ b) / 2;
  32. }
  33. /**
  34. * @dev Returns the ceiling of the division of two numbers.
  35. *
  36. * This differs from standard division with `/` in that it rounds up instead
  37. * of rounding down.
  38. */
  39. function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
  40. // (a + b - 1) / b can overflow on addition, so we distribute.
  41. return a == 0 ? 0 : (a - 1) / b + 1;
  42. }
  43. /**
  44. * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
  45. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
  46. * with further edits by Uniswap Labs also under MIT license.
  47. */
  48. function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
  49. unchecked {
  50. // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
  51. // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
  52. // variables such that product = prod1 * 2^256 + prod0.
  53. uint256 prod0; // Least significant 256 bits of the product
  54. uint256 prod1; // Most significant 256 bits of the product
  55. assembly {
  56. let mm := mulmod(x, y, not(0))
  57. prod0 := mul(x, y)
  58. prod1 := sub(sub(mm, prod0), lt(mm, prod0))
  59. }
  60. // Handle non-overflow cases, 256 by 256 division.
  61. if (prod1 == 0) {
  62. // Solidity will revert if denominator == 0, unlike the div opcode on its own.
  63. // The surrounding unchecked block does not change this fact.
  64. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
  65. return prod0 / denominator;
  66. }
  67. // Make sure the result is less than 2^256. Also prevents denominator == 0.
  68. require(denominator > prod1, "Math: mulDiv overflow");
  69. ///////////////////////////////////////////////
  70. // 512 by 256 division.
  71. ///////////////////////////////////////////////
  72. // Make division exact by subtracting the remainder from [prod1 prod0].
  73. uint256 remainder;
  74. assembly {
  75. // Compute remainder using mulmod.
  76. remainder := mulmod(x, y, denominator)
  77. // Subtract 256 bit number from 512 bit number.
  78. prod1 := sub(prod1, gt(remainder, prod0))
  79. prod0 := sub(prod0, remainder)
  80. }
  81. // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
  82. // See https://cs.stackexchange.com/q/138556/92363.
  83. // Does not overflow because the denominator cannot be zero at this stage in the function.
  84. uint256 twos = denominator & (~denominator + 1);
  85. assembly {
  86. // Divide denominator by twos.
  87. denominator := div(denominator, twos)
  88. // Divide [prod1 prod0] by twos.
  89. prod0 := div(prod0, twos)
  90. // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
  91. twos := add(div(sub(0, twos), twos), 1)
  92. }
  93. // Shift in bits from prod1 into prod0.
  94. prod0 |= prod1 * twos;
  95. // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
  96. // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
  97. // four bits. That is, denominator * inv = 1 mod 2^4.
  98. uint256 inverse = (3 * denominator) ^ 2;
  99. // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
  100. // in modular arithmetic, doubling the correct bits in each step.
  101. inverse *= 2 - denominator * inverse; // inverse mod 2^8
  102. inverse *= 2 - denominator * inverse; // inverse mod 2^16
  103. inverse *= 2 - denominator * inverse; // inverse mod 2^32
  104. inverse *= 2 - denominator * inverse; // inverse mod 2^64
  105. inverse *= 2 - denominator * inverse; // inverse mod 2^128
  106. inverse *= 2 - denominator * inverse; // inverse mod 2^256
  107. // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
  108. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
  109. // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
  110. // is no longer required.
  111. result = prod0 * inverse;
  112. return result;
  113. }
  114. }
  115. /**
  116. * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
  117. */
  118. function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
  119. uint256 result = mulDiv(x, y, denominator);
  120. if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
  121. result += 1;
  122. }
  123. return result;
  124. }
  125. /**
  126. * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
  127. *
  128. * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
  129. */
  130. function sqrt(uint256 a) internal pure returns (uint256) {
  131. if (a == 0) {
  132. return 0;
  133. }
  134. // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
  135. //
  136. // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
  137. // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
  138. //
  139. // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
  140. // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
  141. // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
  142. //
  143. // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
  144. uint256 result = 1 << (log2(a) >> 1);
  145. // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
  146. // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
  147. // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
  148. // into the expected uint128 result.
  149. unchecked {
  150. result = (result + a / result) >> 1;
  151. result = (result + a / result) >> 1;
  152. result = (result + a / result) >> 1;
  153. result = (result + a / result) >> 1;
  154. result = (result + a / result) >> 1;
  155. result = (result + a / result) >> 1;
  156. result = (result + a / result) >> 1;
  157. return min(result, a / result);
  158. }
  159. }
  160. /**
  161. * @notice Calculates sqrt(a), following the selected rounding direction.
  162. */
  163. function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
  164. unchecked {
  165. uint256 result = sqrt(a);
  166. return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
  167. }
  168. }
  169. /**
  170. * @dev Return the log in base 2, rounded down, of a positive value.
  171. * Returns 0 if given 0.
  172. */
  173. function log2(uint256 value) internal pure returns (uint256) {
  174. uint256 result = 0;
  175. unchecked {
  176. if (value >> 128 > 0) {
  177. value >>= 128;
  178. result += 128;
  179. }
  180. if (value >> 64 > 0) {
  181. value >>= 64;
  182. result += 64;
  183. }
  184. if (value >> 32 > 0) {
  185. value >>= 32;
  186. result += 32;
  187. }
  188. if (value >> 16 > 0) {
  189. value >>= 16;
  190. result += 16;
  191. }
  192. if (value >> 8 > 0) {
  193. value >>= 8;
  194. result += 8;
  195. }
  196. if (value >> 4 > 0) {
  197. value >>= 4;
  198. result += 4;
  199. }
  200. if (value >> 2 > 0) {
  201. value >>= 2;
  202. result += 2;
  203. }
  204. if (value >> 1 > 0) {
  205. result += 1;
  206. }
  207. }
  208. return result;
  209. }
  210. /**
  211. * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
  212. * Returns 0 if given 0.
  213. */
  214. function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
  215. unchecked {
  216. uint256 result = log2(value);
  217. return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
  218. }
  219. }
  220. /**
  221. * @dev Return the log in base 10, rounded down, of a positive value.
  222. * Returns 0 if given 0.
  223. */
  224. function log10(uint256 value) internal pure returns (uint256) {
  225. uint256 result = 0;
  226. unchecked {
  227. if (value >= 10 ** 64) {
  228. value /= 10 ** 64;
  229. result += 64;
  230. }
  231. if (value >= 10 ** 32) {
  232. value /= 10 ** 32;
  233. result += 32;
  234. }
  235. if (value >= 10 ** 16) {
  236. value /= 10 ** 16;
  237. result += 16;
  238. }
  239. if (value >= 10 ** 8) {
  240. value /= 10 ** 8;
  241. result += 8;
  242. }
  243. if (value >= 10 ** 4) {
  244. value /= 10 ** 4;
  245. result += 4;
  246. }
  247. if (value >= 10 ** 2) {
  248. value /= 10 ** 2;
  249. result += 2;
  250. }
  251. if (value >= 10 ** 1) {
  252. result += 1;
  253. }
  254. }
  255. return result;
  256. }
  257. /**
  258. * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
  259. * Returns 0 if given 0.
  260. */
  261. function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
  262. unchecked {
  263. uint256 result = log10(value);
  264. return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
  265. }
  266. }
  267. /**
  268. * @dev Return the log in base 256, rounded down, of a positive value.
  269. * Returns 0 if given 0.
  270. *
  271. * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
  272. */
  273. function log256(uint256 value) internal pure returns (uint256) {
  274. uint256 result = 0;
  275. unchecked {
  276. if (value >> 128 > 0) {
  277. value >>= 128;
  278. result += 16;
  279. }
  280. if (value >> 64 > 0) {
  281. value >>= 64;
  282. result += 8;
  283. }
  284. if (value >> 32 > 0) {
  285. value >>= 32;
  286. result += 4;
  287. }
  288. if (value >> 16 > 0) {
  289. value >>= 16;
  290. result += 2;
  291. }
  292. if (value >> 8 > 0) {
  293. result += 1;
  294. }
  295. }
  296. return result;
  297. }
  298. /**
  299. * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
  300. * Returns 0 if given 0.
  301. */
  302. function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
  303. unchecked {
  304. uint256 result = log256(value);
  305. return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
  306. }
  307. }
  308. }