solidity-math-utils 1.2.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,14 +38,14 @@ A library cannot utilize non-constant state variables, nor can it extend (inheri
38
38
  ## IntegralMath
39
39
 
40
40
  This module implements the following interface:
41
- - `function roundDiv(uint256 n, uint256 d)` => `(uint256)`
42
41
  - `function floorLog2(uint256 n)` => `(uint8)`
43
42
  - `function floorSqrt(uint256 n)` => `(uint256)`
44
43
  - `function ceilSqrt(uint256 n)` => `(uint256)`
45
- - `function muldivF(uint256 x, uint256 y, uint256 z)` => `(uint256)`
46
- - `function muldivC(uint256 x, uint256 y, uint256 z)` => `(uint256)`
47
-
48
- Function `roundDiv(n, d)` computes the nearest integer to the quotient of `n / d`.
44
+ - `function floorCbrt(uint256 n)` => `(uint256)`
45
+ - `function ceilCbrt(uint256 n)` => `(uint256)`
46
+ - `function roundDiv(uint256 n, uint256 d)` => `(uint256)`
47
+ - `function mulDivF(uint256 x, uint256 y, uint256 z)` => `(uint256)`
48
+ - `function mulDivC(uint256 x, uint256 y, uint256 z)` => `(uint256)`
49
49
 
50
50
  Function `floorLog2(n)` computes the largest integer smaller than or equal to the binary logarithm of `n`.
51
51
 
@@ -53,11 +53,17 @@ Function `floorSqrt(n)` computes the largest integer smaller than or equal to th
53
53
 
54
54
  Function `ceilSqrt(n)` computes the smallest integer larger than or equal to the square root of `n`.
55
55
 
56
- Function `muldivF(x, y, z)` computes the largest integer smaller than or equal to `x * y / z`.
56
+ Function `floorCbrt(n)` computes the largest integer smaller than or equal to the cubic root of `n`.
57
+
58
+ Function `ceilCbrt(n)` computes the smallest integer larger than or equal to the cubic root of `n`.
59
+
60
+ Function `roundDiv(n, d)` computes the nearest integer to the quotient of `n` and `d` (or `n / d`).
57
61
 
58
- Function `muldivC(x, y, z)` computes the smallest integer larger than or equal to `x * y / z`.
62
+ Function `mulDivF(x, y, z)` computes the largest integer smaller than or equal to `x * y / z`.
59
63
 
60
- Note that function `muldivF` and function `muldivC` revert when the **actual** result is larger than 256 bits.
64
+ Function `mulDivC(x, y, z)` computes the smallest integer larger than or equal to `x * y / z`.
65
+
66
+ Note that function `mulDivF` and function `mulDivC` revert when the **actual** result is larger than 256 bits.
61
67
 
62
68
  Note that function `floorSqrt` and function `ceilSqrt` are guaranteed to return the correct output for every input.
63
69
 
@@ -65,6 +71,12 @@ However, when compared with the **actual** square root, smaller input generally
65
71
 
66
72
  For example, `floorSqrt(3)` returns 1, but the actual square root of 3 is ~1.73, which yields a relative accuracy of only ~57%.
67
73
 
74
+ Note that function `floorCbrt` and function `ceilCbrt` are guaranteed to return the correct output for every input.
75
+
76
+ However, when compared with the **actual** cubic root, smaller input generally yields relatively lower accuracy of the output.
77
+
78
+ For example, `floorCbrt(7)` returns 1, but the actual cubic root of 7 is ~1.91, which yields a relative accuracy of only ~52%.
79
+
68
80
  <br/><br/>
69
81
 
70
82
  ---
@@ -74,33 +86,33 @@ For example, `floorSqrt(3)` returns 1, but the actual square root of 3 is ~1.73,
74
86
  ## FractionMath
75
87
 
76
88
  This module implements the following interface:
77
- - `function normalizedRatio(uint256 n, uint256 d, uint256 scale)` => `(uint256, uint256)`
89
+ - `function poweredRatio(uint256 n, uint256 d, uint256 exp, bool fast)` => `(uint256, uint256)`
90
+ - `function productRatio(uint256 xn, uint256 yn, uint256 xd, uint256 yd)` => `(uint256, uint256)`
78
91
  - `function reducedRatio(uint256 n, uint256 d, uint256 max)` => `(uint256, uint256)`
79
- - `function poweredRatio(uint256 n, uint256 d, uint256 exp)` => `(uint256, uint256)`
80
- - `function productRatio(uint256 n1, uint256 n2, uint256 d1, uint256 d2)` => `(uint256, uint256)`
92
+ - `function normalizedRatio(uint256 n, uint256 d, uint256 scale)` => `(uint256, uint256)`
81
93
 
82
- ### Normalized Ratio
94
+ ### Powered Ratio
83
95
 
84
- Function `normalizedRatio` computes the nearest ratio whose sum of components (numerator + denominator) equals the input scale.
96
+ Function `poweredRatio` computes the power of a given ratio by a given exponent.
85
97
 
86
- Note that the output ratio can be larger than the input ratio in some cases, and smaller than the input ratio in other cases.
98
+ In order to avoid multiplication overflow, it may truncate the intermediate result on each iteration.
87
99
 
88
- For example:
89
- - `normalizedRatio(12, 34, 100)` returns `(26 74)`; the output ratio is smaller than the input ratio (26 / 74 = 0.351 < 0.352 = 12 / 34)
90
- - `normalizedRatio(1234, 5678, 100)` returns `(18 82)`; the output ratio is larger than the input ratio (18 / 82 = 0.219 > 0.217 = 1234 / 5678)
100
+ Subsequently, the larger the input exponent is, the lower the accuracy of the output is likely to be.
91
101
 
92
- Keep in mind that it is an important consideration to take when choosing to use this function.
102
+ The input argument `fast` allows to opt for either performance (using `true`) or accuracy (using `false`).
93
103
 
94
- For example, when designing a sustainable financial model, it is imperative to never entitle more than the actual entitlement.
104
+ This library defines a maximum exponent of 4 bits (i.e., 15), which can be customized to fit the system requirements.
105
+
106
+ ### Product Ratio
95
107
 
96
- The same consideration applies for all the other functions in this module, since each one of them uses this function internally.
108
+ Function `productRatio` computes the product of two ratios as a single ratio whose components are not larger than 256 bits.
109
+
110
+ If either one of the intermediate components is larger than 256 bits, then both of them are reduced based on the larger one.
97
111
 
98
112
  ### Reduced Ratio
99
113
 
100
114
  Function `reducedRatio` computes the nearest ratio whose components (numerator and denominator) are not larger than the input threshold.
101
115
 
102
- Internally, it calls function `normalizedRatio` with the input threshold, but only if one of the components is larger than that threshold.
103
-
104
116
  Note that function `reducedRatio` is not meant to replace GCD, nor does it strive to achieve better accuracy.
105
117
 
106
118
  GCD is not being used here, because the time-complexity of this method depends on the bit-length of the input.
@@ -113,19 +125,21 @@ Reducing an input ratio by its GCD in advance (at your own expense) can most cer
113
125
 
114
126
  However, without knowing specific characteristics of that ratio (e.g., each one of its components is a multiple of `0x1000`), doing so is generally useless.
115
127
 
116
- ### Powered Ratio
128
+ ### Normalized Ratio
117
129
 
118
- Function `poweredRatio` computes the power of a given ratio by a given exponent.
130
+ Function `normalizedRatio` computes the nearest ratio whose sum of components (numerator + denominator) equals the input scale.
119
131
 
120
- Note that this function uses `reducedRatio(n, d, MAX_UINT128)` internally, in order to avoid multiplication overflow.
132
+ Note that the output ratio can be larger than the input ratio in some cases, and smaller than the input ratio in other cases.
121
133
 
122
- Subsequently, the larger the input exponent is, the lower the accuracy of the output is.
134
+ For example:
135
+ - `normalizedRatio(12, 34, 100)` returns `(26 74)`; the output ratio is smaller than the input ratio (26 / 74 = 0.351 < 0.352 = 12 / 34)
136
+ - `normalizedRatio(1234, 5678, 100)` returns `(18 82)`; the output ratio is larger than the input ratio (18 / 82 = 0.219 > 0.217 = 1234 / 5678)
123
137
 
124
- This library defines a maximum exponent of 4 bits (i.e., 15), which can be customized to fit the system requirements.
138
+ Keep in mind that it is an important consideration to take when choosing to use this function.
125
139
 
126
- ### Product Ratio
140
+ For example, when designing a sustainable financial model, it is imperative to never entitle more than the actual entitlement.
127
141
 
128
- Function `productRatio` computes the product of two ratios as a single ratio.
142
+ The same consideration applies for all the other functions in this module.
129
143
 
130
144
  <br/><br/>
131
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solidity-math-utils",
3
- "version": "1.2.2",
3
+ "version": "1.5.0",
4
4
  "description": "Solidity Mathematical Utilities",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,9 +17,9 @@
17
17
  "verify": "truffle run coverage"
18
18
  },
