S = (E + x - y + sqrt(E^2 + 2E(x + y) + (x - y)^2)) / 2
Where:
s: Amount DS user received
e: RA user provided
x: RA reserve
y: CT reserve
r: RA needed to borrow from AMM
*/
function getAmountOutDs(int256 x, int256 y, int256 e) external pure returns (uint256 r, uint256 s) {
// first we solve the sqrt part of the equation first
// E^2
int256 q1 = e ** 2;
// 2E(x + y)
int256 q2 = 2 * e * (x + y);
// (x - y)^2
int256 q3 = (x - y) ** 2;
// q = sqrt(E^2 + 2E(x + y) + (x - y)^2)
uint256 q = SignedMath.abs(q1 + q2 + q3);
q = Math.sqrt(q);
// then we substitue back the sqrt part to the main equation
// S = (E + x - y + q) / 2
// r1 = x - y (to absolute, and we reverse the equation)
uint256 r1 = SignedMath.abs(x - y);
// r2 = -r1 + q = q - r1
uint256 r2 = q - r1;
// E + r2
uint256 r3 = r2 + SignedMath.abs(e);
// S = r3/2 (we multiply by 1e18 to have 18 decimals precision)
s = (r3 * 1e18) / 2e18;
// R = s - e (should be fine with direct typecasting)
r = s - SignedMath.abs(e);
}
In comment shows following formula
S = (E + x - y + sqrt(E^2 + 2E(x + y) + (x - y)^2)) / 2
but the calculation of the code is different.
// r2 = -r1 + q = q - r1
uint256 r2 = q - r1;
so the comment need to be following.
S = (E - |(x - y)| + sqrt(E^2 + 2E(x + y) + (x - y)^2)) / 2
Fluffy Crepe Platypus
Low/Info
Wrong comment
Summary
https://github.com/sherlock-audit/2024-08-cork-protocol/blob/main/Depeg-swap/contracts/libraries/DsSwapperMathLib.sol#L100
/*
*/ function getAmountOutDs(int256 x, int256 y, int256 e) external pure returns (uint256 r, uint256 s) { // first we solve the sqrt part of the equation first
}
In comment shows following formula S = (E + x - y + sqrt(E^2 + 2E(x + y) + (x - y)^2)) / 2
but the calculation of the code is different. // r2 = -r1 + q = q - r1 uint256 r2 = q - r1;
so the comment need to be following. S = (E - |(x - y)| + sqrt(E^2 + 2E(x + y) + (x - y)^2)) / 2