Math.sol 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 {Panic} from "../Panic.sol";
  5. import {SafeCast} from "./SafeCast.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. return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
  186. }
  187. /**
  188. * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
  189. *
  190. * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, expect 0.
  191. * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
  192. *
  193. * If the input value is not inversible, 0 is returned.
  194. *
  195. * 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
  196. * inverse using `Math.modExp(a, n - 2, n)`.
  197. */
  198. function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
  199. unchecked {
  200. if (n == 0) return 0;
  201. // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
  202. // Used to compute integers x and y such that: ax + ny = gcd(a, n).
  203. // When the gcd is 1, then the inverse of a modulo n exists and it's x.
  204. // ax + ny = 1
  205. // ax = 1 + (-y)n
  206. // ax ≡ 1 (mod n) # x is the inverse of a modulo n
  207. // If the remainder is 0 the gcd is n right away.
  208. uint256 remainder = a % n;
  209. uint256 gcd = n;
  210. // Therefore the initial coefficients are:
  211. // ax + ny = gcd(a, n) = n
  212. // 0a + 1n = n
  213. int256 x = 0;
  214. int256 y = 1;
  215. while (remainder != 0) {
  216. uint256 quotient = gcd / remainder;
  217. (gcd, remainder) = (
  218. // The old remainder is the next gcd to try.
  219. remainder,
  220. // Compute the next remainder.
  221. // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
  222. // where gcd is at most n (capped to type(uint256).max)
  223. gcd - remainder * quotient
  224. );
  225. (x, y) = (
  226. // Increment the coefficient of a.
  227. y,
  228. // Decrement the coefficient of n.
  229. // Can overflow, but the result is casted to uint256 so that the
  230. // next value of y is "wrapped around" to a value between 0 and n - 1.
  231. x - y * int256(quotient)
  232. );
  233. }
  234. if (gcd != 1) return 0; // No inverse exists.
  235. return x < 0 ? (n - uint256(-x)) : uint256(x); // Wrap the result if it's negative.
  236. }
  237. }
  238. /**
  239. * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
  240. *
  241. * Requirements:
  242. * - modulus can't be zero
  243. * - underlying staticcall to precompile must succeed
  244. *
  245. * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
  246. * sure the chain you're using it on supports the precompiled contract for modular exponentiation
  247. * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
  248. * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
  249. * interpreted as 0.
  250. */
  251. function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
  252. (bool success, uint256 result) = tryModExp(b, e, m);
  253. if (!success) {
  254. Panic.panic(Panic.DIVISION_BY_ZERO);
  255. }
  256. return result;
  257. }
  258. /**
  259. * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
  260. * It includes a success flag indicating if the operation succeeded. Operation will be marked has failed if trying
  261. * to operate modulo 0 or if the underlying precompile reverted.
  262. *
  263. * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
  264. * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
  265. * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
  266. * of a revert, but the result may be incorrectly interpreted as 0.
  267. */
  268. function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
  269. if (m == 0) return (false, 0);
  270. /// @solidity memory-safe-assembly
  271. assembly {
  272. let ptr := mload(0x40)
  273. // | Offset | Content | Content (Hex) |
  274. // |-----------|------------|--------------------------------------------------------------------|
  275. // | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
  276. // | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
  277. // | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
  278. // | 0x60:0x7f | value of b | 0x<.............................................................b> |
  279. // | 0x80:0x9f | value of e | 0x<.............................................................e> |
  280. // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
  281. mstore(ptr, 0x20)
  282. mstore(add(ptr, 0x20), 0x20)
  283. mstore(add(ptr, 0x40), 0x20)
  284. mstore(add(ptr, 0x60), b)
  285. mstore(add(ptr, 0x80), e)
  286. mstore(add(ptr, 0xa0), m)
  287. // Given the result < m, it's guaranteed to fit in 32 bytes,
  288. // so we can use the memory scratch space located at offset 0.
  289. success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
  290. result := mload(0x00)
  291. }
  292. }
  293. /**
  294. * @dev Variant of {modExp} that supports inputs of arbitrary length.
  295. */
  296. function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
  297. (bool success, bytes memory result) = tryModExp(b, e, m);
  298. if (!success) {
  299. Panic.panic(Panic.DIVISION_BY_ZERO);
  300. }
  301. return result;
  302. }
  303. /**
  304. * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
  305. */
  306. function tryModExp(
  307. bytes memory b,
  308. bytes memory e,
  309. bytes memory m
  310. ) internal view returns (bool success, bytes memory result) {
  311. if (_zeroBytes(m)) return (false, new bytes(0));
  312. uint256 mLen = m.length;
  313. // Encode call args in result and move the free memory pointer
  314. result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
  315. /// @solidity memory-safe-assembly
  316. assembly {
  317. let dataPtr := add(result, 0x20)
  318. // Write result on top of args to avoid allocating extra memory.
  319. success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
  320. // Overwrite the length.
  321. // result.length > returndatasize() is guaranteed because returndatasize() == m.length
  322. mstore(result, mLen)
  323. // Set the memory pointer after the returned data.
  324. mstore(0x40, add(dataPtr, mLen))
  325. }
  326. }
  327. /**
  328. * @dev Returns whether the provided byte array is zero.
  329. */
  330. function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
  331. for (uint256 i = 0; i < byteArray.length; ++i) {
  332. if (byteArray[i] != 0) {
  333. return false;
  334. }
  335. }
  336. return true;
  337. }
  338. /**
  339. * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
  340. * towards zero.
  341. *
  342. * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
  343. */
  344. function sqrt(uint256 a) internal pure returns (uint256) {
  345. if (a == 0) {
  346. return 0;
  347. }
  348. // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
  349. //
  350. // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
  351. // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
  352. //
  353. // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
  354. // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
  355. // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
  356. //
  357. // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
  358. uint256 result = 1 << (log2(a) >> 1);
  359. // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
  360. // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
  361. // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
  362. // into the expected uint128 result.
  363. unchecked {
  364. result = (result + a / result) >> 1;
  365. result = (result + a / result) >> 1;
  366. result = (result + a / result) >> 1;
  367. result = (result + a / result) >> 1;
  368. result = (result + a / result) >> 1;
  369. result = (result + a / result) >> 1;
  370. result = (result + a / result) >> 1;
  371. return min(result, a / result);
  372. }
  373. }
  374. /**
  375. * @dev Calculates sqrt(a), following the selected rounding direction.
  376. */
  377. function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
  378. unchecked {
  379. uint256 result = sqrt(a);
  380. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
  381. }
  382. }
  383. /**
  384. * @dev Return the log in base 2 of a positive value rounded towards zero.
  385. * Returns 0 if given 0.
  386. */
  387. function log2(uint256 value) internal pure returns (uint256) {
  388. uint256 result = 0;
  389. uint256 exp;
  390. unchecked {
  391. exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
  392. value >>= exp;
  393. result += exp;
  394. exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
  395. value >>= exp;
  396. result += exp;
  397. exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
  398. value >>= exp;
  399. result += exp;
  400. exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
  401. value >>= exp;
  402. result += exp;
  403. exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
  404. value >>= exp;
  405. result += exp;
  406. exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
  407. value >>= exp;
  408. result += exp;
  409. exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
  410. value >>= exp;
  411. result += exp;
  412. result += SafeCast.toUint(value > 1);
  413. }
  414. return result;
  415. }
  416. /**
  417. * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
  418. * Returns 0 if given 0.
  419. */
  420. function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
  421. unchecked {
  422. uint256 result = log2(value);
  423. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
  424. }
  425. }
  426. /**
  427. * @dev Return the log in base 10 of a positive value rounded towards zero.
  428. * Returns 0 if given 0.
  429. */
  430. function log10(uint256 value) internal pure returns (uint256) {
  431. uint256 result = 0;
  432. unchecked {
  433. if (value >= 10 ** 64) {
  434. value /= 10 ** 64;
  435. result += 64;
  436. }
  437. if (value >= 10 ** 32) {
  438. value /= 10 ** 32;
  439. result += 32;
  440. }
  441. if (value >= 10 ** 16) {
  442. value /= 10 ** 16;
  443. result += 16;
  444. }
  445. if (value >= 10 ** 8) {
  446. value /= 10 ** 8;
  447. result += 8;
  448. }
  449. if (value >= 10 ** 4) {
  450. value /= 10 ** 4;
  451. result += 4;
  452. }
  453. if (value >= 10 ** 2) {
  454. value /= 10 ** 2;
  455. result += 2;
  456. }
  457. if (value >= 10 ** 1) {
  458. result += 1;
  459. }
  460. }
  461. return result;
  462. }
  463. /**
  464. * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
  465. * Returns 0 if given 0.
  466. */
  467. function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
  468. unchecked {
  469. uint256 result = log10(value);
  470. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
  471. }
  472. }
  473. /**
  474. * @dev Return the log in base 256 of a positive value rounded towards zero.
  475. * Returns 0 if given 0.
  476. *
  477. * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
  478. */
  479. function log256(uint256 value) internal pure returns (uint256) {
  480. uint256 result = 0;
  481. uint256 isGt;
  482. unchecked {
  483. isGt = SafeCast.toUint(value > (1 << 128) - 1);
  484. value >>= isGt * 128;
  485. result += isGt * 16;
  486. isGt = SafeCast.toUint(value > (1 << 64) - 1);
  487. value >>= isGt * 64;
  488. result += isGt * 8;
  489. isGt = SafeCast.toUint(value > (1 << 32) - 1);
  490. value >>= isGt * 32;
  491. result += isGt * 4;
  492. isGt = SafeCast.toUint(value > (1 << 16) - 1);
  493. value >>= isGt * 16;
  494. result += isGt * 2;
  495. result += SafeCast.toUint(value > (1 << 8) - 1);
  496. }
  497. return result;
  498. }
  499. /**
  500. * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
  501. * Returns 0 if given 0.
  502. */
  503. function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
  504. unchecked {
  505. uint256 result = log256(value);
  506. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
  507. }
  508. }
  509. /**
  510. * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
  511. */
  512. function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
  513. return uint8(rounding) % 2 == 1;
  514. }
  515. }