19
19
  "devDependencies": {
20
- "decimal.js": "10.2.1",
20
+ "decimal.js": "10.3.1",
21
21
  "solidity-coverage": "0.7.16",
22
- "truffle": "5.3.5",
23
- "web3": "1.3.5"
22
+ "truffle": "5.4.0",
23
+ "web3": "1.4.0"
24
24
  }
25
25
  }
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.10;
3
3
 
4
4
  import "./AnalyticMath.sol";
5
5
  import "./FractionMath.sol";
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.10;
3
3
 
4
4
  import "./IntegralMath.sol";
5
5
 
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.10;
3
3
 
4
4
  import "./AnalyticMath.sol";
5
5
 
@@ -26,10 +26,10 @@ contract BondingCurve is AnalyticMath {
26
26
  return 0;
27
27
 
28
28
  if (weight == MAX_WEIGHT)
29
- return mulDivF(amount, supply, balance);
29
+ return IntegralMath.mulDivF(amount, supply, balance);
30
30
 
31
- (uint256 n, uint256 d) = pow(add(balance, amount), balance, weight, MAX_WEIGHT);
32
- return mulDivF(supply, n, d) - supply;
31
+ (uint256 n, uint256 d) = pow(safeAdd(balance, amount), balance, weight, MAX_WEIGHT);
32
+ return IntegralMath.mulDivF(supply, n, d) - supply;
33
33
  }}
