Skip to content

Instantly share code, notes, and snippets.

@ameensol
Created August 1, 2019 19:22
Show Gist options
  • Save ameensol/9bc5f42e0ae010aa91685f753508369a to your computer and use it in GitHub Desktop.
Save ameensol/9bc5f42e0ae010aa91685f753508369a to your computer and use it in GitHub Desktop.
/*
* @dev Calculates the utilization and borrow rates for use by getBorrowRate function
*/
function getUtilizationAndAnnualBorrowRate(uint cash, uint borrows) view internal returns (IRError, Exp memory, Exp memory) {
(IRError err0, Exp memory utilizationRate) = getUtilizationRate(cash, borrows);
if (err0 != IRError.NO_ERROR) {
return (err0, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Borrow Rate is 5% + UtilizationRate * 45% (baseRate + UtilizationRate * multiplier);
// 45% of utilizationRate, is `rate * 45 / 100`
(MathError err1, Exp memory utilizationRateMuled) = mulScalar(utilizationRate, multiplier);
// `mulScalar` only overflows when the product is >= 2^256.
// utilizationRate is a real number on the interval [0,1], which means that
// utilizationRate.mantissa is in the interval [0e18,1e18], which means that 45 times
// that is in the interval [0e18,45e18]. That interval has no intersection with 2^256, and therefore
// this can never overflow for the standard rates.
if (err1 != MathError.NO_ERROR) {
return (IRError.FAILED_TO_MUL_UTILIZATION_RATE, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(MathError err2, Exp memory utilizationRateScaled) = divScalar(utilizationRateMuled, mantissaOne);
// 100 is a constant, and therefore cannot be zero, which is the only error case of divScalar.
assert(err2 == MathError.NO_ERROR);
// Add the 5% for (5% + 45% * Ua)
(MathError err3, Exp memory annualBorrowRate) = addExp(utilizationRateScaled, Exp({mantissa: baseRate}));
// `addExp` only fails when the addition of mantissas overflow.
// As per above, utilizationRateMuled is capped at 45e18,
// and utilizationRateScaled is capped at 4.5e17. mantissaFivePercent = 0.5e17, and thus the addition
// is capped at 5e17, which is less than 2^256. This only applies to the standard rates
if (err3 != MathError.NO_ERROR) {
return (IRError.FAILED_TO_ADD_BASE_RATE, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
return (IRError.NO_ERROR, utilizationRate, annualBorrowRate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment