Math.sol 21 KB

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