Math.sol 15 KB

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