@aave/protocol-js
Version:
Aave protocol data aggregation tool
963 lines (859 loc) • 305 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var BigNumber = require('bignumber.js');
var BigNumber__default = _interopDefault(BigNumber);
var tslib = require('tslib');
var ethers = require('ethers');
require('reflect-metadata');
var utils = require('ethers/lib/utils');
var axios = _interopDefault(require('axios'));
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var BigNumberZD =
/*#__PURE__*/
BigNumber__default.clone({
DECIMAL_PLACES: 0,
ROUNDING_MODE: BigNumber__default.ROUND_DOWN
});
function valueToBigNumber(amount) {
return new BigNumber__default(amount);
}
function valueToZDBigNumber(amount) {
return new BigNumberZD(amount);
}
var bn10 =
/*#__PURE__*/
new BigNumber__default(10);
var bn10PowLookup = {};
/**
* It's a performance optimized version of 10 ** x, which essentially memoizes previously used pows and resolves them as lookup.
* @param decimals
* @returns 10 ** decimals
*/
function pow10(decimals) {
if (!bn10PowLookup[decimals]) bn10PowLookup[decimals] = bn10.pow(decimals);
return bn10PowLookup[decimals];
}
function normalize(n, decimals) {
return normalizeBN(n, decimals).toString(10);
}
function normalizeBN(n, decimals) {
return valueToBigNumber(n).dividedBy(pow10(decimals));
}
var WAD =
/*#__PURE__*/
valueToZDBigNumber(10).pow(18);
var HALF_WAD =
/*#__PURE__*/
WAD.dividedBy(2);
var RAY =
/*#__PURE__*/
valueToZDBigNumber(10).pow(27);
var HALF_RAY =
/*#__PURE__*/
RAY.dividedBy(2);
var WAD_RAY_RATIO =
/*#__PURE__*/
valueToZDBigNumber(10).pow(9);
function wadMul(a, b) {
return HALF_WAD.plus(valueToZDBigNumber(a).multipliedBy(b)).div(WAD);
}
function wadDiv(a, b) {
var halfB = valueToZDBigNumber(b).div(2);
return halfB.plus(valueToZDBigNumber(a).multipliedBy(WAD)).div(b);
}
function rayMul(a, b) {
return HALF_RAY.plus(valueToZDBigNumber(a).multipliedBy(b)).div(RAY);
}
function rayDiv(a, b) {
var halfB = valueToZDBigNumber(b).div(2);
return halfB.plus(valueToZDBigNumber(a).multipliedBy(RAY)).div(b);
}
function rayToWad(a) {
var halfRatio = valueToZDBigNumber(WAD_RAY_RATIO).div(2);
return halfRatio.plus(a).div(WAD_RAY_RATIO);
}
function wadToRay(a) {
return valueToZDBigNumber(a).multipliedBy(WAD_RAY_RATIO).decimalPlaces(0);
}
function rayPow(a, p) {
var x = valueToZDBigNumber(a);
var n = valueToZDBigNumber(p);
var z = !n.modulo(2).eq(0) ? x : valueToZDBigNumber(RAY);
for (n = n.div(2); !n.eq(0); n = n.div(2)) {
x = rayMul(x, x);
if (!n.modulo(2).eq(0)) {
z = rayMul(z, x);
}
}
return z;
}
/**
* RayPow is slow and gas intensive therefore in v2 we switched to binomial approximation on the contract level.
* While the results ar not exact to the last decimal, they are close enough.
*/
function binomialApproximatedRayPow(a, p) {
var base = valueToZDBigNumber(a);
var exp = valueToZDBigNumber(p);
if (exp.eq(0)) return RAY;
var expMinusOne = exp.minus(1);
var expMinusTwo = exp.gt(2) ? exp.minus(2) : 0;
var basePowerTwo = rayMul(base, base);
var basePowerThree = rayMul(basePowerTwo, base);
var firstTerm = exp.multipliedBy(base);
var secondTerm = exp.multipliedBy(expMinusOne).multipliedBy(basePowerTwo).div(2);
var thirdTerm = exp.multipliedBy(expMinusOne).multipliedBy(expMinusTwo).multipliedBy(basePowerThree).div(6);
return RAY.plus(firstTerm).plus(secondTerm).plus(thirdTerm);
}
function rayToDecimal(a) {
return valueToZDBigNumber(a).dividedBy(RAY);
}
var BorrowRateMode;
(function (BorrowRateMode) {
BorrowRateMode["None"] = "None";
BorrowRateMode["Stable"] = "Stable";
BorrowRateMode["Variable"] = "Variable";
})(BorrowRateMode || (BorrowRateMode = {}));
var SECONDS_PER_YEAR =
/*#__PURE__*/
valueToBigNumber('31536000');
var ETH_DECIMALS = 18;
var USD_DECIMALS = 10;
var RAY_DECIMALS = 27;
var LTV_PRECISION = 4;
function calculateCompoundedInterest(rate, currentTimestamp, lastUpdateTimestamp) {
var timeDelta = valueToZDBigNumber(currentTimestamp - lastUpdateTimestamp);
var ratePerSecond = valueToZDBigNumber(rate).dividedBy(SECONDS_PER_YEAR);
return binomialApproximatedRayPow(ratePerSecond, timeDelta);
}
function getCompoundedBalance(_principalBalance, _reserveIndex, _reserveRate, _lastUpdateTimestamp, currentTimestamp) {
var principalBalance = valueToZDBigNumber(_principalBalance);
if (principalBalance.eq('0')) {
return principalBalance;
}
var compoundedInterest = calculateCompoundedInterest(_reserveRate, currentTimestamp, _lastUpdateTimestamp);
var cumulatedInterest = rayMul(compoundedInterest, _reserveIndex);
var principalBalanceRay = wadToRay(principalBalance);
return rayToWad(rayMul(principalBalanceRay, cumulatedInterest));
}
var calculateLinearInterest = function calculateLinearInterest(rate, currentTimestamp, lastUpdateTimestamp) {
var timeDelta = wadToRay(valueToZDBigNumber(currentTimestamp - lastUpdateTimestamp));
var timeDeltaInSeconds = rayDiv(timeDelta, wadToRay(SECONDS_PER_YEAR));
return rayMul(rate, timeDeltaInSeconds).plus(RAY);
};
function getReserveNormalizedIncome(rate, index, lastUpdateTimestamp, currentTimestamp) {
if (valueToZDBigNumber(rate).eq('0')) {
return valueToZDBigNumber(index);
}
var cumulatedInterest = calculateLinearInterest(rate, currentTimestamp, lastUpdateTimestamp);
return rayMul(cumulatedInterest, index);
}
function getLinearBalance(balance, index, rate, lastUpdateTimestamp, currentTimestamp) {
return rayToWad(rayMul(wadToRay(balance), getReserveNormalizedIncome(rate, index, lastUpdateTimestamp, currentTimestamp)));
}
function getCompoundedStableBalance(_principalBalance, _userStableRate, _lastUpdateTimestamp, currentTimestamp) {
var principalBalance = valueToZDBigNumber(_principalBalance);
if (principalBalance.eq('0')) {
return principalBalance;
}
var cumulatedInterest = calculateCompoundedInterest(_userStableRate, currentTimestamp, _lastUpdateTimestamp);
var principalBalanceRay = wadToRay(principalBalance);
return rayToWad(rayMul(principalBalanceRay, cumulatedInterest));
}
function calculateHealthFactorFromBalances(collateralBalanceETH, borrowBalanceETH, currentLiquidationThreshold) {
if (valueToBigNumber(borrowBalanceETH).eq(0)) {
return valueToBigNumber('-1'); // invalid number
}
return valueToBigNumber(collateralBalanceETH).multipliedBy(currentLiquidationThreshold).dividedBy(pow10(LTV_PRECISION)).div(borrowBalanceETH);
}
function calculateHealthFactorFromBalancesBigUnits(collateralBalanceETH, borrowBalanceETH, currentLiquidationThreshold) {
return calculateHealthFactorFromBalances(collateralBalanceETH, borrowBalanceETH, new BigNumber__default(currentLiquidationThreshold).multipliedBy(pow10(LTV_PRECISION)).decimalPlaces(0, BigNumber__default.ROUND_DOWN));
}
function calculateAvailableBorrowsETH(collateralBalanceETH, borrowBalanceETH, currentLtv) {
if (valueToZDBigNumber(currentLtv).eq(0)) {
return valueToZDBigNumber('0');
}
var availableBorrowsETH = valueToZDBigNumber(collateralBalanceETH).multipliedBy(currentLtv).dividedBy(pow10(LTV_PRECISION)).minus(borrowBalanceETH);
return availableBorrowsETH.gt('0') ? availableBorrowsETH : valueToZDBigNumber('0');
}
function calculateAverageRate(index0, index1, timestamp0, timestamp1) {
return valueToBigNumber(index1).dividedBy(index0).minus('1').dividedBy(timestamp1 - timestamp0).multipliedBy(SECONDS_PER_YEAR).toString();
}
function getCompoundedBorrowBalance(reserve, userReserve, currentTimestamp) {
var principalBorrows = valueToZDBigNumber(userReserve.principalBorrows);
if (principalBorrows.eq('0')) {
return valueToZDBigNumber('0');
}
var cumulatedInterest;
if (userReserve.borrowRateMode === BorrowRateMode.Variable) {
var compoundedInterest = calculateCompoundedInterest$1(reserve.variableBorrowRate, currentTimestamp, reserve.lastUpdateTimestamp);
cumulatedInterest = rayDiv(rayMul(compoundedInterest, reserve.variableBorrowIndex), userReserve.variableBorrowIndex);
} else {
// if stable
cumulatedInterest = calculateCompoundedInterest$1(userReserve.borrowRate, currentTimestamp, userReserve.lastUpdateTimestamp);
}
var borrowBalanceRay = wadToRay(principalBorrows);
return rayToWad(rayMul(borrowBalanceRay, cumulatedInterest));
}
var calculateCompoundedInterest$1 = function calculateCompoundedInterest(rate, currentTimestamp, lastUpdateTimestamp) {
var timeDelta = valueToZDBigNumber(currentTimestamp - lastUpdateTimestamp);
var ratePerSecond = valueToZDBigNumber(rate).dividedBy(SECONDS_PER_YEAR);
return binomialApproximatedRayPow(ratePerSecond, timeDelta);
};
function calculateHealthFactorFromBalances$1(collateralBalanceETH, borrowBalanceETH, totalFeesETH, currentLiquidationThreshold) {
if (valueToBigNumber(borrowBalanceETH).eq(0)) {
return valueToBigNumber('-1'); // invalid number
}
return valueToBigNumber(collateralBalanceETH).multipliedBy(currentLiquidationThreshold).dividedBy(100).div(valueToBigNumber(borrowBalanceETH).plus(totalFeesETH));
}
function calculateHealthFactorFromBalancesBigUnits$1(collateralBalanceETH, borrowBalanceETH, totalFeesETH, currentLiquidationThreshold) {
return calculateHealthFactorFromBalances$1(collateralBalanceETH, borrowBalanceETH, totalFeesETH, new BigNumber__default(currentLiquidationThreshold).multipliedBy(100).decimalPlaces(0, BigNumber__default.ROUND_DOWN));
}
function calculateAvailableBorrowsETH$1(collateralBalanceETH, borrowBalanceETH, totalFeesETH, currentLtv) {
if (valueToZDBigNumber(currentLtv).eq(0)) {
return valueToZDBigNumber('0');
}
var availableBorrowsETH = valueToZDBigNumber(collateralBalanceETH).multipliedBy(currentLtv).dividedBy(100);
if (availableBorrowsETH.lt(borrowBalanceETH)) {
return valueToZDBigNumber('0');
}
availableBorrowsETH = availableBorrowsETH.minus(borrowBalanceETH).minus(totalFeesETH);
var borrowFee = availableBorrowsETH.multipliedBy('0.0025');
return availableBorrowsETH.minus(borrowFee);
}
function calculateCumulatedBalance(balance, userReserve, poolReserve, currentTimestamp) {
return rayToWad(rayDiv(rayMul(wadToRay(balance), getReserveNormalizedIncome(poolReserve.liquidityRate, poolReserve.liquidityIndex, poolReserve.lastUpdateTimestamp, currentTimestamp)), userReserve.userBalanceIndex));
}
function calculateCurrentUnderlyingBalance(userReserve, poolReserve, currentTimestamp) {
if (userReserve.principalATokenBalance === '0' && userReserve.redirectedBalance === '0') {
return valueToZDBigNumber('0');
}
if (userReserve.interestRedirectionAddress !== '0x0000000000000000000000000000000000000000') {
return valueToZDBigNumber(userReserve.principalATokenBalance).plus(calculateCumulatedBalance(userReserve.redirectedBalance, userReserve, poolReserve, currentTimestamp).minus(userReserve.redirectedBalance));
}
return calculateCumulatedBalance(valueToBigNumber(userReserve.redirectedBalance).plus(userReserve.principalATokenBalance).toString(), userReserve, poolReserve, currentTimestamp).minus(userReserve.redirectedBalance);
}
function computeUserReserveData(poolReserve, userReserve, usdPriceEth, currentTimestamp) {
var priceInEth = poolReserve.price.priceInEth,
decimals = poolReserve.decimals;
var currentUnderlyingBalance = calculateCurrentUnderlyingBalance(userReserve, poolReserve, currentTimestamp);
var currentUnderlyingBalanceETH = currentUnderlyingBalance.multipliedBy(priceInEth).dividedBy(pow10(decimals));
var currentUnderlyingBalanceUSD = currentUnderlyingBalanceETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toFixed(0);
var principalBorrowsETH = valueToZDBigNumber(userReserve.principalBorrows).multipliedBy(priceInEth).dividedBy(pow10(decimals));
var principalBorrowsUSD = principalBorrowsETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toFixed(0);
var currentBorrows = getCompoundedBorrowBalance(poolReserve, userReserve, currentTimestamp);
var currentBorrowsETH = currentBorrows.multipliedBy(priceInEth).dividedBy(pow10(decimals));
var currentBorrowsUSD = currentBorrowsETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toFixed(0);
var originationFeeETH = valueToZDBigNumber(userReserve.originationFee).multipliedBy(priceInEth).dividedBy(pow10(decimals));
var originationFeeUSD = originationFeeETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toFixed(0);
return _extends({}, userReserve, {
principalBorrowsUSD: principalBorrowsUSD,
currentBorrowsUSD: currentBorrowsUSD,
originationFeeUSD: originationFeeUSD,
currentUnderlyingBalanceUSD: currentUnderlyingBalanceUSD,
originationFeeETH: originationFeeETH.toString(),
currentBorrows: currentBorrows.toString(),
currentBorrowsETH: currentBorrowsETH.toString(),
principalBorrowsETH: principalBorrowsETH.toString(),
currentUnderlyingBalance: currentUnderlyingBalance.toFixed(),
currentUnderlyingBalanceETH: currentUnderlyingBalanceETH.toFixed()
});
}
function computeRawUserSummaryData(poolReservesData, rawUserReserves, userId, usdPriceEth, currentTimestamp) {
var totalLiquidityETH = valueToZDBigNumber('0');
var totalCollateralETH = valueToZDBigNumber('0');
var totalBorrowsETH = valueToZDBigNumber('0');
var totalFeesETH = valueToZDBigNumber('0');
var currentLtv = valueToBigNumber('0');
var currentLiquidationThreshold = valueToBigNumber('0');
var userReservesData = rawUserReserves.map(function (userReserve) {
var poolReserve = poolReservesData.find(function (reserve) {
return reserve.id === userReserve.reserve.id;
});
if (!poolReserve) {
throw new Error('Reserve is not registered on platform, please contact support');
}
var computedUserReserve = computeUserReserveData(poolReserve, userReserve, usdPriceEth, currentTimestamp);
totalLiquidityETH = totalLiquidityETH.plus(computedUserReserve.currentUnderlyingBalanceETH);
totalBorrowsETH = totalBorrowsETH.plus(computedUserReserve.currentBorrowsETH);
totalFeesETH = totalFeesETH.plus(computedUserReserve.originationFeeETH); // asset enabled as collateral
if (poolReserve.usageAsCollateralEnabled && userReserve.usageAsCollateralEnabledOnUser) {
totalCollateralETH = totalCollateralETH.plus(computedUserReserve.currentUnderlyingBalanceETH);
currentLtv = currentLtv.plus(valueToBigNumber(computedUserReserve.currentUnderlyingBalanceETH).multipliedBy(poolReserve.baseLTVasCollateral));
currentLiquidationThreshold = currentLiquidationThreshold.plus(valueToBigNumber(computedUserReserve.currentUnderlyingBalanceETH).multipliedBy(poolReserve.reserveLiquidationThreshold));
}
return computedUserReserve;
}).sort(function (a, b) {
return a.reserve.symbol > b.reserve.symbol ? 1 : a.reserve.symbol < b.reserve.symbol ? -1 : 0;
});
if (currentLtv.gt(0)) {
currentLtv = currentLtv.div(totalCollateralETH).decimalPlaces(0, BigNumber__default.ROUND_DOWN);
}
if (currentLiquidationThreshold.gt(0)) {
currentLiquidationThreshold = currentLiquidationThreshold.div(totalCollateralETH).decimalPlaces(0, BigNumber__default.ROUND_DOWN);
}
var healthFactor = calculateHealthFactorFromBalances$1(totalCollateralETH, totalBorrowsETH, totalFeesETH, currentLiquidationThreshold);
var totalCollateralUSD = totalCollateralETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toString();
var totalLiquidityUSD = totalLiquidityETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toString();
var totalBorrowsUSD = totalBorrowsETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toString();
var totalFeesUSD = totalFeesETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth);
var totalBorrowsWithFeesETH = totalFeesETH.plus(totalBorrowsETH);
var totalBorrowsWithFeesUSD = totalFeesUSD.plus(totalBorrowsUSD);
var availableBorrowsETH = calculateAvailableBorrowsETH$1(totalCollateralETH, totalBorrowsETH, totalFeesETH, currentLtv);
var totalBorrowsAndFeesETH = totalBorrowsETH.plus(totalFeesETH);
var maxAmountToWithdrawInEth = totalLiquidityETH.minus(totalBorrowsAndFeesETH.eq(0) ? '0' : totalBorrowsAndFeesETH.multipliedBy(100).dividedBy(currentLiquidationThreshold));
return {
totalLiquidityUSD: totalLiquidityUSD,
totalCollateralUSD: totalCollateralUSD,
totalBorrowsUSD: totalBorrowsUSD,
id: userId,
totalLiquidityETH: totalLiquidityETH.toString(),
totalCollateralETH: totalCollateralETH.toString(),
totalFeesETH: totalFeesETH.toString(),
totalBorrowsETH: totalBorrowsETH.toString(),
availableBorrowsETH: availableBorrowsETH.toString(),
currentLoanToValue: currentLtv.toString(),
currentLiquidationThreshold: currentLiquidationThreshold.toString(),
maxAmountToWithdrawInEth: maxAmountToWithdrawInEth.toString(),
healthFactor: healthFactor.toString(),
reservesData: userReservesData,
totalFeesUSD: totalFeesUSD.toString(),
totalBorrowsWithFeesETH: totalBorrowsWithFeesETH.toString(),
totalBorrowsWithFeesUSD: totalBorrowsWithFeesUSD.toString()
};
}
function formatUserSummaryData(poolReservesData, rawUserReserves, userId, usdPriceEth, currentTimestamp) {
var userData = computeRawUserSummaryData(poolReservesData, rawUserReserves, userId, usdPriceEth, currentTimestamp);
var userReservesData = userData.reservesData.map(function (_ref) {
var reserve = _ref.reserve,
userReserve = _objectWithoutPropertiesLoose(_ref, ["reserve"]);
var reserveDecimals = reserve.decimals;
return _extends({}, userReserve, {
reserve: _extends({}, reserve, {
reserveLiquidationBonus: normalize(valueToBigNumber(reserve.reserveLiquidationBonus).minus(100), 2),
liquidityRate: normalize(reserve.liquidityRate, RAY_DECIMALS)
}),
redirectedBalance: normalize(userReserve.redirectedBalance, reserveDecimals),
principalATokenBalance: normalize(userReserve.principalATokenBalance, reserveDecimals),
borrowRate: normalize(userReserve.borrowRate, RAY_DECIMALS),
lastUpdateTimestamp: userReserve.lastUpdateTimestamp,
variableBorrowIndex: normalize(userReserve.variableBorrowIndex, RAY_DECIMALS),
userBalanceIndex: normalize(userReserve.userBalanceIndex, RAY_DECIMALS),
currentUnderlyingBalance: normalize(userReserve.currentUnderlyingBalance, reserveDecimals),
currentUnderlyingBalanceETH: normalize(userReserve.currentUnderlyingBalanceETH, ETH_DECIMALS),
currentUnderlyingBalanceUSD: normalize(userReserve.currentUnderlyingBalanceUSD, USD_DECIMALS),
principalBorrows: normalize(userReserve.principalBorrows, reserveDecimals),
principalBorrowsETH: normalize(userReserve.principalBorrowsETH, ETH_DECIMALS),
principalBorrowsUSD: normalize(userReserve.principalBorrowsUSD, USD_DECIMALS),
currentBorrows: normalize(userReserve.currentBorrows, reserveDecimals),
currentBorrowsETH: normalize(userReserve.currentBorrowsETH, ETH_DECIMALS),
currentBorrowsUSD: normalize(userReserve.currentBorrowsUSD, USD_DECIMALS),
originationFee: normalize(userReserve.originationFee, reserveDecimals),
originationFeeETH: normalize(userReserve.originationFeeETH, ETH_DECIMALS),
originationFeeUSD: normalize(userReserve.originationFeeUSD, USD_DECIMALS)
});
});
return {
id: userData.id,
reservesData: userReservesData,
totalLiquidityETH: normalize(userData.totalLiquidityETH, ETH_DECIMALS),
totalLiquidityUSD: normalize(userData.totalLiquidityUSD, USD_DECIMALS),
totalCollateralETH: normalize(userData.totalCollateralETH, ETH_DECIMALS),
totalCollateralUSD: normalize(userData.totalCollateralUSD, USD_DECIMALS),
totalFeesETH: normalize(userData.totalFeesETH, ETH_DECIMALS),
totalFeesUSD: normalize(userData.totalFeesUSD, USD_DECIMALS),
totalBorrowsETH: normalize(userData.totalBorrowsETH, ETH_DECIMALS),
totalBorrowsUSD: normalize(userData.totalBorrowsUSD, USD_DECIMALS),
totalBorrowsWithFeesETH: normalize(userData.totalBorrowsWithFeesETH, ETH_DECIMALS),
totalBorrowsWithFeesUSD: normalize(userData.totalBorrowsWithFeesUSD, USD_DECIMALS),
availableBorrowsETH: normalize(userData.availableBorrowsETH, ETH_DECIMALS),
currentLoanToValue: normalize(userData.currentLoanToValue, 2),
currentLiquidationThreshold: normalize(userData.currentLiquidationThreshold, 2),
maxAmountToWithdrawInEth: normalize(userData.maxAmountToWithdrawInEth, ETH_DECIMALS),
healthFactor: userData.healthFactor
};
}
function formatReserves(reserves, reserveIndexes30DaysAgo) {
return reserves.map(function (reserve) {
var _reserveIndexes30Days, _reserveIndexes30Days2;
var reserve30DaysAgo = reserveIndexes30DaysAgo == null ? void 0 : (_reserveIndexes30Days = reserveIndexes30DaysAgo.find(function (res) {
return res.id === reserve.id;
})) == null ? void 0 : (_reserveIndexes30Days2 = _reserveIndexes30Days.paramsHistory) == null ? void 0 : _reserveIndexes30Days2[0];
return _extends({}, reserve, {
price: _extends({}, reserve.price, {
priceInEth: normalize(reserve.price.priceInEth, ETH_DECIMALS)
}),
baseLTVasCollateral: normalize(reserve.baseLTVasCollateral, 2),
variableBorrowRate: normalize(reserve.variableBorrowRate, RAY_DECIMALS),
avg30DaysVariableBorrowRate: reserve30DaysAgo ? calculateAverageRate(reserve30DaysAgo.variableBorrowIndex, reserve.variableBorrowIndex, reserve30DaysAgo.timestamp, reserve.lastUpdateTimestamp) : undefined,
avg30DaysLiquidityRate: reserve30DaysAgo ? calculateAverageRate(reserve30DaysAgo.liquidityIndex, reserve.liquidityIndex, reserve30DaysAgo.timestamp, reserve.lastUpdateTimestamp) : undefined,
stableBorrowRate: normalize(reserve.stableBorrowRate, RAY_DECIMALS),
liquidityRate: normalize(reserve.liquidityRate, RAY_DECIMALS),
totalLiquidity: normalize(reserve.totalLiquidity, reserve.decimals),
availableLiquidity: normalize(reserve.availableLiquidity, reserve.decimals),
liquidityIndex: normalize(reserve.liquidityIndex, RAY_DECIMALS),
reserveLiquidationThreshold: normalize(reserve.reserveLiquidationThreshold, 2),
reserveLiquidationBonus: normalize(valueToBigNumber(reserve.reserveLiquidationBonus).minus(100), 2),
totalBorrows: normalize(reserve.totalBorrows, reserve.decimals),
totalBorrowsVariable: normalize(reserve.totalBorrowsVariable, reserve.decimals),
totalBorrowsStable: normalize(reserve.totalBorrowsStable, reserve.decimals),
variableBorrowIndex: normalize(reserve.variableBorrowIndex, RAY_DECIMALS)
});
});
}
function calculateInterestRates(reserve, amountToDeposit, amountToBorrow, borrowMode) {
if (borrowMode === void 0) {
borrowMode = 'variable';
}
var optimalUtilisationRate = reserve.optimalUtilisationRate;
var baseVariableBorrowRate = valueToBigNumber(reserve.baseVariableBorrowRate);
var totalBorrowsStable = valueToBigNumber(reserve.totalBorrowsStable).plus(borrowMode === 'stable' ? amountToBorrow : '0');
var totalBorrowsVariable = valueToBigNumber(reserve.totalBorrowsVariable).plus(borrowMode === 'variable' ? amountToBorrow : '0');
var totalBorrows = totalBorrowsStable.plus(totalBorrowsVariable);
var totalDeposits = valueToBigNumber(reserve.totalLiquidity).plus(amountToDeposit);
var utilizationRate = totalDeposits.eq(0) && totalBorrows.eq(0) ? valueToBigNumber(0) : totalBorrows.dividedBy(totalDeposits);
var currentStableBorrowRate = valueToBigNumber(reserve.stableBorrowRate);
var currentVariableBorrowRate = valueToBigNumber(0);
var currentLiquidityRate = valueToBigNumber(0);
if (utilizationRate.gt(optimalUtilisationRate)) {
var excessUtilizationRateRatio = utilizationRate.minus(optimalUtilisationRate).dividedBy(valueToBigNumber(1).minus(optimalUtilisationRate));
currentStableBorrowRate = currentStableBorrowRate.plus(reserve.stableRateSlope1).plus(excessUtilizationRateRatio.multipliedBy(reserve.stableRateSlope2));
currentVariableBorrowRate = baseVariableBorrowRate.plus(reserve.variableRateSlope1).plus(excessUtilizationRateRatio.multipliedBy(reserve.variableRateSlope2));
} else {
currentStableBorrowRate = currentVariableBorrowRate.plus(utilizationRate.dividedBy(optimalUtilisationRate).multipliedBy(reserve.stableRateSlope1));
currentVariableBorrowRate = baseVariableBorrowRate.plus(utilizationRate.dividedBy(optimalUtilisationRate).multipliedBy(reserve.variableRateSlope1));
}
if (!totalBorrows.eq(0)) {
var weightedVariableRate = currentVariableBorrowRate.multipliedBy(totalBorrowsVariable);
var weightedStableRate = valueToBigNumber(reserve.averageStableBorrowRate).multipliedBy(totalBorrowsStable);
currentLiquidityRate = weightedVariableRate.plus(weightedStableRate).dividedBy(totalBorrows);
}
return {
variableBorrowRate: currentVariableBorrowRate.toString(),
stableBorrowRate: currentStableBorrowRate.toString(),
liquidityRate: currentLiquidityRate.toString()
};
}
var index = {
__proto__: null,
getCompoundedBorrowBalance: getCompoundedBorrowBalance,
calculateCompoundedInterest: calculateCompoundedInterest$1,
calculateHealthFactorFromBalances: calculateHealthFactorFromBalances$1,
calculateHealthFactorFromBalancesBigUnits: calculateHealthFactorFromBalancesBigUnits$1,
calculateAvailableBorrowsETH: calculateAvailableBorrowsETH$1,
calculateCumulatedBalance: calculateCumulatedBalance,
calculateCurrentUnderlyingBalance: calculateCurrentUnderlyingBalance,
computeRawUserSummaryData: computeRawUserSummaryData,
formatUserSummaryData: formatUserSummaryData,
formatReserves: formatReserves,
calculateInterestRates: calculateInterestRates,
get BorrowRateMode () { return BorrowRateMode; }
};
function getEthAndUsdBalance(balance, priceInEth, decimals, usdPriceEth) {
var balanceInEth = valueToZDBigNumber(balance).multipliedBy(priceInEth).dividedBy(pow10(decimals));
var balanceInUsd = balanceInEth.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toFixed(0);
return [balanceInEth.toString(), balanceInUsd];
}
/*
type ComputeUserReserveDataPoolReserve = Pick<
ReserveData,
| 'price'
| 'decimals'
| 'liquidityIndex'
| 'liquidityRate'
| 'lastUpdateTimestamp'
| 'variableBorrowIndex'
| 'variableBorrowRate'
>;
type ComputeUserReserveDataUserReserve = Pick<
UserReserveData,
| 'scaledATokenBalance'
| 'scaledVariableDebt'
| 'principalStableDebt'
| 'stableBorrowRate'
| 'stableBorrowLastUpdateTimestamp'
>;
*/
function computeUserReserveData$1(poolReserve, userReserve, usdPriceEth, currentTimestamp, rewardsInfo) {
var priceInEth = poolReserve.price.priceInEth,
decimals = poolReserve.decimals;
var underlyingBalance = getLinearBalance(userReserve.scaledATokenBalance, poolReserve.liquidityIndex, poolReserve.liquidityRate, poolReserve.lastUpdateTimestamp, currentTimestamp).toString();
var _getEthAndUsdBalance = getEthAndUsdBalance(underlyingBalance, priceInEth, decimals, usdPriceEth),
underlyingBalanceETH = _getEthAndUsdBalance[0],
underlyingBalanceUSD = _getEthAndUsdBalance[1];
var variableBorrows = getCompoundedBalance(userReserve.scaledVariableDebt, poolReserve.variableBorrowIndex, poolReserve.variableBorrowRate, poolReserve.lastUpdateTimestamp, currentTimestamp).toString();
var _getEthAndUsdBalance2 = getEthAndUsdBalance(variableBorrows, priceInEth, decimals, usdPriceEth),
variableBorrowsETH = _getEthAndUsdBalance2[0],
variableBorrowsUSD = _getEthAndUsdBalance2[1];
var stableBorrows = getCompoundedStableBalance(userReserve.principalStableDebt, poolReserve.stableBorrowRate, userReserve.stableBorrowLastUpdateTimestamp, currentTimestamp).toString();
var _getEthAndUsdBalance3 = getEthAndUsdBalance(stableBorrows, priceInEth, decimals, usdPriceEth),
stableBorrowsETH = _getEthAndUsdBalance3[0],
stableBorrowsUSD = _getEthAndUsdBalance3[1];
var _calculateSupplies = calculateSupplies({
totalScaledVariableDebt: poolReserve.totalScaledVariableDebt,
variableBorrowIndex: poolReserve.variableBorrowIndex,
variableBorrowRate: poolReserve.variableBorrowRate,
totalPrincipalStableDebt: poolReserve.totalPrincipalStableDebt,
averageStableRate: poolReserve.averageStableRate,
availableLiquidity: poolReserve.availableLiquidity,
stableDebtLastUpdateTimestamp: poolReserve.stableDebtLastUpdateTimestamp,
lastUpdateTimestamp: poolReserve.lastUpdateTimestamp
}, currentTimestamp),
totalLiquidity = _calculateSupplies.totalLiquidity,
totalStableDebt = _calculateSupplies.totalStableDebt,
totalVariableDebt = _calculateSupplies.totalVariableDebt;
var aTokenRewards = totalLiquidity.gt(0) ? calculateRewards(userReserve.scaledATokenBalance, poolReserve.aTokenIncentivesIndex, userReserve.aTokenincentivesUserIndex, rewardsInfo.incentivePrecision, rewardsInfo.rewardTokenDecimals, poolReserve.aIncentivesLastUpdateTimestamp, poolReserve.aEmissionPerSecond, rayDiv(totalLiquidity, poolReserve.liquidityIndex), currentTimestamp, rewardsInfo.emissionEndTimestamp) : '0';
var _getEthAndUsdBalance4 = getEthAndUsdBalance(aTokenRewards, rewardsInfo.rewardTokenPriceEth, rewardsInfo.rewardTokenDecimals, usdPriceEth),
aTokenRewardsETH = _getEthAndUsdBalance4[0],
aTokenRewardsUSD = _getEthAndUsdBalance4[1];
var vTokenRewards = totalVariableDebt.gt(0) ? calculateRewards(userReserve.scaledVariableDebt, poolReserve.vTokenIncentivesIndex, userReserve.vTokenincentivesUserIndex, rewardsInfo.incentivePrecision, rewardsInfo.rewardTokenDecimals, poolReserve.vIncentivesLastUpdateTimestamp, poolReserve.vEmissionPerSecond, new BigNumber__default(poolReserve.totalScaledVariableDebt), currentTimestamp, rewardsInfo.emissionEndTimestamp) : '0';
var _getEthAndUsdBalance5 = getEthAndUsdBalance(vTokenRewards, rewardsInfo.rewardTokenPriceEth, rewardsInfo.rewardTokenDecimals, usdPriceEth),
vTokenRewardsETH = _getEthAndUsdBalance5[0],
vTokenRewardsUSD = _getEthAndUsdBalance5[1];
var sTokenRewards = totalStableDebt.gt(0) ? calculateRewards(userReserve.principalStableDebt, poolReserve.sTokenIncentivesIndex, userReserve.sTokenincentivesUserIndex, rewardsInfo.incentivePrecision, rewardsInfo.rewardTokenDecimals, poolReserve.sIncentivesLastUpdateTimestamp, poolReserve.sEmissionPerSecond, new BigNumber__default(poolReserve.totalPrincipalStableDebt), currentTimestamp, rewardsInfo.emissionEndTimestamp) : '0';
var _getEthAndUsdBalance6 = getEthAndUsdBalance(sTokenRewards, rewardsInfo.rewardTokenPriceEth, rewardsInfo.rewardTokenDecimals, usdPriceEth),
sTokenRewardsETH = _getEthAndUsdBalance6[0],
sTokenRewardsUSD = _getEthAndUsdBalance6[1];
var exactStableBorrowRate = rayPow(valueToZDBigNumber(userReserve.stableBorrowRate).dividedBy(SECONDS_PER_YEAR).plus(RAY), SECONDS_PER_YEAR).minus(RAY);
return _extends({}, userReserve, {
underlyingBalance: underlyingBalance,
underlyingBalanceETH: underlyingBalanceETH,
underlyingBalanceUSD: underlyingBalanceUSD,
variableBorrows: variableBorrows,
variableBorrowsETH: variableBorrowsETH,
variableBorrowsUSD: variableBorrowsUSD,
stableBorrows: stableBorrows,
stableBorrowsETH: stableBorrowsETH,
stableBorrowsUSD: stableBorrowsUSD,
totalBorrows: valueToZDBigNumber(variableBorrows).plus(stableBorrows).toString(),
totalBorrowsETH: valueToZDBigNumber(variableBorrowsETH).plus(stableBorrowsETH).toString(),
totalBorrowsUSD: valueToZDBigNumber(variableBorrowsUSD).plus(stableBorrowsUSD).toString(),
aTokenRewards: aTokenRewards,
aTokenRewardsETH: aTokenRewardsETH,
aTokenRewardsUSD: aTokenRewardsUSD,
vTokenRewards: vTokenRewards,
vTokenRewardsETH: vTokenRewardsETH,
vTokenRewardsUSD: vTokenRewardsUSD,
sTokenRewards: sTokenRewards,
sTokenRewardsETH: sTokenRewardsETH,
sTokenRewardsUSD: sTokenRewardsUSD,
totalRewards: valueToZDBigNumber(aTokenRewards).plus(vTokenRewards).plus(sTokenRewards).toString(),
totalRewardsETH: valueToZDBigNumber(aTokenRewardsETH).plus(vTokenRewardsETH).plus(sTokenRewardsETH).toString(),
totalRewardsUSD: valueToZDBigNumber(aTokenRewardsUSD).plus(vTokenRewardsUSD).plus(sTokenRewardsUSD).toString(),
stableBorrowAPR: normalize(userReserve.stableBorrowRate, RAY_DECIMALS),
stableBorrowAPY: normalize(exactStableBorrowRate, RAY_DECIMALS)
});
}
function computeRawUserSummaryData$1(poolReservesData, rawUserReserves, userId, usdPriceEth, currentTimestamp, rewardsInfo) {
var totalLiquidityETH = valueToZDBigNumber('0');
var totalCollateralETH = valueToZDBigNumber('0');
var totalBorrowsETH = valueToZDBigNumber('0');
var currentLtv = valueToBigNumber('0');
var currentLiquidationThreshold = valueToBigNumber('0');
var totalRewards = valueToBigNumber('0');
var totalRewardsETH = valueToBigNumber('0');
var totalRewardsUSD = valueToBigNumber('0');
var userReservesData = rawUserReserves.map(function (userReserve) {
var poolReserve = poolReservesData.find(function (reserve) {
return reserve.id === userReserve.reserve.id;
});
if (!poolReserve) {
throw new Error('Reserve is not registered on platform, please contact support');
}
var computedUserReserve = computeUserReserveData$1(poolReserve, userReserve, usdPriceEth, currentTimestamp, rewardsInfo);
totalRewards = totalRewards.plus(computedUserReserve.totalRewards);
totalRewardsETH = totalRewardsETH.plus(computedUserReserve.totalRewardsETH);
totalRewardsUSD = totalRewardsUSD.plus(computedUserReserve.totalRewardsUSD);
totalLiquidityETH = totalLiquidityETH.plus(computedUserReserve.underlyingBalanceETH);
totalBorrowsETH = totalBorrowsETH.plus(computedUserReserve.variableBorrowsETH).plus(computedUserReserve.stableBorrowsETH); // asset enabled as collateral
if (poolReserve.usageAsCollateralEnabled && userReserve.usageAsCollateralEnabledOnUser) {
totalCollateralETH = totalCollateralETH.plus(computedUserReserve.underlyingBalanceETH);
currentLtv = currentLtv.plus(valueToBigNumber(computedUserReserve.underlyingBalanceETH).multipliedBy(poolReserve.baseLTVasCollateral));
currentLiquidationThreshold = currentLiquidationThreshold.plus(valueToBigNumber(computedUserReserve.underlyingBalanceETH).multipliedBy(poolReserve.reserveLiquidationThreshold));
}
return computedUserReserve;
}).sort(function (a, b) {
return a.reserve.symbol > b.reserve.symbol ? 1 : a.reserve.symbol < b.reserve.symbol ? -1 : 0;
});
if (currentLtv.gt(0)) {
currentLtv = currentLtv.div(totalCollateralETH).decimalPlaces(0, BigNumber__default.ROUND_DOWN);
}
if (currentLiquidationThreshold.gt(0)) {
currentLiquidationThreshold = currentLiquidationThreshold.div(totalCollateralETH).decimalPlaces(0, BigNumber__default.ROUND_DOWN);
}
var healthFactor = calculateHealthFactorFromBalances(totalCollateralETH, totalBorrowsETH, currentLiquidationThreshold);
var totalCollateralUSD = totalCollateralETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toString();
var totalLiquidityUSD = totalLiquidityETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toString();
var totalBorrowsUSD = totalBorrowsETH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceEth).toString();
var availableBorrowsETH = calculateAvailableBorrowsETH(totalCollateralETH, totalBorrowsETH, currentLtv);
return {
totalLiquidityUSD: totalLiquidityUSD,
totalCollateralUSD: totalCollateralUSD,
totalBorrowsUSD: totalBorrowsUSD,
totalRewards: totalRewards.toString(),
totalRewardsETH: totalRewardsETH.toString(),
totalRewardsUSD: totalRewardsUSD.toString(),
id: userId,
totalLiquidityETH: totalLiquidityETH.toString(),
totalCollateralETH: totalCollateralETH.toString(),
totalBorrowsETH: totalBorrowsETH.toString(),
availableBorrowsETH: availableBorrowsETH.toString(),
currentLoanToValue: currentLtv.toString(),
currentLiquidationThreshold: currentLiquidationThreshold.toString(),
healthFactor: healthFactor.toString(),
reservesData: userReservesData
};
}
function formatUserSummaryData$1(poolReservesData, rawUserReserves, userId, usdPriceEth, currentTimestamp, rewardsInfo) {
var userData = computeRawUserSummaryData$1(poolReservesData, rawUserReserves, userId, usdPriceEth, currentTimestamp, rewardsInfo);
var userReservesData = userData.reservesData.map(function (_ref) {
var reserve = _ref.reserve,
userReserve = _objectWithoutPropertiesLoose(_ref, ["reserve"]);
var reserveDecimals = reserve.decimals;
var exactStableBorrowRate = rayPow(valueToZDBigNumber(userReserve.stableBorrowRate).dividedBy(SECONDS_PER_YEAR).plus(RAY), SECONDS_PER_YEAR).minus(RAY);
return _extends({}, userReserve, {
reserve: _extends({}, reserve, {
reserveLiquidationBonus: normalize(valueToBigNumber(reserve.reserveLiquidationBonus).minus(pow10(LTV_PRECISION)), 4)
}),
scaledATokenBalance: normalize(userReserve.scaledATokenBalance, reserveDecimals),
stableBorrowAPR: normalize(userReserve.stableBorrowRate, RAY_DECIMALS),
stableBorrowAPY: normalize(exactStableBorrowRate, RAY_DECIMALS),
variableBorrowIndex: normalize(userReserve.variableBorrowIndex, RAY_DECIMALS),
underlyingBalance: normalize(userReserve.underlyingBalance, reserveDecimals),
underlyingBalanceETH: normalize(userReserve.underlyingBalanceETH, ETH_DECIMALS),
underlyingBalanceUSD: normalize(userReserve.underlyingBalanceUSD, USD_DECIMALS),
stableBorrows: normalize(userReserve.stableBorrows, reserveDecimals),
stableBorrowsETH: normalize(userReserve.stableBorrowsETH, ETH_DECIMALS),
stableBorrowsUSD: normalize(userReserve.stableBorrowsUSD, USD_DECIMALS),
variableBorrows: normalize(userReserve.variableBorrows, reserveDecimals),
variableBorrowsETH: normalize(userReserve.variableBorrowsETH, ETH_DECIMALS),
variableBorrowsUSD: normalize(userReserve.variableBorrowsUSD, USD_DECIMALS),
totalBorrows: normalize(userReserve.totalBorrows, reserveDecimals),
totalBorrowsETH: normalize(userReserve.totalBorrowsETH, ETH_DECIMALS),
totalBorrowsUSD: normalize(userReserve.totalBorrowsUSD, USD_DECIMALS)
});
});
return {
id: userData.id,
reservesData: userReservesData,
totalLiquidityETH: normalize(userData.totalLiquidityETH, ETH_DECIMALS),
totalLiquidityUSD: normalize(userData.totalLiquidityUSD, USD_DECIMALS),
totalCollateralETH: normalize(userData.totalCollateralETH, ETH_DECIMALS),
totalCollateralUSD: normalize(userData.totalCollateralUSD, USD_DECIMALS),
totalBorrowsETH: normalize(userData.totalBorrowsETH, ETH_DECIMALS),
totalBorrowsUSD: normalize(userData.totalBorrowsUSD, USD_DECIMALS),
availableBorrowsETH: normalize(userData.availableBorrowsETH, ETH_DECIMALS),
currentLoanToValue: normalize(userData.currentLoanToValue, 4),
currentLiquidationThreshold: normalize(userData.currentLiquidationThreshold, 4),
healthFactor: userData.healthFactor,
totalRewards: userData.totalRewards,
totalRewardsETH: userData.totalRewardsETH,
totalRewardsUSD: userData.totalRewardsUSD
};
}
/**
* Calculates the formatted debt accrued to a given point in time.
* @param reserve
* @param currentTimestamp unix timestamp which must be higher than reserve.lastUpdateTimestamp
*/
function calculateReserveDebt(reserve, currentTimestamp) {
var totalVariableDebt = normalize(rayMul(rayMul(reserve.totalScaledVariableDebt, reserve.variableBorrowIndex), calculateCompoundedInterest(reserve.variableBorrowRate, currentTimestamp, reserve.lastUpdateTimestamp)), reserve.decimals);
var totalStableDebt = normalize(rayMul(reserve.totalPrincipalStableDebt, calculateCompoundedInterest(reserve.averageStableRate, currentTimestamp, reserve.stableDebtLastUpdateTimestamp)), reserve.decimals);
return {
totalVariableDebt: totalVariableDebt,
totalStableDebt: totalStableDebt
};
}
function formatReserves$1(reserves, currentTimestamp, reserveIndexes30DaysAgo, rewardTokenPriceEth, emissionEndTimestamp) {
if (rewardTokenPriceEth === void 0) {
rewardTokenPriceEth = '0';
}
return reserves.map(function (reserve) {
var _reserveIndexes30Days, _reserveIndexes30Days2;
var reserve30DaysAgo = reserveIndexes30DaysAgo == null ? void 0 : (_reserveIndexes30Days = reserveIndexes30DaysAgo.find(function (res) {
return res.id === reserve.id;
})) == null ? void 0 : (_reserveIndexes30Days2 = _reserveIndexes30Days.paramsHistory) == null ? void 0 : _reserveIndexes30Days2[0];
var availableLiquidity = normalize(reserve.availableLiquidity, reserve.decimals);
var _calculateReserveDebt = calculateReserveDebt(reserve, currentTimestamp || reserve.lastUpdateTimestamp),
totalVariableDebt = _calculateReserveDebt.totalVariableDebt,
totalStableDebt = _calculateReserveDebt.totalStableDebt;
var totalDebt = valueToBigNumber(totalStableDebt).plus(totalVariableDebt);
var totalLiquidity = totalDebt.plus(availableLiquidity).toString();
var utilizationRate = totalLiquidity !== '0' ? totalDebt.dividedBy(totalLiquidity).toString() : '0';
var hasEmission = emissionEndTimestamp && emissionEndTimestamp > (currentTimestamp || Math.floor(Date.now() / 1000));
var aIncentivesAPY = hasEmission && totalLiquidity !== '0' ? calculateIncentivesAPY(reserve.aEmissionPerSecond, rewardTokenPriceEth, totalLiquidity, reserve.price.priceInEth) : '0';
var vIncentivesAPY = hasEmission && totalVariableDebt !== '0' ? calculateIncentivesAPY(reserve.vEmissionPerSecond, rewardTokenPriceEth, totalVariableDebt, reserve.price.priceInEth) : '0';
var sIncentivesAPY = hasEmission && totalStableDebt !== '0' ? calculateIncentivesAPY(reserve.sEmissionPerSecond, rewardTokenPriceEth, totalStableDebt, reserve.price.priceInEth) : '0';
var supplyAPY = rayPow(valueToZDBigNumber(reserve.liquidityRate).dividedBy(SECONDS_PER_YEAR).plus(RAY), SECONDS_PER_YEAR).minus(RAY);
var variableBorrowAPY = rayPow(valueToZDBigNumber(reserve.variableBorrowRate).dividedBy(SECONDS_PER_YEAR).plus(RAY), SECONDS_PER_YEAR).minus(RAY);
var stableBorrowAPY = rayPow(valueToZDBigNumber(reserve.stableBorrowRate).dividedBy(SECONDS_PER_YEAR).plus(RAY), SECONDS_PER_YEAR).minus(RAY);
return _extends({}, reserve, {
totalVariableDebt: totalVariableDebt,
totalStableDebt: totalStableDebt,
totalLiquidity: totalLiquidity,
availableLiquidity: availableLiquidity,
utilizationRate: utilizationRate,
aIncentivesAPY: aIncentivesAPY,
vIncentivesAPY: vIncentivesAPY,
sIncentivesAPY: sIncentivesAPY,
totalDebt: totalDebt.toString(),
price: _extends({}, reserve.price, {
priceInEth: normalize(reserve.price.priceInEth, ETH_DECIMALS)
}),
baseLTVasCollateral: normalize(reserve.baseLTVasCollateral, LTV_PRECISION),
reserveFactor: normalize(reserve.reserveFactor, LTV_PRECISION),
variableBorrowAPR: normalize(reserve.variableBorrowRate, RAY_DECIMALS),
variableBorrowAPY: normalize(variableBorrowAPY, RAY_DECIMALS),
avg30DaysVariableBorrowRate: reserve30DaysAgo ? calculateAverageRate(reserve30DaysAgo.variableBorrowIndex, reserve.variableBorrowIndex, reserve30DaysAgo.timestamp, reserve.lastUpdateTimestamp) : undefined,
avg30DaysLiquidityRate: reserve30DaysAgo ? calculateAverageRate(reserve30DaysAgo.liquidityIndex, reserve.liquidityIndex, reserve30DaysAgo.timestamp, reserve.lastUpdateTimestamp) : undefined,
stableBorrowAPR: normalize(reserve.stableBorrowRate, RAY_DECIMALS),
stableBorrowAPY: normalize(stableBorrowAPY, RAY_DECIMALS),
supplyAPR: normalize(reserve.liquidityRate, RAY_DECIMALS),
supplyAPY: normalize(supplyAPY, RAY_DECIMALS),
liquidityIndex: normalize(reserve.liquidityIndex, RAY_DECIMALS),
reserveLiquidationThreshold: normalize(reserve.reserveLiquidationThreshold, 4),
reserveLiquidationBonus: normalize(valueToBigNumber(reserve.reserveLiquidationBonus).minus(Math.pow(10, LTV_PRECISION)), 4),
totalScaledVariableDebt: normalize(reserve.totalScaledVariableDebt, reserve.decimals),
totalPrincipalStableDebt: normalize(reserve.totalPrincipalStableDebt, reserve.decimals),
variableBorrowIndex: normalize(reserve.variableBorrowIndex, RAY_DECIMALS)
});
});
}
/**
* Calculates the debt accrued to a given point in time.
* @param reserve
* @param currentTimestamp unix timestamp which must be higher than reserve.lastUpdateTimestamp
*/
function calculateReserveDebtSuppliesRaw(reserve, currentTimestamp) {
var totalVariableDebt = rayMul(rayMul(reserve.totalScaledVariableDebt, reserve.variableBorrowIndex), calculateCompoundedInterest(reserve.variableBorrowRate, currentTimestamp, reserve.lastUpdateTimestamp));
var totalStableDebt = rayMul(reserve.totalPrincipalStableDebt, calculateCompoundedInterest(reserve.averageStableRate, currentTimestamp, reserve.stableDebtLastUpdateTimestamp));
return {
totalVariableDebt: totalVariableDebt,
totalStableDebt: totalStableDebt
};
}
function calculateSupplies(reserve, currentTimestamp) {
var _calculateReserveDebt2 = calculateReserveDebtSuppliesRaw(reserve, currentTimestamp),
totalVariableDebt = _calculateReserveDebt2.totalVariableDebt,
totalStableDebt = _calculateReserveDebt2.totalStableDebt;
var totalDebt = totalVariableDebt.plus(totalStableDebt);
var totalLiquidity = totalDebt.plus(reserve.availableLiquidity);
return {
totalVariableDebt: totalVariableDebt,
totalStableDebt: totalStableDebt,
totalLiquidity: totalLiquidity
};
}
function calculateIncentivesAPY(emissionPerSecond, rewardTokenPriceInEth, tokenTotalSupplyNormalized, tokenPriceInEth) {
var emissionPerSecondNormalized = normalizeBN(emissionPerSecond, ETH_DECIMALS).multipliedBy(rewardTokenPriceInEth);
var emissionPerYear = emissionPerSecondNormalized.multipliedBy(SECONDS_PER_YEAR);
var totalSupplyNormalized = valueToBigNumber(tokenTotalSupplyNormalized).multipliedBy(tokenPriceInEth);
return emissionPerYear.dividedBy(totalSupplyNormalized).toString(10);
}
function calculateRewards(principalUserBalance, reserveIndex, userIndex, precision, rewardTokenDecimals, reserveIndexTimestamp, emissionPerSecond, totalSupply, currentTimestamp, emissionEndTimestamp) {
var actualCurrentTimestamp = currentTimestamp > emissionEndTimestamp ? emissionEndTimestamp : currentTimestamp;
var timeDelta = actualCurrentTimestamp - reserveIndexTimestamp;
var currentReserveIndex;
if (reserveIndexTimestamp == +currentTimestamp || reserveIndexTimestamp >= emissionEndTimestamp) {
currentReserveIndex = valueToZDBigNumber(reserveIndex);
} else {
currentReserveIndex = valueToZDBigNumber(emissionPerSecond).multipliedBy(timeDelta).multipliedBy(pow10(precision)).dividedBy(totalSupply).plus(reserveIndex);
}
var reward = valueToZDBigNumber(principalUserBalance).multipliedBy(currentReserveIndex.minus(userIndex)).dividedBy(pow10(precision));
return normalize(reward, rewardTokenDecimals);
}
var index$1 = {
__proto__: null,
getEthAndUsdBalance: getEthAndUsdBalance,
computeUserReserveData: computeUserReserveData$1,
computeRawUserSummaryData: computeRawUserSummaryData$1,
formatUserSummaryData: formatUserSummaryData$1,
calculateReserveDebt: calculateReserveDebt,
formatReserves: formatReserves$1,
calculateReserveDebtSuppliesRaw: calculateReserveDebtSuppliesRaw,
calculateSupplies: calculateSupplies,
calculateIncentivesAPY: calculateIncentivesAPY,
calculateRewards: calculateRewards
};
/** InterestRate options */
(function (InterestRate) {
InterestRate["None"] = "None";
InterestRate["Stable"] = "Stable";
InterestRate["Variable"] = "Variable";
})(exports.InterestRate || (exports.InterestRate = {}));
(function (Market) {
Market["Proto"] = "proto";
Market["AMM"] = "amm";
})(exports.Market || (exports.Market = {}));
(function (Network) {
Network["mainnet"] = "mainnet";
Network["ropsten"] = "ropsten";
Network["kovan"] = "kovan";
Network["polygon"] = "polygon";
Network["fork"] = "fork";
Network["mumbai"] = "mumbai";
Network["polygon_fork"] = "polygon_fork";
Network["avalanche"] = "avalanche";
Network["avalanche_fork"] = "avalanche_fork";
Network["fuji"] = "fuji";
Network["arbitrum_one"] = "arbitr