34
34
 
35
35
  /**
@@ -55,10 +55,10 @@ contract BondingCurve is AnalyticMath {
55
55
  return balance;
56
56
 
57
57
  if (weight == MAX_WEIGHT)
58
- return mulDivF(amount, balance, supply);
58
+ return IntegralMath.mulDivF(amount, balance, supply);
59
59
 
60
60
  (uint256 n, uint256 d) = pow(supply, supply - amount, MAX_WEIGHT, weight);
61
- return mulDivF(balance, n - d, n);
61
+ return IntegralMath.mulDivF(balance, n - d, n);
62
62
  }}
63
63
 
64
64
  /**
@@ -79,10 +79,10 @@ contract BondingCurve is AnalyticMath {
79
79
  require(MIN_WEIGHT <= weight2 && weight2 <= MAX_WEIGHT, "invalid target weight");
80
80
 
81
81
  if (weight1 == weight2)
82
- return mulDivF(balance2, amount, add(balance1, amount));
82
+ return IntegralMath.mulDivF(balance2, amount, safeAdd(balance1, amount));
83
83
 
84
- (uint256 n, uint256 d) = pow(add(balance1, amount), balance1, weight1, weight2);
85
- return mulDivF(balance2, n - d, n);
84
+ (uint256 n, uint256 d) = pow(safeAdd(balance1, amount), balance1, weight1, weight2);
85
+ return IntegralMath.mulDivF(balance2, n - d, n);
86
86
  }}
87
87
 
88
88
  /**
@@ -104,10 +104,10 @@ contract BondingCurve is AnalyticMath {
104
104
  return 0;
105
105
 
106
106
  if (weights == MAX_WEIGHT)
107
- return mulDivF(amount, supply, balance);
107
+ return IntegralMath.mulDivF(amount, supply, balance);
108
108
 
109
- (uint256 n, uint256 d) = pow(add(balance, amount), balance, weights, MAX_WEIGHT);
110
- return mulDivF(supply, n, d) - supply;
109
+ (uint256 n, uint256 d) = pow(safeAdd(balance, amount), balance, weights, MAX_WEIGHT);
110
+ return IntegralMath.mulDivF(supply, n, d) - supply;
111
111
  }}
112
112
 
113
113
  /**
@@ -133,10 +133,10 @@ contract BondingCurve is AnalyticMath {
133
133
  return balance;
134
134
 
135
135
  if (weights == MAX_WEIGHT)
136
- return mulDivF(amount, balance, supply);
136
+ return IntegralMath.mulDivF(amount, balance, supply);
137
137
 
138
138
  (uint256 n, uint256 d) = pow(supply, supply - amount, MAX_WEIGHT, weights);
139
- return mulDivF(balance, n - d, n);
139
+ return IntegralMath.mulDivF(balance, n - d, n);
140
140
  }}
141
141
 
142
142
  /**
@@ -158,24 +158,9 @@ contract BondingCurve is AnalyticMath {
158
158
  return 0;
159
159
 
160
160
  if (weights == MAX_WEIGHT)
161
- return mulDivC(amount, balance, supply);
161
+ return IntegralMath.mulDivC(amount, balance, supply);
162
162
 
163
- (uint256 n, uint256 d) = pow(add(supply, amount), supply, MAX_WEIGHT, weights);
164
- return mulDivC(balance, n, d) - balance;
163
+ (uint256 n, uint256 d) = pow(safeAdd(supply, amount), supply, MAX_WEIGHT, weights);
164
+ return IntegralMath.mulDivC(balance, n, d) - balance;
165
165
  }}
166
-
167
- // auxiliary function
168
- function add(uint256 x, uint256 y) private pure returns (uint256) {
169
- return Uint.safeAdd(x, y);
170
- }
171
-
172
- // auxiliary function
173
- function mulDivF(uint256 x, uint256 y, uint256 z) private pure returns (uint256) {
174
- return IntegralMath.mulDivF(x, y, z);
175
- }
176
-
177
- // auxiliary function
178
- function mulDivC(uint256 x, uint256 y, uint256 z) private pure returns (uint256) {
179
- return IntegralMath.mulDivC(x, y, z);
180
- }
181
166
  }
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.10;
3
3
 
4
4
  import "./AdvancedMath.sol";
5
5
 
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.10;
3
3
 
4
4
  import "./IntegralMath.sol";
5
5
 
@@ -8,132 +8,147 @@ library FractionMath {
8
8
 
9
9
  uint256 internal constant MAX_EXP_BIT_LEN = 4;
10
10
  uint256 internal constant MAX_EXP = 2 ** MAX_EXP_BIT_LEN - 1;
11
- uint256 internal constant MAX_UINT128 = 2 ** 128 - 1;
12
- uint256 internal constant MAX_UINT256 = 2 ** 256 - 1;
13
-
14
- /**
15
- * @dev Compute the product of two given ratios
16
- *
17
- * @param xn The 1st ratio numerator
18
- * @param yn The 2nd ratio numerator
19
- * @param xd The 1st ratio denominator
20
- * @param yd The 2nd ratio denominator
21
- *
22
- * @return The product ratio numerator
23
- * @return The product ratio denominator
24
- */
25
- function productRatio(uint256 xn, uint256 yn, uint256 xd, uint256 yd) internal pure returns (uint256, uint256) { unchecked {
26
- uint256 n = IntegralMath.mulDivC(xn, yn, MAX_UINT256);
27
- uint256 d = IntegralMath.mulDivC(xd, yd, MAX_UINT256);
28
- uint256 z = n > d ? n : d;
29
- if (z > 1)
30
- return (IntegralMath.mulDivC(xn, yn, z), IntegralMath.mulDivC(xd, yd, z));
31
- return (xn * yn, xd * yd);
32
- }}
11
+ uint256 internal constant MAX_UINT128 = type(uint128).max;
33
12
 
