solidity-math-utils 1.12.0 → 2.0.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.
@@ -1,54 +1,96 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.26;
2
+ pragma solidity 0.8.28;
3
3
 
4
4
  import "./AdvancedMath.sol";
5
+ import "./FractionMath.sol";
5
6
 
6
- contract DynamicCurve is AdvancedMath {
7
- uint256 private constant MAX_WEIGHT = 1000000;
7
+ library DynamicCurve {
8
+ uint256 internal constant MAX_WEIGHT = 1000000;
9
+
10
+ // Abstract:
11
+ // Consider a pool which implements the bonding-curve model over a primary reserve token and a secondary reserve token.
12
+ // Let 'on-chain price' denote the conversion rate between these tokens inside the pool (i.e., as determined by the pool).
13
+ // Let 'off-chain price' denote the conversion rate between these tokens outside the pool (i.e., as determined by the market).
14
+ // The arbitrage incentive is always to convert to the point where the on-chain price is equal to the off-chain price.
15
+ // We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance.
16
+ // In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance.
17
+ // Hence we adjust the weights in order to create an arbitrage incentive which, when realized, will subsequently equalize the pool.
18
+ //
19
+ // Input:
20
+ // - Let t denote the primary reserve token staked balance
21
+ // - Let s denote the primary reserve token balance
22
+ // - Let r denote the secondary reserve token balance
23
+ // - Let q denote the numerator of the off-chain price
24
+ // - Let p denote the denominator of the off-chain price
25
+ // Where p primary tokens are equal to q secondary tokens
26
+ //
27
+ // Output:
28
+ // - Solve the equation x * (s / t) ^ x = (t / r) * (q / p)
29
+ // - Return x / (x + 1) as the weight of the primary reserve token
30
+ // - Return 1 / (x + 1) as the weight of the secondary reserve token
31
+ //
32
+ // If the rate-provider provides the rates for a common unit, for example:
33
+ // - P = 2 ==> 2 primary reserve tokens = 1 ether
34
+ // - Q = 3 ==> 3 secondary reserve tokens = 1 ether
35
+ // Then you can simply use p = P and q = Q
36
+ //
37
+ // If the rate-provider provides the rates for a single unit, for example:
38
+ // - P = 2 ==> 1 primary reserve token = 2 ethers
39
+ // - Q = 3 ==> 1 secondary reserve token = 3 ethers
40
+ // Then you can simply use p = Q and q = P
8
41
 
9
42
  /**
10
- * @dev Consider a pool which implements the bonding-curve model over a primary reserve token and a secondary reserve token.
11
- * Let 'on-chain price' denote the conversion rate between these tokens inside the pool (i.e., as determined by the pool).
12
- * Let 'off-chain price' denote the conversion rate between these tokens outside the pool (i.e., as determined by the market).
13
- * The arbitrage incentive is always to convert to the point where the on-chain price is equal to the off-chain price.
14
- * We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance.
15
- * In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance.
16
- * Hence we adjust the weights in order to create an arbitrage incentive which, when realized, will subsequently equalize the pool.
43
+ * @dev Equalize the weights of a given pool while opting for accuracy over performance
17
44
  *
18
- * Input:
19
- * - Let t denote the primary reserve token staked balance
20
- * - Let s denote the primary reserve token balance
21
- * - Let r denote the secondary reserve token balance
22
- * - Let q denote the numerator of the off-chain price
23
- * - Let p denote the denominator of the off-chain price
24
- * Where p primary tokens are equal to q secondary tokens
45
+ * @param t The primary reserve token staked balance
46
+ * @param s The primary reserve token balance
47
+ * @param r The secondary reserve token balance
48
+ * @param q The numerator of the off-chain price
49
+ * @param p The denominator of the off-chain price
25
50
  *
26
- * Output:
27
- * - Solve the equation x * (s / t) ^ x = (t / r) * (q / p)
28
- * - Return x / (x + 1) as the weight of the primary reserve token
29
- * - Return 1 / (x + 1) as the weight of the secondary reserve token
51
+ * Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token
30
52
  *
31
- * If the rate-provider provides the rates for a common unit, for example:
32
- * - P = 2 ==> 2 primary reserve tokens = 1 ether
33
- * - Q = 3 ==> 3 secondary reserve tokens = 1 ether
34
- * Then you can simply use p = P and q = Q
53
+ * @return The weight of the primary reserve token and the weight of the secondary reserve token, both in ppm units
54
+ */
55
+ function equalizeExact(uint256 t, uint256 s, uint256 r, uint256 q, uint256 p) internal pure returns (uint256, uint256) { unchecked {
56
+ return equalize(t, s, r, q, p, AdvancedMath.solveExact);
57
+ }}
58
+
59
+ /**
60
+ * @dev Equalize the weights of a given pool while opting for performance over accuracy
35
61
  *
36
- * If the rate-provider provides the rates for a single unit, for example:
37
- * - P = 2 ==> 1 primary reserve token = 2 ethers
38
- * - Q = 3 ==> 1 secondary reserve token = 3 ethers
39
- * Then you can simply use p = Q and q = P
62
+ * @param t The primary reserve token staked balance
63
+ * @param s The primary reserve token balance
64
+ * @param r The secondary reserve token balance
65
+ * @param q The numerator of the off-chain price
66
+ * @param p The denominator of the off-chain price
67
+ *
68
+ * Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token
69
+ *
70
+ * @return The weight of the primary reserve token and the weight of the secondary reserve token, both in ppm units
71
+ */
72
+ function equalizeQuick(uint256 t, uint256 s, uint256 r, uint256 q, uint256 p) internal pure returns (uint256, uint256) { unchecked {
73
+ return equalize(t, s, r, q, p, AdvancedMath.solveQuick);
74
+ }}
75
+
76
+ /**
77
+ * @dev Equalize the weights of a given pool
40
78
  *
41
79
  * @param t The primary reserve token staked balance
42
80
  * @param s The primary reserve token balance
43
81
  * @param r The secondary reserve token balance
44
82
  * @param q The numerator of the off-chain price
45
83
  * @param p The denominator of the off-chain price
84
+ * @param AdvancedMath_solveFunction An equation solver
46
85
  *
47
86
  * Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token
48
87
  *
49
88
  * @return The weight of the primary reserve token and the weight of the secondary reserve token, both in ppm units
50
89
  */
51
- function equalize(uint256 t, uint256 s, uint256 r, uint256 q, uint256 p) public view returns (uint256, uint256) { unchecked {
90
+ function equalize(
91
+ uint256 t, uint256 s, uint256 r, uint256 q, uint256 p,
92
+ function (uint256, uint256, uint256, uint256) pure returns (uint256, uint256) AdvancedMath_solveFunction
93
+ ) private pure returns (uint256, uint256) { unchecked {
52
94
  if (t == s)
53
95
  require(t > 0 || r > 0, "invalid balance");
54
96
  else
@@ -56,7 +98,7 @@ contract DynamicCurve is AdvancedMath {
56
98
  require(q > 0 && p > 0, "invalid rate");
57
99
 
58
100
  (uint256 tq, uint256 rp) = FractionMath.productRatio(t, q, r, p);
59
- (uint256 xn, uint256 xd) = solve(s, t, tq, rp);
101
+ (uint256 xn, uint256 xd) = AdvancedMath_solveFunction(s, t, tq, rp);
60
102
  (uint256 w1, uint256 w2) = FractionMath.normalizedRatio(xn, xd, MAX_WEIGHT);
61
103
 
62
104
  return (w1, w2);
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.26;
2
+ pragma solidity 0.8.28;
3
3
 
4
4
  import "./IntegralMath.sol";
5
5
 
@@ -9,39 +9,31 @@ library FractionMath {
9
9
  uint256 internal constant MAX_UINT128 = type(uint128).max;
10
10
 
11
11
  /**
12
- * @dev Compute the power of a given ratio
12
+ * @dev Compute the power of a given ratio while opting for accuracy over performance
13
13
  *
14
14
  * @param n The ratio numerator
15
15
  * @param d The ratio denominator
16
16
  * @param exp The exponentiation value
17
- * @param fast Opt for performance over accuracy
18
17
  *
19
18
  * @return The powered ratio numerator
20
19
  * @return The powered ratio denominator
21
20
  */
22
- function poweredRatio(uint256 n, uint256 d, uint256 exp, bool fast) internal pure returns (uint256, uint256) { unchecked {
23
- require(exp <= MAX_EXP, "exp too large");
24
-
25
- function (uint256, uint256, uint256, uint256) pure returns (uint256, uint256) safeRatio = fast ? mulRatio128 : productRatio;
26
-
27
- uint256[MAX_EXP_BIT_LEN] memory ns;
28
- uint256[MAX_EXP_BIT_LEN] memory ds;
29
-
30
- (ns[0], ds[0]) = safeRatio(n, 1, d, 1);
31
- for (uint256 i = 0; (exp >> i) > 1; ++i) {
32
- (ns[i + 1], ds[i + 1]) = safeRatio(ns[i], ns[i], ds[i], ds[i]);
33
- }
34
-
35
- n = 1;
36
- d = 1;
37
-
38
- for (uint256 i = 0; (exp >> i) > 0; ++i) {
39
- if (((exp >> i) & 1) > 0) {
40
- (n, d) = safeRatio(n, ns[i], d, ds[i]);
41
- }
42
- }
21
+ function poweredRatioExact(uint256 n, uint256 d, uint256 exp) internal pure returns (uint256, uint256) { unchecked {
22
+ return poweredRatio(n, d, exp, productRatio);
23
+ }}
43
24
 
44
- return (n, d);
25
+ /**
26
+ * @dev Compute the power of a given ratio while opting for performance over accuracy
27
+ *
28
+ * @param n The ratio numerator
29
+ * @param d The ratio denominator
30
+ * @param exp The exponentiation value
31
+ *
32
+ * @return The powered ratio numerator
33
+ * @return The powered ratio denominator
34
+ */
35
+ function poweredRatioQuick(uint256 n, uint256 d, uint256 exp) internal pure returns (uint256, uint256) { unchecked {
36
+ return poweredRatio(n, d, exp, mulRatio128);
45
37
  }}
46
38
 
47
39
  /**
@@ -63,22 +55,25 @@ library FractionMath {
63
55
  }}
64
56
 
65
57
  /**
66
- * @dev Reduce the components of a given ratio
58
+ * @dev Reduce the components of a given ratio to fit up to a given threshold
67
59
  *
68
60
  * @param n The ratio numerator
69
61
  * @param d The ratio denominator
70
- * @param max The maximum desired value
62
+ * @param cap The desired threshold
71
63
  *
72
64
  * @return The reduced ratio numerator
73
65
  * @return The reduced ratio denominator
74
66
  */
75
- function reducedRatio(uint256 n, uint256 d, uint256 max) internal pure returns (uint256, uint256) { unchecked {
76
- uint256 scale = ((n > d ? n : d) - 1) / max + 1;
77
- return (n / scale, d / scale);
67
+ function reducedRatio(uint256 n, uint256 d, uint256 cap) internal pure returns (uint256, uint256) { unchecked {
68
+ if (n < d)
69
+ (n, d) = reducedRatioCalc(n, d, cap);
70
+ else
71
+ (d, n) = reducedRatioCalc(d, n, cap);
72
+ return (n, d);
78
73
  }}
79
74
 
80
75
  /**
81
- * @dev Compute a normalized ratio as `scale * n / (n + d)` and `scale * d / (n + d)`
76
+ * @dev Normalize the components of a given ratio to sum up to a given scale
82
77
  *
83
78
  * @param n The ratio numerator
84
79
  * @param d The ratio denominator
@@ -88,47 +83,89 @@ library FractionMath {
88
83
  * @return The normalized ratio denominator
89
84
  */
90
85
  function normalizedRatio(uint256 n, uint256 d, uint256 scale) internal pure returns (uint256, uint256) { unchecked {
91
- if (n <= d) {
92
- return estimatedRatio(n, d, scale);
93
- }
94
- (d, n) = estimatedRatio(d, n, scale);
86
+ if (n < d)
87
+ (n, d) = normalizedRatioCalc(n, d, scale);
88
+ else
89
+ (d, n) = normalizedRatioCalc(d, n, scale);
95
90
  return (n, d);
96
91
  }}
97
92
 
98
93
  /**
99
- * @dev Compute an estimated ratio as `scale * n / (n + d)` and `scale * d / (n + d)`, assuming that `n <= d`
94
+ * @dev Compute the power of a given ratio
100
95
  *
101
96
  * @param n The ratio numerator
102
97
  * @param d The ratio denominator
103
- * @param scale The desired scale
98
+ * @param exp The exponentiation value
99
+ * @param safeRatio The computing function
104
100
  *
105
- * @return The estimated ratio numerator
106
- * @return The estimated ratio denominator
101
+ * @return The powered ratio numerator
102
+ * @return The powered ratio denominator
107
103
  */
108
- function estimatedRatio(uint256 n, uint256 d, uint256 scale) private pure returns (uint256, uint256) { unchecked {
109
- uint256 x = MAX_VAL / scale;
110
- if (n > x) {
111
- // `n * scale` will overflow
112
- uint256 y = (n - 1) / x + 1;
113
- n /= y;
114
- d /= y;
115
- // `n * scale` will not overflow
104
+ function poweredRatio(
105
+ uint256 n, uint256 d, uint256 exp,
106
+ function (uint256, uint256, uint256, uint256) pure returns (uint256, uint256) safeRatio
107
+ ) private pure returns (uint256, uint256) { unchecked {
108
+ require(exp <= MAX_EXP, "exp too large");
109
+
110
+ uint256[MAX_EXP_BIT_LEN] memory ns;
111
+ uint256[MAX_EXP_BIT_LEN] memory ds;
112
+
113
+ (ns[0], ds[0]) = safeRatio(n, 1, d, 1);
114
+ for (uint256 i = 0; (exp >> i) > 1; ++i) {
115
+ (ns[i + 1], ds[i + 1]) = safeRatio(ns[i], ns[i], ds[i], ds[i]);
116
116
  }
117
117
 
118
- if (n < d) {
119
- uint256 p = n * scale;
120
- uint256 q = unsafeAdd(n, d); // `n + d` can overflow
121
- if (q >= n) {
122
- // `n + d` did not overflow
123
- uint256 r = IntegralMath.roundDiv(p, q);
124
- return (r, scale - r); // `r = n * scale / (n + d) < scale`
125
- }
126
- if (p < d - (d - n) / 2) {
127
- return (0, scale); // `n * scale < (n + d) / 2 < MAX_VAL < n + d`
118
+ n = 1;
119
+ d = 1;
120
+
121
+ for (uint256 i = 0; (exp >> i) > 0; ++i) {
122
+ if (((exp >> i) & 1) > 0) {
123
+ (n, d) = safeRatio(n, ns[i], d, ds[i]);
128
124
  }
129
- return (1, scale - 1); // `(n + d) / 2 < n * scale < MAX_VAL < n + d`
130
125
  }
131
- return (scale / 2, scale - scale / 2); // reflect the fact that initially `n <= d`
126
+
127
+ return (n, d);
128
+ }}
129
+
130
+ /**
131
+ * @dev Reduce the components of a given ratio to fit up to a given threshold,
132
+ * under the implicit assumption that the ratio is smaller than or equal to 1
133
+ *
134
+ * @param n The ratio numerator
135
+ * @param d The ratio denominator
136
+ * @param cap The desired threshold
137
+ *
138
+ * @return The reduced ratio numerator
139
+ * @return The reduced ratio denominator
140
+ */
141
+ function reducedRatioCalc(uint256 n, uint256 d, uint256 cap) private pure returns (uint256, uint256) { unchecked {
142
+ if (d > cap) {
143
+ n = IntegralMath.mulDivR(n, cap, d);
144
+ d = cap;
145
+ }
146
+ return (n, d);
147
+ }}
148
+
149
+ /**
150
+ * @dev Normalize the components of a given ratio to sum up to a given scale,
151
+ * under the implicit assumption that the ratio is smaller than or equal to 1
152
+ *
153
+ * @param n The ratio numerator
154
+ * @param d The ratio denominator
155
+ * @param scale The desired scale
156
+ *
157
+ * @return The normalized ratio numerator
158
+ * @return The normalized ratio denominator
159
+ */
160
+ function normalizedRatioCalc(uint256 n, uint256 d, uint256 scale) private pure returns (uint256, uint256) { unchecked {
161
+ if (n > ~d) {
162
+ uint256 x = unsafeAdd(n, d) + 1;
163
+ uint256 y = IntegralMath.mulDivF(x, n / 2, n / 2 + d / 2);
164
+ n -= y;
165
+ d -= x - y;
166
+ }
167
+ uint256 z = IntegralMath.mulDivR(scale, n, n + d);
168
+ return(z, scale - z);
132
169
  }}
133
170
 
134
171
  /**
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.26;
2
+ pragma solidity 0.8.28;
3
3
 
4
- import "./common/Uint.sol";
4
+ import "./common/Uint256.sol";
5
5
 
6
6
  library IntegralMath {
7
7
  /**
@@ -34,16 +34,16 @@ library IntegralMath {
34
34
  * @dev Compute the largest integer smaller than or equal to the square root of `n`
35
35
  */
36
36
  function floorSqrt(uint256 n) internal pure returns (uint256) { unchecked {
37
- if (n > 0) {
38
- uint256 x = n / 2 + 1;
39
- uint256 y = (x + n / x) / 2;
37
+ if (n > 63) {
38
+ uint256 x = n;
39
+ uint256 y = 1 << (floorLog2(n) / 2 + 1);
40
40
  while (x > y) {
41
41
  x = y;
42
- y = (x + n / x) / 2;
42
+ y = (x + n / x) >> 1;
43
43
  }
44
44
  return x;
45
45
  }
46
- return 0;
46
+ return 0x7777777777777776666666666666555555555554444444443333333222221110 >> (n * 4) & 0xf;
47
47
  }}
48
48
 
49
49
  /**
@@ -58,16 +58,16 @@ library IntegralMath {
58
58
  * @dev Compute the largest integer smaller than or equal to the cubic root of `n`
59
59
  */
60
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;
61
+ if (n > 84) {
62
+ uint256 x = n;
63
+ uint256 y = 1 << (floorLog2(n) / 3 + 1);
64
+ while (x > y) {
65
+ x = y;
66
+ y = ((x << 1) + n / x ** 2) / 3;
68
67
  }
68
+ return x;
69
69
  }
70
- return x;
70
+ return 0x49249249249249246db6db6db6db6db6db6db6db6db692492492492492249248 >> (n * 3) & 0x7;
71
71
  }}
72
72
 
73
73
  /**
@@ -79,7 +79,7 @@ library IntegralMath {
79
79
  }}
80
80
 
81
81
  /**
82
- * @dev Compute the nearest integer to the quotient of `n` and `d` (or `n / d`)
82
+ * @dev Compute the nearest integer (half being rounded upwards) to `n / d`
83
83
  */
84
84
  function roundDiv(uint256 n, uint256 d) internal pure returns (uint256) { unchecked {
85
85
  return n / d + (n % d) / (d - d / 2);
@@ -153,7 +153,7 @@ library IntegralMath {
153
153
  return xyl / z;
154
154
  }
155
155
  if (xyh < z) { // `x * y / z < 2 ^ 256`
156
- uint256 m = mulMod(x, y, z); // `m = x * y % z`
156
+ uint256 m = mulmod(x, y, z); // `m = x * y % z`
157
157
  (uint256 nh, uint256 nl) = sub512(xyh, xyl, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
158
158
  if (nh == 0) { // `n < 2 ^ 256`
159
159
  return nl / z;
@@ -171,7 +171,17 @@ library IntegralMath {
171
171
  */
172
172
  function mulDivC(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) { unchecked {
173
173
  uint256 w = mulDivF(x, y, z);
174
- if (mulMod(x, y, z) > 0)
174
+ if (mulmod(x, y, z) > 0)
175
+ return safeAdd(w, 1);
176
+ return w;
177
+ }}
178
+
179
+ /**
180
+ * @dev Compute the nearest integer (half being rounded upwards) to `x * y / z`
181
+ */
182
+ function mulDivR(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) { unchecked {
183
+ uint256 w = mulDivF(x, y, z);
184
+ if (mulmod(x, y, z) > (z - 1) / 2)
175
185
  return safeAdd(w, 1);
176
186
  return w;
177
187
  }}
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: SEE LICENSE IN LICENSE
2
- pragma solidity 0.8.26;
2
+ pragma solidity 0.8.28;
3
3
 
4
4
  uint256 constant MAX_VAL = type(uint256).max;
5
5
 
@@ -27,8 +27,3 @@ function unsafeMul(uint256 x, uint256 y) pure returns (uint256) { unchecked {
27
27
  function mulModMax(uint256 x, uint256 y) pure returns (uint256) { unchecked {
28
28
  return mulmod(x, y, MAX_VAL);
29
29
  }}
30
-
31
- // does not overflow
32
- function mulMod(uint256 x, uint256 y, uint256 z) pure returns (uint256) { unchecked {
33
- return mulmod(x, y, z);
34
- }}