Math.sol 21 KB

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