Skip to content

Commit 1400cc0

Browse files
committed
feat: add unchecked to fInverse()
1 parent 957d3b6 commit 1400cc0

File tree

1 file changed

+26
-24
lines changed

1 file changed

+26
-24
lines changed

src/EulerSwapPeriphery.sol

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -214,32 +214,34 @@ contract EulerSwapPeriphery is IEulerSwapPeriphery {
214214
pure
215215
returns (uint256)
216216
{
217-
// A component of the quadratic formula: a = 2 * c
218-
uint256 A = 2 * c;
219-
220-
// B component of the quadratic formula
221-
int256 B = int256((px * (y - y0) + py - 1) / py) - int256((x0 * (2 * c - 1e18) + 1e18 - 1) / 1e18);
222-
223-
// B^2 component, using FullMath for overflow safety
224-
uint256 absB = B < 0 ? uint256(-B) : uint256(B);
225-
uint256 squaredB = Math.mulDiv(absB, absB, 1e18, Math.Rounding.Ceil);
226-
227-
// 4 * A * C component of the quadratic formula
228-
uint256 AC4 = Math.mulDiv(
229-
Math.mulDiv(4 * c, (1e18 - c), 1e18, Math.Rounding.Ceil),
230-
Math.mulDiv(x0, x0, 1e18, Math.Rounding.Ceil),
231-
1e18,
232-
Math.Rounding.Ceil
233-
);
217+
unchecked {
218+
// A component of the quadratic formula: a = 2 * c
219+
uint256 A = 2 * c;
220+
221+
// B component of the quadratic formula
222+
int256 B = int256((px * (y - y0) + py - 1) / py) - int256((x0 * (2 * c - 1e18) + 1e18 - 1) / 1e18);
234223

235-
// Discriminant: b^2 + 4ac, scaled up to maintain precision
236-
uint256 discriminant = (squaredB + AC4) * 1e18;
224+
// B^2 component, using FullMath for overflow safety
225+
uint256 absB = B < 0 ? uint256(-B) : uint256(B);
226+
uint256 squaredB = Math.mulDiv(absB, absB, 1e18, Math.Rounding.Ceil);
237227

238-
// Square root of the discriminant (rounded up)
239-
uint256 sqrt = Math.sqrt(discriminant);
240-
sqrt = (sqrt * sqrt < discriminant) ? sqrt + 1 : sqrt;
228+
// 4 * A * C component of the quadratic formula
229+
uint256 AC4 = Math.mulDiv(
230+
Math.mulDiv(4 * c, (1e18 - c), 1e18, Math.Rounding.Ceil),
231+
Math.mulDiv(x0, x0, 1e18, Math.Rounding.Ceil),
232+
1e18,
233+
Math.Rounding.Ceil
234+
);
241235

242-
// Compute and return x = fInverse(y) using the quadratic formula
243-
return Math.mulDiv(uint256(int256(sqrt) - B), 1e18, A, Math.Rounding.Ceil);
236+
// Discriminant: b^2 + 4ac, scaled up to maintain precision
237+
uint256 discriminant = (squaredB + AC4) * 1e18;
238+
239+
// Square root of the discriminant (rounded up)
240+
uint256 sqrt = Math.sqrt(discriminant);
241+
sqrt = (sqrt * sqrt < discriminant) ? sqrt + 1 : sqrt;
242+
243+
// Compute and return x = fInverse(y) using the quadratic formula
244+
return Math.mulDiv(uint256(int256(sqrt) - B), 1e18, A, Math.Rounding.Ceil);
245+
}
244246
}
245247
}

0 commit comments

Comments
 (0)