solidity-math-utils 1.3.0 → 1.6.1

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
@@ -41,9 +41,11 @@ This module implements the following interface:
41
41
  - `function floorLog2(uint256 n)` => `(uint8)`
42
42
  - `function floorSqrt(uint256 n)` => `(uint256)`
43
43
  - `function ceilSqrt(uint256 n)` => `(uint256)`
44
+ - `function floorCbrt(uint256 n)` => `(uint256)`
45
+ - `function ceilCbrt(uint256 n)` => `(uint256)`
44
46
  - `function roundDiv(uint256 n, uint256 d)` => `(uint256)`
45
- - `function muldivF(uint256 x, uint256 y, uint256 z)` => `(uint256)`
46
- - `function muldivC(uint256 x, uint256 y, uint256 z)` => `(uint256)`
47
+ - `function mulDivF(uint256 x, uint256 y, uint256 z)` => `(uint256)`
48
+ - `function mulDivC(uint256 x, uint256 y, uint256 z)` => `(uint256)`
47
49
 
48
50
  Function `floorLog2(n)` computes the largest integer smaller than or equal to the binary logarithm of `n`.
49
51
 
@@ -51,13 +53,17 @@ Function `floorSqrt(n)` computes the largest integer smaller than or equal to th
51
53
 
52
54
  Function `ceilSqrt(n)` computes the smallest integer larger than or equal to the square root of `n`.
53
55
 
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
+
54
60
  Function `roundDiv(n, d)` computes the nearest integer to the quotient of `n` and `d` (or `n / d`).
55
61
 
56
- Function `muldivF(x, y, z)` computes the largest integer smaller 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`.
57
63
 
58
- Function `muldivC(x, y, z)` computes the smallest integer larger than or equal to `x * y / z`.
64
+ Function `mulDivC(x, y, z)` computes the smallest integer larger than or equal to `x * y / z`.
59
65
 
60
- Note that function `muldivF` and function `muldivC` revert when the **actual** result is larger than 256 bits.
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)`
78
- - `function reducedRatio(uint256 n, uint256 d, uint256 max)` => `(uint256, uint256)`
79
- - `function productRatio(uint256 n1, uint256 n2, uint256 d1, uint256 d2)` => `(uint256, uint256)`
80
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)`
91
+ - `function reducedRatio(uint256 n, uint256 d, uint256 max)` => `(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
107
+
108
+ Function `productRatio` computes the product of two ratios as a single ratio whose components are not larger than 256 bits.
95
109
 
96
- The same consideration applies for all the other functions in this module, since each one of them uses this function internally.
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,23 +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
- ### Product Ratio
117
-
118
- Function `productRatio` computes the product of two ratios as a single ratio whose components are not larger than 256 bits.
119
-
120
- If either one of the intermediate components is larger than 256 bits, then both of them are reduced based on the larger one.
128
+ ### Normalized Ratio
121
129
 
122
- ### Powered Ratio
130
+ Function `normalizedRatio` computes the nearest ratio whose sum of components (numerator + denominator) equals the input scale.
123
131
 
124
- Function `poweredRatio` computes the power of a given ratio by a given exponent.
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.
125
133
 
126
- In order to avoid multiplication overflow, it may truncate the intermediate result on each iteration.
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)
127
137
 
128
- Subsequently, the larger the input exponent is, the lower the accuracy of the output is likely to be.
138
+ Keep in mind that it is an important consideration to take when choosing to use this function.
129
139
 
130
- The input argument `fast` allows to opt for either accuracy (using `false`) or performance (using `true`).
140
+ For example, when designing a sustainable financial model, it is imperative to never entitle more than the actual entitlement.
131
141
 
132
- This library defines a maximum exponent of 4 bits (i.e., 15), which can be customized to fit the system requirements.
142
+ The same consideration applies for all the other functions in this module.
133
143
 
134
144
  <br/><br/>
135
145
 
@@ -335,8 +345,8 @@ The dynamic-curve method was conceived by [Bancor](https://github.com/bancorprot
335
345
 
336
346
  ### Prerequisites
337
347
 
338
- - `node 12.20.0`
339
- - `yarn 1.22.10` or `npm 7.12.0`
348
+ - `node 16.13.0`
349
+ - `yarn 1.22.10` or `npm 8.1.0`
340
350
 
341
351
  ### Installation
342
352
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solidity-math-utils",
3
- "version": "1.3.0",
3
+ "version": "1.6.1",
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",
21
- "solidity-coverage": "0.7.16",
22
- "truffle": "5.3.5",
23
- "web3": "1.3.5"
20
+ "decimal.js": "10.3.1",
21
+ "solidity-coverage": "0.7.18",
22
+ "truffle": "5.4.32",
23
+ "web3": "1.7.0"
24
24
  }
25
25
  }
@@ -1,12 +1,10 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.11;
3
3
 
4
4
  import "./AnalyticMath.sol";
