Skip to content

Instantly share code, notes, and snippets.

@kadenzipfel
Created November 12, 2023 22:38
Show Gist options
  • Save kadenzipfel/75b04e1b3e6a534c67cc2a106aa7967a to your computer and use it in GitHub Desktop.
Save kadenzipfel/75b04e1b3e6a534c67cc2a106aa7967a to your computer and use it in GitHub Desktop.
pragma solidity 0.8.19;
contract MatchCalcs {
uint constant expScale = 1e18;
struct Exp {
uint mantissa;
}
function mulScalarTruncate(Exp memory a, uint scalar) pure external returns (uint) {
return truncate(mulScalar(a, scalar));
}
function mulScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint256 scaledMantissa = mulUInt(a.mantissa, scalar);
return Exp({mantissa: scaledMantissa});
}
function mulUInt(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
if (c / a != b) {
return 0;
} else {
return c;
}
}
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
function getToWithdraw(uint256 amount, uint256 exchangeRate) pure external returns (uint) {
return amount * (10 ** 18) / exchangeRate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment