Math.sol 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. 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 overflow flag.
  20. */
  21. function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  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 overflow flag.
  30. */
  31. function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  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 overflow flag.
  39. */
  40. function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  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 division by zero flag.
  53. */
  54. function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  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 division by zero flag.
  62. */
  63. function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
  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. // (a + b - 1) / b can overflow on addition, so we distribute.
  101. return a == 0 ? 0 : (a - 1) / b + 1;
  102. }
  103. /**
  104. * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
  105. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
  106. * with further edits by Uniswap Labs also under MIT license.
  107. */
  108. function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
  109. unchecked {
  110. // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
  111. // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
  112. // variables such that product = prod1 * 2^256 + prod0.
  113. uint256 prod0; // Least significant 256 bits of the product
  114. uint256 prod1; // Most significant 256 bits of the product
  115. assembly {
  116. let mm := mulmod(x, y, not(0))
  117. prod0 := mul(x, y)
  118. prod1 := sub(sub(mm, prod0), lt(mm, prod0))
  119. }
  120. // Handle non-overflow cases, 256 by 256 division.
  121. if (prod1 == 0) {
  122. // Solidity will revert if denominator == 0, unlike the div opcode on its own.
  123. // The surrounding unchecked block does not change this fact.
  124. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
  125. return prod0 / denominator;
  126. }
  127. // Make sure the result is less than 2^256. Also prevents denominator == 0.
  128. if (denominator <= prod1) {
  129. revert MathOverflowedMulDiv();
  130. }
  131. ///////////////////////////////////////////////
  132. // 512 by 256 division.
  133. ///////////////////////////////////////////////
  134. // Make division exact by subtracting the remainder from [prod1 prod0].
  135. uint256 remainder;
  136. assembly {
  137. // Compute remainder using mulmod.
  138. remainder := mulmod(x, y, denominator)
  139. // Subtract 256 bit number from 512 bit number.
  140. prod1 := sub(prod1, gt(remainder, prod0))
  141. prod0 := sub(prod0, remainder)
  142. }
  143. // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
  144. // See https://cs.stackexchange.com/q/138556/92363.
  145. // Does not overflow because the denominator cannot be zero at this stage in the function.
  146. uint256 twos = denominator & (~denominator + 1);
  147. assembly {
  148. // Divide denominator by twos.
  149. denominator := div(denominator, twos)
  150. // Divide [prod1 prod0] by twos.
  151. prod0 := div(prod0, twos)
  152. // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
  153. twos := add(div(sub(0, twos), twos), 1)
  154. }
  155. // Shift in bits from prod1 into prod0.
  156. prod0 |= prod1 * twos;
  157. // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
  158. // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
  159. // four bits. That is, denominator * inv = 1 mod 2^4.
  160. uint256 inverse = (3 * denominator) ^ 2;
  161. // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
  162. // in modular arithmetic, doubling the correct bits in each step.
  163. inverse *= 2 - denominator * inverse; // inverse mod 2^8
  164. inverse *= 2 - denominator * inverse; // inverse mod 2^16
  165. inverse *= 2 - denominator * inverse; // inverse mod 2^32
  166. inverse *= 2 - denominator * inverse; // inverse mod 2^64
  167. inverse *= 2 - denominator * inverse; // inverse mod 2^128
  168. inverse *= 2 - denominator * inverse; // inverse mod 2^256
  169. // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
  170. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
  171. // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
  172. // is no longer required.
  173. result = prod0 * inverse;
  174. return result;
  175. }
  176. }
  177. /**
  178. * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
  179. */
  180. function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
  181. uint256 result = mulDiv(x, y, denominator);
  182. if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
  183. result += 1;
  184. }
  185. return result;
  186. }
  187. /**
  188. * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
  189. * towards zero.
  190. *
  191. * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
  192. */
  193. function sqrt(uint256 a) internal pure returns (uint256) {
  194. if (a == 0) {
  195. return 0;
  196. }
  197. // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
  198. //
  199. // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
  200. // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
  201. //
  202. // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
  203. // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
  204. // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
  205. //
  206. // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
  207. uint256 result = 1 << (log2(a) >> 1);
  208. // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
  209. // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
  210. // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
  211. // into the expected uint128 result.
  212. unchecked {
  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. result = (result + a / result) >> 1;
  219. result = (result + a / result) >> 1;
  220. return min(result, a / result);
  221. }
  222. }
  223. /**
  224. * @notice Calculates sqrt(a), following the selected rounding direction.
  225. */
  226. function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
  227. unchecked {
  228. uint256 result = sqrt(a);
  229. return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
  230. }
  231. }
  232. /**
  233. * @dev Return the log in base 2 of a positive value rounded towards zero.
  234. * Returns 0 if given 0.
  235. */
  236. function log2(uint256 value) internal pure returns (uint256) {
  237. uint256 result = 0;
  238. unchecked {
  239. if (value >> 128 > 0) {
  240. value >>= 128;
  241. result += 128;
  242. }
  243. if (value >> 64 > 0) {
  244. value >>= 64;
  245. result += 64;
  246. }
  247. if (value >> 32 > 0) {
  248. value >>= 32;
  249. result += 32;
  250. }
  251. if (value >> 16 > 0) {
  252. value >>= 16;
  253. result += 16;
  254. }
  255. if (value >> 8 > 0) {
  256. value >>= 8;
  257. result += 8;
  258. }
  259. if (value >> 4 > 0) {
  260. value >>= 4;
  261. result += 4;
  262. }
  263. if (value >> 2 > 0) {
  264. value >>= 2;
  265. result += 2;
  266. }
  267. if (value >> 1 > 0) {
  268. result += 1;
  269. }
  270. }
  271. return result;
  272. }
  273. /**
  274. * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
  275. * Returns 0 if given 0.
  276. */
  277. function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
  278. unchecked {
  279. uint256 result = log2(value);
  280. return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
  281. }
  282. }
  283. /**
  284. * @dev Return the log in base 10 of a positive value rounded towards zero.
  285. * Returns 0 if given 0.
  286. */
  287. function log10(uint256 value) internal pure returns (uint256) {
  288. uint256 result = 0;
  289. unchecked {
  290. if (value >= 10 ** 64) {
  291. value /= 10 ** 64;
  292. result += 64;
  293. }
  294. if (value >= 10 ** 32) {
  295. value /= 10 ** 32;
  296. result += 32;
  297. }
  298. if (value >= 10 ** 16) {
  299. value /= 10 ** 16;
  300. result += 16;
  301. }
  302. if (value >= 10 ** 8) {
  303. value /= 10 ** 8;
  304. result += 8;
  305. }
  306. if (value >= 10 ** 4) {
  307. value /= 10 ** 4;
  308. result += 4;
  309. }
  310. if (value >= 10 ** 2) {
  311. value /= 10 ** 2;
  312. result += 2;
  313. }
  314. if (value >= 10 ** 1) {
  315. result += 1;
  316. }
  317. }
  318. return result;
  319. }
  320. /**
  321. * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
  322. * Returns 0 if given 0.
  323. */
  324. function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
  325. unchecked {
  326. uint256 result = log10(value);
  327. return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
  328. }
  329. }
  330. /**
  331. * @dev Return the log in base 256 of a positive value rounded towards zero.
  332. * Returns 0 if given 0.
  333. *
  334. * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
  335. */
  336. function log256(uint256 value) internal pure returns (uint256) {
  337. uint256 result = 0;
  338. unchecked {
  339. if (value >> 128 > 0) {
  340. value >>= 128;
  341. result += 16;
  342. }
  343. if (value >> 64 > 0) {
  344. value >>= 64;
  345. result += 8;
  346. }
  347. if (value >> 32 > 0) {
  348. value >>= 32;
  349. result += 4;
  350. }
  351. if (value >> 16 > 0) {
  352. value >>= 16;
  353. result += 2;
  354. }
  355. if (value >> 8 > 0) {
  356. result += 1;
  357. }
  358. }
  359. return result;
  360. }
  361. /**
  362. * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
  363. * Returns 0 if given 0.
  364. */
  365. function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
  366. unchecked {
  367. uint256 result = log256(value);
  368. return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
  369. }
  370. }
  371. /**
  372. * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
  373. */
  374. function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
  375. return uint8(rounding) % 2 == 1;
  376. }
  377. }