5
5
  import "./FractionMath.sol";
6
6
 
7
7
  contract AdvancedMath is AnalyticMath {
8
- using FractionMath for *;
9
-
10
8
  // Auto-generated via 'PrintLambertFactors.py'
11
9
  uint256 internal constant LAMBERT_CONV_RADIUS = 0x002f16ac6c59de6f8d5d6f63c1482a7c86;
12
10
  uint256 internal constant LAMBERT_POS2_SAMPLE = 0x0003060c183060c183060c183060c18306;
@@ -1,11 +1,9 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.11;
3
3
 
4
4
  import "./IntegralMath.sol";
5
5
 
6
6
  contract AnalyticMath {
7
- using IntegralMath for *;
8
-
9
7
  uint8 internal constant MIN_PRECISION = 32;
10
8
  uint8 internal constant MAX_PRECISION = 127;
11
9
 
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.11;
3
3
 
4
4
  import "./AnalyticMath.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.11;
3
3
 
4
4
  import "./AdvancedMath.sol";
5
5
 
@@ -1,11 +1,9 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.11;
3
3
 
4
4
  import "./IntegralMath.sol";
5
5
 
6
6
  library FractionMath {
7
- using IntegralMath for *;
8
-
9
7
  uint256 internal constant MAX_EXP_BIT_LEN = 4;
10
8
  uint256 internal constant MAX_EXP = 2 ** MAX_EXP_BIT_LEN - 1;
11
9
  uint256 internal constant MAX_UINT128 = type(uint128).max;
@@ -13,15 +11,15 @@ library FractionMath {
13
11
  /**
14
12
  * @dev Compute the power of a given ratio
15
13
  *
16
- * @param baseN The ratio numerator
17
- * @param baseD The ratio denominator
18
- * @param exp The exponentiation value
19
- * @param fast Opt for accuracy or performance
14
+ * @param n The ratio numerator
15
+ * @param d The ratio denominator
16
+ * @param exp The exponentiation value
17
+ * @param fast Opt for performance over accuracy
20
18
  *
21
19
  * @return The powered ratio numerator
22
20
  * @return The powered ratio denominator
23
21
  */
24
- function poweredRatio(uint256 baseN, uint256 baseD, uint256 exp, bool fast) internal pure returns (uint256, uint256) { unchecked {
22
+ function poweredRatio(uint256 n, uint256 d, uint256 exp, bool fast) internal pure returns (uint256, uint256) { unchecked {
25
23
  require(exp <= MAX_EXP, "exp too large");
26
24
 
27
25
  function (uint256, uint256, uint256, uint256) pure returns (uint256, uint256) safeRatio = fast ? mulRatio128 : productRatio;
@@ -29,13 +27,13 @@ library FractionMath {
29
27
  uint256[MAX_EXP_BIT_LEN] memory ns;
30
28
  uint256[MAX_EXP_BIT_LEN] memory ds;
31
29
 
32
- (ns[0], ds[0]) = safeRatio(baseN, 1, baseD, 1);
30
+ (ns[0], ds[0]) = safeRatio(n, 1, d, 1);
33
31
  for (uint256 i = 0; (exp >> i) > 1; ++i) {
34
32
  (ns[i + 1], ds[i + 1]) = safeRatio(ns[i], ns[i], ds[i], ds[i]);
35
33
  }
36
34
 
37
- uint256 n = 1;
38
- uint256 d = 1;
35
+ n = 1;
36
+ d = 1;
39
37
 
40
38
  for (uint256 i = 0; (exp >> i) > 0; ++i) {
41
39
  if (((exp >> i) & 1) > 0) {
@@ -70,73 +68,70 @@ library FractionMath {
70
68
  /**
71
69
  * @dev Reduce the components of a given ratio
72
70
  *
73
- * @param baseN The ratio numerator
74
- * @param baseD The ratio denominator
75
- * @param max The maximum desired value
71
+ * @param n The ratio numerator
72
+ * @param d The ratio denominator
73
+ * @param max The maximum desired value
76
74
  *
77
75
  * @return The reduced ratio numerator
78
76
  * @return The reduced ratio denominator
79
77
  */
80
- function reducedRatio(uint256 baseN, uint256 baseD, uint256 max) internal pure returns (uint256, uint256) { unchecked {
81
- if (baseN > max || baseD > max) {
82
- return normalizedRatio(baseN, baseD, max);
83
- }
84
- return (baseN, baseD);
78
+ function reducedRatio(uint256 n, uint256 d, uint256 max) internal pure returns (uint256, uint256) { unchecked {
79
+ uint256 scale = ((n > d ? n : d) - 1) / max + 1;
80
+ return (n / scale, d / scale);
85
81
  }}
86
82
 
87
83
  /**
88
84
  * @dev Compute a normalized ratio as `scale * n / (n + d)` and `scale * d / (n + d)`
89
85
  *
90
- * @param baseN The ratio numerator
91
- * @param baseD The ratio denominator
86
+ * @param n The ratio numerator
87
+ * @param d The ratio denominator
92
88
  * @param scale The desired scale
93
89
  *
94
90
  * @return The normalized ratio numerator
95
91
  * @return The normalized ratio denominator
96
92
  */
97
- function normalizedRatio(uint256 baseN, uint256 baseD, uint256 scale) internal pure returns (uint256, uint256) { unchecked {
98
- if (baseN <= baseD) {
99
- return estimatedRatio(baseN, baseD, scale);
93
+ function normalizedRatio(uint256 n, uint256 d, uint256 scale) internal pure returns (uint256, uint256) { unchecked {
94
+ if (n <= d) {
95
+ return estimatedRatio(n, d, scale);
100
96
  }
101
- (uint256 d, uint256 n) = estimatedRatio(baseD, baseN, scale);
97
+ (d, n) = estimatedRatio(d, n, scale);
102
98
  return (n, d);
103
99
  }}
104
100
 
105
101
  /**
106
102
  * @dev Compute an estimated ratio as `scale * n / (n + d)` and `scale * d / (n + d)`, assuming that `n <= d`
107
103
  *
108
- * @param baseN The ratio numerator
109
- * @param baseD The ratio denominator
104
+ * @param n The ratio numerator
105
+ * @param d The ratio denominator
110
106
  * @param scale The desired scale
111
107
  *
112
108
  * @return The estimated ratio numerator
113
109
  * @return The estimated ratio denominator
114
110
  */
115
- function estimatedRatio(uint256 baseN, uint256 baseD, uint256 scale) private pure returns (uint256, uint256) { unchecked {
116
- uint256 maxN = MAX_VAL / scale; // `MAX_VAL >= scale` hence `maxN >= 1`
117
- if (maxN < baseN) {
118
- // `maxN < baseN <= MAX_VAL` hence `maxN < MAX_VAL` hence `maxN + 1` is safe
119
- // `maxN + 1 >= 2` hence `baseN / (maxN + 1) < MAX_VAL` hence `baseN / (maxN + 1) + 1` is safe
120
- uint256 c = baseN / (maxN + 1) + 1;
121
- baseN /= c; // we can now safely compute `baseN * scale`
122
- baseD /= c;
111
+ function estimatedRatio(uint256 n, uint256 d, uint256 scale) private pure returns (uint256, uint256) { unchecked {
112
+ uint256 x = MAX_VAL / scale;
113
+ if (n > x) {
114
+ // `n * scale` will overflow
115
+ uint256 y = (n - 1) / x + 1;
116
+ n /= y;
117
+ d /= y;
118
+ // `n * scale` will not overflow
123
119
  }
124
120
 
125
- if (baseN != baseD) {
126
- uint256 n = baseN * scale;
127
- uint256 d = unsafeAdd(baseN, baseD); // `baseN + baseD` can overflow
128
- if (d >= baseN) {
129
- // `baseN + baseD` did not overflow
130
- uint256 x = IntegralMath.roundDiv(n, d); // we can now safely compute `scale - x`
131
- uint256 y = scale - x;
132
- return (x, y);
121
+ if (n < d) {
122
+ uint256 p = n * scale;
123
+ uint256 q = unsafeAdd(n, d); // `n + d` can overflow
124
+ if (q >= n) {
125
+ // `n + d` did not overflow
126
+ uint256 r = IntegralMath.roundDiv(p, q);
127
+ return (r, scale - r); // `r = n * scale / (n + d) < scale`
133
128
  }
134
- if (n < baseD - (baseD - baseN) / 2) {
135
- return (0, scale); // `baseN * scale < (baseN + baseD) / 2 < MAX_VAL < baseN + baseD`
129
+ if (p < d - (d - n) / 2) {
130
+ return (0, scale); // `n * scale < (n + d) / 2 < MAX_VAL < n + d`
136
131
  }
137
- return (1, scale - 1); // `(baseN + baseD) / 2 < baseN * scale < MAX_VAL < baseN + baseD`
132
+ return (1, scale - 1); // `(n + d) / 2 < n * scale < MAX_VAL < n + d`
138
133
  }
139
- return (scale / 2, scale - scale / 2); // reflect the fact that initially `baseN <= baseD`
134
+ return (scale / 2, scale - scale / 2); // reflect the fact that initially `n <= d`
140
135
  }}
141
136
 
142
137
  /**
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.4;
2
+ pragma solidity 0.8.11;
3
3
 
4
4
  import "./common/Uint.sol";
5
5
 
@@ -51,7 +51,31 @@ library IntegralMath {
51
51
  */
52
52
  function ceilSqrt(uint256 n) internal pure returns (uint256) { unchecked {
53
53
  uint256 x = floorSqrt(n);
54
- 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;
55
79
  }}
56
80
 
57
81
  /**