Math.sol 17 KB

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