@bandz/protocol-js
Version:
Bandz protocol data aggregation tool
991 lines (878 loc) • 295 kB
JavaScript
import BigNumber from 'bignumber.js';
export { BigNumber } from 'bignumber.js';
import { __decorate, __param, __metadata } from 'tslib';
import { BigNumber as BigNumber$1, constants, Contract, utils, ethers, providers } from 'ethers';
import 'reflect-metadata';
import { base58, formatEther, splitSignature } from 'ethers/lib/utils';
import axios from '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.clone({
DECIMAL_PLACES: 0,
ROUNDING_MODE: BigNumber.ROUND_DOWN
});
function valueToBigNumber(amount) {
return new BigNumber(amount);
}
function valueToZDBigNumber(amount) {
return new BigNumberZD(amount);
}
var bn10 =
/*#__PURE__*/
new BigNumber(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 BCH_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(collateralBalanceBCH, borrowBalanceBCH, currentLiquidationThreshold) {
if (valueToBigNumber(borrowBalanceBCH).eq(0)) {
return valueToBigNumber('-1'); // invalid number
}
return valueToBigNumber(collateralBalanceBCH).multipliedBy(currentLiquidationThreshold).dividedBy(pow10(LTV_PRECISION)).div(borrowBalanceBCH);
}
function calculateHealthFactorFromBalancesBigUnits(collateralBalanceBCH, borrowBalanceBCH, currentLiquidationThreshold) {
return calculateHealthFactorFromBalances(collateralBalanceBCH, borrowBalanceBCH, new BigNumber(currentLiquidationThreshold).multipliedBy(pow10(LTV_PRECISION)).decimalPlaces(0, BigNumber.ROUND_DOWN));
}
function calculateavailableBorrowsBCH(collateralBalanceBCH, borrowBalanceBCH, currentLtv) {
if (valueToZDBigNumber(currentLtv).eq(0)) {
return valueToZDBigNumber('0');
}
var availableBorrowsBCH = valueToZDBigNumber(collateralBalanceBCH).multipliedBy(currentLtv).dividedBy(pow10(LTV_PRECISION)).minus(borrowBalanceBCH);
return availableBorrowsBCH.gt('0') ? availableBorrowsBCH : 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(collateralBalanceBCH, borrowBalanceBCH, totalFeesBCH, currentLiquidationThreshold) {
if (valueToBigNumber(borrowBalanceBCH).eq(0)) {
return valueToBigNumber('-1'); // invalid number
}
return valueToBigNumber(collateralBalanceBCH).multipliedBy(currentLiquidationThreshold).dividedBy(100).div(valueToBigNumber(borrowBalanceBCH).plus(totalFeesBCH));
}
function calculateHealthFactorFromBalancesBigUnits$1(collateralBalanceBCH, borrowBalanceBCH, totalFeesBCH, currentLiquidationThreshold) {
return calculateHealthFactorFromBalances$1(collateralBalanceBCH, borrowBalanceBCH, totalFeesBCH, new BigNumber(currentLiquidationThreshold).multipliedBy(100).decimalPlaces(0, BigNumber.ROUND_DOWN));
}
function calculateavailableBorrowsBCH$1(collateralBalanceBCH, borrowBalanceBCH, totalFeesBCH, currentLtv) {
if (valueToZDBigNumber(currentLtv).eq(0)) {
return valueToZDBigNumber('0');
}
var availableBorrowsBCH = valueToZDBigNumber(collateralBalanceBCH).multipliedBy(currentLtv).dividedBy(100);
if (availableBorrowsBCH.lt(borrowBalanceBCH)) {
return valueToZDBigNumber('0');
}
availableBorrowsBCH = availableBorrowsBCH.minus(borrowBalanceBCH).minus(totalFeesBCH);
var borrowFee = availableBorrowsBCH.multipliedBy('0.0025');
return availableBorrowsBCH.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, usdPriceBch, currentTimestamp) {
var priceInBch = poolReserve.price.priceInBch,
decimals = poolReserve.decimals;
var currentUnderlyingBalance = calculateCurrentUnderlyingBalance(userReserve, poolReserve, currentTimestamp);
var currentunderlyingBalanceBCH = currentUnderlyingBalance.multipliedBy(priceInBch).dividedBy(pow10(decimals));
var currentUnderlyingBalanceUSD = currentunderlyingBalanceBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toFixed(0);
var principalBorrowsBCH = valueToZDBigNumber(userReserve.principalBorrows).multipliedBy(priceInBch).dividedBy(pow10(decimals));
var principalBorrowsUSD = principalBorrowsBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toFixed(0);
var currentBorrows = getCompoundedBorrowBalance(poolReserve, userReserve, currentTimestamp);
var currentBorrowsBCH = currentBorrows.multipliedBy(priceInBch).dividedBy(pow10(decimals));
var currentBorrowsUSD = currentBorrowsBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toFixed(0);
var originationFeeBCH = valueToZDBigNumber(userReserve.originationFee).multipliedBy(priceInBch).dividedBy(pow10(decimals));
var originationFeeUSD = originationFeeBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toFixed(0);
return _extends({}, userReserve, {
principalBorrowsUSD: principalBorrowsUSD,
currentBorrowsUSD: currentBorrowsUSD,
originationFeeUSD: originationFeeUSD,
currentUnderlyingBalanceUSD: currentUnderlyingBalanceUSD,
originationFeeBCH: originationFeeBCH.toString(),
currentBorrows: currentBorrows.toString(),
currentBorrowsBCH: currentBorrowsBCH.toString(),
principalBorrowsBCH: principalBorrowsBCH.toString(),
currentUnderlyingBalance: currentUnderlyingBalance.toFixed(),
currentunderlyingBalanceBCH: currentunderlyingBalanceBCH.toFixed()
});
}
function computeRawUserSummaryData(poolReservesData, rawUserReserves, userId, usdPriceBch, currentTimestamp) {
var totalLiquidityBCH = valueToZDBigNumber('0');
var totalCollateralBCH = valueToZDBigNumber('0');
var totalBorrowsBCH = valueToZDBigNumber('0');
var totalFeesBCH = 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, usdPriceBch, currentTimestamp);
totalLiquidityBCH = totalLiquidityBCH.plus(computedUserReserve.currentunderlyingBalanceBCH);
totalBorrowsBCH = totalBorrowsBCH.plus(computedUserReserve.currentBorrowsBCH);
totalFeesBCH = totalFeesBCH.plus(computedUserReserve.originationFeeBCH); // asset enabled as collateral
if (poolReserve.usageAsCollateralEnabled && userReserve.usageAsCollateralEnabledOnUser) {
totalCollateralBCH = totalCollateralBCH.plus(computedUserReserve.currentunderlyingBalanceBCH);
currentLtv = currentLtv.plus(valueToBigNumber(computedUserReserve.currentunderlyingBalanceBCH).multipliedBy(poolReserve.baseLTVasCollateral));
currentLiquidationThreshold = currentLiquidationThreshold.plus(valueToBigNumber(computedUserReserve.currentunderlyingBalanceBCH).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(totalCollateralBCH).decimalPlaces(0, BigNumber.ROUND_DOWN);
}
if (currentLiquidationThreshold.gt(0)) {
currentLiquidationThreshold = currentLiquidationThreshold.div(totalCollateralBCH).decimalPlaces(0, BigNumber.ROUND_DOWN);
}
var healthFactor = calculateHealthFactorFromBalances$1(totalCollateralBCH, totalBorrowsBCH, totalFeesBCH, currentLiquidationThreshold);
var totalCollateralUSD = totalCollateralBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toString();
var totalLiquidityUSD = totalLiquidityBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toString();
var totalBorrowsUSD = totalBorrowsBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toString();
var totalFeesUSD = totalFeesBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch);
var totalBorrowsWithFeesBCH = totalFeesBCH.plus(totalBorrowsBCH);
var totalBorrowsWithFeesUSD = totalFeesUSD.plus(totalBorrowsUSD);
var availableBorrowsBCH = calculateavailableBorrowsBCH$1(totalCollateralBCH, totalBorrowsBCH, totalFeesBCH, currentLtv);
var totalBorrowsAndFeesETH = totalBorrowsBCH.plus(totalFeesBCH);
var maxAmountToWithdrawInBch = totalLiquidityBCH.minus(totalBorrowsAndFeesETH.eq(0) ? '0' : totalBorrowsAndFeesETH.multipliedBy(100).dividedBy(currentLiquidationThreshold));
return {
totalLiquidityUSD: totalLiquidityUSD,
totalCollateralUSD: totalCollateralUSD,
totalBorrowsUSD: totalBorrowsUSD,
id: userId,
totalLiquidityBCH: totalLiquidityBCH.toString(),
totalCollateralBCH: totalCollateralBCH.toString(),
totalFeesBCH: totalFeesBCH.toString(),
totalBorrowsBCH: totalBorrowsBCH.toString(),
availableBorrowsBCH: availableBorrowsBCH.toString(),
currentLoanToValue: currentLtv.toString(),
currentLiquidationThreshold: currentLiquidationThreshold.toString(),
maxAmountToWithdrawInBch: maxAmountToWithdrawInBch.toString(),
healthFactor: healthFactor.toString(),
reservesData: userReservesData,
totalFeesUSD: totalFeesUSD.toString(),
totalBorrowsWithFeesBCH: totalBorrowsWithFeesBCH.toString(),
totalBorrowsWithFeesUSD: totalBorrowsWithFeesUSD.toString()
};
}
function formatUserSummaryData(poolReservesData, rawUserReserves, userId, usdPriceBch, currentTimestamp) {
var userData = computeRawUserSummaryData(poolReservesData, rawUserReserves, userId, usdPriceBch, 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),
currentunderlyingBalanceBCH: normalize(userReserve.currentunderlyingBalanceBCH, BCH_DECIMALS),
currentUnderlyingBalanceUSD: normalize(userReserve.currentUnderlyingBalanceUSD, USD_DECIMALS),
principalBorrows: normalize(userReserve.principalBorrows, reserveDecimals),
principalBorrowsBCH: normalize(userReserve.principalBorrowsBCH, BCH_DECIMALS),
principalBorrowsUSD: normalize(userReserve.principalBorrowsUSD, USD_DECIMALS),
currentBorrows: normalize(userReserve.currentBorrows, reserveDecimals),
currentBorrowsBCH: normalize(userReserve.currentBorrowsBCH, BCH_DECIMALS),
currentBorrowsUSD: normalize(userReserve.currentBorrowsUSD, USD_DECIMALS),
originationFee: normalize(userReserve.originationFee, reserveDecimals),
originationFeeBCH: normalize(userReserve.originationFeeBCH, BCH_DECIMALS),
originationFeeUSD: normalize(userReserve.originationFeeUSD, USD_DECIMALS)
});
});
return {
id: userData.id,
reservesData: userReservesData,
totalLiquidityBCH: normalize(userData.totalLiquidityBCH, BCH_DECIMALS),
totalLiquidityUSD: normalize(userData.totalLiquidityUSD, USD_DECIMALS),
totalCollateralBCH: normalize(userData.totalCollateralBCH, BCH_DECIMALS),
totalCollateralUSD: normalize(userData.totalCollateralUSD, USD_DECIMALS),
totalFeesBCH: normalize(userData.totalFeesBCH, BCH_DECIMALS),
totalFeesUSD: normalize(userData.totalFeesUSD, USD_DECIMALS),
totalBorrowsBCH: normalize(userData.totalBorrowsBCH, BCH_DECIMALS),
totalBorrowsUSD: normalize(userData.totalBorrowsUSD, USD_DECIMALS),
totalBorrowsWithFeesBCH: normalize(userData.totalBorrowsWithFeesBCH, BCH_DECIMALS),
totalBorrowsWithFeesUSD: normalize(userData.totalBorrowsWithFeesUSD, USD_DECIMALS),
availableBorrowsBCH: normalize(userData.availableBorrowsBCH, BCH_DECIMALS),
currentLoanToValue: normalize(userData.currentLoanToValue, 2),
currentLiquidationThreshold: normalize(userData.currentLiquidationThreshold, 2),
maxAmountToWithdrawInBch: normalize(userData.maxAmountToWithdrawInBch, BCH_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, {
priceInBch: normalize(reserve.price.priceInBch, BCH_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,
calculateavailableBorrowsBCH: calculateavailableBorrowsBCH$1,
calculateCumulatedBalance: calculateCumulatedBalance,
calculateCurrentUnderlyingBalance: calculateCurrentUnderlyingBalance,
computeRawUserSummaryData: computeRawUserSummaryData,
formatUserSummaryData: formatUserSummaryData,
formatReserves: formatReserves,
calculateInterestRates: calculateInterestRates,
get BorrowRateMode () { return BorrowRateMode; }
};
function getBchAndUsdBalance(balance, priceInBch, decimals, usdPriceBch) {
var balanceInBch = valueToZDBigNumber(balance).multipliedBy(priceInBch).dividedBy(pow10(decimals));
var balanceInUsd = balanceInBch.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toFixed(0);
return [balanceInBch.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, usdPriceBch, currentTimestamp, rewardsInfo) {
var priceInBch = poolReserve.price.priceInBch,
decimals = poolReserve.decimals;
var underlyingBalance = getLinearBalance(userReserve.scaledATokenBalance, poolReserve.liquidityIndex, poolReserve.liquidityRate, poolReserve.lastUpdateTimestamp, currentTimestamp).toString();
var _getBchAndUsdBalance = getBchAndUsdBalance(underlyingBalance, priceInBch, decimals, usdPriceBch),
underlyingBalanceBCH = _getBchAndUsdBalance[0],
underlyingBalanceUSD = _getBchAndUsdBalance[1];
var variableBorrows = getCompoundedBalance(userReserve.scaledVariableDebt, poolReserve.variableBorrowIndex, poolReserve.variableBorrowRate, poolReserve.lastUpdateTimestamp, currentTimestamp).toString();
var _getBchAndUsdBalance2 = getBchAndUsdBalance(variableBorrows, priceInBch, decimals, usdPriceBch),
variableBorrowsBCH = _getBchAndUsdBalance2[0],
variableBorrowsUSD = _getBchAndUsdBalance2[1];
var stableBorrows = getCompoundedStableBalance(userReserve.principalStableDebt, userReserve.stableBorrowRate, userReserve.stableBorrowLastUpdateTimestamp, currentTimestamp).toString();
var _getBchAndUsdBalance3 = getBchAndUsdBalance(stableBorrows, priceInBch, decimals, usdPriceBch),
stableBorrowsBCH = _getBchAndUsdBalance3[0],
stableBorrowsUSD = _getBchAndUsdBalance3[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 _getBchAndUsdBalance4 = getBchAndUsdBalance(aTokenRewards, rewardsInfo.rewardTokenPriceBch, rewardsInfo.rewardTokenDecimals, usdPriceBch),
aTokenRewardsBCH = _getBchAndUsdBalance4[0],
aTokenRewardsUSD = _getBchAndUsdBalance4[1];
var vTokenRewards = totalVariableDebt.gt(0) ? calculateRewards(userReserve.scaledVariableDebt, poolReserve.vTokenIncentivesIndex, userReserve.vTokenincentivesUserIndex, rewardsInfo.incentivePrecision, rewardsInfo.rewardTokenDecimals, poolReserve.vIncentivesLastUpdateTimestamp, poolReserve.vEmissionPerSecond, new BigNumber(poolReserve.totalScaledVariableDebt), currentTimestamp, rewardsInfo.emissionEndTimestamp) : '0';
var _getBchAndUsdBalance5 = getBchAndUsdBalance(vTokenRewards, rewardsInfo.rewardTokenPriceBch, rewardsInfo.rewardTokenDecimals, usdPriceBch),
vTokenRewardsBCH = _getBchAndUsdBalance5[0],
vTokenRewardsUSD = _getBchAndUsdBalance5[1];
var sTokenRewards = totalStableDebt.gt(0) ? calculateRewards(userReserve.principalStableDebt, poolReserve.sTokenIncentivesIndex, userReserve.sTokenincentivesUserIndex, rewardsInfo.incentivePrecision, rewardsInfo.rewardTokenDecimals, poolReserve.sIncentivesLastUpdateTimestamp, poolReserve.sEmissionPerSecond, new BigNumber(poolReserve.totalPrincipalStableDebt), currentTimestamp, rewardsInfo.emissionEndTimestamp) : '0';
var _getBchAndUsdBalance6 = getBchAndUsdBalance(sTokenRewards, rewardsInfo.rewardTokenPriceBch, rewardsInfo.rewardTokenDecimals, usdPriceBch),
sTokenRewardsBCH = _getBchAndUsdBalance6[0],
sTokenRewardsUSD = _getBchAndUsdBalance6[1];
return _extends({}, userReserve, {
underlyingBalance: underlyingBalance,
underlyingBalanceBCH: underlyingBalanceBCH,
underlyingBalanceUSD: underlyingBalanceUSD,
variableBorrows: variableBorrows,
variableBorrowsBCH: variableBorrowsBCH,
variableBorrowsUSD: variableBorrowsUSD,
stableBorrows: stableBorrows,
stableBorrowsBCH: stableBorrowsBCH,
stableBorrowsUSD: stableBorrowsUSD,
totalBorrows: valueToZDBigNumber(variableBorrows).plus(stableBorrows).toString(),
totalBorrowsBCH: valueToZDBigNumber(variableBorrowsBCH).plus(stableBorrowsBCH).toString(),
totalBorrowsUSD: valueToZDBigNumber(variableBorrowsUSD).plus(stableBorrowsUSD).toString(),
aTokenRewards: aTokenRewards,
aTokenRewardsBCH: aTokenRewardsBCH,
aTokenRewardsUSD: aTokenRewardsUSD,
vTokenRewards: vTokenRewards,
vTokenRewardsBCH: vTokenRewardsBCH,
vTokenRewardsUSD: vTokenRewardsUSD,
sTokenRewards: sTokenRewards,
sTokenRewardsBCH: sTokenRewardsBCH,
sTokenRewardsUSD: sTokenRewardsUSD,
totalRewards: valueToZDBigNumber(aTokenRewards).plus(vTokenRewards).plus(sTokenRewards).toString(),
totalRewardsBCH: valueToZDBigNumber(aTokenRewardsBCH).plus(vTokenRewardsBCH).plus(sTokenRewardsBCH).toString(),
totalRewardsUSD: valueToZDBigNumber(aTokenRewardsUSD).plus(vTokenRewardsUSD).plus(sTokenRewardsUSD).toString()
});
}
function computeRawUserSummaryData$1(poolReservesData, rawUserReserves, userId, usdPriceBch, currentTimestamp, rewardsInfo) {
var totalLiquidityBCH = valueToZDBigNumber('0');
var totalCollateralBCH = valueToZDBigNumber('0');
var totalBorrowsBCH = valueToZDBigNumber('0');
var currentLtv = valueToBigNumber('0');
var currentLiquidationThreshold = valueToBigNumber('0');
var totalRewards = valueToBigNumber('0');
var totalRewardsBCH = 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, usdPriceBch, currentTimestamp, rewardsInfo);
totalRewards = totalRewards.plus(computedUserReserve.totalRewards);
totalRewardsBCH = totalRewardsBCH.plus(computedUserReserve.totalRewardsBCH);
totalRewardsUSD = totalRewardsUSD.plus(computedUserReserve.totalRewardsUSD);
totalLiquidityBCH = totalLiquidityBCH.plus(computedUserReserve.underlyingBalanceBCH);
totalBorrowsBCH = totalBorrowsBCH.plus(computedUserReserve.variableBorrowsBCH).plus(computedUserReserve.stableBorrowsBCH); // asset enabled as collateral
if (poolReserve.usageAsCollateralEnabled && userReserve.usageAsCollateralEnabledOnUser) {
totalCollateralBCH = totalCollateralBCH.plus(computedUserReserve.underlyingBalanceBCH);
currentLtv = currentLtv.plus(valueToBigNumber(computedUserReserve.underlyingBalanceBCH).multipliedBy(poolReserve.baseLTVasCollateral));
currentLiquidationThreshold = currentLiquidationThreshold.plus(valueToBigNumber(computedUserReserve.underlyingBalanceBCH).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(totalCollateralBCH).decimalPlaces(0, BigNumber.ROUND_DOWN);
}
if (currentLiquidationThreshold.gt(0)) {
currentLiquidationThreshold = currentLiquidationThreshold.div(totalCollateralBCH).decimalPlaces(0, BigNumber.ROUND_DOWN);
}
var healthFactor = calculateHealthFactorFromBalances(totalCollateralBCH, totalBorrowsBCH, currentLiquidationThreshold);
var totalCollateralUSD = totalCollateralBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toString();
var totalLiquidityUSD = totalLiquidityBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toString();
var totalBorrowsUSD = totalBorrowsBCH.multipliedBy(pow10(USD_DECIMALS)).dividedBy(usdPriceBch).toString();
var availableBorrowsBCH = calculateavailableBorrowsBCH(totalCollateralBCH, totalBorrowsBCH, currentLtv);
return {
totalLiquidityUSD: totalLiquidityUSD,
totalCollateralUSD: totalCollateralUSD,
totalBorrowsUSD: totalBorrowsUSD,
totalRewards: totalRewards.toString(),
totalRewardsBCH: totalRewardsBCH.toString(),
totalRewardsUSD: totalRewardsUSD.toString(),
id: userId,
totalLiquidityBCH: totalLiquidityBCH.toString(),
totalCollateralBCH: totalCollateralBCH.toString(),
totalBorrowsBCH: totalBorrowsBCH.toString(),
availableBorrowsBCH: availableBorrowsBCH.toString(),
currentLoanToValue: currentLtv.toString(),
currentLiquidationThreshold: currentLiquidationThreshold.toString(),
healthFactor: healthFactor.toString(),
reservesData: userReservesData
};
}
function formatUserSummaryData$1(poolReservesData, rawUserReserves, userId, usdPriceBch, currentTimestamp, rewardsInfo) {
var userData = computeRawUserSummaryData$1(poolReservesData, rawUserReserves, userId, usdPriceBch, currentTimestamp, rewardsInfo);
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(pow10(LTV_PRECISION)), 4),
liquidityRate: normalize(reserve.liquidityRate, RAY_DECIMALS)
}),
scaledATokenBalance: normalize(userReserve.scaledATokenBalance, reserveDecimals),
stableBorrowRate: normalize(userReserve.stableBorrowRate, RAY_DECIMALS),
variableBorrowIndex: normalize(userReserve.variableBorrowIndex, RAY_DECIMALS),
underlyingBalance: normalize(userReserve.underlyingBalance, reserveDecimals),
underlyingBalanceBCH: normalize(userReserve.underlyingBalanceBCH, BCH_DECIMALS),
underlyingBalanceUSD: normalize(userReserve.underlyingBalanceUSD, USD_DECIMALS),
stableBorrows: normalize(userReserve.stableBorrows, reserveDecimals),
stableBorrowsBCH: normalize(userReserve.stableBorrowsBCH, BCH_DECIMALS),
stableBorrowsUSD: normalize(userReserve.stableBorrowsUSD, USD_DECIMALS),
variableBorrows: normalize(userReserve.variableBorrows, reserveDecimals),
variableBorrowsBCH: normalize(userReserve.variableBorrowsBCH, BCH_DECIMALS),
variableBorrowsUSD: normalize(userReserve.variableBorrowsUSD, USD_DECIMALS),
totalBorrows: normalize(userReserve.totalBorrows, reserveDecimals),
totalBorrowsBCH: normalize(userReserve.totalBorrowsBCH, BCH_DECIMALS),
totalBorrowsUSD: normalize(userReserve.totalBorrowsUSD, USD_DECIMALS)
});
});
return {
id: userData.id,
reservesData: userReservesData,
totalLiquidityBCH: normalize(userData.totalLiquidityBCH, BCH_DECIMALS),
totalLiquidityUSD: normalize(userData.totalLiquidityUSD, USD_DECIMALS),
totalCollateralBCH: normalize(userData.totalCollateralBCH, BCH_DECIMALS),
totalCollateralUSD: normalize(userData.totalCollateralUSD, USD_DECIMALS),
totalBorrowsBCH: normalize(userData.totalBorrowsBCH, BCH_DECIMALS),
totalBorrowsUSD: normalize(userData.totalBorrowsUSD, USD_DECIMALS),
availableBorrowsBCH: normalize(userData.availableBorrowsBCH, BCH_DECIMALS),
currentLoanToValue: normalize(userData.currentLoanToValue, 4),
currentLiquidationThreshold: normalize(userData.currentLiquidationThreshold, 4),
healthFactor: userData.healthFactor,
totalRewards: userData.totalRewards,
totalRewardsBCH: userData.totalRewardsBCH,
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, rewardTokenPriceBch, emissionEndTimestamp) {
if (rewardTokenPriceBch === void 0) {
rewardTokenPriceBch = '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, rewardTokenPriceBch, totalLiquidity, reserve.price.priceInBch) : '0';
var vIncentivesAPY = hasEmission && totalVariableDebt !== '0' ? calculateIncentivesAPY(reserve.vEmissionPerSecond, rewardTokenPriceBch, totalVariableDebt, reserve.price.priceInBch) : '0';
var sIncentivesAPY = hasEmission && totalStableDebt !== '0' ? calculateIncentivesAPY(reserve.sEmissionPerSecond, rewardTokenPriceBch, totalStableDebt, reserve.price.priceInBch) : '0';
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, {
priceInBch: normalize(reserve.price.priceInBch, BCH_DECIMALS)
}),
baseLTVasCollateral: normalize(reserve.baseLTVasCollateral, LTV_PRECISION),
reserveFactor: normalize(reserve.reserveFactor, LTV_PRECISION),
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),
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, rewardTokenpriceInBch, tokenTotalSupplyNormalized, tokenpriceInBch) {
var emissionPerSecondNormalized = normalizeBN(emissionPerSecond, BCH_DECIMALS).multipliedBy(rewardTokenpriceInBch);
var emissionPerYear = emissionPerSecondNormalized.multipliedBy(SECONDS_PER_YEAR);
var totalSupplyNormalized = valueToBigNumber(tokenTotalSupplyNormalized).multipliedBy(tokenpriceInBch);
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,
getBchAndUsdBalance: getBchAndUsdBalance,
computeUserReserveData: computeUserReserveData$1,
computeRawUserSummaryData: computeRawUserSummaryData$1,
formatUserSummaryData: formatUserSummaryData$1,
calculateReserveDebt: calculateReserveDebt,
formatReserves: formatReserves$1,
calculateReserveDebtSuppliesRaw: calculateReserveDebtSuppliesRaw,
calculateSupplies: calculateSupplies,
calculateIncentivesAPY: calculateIncentivesAPY,
calculateRewards: calculateRewards
};
/** InterestRate options */
var InterestRate;
(function (InterestRate) {
InterestRate["None"] = "None";
InterestRate["Stable"] = "Stable";
InterestRate["Variable"] = "Variable";
})(InterestRate || (InterestRate = {}));
var Market;
(function (Market) {
Market["Proto"] = "proto";
Market["AMM"] = "amm";
})(Market || (Market = {}));
var Network;
(function (Network) {
Network["mainnet"] = "mainnet";
Network["amber"] = "amber";
})(Network || (Network = {}));
var ChainId;
(function (ChainId) {
ChainId[ChainId["mainnet"] = 10000] = "mainnet";
ChainId[ChainId["amber"] = 10001] = "amber";
})(ChainId || (ChainId = {}));
var eSmartBCHTxType;
(function (eSmartBCHTxType) {
eSmartBCHTxType["ERC20_APPROVAL"] = "ERC20_APPROVAL";
eSmartBCHTxType["DLP_ACTION"] = "DLP_ACTION";
eSmartBCHTxType["GOVERNANCE_ACTION"] = "GOVERNANCE_ACTION";
eSmartBCHTxType["GOV_DELEGATION_ACTION"] = "GOV_DELEGATION_ACTION";
eSmartBCHTxType["STAKE_ACTION"] = "STAKE_ACTION";
eSmartBCHTxType["MIGRATION_LEND_AAVE"] = "MIGRATION_LEND_AAVE";
eSmartBCHTxType["FAUCET_MINT"] = "FAUCET_MINT";
eSmartBCHTxType["REWARD_ACTION"] = "REWARD_ACTION";
})(eSmartBCHTxType || (eSmartBCHTxType = {}));
var ProtocolAction;
(function (ProtocolAction) {
ProtocolAction["default"] = "default";
ProtocolAction["withdraw"] = "withdraw";
ProtocolAction["deposit"] = "deposit";
ProtocolAction["liquidationCall"] = "liquidationCall";
ProtocolAction["liquidationFlash"] = "liquidationFlash";
ProtocolAction["repay"] = "repay";
ProtocolAction["swapCollateral"] = "swapCollateral";
ProtocolAction["repayCollateral"] = "repayCollateral";
ProtocolAction["withdrawBCH"] = "withdrawBCH";
ProtocolAction["borrowBCH"] = "borrowBCH";
})(ProtocolAction || (ProtocolAction = {}));
var GovernanceVote;
(function (GovernanceVote) {
GovernanceVote[GovernanceVote["Abstain"] = 0] = "Abstain";
GovernanceVote[GovernanceVote["Yes"] = 1] = "Yes";
GovernanceVote[GovernanceVote["No"] = 2] = "No";
})(GovernanceVote || (GovernanceVote = {}));
var Stake;
(func