34
13
  /**
35
14
  * @dev Compute the power of a given ratio
36
15
  *
37
- * @param baseN The ratio numerator
38
- * @param baseD The ratio denominator
39
- * @param exp The exponentiation value
16
+ * @param n The ratio numerator
17
+ * @param d The ratio denominator
18
+ * @param exp The exponentiation value
19
+ * @param fast Opt for performance over accuracy
40
20
  *
41
21
  * @return The powered ratio numerator
42
22
  * @return The powered ratio denominator
43
23
  */
44
- function poweredRatio(uint256 baseN, uint256 baseD, uint256 exp) internal pure returns (uint256, uint256) { unchecked {
24
+ function poweredRatio(uint256 n, uint256 d, uint256 exp, bool fast) internal pure returns (uint256, uint256) { unchecked {
45
25
  require(exp <= MAX_EXP, "exp too large");
46
26
 
27
+ function (uint256, uint256, uint256, uint256) pure returns (uint256, uint256) safeRatio = fast ? mulRatio128 : productRatio;
28
+
47
29
  uint256[MAX_EXP_BIT_LEN] memory ns;
48
30
  uint256[MAX_EXP_BIT_LEN] memory ds;
49
31
 
50
- (ns[0], ds[0]) = reducedRatio(baseN, baseD, MAX_UINT128);
32
+ (ns[0], ds[0]) = safeRatio(n, 1, d, 1);
51
33
  for (uint256 i = 0; (exp >> i) > 1; ++i) {
52
- (ns[i + 1], ds[i + 1]) = reducedRatio(ns[i] ** 2, ds[i] ** 2, MAX_UINT128);
34
+ (ns[i + 1], ds[i + 1]) = safeRatio(ns[i], ns[i], ds[i], ds[i]);
53
35
  }
54
36
 
55
- uint256 n = 1;
56
- uint256 d = 1;
37
+ n = 1;
38
+ d = 1;
57
39
 
58
40
  for (uint256 i = 0; (exp >> i) > 0; ++i) {
59
41
  if (((exp >> i) & 1) > 0) {
60
- (n, d) = reducedRatio(n * ns[i], d * ds[i], MAX_UINT128);
42
+ (n, d) = safeRatio(n, ns[i], d, ds[i]);
61
43
  }
62
44
  }
63
45
 
64
- // TODO: improve `productRatio` and use it here instead of `reducedRatio`
65
46
  return (n, d);
66
47
  }}
67
48
 
49
+ /**
50
+ * @dev Compute the product of two given ratios
51
+ *
52
+ * @param xn The 1st ratio numerator
53
+ * @param yn The 2nd ratio numerator
54
+ * @param xd The 1st ratio denominator
55
+ * @param yd The 2nd ratio denominator
56
+ *
57
+ * @return The product ratio numerator
58
+ * @return The product ratio denominator
59
+ */
60
+ function productRatio(uint256 xn, uint256 yn, uint256 xd, uint256 yd) internal pure returns (uint256, uint256) { unchecked {
61
+ uint256 n = IntegralMath.mulDivC(xn, yn, MAX_VAL);
62
+ uint256 d = IntegralMath.mulDivC(xd, yd, MAX_VAL);
63
+ uint256 z = n > d ? n : d;
64
+ if (z > 1) {
65
+ return (IntegralMath.mulDivC(xn, yn, z), IntegralMath.mulDivC(xd, yd, z));
66
+ }
67
+ return (xn * yn, xd * yd);
68
+ }}
69
+
68
70
  /**
69
71
  * @dev Reduce the components of a given ratio
70
72
  *
71
- * @param baseN The ratio numerator
72
- * @param baseD The ratio denominator
73
- * @param max The maximum desired value
73
+ * @param n The ratio numerator
74
+ * @param d The ratio denominator
75
+ * @param max The maximum desired value
74
76
  *
75
77
  * @return The reduced ratio numerator
76
78
  * @return The reduced ratio denominator
77
79
  */
78
- function reducedRatio(uint256 baseN, uint256 baseD, uint256 max) internal pure returns (uint256, uint256) { unchecked {
79
- if (baseN > max || baseD > max) {
80
- return normalizedRatio(baseN, baseD, max);
81
- }
82
- return (baseN, baseD);
80
+ function reducedRatio(uint256 n, uint256 d, uint256 max) internal pure returns (uint256, uint256) { unchecked {
81
+ uint256 scale = ((n > d ? n : d) - 1) / max + 1;
82
+ return (n / scale, d / scale);
83
83
  }}
84
84
 
85
85
  /**
86
86
  * @dev Compute a normalized ratio as `scale * n / (n + d)` and `scale * d / (n + d)`
87
87
  *
88
- * @param baseN The ratio numerator
89
- * @param baseD The ratio denominator
88
+ * @param n The ratio numerator
89
+ * @param d The ratio denominator
90
90
  * @param scale The desired scale
91
91
  *
92
92
  * @return The normalized ratio numerator
93
93
  * @return The normalized ratio denominator
94
94
  */
95
- function normalizedRatio(uint256 baseN, uint256 baseD, uint256 scale) internal pure returns (uint256, uint256) { unchecked {
96
- if (baseN <= baseD) {
97
- return accurateRatio(baseN, baseD, scale);
95
+ function normalizedRatio(uint256 n, uint256 d, uint256 scale) internal pure returns (uint256, uint256) { unchecked {
96
+ if (n <= d) {
97
+ return estimatedRatio(n, d, scale);
98
98
  }
99
- (uint256 d, uint256 n) = accurateRatio(baseD, baseN, scale);
99
+ (d, n) = estimatedRatio(d, n, scale);
100
100
  return (n, d);
101
101
  }}
102
102
 
103
103
  /**
104
- * @dev Compute a normalized ratio as `scale * n / (n + d)` and `scale * d / (n + d)`, assuming that `n <= d`
104
+ * @dev Compute an estimated ratio as `scale * n / (n + d)` and `scale * d / (n + d)`, assuming that `n <= d`
105
105
  *
106
- * @param baseN The ratio numerator
107
- * @param baseD The ratio denominator
106
+ * @param n The ratio numerator
107
+ * @param d The ratio denominator
108
108
  * @param scale The desired scale
109
109
  *
110
- * @return The normalized ratio numerator
111
- * @return The normalized ratio denominator
110
+ * @return The estimated ratio numerator
111
+ * @return The estimated ratio denominator
112
112
  */
113
- function accurateRatio(uint256 baseN, uint256 baseD, uint256 scale) private pure returns (uint256, uint256) { unchecked {
114
- uint256 maxVal = MAX_UINT256 / scale; // `MAX_UINT256 >= scale` hence `maxVal >= 1`
115
- if (maxVal < baseN) {
116
- // `maxVal < baseN <= MAX_UINT256` hence `maxVal < MAX_UINT256` hence `maxVal + 1` is safe
117
- // `maxVal + 1 >= 2` hence `baseN / (maxVal + 1) < MAX_UINT256` hence `baseN / (maxVal + 1) + 1` is safe
118
- uint256 c = baseN / (maxVal + 1) + 1;
119
- baseN /= c; // we can now safely compute `baseN * scale`
120
- baseD /= c;
113
+ function estimatedRatio(uint256 n, uint256 d, uint256 scale) private pure returns (uint256, uint256) { unchecked {
114
+ uint256 x = MAX_VAL / scale; // `MAX_VAL >= scale` hence `x >= 1`
115
+ if (x < n) {
116
+ // `x < n <= MAX_VAL` hence `x < MAX_VAL` hence `x + 1` is safe
117
+ // `x >= 1` hence `n / (x + 1) < MAX_VAL` hence `n / (x + 1) + 1` is safe
118
+ uint256 y = n / (x + 1) + 1;
119
+ n /= y; // we can now safely compute `n * scale`
120
+ d /= y;
121
121
  }
122
122
 
123
- if (baseN != baseD) {
124
- uint256 n = baseN * scale;
125
- uint256 d = Uint.unsafeAdd(baseN, baseD); // `baseN + baseD` can overflow
126
- if (d >= baseN) {
127
- // `baseN + baseD` did not overflow
128
- uint256 x = IntegralMath.roundDiv(n, d); // we can now safely compute `scale - x`
129
- uint256 y = scale - x;
130
- return (x, y);
123
+ if (n < d) {
124
+ uint256 p = n * scale;
125
+ uint256 q = unsafeAdd(n, d); // `n + d` can overflow
126
+ if (q >= n) {
127
+ // `n + d` did not overflow
128
+ uint256 r = IntegralMath.roundDiv(p, q);
129
+ return (r, scale - r); // `r = n * scale / (n + d) < scale`
131
130
  }
132
- if (n < baseD - (baseD - baseN) / 2) {
133
- return (0, scale); // `baseN * scale < (baseN + baseD) / 2 < MAX_UINT256 < baseN + baseD`
131
+ if (p < d - (d - n) / 2) {
132
+ return (0, scale); // `n * scale < (n + d) / 2 < MAX_VAL < n + d`
134
133
  }
135
- return (1, scale - 1); // `(baseN + baseD) / 2 < baseN * scale < MAX_UINT256 < baseN + baseD`
134
+ return (1, scale - 1); // `(n + d) / 2 < n * scale < MAX_VAL < n + d`
136
135
  }
137
- return (scale / 2, scale - scale / 2); // reflect the fact that `baseN <= baseD` at the beginning
136
+ return (scale / 2, scale - scale / 2); // reflect the fact that initially `n <= d`
137
+ }}
138
+
139
+ /**
140
+ * @dev Compute the product of two ratios and reduce the components of the result to 128 bits,
141
+ * under the implicit assumption that the components of the product are not larger than 256 bits
142
+ *
143
+ * @param xn The 1st ratio numerator
144
+ * @param yn The 2nd ratio numerator
145
+ * @param xd The 1st ratio denominator
146
+ * @param yd The 2nd ratio denominator
147
+ *
148
+ * @return The product ratio numerator
149
+ * @return The product ratio denominator
150
+ */
151
+ function mulRatio128(uint256 xn, uint256 yn, uint256 xd, uint256 yd) private pure returns (uint256, uint256) { unchecked {
152
+ return reducedRatio(xn * yn, xd * yd, MAX_UINT128);
138
153
  }}
139
154
  }
@@ -1,18 +1,9 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.10;
3
3
 
4
4
  import "./common/Uint.sol";
5
5
 
6
6
  library IntegralMath {
7
- using Uint for *;
8
-
9
- /**
10
- * @dev Compute the nearest integer to the quotient of `n / d`
11
- */
12
- function roundDiv(uint256 n, uint256 d) internal pure returns (uint256) { unchecked {
13
- return n / d + (n % d) / (d - d / 2);
14
- }}
15
-
16
7
  /**
17
8
  * @dev Compute the largest integer smaller than or equal to the binary logarithm of `n`
18
9
  */
@@ -60,7 +51,38 @@ library IntegralMath {
60
51
  */
61
52
  function ceilSqrt(uint256 n) internal pure returns (uint256) { unchecked {
62
53
  uint256 x = floorSqrt(n);
63
- return x * x == n ? x : x + 1;
54
+ return x ** 2 == n ? x : x + 1;
55
+ }}
56
+
57
+ /**
58
+ * @dev Compute the largest integer smaller than or equal to the cubic root of `n`
59
+ */
60
+ function floorCbrt(uint256 n) internal pure returns (uint256) { unchecked {
61
+ uint256 x = 0;
62
+ for (uint256 y = 1 << 255; y > 0; y >>= 3) {
63
+ x <<= 1;
64
+ uint256 z = 3 * x * (x + 1) + 1;
65
+ if (n / y >= z) {
66
+ n -= y * z;
67
+ x += 1;
68
+ }
69
+ }
70
+ return x;
71
+ }}
72
+
73
+ /**
74
+ * @dev Compute the smallest integer larger than or equal to the cubic root of `n`
75
+ */
76
+ function ceilCbrt(uint256 n) internal pure returns (uint256) { unchecked {
77
+ uint256 x = floorCbrt(n);
78
+ return x ** 3 == n ? x : x + 1;
79
+ }}
80
+
81
+ /**
82
+ * @dev Compute the nearest integer to the quotient of `n` and `d` (or `n / d`)
83
+ */
84
+ function roundDiv(uint256 n, uint256 d) internal pure returns (uint256) { unchecked {
85
+ return n / d + (n % d) / (d - d / 2);
64
86
  }}
65
87
 
66
88
  /**
@@ -68,9 +90,21 @@ library IntegralMath {
68
90
  */
69
91
  function mulDivF(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) { unchecked {
70
92
  (uint256 xyh, uint256 xyl) = mul512(x, y);
71
- if (xyh > 0)
72
- return div512(xyh, xyl, z);
73
- return xyl / z;
93
+ if (xyh == 0) { // `x * y < 2 ^ 256`
94
+ return xyl / z;
95
+ }
96
+ if (xyh < z) { // `x * y / z < 2 ^ 256`
97
+ uint256 m = mulMod(x, y, z); // `m = x * y % z`
98
+ (uint256 nh, uint256 nl) = sub512(xyh, xyl, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
99
+ if (nh == 0) { // `n < 2 ^ 256`
100
+ return nl / z;
101
+ }
102
+ uint256 p = unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
103
+ uint256 q = div512(nh, nl, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
104
+ uint256 r = inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
105
+ return unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
106
+ }
107
+ revert(); // `x * y / z >= 2 ^ 256`
74
108
  }}
75
109
 
76
110
  /**
@@ -78,8 +112,8 @@ library IntegralMath {
78
112
  */
79
113
  function mulDivC(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) { unchecked {
80
114
  uint256 w = mulDivF(x, y, z);
81
- if (Uint.mulMod(x, y, z) > 0)
82
- return Uint.safeAdd(w, 1);
115
+ if (mulMod(x, y, z) > 0)
116
+ return safeAdd(w, 1);
83
117
  return w;
84
118
  }}
85
119
 
@@ -87,42 +121,38 @@ library IntegralMath {
87
121
  * @dev Compute the value of `x * y`
88
122
  */
89
123
  function mul512(uint256 x, uint256 y) private pure returns (uint256, uint256) { unchecked {
90
- uint256 p = Uint.mulModMax(x, y);
91
- uint256 q = Uint.unsafeMul(x, y);
124
+ uint256 p = mulModMax(x, y);
125
+ uint256 q = unsafeMul(x, y);
92
126
  if (p >= q)
93
127
  return (p - q, q);
94
- return (Uint.unsafeSub(p, q) - 1, q);
128
+ return (unsafeSub(p, q) - 1, q);
95
129
  }}
96
130
 
97
131
  /**
98
- * @dev Compute the largest integer smaller than or equal to `(2 ^ 256 * xh + xl) / y`
132
+ * @dev Compute the value of `2 ^ 256 * xh + xl - y`, where `2 ^ 256 * xh + xl >= y`
99
133
  */
100
- function div512(uint256 xh, uint256 xl, uint256 y) private pure returns (uint256) { unchecked {
101
- require(xh < y);
102
- uint256 result = 0;
103
- uint256 length = 255 - floorLog2(y);
104
- while (xh > 0) {
105
- uint256 bits = floorLog2(xh) + length;
106
- result += 1 << bits;
107
- (uint256 yh, uint256 yl) = shl512(y, bits);
108
- (xh, xl) = sub512(xh, xl, yh, yl);
109
- }
110
- return result + xl / y;
134
+ function sub512(uint256 xh, uint256 xl, uint256 y) private pure returns (uint256, uint256) { unchecked {
135
+ if (xl >= y)
136
+ return (xh, xl - y);
137
+ return (xh - 1, unsafeSub(xl, y));
111
138
  }}
112
139
 
113
140
  /**
114
- * @dev Compute the value of `x * 2 ^ y`
141
+ * @dev Compute the value of `(2 ^ 256 * xh + xl) / pow2n`, where `xl` is divisible by `pow2n`
115
142
  */
116
- function shl512(uint256 x, uint256 y) private pure returns (uint256, uint256) { unchecked {
117
- return (x >> (256 - y), Uint.unsafeShl(x, y));
143
+ function div512(uint256 xh, uint256 xl, uint256 pow2n) private pure returns (uint256) { unchecked {
144
+ uint256 pow2nInv = unsafeAdd(unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
145
+ return unsafeMul(xh, pow2nInv) | (xl / pow2n); // `(xh << (256 - n)) | (xl >> n)`
118
146
  }}
119
147
 
120
148
  /**
121
- * @dev Compute the value of `2 ^ 256 * xh + xl - 2 ^ 256 * yh - yl`
149
+ * @dev Compute the inverse of `d` modulo `2 ^ 256`, where `d` is congruent to `1` modulo `2`
122
150
  */
123
- function sub512(uint256 xh, uint256 xl, uint256 yh, uint256 yl) private pure returns (uint256, uint256) { unchecked {
124
- if (xl >= yl)
125
- return (xh - yh, xl - yl);
126
- return (xh - yh - 1, Uint.unsafeSub(xl, yl));
151
+ function inv256(uint256 d) private pure returns (uint256) { unchecked {
152
+ // approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
153
+ uint256 x = 1;
154
+ for (uint256 i = 0; i < 8; ++i)
155
+ x = unsafeMul(x, unsafeSub(2, unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
156
+ return x;
127
157
  }}
128
158
  }